]> gitweb.ps.run Git - matrix_esp_thesis/blobdiff - src/matrix.c
matrix.c: add masterKey and verified, add HandleSync/HandleEvent
[matrix_esp_thesis] / src / matrix.c
index 1d2c3fac92afe864663542383e212fe2eeaa445d..4ce78ce6248e12b2e370b13cddf9f893795abe6a 100644 (file)
@@ -3,50 +3,79 @@
 #include <time.h>\r
 #include <stdio.h>\r
 #include <mjson.h>\r
 #include <time.h>\r
 #include <stdio.h>\r
 #include <mjson.h>\r
+#include <olm/sas.h>\r
 \r
 \r
+#ifdef ESP_PLATFORM\r
+#include <esp_random.h>\r
+#endif\r
+\r
+#define STATIC static\r
 \r
 #define LOGIN_REQUEST_SIZE 1024\r
 #define LOGIN_RESPONSE_SIZE 1024\r
 #define LOGIN_URL "/_matrix/client/v3/login"\r
 \r
 #define ENCRYPTED_REQUEST_SIZE (1024*5)\r
 \r
 #define LOGIN_REQUEST_SIZE 1024\r
 #define LOGIN_RESPONSE_SIZE 1024\r
 #define LOGIN_URL "/_matrix/client/v3/login"\r
 \r
 #define ENCRYPTED_REQUEST_SIZE (1024*5)\r
-#define ENCRYPTED_EVENT_SIZE 1024\r
-#define ROOMEVENT_REQUEST_SIZE 256\r
-#define ROOMEVENT_RESPONSE_SIZE 1024\r
-#define ROOMEVENT_URL "/_matrix/client/v3/rooms/%s/send/%s/%d"\r
+STATIC char g_EncryptedRequestBuffer[ENCRYPTED_REQUEST_SIZE];\r
+#define ENCRYPTED_EVENT_SIZE (1024*10)\r
+STATIC char g_EncryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
+#define ROOM_SEND_REQUEST_SIZE 256\r
+#define ROOM_SEND_RESPONSE_SIZE 1024\r
+#define ROOM_SEND_URL "/_matrix/client/v3/rooms/%s/send/%s/%d"\r
+\r
+#define ROOMKEY_REQUEST_SIZE (1024*4)\r
 \r
 #define TODEVICE_EVENT_SIZE (1024*5)\r
 \r
 #define TODEVICE_EVENT_SIZE (1024*5)\r
+STATIC char g_TodeviceEventBuffer[TODEVICE_EVENT_SIZE];\r
 #define TODEVICE_URL "/_matrix/client/v3/sendToDevice/%s/%d"\r
 \r
 #define KEYS_QUERY_URL "/_matrix/client/v3/keys/query"\r
 #define KEYS_QUERY_REQUEST_SIZE 256\r
 #define TODEVICE_URL "/_matrix/client/v3/sendToDevice/%s/%d"\r
 \r
 #define KEYS_QUERY_URL "/_matrix/client/v3/keys/query"\r
 #define KEYS_QUERY_REQUEST_SIZE 256\r
-#define KEYS_QUERY_RESPONSE_SIZE (1024*10)\r
+#define KEYS_QUERY_RESPONSE_SIZE (1024*5)\r
 \r
 #define KEYS_UPLOAD_URL "/_matrix/client/v3/keys/upload"\r
 \r
 #define KEYS_UPLOAD_URL "/_matrix/client/v3/keys/upload"\r
-#define KEYS_UPLOAD_REQUEST_SIZE 1024\r
-#define KEYS_UPLOAD_REQUEST_SIGNED_SIZE 2048\r
+#define KEYS_UPLOAD_REQUEST_SIZE 1024*4\r
+STATIC char g_KeysUploadRequestBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
+#define KEYS_UPLOAD_REQUEST_SIGNED_SIZE 2048*4\r
+STATIC char g_KeysUploadRequestSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
 #define KEYS_UPLOAD_RESPONSE_SIZE 2048\r
 \r
 #define KEYS_CLAIM_URL "/_matrix/client/v3/keys/claim"\r
 #define KEYS_CLAIM_REQUEST_SIZE 1024\r
 #define KEYS_CLAIM_RESPONSE_SIZE 1024\r
 \r
 #define KEYS_UPLOAD_RESPONSE_SIZE 2048\r
 \r
 #define KEYS_CLAIM_URL "/_matrix/client/v3/keys/claim"\r
 #define KEYS_CLAIM_REQUEST_SIZE 1024\r
 #define KEYS_CLAIM_RESPONSE_SIZE 1024\r
 \r
-#define JSON_QUERY_SIZE 128\r
+#define SYNC_TIMEOUT 5000\r
 \r
 \r
+#define JSON_QUERY_SIZE 128\r
+#define JSON_MAX_INDICES 100\r
+#define JSON_MAX_ENTRY_SIZE 1024\r
 \r
 \r
+#define MAX(a,b) ((a) > (b) ? (a) : (b))\r
+#define MIN(a,b) ((a) < (b) ? (a) : (b))\r
 \r
 void\r
 Randomize(\r
     uint8_t * random,\r
     int randomLen)\r
 {\r
 \r
 void\r
 Randomize(\r
     uint8_t * random,\r
     int randomLen)\r
 {\r
-    static bool first = true;\r
+    #ifdef ESP_PLATFORM\r
+\r
+    for (int i = 0; i < randomLen; i++)\r
+    {\r
+        random[i] = esp_random() % 256;\r
+    }\r
+\r
+    #else\r
+\r
+    STATIC bool first = true;\r
     if (first) { srand(time(0)); first = false; }\r
 \r
     for (int i = 0; i < randomLen; i++)\r
     {\r
         random[i] = rand() % 256;\r
     }\r
     if (first) { srand(time(0)); first = false; }\r
 \r
     for (int i = 0; i < randomLen; i++)\r
     {\r
         random[i] = rand() % 256;\r
     }\r
+\r
+    #endif\r
 }\r
 \r
 bool\r
 }\r
 \r
 bool\r
@@ -76,20 +105,86 @@ JsonEscape(
     return true;\r
 }\r
 \r
     return true;\r
 }\r
 \r
