X-Git-Url: https://gitweb.ps.run/matrix_esp_thesis/blobdiff_plain/a6eff84624ab1f3786d02aa2ec740b9a88090d94..8d8ae609f0201ec4640738ff49b768e899695423:/src/matrix.c diff --git a/src/matrix.c b/src/matrix.c index 1f5ed2d..06409b8 100644 --- a/src/matrix.c +++ b/src/matrix.c @@ -9,24 +9,28 @@ #define LOGIN_RESPONSE_SIZE 1024 #define LOGIN_URL "/_matrix/client/v3/login" -#define ENCRYPTED_REQUEST_SIZE 512 -#define ENCRYPTED_EVENT_SIZE 1024 +#define ENCRYPTED_REQUEST_SIZE (1024*5) +#define ENCRYPTED_EVENT_SIZE (1024*10) #define ROOMEVENT_REQUEST_SIZE 256 #define ROOMEVENT_RESPONSE_SIZE 1024 #define ROOMEVENT_URL "/_matrix/client/v3/rooms/%s/send/%s/%d" -#define TODEVICE_EVENT_SIZE 512 +#define TODEVICE_EVENT_SIZE (1024*5) #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 +#define KEYS_QUERY_RESPONSE_SIZE (1024*10) #define KEYS_UPLOAD_URL "/_matrix/client/v3/keys/upload" -#define KEYS_UPLOAD_REQUEST_SIZE 1024 -#define KEYS_UPLOAD_REQUEST_SIGNED_SIZE 2048 +#define KEYS_UPLOAD_REQUEST_SIZE 1024*4 +#define KEYS_UPLOAD_REQUEST_SIGNED_SIZE 2048*4 #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 @@ -36,7 +40,7 @@ Randomize( uint8_t * random, int randomLen) { - static bool first = false; + static bool first = true; if (first) { srand(time(0)); first = false; } for (int i = 0; i < randomLen; i++) @@ -47,7 +51,7 @@ Randomize( bool JsonEscape( - char * sIn, int sInLen, + const char * sIn, int sInLen, char * sOut, int sOutCap) { int sOutIndex = 0; @@ -74,7 +78,7 @@ JsonEscape( bool JsonSign( MatrixClient * client, - char * sIn, int sInLen, + const char * sIn, int sInLen, char * sOut, int sOutCap) { static char signature[OLM_SIGNATURE_SIZE]; @@ -84,6 +88,9 @@ bool JsonSign( signature, OLM_SIGNATURE_SIZE); int signatureLen = res; + + char thisSigningKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE); static char signatureJson[JSON_SIGNATURE_SIZE]; int signatureJsonLen = @@ -96,7 +103,7 @@ bool JsonSign( "}" "}", client->userId, - client->deviceId, + "1", signatureLen, signature); struct mjson_fixedbuf result = { sOut, sOutCap, 0 }; @@ -127,25 +134,112 @@ MatrixOlmAccountInit( return res != olm_error(); } -// TODO: in/outbound sessions bool -MatrixOlmSessionInit( +MatrixOlmAccountUnpickle( + MatrixOlmAccount * account, + void * pickled, int pickledLen, + const void * key, int keyLen) +{ + size_t res; + res = olm_unpickle_account(account->account, + key, keyLen, + pickled, pickledLen); + if (res == olm_error()) { + printf("error unpickling olm account:%s\n", + olm_account_last_error(account->account)); + } + return res != olm_error(); +} + +bool +MatrixOlmAccountGetDeviceKey( + MatrixOlmAccount * account, + char * key, int keyCap) +{ + static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE]; + size_t res = + olm_account_identity_keys(account->account, + deviceKeysJson, OLM_IDENTITY_KEYS_JSON_SIZE); + mjson_get_string(deviceKeysJson, res, + "$.curve25519", + key, keyCap); + return true; +} + +bool +MatrixOlmAccountGetSigningKey( + MatrixOlmAccount * account, + char * key, int keyCap) +{ + static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE]; + size_t res = + olm_account_identity_keys(account->account, + deviceKeysJson, OLM_IDENTITY_KEYS_JSON_SIZE); + mjson_get_string(deviceKeysJson, res, + "$.ed25519", + key, keyCap); + return true; +} + +// TODO:in/outbound sessions +bool +MatrixOlmSessionTo( MatrixOlmSession * session, - const char * deviceId) + OlmAccount * olmAccount, + const char * deviceId, + const char * deviceKey, + const char * deviceOnetimeKey) { memset(session, 0, sizeof(MatrixOlmSession)); - static uint8_t random[MEGOLM_INIT_RANDOM_SIZE]; - Randomize(random, MEGOLM_INIT_RANDOM_SIZE); - session->deviceId = deviceId; session->session = olm_session(session->memory); + static uint8_t random[OLM_OUTBOUND_SESSION_RANDOM_SIZE]; + Randomize(random, OLM_OUTBOUND_SESSION_RANDOM_SIZE); + + size_t res = + olm_create_outbound_session(session->session, + olmAccount, + deviceKey, strlen(deviceKey), + deviceOnetimeKey, strlen(deviceOnetimeKey), + random, OLM_OUTBOUND_SESSION_RANDOM_SIZE); + + if (res == olm_error()) { + printf("error olm:%s\n", olm_session_last_error(session->session)); + } + return session->session != NULL; } +bool +MatrixOlmSessionUnpickle( + MatrixOlmSession * session, + const char * deviceId, + void * pickled, int pickledLen, + const void * key, int keyLen) +{ + memset(session, 0, sizeof(MatrixOlmSession)); + + session->deviceId = deviceId; + + session->session = + olm_session(session->memory); + + size_t res; + res = olm_unpickle_session(session->session, + key, keyLen, + pickled, pickledLen); + + if (res == olm_error()) { + printf("error unpickling olm session:%s\n", olm_session_last_error(session->session)); + } + + return res != olm_error(); +} + bool MatrixOlmSessionEncrypt( MatrixOlmSession * session, @@ -174,7 +268,7 @@ MatrixMegolmOutSessionInit( static uint8_t random[MEGOLM_INIT_RANDOM_SIZE]; Randomize(random, MEGOLM_INIT_RANDOM_SIZE); - session->roomId = roomId; + strncpy(session->roomId, roomId, ROOM_ID_SIZE); session->session = olm_outbound_group_session(session->memory); @@ -208,6 +302,72 @@ MatrixMegolmOutSessionEncrypt( return res != olm_error(); } +bool +MatrixMegolmOutSessionSave( + MatrixMegolmOutSession * session, + const char * filename, + const char * key) +{ + FILE * f = fopen(filename, "w"); + + size_t roomIdLen = strlen(session->roomId); + fwrite(&roomIdLen, sizeof(size_t), 1, f); + fwrite(session->roomId, 1, roomIdLen, f); + + size_t pickleBufferLen = + olm_pickle_outbound_group_session_length( + session->session); + void * pickleBuffer = malloc(pickleBufferLen); + + olm_pickle_outbound_group_session( + session->session, + key, strlen(key), + pickleBuffer, pickleBufferLen); + + fwrite(&pickleBufferLen, sizeof(size_t), 1, f); + fwrite(pickleBuffer, 1, pickleBufferLen, f); + free(pickleBuffer); + + fclose(f); + + return true; +} + +bool +MatrixMegolmOutSessionLoad( + MatrixMegolmOutSession * session, + const char * filename, + const char * key) +{ + FILE * f = fopen(filename, "r"); + + size_t roomIdLen; + fread(&roomIdLen, sizeof(size_t), 1, f); + fread(session->roomId, 1, roomIdLen, f); + for (int i = roomIdLen; i < ROOM_ID_SIZE; i++) + session->roomId[i] = '\0'; + + size_t pickleBufferLen; + fread(&pickleBufferLen, sizeof(size_t), 1, f); + + void * pickleBuffer = malloc(pickleBufferLen); + fread(pickleBuffer, 1, pickleBufferLen, f); + + olm_unpickle_outbound_group_session( + session->session, + key, strlen(key), + pickleBuffer, pickleBufferLen); + + free(pickleBuffer); + + olm_outbound_group_session_id(session->session, (uint8_t *)session->id, MEGOLM_SESSION_ID_SIZE); + olm_outbound_group_session_key(session->session, (uint8_t *)session->key, MEGOLM_SESSION_KEY_SIZE); + + fclose(f); + + return true; +} + bool @@ -222,36 +382,83 @@ MatrixClientInit( // init olm account MatrixOlmAccountInit(&client->olmAccount); - // set device key - static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE]; - size_t res = - olm_account_identity_keys( - client->olmAccount.account, - deviceKeysJson, - OLM_IDENTITY_KEYS_JSON_SIZE); + return true; +} - mjson_get_string(deviceKeysJson, res, - "$.curve25519", - client->deviceKey, DEVICE_KEY_SIZE); - mjson_get_string(deviceKeysJson, res, - "$.ed25519", - client->signingKey, SIGNING_KEY_SIZE); +bool +MatrixClientSave( + MatrixClient * client, + const char * filename) +{ + FILE * f = fopen(filename, "w"); + + + char thisDeviceKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE); + char thisSigningKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE); + + + 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); + fwrite(client->refreshToken, 1, REFRESH_TOKEN_SIZE, f); + + fwrite(&client->numDevices, sizeof(int), 1, f); + for (int i = 0; i < client->numDevices; i++) { + fwrite(client->devices[i].deviceId, 1, DEVICE_ID_SIZE, f); + fwrite(client->devices[i].deviceKey, 1, DEVICE_KEY_SIZE, f); + } + fclose(f); return true; } bool -MatrixClientSetAccessToken( +MatrixClientLoad( MatrixClient * client, - const char * accessToken) + const char * filename) { - int accessTokenLen = strlen(accessToken); + FILE * f = fopen(filename, "r"); + + + char thisDeviceKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE); + char thisSigningKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE); + + + 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); + fread(client->refreshToken, 1, REFRESH_TOKEN_SIZE, f); + + fread(&client->numDevices, sizeof(int), 1, f); + for (int i = 0; i < client->numDevices; i++) { + fread(client->devices[i].deviceId, 1, DEVICE_ID_SIZE, f); + fread(client->devices[i].deviceKey, 1, DEVICE_KEY_SIZE, f); + } - if (accessTokenLen > ACCESS_TOKEN_SIZE - 1) - return false; + fclose(f); + return true; +} - for (int i = 0; i < accessTokenLen; i++) +bool +MatrixClientSetAccessToken( + MatrixClient * client, + const char * accessToken) +{ + for (int i = 0; i < ACCESS_TOKEN_SIZE-1; i++) client->accessToken[i] = accessToken[i]; + client->accessToken[ACCESS_TOKEN_SIZE-1] = '\0'; return true; } @@ -261,13 +468,9 @@ MatrixClientSetDeviceId( MatrixClient * client, const char * deviceId) { - int deviceIdLen = strlen(deviceId); - - if (deviceIdLen > DEVICE_ID_SIZE - 1) - return false; - - for (int i = 0; i < deviceIdLen; i++) + for (int i = 0; i < DEVICE_ID_SIZE-1; i++) client->deviceId[i] = deviceId[i]; + client->deviceId[DEVICE_ID_SIZE-1] = '\0'; return true; } @@ -277,13 +480,9 @@ MatrixClientSetUserId( MatrixClient * client, const char * userId) { - int userIdLen = strlen(userId); - - if (userIdLen > USER_ID_SIZE - 1) - return false; - - for (int i = 0; i < userIdLen; i++) + for (int i = 0; i < USER_ID_SIZE-1; i++) client->userId[i] = userId[i]; + client->userId[USER_ID_SIZE-1] = '\0'; return true; } @@ -356,9 +555,14 @@ MatrixClientUploadOnetimeKeys( // https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysupload bool -MatrixClientUploadDeviceKeys( +MatrixClientUploadDeviceKey( MatrixClient * client) { + char thisDeviceKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE); + char thisSigningKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE); + static char deviceKeysBuffer[KEYS_UPLOAD_REQUEST_SIZE]; mjson_snprintf(deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE, @@ -372,8 +576,8 @@ MatrixClientUploadDeviceKeys( "\"user_id\":\"%s\"" "}}", client->deviceId, - client->deviceId, client->deviceKey, - client->deviceId, client->signingKey, + client->deviceId, thisDeviceKey, + client->deviceId, thisSigningKey, client->userId); static char deviceKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; @@ -392,6 +596,62 @@ MatrixClientUploadDeviceKeys( return true; } +// https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysclaim +bool +MatrixClientClaimOnetimeKey( + MatrixClient * client, + const char * userId, + const char * deviceId, + char * outOnetimeKey, int outOnetimeKeyCap) +{ + static char requestBuffer[KEYS_CLAIM_REQUEST_SIZE]; + mjson_snprintf(requestBuffer, KEYS_CLAIM_REQUEST_SIZE, + "{" + "\"one_time_keys\":{" + "\"%s\":{" + "\"%s\":\"signed_curve25519\"" + "}" + "}," + "\"timeout\":10000" + "}", + userId, + deviceId); + + static char responseBuffer[KEYS_CLAIM_RESPONSE_SIZE]; + MatrixHttpPost(client, + KEYS_CLAIM_URL, + requestBuffer, + responseBuffer, KEYS_CLAIM_RESPONSE_SIZE, + true); + + char userIdEscaped[USER_ID_SIZE]; + JsonEscape(userId, strlen(userId), + userIdEscaped, USER_ID_SIZE); + + static char query[JSON_QUERY_SIZE]; + snprintf(query, JSON_QUERY_SIZE, + "$.one_time_keys.%s.%s", + userIdEscaped, + deviceId); + + const char * keyObject; + int keyObjectSize; + mjson_find(responseBuffer, strlen(responseBuffer), + query, + &keyObject, &keyObjectSize); + + int koff, klen, voff, vlen, vtype; + mjson_next(keyObject, keyObjectSize, 0, + &koff, &klen, &voff, &vlen, &vtype); + + mjson_get_string(keyObject + voff, vlen, + "$.key", outOnetimeKey, outOnetimeKeyCap); + + // TODO:verify signature + + return true; +} + // https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3login bool MatrixClientLoginPassword( @@ -404,13 +664,13 @@ MatrixClientLoginPassword( mjson_snprintf(requestBuffer, LOGIN_REQUEST_SIZE, "{" - "\"type\": \"m.login.password\"," - "\"identifier\": {" - "\"type\": \"m.id.user\"," - "\"user\": \"%s\"" + "\"type\":\"m.login.password\"," + "\"identifier\":{" + "\"type\":\"m.id.user\"," + "\"user\":\"%s\"" "}," - "\"password\": \"%s\"," - "\"initial_device_display_name\": \"%s\"" + "\"password\":\"%s\"," + "\"initial_device_display_name\":\"%s\"" "}", username, password, @@ -424,10 +684,10 @@ MatrixClientLoginPassword( responseBuffer, LOGIN_RESPONSE_SIZE, false); - int responseLen = strlen(responseBuffer); - if (!result) return false; + + int responseLen = strlen(responseBuffer); mjson_get_string(responseBuffer, responseLen, "$.access_token", @@ -499,8 +759,12 @@ MatrixClientSendEventEncrypted( requestBuffer, encryptedBuffer, ENCRYPTED_REQUEST_SIZE); + char thisDeviceKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE); + + // encrypted event json - const char * senderKey = client->deviceKey; + const char * senderKey = thisDeviceKey; const char * sessionId = outSession->id; const char * deviceId = client->deviceId; @@ -508,15 +772,15 @@ MatrixClientSendEventEncrypted( sprintf(encryptedEventBuffer, "{" "\"algorithm\":\"m.megolm.v1.aes-sha2\"," - "\"sender_key\":\"%s\"," "\"ciphertext\":\"%s\"," - "\"session_id\":\"%s\"," - "\"device_id\":\"%s\"" + "\"device_id\":\"%s\"," + "\"sender_key\":\"%s\"," + "\"session_id\":\"%s\"" "}", - senderKey, encryptedBuffer, - sessionId, - deviceId); + deviceId, + senderKey, + sessionId); // send return MatrixClientSendEvent(client, @@ -541,11 +805,12 @@ MatrixClientSync( bool MatrixClientShareMegolmOutSession( MatrixClient * client, + const char * userId, const char * deviceId, MatrixMegolmOutSession * session) { // generate room key event - char eventBuffer[KEY_SHARE_EVENT_LEN]; + static char eventBuffer[KEY_SHARE_EVENT_LEN]; sprintf(eventBuffer, "{" "\"algorithm\":\"m.megolm.v1.aes-sha2\"," @@ -558,21 +823,21 @@ MatrixClientShareMegolmOutSession( session->key ); - // get olm session - MatrixOlmSession * olmSession; - MatrixClientGetOlmSession(client, deviceId, &olmSession); + // // 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); + // // encrypt + // char encryptedBuffer[KEY_SHARE_EVENT_LEN]; + // MatrixOlmSessionEncrypt(olmSession, + // eventBuffer, + // encryptedBuffer, KEY_SHARE_EVENT_LEN); // send MatrixClientSendToDeviceEncrypted(client, - client->userId, + userId, deviceId, - encryptedBuffer, + eventBuffer, "m.room_key"); return true; @@ -581,6 +846,7 @@ MatrixClientShareMegolmOutSession( bool MatrixClientShareMegolmOutSessionTest( MatrixClient * client, + const char * userId, const char * deviceId, MatrixMegolmOutSession * session) { @@ -600,7 +866,7 @@ MatrixClientShareMegolmOutSessionTest( // send MatrixClientSendToDevice(client, - client->userId, + userId, deviceId, eventBuffer, "m.room_key"); @@ -640,25 +906,36 @@ MatrixClientGetMegolmOutSession( } } + if (MatrixClientInitMegolmOutSession(client, roomId)) { + *outSession = &client->megolmOutSessions[client->numMegolmOutSessions-1]; + return true; + } + + return false; +} + +bool +MatrixClientInitMegolmOutSession( + MatrixClient * client, + const char * roomId) +{ if (client->numMegolmOutSessions < NUM_MEGOLM_SESSIONS) { MatrixMegolmOutSessionInit( &client->megolmOutSessions[client->numMegolmOutSessions], roomId); - - *outSession = &client->megolmOutSessions[client->numMegolmOutSessions]; client->numMegolmOutSessions++; return true; } - return false; } bool MatrixClientGetOlmSession( MatrixClient * client, + const char * userId, const char * deviceId, MatrixOlmSession ** outSession) { @@ -673,9 +950,23 @@ MatrixClientGetOlmSession( if (client->numOlmSessions < NUM_OLM_SESSIONS) { - MatrixOlmSessionInit( + static char deviceKey[DEVICE_KEY_SIZE]; + MatrixClientRequestDeviceKey(client, + deviceId, + deviceKey, DEVICE_KEY_SIZE); + + char onetimeKey[ONETIME_KEY_SIZE]; + MatrixClientClaimOnetimeKey(client, + userId, + deviceId, + onetimeKey, ONETIME_KEY_SIZE); + + MatrixOlmSessionTo( &client->olmSessions[client->numOlmSessions], - deviceId); + client->olmAccount.account, + deviceId, + deviceKey, + onetimeKey); *outSession = &client->olmSessions[client->numOlmSessions]; @@ -703,8 +994,8 @@ MatrixClientSendToDevice( static char eventBuffer[TODEVICE_EVENT_SIZE]; snprintf(eventBuffer, TODEVICE_EVENT_SIZE, "{" - "\"messages\": {" - "\"%s\": {" + "\"messages\":{" + "\"%s\":{" "\"%s\":%s" "}" "}" @@ -734,33 +1025,39 @@ MatrixClientSendToDeviceEncrypted( { // get olm session MatrixOlmSession * olmSession; - MatrixClientGetOlmSession(client, deviceId, &olmSession); + MatrixClientGetOlmSession(client, userId, deviceId, &olmSession); // create event json - char deviceKey[DEVICE_KEY_SIZE]; - MatrixClientGetDeviceKey(client, deviceId, deviceKey, DEVICE_KEY_SIZE); - const char * senderKey = client->deviceKey; + char targetDeviceKey[DEVICE_KEY_SIZE]; + MatrixClientRequestDeviceKey(client, deviceId, targetDeviceKey, DEVICE_KEY_SIZE); + char targetSigningKey[SIGNING_KEY_SIZE]; + MatrixClientRequestSigningKey(client, deviceId, targetSigningKey, SIGNING_KEY_SIZE); + char thisSigningKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, DEVICE_KEY_SIZE); + static char eventBuffer[TODEVICE_EVENT_SIZE]; sprintf(eventBuffer, "{" - "\"type\": \"%s\"," - "\"content\": \"%s\"," - "\"sender\": \"%s\"," - "\"recipient\": \"%s\"," - "\"recipient_keys\": {" - "\"ed25519\": \"%s\"" + "\"type\":\"%s\"," + "\"content\":%s," + "\"sender\":\"%s\"," + "\"recipient\":\"%s\"," + "\"recipient_keys\":{" + "\"ed25519\":\"%s\"" "}," - "\"keys\": {" - "\"ed25519\": \"%s\"" + "\"keys\":{" + "\"ed25519\":\"%s\"" "}" "}", msgType, message, client->userId, userId, // recipient user id - deviceKey, // recipient device key - client->deviceKey); + targetSigningKey, // recipient device key + thisSigningKey); + + printf("%s\n", eventBuffer); // encrypt static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE]; @@ -768,22 +1065,28 @@ MatrixClientSendToDeviceEncrypted( eventBuffer, encryptedBuffer, ENCRYPTED_REQUEST_SIZE); + char thisDeviceKey[DEVICE_KEY_SIZE]; + MatrixOlmAccountGetDeviceKey(&client->olmAccount, thisDeviceKey, DEVICE_KEY_SIZE); + + static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE]; sprintf(encryptedEventBuffer, "{" - "\"algorithm\":\"m.megolm.v1.aes-sha2\"," - "\"sender_key\":\"%s\"," + "\"algorithm\":\"m.olm.v1.curve25519-aes-sha2\"," "\"ciphertext\":{" "\"%s\":{" "\"body\":\"%s\"," - "\"type\":\"%d\"" + "\"type\":%d" "}" - "}" + "}," + "\"device_id\":\"%s\"," + "\"sender_key\":\"%s\"" "}", - senderKey, - deviceKey, + targetDeviceKey, encryptedBuffer, - olmSession->type); + olm_session_has_received_message(olmSession->session), + client->deviceId, + thisDeviceKey); // send return MatrixClientSendToDevice( @@ -816,14 +1119,21 @@ MatrixClientFindDevice( } bool -MatrixClientGetDeviceKey( +MatrixClientRequestDeviceKey( MatrixClient * client, const char * deviceId, char * outDeviceKey, int outDeviceKeyCap) { + MatrixDevice * device; + + if (MatrixClientFindDevice(client, deviceId, &device)) + { + strncpy(outDeviceKey, device->deviceKey, outDeviceKeyCap); + return true; + } + MatrixClientRequestDeviceKeys(client); - MatrixDevice * device; if (MatrixClientFindDevice(client, deviceId, &device)) { strncpy(outDeviceKey, device->deviceKey, outDeviceKeyCap); @@ -833,73 +1143,124 @@ MatrixClientGetDeviceKey( return false; } +bool +MatrixClientRequestSigningKey( + MatrixClient * client, + const char * deviceId, + char * outSigningKey, int outSigningKeyCap) +{ + MatrixDevice * device; + + if (MatrixClientFindDevice(client, deviceId, &device)) + { + strncpy(outSigningKey, device->signingKey, outSigningKeyCap); + return true; + } + + MatrixClientRequestDeviceKeys(client); + + if (MatrixClientFindDevice(client, deviceId, &device)) + { + strncpy(outSigningKey, device->signingKey, outSigningKeyCap); + return true; + } + + return false; +} + // https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3keysquery bool MatrixClientRequestDeviceKeys( MatrixClient * client) { - char userIdEscaped[USER_ID_SIZE]; + static char userIdEscaped[USER_ID_SIZE]; JsonEscape(client->userId, strlen(client->userId), userIdEscaped, USER_ID_SIZE); - char request[KEYS_QUERY_REQUEST_SIZE]; + static char request[KEYS_QUERY_REQUEST_SIZE]; snprintf(request, KEYS_QUERY_REQUEST_SIZE, - "{\"device_keys\":{\"%s\":[]}}", userIdEscaped); + "{\"device_keys\":{\"%s\":[]}}", client->userId); - char responseBuffer[KEYS_QUERY_RESPONSE_SIZE]; + static char responseBuffer[KEYS_QUERY_RESPONSE_SIZE]; bool requestResult = MatrixHttpPost(client, KEYS_QUERY_URL, request, responseBuffer, KEYS_QUERY_RESPONSE_SIZE, true); - if (requestResult) - { - // query for retrieving device keys for user id - char query[JSON_QUERY_SIZE]; - snprintf(query, JSON_QUERY_SIZE, - "$.device_keys.%s", userIdEscaped); - - const char * s; - int slen; - mjson_find(responseBuffer, strlen(responseBuffer), - query, &s, &slen); + if (! requestResult) + return false; - // loop over keys - - int koff, klen, voff, vlen, vtype, off; - for (off = 0; (off = mjson_next(s, slen, off, &koff, &klen, - &voff, &vlen, &vtype)) != 0; ) { - const char * key = s + koff; - const char * val = s + voff; - - // set device id, "key" is the JSON key - MatrixDevice d; - strncpy(d.deviceId, key, klen); - - // look for device key in value - char deviceKeyQuery[JSON_QUERY_SIZE]; - snprintf(deviceKeyQuery, JSON_QUERY_SIZE, - "$.keys.curve25519:%.*s", klen, key); - mjson_get_string(val, vlen, - deviceKeyQuery, d.deviceKey, DEVICE_KEY_SIZE); - - // add device - if (client->numDevices < NUM_DEVICES) - { + // query for retrieving device keys for user id + static char query[JSON_QUERY_SIZE]; + snprintf(query, JSON_QUERY_SIZE, + "$.device_keys.%s", userIdEscaped); + + const char * s; + int slen; + mjson_find(responseBuffer, strlen(responseBuffer), + query, &s, &slen); + + // loop over keys + + int koff, klen, voff, vlen, vtype, off = 0; + for (off = 0; (off = mjson_next(s, slen, off, &koff, &klen, + &voff, &vlen, &vtype)) != 0; ) { + const char * key = s + koff; + const char * val = s + voff; + + // set device id, "key" is the JSON key + MatrixDevice d; + snprintf(d.deviceId, DEVICE_ID_SIZE, + "%.*s", klen-2, key+1); + + // look for device key in value + 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]; + snprintf(signingKeyQuery, JSON_QUERY_SIZE, + "$.keys.ed25519:%s", d.deviceId); + mjson_get_string(val, vlen, + signingKeyQuery, d.signingKey, SIGNING_KEY_SIZE); + + // add device + if (client->numDevices < NUM_DEVICES) + { + bool foundDevice = false; + for (int i = 0; i < client->numDevices; i++) + if (strcmp(client->devices[i].deviceId, d.deviceId) == 0) + foundDevice = true; + + if (! foundDevice) { + printf("new device: %s %s %s\n", d.deviceId, d.deviceKey, d.signingKey); client->devices[client->numDevices] = d; client->numDevices++; } - else - { - return false; - } } - - return true; - } - else - { - return false; + else + { + return false; + } } + + return true; } + +bool +MatrixClientDeleteDevice( + MatrixClient * client) +{ + static char deleteRequest[1024]; + snprintf(deleteRequest, 1024, + "{\"devices\":[\"%s\"]}", + client->deviceId); + static char deleteResponse[1024]; + bool res = MatrixHttpPost(client, "/_matrix/client/v3/delete_devices", + deleteRequest, deleteResponse, 1024, true); + return res; +} \ No newline at end of file