]> gitweb.ps.run Git - matrix_esp_thesis/blobdiff - src/matrix.c
cli send encrypted & manage megolm session, save/load megolm sessions
[matrix_esp_thesis] / src / matrix.c
index 1f5ed2de70135ea20d2f215b8f251156380c3f34..fa7303f891e250dfc5d1349e6293ee8bf4d5a7ff 100644 (file)
@@ -9,24 +9,28 @@
 #define LOGIN_RESPONSE_SIZE 1024\r
 #define LOGIN_URL "/_matrix/client/v3/login"\r
 \r
 #define LOGIN_RESPONSE_SIZE 1024\r
 #define LOGIN_URL "/_matrix/client/v3/login"\r
 \r
-#define ENCRYPTED_REQUEST_SIZE 512\r
-#define ENCRYPTED_EVENT_SIZE 1024\r
+#define ENCRYPTED_REQUEST_SIZE (1024*5)\r
+#define ENCRYPTED_EVENT_SIZE (1024*10)\r
 #define ROOMEVENT_REQUEST_SIZE 256\r
 #define ROOMEVENT_RESPONSE_SIZE 1024\r
 #define ROOMEVENT_URL "/_matrix/client/v3/rooms/%s/send/%s/%d"\r
 \r
 #define ROOMEVENT_REQUEST_SIZE 256\r
 #define ROOMEVENT_RESPONSE_SIZE 1024\r
 #define ROOMEVENT_URL "/_matrix/client/v3/rooms/%s/send/%s/%d"\r
 \r
-#define TODEVICE_EVENT_SIZE 512\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 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\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\r
 #define KEYS_UPLOAD_REQUEST_SIGNED_SIZE 2048\r
 #define KEYS_UPLOAD_RESPONSE_SIZE 2048\r
 \r
 \r
 #define KEYS_UPLOAD_URL "/_matrix/client/v3/keys/upload"\r
 #define KEYS_UPLOAD_REQUEST_SIZE 1024\r
 #define KEYS_UPLOAD_REQUEST_SIGNED_SIZE 2048\r
 #define KEYS_UPLOAD_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
 #define JSON_QUERY_SIZE 128\r
 \r
 \r
