]> gitweb.ps.run Git - matrix_esp_thesis/blobdiff - src/matrix.c
start working on Sync example (reply to to_device messages)
[matrix_esp_thesis] / src / matrix.c
index bc0f1ca704af357798fff98fca2b1722b1d0c736..147d9198730c1221a7b0b6db2f44270afefc28eb 100644 (file)
 #include "matrix.h"\r
 \r
 #include "matrix.h"\r
 \r
-FixedBuffer\r
-FixedBuf(const char * str)\r
-{\r
-    int len = strlen(str);\r
-    FixedBuffer result;\r
-    result.ptr = (char *)str;\r
-    result.size = len;\r
-    result.len = len;\r
-    return result;\r
+#include <time.h>\r
+#include <stdio.h>\r
+#include <mjson.h>\r
+\r
+\r
+#define LOGIN_REQUEST_SIZE 1024\r
+#define LOGIN_RESPONSE_SIZE 1024\r
+#define LOGIN_URL "/_matrix/client/v3/login"\r
+\r
+#define ENCRYPTED_REQUEST_SIZE (1024*5)\r
+#define ENCRYPTED_EVENT_SIZE (1024*10)\r
+#define ROOM_SEND_REQUEST_SIZE 256\r
+#define ROOM_SEND_RESPONSE_SIZE 1024\r
+#define ROOM_SEND_URL "/_matrix/client/v3/rooms/%s/send/%s/%d"\r
+\r
+#define ROOMKEY_REQUEST_SIZE (1024*4)\r
+\r
+#define TODEVICE_EVENT_SIZE (1024*5)\r
+#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
+\r
+#define KEYS_UPLOAD_URL "/_matrix/client/v3/keys/upload"\r
+#define KEYS_UPLOAD_REQUEST_SIZE 1024*4\r
+#define KEYS_UPLOAD_REQUEST_SIGNED_SIZE 2048*4\r
+#define KEYS_UPLOAD_RESPONSE_SIZE 2048\r
+\r
+#define KEYS_CLAIM_URL "/_matrix/client/v3/keys/claim"\r
+#define KEYS_CLAIM_REQUEST_SIZE 1024\r
+#define KEYS_CLAIM_RESPONSE_SIZE 1024\r
+\r
+#define JSON_QUERY_SIZE 128\r
+\r
+\r
+\r
+void\r
+Randomize(\r
+    uint8_t * random,\r
+    int randomLen)\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
+\r
+bool\r
+JsonEscape(\r
+    const char * sIn, int sInLen,\r
+    char * sOut, int sOutCap)\r
+{\r
+    int sOutIndex = 0;\r
+\r
+    for (int i = 0; i < sInLen; i++)\r
+    {\r
+        if (i >= sOutCap)\r
+            return false;\r
+        \r
+        if (sIn[i] == '.' ||\r
+            sIn[i] == '[' ||\r
+            sIn[i] == ']'\r
+        ) {\r
+            sOut[sOutIndex++] = '\\';\r
+        }\r
+        sOut[sOutIndex++] = sIn[i];\r
+    }\r
+\r
+    if (sOutIndex < sOutCap)\r
+        sOut[sOutIndex] = '\0';\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
+    size_t res =\r
+        olm_account_sign(client->olmAccount.account,\r
+            sIn, sInLen,\r
+            signature, OLM_SIGNATURE_SIZE);\r
+    \r
+    int signatureLen = res;\r
+    \r
+    static char thisSigningKey[SIGNING_KEY_SIZE];\r
+    MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, SIGNING_KEY_SIZE);\r
+\r
+    static char signatureJson[JSON_SIGNATURE_SIZE];\r
+    int signatureJsonLen =\r
+        mjson_snprintf(signatureJson, JSON_SIGNATURE_SIZE,\r
+            "{"\r
+                "\"signatures\":{"\r
+                    "\"%s\":{"\r
+                        "\"ed25519:%s\":\"%.*s\""\r
+                    "}"\r
+                "}"\r
+            "}",\r
+            client->userId,\r
+            //"1",\r
+            client->deviceId,\r
+            signatureLen, signature);\r
+\r
+    struct mjson_fixedbuf result = { sOut, sOutCap, 0 };\r
+    mjson_merge(\r
+        sIn, sInLen,\r
+        signatureJson, signatureJsonLen,\r
+        mjson_print_fixed_buf,\r
+        &result);\r
+\r
+    return true;\r
 }\r
 \r
 \r
 }\r
 \r
 \r