+bool\r
+JsonCanonicalize(\r
+    const char * sIn, int sInLen,\r
+    char * sOut, int sOutCap)\r
+{\r
+    snprintf(sOut, sOutCap, "{}");\r
+\r
+    int koff, klen, voff, vlen, vtype, off;\r
+\r
+    struct Key {\r
+        const char * ptr;\r
+        int len;\r
+    };\r
+\r
+    struct Key keys[JSON_MAX_INDICES];\r
+    int numKeys = 0;\r
+\r
+    for (off = 0; (off = mjson_next(sIn, sInLen, off, &koff, &klen, &voff, &vlen, &vtype)) != 0; ) {\r
+        keys[numKeys].ptr = sIn + koff;\r
+        keys[numKeys].len = klen;\r
+        numKeys++;\r
+    }\r
+\r
+    for (int i = 0; i < numKeys; i++) {\r
+        for (int j = i; j < numKeys; j++) {\r
+            if (\r
+                strncmp(\r
+                    keys[i].ptr,\r
+                    keys[j].ptr,\r
+                    MIN(keys[i].len, keys[j].len)\r
+                ) > 0\r
+            ) {\r
+                struct Key k = keys[i];\r
+                keys[i] = keys[j];\r
+                keys[j] = k;\r
+            }\r
+        }\r
+    }\r
+\r
+    for (int i = 0; i < numKeys; i++) {\r
+        char jp[JSON_QUERY_SIZE];\r
+        snprintf(jp, JSON_QUERY_SIZE, "$.%.*s", keys[i].len-2, keys[i].ptr+1);\r
+\r
+        const char * valPtr;\r
+        int valLen;\r
+        mjson_find(sIn, sInLen, jp, &valPtr, &valLen);\r
+        \r
+        STATIC char newEntry[JSON_MAX_ENTRY_SIZE];\r
+        snprintf(newEntry, JSON_MAX_ENTRY_SIZE, "{%.*s:%.*s}", keys[i].len, keys[i].ptr, valLen, valPtr);\r
+\r
+        char * buffer = strdup(sOut);\r
+\r
+        struct mjson_fixedbuf fb = { sOut, sOutCap, 0 };\r
+        mjson_merge(buffer, strlen(buffer), newEntry, strlen(newEntry), mjson_print_fixed_buf, &fb);\r
+\r
+        free(buffer);\r
+    }\r
+\r
+    // TODO: recursively sort entries\r
+\r
+    return true;\r
+}\r
+\r
 bool JsonSign(\r
     MatrixClient * client,\r
     const char * sIn, int sInLen,\r
     char * sOut, int sOutCap)\r
 {\r
 bool JsonSign(\r
     MatrixClient * client,\r
     const char * sIn, int sInLen,\r
     char * sOut, int sOutCap)\r
 {\r
-    static char signature[OLM_SIGNATURE_SIZE];\r
+    STATIC char signature[OLM_SIGNATURE_SIZE];\r
     size_t res =\r
         olm_account_sign(client->olmAccount.account,\r
             sIn, sInLen,\r
             signature, OLM_SIGNATURE_SIZE);\r
     \r
     int signatureLen = res;\r
     size_t res =\r
         olm_account_sign(client->olmAccount.account,\r
             sIn, sInLen,\r
             signature, OLM_SIGNATURE_SIZE);\r
     \r
     int signatureLen = res;\r
+    \r
+    STATIC char thisSigningKey[SIGNING_KEY_SIZE];\r
+    MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, SIGNING_KEY_SIZE);\r
 \r
 \r
-    static char signatureJson[JSON_SIGNATURE_SIZE];\r
+    STATIC char signatureJson[JSON_SIGNATURE_SIZE];\r
     int signatureJsonLen =\r
         mjson_snprintf(signatureJson, JSON_SIGNATURE_SIZE,\r
             "{"\r
     int signatureJsonLen =\r
         mjson_snprintf(signatureJson, JSON_SIGNATURE_SIZE,\r
             "{"\r
@@ -100,6 +195,7 @@ bool JsonSign(
                 "}"\r
             "}",\r
             client->userId,\r
                 "}"\r
             "}",\r
             client->userId,\r
+            //"1",\r
             client->deviceId,\r
             signatureLen, signature);\r
 \r
             client->deviceId,\r
             signatureLen, signature);\r
 \r
@@ -120,7 +216,7 @@ MatrixOlmAccountInit(
 {\r
     account->account = olm_account(account->memory);\r
 \r
 {\r
     account->account = olm_account(account->memory);\r
 \r
-    static uint8_t random[OLM_ACCOUNT_RANDOM_SIZE];\r
+    STATIC uint8_t random[OLM_ACCOUNT_RANDOM_SIZE];\r
     Randomize(random, OLM_ACCOUNT_RANDOM_SIZE);\r
 \r
     size_t res = olm_create_account(\r
     Randomize(random, OLM_ACCOUNT_RANDOM_SIZE);\r
 \r
     size_t res = olm_create_account(\r
@@ -131,7 +227,82 @@ MatrixOlmAccountInit(
     return res != olm_error();\r
 }\r
 \r
     return res != olm_error();\r
 }\r
 \r
-// TODO: in/outbound sessions\r
+bool\r
+MatrixOlmAccountUnpickle(\r
+    MatrixOlmAccount * account,\r
+    void * pickled, int pickledLen,\r
+    const void * key, int keyLen)\r
+{\r
+    size_t res;\r
+    res = olm_unpickle_account(account->account,\r
+        key, keyLen,\r
+        pickled, pickledLen);\r
+    if (res == olm_error()) {\r
+        printf("error unpickling olm account:%s\n",\r
+            olm_account_last_error(account->account));\r
+    }\r
+    return res != olm_error();\r
+}\r
+\r
+bool\r
+MatrixOlmAccountGetDeviceKey(\r
+    MatrixOlmAccount * account,\r
+    char * key, int keyCap)\r
+{\r
+    STATIC char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE];\r
+    size_t res =\r
+        olm_account_identity_keys(account->account,\r
+            deviceKeysJson, OLM_IDENTITY_KEYS_JSON_SIZE);\r
+    mjson_get_string(deviceKeysJson, res,\r
+        "$.curve25519",\r
+        key, keyCap);\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixOlmAccountGetSigningKey(\r
+    MatrixOlmAccount * account,\r
+    char * key, int keyCap)\r
+{\r
+    STATIC char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE];\r
+    size_t res =\r
+        olm_account_identity_keys(account->account,\r
+            deviceKeysJson, OLM_IDENTITY_KEYS_JSON_SIZE);\r
+    mjson_get_string(deviceKeysJson, res,\r
+        "$.ed25519",\r
+        key, keyCap);\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixOlmSessionFrom(\r
+    MatrixOlmSession * session,\r
+    OlmAccount * olmAccount,\r
+    const char * deviceId,\r
+    const char * deviceKey,\r
+    const char * encrypted)\r
+{\r
+    memset(session, 0, sizeof(MatrixOlmSession));\r
+\r
+    session->deviceId = deviceId;\r
+\r
+    session->session =\r
+        olm_session(session->memory);\r
+    \r
+    char * encryptedCopy = strdup(encrypted);\r
+    \r
+    size_t res =\r
+        olm_create_inbound_session_from(session->session, olmAccount,\r
+            deviceKey, strlen(deviceKey),\r
+            encryptedCopy, strlen(encryptedCopy));\r
+    \r
+    if (res == olm_error()) {\r
+        printf("error olm:%s\n", olm_session_last_error(session->session));\r
+    }\r
+\r
+    return res != olm_error();\r
+}\r
+\r
 bool\r
 MatrixOlmSessionTo(\r
     MatrixOlmSession * session,\r
 bool\r
 MatrixOlmSessionTo(\r
     MatrixOlmSession * session,\r
@@ -147,7 +318,7 @@ MatrixOlmSessionTo(
     session->session =\r
         olm_session(session->memory);\r
 \r
     session->session =\r
         olm_session(session->memory);\r
 \r
-    static uint8_t random[OLM_OUTBOUND_SESSION_RANDOM_SIZE];\r
+    STATIC uint8_t random[OLM_OUTBOUND_SESSION_RANDOM_SIZE];\r
     Randomize(random, OLM_OUTBOUND_SESSION_RANDOM_SIZE);\r
 \r
     size_t res =\r
     Randomize(random, OLM_OUTBOUND_SESSION_RANDOM_SIZE);\r
 \r
     size_t res =\r
@@ -158,10 +329,36 @@ MatrixOlmSessionTo(
             random, OLM_OUTBOUND_SESSION_RANDOM_SIZE);\r
     \r
     if (res == olm_error()) {\r
             random, OLM_OUTBOUND_SESSION_RANDOM_SIZE);\r
     \r
     if (res == olm_error()) {\r
-        printf("error olm: %s\n", olm_account_last_error(olmAccount));\r
+        printf("error olm:%s\n", olm_session_last_error(session->session));\r
+    }\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+bool\r
+MatrixOlmSessionUnpickle(\r
+    MatrixOlmSession * session,\r
+    const char * deviceId,\r
+    void * pickled, int pickledLen,\r
+    const void * key, int keyLen)\r
+{\r
+    memset(session, 0, sizeof(MatrixOlmSession));\r
+\r
+    session->deviceId = deviceId;\r
+\r
+    session->session =\r
+        olm_session(session->memory);\r
+    \r
+    size_t res;\r
+    res = olm_unpickle_session(session->session,\r
+        key, keyLen,\r
+        pickled, pickledLen);\r
+    \r
+    if (res == olm_error()) {\r
+        printf("error unpickling olm session:%s\n", olm_session_last_error(session->session));\r
     }\r
 \r
     }\r
 \r
-    return session->session != NULL;\r
+    return res != olm_error();\r
 }\r
 \r
 bool\r
 }\r
 \r
 bool\r
@@ -170,9 +367,10 @@ MatrixOlmSessionEncrypt(
     const char * plaintext,\r
     char * outBuffer, int outBufferCap)\r
 {\r
     const char * plaintext,\r
     char * outBuffer, int outBufferCap)\r
 {\r
-    static uint8_t random[OLM_ENCRYPT_RANDOM_SIZE];\r
+    STATIC uint8_t random[OLM_ENCRYPT_RANDOM_SIZE];\r
     Randomize(random, OLM_ENCRYPT_RANDOM_SIZE);\r
 \r
     Randomize(random, OLM_ENCRYPT_RANDOM_SIZE);\r
 \r
+    memset(outBuffer, 0, outBufferCap);\r
     size_t res = olm_encrypt(session->session,\r
         plaintext, strlen(plaintext),\r
         random, OLM_ENCRYPT_RANDOM_SIZE,\r
     size_t res = olm_encrypt(session->session,\r
         plaintext, strlen(plaintext),\r
         random, OLM_ENCRYPT_RANDOM_SIZE,\r
@@ -181,6 +379,85 @@ MatrixOlmSessionEncrypt(
     return res != olm_error();\r
 }\r
 \r
     return res != olm_error();\r
 }\r
 \r
+bool\r
+MatrixOlmSessionDecrypt(\r
+    MatrixOlmSession * session,\r
+    size_t messageType,\r
+    char * encrypted,\r
+    char * outBuffer, int outBufferCap)\r
+{\r
+    STATIC uint8_t random[OLM_ENCRYPT_RANDOM_SIZE];\r
+    Randomize(random, OLM_ENCRYPT_RANDOM_SIZE);\r
+\r
+    size_t res =\r
+        olm_decrypt(session->session,\r
+            messageType,\r
+            encrypted, strlen(encrypted),\r
+            outBuffer, outBufferCap);\r
+    \r
+    if (res != olm_error() && (int)res < outBufferCap)\r
+        outBuffer[res] = '\0';\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+bool\r
+MatrixMegolmInSessionInit(\r
+    MatrixMegolmInSession * session,\r
+    const char * roomId,\r
+    const char * sessionId,\r
+    const char * sessionKey, int sessionKeyLen)\r
+{\r
+    memset(session, 0, sizeof(MatrixMegolmInSession));\r
+    \r
+    strncpy(session->roomId, roomId, sizeof(session->roomId));\r
+    strncpy(session->id, sessionId, sizeof(session->id));\r
+    strncpy(session->key, sessionKey, sizeof(session->key));\r
+\r
+    session->session =\r
+        olm_inbound_group_session(session->memory);\r
+\r
+    size_t res =\r
+        olm_init_inbound_group_session(\r
+        // olm_import_inbound_group_session(\r
+            session->session,\r
+            (const uint8_t *)sessionKey, sessionKeyLen);\r
+    if (res == olm_error()) {\r
+        printf("Error initializing Megolm session: %s\n", olm_inbound_group_session_last_error(session->session));\r
+    }\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+bool\r
+MatrixMegolmInSessionDecrypt(\r
+    MatrixMegolmInSession * session,\r
+    const char * encrypted, int encryptedLen,\r
+    char * outDecrypted, int outDecryptedCap)\r
+{\r
+    // uint8_t buffer[1024];\r
+    // memcpy(buffer, encrypted, encryptedLen);\r
+\r
+    uint32_t megolmInMessageIndex;\r
+\r
+    size_t res =\r
+        olm_group_decrypt(session->session,\r
+            (uint8_t *)encrypted, encryptedLen,\r
+            (uint8_t *)outDecrypted, outDecryptedCap,\r
+            &megolmInMessageIndex);\r
+    \r
+    printf("message index: %d\n", (int)megolmInMessageIndex);\r
+    \r
+    if (res == olm_error()) {\r
+        printf("error decrypting megolm message: %s\n", olm_inbound_group_session_last_error(session->session));\r
+    }\r
+    else {\r
+        printf("decrypted len: %d\n", res);\r
+    }\r
+    \r
+    return true;\r
+}\r
+\r
 // https://matrix.org/docs/guides/end-to-end-encryption-implementation-guide#starting-a-megolm-session\r
 bool\r
 MatrixMegolmOutSessionInit(\r
 // https://matrix.org/docs/guides/end-to-end-encryption-implementation-guide#starting-a-megolm-session\r
 bool\r
 MatrixMegolmOutSessionInit(\r
@@ -189,10 +466,10 @@ MatrixMegolmOutSessionInit(
 {\r
     memset(session, 0, sizeof(MatrixMegolmOutSession));\r
 \r
 {\r
     memset(session, 0, sizeof(MatrixMegolmOutSession));\r
 \r
-    static uint8_t random[MEGOLM_INIT_RANDOM_SIZE];\r
+    STATIC uint8_t random[MEGOLM_INIT_RANDOM_SIZE];\r
     Randomize(random, MEGOLM_INIT_RANDOM_SIZE);\r
 \r
     Randomize(random, MEGOLM_INIT_RANDOM_SIZE);\r
 \r
-    session->roomId = roomId;\r
+    strncpy(session->roomId, roomId, ROOM_ID_SIZE);\r
 \r
     session->session =\r
         olm_outbound_group_session(session->memory);\r
 \r
     session->session =\r
         olm_outbound_group_session(session->memory);\r
@@ -219,6 +496,7 @@ MatrixMegolmOutSessionEncrypt(
     const char * plaintext,\r
     char * outBuffer, int outBufferCap)\r
 {\r
     const char * plaintext,\r
     char * outBuffer, int outBufferCap)\r
 {\r
+    memset(outBuffer, 0, outBufferCap);\r
     size_t res = olm_group_encrypt(session->session,\r
         (uint8_t *)plaintext, strlen(plaintext),\r
         (uint8_t *)outBuffer, outBufferCap);\r
     size_t res = olm_group_encrypt(session->session,\r
         (uint8_t *)plaintext, strlen(plaintext),\r
         (uint8_t *)outBuffer, outBufferCap);\r
@@ -227,34 +505,15 @@ MatrixMegolmOutSessionEncrypt(
 }\r
 \r
 \r
 }\r
 \r
 \r
-\r
 bool\r
 MatrixClientInit(\r
 bool\r
 MatrixClientInit(\r
-    MatrixClient * client,\r
-    const char * server)\r
+    MatrixClient * client)\r
 {\r
     memset(client, 0, sizeof(MatrixClient));\r
 \r
 {\r
     memset(client, 0, sizeof(MatrixClient));\r
 \r
-    strcpy(client->server, server);\r
-\r
     // init olm account\r
     MatrixOlmAccountInit(&client->olmAccount);\r
 \r
     // init olm account\r
     MatrixOlmAccountInit(&client->olmAccount);\r
 \r
-    // set device key\r
-    static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE];\r
-    size_t res =\r
-        olm_account_identity_keys(\r
-            client->olmAccount.account,\r
-            deviceKeysJson,\r
-            OLM_IDENTITY_KEYS_JSON_SIZE);\r
-\r
-    mjson_get_string(deviceKeysJson, res,\r
-        "$.curve25519",\r
-        client->deviceKey, DEVICE_KEY_SIZE);\r
-    mjson_get_string(deviceKeysJson, res,\r
-        "$.ed25519",\r
-        client->signingKey, SIGNING_KEY_SIZE);\r
-\r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
 \r
@@ -263,13 +522,9 @@ MatrixClientSetAccessToken(
     MatrixClient * client,\r
     const char * accessToken)\r
 {\r
     MatrixClient * client,\r
     const char * accessToken)\r
 {\r
-    int accessTokenLen = strlen(accessToken);\r
-\r
-    if (accessTokenLen > ACCESS_TOKEN_SIZE - 1)\r
-        return false;\r
-\r
-    for (int i = 0; i < accessTokenLen; i++)\r
+    for (int i = 0; i < ACCESS_TOKEN_SIZE-1; i++)\r
         client->accessToken[i] = accessToken[i];\r
         client->accessToken[i] = accessToken[i];\r
+    client->accessToken[ACCESS_TOKEN_SIZE-1] = '\0';\r
 \r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
@@ -279,13 +534,9 @@ MatrixClientSetDeviceId(
     MatrixClient * client,\r
     const char * deviceId)\r
 {\r
     MatrixClient * client,\r
     const char * deviceId)\r
 {\r
-    int deviceIdLen = strlen(deviceId);\r
-\r
-    if (deviceIdLen > DEVICE_ID_SIZE - 1)\r
-        return false;\r
-\r
-    for (int i = 0; i < deviceIdLen; i++)\r
+    for (int i = 0; i < DEVICE_ID_SIZE-1; i++)\r
         client->deviceId[i] = deviceId[i];\r
         client->deviceId[i] = deviceId[i];\r
+    client->deviceId[DEVICE_ID_SIZE-1] = '\0';\r
 \r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
@@ -295,13 +546,9 @@ MatrixClientSetUserId(
     MatrixClient * client,\r
     const char * userId)\r
 {\r
     MatrixClient * client,\r
     const char * userId)\r
 {\r
-    int userIdLen = strlen(userId);\r
-\r
-    if (userIdLen > USER_ID_SIZE - 1)\r
-        return false;\r
-\r
-    for (int i = 0; i < userIdLen; i++)\r
+    for (int i = 0; i < USER_ID_SIZE-1; i++)\r
         client->userId[i] = userId[i];\r
         client->userId[i] = userId[i];\r
+    client->userId[USER_ID_SIZE-1] = '\0';\r
 \r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
@@ -311,7 +558,7 @@ MatrixClientGenerateOnetimeKeys(
     MatrixClient * client,\r
     int numberOfKeys)\r
 {\r
     MatrixClient * client,\r
     int numberOfKeys)\r
 {\r
-    static uint8_t random[OLM_ONETIME_KEYS_RANDOM_SIZE];\r
+    STATIC uint8_t random[OLM_ONETIME_KEYS_RANDOM_SIZE];\r
     Randomize(random, OLM_ONETIME_KEYS_RANDOM_SIZE);\r
 \r
     size_t res =\r
     Randomize(random, OLM_ONETIME_KEYS_RANDOM_SIZE);\r
 \r
     size_t res =\r
@@ -326,12 +573,10 @@ bool
 MatrixClientUploadOnetimeKeys(\r
     MatrixClient * client)\r
 {\r
 MatrixClientUploadOnetimeKeys(\r
     MatrixClient * client)\r
 {\r
-    static char requestBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
+    mjson_snprintf(g_KeysUploadRequestBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
+        "{");\r
 \r
 \r
-    mjson_snprintf(requestBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
-        "{\"one_time_keys\":{");\r
-\r
-    static char onetimeKeysBuffer[1024];\r
+    STATIC char onetimeKeysBuffer[1024];\r
     olm_account_one_time_keys(client->olmAccount.account,\r
         onetimeKeysBuffer, 1024);\r
 \r
     olm_account_one_time_keys(client->olmAccount.account,\r
         onetimeKeysBuffer, 1024);\r
 \r
@@ -341,31 +586,46 @@ MatrixClientUploadOnetimeKeys(
 \r
     int koff, klen, voff, vlen, vtype, off = 0;\r
     while ((off = mjson_next(keys, keysLen, off, &koff, &klen, &voff, &vlen, &vtype)) != 0) {\r
 \r
     int koff, klen, voff, vlen, vtype, off = 0;\r
     while ((off = mjson_next(keys, keysLen, off, &koff, &klen, &voff, &vlen, &vtype)) != 0) {\r
-        static char keyJson[JSON_ONETIME_KEY_SIZE];\r
+        STATIC char keyJson[JSON_ONETIME_KEY_SIZE];\r
         \r
         \r
-        snprintf(keyJson, JSON_ONETIME_KEY_SIZE,\r
-            "{\"key\":\"%.*s\"}",\r
-            vlen-2, keys + voff+1);\r
+        int keyJsonLen =\r
+            snprintf(keyJson, JSON_ONETIME_KEY_SIZE,\r
+                "{\"key\":\"%.*s\"}",\r
+                vlen-2, keys + voff+1);\r
 \r
 \r
-        static char keyJsonSigned[JSON_ONETIME_KEY_SIGNED_SIZE];\r
+        STATIC char keyJsonSigned[JSON_ONETIME_KEY_SIGNED_SIZE];\r
 \r
         JsonSign(client,\r
 \r
         JsonSign(client,\r
-            keyJson, JSON_ONETIME_KEY_SIZE,\r
+            keyJson, keyJsonLen,\r
             keyJsonSigned, JSON_ONETIME_KEY_SIGNED_SIZE);\r
         \r
             keyJsonSigned, JSON_ONETIME_KEY_SIGNED_SIZE);\r
         \r
-        mjson_snprintf(requestBuffer+strlen(requestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer),\r
+        mjson_snprintf(g_KeysUploadRequestBuffer+strlen(g_KeysUploadRequestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(g_KeysUploadRequestBuffer),\r
             "\"signed_curve25519:%.*s\":%s,",\r
             klen-2, keys + koff+1,\r
             keyJsonSigned);\r
     }\r
 \r
             "\"signed_curve25519:%.*s\":%s,",\r
             klen-2, keys + koff+1,\r
             keyJsonSigned);\r
     }\r
 \r
-    mjson_snprintf(requestBuffer+strlen(requestBuffer)-1, KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer),\r
-        "}}");\r
+    if (g_KeysUploadRequestBuffer[strlen(g_KeysUploadRequestBuffer)-1] == ',')\r
+        g_KeysUploadRequestBuffer[strlen(g_KeysUploadRequestBuffer)-1] = '\0';\r
 \r
 \r
-    static char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE];\r
-    MatrixHttpPost(client,\r
+    mjson_snprintf(g_KeysUploadRequestBuffer+strlen(g_KeysUploadRequestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(g_KeysUploadRequestBuffer),\r
+        "}");\r
+        \r
+    // STATIC char onetimeKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
+    // JsonSign(client,\r
+    //     g_KeysUploadRequestBuffer, strlen(g_KeysUploadRequestBuffer),\r
+    //     onetimeKeysSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE);\r
+        \r
+    // STATIC char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
+    // snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE,\r
+    // "{\"one_time_keys\":%s}", onetimeKeysSignedBuffer);\r
+    snprintf(g_KeysUploadRequestSignedBuffer, KEYS_UPLOAD_REQUEST_SIGNED_SIZE,\r
+    "{\"one_time_keys\":%s}", g_KeysUploadRequestBuffer);\r
+\r
+    STATIC char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE];\r
+    MatrixHttpPost(client->hc,\r
         KEYS_UPLOAD_URL,\r
         KEYS_UPLOAD_URL,\r
-        requestBuffer,\r
+        g_KeysUploadRequestSignedBuffer,\r
         responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE,\r
         true);\r
 \r
         responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE,\r
         true);\r
 \r
@@ -377,33 +637,39 @@ bool
 MatrixClientUploadDeviceKeys(\r
     MatrixClient * client)\r
 {\r
 MatrixClientUploadDeviceKeys(\r
     MatrixClient * client)\r
 {\r
-    static char deviceKeysBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
+    char thisDeviceKey[DEVICE_KEY_SIZE];\r
+    MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE);\r
+    char thisSigningKey[DEVICE_KEY_SIZE];\r
+    MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE);\r
 \r
 \r
-    mjson_snprintf(deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
-        "{\"device_keys\":{"\r
-            "\"algorithms\":[\"m.olm.v1.curve25519-aes-sha2\",\"m.megolm.v1.aes-sha2\"],"\r
-            "\"device_id\":\"%s\","\r
-            "\"keys\":{"\r
-                "\"curve25519:%s\":\"%s\","\r
-                "\"ed25519:%s\":\"%s\""\r
-            "},"\r
-            "\"user_id\":\"%s\""\r
-        "}}",\r
-        client->deviceId,\r
-        client->deviceId, client->deviceKey,\r
-        client->deviceId, client->signingKey,\r
-        client->userId);\r
+    int deviceKeysBufferLen =\r
+        mjson_snprintf(g_KeysUploadRequestBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
+            "{"\r
+                "\"algorithms\":[\"m.olm.v1.curve25519-aes-sha2\",\"m.megolm.v1.aes-sha2\"],"\r
+                "\"device_id\":\"%s\","\r
+                "\"keys\":{"\r
+                    "\"curve25519:%s\":\"%s\","\r
+                    "\"ed25519:%s\":\"%s\""\r
+                "},"\r
+                "\"user_id\":\"%s\""\r
+            "}",\r
+            client->deviceId,\r
+            client->deviceId, thisDeviceKey,\r
+            client->deviceId, thisSigningKey,\r
+            client->userId);\r
 \r
 \r
-    static char deviceKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
     JsonSign(client,\r
     JsonSign(client,\r
-        deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
-        deviceKeysSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE);\r
-\r
+        g_KeysUploadRequestBuffer, deviceKeysBufferLen,\r
+        g_KeysUploadRequestSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE);\r
+    \r
+    STATIC char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE+30];\r
+    snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE+30,\r
+    "{\"device_keys\":%s}", g_KeysUploadRequestSignedBuffer);\r
 \r
 \r
-    static char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE];\r
-    MatrixHttpPost(client,\r
+    STATIC char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE];\r
+    MatrixHttpPost(client->hc,\r
         KEYS_UPLOAD_URL,\r
         KEYS_UPLOAD_URL,\r
-        deviceKeysSignedBuffer,\r
+        finalEvent,\r
         responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE,\r
         true);\r
 \r
         responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE,\r
         true);\r
 \r
@@ -418,31 +684,31 @@ MatrixClientClaimOnetimeKey(
     const char * deviceId,\r
     char * outOnetimeKey, int outOnetimeKeyCap)\r
 {\r
     const char * deviceId,\r
     char * outOnetimeKey, int outOnetimeKeyCap)\r
 {\r
-    static char requestBuffer[KEYS_CLAIM_REQUEST_SIZE];\r
+    STATIC char requestBuffer[KEYS_CLAIM_REQUEST_SIZE];\r
     mjson_snprintf(requestBuffer, KEYS_CLAIM_REQUEST_SIZE,\r
     "{"\r
     mjson_snprintf(requestBuffer, KEYS_CLAIM_REQUEST_SIZE,\r
     "{"\r
-      "\"one_time_keys\": {"\r
-        "\"%s\": {"\r
-          "\"%s\": \"signed_curve25519\""\r
+      "\"one_time_keys\":{"\r
+        "\"%s\":{"\r
+          "\"%s\":\"signed_curve25519\""\r
         "}"\r
       "},"\r
         "}"\r
       "},"\r
-      "\"timeout\": 10000"\r
+      "\"timeout\":10000"\r
     "}",\r
     userId,\r
     deviceId);\r
 \r
     "}",\r
     userId,\r
     deviceId);\r
 \r
-    static char responseBuffer[KEYS_CLAIM_RESPONSE_SIZE];\r
-    MatrixHttpPost(client,\r
+    STATIC char responseBuffer[KEYS_CLAIM_RESPONSE_SIZE];\r
+    MatrixHttpPost(client->hc,\r
         KEYS_CLAIM_URL,\r
         requestBuffer,\r
         responseBuffer, KEYS_CLAIM_RESPONSE_SIZE,\r
         true);\r
     \r
         KEYS_CLAIM_URL,\r
         requestBuffer,\r
         responseBuffer, KEYS_CLAIM_RESPONSE_SIZE,\r
         true);\r
     \r
-    char userIdEscaped[USER_ID_SIZE];\r
+    STATIC char userIdEscaped[USER_ID_SIZE];\r
     JsonEscape(userId, strlen(userId),\r
         userIdEscaped, USER_ID_SIZE);\r
     \r
     JsonEscape(userId, strlen(userId),\r
         userIdEscaped, USER_ID_SIZE);\r
     \r
-    static char query[JSON_QUERY_SIZE];\r
+    STATIC char query[JSON_QUERY_SIZE];\r
     snprintf(query, JSON_QUERY_SIZE,\r
         "$.one_time_keys.%s.%s",\r
         userIdEscaped,\r
     snprintf(query, JSON_QUERY_SIZE,\r
         "$.one_time_keys.%s.%s",\r
         userIdEscaped,\r
@@ -461,7 +727,7 @@ MatrixClientClaimOnetimeKey(
     mjson_get_string(keyObject + voff, vlen,\r
         "$.key", outOnetimeKey, outOnetimeKeyCap);\r
     \r
     mjson_get_string(keyObject + voff, vlen,\r
         "$.key", outOnetimeKey, outOnetimeKeyCap);\r
     \r
-    // TODO: verify signature\r
+    // TODO:verify signature\r
     \r
     return true;\r
 }\r
     \r
     return true;\r
 }\r
@@ -474,34 +740,34 @@ MatrixClientLoginPassword(
     const char * password,\r
     const char * displayName)\r
 {\r
     const char * password,\r
     const char * displayName)\r
 {\r
-    static char requestBuffer[LOGIN_REQUEST_SIZE];\r
+    STATIC char requestBuffer[LOGIN_REQUEST_SIZE];\r
 \r
     mjson_snprintf(requestBuffer, LOGIN_REQUEST_SIZE,\r
         "{"\r
 \r
     mjson_snprintf(requestBuffer, LOGIN_REQUEST_SIZE,\r
         "{"\r
-            "\"type\": \"m.login.password\","\r
-            "\"identifier\": {"\r
-                "\"type\": \"m.id.user\","\r
-                "\"user\": \"%s\""\r
+            "\"type\":\"m.login.password\","\r
+            "\"identifier\":{"\r
+                "\"type\":\"m.id.user\","\r
+                "\"user\":\"%s\""\r
             "},"\r
             "},"\r
-            "\"password\": \"%s\","\r
-            "\"initial_device_display_name\": \"%s\""\r
+            "\"password\":\"%s\","\r
+            "\"initial_device_display_name\":\"%s\""\r
         "}",\r
         username,\r
         password,\r
         displayName);\r
     \r
         "}",\r
         username,\r
         password,\r
         displayName);\r
     \r
-    static char responseBuffer[LOGIN_RESPONSE_SIZE];\r
+    STATIC char responseBuffer[LOGIN_RESPONSE_SIZE];\r
     bool result =\r
     bool result =\r
-        MatrixHttpPost(client,\r
+        MatrixHttpPost(client->hc,\r
             LOGIN_URL,\r
             requestBuffer,\r
             responseBuffer, LOGIN_RESPONSE_SIZE,\r
             false);\r
     \r
             LOGIN_URL,\r
             requestBuffer,\r
             responseBuffer, LOGIN_RESPONSE_SIZE,\r
             false);\r
     \r
-    int responseLen = strlen(responseBuffer);\r
-    \r
     if (!result)\r
         return false;\r
     if (!result)\r
         return false;\r
+    \r
+    int responseLen = strlen(responseBuffer);\r
 \r
     mjson_get_string(responseBuffer, responseLen,\r
         "$.access_token",\r
 \r
     mjson_get_string(responseBuffer, responseLen,\r
         "$.access_token",\r
@@ -515,6 +781,8 @@ MatrixClientLoginPassword(
     mjson_get_string(responseBuffer, responseLen,\r
         "$.refresh_token",\r
         client->refreshToken, REFRESH_TOKEN_SIZE);\r
     mjson_get_string(responseBuffer, responseLen,\r
         "$.refresh_token",\r
         client->refreshToken, REFRESH_TOKEN_SIZE);\r
+        \r
+    MatrixHttpSetAccessToken(client->hc, client->accessToken);\r
 \r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
@@ -527,16 +795,16 @@ MatrixClientSendEvent(
     const char * msgType,\r
     const char * msgBody)\r
 {    \r
     const char * msgType,\r
     const char * msgBody)\r
 {    \r
-    static char requestUrl[MAX_URL_LEN];\r
+    STATIC char requestUrl[MAX_URL_LEN];\r
     sprintf(requestUrl,\r
     sprintf(requestUrl,\r
-        ROOMEVENT_URL, roomId, msgType, (int)time(NULL));\r
+        ROOM_SEND_URL, roomId, msgType, (int)time(NULL));\r
 \r
 \r
-    static char responseBuffer[ROOMEVENT_RESPONSE_SIZE];\r
+    STATIC char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
     bool result =\r
     bool result =\r
-        MatrixHttpPut(client,\r
+        MatrixHttpPut(client->hc,\r
             requestUrl,\r
             msgBody,\r
             requestUrl,\r
             msgBody,\r
-            responseBuffer, ROOMEVENT_RESPONSE_SIZE,\r
+            responseBuffer, ROOM_SEND_RESPONSE_SIZE,\r
             true);\r
     \r
     return result;\r
             true);\r
     \r
     return result;\r
@@ -552,7 +820,7 @@ MatrixClientSendEventEncrypted(
     const char * msgBody)\r
 {\r
     // event json\r
     const char * msgBody)\r
 {\r
     // event json\r
-    static char requestBuffer[ROOMEVENT_REQUEST_SIZE];\r
+    STATIC char requestBuffer[ROOM_SEND_REQUEST_SIZE];\r
     sprintf(requestBuffer,\r
         "{"\r
         "\"type\":\"%s\","\r
     sprintf(requestBuffer,\r
         "{"\r
         "\"type\":\"%s\","\r
@@ -565,21 +833,24 @@ MatrixClientSendEventEncrypted(
 \r
     // get megolm session\r
     MatrixMegolmOutSession * outSession;\r
 \r
     // get megolm session\r
     MatrixMegolmOutSession * outSession;\r
-    MatrixClientGetMegolmOutSession(client, roomId, &outSession);\r
+    if (! MatrixClientGetMegolmOutSession(client, roomId, &outSession))\r
+        MatrixClientNewMegolmOutSession(client, roomId, &outSession);\r
         \r
     // encrypt\r
         \r
     // encrypt\r
-    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\r
     MatrixMegolmOutSessionEncrypt(outSession,\r
         requestBuffer,\r
     MatrixMegolmOutSessionEncrypt(outSession,\r
         requestBuffer,\r
-        encryptedBuffer, ENCRYPTED_REQUEST_SIZE);\r
+        g_EncryptedRequestBuffer, ENCRYPTED_REQUEST_SIZE);\r
+\r
+    char thisDeviceKey[DEVICE_KEY_SIZE];\r
+    MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE);\r
+    \r
 \r
     // encrypted event json\r
 \r
     // encrypted event json\r
-    const char * senderKey = client->deviceKey;\r
+    const char * senderKey = thisDeviceKey;\r
     const char * sessionId = outSession->id;\r
     const char * deviceId = client->deviceId;\r
 \r
     const char * sessionId = outSession->id;\r
     const char * deviceId = client->deviceId;\r
 \r
-    static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
-    sprintf(encryptedEventBuffer,\r
+    snprintf(g_EncryptedEventBuffer, ENCRYPTED_EVENT_SIZE,\r
         "{"\r
         "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
         "\"ciphertext\":\"%s\","\r
         "{"\r
         "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
         "\"ciphertext\":\"%s\","\r
@@ -587,7 +858,7 @@ MatrixClientSendEventEncrypted(
         "\"sender_key\":\"%s\","\r
         "\"session_id\":\"%s\""\r
         "}",\r
         "\"sender_key\":\"%s\","\r
         "\"session_id\":\"%s\""\r
         "}",\r
-        encryptedBuffer,\r
+        g_EncryptedRequestBuffer,\r
         deviceId,\r
         senderKey,\r
         sessionId);\r
         deviceId,\r
         senderKey,\r
         sessionId);\r
@@ -596,20 +867,508 @@ MatrixClientSendEventEncrypted(
     return MatrixClientSendEvent(client,\r
         roomId,\r
         "m.room.encrypted",\r
     return MatrixClientSendEvent(client,\r
         roomId,\r
         "m.room.encrypted",\r
-        encryptedEventBuffer);\r
+        g_EncryptedEventBuffer);\r
+}\r
+\r
+void\r
+MatrixClientHandleEvent(\r
+    MatrixClient * client,\r
+    const char * event, int eventLen\r
+) {\r
+    STATIC char eventType[128];\r
+    memset(eventType, 0, sizeof(eventType));\r
+    mjson_get_string(event, eventLen, "$.type", eventType, 128);\r
+\r
+    static char transactionId[64];\r
+    static char verifyFromDeviceId[DEVICE_ID_SIZE];\r
+    static OlmSAS * olmSas = NULL;\r
+\r
+    if (strcmp(eventType, "m.key.verification.request") == 0) {\r
+        memset(transactionId, 0, 64);\r
+        if (olmSas != NULL)\r
+            free(olmSas);\r
+        \r
+        mjson_get_string(event, eventLen, "$.content.transaction_id", transactionId, 64);\r
+        mjson_get_string(event, eventLen, "$.content.from_device", verifyFromDeviceId, DEVICE_ID_SIZE);\r
+        \r
+        char verificationReadyBuffer[2048];\r
+        snprintf(verificationReadyBuffer, 2048,\r
+            "{"\r
+            "\"from_device\":\"%s\","\r
+            "\"methods\":[\"m.sas.v1\"],"\r
+            "\"transaction_id\":\"%s\""\r
+            "}",\r
+            client->deviceId,\r
+            transactionId);\r
+        \r
+        MatrixClientSendToDevice(client,\r
+            client->userId,\r
+            verifyFromDeviceId,\r
+            verificationReadyBuffer,\r
+            "m.key.verification.ready");\r
+    }\r
+    else if (strcmp(eventType, "m.key.verification.start") == 0) {\r
+        olmSas = olm_sas(malloc(olm_sas_size()));\r
+        void * sasRandomBytes = malloc(olm_create_sas_random_length(olmSas));\r
+        olm_create_sas(olmSas,\r
+            sasRandomBytes,\r
+            olm_create_sas_random_length(olmSas));\r
+        \r
+        OlmUtility * olmUtil = olm_utility(malloc(olm_utility_size()));\r
+        \r
+        STATIC char publicKey[64];\r
+        STATIC char keyStartJsonCanonical[512];\r
+        STATIC char concat[512+64];\r
+        STATIC char commitment[1024];\r
+        olm_sas_get_pubkey(olmSas,\r
+            publicKey,\r
+            64);\r
+        printf("public key: %.*s\n", olm_sas_pubkey_length(olmSas), publicKey);\r
+\r
+        const char * keyStartJson;\r
+        int keyStartJsonLen;\r
+        mjson_find(event, eventLen, "$.content", &keyStartJson, &keyStartJsonLen);\r
+        JsonCanonicalize(keyStartJson, keyStartJsonLen, keyStartJsonCanonical, 512);\r
+\r
+        printf("json:\n%.*s\ncanonical json:\n%s\n", keyStartJsonLen, keyStartJson, keyStartJsonCanonical);\r
+\r
+        int concatLen =\r
+            snprintf(concat, 512+64, "%.*s%s", olm_sas_pubkey_length(olmSas), publicKey, keyStartJsonCanonical);\r
+\r
+        int commitmentLen =\r
+            olm_sha256(olmUtil, concat, concatLen, commitment, 1024);\r
+        \r
+        STATIC char verificationAcceptBuffer[512];\r
+        snprintf(verificationAcceptBuffer, 512,\r
+            "{"\r
+            "\"commitment\":\"%.*s\","\r
+            "\"hash\":\"sha256\","\r
+            "\"key_agreement_protocol\":\"curve25519\","\r
+            "\"message_authentication_code\":\"hkdf-hmac-sha256.v2\","\r
+            "\"method\":\"m.sas.v1\","\r
+            "\"short_authentication_string\":[\"decimal\"],"\r
+            "\"transaction_id\":\"%s\""\r
+            "}",\r
+            commitmentLen, commitment,\r
+            transactionId);\r
+        \r
+        MatrixClientSendToDevice(client,\r
+            client->userId,\r
+            verifyFromDeviceId,\r
+            verificationAcceptBuffer,\r
+            "m.key.verification.accept");\r
+    }\r
+    else if (strcmp(eventType, "m.key.verification.key") == 0) {\r
+        STATIC char publicKey[128];\r
+        olm_sas_get_pubkey(olmSas,\r
+            publicKey,\r
+            128);\r
+\r
+        STATIC char theirPublicKey[128];\r
+        int theirPublicKeyLen =\r
+            mjson_get_string(event, eventLen, "$.content.key", theirPublicKey, 128);\r
+        \r
+        printf("event: %.*s\n", eventLen, event);\r
+        printf("theirPublicKey: %.*s\n", theirPublicKeyLen, theirPublicKey);\r
+        printf("publicKey: %.*s\n", olm_sas_pubkey_length(olmSas), publicKey);\r
+\r
+        olm_sas_set_their_key(olmSas, theirPublicKey, theirPublicKeyLen);\r
+        \r
+        STATIC char verificationKeyBuffer[256];\r
+        snprintf(verificationKeyBuffer, 256,\r
+            "{"\r
+            "\"key\":\"%.*s\","\r
+            "\"transaction_id\":\"%s\""\r
+            "}",\r
+            olm_sas_pubkey_length(olmSas), publicKey,\r
+            transactionId);\r
+        \r
+        MatrixClientSendToDevice(client,\r
+            client->userId,\r
+            verifyFromDeviceId,\r
+            verificationKeyBuffer,\r
+            "m.key.verification.key");\r
+        \r
+        // sas\r
+        STATIC char hkdfInfo[1024];\r
+        int hkdfInfoLen =\r
+            snprintf(hkdfInfo, 1024,\r
+                "MATRIX_KEY_VERIFICATION_SAS%s%s%s%s%s",\r
+                client->userId,\r
+                verifyFromDeviceId,\r
+                client->userId,\r
+                client->deviceId,\r
+                transactionId);\r
+\r
+        unsigned char sasBytes[5];\r
+        olm_sas_generate_bytes(olmSas,\r
+            hkdfInfo, hkdfInfoLen,\r
+            sasBytes, 5);\r
+        int b0 = sasBytes[0];\r
+        int b1 = sasBytes[1];\r
+        int b2 = sasBytes[2];\r
+        int b3 = sasBytes[3];\r
+        int b4 = sasBytes[4];\r
+        \r
+        printf("%d %d %d %d %d\n", b0, b1, b2, b3, b4);\r
+\r
+        // https://spec.matrix.org/v1.7/client-server-api/#sas-method-decimal\r
+        printf("%d | %d | %d\n",\r
+            (b0 << 5 | b1 >> 3) + 1000,\r
+            ((b1 & 0x7) << 10 | b2 << 2 | b3 >> 6) + 1000,\r
+            ((b3 & 0x3F) << 7 | b4 >> 1) + 1000);\r
+        printf("%d | %d | %d\n",\r
+            ((b0 << 5) | (b1 >> 3)) + 1000,\r
+            (((b1 & 0x7) << 10) | (b2 << 2) | (b3 >> 6)) + 1000,\r
+            (((b3 & 0x3F) << 7) | (b4 >> 1)) + 1000);\r
+    }\r
+    else if (strcmp(eventType, "m.key.verification.mac") == 0) {        \r
+        // mac\r
+        STATIC char masterKey[123];\r
+        MatrixClientRequestMasterKey(client, masterKey, 123);\r
+\r
+        STATIC char keyList[256];\r
+        STATIC char keyListMac[256];\r
+        STATIC char key1Id[128];\r
+        STATIC char key1[128];\r
+        STATIC char key1Mac[128];\r
+        STATIC char key2Id[128];\r
+        STATIC char key2[128];\r
+        STATIC char key2Mac[128];\r
+\r
+        if (strcmp(masterKey, client->deviceId) < 0) {\r
+            snprintf(key1Id, 1024, "ed25519:%s", masterKey);\r
+            strcpy(key1, masterKey);\r
+            snprintf(key2Id, 1024, "ed25519:%s", client->deviceId);\r
+            MatrixOlmAccountGetSigningKey(&client->olmAccount, key2, 1024);\r
+        }\r
+        else {\r
+            snprintf(key1Id, 1024, "ed25519:%s", client->deviceId);\r
+            MatrixOlmAccountGetSigningKey(&client->olmAccount, key1, 1024);\r
+            snprintf(key2Id, 1024, "ed25519:%s", masterKey);\r
+            strcpy(key2, masterKey);\r
+        }\r
+\r
+        snprintf(keyList, 1024,\r
+            "%s,%s", key1Id, key2Id);\r
+        \r
+        STATIC char macInfo[1024];\r
+        int macInfoLen;\r
+        {\r
+            macInfoLen =\r
+                snprintf(macInfo, 1024,\r
+                    "MATRIX_KEY_VERIFICATION_MAC%s%s%s%s%s%s",\r
+                    client->userId,\r
+                    client->deviceId,\r
+                    client->userId,\r
+                    verifyFromDeviceId,\r
+                    transactionId,\r
+                    "KEY_IDS");\r
+            olm_sas_calculate_mac_fixed_base64(olmSas, keyList, strlen(keyList), macInfo, macInfoLen, keyListMac, 1024);\r
+        }\r
+        {\r
+            macInfoLen =\r
+                snprintf(macInfo, 1024,\r
+                    "MATRIX_KEY_VERIFICATION_MAC%s%s%s%s%s%s",\r
+                    client->userId,\r
+                    client->deviceId,\r
+                    client->userId,\r
+                    verifyFromDeviceId,\r
+                    transactionId,\r
+                    key1Id);\r
+            olm_sas_calculate_mac_fixed_base64(olmSas, key1, strlen(key1), macInfo, macInfoLen, key1Mac, 1024);\r
+        }\r
+        {\r
+            macInfoLen =\r
+                snprintf(macInfo, 1024,\r
+                    "MATRIX_KEY_VERIFICATION_MAC%s%s%s%s%s%s",\r
+                    client->userId,\r
+                    client->deviceId,\r
+                    client->userId,\r
+                    verifyFromDeviceId,\r
+                    transactionId,\r
+                    key2Id);\r
+            olm_sas_calculate_mac_fixed_base64(olmSas, key2, strlen(key2), macInfo, macInfoLen, key2Mac, 1024);\r
+        }\r
+\r
+        STATIC char verificationMacBuffer[1024];\r
+        snprintf(verificationMacBuffer, 1024,\r
+            "{"\r
+            "\"keys\":\"%s\","\r
+            "\"mac\":{"\r
+            "\"%s\":\"%s\","\r
+            "\"%s\":\"%s\""\r
+            "},"\r
+            "\"transaction_id\":\"%s\""\r
+            "}",\r
+            keyListMac,\r
+            key1Id,\r
+            key1Mac,\r
+            key2Id,\r
+            key2Mac,\r
+            transactionId);\r
+        \r
+        MatrixClientSendToDevice(client,\r
+            client->userId,\r
+            verifyFromDeviceId,\r
+            verificationMacBuffer,\r
+            "m.key.verification.mac");\r
+\r
+        STATIC char verificationDoneBuffer[128];\r
+        snprintf(verificationDoneBuffer, 128,\r
+            "{"\r
+            "\"transaction_id\":\"%s\""\r
+            "}",\r
+            transactionId);\r
+        \r
+        MatrixClientSendToDevice(client,\r
+            client->userId,\r
+            verifyFromDeviceId,\r
+            verificationDoneBuffer,\r
+            "m.key.verification.done");\r
+        \r
+        free(olmSas);\r
+        client->verified = true;\r
+    }\r
+    else if (strcmp(eventType, "m.room.encrypted") == 0) {\r
+        STATIC char algorithm[128];\r
+        mjson_get_string(event, eventLen, "$.content.algorithm", algorithm, 128);\r
+\r
+        if (strcmp(algorithm, "m.olm.v1.curve25519-aes-sha2") == 0) {\r
+            STATIC char thisDeviceKey[DEVICE_KEY_SIZE];\r
+            MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE);\r
+\r
+            STATIC char jp[128];\r
+            snprintf(jp, 128, "$.content.ciphertext.%s.type", thisDeviceKey);\r
+\r
+            double messageType;\r
+            mjson_get_number(event, eventLen, jp, &messageType);\r
+            int messageTypeInt = (int)messageType;\r
+\r
+            snprintf(jp, 128, "$.content.ciphertext.%s.body", thisDeviceKey);\r
+\r
+            mjson_get_string(event, eventLen, jp, g_EncryptedEventBuffer, 2048);\r
+\r
+            MatrixOlmSession * olmSession;\r
+            \r
+            if (! MatrixClientGetOlmSession(client, client->userId, verifyFromDeviceId, &olmSession))\r
+            {\r
+                if (messageTypeInt == 0) {\r
+                    MatrixClientNewOlmSessionIn(client,\r
+                        client->userId,\r
+                        verifyFromDeviceId,\r
+                        g_EncryptedEventBuffer,\r
+                        &olmSession);\r
+                }\r
+                else {\r
+                    MatrixClientNewOlmSessionOut(client,\r
+                        client->userId,\r
+                        verifyFromDeviceId,\r
+                        &olmSession);\r
+                }\r
+            }\r
+            \r
+            STATIC char decrypted[2048];\r
+            MatrixOlmSessionDecrypt(olmSession,\r
+                messageTypeInt, g_EncryptedEventBuffer, decrypted, 2048);\r
+            \r
+            MatrixClientHandleEvent(client, decrypted, strlen(decrypted));\r
+        }\r
+    }\r
+    else if (strcmp(eventType, "m.room_key") == 0 ||\r
+             strcmp(eventType, "m.forwarded_room_key") == 0) {\r
+        STATIC char roomId[128];\r
+        STATIC char sessionId[128];\r
+        STATIC char sessionKey[1024];\r
+        mjson_get_string(event, eventLen, "$.content.room_id", roomId, 128);\r
+        mjson_get_string(event, eventLen, "$.content.session_id", sessionId, 128);\r
+        mjson_get_string(event, eventLen, "$.content.session_key", sessionKey, 1024);\r
+        \r
+        printf("sessionId: %s\n", sessionId);\r
+        printf("sessionKey: %s\n", sessionKey);\r
+\r
+        MatrixMegolmInSession * megolmInSession;\r
+        MatrixClientNewMegolmInSession(client, roomId, sessionId, sessionKey, &megolmInSession);\r
+    }\r
+}\r
+\r
+void\r
+MatrixClientHandleRoomEvent(\r
+    MatrixClient * client,\r
+    const char * room, int roomLen,\r
+    const char * event, int eventLen)\r
+{\r
+    STATIC char eventType[128];\r
+    memset(eventType, 0, sizeof(eventType));\r
+    mjson_get_string(event, eventLen, "$.type", eventType, 128);\r
+\r
+    if (strcmp(eventType, "m.room.encrypted") == 0) {\r
+        STATIC char algorithm[128];\r
+        mjson_get_string(event, eventLen, "$.content.algorithm", algorithm, 128);\r
+\r
+        if (strcmp(algorithm, "m.megolm.v1.aes-sha2") == 0) {\r
+            STATIC char sessionId[128];\r
+            int sessionIdLen =\r
+                mjson_get_string(event, eventLen, "$.content.session_id", sessionId, 128);\r
+\r
+            bool res;\r
+\r
+            MatrixMegolmInSession * megolmInSession;\r
+            res = MatrixClientGetMegolmInSession(client,\r
+                room, roomLen,\r
+                sessionId, sessionIdLen,\r
+                &megolmInSession);\r
+\r
+            if (res) {\r
+                mjson_get_string(event, eventLen, "$.content.ciphertext", g_EncryptedEventBuffer, 2048);\r
+\r
+                STATIC char decrypted[2048];\r
+                MatrixMegolmInSessionDecrypt(megolmInSession, g_EncryptedEventBuffer, strlen(g_EncryptedEventBuffer), decrypted, 2048);\r
+\r
+                MatrixClientHandleEvent(client, decrypted, strlen(decrypted));\r
+            }\r
+            else {\r
+                printf("megolm session not known\n");\r
+            }\r
+        }\r
+    }\r
+    MatrixClientHandleEvent(client, event, eventLen);\r
+}\r
+\r
+void\r
+MatrixClientHandleSync(\r
+    MatrixClient * client,\r
+    char * syncBuffer, int syncBufferLen,\r
+    char * nextBatch, int nextBatchCap)\r
+{    \r
+    int res;\r
+\r
+    const char * s = syncBuffer;\r
+    int slen = syncBufferLen;\r
+\r
+    mjson_get_string(s, slen, "$.next_batch", nextBatch, nextBatchCap);\r
+\r
+    // to_device\r
+\r
+    const char * events;\r
+    int eventsLen;\r
+    res =\r
+        mjson_find(s, slen, "$.to_device.events", &events, &eventsLen);\r
+    \r
+    if (res != MJSON_TOK_INVALID) {\r
+        {\r
+        int koff, klen, voff, vlen, vtype, off = 0;\r
+        for (off = 0; (off = mjson_next(events, eventsLen, off, &koff, &klen,\r
+                                        &voff, &vlen, &vtype)) != 0; ) {\r
+            const char * v = events + voff;\r
+\r
+            MatrixClientHandleEvent(client, v, vlen);\r
+        }\r
+        }\r
+    }\r
+\r
+    // rooms\r
+    \r
+    const char * rooms;\r
+    int roomsLen;\r
+    res =\r
+        mjson_find(s, slen, "$.rooms.join", &rooms, &roomsLen);\r
+    \r
+    if (res != MJSON_TOK_INVALID) {\r
+        {\r
+        int koff, klen, voff, vlen, vtype, off = 0;\r
+        for (off = 0; (off = mjson_next(rooms, roomsLen, off, &koff, &klen,\r
+                                        &voff, &vlen, &vtype)) != 0; ) {\r
+            const char * k = rooms + koff;\r
+            const char * v = rooms + voff;\r
+\r
+            const char * events;\r
+            int eventsLen;\r
+            res =\r
+                mjson_find(v, vlen, "$.timeline.events", &events, &eventsLen);\r
+            \r
+            if (res != MJSON_TOK_INVALID) {\r
+                {\r
+                int koff2, klen2, voff2, vlen2, vtype2, off2 = 0;\r
+                for (off2 = 0; (off2 = mjson_next(events, eventsLen, off2, &koff2, &klen2,\r
+                                                &voff2, &vlen2, &vtype2)) != 0; ) {\r
+                    const char * v2 = events + voff2;\r
+\r
+                    MatrixClientHandleRoomEvent(client,\r
+                        k+1, klen-2,\r
+                        v2, vlen2);\r
+                }\r
+                }\r
+            }\r
+        }\r
+        }\r
+    }\r
 }\r
 \r
 // https://spec.matrix.org/v1.6/client-server-api/#get_matrixclientv3sync\r
 bool\r
 MatrixClientSync(\r
     MatrixClient * client,\r
 }\r
 \r
 // https://spec.matrix.org/v1.6/client-server-api/#get_matrixclientv3sync\r
 bool\r
 MatrixClientSync(\r
     MatrixClient * client,\r
-    char * outSyncBuffer, int outSyncCap)\r
+    char * outSyncBuffer, int outSyncCap,\r
+    char * nextBatch, int nextBatchCap)\r
 {\r
 {\r
-    return\r
-        MatrixHttpGet(client,\r
-            "/_matrix/client/v3/sync",\r
+    // filter={\"event_fields\":[\"to_device\"]}\r
+    STATIC char url[MAX_URL_LEN];\r
+    snprintf(url, MAX_URL_LEN,\r
+        "/_matrix/client/v3/sync?timeout=%d" "%s" "%s",\r
+        SYNC_TIMEOUT,\r
+        "",\r
+        // "&filter={\"event_fields\":[\"to_device\"]}",\r
+        strlen(nextBatch) > 0 ? "&since=" : "");\r
+    \r
+    int index = strlen(url);\r
+\r
+    for (size_t i = 0; i < strlen(nextBatch); i++) {\r
+        char c = nextBatch[i];\r
+\r
+        if (c == '~') {\r
+            url[index++] = '%';\r
+            url[index++] = '7';\r
+            url[index++] = 'E';\r
+        }\r
+        else {\r
+            url[index++] = c;\r
+        }\r
+    }\r
+    url[index] = '\0';\r
+\r
+    bool result =\r
+        MatrixHttpGet(client->hc,\r
+            url,\r
             outSyncBuffer, outSyncCap,\r
             true);\r
             outSyncBuffer, outSyncCap,\r
             true);\r
+    \r
+    MatrixClientHandleSync(client,\r
+        outSyncBuffer, strlen(outSyncBuffer),\r
+        nextBatch, nextBatchCap);\r
+    \r
+    return result;\r
+}\r
+\r
+// https://spec.matrix.org/v1.7/client-server-api/#get_matrixclientv3roomsroomideventeventid\r
+bool\r
+MatrixClientGetRoomEvent(\r
+    MatrixClient * client,\r
+    const char * roomId,\r
+    const char * eventId,\r
+    char * outEvent, int outEventCap)\r
+{\r
+    STATIC char url[MAX_URL_LEN];\r
+    snprintf(url, MAX_URL_LEN,\r
+        "/_matrix/client/v3/rooms/%s/event/%s",\r
+            roomId,\r
+            eventId);\r
+\r
+    return\r
+        MatrixHttpGet(client->hc,\r
+            url,\r
+            outEvent, outEventCap,\r
+            true);\r
 }\r
 \r
 bool\r
 }\r
 \r
 bool\r
@@ -620,7 +1379,7 @@ MatrixClientShareMegolmOutSession(
     MatrixMegolmOutSession * session)\r
 {\r
     // generate room key event\r
     MatrixMegolmOutSession * session)\r
 {\r
     // generate room key event\r
-    static char eventBuffer[KEY_SHARE_EVENT_LEN];\r
+    STATIC char eventBuffer[KEY_SHARE_EVENT_LEN];\r
     sprintf(eventBuffer,\r
         "{"\r
             "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
     sprintf(eventBuffer,\r
         "{"\r
             "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
@@ -633,16 +1392,6 @@ MatrixClientShareMegolmOutSession(
         session->key\r
     );\r
 \r
         session->key\r
     );\r
 \r
-    // // get olm session\r
-    // MatrixOlmSession * olmSession;\r
-    // MatrixClientGetOlmSession(client, userId, deviceId, &olmSession);\r
-\r
-    // // encrypt\r
-    // char encryptedBuffer[KEY_SHARE_EVENT_LEN];\r
-    // MatrixOlmSessionEncrypt(olmSession,\r
-    //     eventBuffer,\r
-    //     encryptedBuffer, KEY_SHARE_EVENT_LEN);\r
-\r
     // send\r
     MatrixClientSendToDeviceEncrypted(client,\r
         userId,\r
     // send\r
     MatrixClientSendToDeviceEncrypted(client,\r
         userId,\r
@@ -656,6 +1405,7 @@ MatrixClientShareMegolmOutSession(
 bool\r
 MatrixClientShareMegolmOutSessionTest(\r
     MatrixClient * client,\r
 bool\r
 MatrixClientShareMegolmOutSessionTest(\r
     MatrixClient * client,\r
+    const char * userId,\r
     const char * deviceId,\r
     MatrixMegolmOutSession * session)\r
 {\r
     const char * deviceId,\r
     MatrixMegolmOutSession * session)\r
 {\r
@@ -675,7 +1425,7 @@ MatrixClientShareMegolmOutSessionTest(
 \r
     // send\r
     MatrixClientSendToDevice(client,\r
 \r
     // send\r
     MatrixClientSendToDevice(client,\r
-        client->userId,\r
+        userId,\r
         deviceId,\r
         eventBuffer,\r
         "m.room_key");\r
         deviceId,\r
         eventBuffer,\r
         "m.room_key");\r
@@ -683,23 +1433,6 @@ MatrixClientShareMegolmOutSessionTest(
     return true;\r
 }\r
 \r
     return true;\r
 }\r
 \r
-// bool\r
-// MatrixClientSetMegolmOutSession(\r
-//     MatrixClient * client,\r
-//     const char * roomId,\r
-//     MatrixMegolmOutSession session)\r
-// {\r
-//     if (client->numMegolmOutSessions < 10)\r
-//     {\r
-//         session.roomId = roomId;\r
-//         client->megolmOutSessions[client->numMegolmOutSessions] = session;\r
-//         client->numMegolmOutSessions++;\r
-\r
-//         return true;\r
-//     }\r
-//     return false;\r
-// }\r
-\r
 bool\r
 MatrixClientGetMegolmOutSession(\r
     MatrixClient * client,\r
 bool\r
 MatrixClientGetMegolmOutSession(\r
     MatrixClient * client,\r
@@ -715,14 +1448,25 @@ MatrixClientGetMegolmOutSession(
         }\r
     }\r
 \r
         }\r
     }\r
 \r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientNewMegolmOutSession(\r
+    MatrixClient * client,\r
+    const char * roomId,\r
+    MatrixMegolmOutSession ** outSession)\r
+{\r
     if (client->numMegolmOutSessions < NUM_MEGOLM_SESSIONS)\r
     {\r
     if (client->numMegolmOutSessions < NUM_MEGOLM_SESSIONS)\r
     {\r
-        MatrixMegolmOutSessionInit(\r
-            &client->megolmOutSessions[client->numMegolmOutSessions],\r
+        MatrixMegolmOutSession * result =\r
+            &client->megolmOutSessions[client->numMegolmOutSessions];\r
+        \r
+        MatrixMegolmOutSessionInit(result,\r
             roomId);\r
 \r
             roomId);\r
 \r
-        *outSession = &client->megolmOutSessions[client->numMegolmOutSessions];\r
-        \r
+        *outSession = result;\r
+\r
         client->numMegolmOutSessions++;\r
 \r
         return true;\r
         client->numMegolmOutSessions++;\r
 \r
         return true;\r
@@ -731,6 +1475,95 @@ MatrixClientGetMegolmOutSession(
     return false;\r
 }\r
 \r
     return false;\r
 }\r
 \r
+bool\r
+MatrixClientGetMegolmInSession(\r
+    MatrixClient * client,\r
+    const char * roomId, int roomIdLen,\r
+    const char * sessionId, int sessionIdLen,\r
+    MatrixMegolmInSession ** outSession)\r
+{\r
+    for (int i = 0; i < client->numMegolmInSessions; i++)\r
+    {\r
+        if (strncmp(client->megolmInSessions[i].roomId, roomId, roomIdLen) == 0 &&\r
+            strncmp(client->megolmInSessions[i].id, sessionId, sessionIdLen) == 0)\r
+        {\r
+            *outSession = &client->megolmInSessions[i];\r
+            return true;\r
+        }\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientNewMegolmInSession(\r
+    MatrixClient * client,\r
+    const char * roomId,\r
+    const char * sessionId,\r
+    const char * sessionKey,\r
+    MatrixMegolmInSession ** outSession)\r
+{\r
+    if (client->numMegolmInSessions < NUM_MEGOLM_SESSIONS)\r
+    {\r
+        MatrixMegolmInSession * result =\r
+            &client->megolmInSessions[client->numMegolmInSessions];\r
+        \r
+        MatrixMegolmInSessionInit(result,\r
+            roomId,\r
+            sessionId,\r
+            sessionKey, strlen(sessionKey));\r
+        \r
+        *outSession = result;\r
+\r
+        client->numMegolmInSessions++;\r
+\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientRequestMegolmInSession(\r
+    MatrixClient * client,\r
+    const char * roomId,\r
+    const char * sessionId,\r
+    const char * senderKey,\r
+    const char * userId,\r
+    const char * deviceId)\r
+{\r
+    // TODO: cancel requests\r
+    MatrixClientSendDummy(client, userId, deviceId);\r
+\r
+    STATIC char event[ROOMKEY_REQUEST_SIZE];\r
+    snprintf(event, ROOMKEY_REQUEST_SIZE,\r
+        "{"\r
+            "\"action\":\"request\","\r
+            "\"body\":{"\r
+                "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
+                "\"room_id\":\"%s\","\r
+                "\"sender_key\":\"%s\","\r
+                "\"session_id\":\"%s\""\r
+            "},"\r
+            "\"request_id\":\"%lld\","\r
+            "\"requesting_device_id\":\"%s\""\r
+        "}",\r
+        roomId,\r
+        senderKey,\r
+        sessionId,\r
+        time(NULL),\r
+        client->deviceId);\r
+\r
+    \r
+    MatrixClientSendToDevice(client,\r
+        userId,\r
+        deviceId,\r
+        event,\r
+        "m.room_key_request");\r
+\r
+    return true;\r
+}\r
+\r
 bool\r
 MatrixClientGetOlmSession(\r
     MatrixClient * client,\r
 bool\r
 MatrixClientGetOlmSession(\r
     MatrixClient * client,\r
@@ -738,6 +1571,8 @@ MatrixClientGetOlmSession(
     const char * deviceId,\r
     MatrixOlmSession ** outSession)\r
 {\r
     const char * deviceId,\r
     MatrixOlmSession ** outSession)\r
 {\r
+    (void)userId; //unused for now\r
+\r
     for (int i = 0; i < client->numOlmSessions; i++)\r
     {\r
         if (strcmp(client->olmSessions[i].deviceId, deviceId) == 0)\r
     for (int i = 0; i < client->numOlmSessions; i++)\r
     {\r
         if (strcmp(client->olmSessions[i].deviceId, deviceId) == 0)\r
@@ -747,10 +1582,54 @@ MatrixClientGetOlmSession(
         }\r
     }\r
 \r
         }\r
     }\r
 \r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientNewOlmSessionIn(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    const char * encrypted,\r
+    MatrixOlmSession ** outSession)\r
+{\r
+    (void)userId; //unused for now\r
+    \r
+    if (client->numOlmSessions < NUM_OLM_SESSIONS)\r
+    {\r
+        STATIC char deviceKey[DEVICE_KEY_SIZE];\r
+        MatrixClientRequestDeviceKey(client,\r
+            deviceId,\r
+            deviceKey, DEVICE_KEY_SIZE);\r
+\r
+        MatrixOlmSessionFrom(\r
+            &client->olmSessions[client->numOlmSessions],\r
+            client->olmAccount.account,\r
+            deviceId,\r
+            deviceKey,\r
+            encrypted);\r
+\r
+        *outSession = &client->olmSessions[client->numOlmSessions];\r
+        \r
+        client->numOlmSessions++;\r
+\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientNewOlmSessionOut(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    MatrixOlmSession ** outSession)\r
+{\r
     if (client->numOlmSessions < NUM_OLM_SESSIONS)\r
     {\r
     if (client->numOlmSessions < NUM_OLM_SESSIONS)\r
     {\r
-        static char deviceKey[DEVICE_KEY_SIZE];\r
-        MatrixClientGetDeviceKey(client,\r
+        STATIC char deviceKey[DEVICE_KEY_SIZE];\r
+        MatrixClientRequestDeviceKey(client,\r
             deviceId,\r
             deviceKey, DEVICE_KEY_SIZE);\r
 \r
             deviceId,\r
             deviceKey, DEVICE_KEY_SIZE);\r
 \r
@@ -786,15 +1665,14 @@ MatrixClientSendToDevice(
     const char * message,\r
     const char * msgType)\r
 {\r
     const char * message,\r
     const char * msgType)\r
 {\r
-    static char requestUrl[MAX_URL_LEN];\r
+    STATIC char requestUrl[MAX_URL_LEN];\r
     sprintf(requestUrl,\r
         TODEVICE_URL, msgType, (int)time(NULL));\r
 \r
     sprintf(requestUrl,\r
         TODEVICE_URL, msgType, (int)time(NULL));\r
 \r
-    static char eventBuffer[TODEVICE_EVENT_SIZE];\r
-    snprintf(eventBuffer, TODEVICE_EVENT_SIZE,\r
+    snprintf(g_TodeviceEventBuffer, TODEVICE_EVENT_SIZE,\r
         "{"\r
         "{"\r
-            "\"messages\": {"\r
-                "\"%s\": {"\r
+            "\"messages\":{"\r
+                "\"%s\":{"\r
                     "\"%s\":%s"\r
                 "}"\r
             "}"\r
                     "\"%s\":%s"\r
                 "}"\r
             "}"\r
@@ -803,14 +1681,16 @@ MatrixClientSendToDevice(
         deviceId,\r
         message);\r
 \r
         deviceId,\r
         message);\r
 \r
-    static char responseBuffer[ROOMEVENT_RESPONSE_SIZE];\r
+    STATIC char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
     bool result =\r
     bool result =\r
-        MatrixHttpPut(client,\r
+        MatrixHttpPut(client->hc,\r
             requestUrl,\r
             requestUrl,\r
-            eventBuffer,\r
-            responseBuffer, ROOMEVENT_RESPONSE_SIZE,\r
+            g_TodeviceEventBuffer,\r
+            responseBuffer, ROOM_SEND_RESPONSE_SIZE,\r
             true);\r
     \r
             true);\r
     \r
+    printf("%s\n", responseBuffer);\r
+    \r
     return result;\r
 }\r
 \r
     return result;\r
 }\r
 \r
@@ -824,41 +1704,47 @@ MatrixClientSendToDeviceEncrypted(
 {\r
     // get olm session\r
     MatrixOlmSession * olmSession;\r
 {\r
     // get olm session\r
     MatrixOlmSession * olmSession;\r
-    MatrixClientGetOlmSession(client, userId, deviceId, &olmSession);\r
+    if (! MatrixClientGetOlmSession(client, userId, deviceId, &olmSession))\r
+        MatrixClientNewOlmSessionOut(client, userId, deviceId, &olmSession);\r
 \r
     // create event json\r
 \r
     // create event json\r
-    char deviceKey[DEVICE_KEY_SIZE];\r
-    MatrixClientGetDeviceKey(client, deviceId, deviceKey, DEVICE_KEY_SIZE);\r
+    char targetDeviceKey[DEVICE_KEY_SIZE];\r
+    MatrixClientRequestDeviceKey(client, deviceId, targetDeviceKey, DEVICE_KEY_SIZE);\r
+    char targetSigningKey[SIGNING_KEY_SIZE];\r
+    MatrixClientRequestSigningKey(client, deviceId, targetSigningKey, SIGNING_KEY_SIZE);\r
     \r
     \r
-    static char eventBuffer[TODEVICE_EVENT_SIZE];\r
-    sprintf(eventBuffer,\r
+    char thisSigningKey[DEVICE_KEY_SIZE];\r
+    MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE);\r
+\r
+    snprintf(g_TodeviceEventBuffer, TODEVICE_EVENT_SIZE,\r
         "{"\r
         "{"\r
-        "\"type\": \"%s\","\r
-        "\"content\": \"%s\","\r
-        "\"sender\": \"%s\","\r
-        "\"recipient\": \"%s\","\r
-        "\"recipient_keys\": {"\r
-          "\"ed25519\": \"%s\""\r
+        "\"type\":\"%s\","\r
+        "\"content\":%s,"\r
+        "\"sender\":\"%s\","\r
+        "\"recipient\":\"%s\","\r
+        "\"recipient_keys\":{"\r
+        "\"ed25519\":\"%s\""\r
         "},"\r
         "},"\r
-        "\"keys\": {"\r
-          "\"ed25519\": \"%s\""\r
+        "\"keys\":{"\r
+        "\"ed25519\":\"%s\""\r
         "}"\r
         "}",\r
         msgType,\r
         message,\r
         client->userId,\r
         userId, // recipient user id\r
         "}"\r
         "}",\r
         msgType,\r
         message,\r
         client->userId,\r
         userId, // recipient user id\r
-        deviceKey, // recipient device key\r
-        client->deviceKey);\r
+        targetSigningKey, // recipient device key\r
+        thisSigningKey);\r
 \r
     // encrypt\r
 \r
     // encrypt\r
-    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\r
     MatrixOlmSessionEncrypt(olmSession,\r
     MatrixOlmSessionEncrypt(olmSession,\r
-        eventBuffer,\r
-        encryptedBuffer, ENCRYPTED_REQUEST_SIZE);\r
+        g_TodeviceEventBuffer,\r
+        g_EncryptedRequestBuffer, ENCRYPTED_REQUEST_SIZE);\r
+\r
+    char thisDeviceKey[DEVICE_KEY_SIZE];\r
+    MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE);\r
 \r
 \r
-    static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
-    sprintf(encryptedEventBuffer,\r
+    snprintf(g_EncryptedEventBuffer, ENCRYPTED_EVENT_SIZE,\r
         "{"\r
         "\"algorithm\":\"m.olm.v1.curve25519-aes-sha2\","\r
         "\"ciphertext\":{"\r
         "{"\r
         "\"algorithm\":\"m.olm.v1.curve25519-aes-sha2\","\r
         "\"ciphertext\":{"\r
@@ -870,27 +1756,51 @@ MatrixClientSendToDeviceEncrypted(
         "\"device_id\":\"%s\","\r
         "\"sender_key\":\"%s\""\r
         "}",\r
         "\"device_id\":\"%s\","\r
         "\"sender_key\":\"%s\""\r
         "}",\r
-        deviceKey,\r
-        encryptedBuffer,\r
-        0, //olmSession->type,\r
+        targetDeviceKey,\r
+        // olm_encrypt_message_length(olmSession->session, strlen(g_TodeviceEventBuffer)), g_EncryptedRequestBuffer,\r
+        g_EncryptedRequestBuffer,\r
+        olm_session_has_received_message(olmSession->session),\r
         client->deviceId,\r
         client->deviceId,\r
-        client->deviceKey);\r
+        thisDeviceKey);\r
 \r
     // send\r
     return MatrixClientSendToDevice(\r
         client,\r
         userId,\r
         deviceId,\r
 \r
     // send\r
     return MatrixClientSendToDevice(\r
         client,\r
         userId,\r
         deviceId,\r
-        encryptedEventBuffer,\r
+        g_EncryptedEventBuffer,\r
         "m.room.encrypted");\r
 }\r
 \r
         "m.room.encrypted");\r
 }\r
 \r
+bool\r
+MatrixClientSendDummy(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId)\r
+{\r
+    return MatrixClientSendToDeviceEncrypted(\r
+        client,\r
+        userId,\r
+        deviceId,\r
+        "{}",\r
+        "m.dummy");\r
+}\r
+\r
 bool\r
 MatrixClientFindDevice(\r
     MatrixClient * client,\r
     const char * deviceId,\r
     MatrixDevice ** outDevice)\r
 {\r
 bool\r
 MatrixClientFindDevice(\r
     MatrixClient * client,\r
     const char * deviceId,\r
     MatrixDevice ** outDevice)\r
 {\r
+    for (int i = 0; i < client->numDevices; i++)\r
+    {\r
+        if (strcmp(client->devices[i].deviceId, deviceId) == 0)\r
+        {\r
+            *outDevice = &client->devices[i];\r
+            return true;\r
+        }\r
+    }\r
+\r
     MatrixClientRequestDeviceKeys(client);\r
 \r
     for (int i = 0; i < client->numDevices; i++)\r
     MatrixClientRequestDeviceKeys(client);\r
 \r
     for (int i = 0; i < client->numDevices; i++)\r
@@ -907,7 +1817,7 @@ MatrixClientFindDevice(
 }\r
 \r
 bool\r
 }\r
 \r
 bool\r
-MatrixClientGetDeviceKey(\r
+MatrixClientRequestDeviceKey(\r
     MatrixClient * client,\r
     const char * deviceId,\r
     char * outDeviceKey, int outDeviceKeyCap)\r
     MatrixClient * client,\r
     const char * deviceId,\r
     char * outDeviceKey, int outDeviceKeyCap)\r
@@ -931,21 +1841,71 @@ MatrixClientGetDeviceKey(
     return false;\r
 }\r
 \r
     return false;\r
 }\r
 \r
+bool\r
+MatrixClientRequestSigningKey(\r
+    MatrixClient * client,\r
+    const char * deviceId,\r
+    char * outSigningKey, int outSigningKeyCap)\r
+{\r
+    MatrixDevice * device;\r
+    \r
+    if (MatrixClientFindDevice(client, deviceId, &device))\r
+    {\r
+        strncpy(outSigningKey, device->signingKey, outSigningKeyCap);\r
+        return true;\r
+    }\r
+\r
+    MatrixClientRequestDeviceKeys(client);\r
+    \r
+    if (MatrixClientFindDevice(client, deviceId, &device))\r
+    {\r
+        strncpy(outSigningKey, device->signingKey, outSigningKeyCap);\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientRequestMasterKey(\r
+    MatrixClient * client,\r
+    char * outMasterKey, int outMasterKeyCap)\r
+{\r
+    if (strlen(client->masterKey) > 0) {\r
+        strncpy(outMasterKey, outMasterKeyCap, client->masterKey);\r
+        return true;\r
+    }\r
+\r
+    MatrixClientRequestDeviceKeys(client);\r
+    \r
+    if (strlen(client->masterKey) > 0) {\r
+        strncpy(outMasterKey, outMasterKeyCap, client->masterKey);\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
 // https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3keysquery\r
 bool\r
 MatrixClientRequestDeviceKeys(\r
     MatrixClient * client)\r
 {\r
 // https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3keysquery\r
 bool\r
 MatrixClientRequestDeviceKeys(\r
     MatrixClient * client)\r
 {\r
-    static char userIdEscaped[USER_ID_SIZE];\r
+    if (client->numDevices >= NUM_DEVICES) {\r
+        printf("Maximum number of devices reached\n");\r
+        return false;\r
+    }\r
+\r
+    STATIC char userIdEscaped[USER_ID_SIZE];\r
     JsonEscape(client->userId, strlen(client->userId),\r
         userIdEscaped, USER_ID_SIZE);\r
 \r
     JsonEscape(client->userId, strlen(client->userId),\r
         userIdEscaped, USER_ID_SIZE);\r
 \r
-    static char request[KEYS_QUERY_REQUEST_SIZE];\r
+    STATIC char request[KEYS_QUERY_REQUEST_SIZE];\r
     snprintf(request, KEYS_QUERY_REQUEST_SIZE,\r
         "{\"device_keys\":{\"%s\":[]}}", client->userId);\r
 \r
     snprintf(request, KEYS_QUERY_REQUEST_SIZE,\r
         "{\"device_keys\":{\"%s\":[]}}", client->userId);\r
 \r
-    static char responseBuffer[KEYS_QUERY_RESPONSE_SIZE];\r
-    bool requestResult = MatrixHttpPost(client,\r
+    STATIC char responseBuffer[KEYS_QUERY_RESPONSE_SIZE];\r
+    bool requestResult = MatrixHttpPost(client->hc,\r
         KEYS_QUERY_URL,\r
         request,\r
         responseBuffer, KEYS_QUERY_RESPONSE_SIZE,\r
         KEYS_QUERY_URL,\r
         request,\r
         responseBuffer, KEYS_QUERY_RESPONSE_SIZE,\r
@@ -955,18 +1915,32 @@ MatrixClientRequestDeviceKeys(
         return false;\r
 \r
     // query for retrieving device keys for user id\r
         return false;\r
 \r
     // query for retrieving device keys for user id\r
-    static char query[JSON_QUERY_SIZE];\r
-    snprintf(query, JSON_QUERY_SIZE,\r
-        "$.device_keys.%s", userIdEscaped);\r
-    \r
+    STATIC char query[JSON_QUERY_SIZE];\r
     const char * s;\r
     int slen;\r
     const char * s;\r
     int slen;\r
+\r
+    snprintf(query, JSON_QUERY_SIZE,\r
+        "$.master_keys.%s.keys", userIdEscaped);\r
     mjson_find(responseBuffer, strlen(responseBuffer),\r
         query, &s, &slen);\r
     mjson_find(responseBuffer, strlen(responseBuffer),\r
         query, &s, &slen);\r
+    \r
+    int koff, klen, voff, vlen, vtype, off = 0;\r
+    for (off = 0; (off = mjson_next(s, slen, off, &koff, &klen,\r
+                                    &voff, &vlen, &vtype)) != 0; ) {\r
+        snprintf(client->masterKey, MASTER_KEY_SIZE,\r
+            "%.*s", vlen-2, s+voff+1);\r
+\r
+        printf("found master key: %s\n", client->masterKey);\r
+    }\r
 \r
 \r
+    snprintf(query, JSON_QUERY_SIZE,\r
+        "$.device_keys.%s", userIdEscaped);\r
+    \r
+    mjson_find(responseBuffer, strlen(responseBuffer),\r
+        query, &s, &slen);\r
+    \r
     // loop over keys\r
     \r
     // loop over keys\r
     \r
-    int koff, klen, voff, vlen, vtype, off = 0;\r
     for (off = 0; (off = mjson_next(s, slen, off, &koff, &klen,\r
                                     &voff, &vlen, &vtype)) != 0; ) {\r
         const char * key = s + koff;\r
     for (off = 0; (off = mjson_next(s, slen, off, &koff, &klen,\r
                                     &voff, &vlen, &vtype)) != 0; ) {\r
         const char * key = s + koff;\r
@@ -978,17 +1952,32 @@ MatrixClientRequestDeviceKeys(
             "%.*s", klen-2, key+1);\r
 \r
         // look for device key in value\r
             "%.*s", klen-2, key+1);\r
 \r
         // look for device key in value\r
-        static char deviceKeyQuery[JSON_QUERY_SIZE];\r
+        STATIC char deviceKeyQuery[JSON_QUERY_SIZE];\r
         snprintf(deviceKeyQuery, JSON_QUERY_SIZE,\r
             "$.keys.curve25519:%s", d.deviceId);\r
         mjson_get_string(val, vlen,\r
             deviceKeyQuery, d.deviceKey, DEVICE_KEY_SIZE);\r
 \r
         snprintf(deviceKeyQuery, JSON_QUERY_SIZE,\r
             "$.keys.curve25519:%s", d.deviceId);\r
         mjson_get_string(val, vlen,\r
             deviceKeyQuery, d.deviceKey, DEVICE_KEY_SIZE);\r
 \r
+        // look for signing key in value\r
+        STATIC char signingKeyQuery[JSON_QUERY_SIZE];\r
+        snprintf(signingKeyQuery, JSON_QUERY_SIZE,\r
+            "$.keys.ed25519:%s", d.deviceId);\r
+        mjson_get_string(val, vlen,\r
+            signingKeyQuery, d.signingKey, SIGNING_KEY_SIZE);\r
+\r
         // add device\r
         if (client->numDevices < NUM_DEVICES)\r
         {\r
         // add device\r
         if (client->numDevices < NUM_DEVICES)\r
         {\r
-            client->devices[client->numDevices] = d;\r
-            client->numDevices++;\r
+            bool foundDevice = false;\r
+            for (int i = 0; i < client->numDevices; i++)\r
+                if (strcmp(client->devices[i].deviceId, d.deviceId) == 0)\r
+                    foundDevice = true;\r
+\r
+            if (! foundDevice) {\r
+                printf("new device: %s %s %s\n", d.deviceId, d.deviceKey, d.signingKey);\r
+                client->devices[client->numDevices] = d;\r
+                client->numDevices++;\r
+            }\r
         }\r
         else\r
         {\r
         }\r
         else\r
         {\r
@@ -998,3 +1987,17 @@ MatrixClientRequestDeviceKeys(
 \r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
+\r
+bool\r
+MatrixClientDeleteDevice(\r
+    MatrixClient * client)\r
+{\r
+    STATIC char deleteRequest[1024];\r
+    snprintf(deleteRequest, 1024,\r
+        "{\"devices\":[\"%s\"]}",\r
+        client->deviceId);\r
+    STATIC char deleteResponse[1024];\r
+    bool res = MatrixHttpPost(client->hc, "/_matrix/client/v3/delete_devices",\r
+        deleteRequest, deleteResponse, 1024, true);\r
+    return res;\r
+}\r