]> gitweb.ps.run Git - matrix_esp_thesis/blobdiff - src/matrix.c
HTTP layer for ESP32, make static specifier in matrix.c optional by defining it as...
[matrix_esp_thesis] / src / matrix.c
index 18b700a2e412b1d3699b1781bb1a9cb40e7d0930..ef094b8fad63800f0c425f7b3517fd6072bef750 100644 (file)
@@ -4,6 +4,11 @@
 #include <stdio.h>\r
 #include <mjson.h>\r
 \r
+#ifdef ESP_PLATFORM\r
+#include <esp_random.h>\r
+#endif\r
+\r
+#define STATIC\r
 \r
 #define LOGIN_REQUEST_SIZE 1024\r
 #define LOGIN_RESPONSE_SIZE 1024\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
+#define JSON_QUERY_SIZE 128\r
+#define JSON_MAX_INDICES 100\r
+#define JSON_MAX_ENTRY_SIZE 1024\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
-    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
+\r
+    #endif\r
 }\r
 \r
 bool\r
@@ -78,12 +99,75 @@ JsonEscape(
     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
-    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
@@ -91,10 +175,10 @@ bool JsonSign(
     \r
     int signatureLen = res;\r
     \r
-    static char thisSigningKey[SIGNING_KEY_SIZE];\r
+    STATIC char thisSigningKey[SIGNING_KEY_SIZE];\r
     MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, SIGNING_KEY_SIZE);\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
@@ -126,7 +210,7 @@ MatrixOlmAccountInit(
 {\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
@@ -159,7 +243,7 @@ MatrixOlmAccountGetDeviceKey(
     MatrixOlmAccount * account,\r
     char * key, int keyCap)\r
 {\r
-    static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE];\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
@@ -174,7 +258,7 @@ MatrixOlmAccountGetSigningKey(
     MatrixOlmAccount * account,\r
     char * key, int keyCap)\r
 {\r
-    static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE];\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
@@ -184,7 +268,35 @@ MatrixOlmAccountGetSigningKey(
     return true;\r
 }\r
 \r
-// TODO:in/outbound sessions\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
@@ -200,7 +312,7 @@ MatrixOlmSessionTo(
     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
@@ -214,7 +326,7 @@ MatrixOlmSessionTo(
         printf("error olm:%s\n", olm_session_last_error(session->session));\r
     }\r
 \r
-    return session->session != NULL;\r
+    return res != olm_error();\r
 }\r
 \r
 bool\r
@@ -249,7 +361,7 @@ MatrixOlmSessionEncrypt(
     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
     size_t res = olm_encrypt(session->session,\r
@@ -267,7 +379,7 @@ MatrixOlmSessionDecrypt(
     char * encrypted,\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
     size_t res =\r
@@ -277,11 +389,68 @@ MatrixOlmSessionDecrypt(
             outBuffer, outBufferCap);\r
     \r
     if (res != olm_error() && res < outBufferCap)\r
-        outBuffer[outBufferCap] = '\0';\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
@@ -290,7 +459,7 @@ MatrixMegolmOutSessionInit(
 {\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
     strncpy(session->roomId, roomId, ROOM_ID_SIZE);\r
@@ -397,13 +566,10 @@ MatrixMegolmOutSessionLoad(
 \r
 bool\r
 MatrixClientInit(\r
-    MatrixClient * client,\r
-    const char * server)\r
+    MatrixClient * client)\r
 {\r
     memset(client, 0, sizeof(MatrixClient));\r
 \r
-    strcpy(client->server, server);\r
-\r
     // init olm account\r
     MatrixOlmAccountInit(&client->olmAccount);\r
 \r
@@ -427,7 +593,6 @@ MatrixClientSave(
     fwrite(thisDeviceKey, 1, DEVICE_KEY_SIZE, f);\r
     fwrite(thisSigningKey, 1, DEVICE_KEY_SIZE, f);\r
     fwrite(client->userId, 1, USER_ID_SIZE, f);\r
-    fwrite(client->server, 1, SERVER_SIZE, f);\r
     fwrite(client->accessToken, 1, ACCESS_TOKEN_SIZE, f);\r
     fwrite(client->deviceId, 1, DEVICE_ID_SIZE, f);\r
     fwrite(client->expireMs, 1, EXPIRE_MS_SIZE, f);\r
@@ -460,7 +625,6 @@ MatrixClientLoad(
     fread(thisDeviceKey, 1, DEVICE_KEY_SIZE, f);\r
     fread(thisSigningKey, 1, DEVICE_KEY_SIZE, f);\r
     fread(client->userId, 1, USER_ID_SIZE, f);\r
-    fread(client->server, 1, SERVER_SIZE, f);\r
     fread(client->accessToken, 1, ACCESS_TOKEN_SIZE, f);\r
     fread(client->deviceId, 1, DEVICE_ID_SIZE, f);\r
     fread(client->expireMs, 1, EXPIRE_MS_SIZE, f);\r
@@ -517,7 +681,7 @@ MatrixClientGenerateOnetimeKeys(
     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
@@ -532,12 +696,12 @@ bool
 MatrixClientUploadOnetimeKeys(\r
     MatrixClient * client)\r
 {\r
-    static char requestBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
+    STATIC char requestBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
 \r
     mjson_snprintf(requestBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
         "{");\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
@@ -547,14 +711,14 @@ 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
-        static char keyJson[JSON_ONETIME_KEY_SIZE];\r
+        STATIC char keyJson[JSON_ONETIME_KEY_SIZE];\r
         \r
         int keyJsonLen =\r
             snprintf(keyJson, JSON_ONETIME_KEY_SIZE,\r
                 "{\"key\":\"%.*s\"}",\r
                 vlen-2, keys + voff+1);\r
 \r
-        static char keyJsonSigned[JSON_ONETIME_KEY_SIGNED_SIZE];\r
+        STATIC char keyJsonSigned[JSON_ONETIME_KEY_SIGNED_SIZE];\r
 \r
         JsonSign(client,\r
             keyJson, keyJsonLen,\r
@@ -572,27 +736,25 @@ MatrixClientUploadOnetimeKeys(
     mjson_snprintf(requestBuffer+strlen(requestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer),\r
         "}");\r
         \r
-    // static char onetimeKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
+    // STATIC char onetimeKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
     // JsonSign(client,\r
     //     requestBuffer, strlen(requestBuffer),\r
     //     onetimeKeysSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE);\r
         \r
-    // static char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
+    // STATIC char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
     // snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE,\r
     // "{\"one_time_keys\":%s}", onetimeKeysSignedBuffer);\r
-    static char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
+    STATIC char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
     snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE,\r
     "{\"one_time_keys\":%s}", requestBuffer);\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
         finalEvent,\r
         responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE,\r
         true);\r
 \r
-    printf("%s\n", responseBuffer);\r
-\r
     return true;\r
 }\r
 \r
@@ -606,7 +768,7 @@ MatrixClientUploadDeviceKey(
     char thisSigningKey[DEVICE_KEY_SIZE];\r
     MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE);\r
 \r
-    static char deviceKeysBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
+    STATIC char deviceKeysBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
 \r
     int deviceKeysBufferLen =\r
         mjson_snprintf(deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
@@ -624,23 +786,21 @@ MatrixClientUploadDeviceKey(
             client->deviceId, thisSigningKey,\r
             client->userId);\r
 \r
-    static char deviceKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
+    STATIC char deviceKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
     JsonSign(client,\r
         deviceKeysBuffer, deviceKeysBufferLen,\r
         deviceKeysSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE);\r
     \r
-    static char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
-    snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE,\r
+    STATIC char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE+30];\r
+    snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE+30,\r
     "{\"device_keys\":%s}", deviceKeysSignedBuffer);\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
         finalEvent,\r
         responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE,\r
         true);\r
-        \r
-    printf("%s\n", responseBuffer);\r
 \r
     return true;\r
 }\r
@@ -653,7 +813,7 @@ MatrixClientClaimOnetimeKey(
     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
       "\"one_time_keys\":{"\r
@@ -666,18 +826,18 @@ MatrixClientClaimOnetimeKey(
     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
-    char userIdEscaped[USER_ID_SIZE];\r
+    STATIC char userIdEscaped[USER_ID_SIZE];\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
@@ -709,7 +869,7 @@ MatrixClientLoginPassword(
     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
@@ -725,9 +885,9 @@ MatrixClientLoginPassword(
         password,\r
         displayName);\r
     \r
-    static char responseBuffer[LOGIN_RESPONSE_SIZE];\r
+    STATIC char responseBuffer[LOGIN_RESPONSE_SIZE];\r
     bool result =\r
-        MatrixHttpPost(client,\r
+        MatrixHttpPost(client->hc,\r
             LOGIN_URL,\r
             requestBuffer,\r
             responseBuffer, LOGIN_RESPONSE_SIZE,\r
@@ -750,6 +910,8 @@ MatrixClientLoginPassword(
     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
@@ -762,13 +924,13 @@ MatrixClientSendEvent(
     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
         ROOM_SEND_URL, roomId, msgType, (int)time(NULL));\r
 \r
-    static char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
+    STATIC char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
     bool result =\r
-        MatrixHttpPut(client,\r
+        MatrixHttpPut(client->hc,\r
             requestUrl,\r
             msgBody,\r
             responseBuffer, ROOM_SEND_RESPONSE_SIZE,\r
@@ -787,7 +949,7 @@ MatrixClientSendEventEncrypted(
     const char * msgBody)\r
 {\r
     // event json\r
-    static char requestBuffer[ROOM_SEND_REQUEST_SIZE];\r
+    STATIC char requestBuffer[ROOM_SEND_REQUEST_SIZE];\r
     sprintf(requestBuffer,\r
         "{"\r
         "\"type\":\"%s\","\r
@@ -800,10 +962,11 @@ MatrixClientSendEventEncrypted(
 \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
-    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\r
+    STATIC char encryptedBuffer[ENCRYPTED_REQUEST_SIZE/10];\r
     MatrixMegolmOutSessionEncrypt(outSession,\r
         requestBuffer,\r
         encryptedBuffer, ENCRYPTED_REQUEST_SIZE);\r
@@ -817,7 +980,7 @@ MatrixClientSendEventEncrypted(
     const char * sessionId = outSession->id;\r
     const char * deviceId = client->deviceId;\r
 \r
-    static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
+    STATIC char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE/10];\r
     sprintf(encryptedEventBuffer,\r
         "{"\r
         "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
@@ -842,11 +1005,35 @@ MatrixClientSendEventEncrypted(
 bool\r
 MatrixClientSync(\r
     MatrixClient * client,\r
-    char * outSyncBuffer, int outSyncCap)\r
+    char * outSyncBuffer, int outSyncCap,\r
+    const char * nextBatch)\r
 {\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",\r
+        SYNC_TIMEOUT,\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
     return\r
-        MatrixHttpGet(client,\r
-            "/_matrix/client/v3/sync",\r
+        MatrixHttpGet(client->hc,\r
+            url,\r
             outSyncBuffer, outSyncCap,\r
             true);\r
 }\r
@@ -859,14 +1046,14 @@ MatrixClientGetRoomEvent(
     const char * eventId,\r
     char * outEvent, int outEventCap)\r
 {\r
-    static char url[MAX_URL_LEN];\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,\r
+        MatrixHttpGet(client->hc,\r
             url,\r
             outEvent, outEventCap,\r
             true);\r
@@ -880,7 +1067,7 @@ MatrixClientShareMegolmOutSession(
     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
@@ -893,16 +1080,6 @@ MatrixClientShareMegolmOutSession(
         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
@@ -944,23 +1121,6 @@ MatrixClientShareMegolmOutSessionTest(
     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
@@ -976,8 +1136,27 @@ MatrixClientGetMegolmOutSession(
         }\r
     }\r
 \r
-    if (MatrixClientInitMegolmOutSession(client, roomId)) {\r
-        *outSession = &client->megolmOutSessions[client->numMegolmOutSessions-1];\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
+        MatrixMegolmOutSession * result =\r
+            &client->megolmOutSessions[client->numMegolmOutSessions];\r
+        \r
+        MatrixMegolmOutSessionInit(result,\r
+            roomId);\r
+\r
+        *outSession = result;\r
+\r
+        client->numMegolmOutSessions++;\r
+\r
         return true;\r
     }\r
 \r
@@ -985,20 +1164,50 @@ MatrixClientGetMegolmOutSession(
 }\r
 \r
 bool\r
-MatrixClientInitMegolmOutSession(\r
+MatrixClientGetMegolmInSession(\r
     MatrixClient * client,\r
-    const char * roomId)\r
+    const char * roomId, int roomIdLen,\r
+    const char * sessionId, int sessionIdLen,\r
+    MatrixMegolmInSession ** outSession)\r
 {\r
-    if (client->numMegolmOutSessions < NUM_MEGOLM_SESSIONS)\r
+    for (int i = 0; i < client->numMegolmInSessions; i++)\r
     {\r
-        MatrixMegolmOutSessionInit(\r
-            &client->megolmOutSessions[client->numMegolmOutSessions],\r
-            roomId);\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
-        client->numMegolmOutSessions++;\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
@@ -1009,13 +1218,12 @@ MatrixClientRequestMegolmInSession(
     const char * sessionId,\r
     const char * senderKey,\r
     const char * userId,\r
-    const char * deviceId,\r
-    MatrixMegolmInSession * outMegolmInSession)\r
+    const char * deviceId)\r
 {\r
     // TODO: cancel requests\r
     MatrixClientSendDummy(client, userId, deviceId);\r
 \r
-    static char event[ROOMKEY_REQUEST_SIZE];\r
+    STATIC char event[ROOMKEY_REQUEST_SIZE];\r
     snprintf(event, ROOMKEY_REQUEST_SIZE,\r
         "{"\r
             "\"action\":\"request\","\r
@@ -1025,7 +1233,7 @@ MatrixClientRequestMegolmInSession(
                 "\"sender_key\":\"%s\","\r
                 "\"session_id\":\"%s\""\r
             "},"\r
-            "\"request_id\":\"%d\","\r
+            "\"request_id\":\"%lld\","\r
             "\"requesting_device_id\":\"%s\""\r
         "}",\r
         roomId,\r
@@ -1045,7 +1253,58 @@ MatrixClientRequestMegolmInSession(
 }\r
 \r
 bool\r
-MatrixClientGetOlmSession(\r
+MatrixClientGetOlmSessionIn(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    MatrixOlmSession ** outSession)\r
+{\r
+    for (int i = 0; i < client->numOlmSessions; i++)\r
+    {\r
+        if (strcmp(client->olmSessions[i].deviceId, deviceId) == 0)\r
+        {\r
+            *outSession = &client->olmSessions[i];\r
+            return true;\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
+    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
+MatrixClientGetOlmSessionOut(\r
     MatrixClient * client,\r
     const char * userId,\r
     const char * deviceId,\r
@@ -1060,9 +1319,19 @@ MatrixClientGetOlmSession(
         }\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
-        static char deviceKey[DEVICE_KEY_SIZE];\r
+        STATIC char deviceKey[DEVICE_KEY_SIZE];\r
         MatrixClientRequestDeviceKey(client,\r
             deviceId,\r
             deviceKey, DEVICE_KEY_SIZE);\r
@@ -1099,11 +1368,11 @@ MatrixClientSendToDevice(
     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
-    static char eventBuffer[TODEVICE_EVENT_SIZE];\r
+    STATIC char eventBuffer[TODEVICE_EVENT_SIZE];\r
     snprintf(eventBuffer, TODEVICE_EVENT_SIZE,\r
         "{"\r
             "\"messages\":{"\r
@@ -1116,9 +1385,9 @@ MatrixClientSendToDevice(
         deviceId,\r
         message);\r
 \r
-    static char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
+    STATIC char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
     bool result =\r
-        MatrixHttpPut(client,\r
+        MatrixHttpPut(client->hc,\r
             requestUrl,\r
             eventBuffer,\r
             responseBuffer, ROOM_SEND_RESPONSE_SIZE,\r
@@ -1139,7 +1408,8 @@ MatrixClientSendToDeviceEncrypted(
 {\r
     // get olm session\r
     MatrixOlmSession * olmSession;\r
-    MatrixClientGetOlmSession(client, userId, deviceId, &olmSession);\r
+    if (! MatrixClientGetOlmSessionOut(client, userId, deviceId, &olmSession))\r
+        MatrixClientNewOlmSessionOut(client, userId, deviceId, &olmSession);\r
 \r
     // create event json\r
     char targetDeviceKey[DEVICE_KEY_SIZE];\r
@@ -1150,7 +1420,7 @@ MatrixClientSendToDeviceEncrypted(
     char thisSigningKey[DEVICE_KEY_SIZE];\r
     MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE);\r
 \r
-    static char eventBuffer[TODEVICE_EVENT_SIZE];\r
+    STATIC char eventBuffer[TODEVICE_EVENT_SIZE];\r
     sprintf(eventBuffer,\r
         "{"\r
         "\"type\":\"%s\","\r
@@ -1170,11 +1440,9 @@ MatrixClientSendToDeviceEncrypted(
         userId, // recipient user id\r
         targetSigningKey, // recipient device key\r
         thisSigningKey);\r
-    \r
-    printf("%s\n", eventBuffer);\r
 \r
     // encrypt\r
-    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\r
+    STATIC char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\r
     MatrixOlmSessionEncrypt(olmSession,\r
         eventBuffer,\r
         encryptedBuffer, ENCRYPTED_REQUEST_SIZE);\r
@@ -1183,7 +1451,7 @@ MatrixClientSendToDeviceEncrypted(
     MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE);\r
 \r
 \r
-    static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
+    STATIC char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
     sprintf(encryptedEventBuffer,\r
         "{"\r
         "\"algorithm\":\"m.olm.v1.curve25519-aes-sha2\","\r
@@ -1301,16 +1569,21 @@ bool
 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
-    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
-    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
@@ -1319,10 +1592,8 @@ MatrixClientRequestDeviceKeys(
     if (! requestResult)\r
         return false;\r
 \r
-    printf("keys:\n%s\n", responseBuffer);\r
-\r
     // query for retrieving device keys for user id\r
-    static char query[JSON_QUERY_SIZE];\r
+    STATIC char query[JSON_QUERY_SIZE];\r
     snprintf(query, JSON_QUERY_SIZE,\r
         "$.device_keys.%s", userIdEscaped);\r
     \r
@@ -1345,14 +1616,14 @@ MatrixClientRequestDeviceKeys(
             "%.*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
         // look for signing key in value\r
-        static char signingKeyQuery[JSON_QUERY_SIZE];\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
@@ -1385,12 +1656,12 @@ bool
 MatrixClientDeleteDevice(\r
     MatrixClient * client)\r
 {\r
-    static char deleteRequest[1024];\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, "/_matrix/client/v3/delete_devices",\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
 }
\ No newline at end of file