+bool\r
+MatrixOlmAccountInit(\r
+    MatrixOlmAccount * account)\r
+{\r
+    account->account = olm_account(account->memory);\r
+\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
+        account->account,\r
+        random,\r
+        OLM_ACCOUNT_RANDOM_SIZE);\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+bool\r
+MatrixOlmAccountUnpickle(\r
+    MatrixOlmAccount * account,\r
+    void * pickled, int pickledLen,\r
+    const void * key, int keyLen)\r
+{\r
+    size_t res;\r
+    res = olm_unpickle_account(account->account,\r
+        key, keyLen,\r
+        pickled, pickledLen);\r
+    if (res == olm_error()) {\r
+        printf("error unpickling olm account:%s\n",\r
+            olm_account_last_error(account->account));\r
+    }\r
+    return res != olm_error();\r
+}\r
+\r
+bool\r
+MatrixOlmAccountGetDeviceKey(\r
+    MatrixOlmAccount * account,\r
+    char * key, int keyCap)\r
+{\r
+    static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE];\r
+    size_t res =\r
+        olm_account_identity_keys(account->account,\r
+            deviceKeysJson, OLM_IDENTITY_KEYS_JSON_SIZE);\r
+    mjson_get_string(deviceKeysJson, res,\r
+        "$.curve25519",\r
+        key, keyCap);\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixOlmAccountGetSigningKey(\r
+    MatrixOlmAccount * account,\r
+    char * key, int keyCap)\r
+{\r
+    static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE];\r
+    size_t res =\r
+        olm_account_identity_keys(account->account,\r
+            deviceKeysJson, OLM_IDENTITY_KEYS_JSON_SIZE);\r
+    mjson_get_string(deviceKeysJson, res,\r
+        "$.ed25519",\r
+        key, keyCap);\r
+    return true;\r
+}\r
+\r
+// TODO:in/outbound sessions\r
+bool\r
+MatrixOlmSessionTo(\r
+    MatrixOlmSession * session,\r
+    OlmAccount * olmAccount,\r
+    const char * deviceId,\r
+    const char * deviceKey,\r
+    const char * deviceOnetimeKey)\r
+{\r
+    memset(session, 0, sizeof(MatrixOlmSession));\r
+\r
+    session->deviceId = deviceId;\r
+\r
+    session->session =\r
+        olm_session(session->memory);\r
+\r
+    static uint8_t random[OLM_OUTBOUND_SESSION_RANDOM_SIZE];\r
+    Randomize(random, OLM_OUTBOUND_SESSION_RANDOM_SIZE);\r
+\r
+    size_t res =\r
+        olm_create_outbound_session(session->session,\r
+            olmAccount,\r
+            deviceKey, strlen(deviceKey),\r
+            deviceOnetimeKey, strlen(deviceOnetimeKey),\r
+            random, OLM_OUTBOUND_SESSION_RANDOM_SIZE);\r
+    \r
+    if (res == olm_error()) {\r
+        printf("error olm:%s\n", olm_session_last_error(session->session));\r
+    }\r
+\r
+    return session->session != NULL;\r
+}\r
+\r
+bool\r
+MatrixOlmSessionUnpickle(\r
+    MatrixOlmSession * session,\r
+    const char * deviceId,\r
+    void * pickled, int pickledLen,\r
+    const void * key, int keyLen)\r
+{\r
+    memset(session, 0, sizeof(MatrixOlmSession));\r
+\r
+    session->deviceId = deviceId;\r
+\r
+    session->session =\r
+        olm_session(session->memory);\r
+    \r
+    size_t res;\r
+    res = olm_unpickle_session(session->session,\r
+        key, keyLen,\r
+        pickled, pickledLen);\r
+    \r
+    if (res == olm_error()) {\r
+        printf("error unpickling olm session:%s\n", olm_session_last_error(session->session));\r
+    }\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+bool\r
+MatrixOlmSessionEncrypt(\r
+    MatrixOlmSession * session,\r
+    const char * plaintext,\r
+    char * outBuffer, int outBufferCap)\r
+{\r
+    static uint8_t random[OLM_ENCRYPT_RANDOM_SIZE];\r
+    Randomize(random, OLM_ENCRYPT_RANDOM_SIZE);\r
+\r
+    size_t res = olm_encrypt(session->session,\r
+        plaintext, strlen(plaintext),\r
+        random, OLM_ENCRYPT_RANDOM_SIZE,\r
+        outBuffer, outBufferCap);\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+bool\r
+MatrixOlmSessionDecrypt(\r
+    MatrixOlmSession * session,\r
+    size_t messageType,\r
+    char * encrypted,\r
+    char * outBuffer, int outBufferCap)\r
+{\r
+    static uint8_t random[OLM_ENCRYPT_RANDOM_SIZE];\r
+    Randomize(random, OLM_ENCRYPT_RANDOM_SIZE);\r
+\r
+    size_t res =\r
+        olm_decrypt(session->session,\r
+            messageType,\r
+            encrypted, strlen(encrypted),\r
+            outBuffer, outBufferCap);\r
+    \r
+    if (res != olm_error() && res < outBufferCap)\r
+        outBuffer[outBufferCap] = '\0';\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+// https://matrix.org/docs/guides/end-to-end-encryption-implementation-guide#starting-a-megolm-session\r
+bool\r
+MatrixMegolmOutSessionInit(\r
+    MatrixMegolmOutSession * session,\r
+    const char * roomId)\r
+{\r
+    memset(session, 0, sizeof(MatrixMegolmOutSession));\r
+\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
+\r
+    session->session =\r
+        olm_outbound_group_session(session->memory);\r
+\r
+    olm_init_outbound_group_session(\r
+        session->session,\r
+        random,\r
+        MEGOLM_INIT_RANDOM_SIZE);\r
+\r
+    olm_outbound_group_session_id(session->session,\r
+        (uint8_t *)session->id,\r
+        MEGOLM_SESSION_ID_SIZE);\r
+        \r
+    olm_outbound_group_session_key(session->session,\r
+        (uint8_t *)session->key,\r
+        MEGOLM_SESSION_KEY_SIZE);\r
+    \r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixMegolmOutSessionEncrypt(\r
+    MatrixMegolmOutSession * session,\r
+    const char * plaintext,\r
+    char * outBuffer, int outBufferCap)\r
+{\r
+    size_t res = olm_group_encrypt(session->session,\r
+        (uint8_t *)plaintext, strlen(plaintext),\r
+        (uint8_t *)outBuffer, outBufferCap);\r
+\r
+    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
     MatrixClient * client,\r
 bool\r
 MatrixClientInit(\r
     MatrixClient * client,\r
-    FixedBuffer server\r
-) {\r
+    const char * server)\r
+{\r
+    memset(client, 0, sizeof(MatrixClient));\r
+\r
+    strcpy(client->server, server);\r
+\r
+    // init olm account\r
+    MatrixOlmAccountInit(&client->olmAccount);\r
+\r
+    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->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
+    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->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
+    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
+    const char * accessToken)\r
+{\r
+    for (int i = 0; i < ACCESS_TOKEN_SIZE-1; i++)\r
+        client->accessToken[i] = accessToken[i];\r
+    client->accessToken[ACCESS_TOKEN_SIZE-1] = '\0';\r
+\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixClientSetDeviceId(\r
+    MatrixClient * client,\r
+    const char * deviceId)\r
+{\r
+    for (int i = 0; i < DEVICE_ID_SIZE-1; i++)\r
+        client->deviceId[i] = deviceId[i];\r
+    client->deviceId[DEVICE_ID_SIZE-1] = '\0';\r
+\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixClientSetUserId(\r
+    MatrixClient * client,\r
+    const char * userId)\r
+{\r
+    for (int i = 0; i < USER_ID_SIZE-1; i++)\r
+        client->userId[i] = userId[i];\r
+    client->userId[USER_ID_SIZE-1] = '\0';\r
+\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixClientGenerateOnetimeKeys(\r
+    MatrixClient * client,\r
+    int numberOfKeys)\r
+{\r
+    static uint8_t random[OLM_ONETIME_KEYS_RANDOM_SIZE];\r
+    Randomize(random, OLM_ONETIME_KEYS_RANDOM_SIZE);\r
+\r
+    size_t res =\r
+        olm_account_generate_one_time_keys(client->olmAccount.account,\r
+            numberOfKeys, random, OLM_ONETIME_KEYS_RANDOM_SIZE);\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+// https://spec.matrix.org/v1.7/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
+        "{");\r
+\r
+    static char onetimeKeysBuffer[1024];\r
+    olm_account_one_time_keys(client->olmAccount.account,\r
+        onetimeKeysBuffer, 1024);\r
+\r
+    const char *keys;\r
+    int keysLen;\r
+    mjson_find(onetimeKeysBuffer, strlen(onetimeKeysBuffer), "$.curve25519", &keys, &keysLen);\r
+\r
+    int koff, klen, voff, vlen, vtype, off = 0;\r
+    while ((off = mjson_next(keys, keysLen, off, &koff, &klen, &voff, &vlen, &vtype)) != 0) {\r
+        static char keyJson[JSON_ONETIME_KEY_SIZE];\r
+        \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
+\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
+            "\"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
+\r
+    mjson_snprintf(requestBuffer+strlen(requestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer),\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
+    static char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE];\r
+    MatrixHttpPost(client,\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
+// https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysupload\r
+bool\r
+MatrixClientUploadDeviceKey(\r
+    MatrixClient * client)\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
+    static char deviceKeysBuffer[KEYS_UPLOAD_REQUEST_SIZE];\r
+\r
+    int deviceKeysBufferLen =\r
+        mjson_snprintf(deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE,\r
+            "{"\r
+                "\"algorithms\":[\"m.olm.v1.curve25519-aes-sha2\",\"m.megolm.v1.aes-sha2\"],"\r
+                "\"device_id\":\"%s\","\r
+                "\"keys\":{"\r
+                    "\"curve25519:%s\":\"%s\","\r
+                    "\"ed25519:%s\":\"%s\""\r
+                "},"\r
+                "\"user_id\":\"%s\""\r
+            "}",\r
+            client->deviceId,\r
+            client->deviceId, thisDeviceKey,\r
+            client->deviceId, thisSigningKey,\r
+            client->userId);\r
+\r
+    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
+    "{\"device_keys\":%s}", deviceKeysSignedBuffer);\r
+\r
+    static char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE];\r
+    MatrixHttpPost(client,\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
+// https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysclaim\r
+bool\r
+MatrixClientClaimOnetimeKey(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    char * outOnetimeKey, int outOnetimeKeyCap)\r
+{\r
+    static char requestBuffer[KEYS_CLAIM_REQUEST_SIZE];\r
+    mjson_snprintf(requestBuffer, KEYS_CLAIM_REQUEST_SIZE,\r
+    "{"\r
+      "\"one_time_keys\":{"\r
+        "\"%s\":{"\r
+          "\"%s\":\"signed_curve25519\""\r
+        "}"\r
+      "},"\r
+      "\"timeout\":10000"\r
+    "}",\r
+    userId,\r
+    deviceId);\r
 \r
 \r
+    static char responseBuffer[KEYS_CLAIM_RESPONSE_SIZE];\r
+    MatrixHttpPost(client,\r
+        KEYS_CLAIM_URL,\r
+        requestBuffer,\r
+        responseBuffer, KEYS_CLAIM_RESPONSE_SIZE,\r
+        true);\r
+    \r
+    char userIdEscaped[USER_ID_SIZE];\r
+    JsonEscape(userId, strlen(userId),\r
+        userIdEscaped, USER_ID_SIZE);\r
+    \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
+    const char * keyObject;\r
+    int keyObjectSize;\r
+    mjson_find(responseBuffer, strlen(responseBuffer),\r
+        query,\r
+        &keyObject, &keyObjectSize);\r
+    \r
+    int koff, klen, voff, vlen, vtype;\r
+    mjson_next(keyObject, keyObjectSize, 0,\r
+        &koff, &klen, &voff, &vlen, &vtype);\r
+    \r
+    mjson_get_string(keyObject + voff, vlen,\r
+        "$.key", outOnetimeKey, outOnetimeKeyCap);\r
+    \r
+    // TODO:verify signature\r
+    \r
+    return true;\r
 }\r
 \r
 }\r
 \r
+// https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3login\r
 bool\r
 MatrixClientLoginPassword(\r
     MatrixClient * client,\r
 bool\r
 MatrixClientLoginPassword(\r
     MatrixClient * client,\r
-    FixedBuffer username,\r
-    FixedBuffer password\r
-) {\r
+    const char * username,\r
+    const char * password,\r
+    const char * displayName)\r
+{\r
+    static char requestBuffer[LOGIN_REQUEST_SIZE];\r
 \r
 \r
+    mjson_snprintf(requestBuffer, LOGIN_REQUEST_SIZE,\r
+        "{"\r
+            "\"type\":\"m.login.password\","\r
+            "\"identifier\":{"\r
+                "\"type\":\"m.id.user\","\r
+                "\"user\":\"%s\""\r
+            "},"\r
+            "\"password\":\"%s\","\r
+            "\"initial_device_display_name\":\"%s\""\r
+        "}",\r
+        username,\r
+        password,\r
+        displayName);\r
+    \r
+    static char responseBuffer[LOGIN_RESPONSE_SIZE];\r
+    bool result =\r
+        MatrixHttpPost(client,\r
+            LOGIN_URL,\r
+            requestBuffer,\r
+            responseBuffer, LOGIN_RESPONSE_SIZE,\r
+            false);\r
+    \r
+    if (!result)\r
+        return false;\r
+    \r
+    int responseLen = strlen(responseBuffer);\r
+\r
+    mjson_get_string(responseBuffer, responseLen,\r
+        "$.access_token",\r
+        client->accessToken, ACCESS_TOKEN_SIZE);\r
+    mjson_get_string(responseBuffer, responseLen,\r
+        "$.device_id",\r
+        client->deviceId, DEVICE_ID_SIZE);\r
+    mjson_get_string(responseBuffer, responseLen,\r
+        "$.expires_in_ms",\r
+        client->expireMs, EXPIRE_MS_SIZE);\r
+    mjson_get_string(responseBuffer, responseLen,\r
+        "$.refresh_token",\r
+        client->refreshToken, REFRESH_TOKEN_SIZE);\r
+\r
+    return true;\r
 }\r
 \r
 }\r
 \r
+// https://spec.matrix.org/v1.6/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid\r
 bool\r
 bool\r
-MatrixClientGetAccessToken(\r
+MatrixClientSendEvent(\r
     MatrixClient * client,\r
     MatrixClient * client,\r
-    FixedBuffer * outBuffer\r
-) {\r
+    const char * roomId,\r
+    const char * msgType,\r
+    const char * msgBody)\r
+{    \r
+    static char requestUrl[MAX_URL_LEN];\r
+    sprintf(requestUrl,\r
+        ROOM_SEND_URL, roomId, msgType, (int)time(NULL));\r
 \r
 \r
+    static char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
+    bool result =\r
+        MatrixHttpPut(client,\r
+            requestUrl,\r
+            msgBody,\r
+            responseBuffer, ROOM_SEND_RESPONSE_SIZE,\r
+            true);\r
+    \r
+    return result;\r
 }\r
 }\r
+\r
+// https://spec.matrix.org/v1.6/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
+    MatrixClient * client,\r
+    const char * roomId,\r
+    const char * msgType,\r
+    const char * msgBody)\r
+{\r
+    // event json\r
+    static char requestBuffer[ROOM_SEND_REQUEST_SIZE];\r
+    sprintf(requestBuffer,\r
+        "{"\r
+        "\"type\":\"%s\","\r
+        "\"content\":%s,"\r
+        "\"room_id\":\"%s\""\r
+        "}",\r
+        msgType,\r
+        msgBody,\r
+        roomId);\r
+\r
+    // get megolm session\r
+    MatrixMegolmOutSession * outSession;\r
+    MatrixClientGetMegolmOutSession(client, roomId, &outSession);\r
+        \r
+    // encrypt\r
+    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\r
+    MatrixMegolmOutSessionEncrypt(outSession,\r
+        requestBuffer,\r
+        encryptedBuffer, ENCRYPTED_REQUEST_SIZE);\r
+\r
+    char thisDeviceKey[DEVICE_KEY_SIZE];\r
+    MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE);\r
+    \r
+\r
+    // encrypted event json\r
+    const char * senderKey = thisDeviceKey;\r
+    const char * sessionId = outSession->id;\r
+    const char * deviceId = client->deviceId;\r
+\r
+    static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
+    sprintf(encryptedEventBuffer,\r
+        "{"\r
+        "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
+        "\"ciphertext\":\"%s\","\r
+        "\"device_id\":\"%s\","\r
+        "\"sender_key\":\"%s\","\r
+        "\"session_id\":\"%s\""\r
+        "}",\r
+        encryptedBuffer,\r
+        deviceId,\r
+        senderKey,\r
+        sessionId);\r
+\r
+    // send\r
+    return MatrixClientSendEvent(client,\r
+        roomId,\r
+        "m.room.encrypted",\r
+        encryptedEventBuffer);\r
+}\r
+\r
+// https://spec.matrix.org/v1.6/client-server-api/#get_matrixclientv3sync\r
+bool\r
+MatrixClientSync(\r
+    MatrixClient * client,\r
+    char * outSyncBuffer, int outSyncCap,\r
+    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%s",\r
+        strlen(nextBatch) > 0 ? "?since=" : "");\r
+    \r
+    int index = strlen(url);\r
+\r
+    for (int 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
+            url,\r
+            outSyncBuffer, outSyncCap,\r
+            true);\r
+}\r
+\r
+// https://spec.matrix.org/v1.7/client-server-api/#get_matrixclientv3roomsroomideventeventid\r
+bool\r
+MatrixClientGetRoomEvent(\r
+    MatrixClient * client,\r
+    const char * roomId,\r
+    const char * eventId,\r
+    char * outEvent, int outEventCap)\r
+{\r
+    static char url[MAX_URL_LEN];\r
+    snprintf(url, MAX_URL_LEN,\r
+        "/_matrix/client/v3/rooms/%s/event/%s",\r
+            roomId,\r
+            eventId);\r
+\r
+    return\r
+        MatrixHttpGet(client,\r
+            url,\r
+            outEvent, outEventCap,\r
+            true);\r
+}\r
+\r
+bool\r
+MatrixClientShareMegolmOutSession(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    MatrixMegolmOutSession * session)\r
+{\r
+    // generate room key event\r
+    static 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
+    // // 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
+        deviceId,\r
+        eventBuffer,\r
+        "m.room_key");\r
+\r
+    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
+// 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
+    const char * roomId,\r
+    MatrixMegolmOutSession ** outSession)\r
+{\r
+    for (int i = 0; i < client->numMegolmOutSessions; i++)\r
+    {\r
+        if (strcmp(client->megolmOutSessions[i].roomId, roomId) == 0)\r
+        {\r
+            *outSession = &client->megolmOutSessions[i];\r
+            return true;\r
+        }\r
+    }\r
+\r
+    if (MatrixClientInitMegolmOutSession(client, roomId)) {\r
+        *outSession = &client->megolmOutSessions[client->numMegolmOutSessions-1];\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientInitMegolmOutSession(\r
+    MatrixClient * client,\r
+    const char * roomId)\r
+{\r
+    if (client->numMegolmOutSessions < NUM_MEGOLM_SESSIONS)\r
+    {\r
+        MatrixMegolmOutSessionInit(\r
+            &client->megolmOutSessions[client->numMegolmOutSessions],\r
+            roomId);\r
+        \r
+        client->numMegolmOutSessions++;\r
+\r
+        return true;\r
+    }\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientRequestMegolmInSession(\r
+    MatrixClient * client,\r
+    const char * roomId,\r
+    const char * sessionId,\r
+    const char * senderKey,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    MatrixMegolmInSession * outMegolmInSession)\r
+{\r
+    // TODO: cancel requests\r
+    MatrixClientSendDummy(client, userId, deviceId);\r
+\r
+    static char event[ROOMKEY_REQUEST_SIZE];\r
+    snprintf(event, ROOMKEY_REQUEST_SIZE,\r
+        "{"\r
+            "\"action\":\"request\","\r
+            "\"body\":{"\r
+                "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
+                "\"room_id\":\"%s\","\r
+                "\"sender_key\":\"%s\","\r
+                "\"session_id\":\"%s\""\r
+            "},"\r
+            "\"request_id\":\"%d\","\r
+            "\"requesting_device_id\":\"%s\""\r
+        "}",\r
+        roomId,\r
+        senderKey,\r
+        sessionId,\r
+        time(NULL),\r
+        client->deviceId);\r
+\r
+    \r
+    MatrixClientSendToDevice(client,\r
+        userId,\r
+        deviceId,\r
+        event,\r
+        "m.room_key_request");\r
+\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixClientGetOlmSession(\r
+    MatrixClient * client,\r
+    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
+        MatrixClientRequestDeviceKey(client,\r
+            deviceId,\r
+            deviceKey, DEVICE_KEY_SIZE);\r
+\r
+        char onetimeKey[ONETIME_KEY_SIZE];\r
+        MatrixClientClaimOnetimeKey(client,\r
+            userId,\r
+            deviceId,\r
+            onetimeKey, ONETIME_KEY_SIZE);\r
+\r
+        MatrixOlmSessionTo(\r
+            &client->olmSessions[client->numOlmSessions],\r
+            client->olmAccount.account,\r
+            deviceId,\r
+            deviceKey,\r
+            onetimeKey);\r
+\r
+        *outSession = &client->olmSessions[client->numOlmSessions];\r
+        \r
+        client->numOlmSessions++;\r
+\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+// https://spec.matrix.org/v1.6/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid\r
+bool\r
+MatrixClientSendToDevice(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    const char * message,\r
+    const char * msgType)\r
+{\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
+        "{"\r
+            "\"messages\":{"\r
+                "\"%s\":{"\r
+                    "\"%s\":%s"\r
+                "}"\r
+            "}"\r
+        "}",\r
+        userId,\r
+        deviceId,\r
+        message);\r
+\r
+    static char responseBuffer[ROOM_SEND_RESPONSE_SIZE];\r
+    bool result =\r
+        MatrixHttpPut(client,\r
+            requestUrl,\r
+            eventBuffer,\r
+            responseBuffer, ROOM_SEND_RESPONSE_SIZE,\r
+            true);\r
+    \r
+    printf("%s\n", responseBuffer);\r
+    \r
+    return result;\r
+}\r
+\r
+bool\r
+MatrixClientSendToDeviceEncrypted(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    const char * message,\r
+    const char * msgType)\r
+{\r
+    // get olm session\r
+    MatrixOlmSession * olmSession;\r
+    MatrixClientGetOlmSession(client, userId, deviceId, &olmSession);\r
+\r
+    // create event json\r
+    char targetDeviceKey[DEVICE_KEY_SIZE];\r
+    MatrixClientRequestDeviceKey(client, deviceId, targetDeviceKey, DEVICE_KEY_SIZE);\r
+    char targetSigningKey[SIGNING_KEY_SIZE];\r
+    MatrixClientRequestSigningKey(client, deviceId, targetSigningKey, SIGNING_KEY_SIZE);\r
+    \r
+    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
+        "{"\r
+        "\"type\":\"%s\","\r
+        "\"content\":%s,"\r
+        "\"sender\":\"%s\","\r
+        "\"recipient\":\"%s\","\r
+        "\"recipient_keys\":{"\r
+          "\"ed25519\":\"%s\""\r
+        "},"\r
+        "\"keys\":{"\r
+          "\"ed25519\":\"%s\""\r
+        "}"\r
+        "}",\r
+        msgType,\r
+        message,\r
+        client->userId,\r
+        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
+    MatrixOlmSessionEncrypt(olmSession,\r
+        eventBuffer,\r
+        encryptedBuffer, 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
+        "{"\r
+        "\"algorithm\":\"m.olm.v1.curve25519-aes-sha2\","\r
+        "\"ciphertext\":{"\r
+          "\"%s\":{"\r
+            "\"body\":\"%s\","\r
+            "\"type\":%d"\r
+          "}"\r
+        "},"\r
+        "\"device_id\":\"%s\","\r
+        "\"sender_key\":\"%s\""\r
+        "}",\r
+        targetDeviceKey,\r
+        encryptedBuffer,\r
+        olm_session_has_received_message(olmSession->session),\r
+        client->deviceId,\r
+        thisDeviceKey);\r
+\r
+    // send\r
+    return MatrixClientSendToDevice(\r
+        client,\r
+        userId,\r
+        deviceId,\r
+        encryptedEventBuffer,\r
+        "m.room.encrypted");\r
+}\r
+\r
+bool\r
+MatrixClientSendDummy(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId)\r
+{\r
+    return MatrixClientSendToDeviceEncrypted(\r
+        client,\r
+        userId,\r
+        deviceId,\r
+        "{}",\r
+        "m.dummy");\r
+}\r
+\r
+bool\r
+MatrixClientFindDevice(\r
+    MatrixClient * client,\r
+    const char * deviceId,\r
+    MatrixDevice ** outDevice)\r
+{\r
+    MatrixClientRequestDeviceKeys(client);\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
+    *outDevice = NULL;\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientRequestDeviceKey(\r
+    MatrixClient * client,\r
+    const char * deviceId,\r
+    char * outDeviceKey, int outDeviceKeyCap)\r
+{\r
+    MatrixDevice * device;\r
+    \r
+    if (MatrixClientFindDevice(client, deviceId, &device))\r
+    {\r
+        strncpy(outDeviceKey, device->deviceKey, outDeviceKeyCap);\r
+        return true;\r
+    }\r
+\r
+    MatrixClientRequestDeviceKeys(client);\r
+    \r
+    if (MatrixClientFindDevice(client, deviceId, &device))\r
+    {\r
+        strncpy(outDeviceKey, device->deviceKey, outDeviceKeyCap);\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientRequestSigningKey(\r
+    MatrixClient * client,\r
+    const char * deviceId,\r
+    char * outSigningKey, int outSigningKeyCap)\r
+{\r
+    MatrixDevice * device;\r
+    \r
+    if (MatrixClientFindDevice(client, deviceId, &device))\r
+    {\r
+        strncpy(outSigningKey, device->signingKey, outSigningKeyCap);\r
+        return true;\r
+    }\r
+\r
+    MatrixClientRequestDeviceKeys(client);\r
+    \r
+    if (MatrixClientFindDevice(client, deviceId, &device))\r
+    {\r
+        strncpy(outSigningKey, device->signingKey, outSigningKeyCap);\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+// https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3keysquery\r
+bool\r
+MatrixClientRequestDeviceKeys(\r
+    MatrixClient * client)\r
+{\r
+    static char userIdEscaped[USER_ID_SIZE];\r
+    JsonEscape(client->userId, strlen(client->userId),\r
+        userIdEscaped, USER_ID_SIZE);\r
+\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
+        KEYS_QUERY_URL,\r
+        request,\r
+        responseBuffer, KEYS_QUERY_RESPONSE_SIZE,\r
+        true);\r
+\r
+    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
+    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
+    for (off = 0; (off = mjson_next(s, slen, off, &koff, &klen,\r
+                                    &voff, &vlen, &vtype)) != 0; ) {\r
+        const char * key = s + koff;\r
+        const char * val = s + voff;\r
+\r
+        // set device id, "key" is the JSON key\r
+        MatrixDevice d;\r
+        snprintf(d.deviceId, DEVICE_ID_SIZE,\r
+            "%.*s", klen-2, key+1);\r
+\r
+        // look for device key in value\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
+        snprintf(signingKeyQuery, JSON_QUERY_SIZE,\r
+            "$.keys.ed25519:%s", d.deviceId);\r
+        mjson_get_string(val, vlen,\r
+            signingKeyQuery, d.signingKey, SIGNING_KEY_SIZE);\r
+\r
+        // add device\r
+        if (client->numDevices < NUM_DEVICES)\r
+        {\r
+            bool foundDevice = false;\r
+            for (int i = 0; i < client->numDevices; i++)\r
+                if (strcmp(client->devices[i].deviceId, d.deviceId) == 0)\r
+                    foundDevice = true;\r
+\r
+            if (! foundDevice) {\r
+                printf("new device: %s %s %s\n", d.deviceId, d.deviceKey, d.signingKey);\r
+                client->devices[client->numDevices] = d;\r
+                client->numDevices++;\r
+            }\r
+        }\r
+        else\r
+        {\r
+            return false;\r
+        }\r
+    }\r
+\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixClientDeleteDevice(\r
+    MatrixClient * client)\r
+{\r
+    static char deleteRequest[1024];\r
+    snprintf(deleteRequest, 1024,\r
+        "{\"devices\":[\"%s\"]}",\r
+        client->deviceId);\r
+    static char deleteResponse[1024];\r
+    bool res = MatrixHttpPost(client, "/_matrix/client/v3/delete_devices",\r
+        deleteRequest, deleteResponse, 1024, true);\r
+    return res;\r
+}
\ No newline at end of file