]> gitweb.ps.run Git - matrix_esp_thesis/blobdiff - src/matrix.c
update esp examples
[matrix_esp_thesis] / src / matrix.c
index ef094b8fad63800f0c425f7b3517fd6072bef750..8b186caa945e27cf1f18889d8c296d6d9b4b8e95 100644 (file)
@@ -3,19 +3,24 @@
 #include <time.h>\r
 #include <stdio.h>\r
 #include <mjson.h>\r
+#include <olm/sas.h>\r
 \r
 #ifdef ESP_PLATFORM\r
 #include <esp_random.h>\r
 #endif\r
 \r
-#define STATIC\r
+// can be used to disable static allocation\r
+#define STATIC static\r
 \r
+// DEFINES\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,6 +55,8 @@
 #define MAX(a,b) ((a) > (b) ? (a) : (b))\r
 #define MIN(a,b) ((a) < (b) ? (a) : (b))\r
 \r
+// Util\r
+\r
 void\r
 Randomize(\r
     uint8_t * random,\r
@@ -203,7 +213,6 @@ bool JsonSign(
     return true;\r
 }\r
 \r
-\r
 bool\r
 MatrixOlmAccountInit(\r
     MatrixOlmAccount * account)\r
@@ -364,6 +373,7 @@ MatrixOlmSessionEncrypt(
     STATIC uint8_t random[OLM_ENCRYPT_RANDOM_SIZE];\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
@@ -388,7 +398,7 @@ MatrixOlmSessionDecrypt(
             encrypted, strlen(encrypted),\r
             outBuffer, outBufferCap);\r
     \r
-    if (res != olm_error() && res < outBufferCap)\r
+    if (res != olm_error() && (int)res < outBufferCap)\r
         outBuffer[res] = '\0';\r
 \r
     return res != olm_error();\r
@@ -439,14 +449,9 @@ MatrixMegolmInSessionDecrypt(
             (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
@@ -489,6 +494,7 @@ MatrixMegolmOutSessionEncrypt(
     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
@@ -496,73 +502,6 @@ MatrixMegolmOutSessionEncrypt(
     return res != olm_error();\r
 }\r
 \r
-bool\r
-MatrixMegolmOutSessionSave(\r
-    MatrixMegolmOutSession * session,\r
-    const char * filename,\r
-    const char * key)\r
-{\r
-    FILE * f = fopen(filename, "w");\r
-\r
-    size_t roomIdLen = strlen(session->roomId);\r
-    fwrite(&roomIdLen, sizeof(size_t), 1, f);\r
-    fwrite(session->roomId, 1, roomIdLen, f);\r
-\r
-    size_t pickleBufferLen =\r
-        olm_pickle_outbound_group_session_length(\r
-            session->session);\r
-    void * pickleBuffer = malloc(pickleBufferLen);\r
-\r
-    olm_pickle_outbound_group_session(\r
-        session->session,\r
-        key, strlen(key),\r
-        pickleBuffer, pickleBufferLen);\r
-    \r
-    fwrite(&pickleBufferLen, sizeof(size_t), 1, f);\r
-    fwrite(pickleBuffer, 1, pickleBufferLen, f);\r
-    free(pickleBuffer);\r
-\r
-    fclose(f);\r
-\r
-    return true;\r
-}\r
-\r
-bool\r
-MatrixMegolmOutSessionLoad(\r
-    MatrixMegolmOutSession * session,\r
-    const char * filename,\r
-    const char * key)\r
-{\r
-    FILE * f = fopen(filename, "r");\r
-\r
-    size_t roomIdLen;\r
-    fread(&roomIdLen, sizeof(size_t), 1, f);\r
-    fread(session->roomId, 1, roomIdLen, f);\r
-    for (int i = roomIdLen; i < ROOM_ID_SIZE; i++)\r
-        session->roomId[i] = '\0';\r
-\r
-    size_t pickleBufferLen;\r
-    fread(&pickleBufferLen, sizeof(size_t), 1, f);\r
-\r
-    void * pickleBuffer = malloc(pickleBufferLen);\r
-    fread(pickleBuffer, 1, pickleBufferLen, f);\r
-\r
-    olm_unpickle_outbound_group_session(\r
-        session->session,\r
-        key, strlen(key),\r
-        pickleBuffer, pickleBufferLen);\r
-    \r
-    free(pickleBuffer);\r
-\r
-    olm_outbound_group_session_id(session->session, (uint8_t *)session->id, MEGOLM_SESSION_ID_SIZE);\r
-    olm_outbound_group_session_key(session->session, (uint8_t *)session->key, MEGOLM_SESSION_KEY_SIZE);\r
-\r
-    fclose(f);\r
-\r
-    return true;\r
-}\r
-\r
-\r
 \r
 bool\r
 MatrixClientInit(\r
@@ -576,70 +515,6 @@ MatrixClientInit(
     return true;\r
 }\r
 \r
-bool\r
-MatrixClientSave(\r
-    MatrixClient * client,\r
-    const char * filename)\r
-{\r
-    FILE * f = fopen(filename, "w");\r
-    \r
-    \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
-    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->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
-    fwrite(client->refreshToken, 1, REFRESH_TOKEN_SIZE, f);\r
-\r
-    fwrite(&client->numDevices, sizeof(int), 1, f);\r
-    for (int i = 0; i < client->numDevices; i++) {\r
-        fwrite(client->devices[i].deviceId, 1, DEVICE_ID_SIZE, f);\r
-        fwrite(client->devices[i].deviceKey, 1, DEVICE_KEY_SIZE, f);\r
-    }\r
-\r
-    fclose(f);\r
-    return true;\r
-}\r
-\r
-bool\r
-MatrixClientLoad(\r
-    MatrixClient * client,\r
-    const char * filename)\r
-{\r
-    FILE * f = fopen(filename, "r");\r
-    \r
-    \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
-    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->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
-    fread(client->refreshToken, 1, REFRESH_TOKEN_SIZE, f);\r
-\r
-    fread(&client->numDevices, sizeof(int), 1, f);\r
-    for (int i = 0; i < client->numDevices; i++) {\r
-        fread(client->devices[i].deviceId, 1, DEVICE_ID_SIZE, f);\r
-        fread(client->devices[i].deviceKey, 1, DEVICE_KEY_SIZE, f);\r
-    }\r
-\r
-    fclose(f);\r
-    return true;\r
-}\r
-\r
 bool\r
 MatrixClientSetAccessToken(\r
     MatrixClient * client,\r
@@ -691,24 +566,26 @@ MatrixClientGenerateOnetimeKeys(
     return res != olm_error();\r
 }\r
 \r
-// https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysupload\r
+// https://spec.matrix.org/v1.8/client-server-api/#post_matrixclientv3keysupload\r
 bool\r
 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
     olm_account_one_time_keys(client->olmAccount.account,\r
         onetimeKeysBuffer, 1024);\r
 \r
+    // olm_account_one_time_keys returns a json object\r
+    // find curve25519 member\r
     const char *keys;\r
     int keysLen;\r
     mjson_find(onetimeKeysBuffer, strlen(onetimeKeysBuffer), "$.curve25519", &keys, &keysLen);\r
 \r
+    // iterate over onetime keys, create key object\r
+    // sign it and append to request\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
@@ -724,43 +601,35 @@ MatrixClientUploadOnetimeKeys(
             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
+    // delete last ',' since the loop always appends it\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
-    // JsonSign(client,\r
-    //     requestBuffer, strlen(requestBuffer),\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
-    STATIC char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE];\r
-    snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE,\r
-    "{\"one_time_keys\":%s}", requestBuffer);\r
+\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
-        finalEvent,\r
+        g_KeysUploadRequestSignedBuffer,\r
         responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE,\r
         true);\r
 \r
     return true;\r
 }\r
 \r
-// https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysupload\r
+// https://spec.matrix.org/v1.8/client-server-api/#post_matrixclientv3keysupload\r
 bool\r
-MatrixClientUploadDeviceKey(\r
+MatrixClientUploadDeviceKeys(\r
     MatrixClient * client)\r
 {\r
     char thisDeviceKey[DEVICE_KEY_SIZE];\r
@@ -768,10 +637,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
@@ -786,14 +653,13 @@ 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+30];\r
     snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE+30,\r
-    "{\"device_keys\":%s}", deviceKeysSignedBuffer);\r
+    "{\"device_keys\":%s}", g_KeysUploadRequestSignedBuffer);\r
 \r
     STATIC char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE];\r
     MatrixHttpPost(client->hc,\r
@@ -805,7 +671,7 @@ MatrixClientUploadDeviceKey(
     return true;\r
 }\r
 \r
-// https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysclaim\r
+// https://spec.matrix.org/v1.8/client-server-api/#post_matrixclientv3keysclaim\r
 bool\r
 MatrixClientClaimOnetimeKey(\r
     MatrixClient * client,\r
@@ -837,18 +703,24 @@ MatrixClientClaimOnetimeKey(
     JsonEscape(userId, strlen(userId),\r
         userIdEscaped, USER_ID_SIZE);\r
     \r
+    // create the json query according to\r
+    // https://spec.matrix.org/v1.8/client-server-api/#post_matrixclientv3keysclaim\r
     STATIC char query[JSON_QUERY_SIZE];\r
     snprintf(query, JSON_QUERY_SIZE,\r
         "$.one_time_keys.%s.%s",\r
         userIdEscaped,\r
         deviceId);\r
     \r
+    // find the corresponding json object\r
     const char * keyObject;\r
     int keyObjectSize;\r
     mjson_find(responseBuffer, strlen(responseBuffer),\r
         query,\r
         &keyObject, &keyObjectSize);\r
     \r
+    // use mjson_next (which iterates over all key/value pairs) once\r
+    // because we only request one key\r
+    // (see https://github.com/cesanta/mjson#mjson_next for details)\r
     int koff, klen, voff, vlen, vtype;\r
     mjson_next(keyObject, keyObjectSize, 0,\r
         &koff, &klen, &voff, &vlen, &vtype);\r
@@ -856,12 +728,12 @@ MatrixClientClaimOnetimeKey(
     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
-// https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3login\r
+// https://spec.matrix.org/v1.8/client-server-api/#post_matrixclientv3login\r
 bool\r
 MatrixClientLoginPassword(\r
     MatrixClient * client,\r
@@ -898,6 +770,7 @@ MatrixClientLoginPassword(
     \r
     int responseLen = strlen(responseBuffer);\r
 \r
+    // store variables in MatrixClient\r
     mjson_get_string(responseBuffer, responseLen,\r
         "$.access_token",\r
         client->accessToken, ACCESS_TOKEN_SIZE);\r
@@ -916,7 +789,7 @@ MatrixClientLoginPassword(
     return true;\r
 }\r
 \r
-// https://spec.matrix.org/v1.6/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid\r
+// https://spec.matrix.org/v1.8/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid\r
 bool\r
 MatrixClientSendEvent(\r
     MatrixClient * client,\r
@@ -925,7 +798,7 @@ MatrixClientSendEvent(
     const char * msgBody)\r
 {    \r
     STATIC char requestUrl[MAX_URL_LEN];\r
-    sprintf(requestUrl,\r
+    snprintf(requestUrl, MAX_URL_LEN,\r
         ROOM_SEND_URL, roomId, msgType, (int)time(NULL));\r
 \r
     STATIC char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
@@ -939,7 +812,7 @@ MatrixClientSendEvent(
     return result;\r
 }\r
 \r
-// https://spec.matrix.org/v1.6/client-server-api/#mroomencrypted\r
+// https://spec.matrix.org/v1.8/client-server-api/#mroomencrypted\r
 // https://matrix.org/docs/guides/end-to-end-encryption-implementation-guide#sending-an-encrypted-message-event\r
 bool\r
 MatrixClientSendEventEncrypted(\r
@@ -950,7 +823,7 @@ MatrixClientSendEventEncrypted(
 {\r
     // event json\r
     STATIC char requestBuffer[ROOM_SEND_REQUEST_SIZE];\r
-    sprintf(requestBuffer,\r
+    snprintf(requestBuffer, ROOM_SEND_REQUEST_SIZE,\r
         "{"\r
         "\"type\":\"%s\","\r
         "\"content\":%s,"\r
@@ -966,10 +839,9 @@ MatrixClientSendEventEncrypted(
         MatrixClientNewMegolmOutSession(client, roomId, &outSession);\r
         \r
     // encrypt\r
-    STATIC char encryptedBuffer[ENCRYPTED_REQUEST_SIZE/10];\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
@@ -980,8 +852,7 @@ MatrixClientSendEventEncrypted(
     const char * sessionId = outSession->id;\r
     const char * deviceId = client->deviceId;\r
 \r
-    STATIC char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE/10];\r
-    sprintf(encryptedEventBuffer,\r
+    snprintf(g_EncryptedEventBuffer, ENCRYPTED_EVENT_SIZE,\r
         "{"\r
         "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
         "\"ciphertext\":\"%s\","\r
@@ -989,7 +860,7 @@ MatrixClientSendEventEncrypted(
         "\"sender_key\":\"%s\","\r
         "\"session_id\":\"%s\""\r
         "}",\r
-        encryptedBuffer,\r
+        g_EncryptedRequestBuffer,\r
         deviceId,\r
         senderKey,\r
         sessionId);\r
@@ -998,25 +869,477 @@ 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
+// this handles to_device events received from a sync\r
+// mainly for verification (m.key.verification.* events)\r
+void\r
+MatrixClientHandleEvent(\r
+    MatrixClient * client,\r
+    const char * event, int eventLen\r
+) {\r
+    // get the event type\r
+    STATIC char eventType[128];\r
+    memset(eventType, 0, sizeof(eventType));\r
+    mjson_get_string(event, eventLen, "$.type", eventType, 128);\r
+\r
+    // static variables for verification\r
+    // since verification takes multiple requests\r
+    // data is cleared when verification is finished or started\r
+    static char transactionId[64];\r
+    static char verifyFromDeviceId[DEVICE_ID_SIZE];\r
+    static OlmSAS * olmSas = NULL;\r
+\r
+    // initial verification request, reply that we are ready to verify\r
+    if (strcmp(eventType, "m.key.verification.request") == 0) {\r
+        // reset static data\r
+        memset(transactionId, 0, 64);\r
+        memset(verifyFromDeviceId, 0, DEVICE_ID_SIZE);\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
+        // calculate commitment according to \r
+        // https://spec.matrix.org/v1.8/client-server-api/#mkeyverificationaccept\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
+\r
+        const char * keyStartJson;\r
+        int keyStartJsonLen;\r
+        mjson_find(event, eventLen, "$.content", &keyStartJson, &keyStartJsonLen);\r
+        JsonCanonicalize(keyStartJson, keyStartJsonLen, keyStartJsonCanonical, 512);\r
+\r
+        int concatLen =\r
+            snprintf(concat, 512+64, "%.*s%s", (int)olm_sas_pubkey_length(olmSas), publicKey, keyStartJsonCanonical);\r
+\r
+        int commitmentLen =\r
+            olm_sha256(olmUtil, concat, concatLen, commitment, 1024);\r
+        olm_clear_utility(olmUtil);\r
+        free(olmUtil);\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
+    // send our sas key and calculate sas using their received key\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
+        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
+            (int)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
+        // for now just printf SAS numbers\r
+        // https://spec.matrix.org/v1.8/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
+    }\r
+    // calculate MACs for signing key, master key and the key list\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
+        // keys have to be sorted so write keys/key IDs into key1/key2\r
+        // depending on lexicographical order\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
+        // create key list\r
+        snprintf(keyList, 1024,\r
+            "%s,%s", key1Id, key2Id);\r
+        \r
+        // generate MAC info for both keys and key list\r
+        // https://spec.matrix.org/v1.8/client-server-api/#mac-calculation\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
+        // construct message and send\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
+        // send 'done' message\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
+\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
+        // since this only handles to_device messages algorithm should always be olm\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
+            // depending on message type create new incoming\r
+            // (type 0 indicates a new session so we dont check locally)\r
+            if (messageTypeInt == 0) {\r
+                MatrixClientNewOlmSessionIn(client,\r
+                    client->userId,\r
+                    verifyFromDeviceId,\r
+                    g_EncryptedEventBuffer,\r
+                    &olmSession);\r
+            }\r
+            // or new outgoing, checking for known sessions first\r
+            else {\r
+                if (! MatrixClientGetOlmSession(client, client->userId, verifyFromDeviceId, &olmSession))\r
+                {\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
+        // store session information\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
+        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
+        // only room specific message type is encrypted\r
+        // since this is only room messages, algorithm should always be megolm\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("error: megolm session not known\n");\r
+            }\r
+        }\r
+    }\r
+    MatrixClientHandleEvent(client, event, eventLen);\r
+}\r
+\r
+// pass the response from sync to Handle(Room)Event\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
+    // read next_batch\r
+    mjson_get_string(s, slen, "$.next_batch", nextBatch, nextBatchCap);\r
+\r
+    // to_device\r
+    const char * events;\r
+    int eventsLen;\r
+    res =\r
+        mjson_find(s, slen, "$.to_device.events", &events, &eventsLen);\r
+    \r
+    // iterate event and pass to HandleEvent\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
+    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
+        // iterate rooms\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
+                // iterate messages in that room\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
+// https://spec.matrix.org/v1.8/client-server-api/#get_matrixclientv3sync\r
 bool\r
 MatrixClientSync(\r
     MatrixClient * client,\r
     char * outSyncBuffer, int outSyncCap,\r
-    const char * nextBatch)\r
+    char * nextBatch, int nextBatchCap)\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
+        "/_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
+    // URL encode next_batch parameter since it can include ~\r
     for (size_t i = 0; i < strlen(nextBatch); i++) {\r
         char c = nextBatch[i];\r
 \r
@@ -1031,14 +1354,20 @@ MatrixClientSync(
     }\r
     url[index] = '\0';\r
 \r
-    return\r
+    bool result =\r
         MatrixHttpGet(client->hc,\r
             url,\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
+// https://spec.matrix.org/v1.8/client-server-api/#get_matrixclientv3roomsroomideventeventid\r
 bool\r
 MatrixClientGetRoomEvent(\r
     MatrixClient * client,\r
@@ -1068,7 +1397,7 @@ MatrixClientShareMegolmOutSession(
 {\r
     // generate room key event\r
     STATIC char eventBuffer[KEY_SHARE_EVENT_LEN];\r
-    sprintf(eventBuffer,\r
+    snprintf(eventBuffer, KEY_SHARE_EVENT_LEN,\r
         "{"\r
             "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
             "\"room_id\":\"%s\","\r
@@ -1090,37 +1419,6 @@ MatrixClientShareMegolmOutSession(
     return true;\r
 }\r
 \r
-bool\r
-MatrixClientShareMegolmOutSessionTest(\r
-    MatrixClient * client,\r
-    const char * userId,\r
-    const char * deviceId,\r
-    MatrixMegolmOutSession * session)\r
-{\r
-    // generate room key event\r
-    char eventBuffer[KEY_SHARE_EVENT_LEN];\r
-    sprintf(eventBuffer,\r
-        "{"\r
-            "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
-            "\"room_id\":\"%s\","\r
-            "\"session_id\":\"%s\","\r
-            "\"session_key\":\"%s\""\r
-        "}",\r
-        session->roomId,\r
-        session->id,\r
-        session->key\r
-    );\r
-\r
-    // send\r
-    MatrixClientSendToDevice(client,\r
-        userId,\r
-        deviceId,\r
-        eventBuffer,\r
-        "m.room_key");\r
-\r
-    return true;\r
-}\r
-\r
 bool\r
 MatrixClientGetMegolmOutSession(\r
     MatrixClient * client,\r
@@ -1253,12 +1551,14 @@ MatrixClientRequestMegolmInSession(
 }\r
 \r
 bool\r
-MatrixClientGetOlmSessionIn(\r
+MatrixClientGetOlmSession(\r
     MatrixClient * client,\r
     const char * userId,\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
@@ -1279,6 +1579,8 @@ MatrixClientNewOlmSessionIn(
     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
@@ -1303,25 +1605,6 @@ MatrixClientNewOlmSessionIn(
     return false;\r
 }\r
 \r
-bool\r
-MatrixClientGetOlmSessionOut(\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
 MatrixClientNewOlmSessionOut(\r
     MatrixClient * client,\r
@@ -1359,7 +1642,7 @@ MatrixClientNewOlmSessionOut(
     return false;\r
 }\r
 \r
-// https://spec.matrix.org/v1.6/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid\r
+// https://spec.matrix.org/v1.8/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid\r
 bool\r
 MatrixClientSendToDevice(\r
     MatrixClient * client,\r
@@ -1369,11 +1652,10 @@ MatrixClientSendToDevice(
     const char * msgType)\r
 {\r
     STATIC char requestUrl[MAX_URL_LEN];\r
-    sprintf(requestUrl,\r
+    snprintf(requestUrl, MAX_URL_LEN,\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
@@ -1389,12 +1671,10 @@ MatrixClientSendToDevice(
     bool result =\r
         MatrixHttpPut(client->hc,\r
             requestUrl,\r
-            eventBuffer,\r
+            g_TodeviceEventBuffer,\r
             responseBuffer, ROOM_SEND_RESPONSE_SIZE,\r
             true);\r
     \r
-    printf("%s\n", responseBuffer);\r
-    \r
     return result;\r
 }\r
 \r
@@ -1408,7 +1688,7 @@ MatrixClientSendToDeviceEncrypted(
 {\r
     // get olm session\r
     MatrixOlmSession * olmSession;\r
-    if (! MatrixClientGetOlmSessionOut(client, userId, deviceId, &olmSession))\r
+    if (! MatrixClientGetOlmSession(client, userId, deviceId, &olmSession))\r
         MatrixClientNewOlmSessionOut(client, userId, deviceId, &olmSession);\r
 \r
     // create event json\r
@@ -1420,18 +1700,17 @@ 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
         "\"sender\":\"%s\","\r
         "\"recipient\":\"%s\","\r
         "\"recipient_keys\":{"\r
-          "\"ed25519\":\"%s\""\r
+        "\"ed25519\":\"%s\""\r
         "},"\r
         "\"keys\":{"\r
-          "\"ed25519\":\"%s\""\r
+        "\"ed25519\":\"%s\""\r
         "}"\r
         "}",\r
         msgType,\r
@@ -1442,17 +1721,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
@@ -1465,7 +1741,8 @@ MatrixClientSendToDeviceEncrypted(
         "\"sender_key\":\"%s\""\r
         "}",\r
         targetDeviceKey,\r
-        encryptedBuffer,\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
         thisDeviceKey);\r
@@ -1475,7 +1752,7 @@ MatrixClientSendToDeviceEncrypted(
         client,\r
         userId,\r
         deviceId,\r
-        encryptedEventBuffer,\r
+        g_EncryptedEventBuffer,\r
         "m.room.encrypted");\r
 }\r
 \r
@@ -1499,6 +1776,15 @@ MatrixClientFindDevice(
     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
@@ -1564,20 +1850,42 @@ MatrixClientRequestSigningKey(
     return false;\r
 }\r
 \r
-// https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3keysquery\r
+bool\r
+MatrixClientRequestMasterKey(\r
+    MatrixClient * client,\r
+    char * outMasterKey, int outMasterKeyCap)\r
+{\r
+    if (strlen(client->masterKey) > 0) {\r
+        strncpy(outMasterKey, client->masterKey, outMasterKeyCap);\r
+        return true;\r
+    }\r
+\r
+    MatrixClientRequestDeviceKeys(client);\r
+    \r
+    if (strlen(client->masterKey) > 0) {\r
+        strncpy(outMasterKey, client->masterKey, outMasterKeyCap);\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+// https://spec.matrix.org/v1.8/client-server-api/#post_matrixclientv3keysquery\r
 bool\r
 MatrixClientRequestDeviceKeys(\r
     MatrixClient * client)\r
 {\r
     if (client->numDevices >= NUM_DEVICES) {\r
-        printf("Maximum number of devices reached\n");\r
+        printf("error: Maximum number of devices reached\n");\r
         return false;\r
     }\r
 \r
+    // escape userId so we can use it in json queries\r
     STATIC char userIdEscaped[USER_ID_SIZE];\r
     JsonEscape(client->userId, strlen(client->userId),\r
         userIdEscaped, USER_ID_SIZE);\r
 \r
+    // construct and send request\r
     STATIC char request[KEYS_QUERY_REQUEST_SIZE];\r
     snprintf(request, KEYS_QUERY_REQUEST_SIZE,\r
         "{\"device_keys\":{\"%s\":[]}}", client->userId);\r
@@ -1594,17 +1902,31 @@ MatrixClientRequestDeviceKeys(
 \r
     // query for retrieving device keys for user id\r
     STATIC char query[JSON_QUERY_SIZE];\r
+    const char * s;\r
+    int slen;\r
+\r
+    // look for master key\r
+    snprintf(query, JSON_QUERY_SIZE,\r
+        "$.master_keys.%s.keys", userIdEscaped);\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
+\r
+    // iterate over returned devices for that userId\r
     snprintf(query, JSON_QUERY_SIZE,\r
         "$.device_keys.%s", userIdEscaped);\r
     \r
-    const char * s;\r
-    int slen;\r
     mjson_find(responseBuffer, strlen(responseBuffer),\r
         query, &s, &slen);\r
     \r
     // loop over keys\r
-    \r
-    int koff, klen, voff, vlen, vtype, off = 0;\r
+    // creating a new device if possible\r
     for (off = 0; (off = mjson_next(s, slen, off, &koff, &klen,\r
                                     &voff, &vlen, &vtype)) != 0; ) {\r
         const char * key = s + koff;\r
@@ -1638,7 +1960,6 @@ MatrixClientRequestDeviceKeys(
                     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
@@ -1664,4 +1985,4 @@ MatrixClientDeleteDevice(
     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
+}\r