X-Git-Url: https://gitweb.ps.run/matrix_esp_thesis/blobdiff_plain/f2840d9dd5b8a0683abee189e408c5a6de294eb7..30bde47d1d5d9b6f0b59c318ff16caed6268d1a8:/src/matrix.c diff --git a/src/matrix.c b/src/matrix.c index 966a038..18b700a 100644 --- a/src/matrix.c +++ b/src/matrix.c @@ -9,11 +9,13 @@ #define LOGIN_RESPONSE_SIZE 1024 #define LOGIN_URL "/_matrix/client/v3/login" -#define ENCRYPTED_REQUEST_SIZE 512 -#define ENCRYPTED_EVENT_SIZE 1024 -#define ROOMEVENT_REQUEST_SIZE 256 -#define ROOMEVENT_RESPONSE_SIZE 1024 -#define ROOMEVENT_URL "/_matrix/client/v3/rooms/%s/send/%s/%d" +#define ENCRYPTED_REQUEST_SIZE (1024*5) +#define ENCRYPTED_EVENT_SIZE (1024*10) +#define ROOM_SEND_REQUEST_SIZE 256 +#define ROOM_SEND_RESPONSE_SIZE 1024 +#define ROOM_SEND_URL "/_matrix/client/v3/rooms/%s/send/%s/%d" + +#define ROOMKEY_REQUEST_SIZE (1024*4) #define TODEVICE_EVENT_SIZE (1024*5) #define TODEVICE_URL "/_matrix/client/v3/sendToDevice/%s/%d" @@ -23,8 +25,8 @@ #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" @@ -40,7 +42,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++) @@ -88,6 +90,9 @@ bool JsonSign( signature, OLM_SIGNATURE_SIZE); int signatureLen = res; + + static char thisSigningKey[SIGNING_KEY_SIZE]; + MatrixOlmAccountGetSigningKey(&client->olmAccount, thisSigningKey, SIGNING_KEY_SIZE); static char signatureJson[JSON_SIGNATURE_SIZE]; int signatureJsonLen = @@ -100,6 +105,7 @@ bool JsonSign( "}" "}", client->userId, + //"1", client->deviceId, signatureLen, signature); @@ -131,9 +137,56 @@ MatrixOlmAccountInit( return res != olm_error(); } -// TODO: in/outbound sessions bool -MatrixOlmSessionFrom( +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, OlmAccount * olmAccount, const char * deviceId, @@ -150,15 +203,46 @@ MatrixOlmSessionFrom( static uint8_t random[OLM_OUTBOUND_SESSION_RANDOM_SIZE]; Randomize(random, OLM_OUTBOUND_SESSION_RANDOM_SIZE); - olm_create_outbound_session(session->session, - olmAccount, - deviceKey, strlen(deviceKey), - deviceOnetimeKey, strlen(deviceOnetimeKey), - 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, @@ -176,6 +260,28 @@ MatrixOlmSessionEncrypt( return res != olm_error(); } +bool +MatrixOlmSessionDecrypt( + MatrixOlmSession * session, + size_t messageType, + char * encrypted, + char * outBuffer, int outBufferCap) +{ + static uint8_t random[OLM_ENCRYPT_RANDOM_SIZE]; + Randomize(random, OLM_ENCRYPT_RANDOM_SIZE); + + size_t res = + olm_decrypt(session->session, + messageType, + encrypted, strlen(encrypted), + outBuffer, outBufferCap); + + if (res != olm_error() && res < outBufferCap) + outBuffer[outBufferCap] = '\0'; + + return res != olm_error(); +} + // https://matrix.org/docs/guides/end-to-end-encryption-implementation-guide#starting-a-megolm-session bool MatrixMegolmOutSessionInit( @@ -187,7 +293,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); @@ -221,6 +327,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 @@ -235,36 +407,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; } @@ -274,13 +493,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; } @@ -290,13 +505,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; } @@ -324,7 +535,7 @@ MatrixClientUploadOnetimeKeys( static char requestBuffer[KEYS_UPLOAD_REQUEST_SIZE]; mjson_snprintf(requestBuffer, KEYS_UPLOAD_REQUEST_SIZE, - "{\"one_time_keys\":{"); + "{"); static char onetimeKeysBuffer[1024]; olm_account_one_time_keys(client->olmAccount.account, @@ -338,14 +549,15 @@ MatrixClientUploadOnetimeKeys( while ((off = mjson_next(keys, keysLen, off, &koff, &klen, &voff, &vlen, &vtype)) != 0) { static char keyJson[JSON_ONETIME_KEY_SIZE]; - snprintf(keyJson, JSON_ONETIME_KEY_SIZE, - "{\"key\":\"%.*s\"}", - vlen-2, keys + voff+1); + int keyJsonLen = + snprintf(keyJson, JSON_ONETIME_KEY_SIZE, + "{\"key\":\"%.*s\"}", + vlen-2, keys + voff+1); static char keyJsonSigned[JSON_ONETIME_KEY_SIGNED_SIZE]; JsonSign(client, - keyJson, JSON_ONETIME_KEY_SIZE, + keyJson, keyJsonLen, keyJsonSigned, JSON_ONETIME_KEY_SIGNED_SIZE); mjson_snprintf(requestBuffer+strlen(requestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer), @@ -354,53 +566,81 @@ MatrixClientUploadOnetimeKeys( keyJsonSigned); } - mjson_snprintf(requestBuffer+strlen(requestBuffer)-1, KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer), - "}}"); + if (requestBuffer[strlen(requestBuffer)-1] == ',') + requestBuffer[strlen(requestBuffer)-1] = '\0'; + + mjson_snprintf(requestBuffer+strlen(requestBuffer), KEYS_UPLOAD_REQUEST_SIZE-strlen(requestBuffer), + "}"); + + // static char onetimeKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; + // JsonSign(client, + // requestBuffer, strlen(requestBuffer), + // onetimeKeysSignedBuffer, KEYS_UPLOAD_REQUEST_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); static char responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE]; MatrixHttpPost(client, KEYS_UPLOAD_URL, - requestBuffer, + finalEvent, responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE, true); + printf("%s\n", responseBuffer); + return true; } // 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, - "{\"device_keys\":{" - "\"algorithms\":[\"m.olm.v1.curve25519-aes-sha2\",\"m.megolm.v1.aes-sha2\"]," - "\"device_id\":\"%s\"," - "\"keys\":{" - "\"curve25519:%s\":\"%s\"," - "\"ed25519:%s\":\"%s\"" - "}," - "\"user_id\":\"%s\"" - "}}", - client->deviceId, - client->deviceId, client->deviceKey, - client->deviceId, client->signingKey, - client->userId); + int deviceKeysBufferLen = + mjson_snprintf(deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE, + "{" + "\"algorithms\":[\"m.olm.v1.curve25519-aes-sha2\",\"m.megolm.v1.aes-sha2\"]," + "\"device_id\":\"%s\"," + "\"keys\":{" + "\"curve25519:%s\":\"%s\"," + "\"ed25519:%s\":\"%s\"" + "}," + "\"user_id\":\"%s\"" + "}", + client->deviceId, + client->deviceId, thisDeviceKey, + client->deviceId, thisSigningKey, + client->userId); static char deviceKeysSignedBuffer[KEYS_UPLOAD_REQUEST_SIGNED_SIZE]; JsonSign(client, - deviceKeysBuffer, KEYS_UPLOAD_REQUEST_SIZE, + deviceKeysBuffer, deviceKeysBufferLen, deviceKeysSignedBuffer, 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 responseBuffer[KEYS_UPLOAD_RESPONSE_SIZE]; MatrixHttpPost(client, KEYS_UPLOAD_URL, - deviceKeysSignedBuffer, + finalEvent, responseBuffer, KEYS_UPLOAD_RESPONSE_SIZE, true); + + printf("%s\n", responseBuffer); return true; } @@ -416,12 +656,12 @@ MatrixClientClaimOnetimeKey( static char requestBuffer[KEYS_CLAIM_REQUEST_SIZE]; mjson_snprintf(requestBuffer, KEYS_CLAIM_REQUEST_SIZE, "{" - "\"one_time_keys\": {" - "\"%s\": {" - "\"%s\": \"signed_curve25519\"" + "\"one_time_keys\":{" + "\"%s\":{" + "\"%s\":\"signed_curve25519\"" "}" "}," - "\"timeout\": 10000" + "\"timeout\":10000" "}", userId, deviceId); @@ -455,10 +695,8 @@ MatrixClientClaimOnetimeKey( mjson_get_string(keyObject + voff, vlen, "$.key", outOnetimeKey, outOnetimeKeyCap); - - printf("onetime key: %s\n", outOnetimeKey); - // TODO: verify signature + // TODO:verify signature return true; } @@ -475,13 +713,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, @@ -495,10 +733,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", @@ -526,14 +764,14 @@ MatrixClientSendEvent( { static char requestUrl[MAX_URL_LEN]; sprintf(requestUrl, - ROOMEVENT_URL, roomId, msgType, (int)time(NULL)); + ROOM_SEND_URL, roomId, msgType, (int)time(NULL)); - static char responseBuffer[ROOMEVENT_RESPONSE_SIZE]; + static char responseBuffer[ROOM_SEND_RESPONSE_SIZE]; bool result = MatrixHttpPut(client, requestUrl, msgBody, - responseBuffer, ROOMEVENT_RESPONSE_SIZE, + responseBuffer, ROOM_SEND_RESPONSE_SIZE, true); return result; @@ -549,7 +787,7 @@ MatrixClientSendEventEncrypted( const char * msgBody) { // event json - static char requestBuffer[ROOMEVENT_REQUEST_SIZE]; + static char requestBuffer[ROOM_SEND_REQUEST_SIZE]; sprintf(requestBuffer, "{" "\"type\":\"%s\"," @@ -570,8 +808,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; @@ -579,15 +821,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, @@ -609,6 +851,27 @@ MatrixClientSync( true); } +// https://spec.matrix.org/v1.7/client-server-api/#get_matrixclientv3roomsroomideventeventid +bool +MatrixClientGetRoomEvent( + MatrixClient * client, + const char * roomId, + const char * eventId, + char * outEvent, int outEventCap) +{ + static char url[MAX_URL_LEN]; + snprintf(url, MAX_URL_LEN, + "/_matrix/client/v3/rooms/%s/event/%s", + roomId, + eventId); + + return + MatrixHttpGet(client, + url, + outEvent, outEventCap, + true); +} + bool MatrixClientShareMegolmOutSession( MatrixClient * client, @@ -630,21 +893,21 @@ MatrixClientShareMegolmOutSession( session->key ); - // get olm session - MatrixOlmSession * olmSession; - MatrixClientGetOlmSession(client, userId, 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; @@ -653,6 +916,7 @@ MatrixClientShareMegolmOutSession( bool MatrixClientShareMegolmOutSessionTest( MatrixClient * client, + const char * userId, const char * deviceId, MatrixMegolmOutSession * session) { @@ -672,7 +936,7 @@ MatrixClientShareMegolmOutSessionTest( // send MatrixClientSendToDevice(client, - client->userId, + userId, deviceId, eventBuffer, "m.room_key"); @@ -712,22 +976,74 @@ 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 +MatrixClientRequestMegolmInSession( + MatrixClient * client, + const char * roomId, + const char * sessionId, + const char * senderKey, + const char * userId, + const char * deviceId, + MatrixMegolmInSession * outMegolmInSession) +{ + // TODO: cancel requests + MatrixClientSendDummy(client, userId, deviceId); + + static char event[ROOMKEY_REQUEST_SIZE]; + snprintf(event, ROOMKEY_REQUEST_SIZE, + "{" + "\"action\":\"request\"," + "\"body\":{" + "\"algorithm\":\"m.megolm.v1.aes-sha2\"," + "\"room_id\":\"%s\"," + "\"sender_key\":\"%s\"," + "\"session_id\":\"%s\"" + "}," + "\"request_id\":\"%d\"," + "\"requesting_device_id\":\"%s\"" + "}", + roomId, + senderKey, + sessionId, + time(NULL), + client->deviceId); + + + MatrixClientSendToDevice(client, + userId, + deviceId, + event, + "m.room_key_request"); + + return true; +} + bool MatrixClientGetOlmSession( MatrixClient * client, @@ -747,7 +1063,7 @@ MatrixClientGetOlmSession( if (client->numOlmSessions < NUM_OLM_SESSIONS) { static char deviceKey[DEVICE_KEY_SIZE]; - MatrixClientGetDeviceKey(client, + MatrixClientRequestDeviceKey(client, deviceId, deviceKey, DEVICE_KEY_SIZE); @@ -757,7 +1073,7 @@ MatrixClientGetOlmSession( deviceId, onetimeKey, ONETIME_KEY_SIZE); - MatrixOlmSessionFrom( + MatrixOlmSessionTo( &client->olmSessions[client->numOlmSessions], client->olmAccount.account, deviceId, @@ -790,8 +1106,8 @@ MatrixClientSendToDevice( static char eventBuffer[TODEVICE_EVENT_SIZE]; snprintf(eventBuffer, TODEVICE_EVENT_SIZE, "{" - "\"messages\": {" - "\"%s\": {" + "\"messages\":{" + "\"%s\":{" "\"%s\":%s" "}" "}" @@ -800,14 +1116,16 @@ MatrixClientSendToDevice( deviceId, message); - static char responseBuffer[ROOMEVENT_RESPONSE_SIZE]; + static char responseBuffer[ROOM_SEND_RESPONSE_SIZE]; bool result = MatrixHttpPut(client, requestUrl, eventBuffer, - responseBuffer, ROOMEVENT_RESPONSE_SIZE, + responseBuffer, ROOM_SEND_RESPONSE_SIZE, true); + printf("%s\n", responseBuffer); + return result; } @@ -824,30 +1142,36 @@ MatrixClientSendToDeviceEncrypted( 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]; @@ -855,22 +1179,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( @@ -881,6 +1211,20 @@ MatrixClientSendToDeviceEncrypted( "m.room.encrypted"); } +bool +MatrixClientSendDummy( + MatrixClient * client, + const char * userId, + const char * deviceId) +{ + return MatrixClientSendToDeviceEncrypted( + client, + userId, + deviceId, + "{}", + "m.dummy"); +} + bool MatrixClientFindDevice( MatrixClient * client, @@ -903,14 +1247,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); @@ -920,6 +1271,31 @@ 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( @@ -943,6 +1319,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]; snprintf(query, JSON_QUERY_SIZE, @@ -952,7 +1330,7 @@ MatrixClientRequestDeviceKeys( int slen; mjson_find(responseBuffer, strlen(responseBuffer), query, &s, &slen); - + // loop over keys int koff, klen, voff, vlen, vtype, off = 0; @@ -973,11 +1351,26 @@ MatrixClientRequestDeviceKeys( 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) { - client->devices[client->numDevices] = d; - client->numDevices++; + 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 { @@ -987,3 +1380,17 @@ MatrixClientRequestDeviceKeys( 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