]> gitweb.ps.run Git - matrix_esp_thesis/blobdiff - src/matrix.c
use global static buffers to save memory, get Verify example working on ESP32
[matrix_esp_thesis] / src / matrix.c
index 40c2e5b2b673c4df2328df903bd02078d61498b4..fe8e1a3e241fdabb1b9ac94cc62dbb39e5b897f6 100644 (file)
@@ -4,13 +4,20 @@
 #include <stdio.h>\r
 #include <mjson.h>\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
+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
 #define ROOMKEY_REQUEST_SIZE (1024*4)\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 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
 #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
@@ -47,13 +57,24 @@ Randomize(
     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
@@ -130,7 +151,7 @@ JsonCanonicalize(
         int valLen;\r
         mjson_find(sIn, sInLen, jp, &valPtr, &valLen);\r
         \r
-        static char newEntry[JSON_MAX_ENTRY_SIZE];\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
@@ -151,7 +172,7 @@ bool JsonSign(
     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
@@ -159,10 +180,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
@@ -194,7 +215,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
@@ -227,7 +248,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
@@ -242,7 +263,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
@@ -268,7 +289,7 @@ MatrixOlmSessionFrom(
         olm_session(session->memory);\r
     \r
     char * encryptedCopy = strdup(encrypted);\r
-\r
+    \r
     size_t res =\r
         olm_create_inbound_session_from(session->session, olmAccount,\r
             deviceKey, strlen(deviceKey),\r
@@ -296,7 +317,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
@@ -345,7 +366,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
@@ -363,7 +384,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
@@ -423,7 +444,7 @@ MatrixMegolmInSessionDecrypt(
             (uint8_t *)outDecrypted, outDecryptedCap,\r
             &megolmInMessageIndex);\r
     \r
-    printf("message index: %d\n", megolmInMessageIndex);\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
@@ -443,7 +464,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
@@ -550,13 +571,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
@@ -580,7 +598,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
@@ -613,7 +630,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
@@ -670,7 +686,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
@@ -685,12 +701,10 @@ bool
 MatrixClientUploadOnetimeKeys(\r
     MatrixClient * client)\r
 {\r
-    static char requestBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
-\r
-    mjson_snprintf(requestBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
+    mjson_snprintf(g_KeysUploadRequestBuffer, 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
@@ -700,47 +714,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
-        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
             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
-    if (requestBuffer[strlen(requestBuffer)-1] == ',')\r
-        requestBuffer[strlen(requestBuffer)-1] = '\0';\r
+    if (g_KeysUploadRequestBuffer[strlen(g_KeysUploadRequestBuffer)-1] == ',')\r
+        g_KeysUploadRequestBuffer[strlen(g_KeysUploadRequestBuffer)-1] = '\0';\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
         "}");\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
+    //     g_KeysUploadRequestBuffer, strlen(g_KeysUploadRequestBuffer),\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
-    snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE,\r
-    "{\"one_time_keys\":%s}", requestBuffer);\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,\r
+    STATIC char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE];\r
+    MatrixHttpPost(client->hc,\r
         KEYS_UPLOAD_URL,\r
-        finalEvent,\r
+        g_KeysUploadRequestSignedBuffer,\r
         responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE,\r
         true);\r
 \r
@@ -757,10 +770,8 @@ MatrixClientUploadDeviceKey(
     char thisSigningKey[DEVICE_KEY_SIZE];\r
     MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE);\r
 \r
-    static char deviceKeysBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
-\r
     int deviceKeysBufferLen =\r
-        mjson_snprintf(deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE,\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
@@ -775,17 +786,16 @@ MatrixClientUploadDeviceKey(
             client->deviceId, thisSigningKey,\r
             client->userId);\r
 \r
-    static char deviceKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
     JsonSign(client,\r
-        deviceKeysBuffer, deviceKeysBufferLen,\r
-        deviceKeysSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE);\r
+        g_KeysUploadRequestBuffer, deviceKeysBufferLen,\r
+        g_KeysUploadRequestSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE);\r
     \r
-    static char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
-    snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE,\r
-    "{\"device_keys\":%s}", deviceKeysSignedBuffer);\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
-    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
@@ -802,7 +812,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
@@ -815,18 +825,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
@@ -858,7 +868,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
@@ -874,9 +884,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
@@ -899,6 +909,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
@@ -911,13 +923,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
@@ -936,7 +948,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
@@ -953,10 +965,9 @@ MatrixClientSendEventEncrypted(
         MatrixClientNewMegolmOutSession(client, roomId, &outSession);\r
         \r
     // encrypt\r
-    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\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
@@ -967,8 +978,7 @@ MatrixClientSendEventEncrypted(
     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
@@ -976,7 +986,7 @@ MatrixClientSendEventEncrypted(
         "\"sender_key\":\"%s\","\r
         "\"session_id\":\"%s\""\r
         "}",\r
-        encryptedBuffer,\r
+        g_EncryptedRequestBuffer,\r
         deviceId,\r
         senderKey,\r
         sessionId);\r
@@ -985,7 +995,7 @@ MatrixClientSendEventEncrypted(
     return MatrixClientSendEvent(client,\r
         roomId,\r
         "m.room.encrypted",\r
-        encryptedEventBuffer);\r
+        g_EncryptedEventBuffer);\r
 }\r
 \r
 // https://spec.matrix.org/v1.6/client-server-api/#get_matrixclientv3sync\r
@@ -996,10 +1006,12 @@ MatrixClientSync(
     const char * nextBatch)\r
 {\r
     // filter={\"event_fields\":[\"to_device\"]}\r
-    static char url[MAX_URL_LEN];\r
+    STATIC char url[MAX_URL_LEN];\r
     snprintf(url, MAX_URL_LEN,\r
-        "/_matrix/client/v3/sync?timeout=%d%s",\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
@@ -1019,7 +1031,7 @@ MatrixClientSync(
     url[index] = '\0';\r
 \r
     return\r
-        MatrixHttpGet(client,\r
+        MatrixHttpGet(client->hc,\r
             url,\r
             outSyncBuffer, outSyncCap,\r
             true);\r
@@ -1033,14 +1045,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
@@ -1054,7 +1066,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
@@ -1210,7 +1222,7 @@ MatrixClientRequestMegolmInSession(
     // 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
@@ -1220,7 +1232,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
@@ -1240,11 +1252,10 @@ MatrixClientRequestMegolmInSession(
 }\r
 \r
 bool\r
-MatrixClientGetOlmSessionIn(\r
+MatrixClientGetOlmSession(\r
     MatrixClient * client,\r
     const char * userId,\r
     const char * deviceId,\r
-    const char * encrypted,\r
     MatrixOlmSession ** outSession)\r
 {\r
     for (int i = 0; i < client->numOlmSessions; i++)\r
@@ -1256,9 +1267,20 @@ MatrixClientGetOlmSessionIn(
         }\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
+        STATIC char deviceKey[DEVICE_KEY_SIZE];\r
         MatrixClientRequestDeviceKey(client,\r
             deviceId,\r
             deviceKey, DEVICE_KEY_SIZE);\r
@@ -1281,24 +1303,15 @@ MatrixClientGetOlmSessionIn(
 }\r
 \r
 bool\r
-MatrixClientGetOlmSessionOut(\r
+MatrixClientNewOlmSessionOut(\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
     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
@@ -1335,12 +1348,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
-    snprintf(eventBuffer, TODEVICE_EVENT_SIZE,\r
+    snprintf(g_TodeviceEventBuffer, TODEVICE_EVENT_SIZE,\r
         "{"\r
             "\"messages\":{"\r
                 "\"%s\":{"\r
@@ -1352,11 +1364,11 @@ 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
+            g_TodeviceEventBuffer,\r
             responseBuffer, ROOM_SEND_RESPONSE_SIZE,\r
             true);\r
     \r
@@ -1375,7 +1387,8 @@ MatrixClientSendToDeviceEncrypted(
 {\r
     // get olm session\r
     MatrixOlmSession * olmSession;\r
-    MatrixClientGetOlmSessionOut(client, userId, deviceId, &olmSession);\r
+    if (! MatrixClientGetOlmSession(client, userId, deviceId, &olmSession))\r
+        MatrixClientNewOlmSessionOut(client, userId, deviceId, &olmSession);\r
 \r
     // create event json\r
     char targetDeviceKey[DEVICE_KEY_SIZE];\r
@@ -1386,8 +1399,7 @@ MatrixClientSendToDeviceEncrypted(
     char thisSigningKey[DEVICE_KEY_SIZE];\r
     MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE);\r
 \r
-    static char eventBuffer[TODEVICE_EVENT_SIZE];\r
-    sprintf(eventBuffer,\r
+    snprintf(g_TodeviceEventBuffer, TODEVICE_EVENT_SIZE,\r
         "{"\r
         "\"type\":\"%s\","\r
         "\"content\":%s,"\r
@@ -1408,17 +1420,14 @@ MatrixClientSendToDeviceEncrypted(
         thisSigningKey);\r
 \r
     // encrypt\r
-    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\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
@@ -1431,7 +1440,7 @@ MatrixClientSendToDeviceEncrypted(
         "\"sender_key\":\"%s\""\r
         "}",\r
         targetDeviceKey,\r
-        encryptedBuffer,\r
+        g_EncryptedRequestBuffer,\r
         olm_session_has_received_message(olmSession->session),\r
         client->deviceId,\r
         thisDeviceKey);\r
@@ -1441,7 +1450,7 @@ MatrixClientSendToDeviceEncrypted(
         client,\r
         userId,\r
         deviceId,\r
-        encryptedEventBuffer,\r
+        g_EncryptedEventBuffer,\r
         "m.room.encrypted");\r
 }\r
 \r
@@ -1535,16 +1544,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
@@ -1554,7 +1568,7 @@ MatrixClientRequestDeviceKeys(
         return false;\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
@@ -1577,14 +1591,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
@@ -1617,12 +1631,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