@@ -36,7 +40,7 @@ Randomize(
     uint8_t * random,\r
     int randomLen)\r
 {\r
     uint8_t * random,\r
     int randomLen)\r
 {\r
-    static bool first = false;\r
+    static bool first = true;\r
     if (first) { srand(time(0)); first = false; }\r
 \r
     for (int i = 0; i < randomLen; i++)\r
     if (first) { srand(time(0)); first = false; }\r
 \r
     for (int i = 0; i < randomLen; i++)\r
@@ -47,7 +51,7 @@ Randomize(
 \r
 bool\r
 JsonEscape(\r
 \r
 bool\r
 JsonEscape(\r
-    char * sIn, int sInLen,\r
+    const char * sIn, int sInLen,\r
     char * sOut, int sOutCap)\r
 {\r
     int sOutIndex = 0;\r
     char * sOut, int sOutCap)\r
 {\r
     int sOutIndex = 0;\r
@@ -74,7 +78,7 @@ JsonEscape(
 \r
 bool JsonSign(\r
     MatrixClient * client,\r
 \r
 bool JsonSign(\r
     MatrixClient * client,\r
-    char * sIn, int sInLen,\r
+    const char * sIn, int sInLen,\r
     char * sOut, int sOutCap)\r
 {\r
     static char signature[OLM_SIGNATURE_SIZE];\r
     char * sOut, int sOutCap)\r
 {\r
     static char signature[OLM_SIGNATURE_SIZE];\r
@@ -129,20 +133,34 @@ MatrixOlmAccountInit(
 \r
 // TODO: in/outbound sessions\r
 bool\r
 \r
 // TODO: in/outbound sessions\r
 bool\r
-MatrixOlmSessionInit(\r
+MatrixOlmSessionTo(\r
     MatrixOlmSession * session,\r
     MatrixOlmSession * session,\r
-    const char * deviceId)\r
+    OlmAccount * olmAccount,\r
+    const char * deviceId,\r
+    const char * deviceKey,\r
+    const char * deviceOnetimeKey)\r
 {\r
     memset(session, 0, sizeof(MatrixOlmSession));\r
 \r
 {\r
     memset(session, 0, sizeof(MatrixOlmSession));\r
 \r
-    static uint8_t random[MEGOLM_INIT_RANDOM_SIZE];\r
-    Randomize(random, MEGOLM_INIT_RANDOM_SIZE);\r
-\r
     session->deviceId = deviceId;\r
 \r
     session->session =\r
         olm_session(session->memory);\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_account_last_error(olmAccount));\r
+    }\r
+\r
     return session->session != NULL;\r
 }\r
 \r
     return session->session != NULL;\r
 }\r
 \r
@@ -208,6 +226,67 @@ MatrixMegolmOutSessionEncrypt(
     return res != olm_error();\r
 }\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
+\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
+    fclose(f);\r
+\r
+    return true;\r
+}\r
+\r
 \r
 \r
 bool\r
 \r
 \r
 bool\r
@@ -241,17 +320,65 @@ MatrixClientInit(
 }\r
 \r
 bool\r
 }\r
 \r
 bool\r
-MatrixClientSetAccessToken(\r
+MatrixClientSave(\r
     MatrixClient * client,\r
     MatrixClient * client,\r
-    const char * accessToken)\r
+    const char * filename)\r
 {\r
 {\r
-    int accessTokenLen = strlen(accessToken);\r
+    FILE * f = fopen(filename, "w");\r
+    \r
+    fwrite(client->deviceKey, 1, DEVICE_KEY_SIZE, f);\r
+    fwrite(client->signingKey, 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
 \r
-    if (accessTokenLen > ACCESS_TOKEN_SIZE - 1)\r
-        return false;\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
+    fread(client->deviceKey, 1, DEVICE_KEY_SIZE, f);\r
+    fread(client->signingKey, 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
 \r
-    for (int i = 0; i < accessTokenLen; i++)\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[i] = accessToken[i];\r
+    client->accessToken[ACCESS_TOKEN_SIZE-1] = '\0';\r
 \r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
@@ -261,13 +388,9 @@ MatrixClientSetDeviceId(
     MatrixClient * client,\r
     const char * deviceId)\r
 {\r
     MatrixClient * client,\r
     const char * deviceId)\r
 {\r
-    int deviceIdLen = strlen(deviceId);\r
-\r
-    if (deviceIdLen > DEVICE_ID_SIZE - 1)\r
-        return false;\r
-\r
-    for (int i = 0; i < deviceIdLen; i++)\r
+    for (int i = 0; i < DEVICE_ID_SIZE-1; i++)\r
         client->deviceId[i] = deviceId[i];\r
         client->deviceId[i] = deviceId[i];\r
+    client->deviceId[DEVICE_ID_SIZE-1] = '\0';\r
 \r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
@@ -277,13 +400,9 @@ MatrixClientSetUserId(
     MatrixClient * client,\r
     const char * userId)\r
 {\r
     MatrixClient * client,\r
     const char * userId)\r
 {\r
-    int userIdLen = strlen(userId);\r
-\r
-    if (userIdLen > USER_ID_SIZE - 1)\r
-        return false;\r
-\r
-    for (int i = 0; i < userIdLen; i++)\r
+    for (int i = 0; i < USER_ID_SIZE-1; i++)\r
         client->userId[i] = userId[i];\r
         client->userId[i] = userId[i];\r
+    client->userId[USER_ID_SIZE-1] = '\0';\r
 \r
     return true;\r
 }\r
 \r
     return true;\r
 }\r
@@ -392,6 +511,62 @@ MatrixClientUploadDeviceKeys(
     return true;\r
 }\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
+    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
 // https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3login\r
 bool\r
 MatrixClientLoginPassword(\r
 // https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3login\r
 bool\r
 MatrixClientLoginPassword(\r
@@ -508,15 +683,15 @@ MatrixClientSendEventEncrypted(
     sprintf(encryptedEventBuffer,\r
         "{"\r
         "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
     sprintf(encryptedEventBuffer,\r
         "{"\r
         "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
-        "\"sender_key\":\"%s\","\r
         "\"ciphertext\":\"%s\","\r
         "\"ciphertext\":\"%s\","\r
-        "\"session_id\":\"%s\","\r
-        "\"device_id\":\"%s\""\r
+        "\"device_id\":\"%s\","\r
+        "\"sender_key\":\"%s\","\r
+        "\"session_id\":\"%s\""\r
         "}",\r
         "}",\r
-        senderKey,\r
         encryptedBuffer,\r
         encryptedBuffer,\r
-        sessionId,\r
-        deviceId);\r
+        deviceId,\r
+        senderKey,\r
+        sessionId);\r
 \r
     // send\r
     return MatrixClientSendEvent(client,\r
 \r
     // send\r
     return MatrixClientSendEvent(client,\r
@@ -541,11 +716,12 @@ MatrixClientSync(
 bool\r
 MatrixClientShareMegolmOutSession(\r
     MatrixClient * client,\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
     const char * deviceId,\r
     MatrixMegolmOutSession * session)\r
 {\r
     // generate room key event\r
-    char eventBuffer[KEY_SHARE_EVENT_LEN];\r
+    static char eventBuffer[KEY_SHARE_EVENT_LEN];\r
     sprintf(eventBuffer,\r
         "{"\r
             "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
     sprintf(eventBuffer,\r
         "{"\r
             "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
@@ -558,21 +734,21 @@ MatrixClientShareMegolmOutSession(
         session->key\r
     );\r
 \r
         session->key\r
     );\r
 \r
-    // get olm session\r
-    MatrixOlmSession * olmSession;\r
-    MatrixClientGetOlmSession(client, deviceId, &olmSession);\r
+    // // get olm session\r
+    // MatrixOlmSession * olmSession;\r
+    // MatrixClientGetOlmSession(client, userId, deviceId, &olmSession);\r
 \r
 \r
-    // encrypt\r
-    char encryptedBuffer[KEY_SHARE_EVENT_LEN];\r
-    MatrixOlmSessionEncrypt(olmSession,\r
-        eventBuffer,\r
-        encryptedBuffer, KEY_SHARE_EVENT_LEN);\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
 \r
     // send\r
     MatrixClientSendToDeviceEncrypted(client,\r
-        client->userId,\r
+        userId,\r
         deviceId,\r
         deviceId,\r
-        encryptedBuffer,\r
+        eventBuffer,\r
         "m.room_key");\r
 \r
     return true;\r
         "m.room_key");\r
 \r
     return true;\r
@@ -659,6 +835,7 @@ MatrixClientGetMegolmOutSession(
 bool\r
 MatrixClientGetOlmSession(\r
     MatrixClient * client,\r
 bool\r
 MatrixClientGetOlmSession(\r
     MatrixClient * client,\r
+    const char * userId,\r
     const char * deviceId,\r
     MatrixOlmSession ** outSession)\r
 {\r
     const char * deviceId,\r
     MatrixOlmSession ** outSession)\r
 {\r
@@ -673,9 +850,23 @@ MatrixClientGetOlmSession(
 \r
     if (client->numOlmSessions < NUM_OLM_SESSIONS)\r
     {\r
 \r
     if (client->numOlmSessions < NUM_OLM_SESSIONS)\r
     {\r
-        MatrixOlmSessionInit(\r
+        static char deviceKey[DEVICE_KEY_SIZE];\r
+        MatrixClientGetDeviceKey(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->olmSessions[client->numOlmSessions],\r
-            deviceId);\r
+            client->olmAccount.account,\r
+            deviceId,\r
+            deviceKey,\r
+            onetimeKey);\r
 \r
         *outSession = &client->olmSessions[client->numOlmSessions];\r
         \r
 \r
         *outSession = &client->olmSessions[client->numOlmSessions];\r
         \r
@@ -734,12 +925,11 @@ MatrixClientSendToDeviceEncrypted(
 {\r
     // get olm session\r
     MatrixOlmSession * olmSession;\r
 {\r
     // get olm session\r
     MatrixOlmSession * olmSession;\r
-    MatrixClientGetOlmSession(client, deviceId, &olmSession);\r
+    MatrixClientGetOlmSession(client, userId, deviceId, &olmSession);\r
 \r
     // create event json\r
     char deviceKey[DEVICE_KEY_SIZE];\r
     MatrixClientGetDeviceKey(client, deviceId, deviceKey, DEVICE_KEY_SIZE);\r
 \r
     // create event json\r
     char deviceKey[DEVICE_KEY_SIZE];\r
     MatrixClientGetDeviceKey(client, deviceId, deviceKey, DEVICE_KEY_SIZE);\r
-    const char * senderKey = client->deviceKey;\r
     \r
     static char eventBuffer[TODEVICE_EVENT_SIZE];\r
     sprintf(eventBuffer,\r
     \r
     static char eventBuffer[TODEVICE_EVENT_SIZE];\r
     sprintf(eventBuffer,\r
@@ -771,19 +961,21 @@ MatrixClientSendToDeviceEncrypted(
     static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
     sprintf(encryptedEventBuffer,\r
         "{"\r
     static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
     sprintf(encryptedEventBuffer,\r
         "{"\r
-        "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
-        "\"sender_key\":\"%s\","\r
+        "\"algorithm\":\"m.olm.v1.curve25519-aes-sha2\","\r
         "\"ciphertext\":{"\r
           "\"%s\":{"\r
             "\"body\":\"%s\","\r
         "\"ciphertext\":{"\r
           "\"%s\":{"\r
             "\"body\":\"%s\","\r
-            "\"type\":\"%d\""\r
+            "\"type\":%d"\r
           "}"\r
           "}"\r
-        "}"\r
+        "},"\r
+        "\"device_id\":\"%s\","\r
+        "\"sender_key\":\"%s\""\r
         "}",\r
         "}",\r
-        senderKey,\r
         deviceKey,\r
         encryptedBuffer,\r
         deviceKey,\r
         encryptedBuffer,\r
-        olmSession->type);\r
+        0, //olmSession->type,\r
+        client->deviceId,\r
+        client->deviceKey);\r
 \r
     // send\r
     return MatrixClientSendToDevice(\r
 \r
     // send\r
     return MatrixClientSendToDevice(\r
@@ -821,9 +1013,16 @@ MatrixClientGetDeviceKey(
     const char * deviceId,\r
     char * outDeviceKey, int outDeviceKeyCap)\r
 {\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
     MatrixClientRequestDeviceKeys(client);\r
     \r
-    MatrixDevice * device;\r
     if (MatrixClientFindDevice(client, deviceId, &device))\r
     {\r
         strncpy(outDeviceKey, device->deviceKey, outDeviceKeyCap);\r
     if (MatrixClientFindDevice(client, deviceId, &device))\r
     {\r
         strncpy(outDeviceKey, device->deviceKey, outDeviceKeyCap);\r
@@ -838,68 +1037,65 @@ bool
 MatrixClientRequestDeviceKeys(\r
     MatrixClient * client)\r
 {\r
 MatrixClientRequestDeviceKeys(\r
     MatrixClient * client)\r
 {\r
-    char userIdEscaped[USER_ID_SIZE];\r
+    static char userIdEscaped[USER_ID_SIZE];\r
     JsonEscape(client->userId, strlen(client->userId),\r
         userIdEscaped, USER_ID_SIZE);\r
 \r
     JsonEscape(client->userId, strlen(client->userId),\r
         userIdEscaped, USER_ID_SIZE);\r
 \r
-    char request[KEYS_QUERY_REQUEST_SIZE];\r
+    static char request[KEYS_QUERY_REQUEST_SIZE];\r
     snprintf(request, KEYS_QUERY_REQUEST_SIZE,\r
     snprintf(request, KEYS_QUERY_REQUEST_SIZE,\r
-        "{\"device_keys\":{\"%s\":[]}}", userIdEscaped);\r
+        "{\"device_keys\":{\"%s\":[]}}", client->userId);\r
 \r
 \r
-    char responseBuffer[KEYS_QUERY_RESPONSE_SIZE];\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
     bool requestResult = MatrixHttpPost(client,\r
         KEYS_QUERY_URL,\r
         request,\r
         responseBuffer, KEYS_QUERY_RESPONSE_SIZE,\r
         true);\r
 \r
-    if (requestResult)\r
-    {\r
-        // query for retrieving device keys for user id\r
-        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
+    if (! requestResult)\r
+        return false;\r
 \r
 \r
-        // loop over keys\r
-        \r
-        int koff, klen, voff, vlen, vtype, off;\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
-            strncpy(d.deviceId, key, klen);\r
-\r
-            // look for device key in value\r
-            char deviceKeyQuery[JSON_QUERY_SIZE];\r
-            snprintf(deviceKeyQuery, JSON_QUERY_SIZE,\r
-                "$.keys.curve25519:%.*s", klen, key);\r
-            mjson_get_string(val, vlen,\r
-                deviceKeyQuery, d.deviceKey, DEVICE_KEY_SIZE);\r
-\r
-            // add device\r
-            if (client->numDevices < NUM_DEVICES)\r
-            {\r
-                client->devices[client->numDevices] = d;\r
-                client->numDevices++;\r
-            }\r
-            else\r
-            {\r
-                return false;\r
-            }\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
 \r
-        return true;\r
-    }\r
-    else\r
-    {\r
-        return false;\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
+        // add device\r
+        if (client->numDevices < NUM_DEVICES)\r
+        {\r
+            client->devices[client->numDevices] = d;\r
+            client->numDevices++;\r
+        }\r
+        else\r
+        {\r
+            return false;\r
+        }\r
     }\r
     }\r
+\r
+    return true;\r
 }\r
 }\r