X-Git-Url: https://gitweb.ps.run/matrix_esp_thesis/blobdiff_plain/504241758d7b832af61939beaf61b0e0574174c4..760426d17bc296232b9fedf7e114cb699e2697ae:/src/matrix.c diff --git a/src/matrix.c b/src/matrix.c index 147d919..fe8e1a3 100644 --- a/src/matrix.c +++ b/src/matrix.c @@ -4,13 +4,20 @@ #include #include +#ifdef ESP_PLATFORM +#include +#endif + +#define STATIC static #define LOGIN_REQUEST_SIZE 1024 #define LOGIN_RESPONSE_SIZE 1024 #define LOGIN_URL "/_matrix/client/v3/login" #define ENCRYPTED_REQUEST_SIZE (1024*5) +STATIC char g_EncryptedRequestBuffer[ENCRYPTED_REQUEST_SIZE]; #define ENCRYPTED_EVENT_SIZE (1024*10) +STATIC char g_EncryptedEventBuffer[ENCRYPTED_EVENT_SIZE]; #define ROOM_SEND_REQUEST_SIZE 256 #define ROOM_SEND_RESPONSE_SIZE 1024 #define ROOM_SEND_URL "/_matrix/client/v3/rooms/%s/send/%s/%d" @@ -18,37 +25,56 @@ #define ROOMKEY_REQUEST_SIZE (1024*4) #define TODEVICE_EVENT_SIZE (1024*5) +STATIC char g_TodeviceEventBuffer[TODEVICE_EVENT_SIZE]; #define TODEVICE_URL "/_matrix/client/v3/sendToDevice/%s/%d" #define KEYS_QUERY_URL "/_matrix/client/v3/keys/query" #define KEYS_QUERY_REQUEST_SIZE 256 -#define KEYS_QUERY_RESPONSE_SIZE (1024*10) +#define KEYS_QUERY_RESPONSE_SIZE (1024*5) #define KEYS_UPLOAD_URL "/_matrix/client/v3/keys/upload" #define KEYS_UPLOAD_REQUEST_SIZE 1024*4 +STATIC char g_KeysUploadRequestBuffer[KEYS_UPLOAD_REQUEST_SIZE]; #define KEYS_UPLOAD_REQUEST_SIGNED_SIZE 2048*4 +STATIC char g_KeysUploadRequestSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; #define KEYS_UPLOAD_RESPONSE_SIZE 2048 #define KEYS_CLAIM_URL "/_matrix/client/v3/keys/claim" #define KEYS_CLAIM_REQUEST_SIZE 1024 #define KEYS_CLAIM_RESPONSE_SIZE 1024 -#define JSON_QUERY_SIZE 128 +#define SYNC_TIMEOUT 5000 +#define JSON_QUERY_SIZE 128 +#define JSON_MAX_INDICES 100 +#define JSON_MAX_ENTRY_SIZE 1024 +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define MIN(a,b) ((a) < (b) ? (a) : (b)) void Randomize( uint8_t * random, int randomLen) { - static bool first = true; + #ifdef ESP_PLATFORM + + for (int i = 0; i < randomLen; i++) + { + random[i] = esp_random() % 256; + } + + #else + + STATIC bool first = true; if (first) { srand(time(0)); first = false; } for (int i = 0; i < randomLen; i++) { random[i] = rand() % 256; } + + #endif } bool @@ -78,12 +104,75 @@ JsonEscape( return true; } +bool +JsonCanonicalize( + const char * sIn, int sInLen, + char * sOut, int sOutCap) +{ + snprintf(sOut, sOutCap, "{}"); + + int koff, klen, voff, vlen, vtype, off; + + struct Key { + const char * ptr; + int len; + }; + + struct Key keys[JSON_MAX_INDICES]; + int numKeys = 0; + + for (off = 0; (off = mjson_next(sIn, sInLen, off, &koff, &klen, &voff, &vlen, &vtype)) != 0; ) { + keys[numKeys].ptr = sIn + koff; + keys[numKeys].len = klen; + numKeys++; + } + + for (int i = 0; i < numKeys; i++) { + for (int j = i; j < numKeys; j++) { + if ( + strncmp( + keys[i].ptr, + keys[j].ptr, + MIN(keys[i].len, keys[j].len) + ) > 0 + ) { + struct Key k = keys[i]; + keys[i] = keys[j]; + keys[j] = k; + } + } + } + + for (int i = 0; i < numKeys; i++) { + char jp[JSON_QUERY_SIZE]; + snprintf(jp, JSON_QUERY_SIZE, "$.%.*s", keys[i].len-2, keys[i].ptr+1); + + const char * valPtr; + int valLen; + mjson_find(sIn, sInLen, jp, &valPtr, &valLen); + + STATIC char newEntry[JSON_MAX_ENTRY_SIZE]; + snprintf(newEntry, JSON_MAX_ENTRY_SIZE, "{%.*s:%.*s}", keys[i].len, keys[i].ptr, valLen, valPtr); + + char * buffer = strdup(sOut); + + struct mjson_fixedbuf fb = { sOut, sOutCap, 0 }; + mjson_merge(buffer, strlen(buffer), newEntry, strlen(newEntry), mjson_print_fixed_buf, &fb); + + free(buffer); + } + + // TODO: recursively sort entries + + return true; +} + bool JsonSign( MatrixClient * client, const char * sIn, int sInLen, char * sOut, int sOutCap) { - static char signature[OLM_SIGNATURE_SIZE]; + STATIC char signature[OLM_SIGNATURE_SIZE]; size_t res = olm_account_sign(client->olmAccount.account, sIn, sInLen, @@ -91,10 +180,10 @@ bool JsonSign( int signatureLen = res; - static char thisSigningKey[SIGNING_KEY_SIZE]; + STATIC char thisSigningKey[SIGNING_KEY_SIZE]; MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, SIGNING_KEY_SIZE); - static char signatureJson[JSON_SIGNATURE_SIZE]; + STATIC char signatureJson[JSON_SIGNATURE_SIZE]; int signatureJsonLen = mjson_snprintf(signatureJson, JSON_SIGNATURE_SIZE, "{" @@ -126,7 +215,7 @@ MatrixOlmAccountInit( { account->account = olm_account(account->memory); - static uint8_t random[OLM_ACCOUNT_RANDOM_SIZE]; + STATIC uint8_t random[OLM_ACCOUNT_RANDOM_SIZE]; Randomize(random, OLM_ACCOUNT_RANDOM_SIZE); size_t res = olm_create_account( @@ -159,7 +248,7 @@ MatrixOlmAccountGetDeviceKey( MatrixOlmAccount * account, char * key, int keyCap) { - static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE]; + STATIC char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE]; size_t res = olm_account_identity_keys(account->account, deviceKeysJson, OLM_IDENTITY_KEYS_JSON_SIZE); @@ -174,7 +263,7 @@ MatrixOlmAccountGetSigningKey( MatrixOlmAccount * account, char * key, int keyCap) { - static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE]; + STATIC char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE]; size_t res = olm_account_identity_keys(account->account, deviceKeysJson, OLM_IDENTITY_KEYS_JSON_SIZE); @@ -184,7 +273,35 @@ MatrixOlmAccountGetSigningKey( return true; } -// TODO:in/outbound sessions +bool +MatrixOlmSessionFrom( + MatrixOlmSession * session, + OlmAccount * olmAccount, + const char * deviceId, + const char * deviceKey, + const char * encrypted) +{ + memset(session, 0, sizeof(MatrixOlmSession)); + + session->deviceId = deviceId; + + session->session = + olm_session(session->memory); + + char * encryptedCopy = strdup(encrypted); + + size_t res = + olm_create_inbound_session_from(session->session, olmAccount, + deviceKey, strlen(deviceKey), + encryptedCopy, strlen(encryptedCopy)); + + if (res == olm_error()) { + printf("error olm:%s\n", olm_session_last_error(session->session)); + } + + return res != olm_error(); +} + bool MatrixOlmSessionTo( MatrixOlmSession * session, @@ -200,7 +317,7 @@ MatrixOlmSessionTo( session->session = olm_session(session->memory); - static uint8_t random[OLM_OUTBOUND_SESSION_RANDOM_SIZE]; + STATIC uint8_t random[OLM_OUTBOUND_SESSION_RANDOM_SIZE]; Randomize(random, OLM_OUTBOUND_SESSION_RANDOM_SIZE); size_t res = @@ -214,7 +331,7 @@ MatrixOlmSessionTo( printf("error olm:%s\n", olm_session_last_error(session->session)); } - return session->session != NULL; + return res != olm_error(); } bool @@ -249,7 +366,7 @@ MatrixOlmSessionEncrypt( const char * plaintext, char * outBuffer, int outBufferCap) { - static uint8_t random[OLM_ENCRYPT_RANDOM_SIZE]; + STATIC uint8_t random[OLM_ENCRYPT_RANDOM_SIZE]; Randomize(random, OLM_ENCRYPT_RANDOM_SIZE); size_t res = olm_encrypt(session->session, @@ -267,7 +384,7 @@ MatrixOlmSessionDecrypt( char * encrypted, char * outBuffer, int outBufferCap) { - static uint8_t random[OLM_ENCRYPT_RANDOM_SIZE]; + STATIC uint8_t random[OLM_ENCRYPT_RANDOM_SIZE]; Randomize(random, OLM_ENCRYPT_RANDOM_SIZE); size_t res = @@ -277,11 +394,68 @@ MatrixOlmSessionDecrypt( outBuffer, outBufferCap); if (res != olm_error() && res < outBufferCap) - outBuffer[outBufferCap] = '\0'; + outBuffer[res] = '\0'; return res != olm_error(); } +bool +MatrixMegolmInSessionInit( + MatrixMegolmInSession * session, + const char * roomId, + const char * sessionId, + const char * sessionKey, int sessionKeyLen) +{ + memset(session, 0, sizeof(MatrixMegolmInSession)); + + strncpy(session->roomId, roomId, sizeof(session->roomId)); + strncpy(session->id, sessionId, sizeof(session->id)); + strncpy(session->key, sessionKey, sizeof(session->key)); + + session->session = + olm_inbound_group_session(session->memory); + + size_t res = + olm_init_inbound_group_session( + // olm_import_inbound_group_session( + session->session, + (const uint8_t *)sessionKey, sessionKeyLen); + if (res == olm_error()) { + printf("Error initializing Megolm session: %s\n", olm_inbound_group_session_last_error(session->session)); + } + + return res != olm_error(); +} + +bool +MatrixMegolmInSessionDecrypt( + MatrixMegolmInSession * session, + const char * encrypted, int encryptedLen, + char * outDecrypted, int outDecryptedCap) +{ + // uint8_t buffer[1024]; + // memcpy(buffer, encrypted, encryptedLen); + + uint32_t megolmInMessageIndex; + + size_t res = + olm_group_decrypt(session->session, + (uint8_t *)encrypted, encryptedLen, + (uint8_t *)outDecrypted, outDecryptedCap, + &megolmInMessageIndex); + + printf("message index: %d\n", (int)megolmInMessageIndex); + + if (res == olm_error()) { + printf("error decrypting megolm message: %s\n", olm_inbound_group_session_last_error(session->session)); + } + else { + printf("decrypted len: %d\n", res); + } + + return true; +} + // https://matrix.org/docs/guides/end-to-end-encryption-implementation-guide#starting-a-megolm-session bool MatrixMegolmOutSessionInit( @@ -290,7 +464,7 @@ MatrixMegolmOutSessionInit( { memset(session, 0, sizeof(MatrixMegolmOutSession)); - static uint8_t random[MEGOLM_INIT_RANDOM_SIZE]; + STATIC uint8_t random[MEGOLM_INIT_RANDOM_SIZE]; Randomize(random, MEGOLM_INIT_RANDOM_SIZE); strncpy(session->roomId, roomId, ROOM_ID_SIZE); @@ -397,13 +571,10 @@ MatrixMegolmOutSessionLoad( bool MatrixClientInit( - MatrixClient * client, - const char * server) + MatrixClient * client) { memset(client, 0, sizeof(MatrixClient)); - strcpy(client->server, server); - // init olm account MatrixOlmAccountInit(&client->olmAccount); @@ -427,7 +598,6 @@ MatrixClientSave( fwrite(thisDeviceKey, 1, DEVICE_KEY_SIZE, f); fwrite(thisSigningKey, 1, DEVICE_KEY_SIZE, f); fwrite(client->userId, 1, USER_ID_SIZE, f); - fwrite(client->server, 1, SERVER_SIZE, f); fwrite(client->accessToken, 1, ACCESS_TOKEN_SIZE, f); fwrite(client->deviceId, 1, DEVICE_ID_SIZE, f); fwrite(client->expireMs, 1, EXPIRE_MS_SIZE, f); @@ -460,7 +630,6 @@ MatrixClientLoad( fread(thisDeviceKey, 1, DEVICE_KEY_SIZE, f); fread(thisSigningKey, 1, DEVICE_KEY_SIZE, f); fread(client->userId, 1, USER_ID_SIZE, f); - fread(client->server, 1, SERVER_SIZE, f); fread(client->accessToken, 1, ACCESS_TOKEN_SIZE, f); fread(client->deviceId, 1, DEVICE_ID_SIZE, f); fread(client->expireMs, 1, EXPIRE_MS_SIZE, f); @@ -517,7 +686,7 @@ MatrixClientGenerateOnetimeKeys( MatrixClient * client, int numberOfKeys) { - static uint8_t random[OLM_ONETIME_KEYS_RANDOM_SIZE]; + STATIC uint8_t random[OLM_ONETIME_KEYS_RANDOM_SIZE]; Randomize(random, OLM_ONETIME_KEYS_RANDOM_SIZE); size_t res = @@ -532,12 +701,10 @@ bool MatrixClientUploadOnetimeKeys( MatrixClient * client) { - static char requestBuffer[KEYS_UPLOAD_REQUEST_SIZE]; - - mjson_snprintf(requestBuffer, KEYS_UPLOAD_REQUEST_SIZE, + mjson_snprintf(g_KeysUploadRequestBuffer, KEYS_UPLOAD_REQUEST_SIZE, "{"); - static char onetimeKeysBuffer[1024]; + STATIC char onetimeKeysBuffer[1024]; olm_account_one_time_keys(client->olmAccount.account, onetimeKeysBuffer, 1024); @@ -547,52 +714,49 @@ MatrixClientUploadOnetimeKeys( int koff, klen, voff, vlen, vtype, off = 0; while ((off = mjson_next(keys, keysLen, off, &koff, &klen, &voff, &vlen, &vtype)) != 0) { - static char keyJson[JSON_ONETIME_KEY_SIZE]; + STATIC char keyJson[JSON_ONETIME_KEY_SIZE]; int keyJsonLen = snprintf(keyJson, JSON_ONETIME_KEY_SIZE, "{\"key\":\"%.*s\"}", vlen-2, keys + voff+1); - static char keyJsonSigned[JSON_ONETIME_KEY_SIGNED_SIZE]; + STATIC char keyJsonSigned[JSON_ONETIME_KEY_SIGNED_SIZE]; JsonSign(client, keyJson, keyJsonLen, keyJsonSigned, JSON_ONETIME_KEY_SIGNED_SIZE); - mjson_snprintf(requestBuffer+strlen(requestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer), + mjson_snprintf(g_KeysUploadRequestBuffer+strlen(g_KeysUploadRequestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(g_KeysUploadRequestBuffer), "\"signed_curve25519:%.*s\":%s,", klen-2, keys + koff+1, keyJsonSigned); } - if (requestBuffer[strlen(requestBuffer)-1] == ',') - requestBuffer[strlen(requestBuffer)-1] = '\0'; + if (g_KeysUploadRequestBuffer[strlen(g_KeysUploadRequestBuffer)-1] == ',') + g_KeysUploadRequestBuffer[strlen(g_KeysUploadRequestBuffer)-1] = '\0'; - mjson_snprintf(requestBuffer+strlen(requestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer), + mjson_snprintf(g_KeysUploadRequestBuffer+strlen(g_KeysUploadRequestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(g_KeysUploadRequestBuffer), "}"); - // static char onetimeKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; + // STATIC char onetimeKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; // JsonSign(client, - // requestBuffer, strlen(requestBuffer), + // g_KeysUploadRequestBuffer, strlen(g_KeysUploadRequestBuffer), // onetimeKeysSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE); - // static char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; + // STATIC char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; // snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE, // "{\"one_time_keys\":%s}", onetimeKeysSignedBuffer); - static char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; - snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE, - "{\"one_time_keys\":%s}", requestBuffer); + snprintf(g_KeysUploadRequestSignedBuffer, KEYS_UPLOAD_REQUEST_SIGNED_SIZE, + "{\"one_time_keys\":%s}", g_KeysUploadRequestBuffer); - static char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE]; - MatrixHttpPost(client, + STATIC char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE]; + MatrixHttpPost(client->hc, KEYS_UPLOAD_URL, - finalEvent, + g_KeysUploadRequestSignedBuffer, responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE, true); - printf("%s\n", responseBuffer); - return true; } @@ -606,10 +770,8 @@ MatrixClientUploadDeviceKey( char thisSigningKey[DEVICE_KEY_SIZE]; MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE); - static char deviceKeysBuffer[KEYS_UPLOAD_REQUEST_SIZE]; - int deviceKeysBufferLen = - mjson_snprintf(deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE, + mjson_snprintf(g_KeysUploadRequestBuffer, KEYS_UPLOAD_REQUEST_SIZE, "{" "\"algorithms\":[\"m.olm.v1.curve25519-aes-sha2\",\"m.megolm.v1.aes-sha2\"]," "\"device_id\":\"%s\"," @@ -624,23 +786,20 @@ MatrixClientUploadDeviceKey( client->deviceId, thisSigningKey, client->userId); - static char deviceKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; JsonSign(client, - deviceKeysBuffer, deviceKeysBufferLen, - deviceKeysSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE); + g_KeysUploadRequestBuffer, deviceKeysBufferLen, + g_KeysUploadRequestSignedBuffer, KEYS_UPLOAD_REQUEST_SIZE); - static char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; - snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE, - "{\"device_keys\":%s}", deviceKeysSignedBuffer); + STATIC char finalEvent[KEYS_UPLOAD_REQUEST_SIGNED_SIZE+30]; + snprintf(finalEvent, KEYS_UPLOAD_REQUEST_SIGNED_SIZE+30, + "{\"device_keys\":%s}", g_KeysUploadRequestSignedBuffer); - static char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE]; - MatrixHttpPost(client, + STATIC char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE]; + MatrixHttpPost(client->hc, KEYS_UPLOAD_URL, finalEvent, responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE, true); - - printf("%s\n", responseBuffer); return true; } @@ -653,7 +812,7 @@ MatrixClientClaimOnetimeKey( const char * deviceId, char * outOnetimeKey, int outOnetimeKeyCap) { - static char requestBuffer[KEYS_CLAIM_REQUEST_SIZE]; + STATIC char requestBuffer[KEYS_CLAIM_REQUEST_SIZE]; mjson_snprintf(requestBuffer, KEYS_CLAIM_REQUEST_SIZE, "{" "\"one_time_keys\":{" @@ -666,18 +825,18 @@ MatrixClientClaimOnetimeKey( userId, deviceId); - static char responseBuffer[KEYS_CLAIM_RESPONSE_SIZE]; - MatrixHttpPost(client, + STATIC char responseBuffer[KEYS_CLAIM_RESPONSE_SIZE]; + MatrixHttpPost(client->hc, KEYS_CLAIM_URL, requestBuffer, responseBuffer, KEYS_CLAIM_RESPONSE_SIZE, true); - char userIdEscaped[USER_ID_SIZE]; + STATIC char userIdEscaped[USER_ID_SIZE]; JsonEscape(userId, strlen(userId), userIdEscaped, USER_ID_SIZE); - static char query[JSON_QUERY_SIZE]; + STATIC char query[JSON_QUERY_SIZE]; snprintf(query, JSON_QUERY_SIZE, "$.one_time_keys.%s.%s", userIdEscaped, @@ -709,7 +868,7 @@ MatrixClientLoginPassword( const char * password, const char * displayName) { - static char requestBuffer[LOGIN_REQUEST_SIZE]; + STATIC char requestBuffer[LOGIN_REQUEST_SIZE]; mjson_snprintf(requestBuffer, LOGIN_REQUEST_SIZE, "{" @@ -725,9 +884,9 @@ MatrixClientLoginPassword( password, displayName); - static char responseBuffer[LOGIN_RESPONSE_SIZE]; + STATIC char responseBuffer[LOGIN_RESPONSE_SIZE]; bool result = - MatrixHttpPost(client, + MatrixHttpPost(client->hc, LOGIN_URL, requestBuffer, responseBuffer, LOGIN_RESPONSE_SIZE, @@ -750,6 +909,8 @@ MatrixClientLoginPassword( mjson_get_string(responseBuffer, responseLen, "$.refresh_token", client->refreshToken, REFRESH_TOKEN_SIZE); + + MatrixHttpSetAccessToken(client->hc, client->accessToken); return true; } @@ -762,13 +923,13 @@ MatrixClientSendEvent( const char * msgType, const char * msgBody) { - static char requestUrl[MAX_URL_LEN]; + STATIC char requestUrl[MAX_URL_LEN]; sprintf(requestUrl, ROOM_SEND_URL, roomId, msgType, (int)time(NULL)); - static char responseBuffer[ROOM_SEND_RESPONSE_SIZE]; + STATIC char responseBuffer[ROOM_SEND_RESPONSE_SIZE]; bool result = - MatrixHttpPut(client, + MatrixHttpPut(client->hc, requestUrl, msgBody, responseBuffer, ROOM_SEND_RESPONSE_SIZE, @@ -787,7 +948,7 @@ MatrixClientSendEventEncrypted( const char * msgBody) { // event json - static char requestBuffer[ROOM_SEND_REQUEST_SIZE]; + STATIC char requestBuffer[ROOM_SEND_REQUEST_SIZE]; sprintf(requestBuffer, "{" "\"type\":\"%s\"," @@ -800,13 +961,13 @@ MatrixClientSendEventEncrypted( // get megolm session MatrixMegolmOutSession * outSession; - MatrixClientGetMegolmOutSession(client, roomId, &outSession); + if (! MatrixClientGetMegolmOutSession(client, roomId, &outSession)) + MatrixClientNewMegolmOutSession(client, roomId, &outSession); // encrypt - static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE]; MatrixMegolmOutSessionEncrypt(outSession, requestBuffer, - encryptedBuffer, ENCRYPTED_REQUEST_SIZE); + g_EncryptedRequestBuffer, ENCRYPTED_REQUEST_SIZE); char thisDeviceKey[DEVICE_KEY_SIZE]; MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE); @@ -817,8 +978,7 @@ MatrixClientSendEventEncrypted( const char * sessionId = outSession->id; const char * deviceId = client->deviceId; - static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE]; - sprintf(encryptedEventBuffer, + snprintf(g_EncryptedEventBuffer, ENCRYPTED_EVENT_SIZE, "{" "\"algorithm\":\"m.megolm.v1.aes-sha2\"," "\"ciphertext\":\"%s\"," @@ -826,7 +986,7 @@ MatrixClientSendEventEncrypted( "\"sender_key\":\"%s\"," "\"session_id\":\"%s\"" "}", - encryptedBuffer, + g_EncryptedRequestBuffer, deviceId, senderKey, sessionId); @@ -835,7 +995,7 @@ MatrixClientSendEventEncrypted( return MatrixClientSendEvent(client, roomId, "m.room.encrypted", - encryptedEventBuffer); + g_EncryptedEventBuffer); } // https://spec.matrix.org/v1.6/client-server-api/#get_matrixclientv3sync @@ -846,14 +1006,17 @@ MatrixClientSync( const char * nextBatch) { // filter={\"event_fields\":[\"to_device\"]} - static char url[MAX_URL_LEN]; + STATIC char url[MAX_URL_LEN]; snprintf(url, MAX_URL_LEN, - "/_matrix/client/v3/sync%s", - strlen(nextBatch) > 0 ? "?since=" : ""); + "/_matrix/client/v3/sync?timeout=%d" "%s" "%s", + SYNC_TIMEOUT, + "", + // "&filter={\"event_fields\":[\"to_device\"]}", + strlen(nextBatch) > 0 ? "&since=" : ""); int index = strlen(url); - for (int i = 0; i < strlen(nextBatch); i++) { + for (size_t i = 0; i < strlen(nextBatch); i++) { char c = nextBatch[i]; if (c == '~') { @@ -868,7 +1031,7 @@ MatrixClientSync( url[index] = '\0'; return - MatrixHttpGet(client, + MatrixHttpGet(client->hc, url, outSyncBuffer, outSyncCap, true); @@ -882,14 +1045,14 @@ MatrixClientGetRoomEvent( const char * eventId, char * outEvent, int outEventCap) { - static char url[MAX_URL_LEN]; + STATIC char url[MAX_URL_LEN]; snprintf(url, MAX_URL_LEN, "/_matrix/client/v3/rooms/%s/event/%s", roomId, eventId); return - MatrixHttpGet(client, + MatrixHttpGet(client->hc, url, outEvent, outEventCap, true); @@ -903,7 +1066,7 @@ MatrixClientShareMegolmOutSession( MatrixMegolmOutSession * session) { // generate room key event - static char eventBuffer[KEY_SHARE_EVENT_LEN]; + STATIC char eventBuffer[KEY_SHARE_EVENT_LEN]; sprintf(eventBuffer, "{" "\"algorithm\":\"m.megolm.v1.aes-sha2\"," @@ -916,16 +1079,6 @@ MatrixClientShareMegolmOutSession( session->key ); - // // get olm session - // MatrixOlmSession * olmSession; - // MatrixClientGetOlmSession(client, userId, deviceId, &olmSession); - - // // encrypt - // char encryptedBuffer[KEY_SHARE_EVENT_LEN]; - // MatrixOlmSessionEncrypt(olmSession, - // eventBuffer, - // encryptedBuffer, KEY_SHARE_EVENT_LEN); - // send MatrixClientSendToDeviceEncrypted(client, userId, @@ -967,23 +1120,6 @@ MatrixClientShareMegolmOutSessionTest( return true; } -// bool -// MatrixClientSetMegolmOutSession( -// MatrixClient * client, -// const char * roomId, -// MatrixMegolmOutSession session) -// { -// if (client->numMegolmOutSessions < 10) -// { -// session.roomId = roomId; -// client->megolmOutSessions[client->numMegolmOutSessions] = session; -// client->numMegolmOutSessions++; - -// return true; -// } -// return false; -// } - bool MatrixClientGetMegolmOutSession( MatrixClient * client, @@ -999,8 +1135,27 @@ MatrixClientGetMegolmOutSession( } } - if (MatrixClientInitMegolmOutSession(client, roomId)) { - *outSession = &client->megolmOutSessions[client->numMegolmOutSessions-1]; + return false; +} + +bool +MatrixClientNewMegolmOutSession( + MatrixClient * client, + const char * roomId, + MatrixMegolmOutSession ** outSession) +{ + if (client->numMegolmOutSessions < NUM_MEGOLM_SESSIONS) + { + MatrixMegolmOutSession * result = + &client->megolmOutSessions[client->numMegolmOutSessions]; + + MatrixMegolmOutSessionInit(result, + roomId); + + *outSession = result; + + client->numMegolmOutSessions++; + return true; } @@ -1008,20 +1163,50 @@ MatrixClientGetMegolmOutSession( } bool -MatrixClientInitMegolmOutSession( +MatrixClientGetMegolmInSession( MatrixClient * client, - const char * roomId) + const char * roomId, int roomIdLen, + const char * sessionId, int sessionIdLen, + MatrixMegolmInSession ** outSession) { - if (client->numMegolmOutSessions < NUM_MEGOLM_SESSIONS) + for (int i = 0; i < client->numMegolmInSessions; i++) { - MatrixMegolmOutSessionInit( - &client->megolmOutSessions[client->numMegolmOutSessions], - roomId); + if (strncmp(client->megolmInSessions[i].roomId, roomId, roomIdLen) == 0 && + strncmp(client->megolmInSessions[i].id, sessionId, sessionIdLen) == 0) + { + *outSession = &client->megolmInSessions[i]; + return true; + } + } + + return false; +} + +bool +MatrixClientNewMegolmInSession( + MatrixClient * client, + const char * roomId, + const char * sessionId, + const char * sessionKey, + MatrixMegolmInSession ** outSession) +{ + if (client->numMegolmInSessions < NUM_MEGOLM_SESSIONS) + { + MatrixMegolmInSession * result = + &client->megolmInSessions[client->numMegolmInSessions]; - client->numMegolmOutSessions++; + MatrixMegolmInSessionInit(result, + roomId, + sessionId, + sessionKey, strlen(sessionKey)); + + *outSession = result; + + client->numMegolmInSessions++; return true; } + return false; } @@ -1032,13 +1217,12 @@ MatrixClientRequestMegolmInSession( const char * sessionId, const char * senderKey, const char * userId, - const char * deviceId, - MatrixMegolmInSession * outMegolmInSession) + const char * deviceId) { // TODO: cancel requests MatrixClientSendDummy(client, userId, deviceId); - static char event[ROOMKEY_REQUEST_SIZE]; + STATIC char event[ROOMKEY_REQUEST_SIZE]; snprintf(event, ROOMKEY_REQUEST_SIZE, "{" "\"action\":\"request\"," @@ -1048,7 +1232,7 @@ MatrixClientRequestMegolmInSession( "\"sender_key\":\"%s\"," "\"session_id\":\"%s\"" "}," - "\"request_id\":\"%d\"," + "\"request_id\":\"%lld\"," "\"requesting_device_id\":\"%s\"" "}", roomId, @@ -1083,9 +1267,51 @@ MatrixClientGetOlmSession( } } + return false; +} + +bool +MatrixClientNewOlmSessionIn( + MatrixClient * client, + const char * userId, + const char * deviceId, + const char * encrypted, + MatrixOlmSession ** outSession) +{ + if (client->numOlmSessions < NUM_OLM_SESSIONS) + { + STATIC char deviceKey[DEVICE_KEY_SIZE]; + MatrixClientRequestDeviceKey(client, + deviceId, + deviceKey, DEVICE_KEY_SIZE); + + MatrixOlmSessionFrom( + &client->olmSessions[client->numOlmSessions], + client->olmAccount.account, + deviceId, + deviceKey, + encrypted); + + *outSession = &client->olmSessions[client->numOlmSessions]; + + client->numOlmSessions++; + + return true; + } + + return false; +} + +bool +MatrixClientNewOlmSessionOut( + MatrixClient * client, + const char * userId, + const char * deviceId, + MatrixOlmSession ** outSession) +{ if (client->numOlmSessions < NUM_OLM_SESSIONS) { - static char deviceKey[DEVICE_KEY_SIZE]; + STATIC char deviceKey[DEVICE_KEY_SIZE]; MatrixClientRequestDeviceKey(client, deviceId, deviceKey, DEVICE_KEY_SIZE); @@ -1122,12 +1348,11 @@ MatrixClientSendToDevice( const char * message, const char * msgType) { - static char requestUrl[MAX_URL_LEN]; + STATIC char requestUrl[MAX_URL_LEN]; sprintf(requestUrl, TODEVICE_URL, msgType, (int)time(NULL)); - static char eventBuffer[TODEVICE_EVENT_SIZE]; - snprintf(eventBuffer, TODEVICE_EVENT_SIZE, + snprintf(g_TodeviceEventBuffer, TODEVICE_EVENT_SIZE, "{" "\"messages\":{" "\"%s\":{" @@ -1139,11 +1364,11 @@ MatrixClientSendToDevice( deviceId, message); - static char responseBuffer[ROOM_SEND_RESPONSE_SIZE]; + STATIC char responseBuffer[ROOM_SEND_RESPONSE_SIZE]; bool result = - MatrixHttpPut(client, + MatrixHttpPut(client->hc, requestUrl, - eventBuffer, + g_TodeviceEventBuffer, responseBuffer, ROOM_SEND_RESPONSE_SIZE, true); @@ -1162,7 +1387,8 @@ MatrixClientSendToDeviceEncrypted( { // get olm session MatrixOlmSession * olmSession; - MatrixClientGetOlmSession(client, userId, deviceId, &olmSession); + if (! MatrixClientGetOlmSession(client, userId, deviceId, &olmSession)) + MatrixClientNewOlmSessionOut(client, userId, deviceId, &olmSession); // create event json char targetDeviceKey[DEVICE_KEY_SIZE]; @@ -1173,8 +1399,7 @@ MatrixClientSendToDeviceEncrypted( char thisSigningKey[DEVICE_KEY_SIZE]; MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE); - static char eventBuffer[TODEVICE_EVENT_SIZE]; - sprintf(eventBuffer, + snprintf(g_TodeviceEventBuffer, TODEVICE_EVENT_SIZE, "{" "\"type\":\"%s\"," "\"content\":%s," @@ -1193,21 +1418,16 @@ MatrixClientSendToDeviceEncrypted( userId, // recipient user id targetSigningKey, // recipient device key thisSigningKey); - - printf("%s\n", eventBuffer); // encrypt - static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE]; MatrixOlmSessionEncrypt(olmSession, - eventBuffer, - encryptedBuffer, ENCRYPTED_REQUEST_SIZE); + g_TodeviceEventBuffer, + g_EncryptedRequestBuffer, ENCRYPTED_REQUEST_SIZE); char thisDeviceKey[DEVICE_KEY_SIZE]; MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE); - - static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE]; - sprintf(encryptedEventBuffer, + snprintf(g_EncryptedEventBuffer, ENCRYPTED_EVENT_SIZE, "{" "\"algorithm\":\"m.olm.v1.curve25519-aes-sha2\"," "\"ciphertext\":{" @@ -1220,7 +1440,7 @@ MatrixClientSendToDeviceEncrypted( "\"sender_key\":\"%s\"" "}", targetDeviceKey, - encryptedBuffer, + g_EncryptedRequestBuffer, olm_session_has_received_message(olmSession->session), client->deviceId, thisDeviceKey); @@ -1230,7 +1450,7 @@ MatrixClientSendToDeviceEncrypted( client, userId, deviceId, - encryptedEventBuffer, + g_EncryptedEventBuffer, "m.room.encrypted"); } @@ -1324,16 +1544,21 @@ bool MatrixClientRequestDeviceKeys( MatrixClient * client) { - static char userIdEscaped[USER_ID_SIZE]; + if (client->numDevices >= NUM_DEVICES) { + printf("Maximum number of devices reached\n"); + return false; + } + + STATIC char userIdEscaped[USER_ID_SIZE]; JsonEscape(client->userId, strlen(client->userId), userIdEscaped, USER_ID_SIZE); - static char request[KEYS_QUERY_REQUEST_SIZE]; + STATIC char request[KEYS_QUERY_REQUEST_SIZE]; snprintf(request, KEYS_QUERY_REQUEST_SIZE, "{\"device_keys\":{\"%s\":[]}}", client->userId); - static char responseBuffer[KEYS_QUERY_RESPONSE_SIZE]; - bool requestResult = MatrixHttpPost(client, + STATIC char responseBuffer[KEYS_QUERY_RESPONSE_SIZE]; + bool requestResult = MatrixHttpPost(client->hc, KEYS_QUERY_URL, request, responseBuffer, KEYS_QUERY_RESPONSE_SIZE, @@ -1342,10 +1567,8 @@ MatrixClientRequestDeviceKeys( if (! requestResult) return false; - printf("keys:\n%s\n", responseBuffer); - // query for retrieving device keys for user id - static char query[JSON_QUERY_SIZE]; + STATIC char query[JSON_QUERY_SIZE]; snprintf(query, JSON_QUERY_SIZE, "$.device_keys.%s", userIdEscaped); @@ -1368,14 +1591,14 @@ MatrixClientRequestDeviceKeys( "%.*s", klen-2, key+1); // look for device key in value - static char deviceKeyQuery[JSON_QUERY_SIZE]; + STATIC char deviceKeyQuery[JSON_QUERY_SIZE]; snprintf(deviceKeyQuery, JSON_QUERY_SIZE, "$.keys.curve25519:%s", d.deviceId); mjson_get_string(val, vlen, deviceKeyQuery, d.deviceKey, DEVICE_KEY_SIZE); // look for signing key in value - static char signingKeyQuery[JSON_QUERY_SIZE]; + STATIC char signingKeyQuery[JSON_QUERY_SIZE]; snprintf(signingKeyQuery, JSON_QUERY_SIZE, "$.keys.ed25519:%s", d.deviceId); mjson_get_string(val, vlen, @@ -1408,12 +1631,12 @@ bool MatrixClientDeleteDevice( MatrixClient * client) { - static char deleteRequest[1024]; + STATIC char deleteRequest[1024]; snprintf(deleteRequest, 1024, "{\"devices\":[\"%s\"]}", client->deviceId); - static char deleteResponse[1024]; - bool res = MatrixHttpPost(client, "/_matrix/client/v3/delete_devices", + STATIC char deleteResponse[1024]; + bool res = MatrixHttpPost(client->hc, "/_matrix/client/v3/delete_devices", deleteRequest, deleteResponse, 1024, true); return res; } \ No newline at end of file