olm_inbound_group_session.cpp 19.7 KB
Newer Older
1
2
/*
 * Copyright 2016 OpenMarket Ltd
ylecollen's avatar
ylecollen committed
3
 * Copyright 2016 Vector Creations Ltd
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "olm_inbound_group_session.h"

pedroGitt's avatar
pedroGitt committed
20
using namespace AndroidOlmSdk;
21
22
23
24
25
26
27
28
29
30

/**
 * Release the session allocation made by initializeInboundGroupSessionMemory().<br>
 * This method MUST be called when java counter part account instance is done.
 *
 */
JNIEXPORT void OLM_INBOUND_GROUP_SESSION_FUNC_DEF(releaseSessionJni)(JNIEnv *env, jobject thiz)
{
  OlmInboundGroupSession* sessionPtr = NULL;

pedroGitt's avatar
pedroGitt committed
31
  LOGD("## releaseSessionJni(): InBound group session IN");
32
33
34
35
36
37
38

  if(NULL == (sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
  {
      LOGE("## releaseSessionJni(): failure - invalid inbound group session instance");
  }
  else
  {
39
    LOGD(" ## releaseSessionJni(): sessionPtr=%p",sessionPtr);
40
#ifdef ENABLE_JNI_LOG
41
    size_t retCode = olm_clear_inbound_group_session(sessionPtr);
42
43
44
45
    LOGD(" ## releaseSessionJni(): clear_inbound_group_session=%lu",static_cast<long unsigned int>(retCode));
#else
    olm_clear_inbound_group_session(sessionPtr);
#endif
46

47
    LOGD(" ## releaseSessionJni(): free IN");
48
    free(sessionPtr);
49
    LOGD(" ## releaseSessionJni(): free OUT");
50
51
52
53
54
55
56
57
58
  }
}

/**
* Initialize a new inbound group session and return it to JAVA side.<br>
* Since a C prt is returned as a jlong, special care will be taken
* to make the cast (OlmInboundGroupSession* => jlong) platform independent.
* @return the initialized OlmInboundGroupSession* instance if init succeed, NULL otherwise
**/
59
JNIEXPORT jlong OLM_INBOUND_GROUP_SESSION_FUNC_DEF(createNewSessionJni)(JNIEnv *env, jobject thiz)
60
61
{
    OlmInboundGroupSession* sessionPtr = NULL;
62
63
    size_t sessionSize = 0;

64
    LOGD("## createNewSessionJni(): inbound group session IN");
65
    sessionSize = olm_inbound_group_session_size();
66
67
68

    if(0 == sessionSize)
    {
69
        LOGE(" ## createNewSessionJni(): failure - inbound group session size = 0");
70
71
72
73
    }
    else if(NULL != (sessionPtr=(OlmInboundGroupSession*)malloc(sessionSize)))
    {
      sessionPtr = olm_inbound_group_session(sessionPtr);
pedroGitt's avatar
pedroGitt committed
74
      LOGD(" ## createNewSessionJni(): success - inbound group session size=%lu",static_cast<long unsigned int>(sessionSize));
75
76
77
    }
    else
    {
78
      LOGE(" ## createNewSessionJni(): failure - inbound group session OOM");
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    }

    return (jlong)(intptr_t)sessionPtr;
}

/**
 * Create a new in-bound session.<br>
 * @param aSessionKey session key from an outbound session
 * @return ERROR_CODE_OK if operation succeed, ERROR_CODE_KO otherwise
 */
JNIEXPORT jint OLM_INBOUND_GROUP_SESSION_FUNC_DEF(initInboundGroupSessionWithSessionKeyJni)(JNIEnv *env, jobject thiz, jstring aSessionKey)
{
    jint retCode = ERROR_CODE_KO;
    OlmInboundGroupSession *sessionPtr = NULL;
    const uint8_t *sessionKeyPtr = NULL;
    size_t sessionResult;

96
97
    LOGD("## initInboundGroupSessionWithSessionKeyJni(): inbound group session IN");

98
99
    if(NULL == (sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
    {
100
        LOGE(" ## initInboundGroupSessionWithSessionKeyJni(): failure - invalid inbound group session instance");
101
102
103
    }
    else if(0 == aSessionKey)
    {
104
        LOGE(" ## initInboundGroupSessionWithSessionKeyJni(): failure - invalid aSessionKey");
105
106
107
    }
    else if(NULL == (sessionKeyPtr = (const uint8_t *)env->GetStringUTFChars(aSessionKey, 0)))
    {
108
        LOGE(" ## initInboundSessionFromIdKeyJni(): failure - session key JNI allocation OOM");
109
110
111
112
    }
    else
    {
        size_t sessionKeyLength = (size_t)env->GetStringUTFLength(aSessionKey);
pedroGitt's avatar
pedroGitt committed
113
        LOGD(" ## initInboundSessionFromIdKeyJni(): sessionKeyLength=%lu",static_cast<long unsigned int>(sessionKeyLength));
114
115
116
117

        sessionResult = olm_init_inbound_group_session(sessionPtr, sessionKeyPtr, sessionKeyLength);
        if(sessionResult == olm_error()) {
            const char *errorMsgPtr = olm_inbound_group_session_last_error(sessionPtr);
118
            LOGE(" ## initInboundSessionFromIdKeyJni(): failure - init inbound session creation Msg=%s",errorMsgPtr);
119
120
121
122
        }
        else
        {
            retCode = ERROR_CODE_OK;
pedroGitt's avatar
pedroGitt committed
123
            LOGD(" ## initInboundSessionFromIdKeyJni(): success - result=%lu", static_cast<long unsigned int>(sessionResult));
124
125
126
127
128
129
130
131
132
133
134
135
136
        }
     }

     // free local alloc
     if(NULL!= sessionKeyPtr)
     {
         env->ReleaseStringUTFChars(aSessionKey, (const char*)sessionKeyPtr);
     }

    return retCode;
}


137
138
139
/**
* Get a base64-encoded identifier for this inbound group session.
*/
140
141
142
143
144
145
JNIEXPORT jstring OLM_INBOUND_GROUP_SESSION_FUNC_DEF(sessionIdentifierJni)(JNIEnv *env, jobject thiz)
{
    OlmInboundGroupSession *sessionPtr = NULL;
    uint8_t *sessionIdPtr = NULL;
    jstring returnValueStr=0;

146
    LOGD("## sessionIdentifierJni(): inbound group session IN");
147
148
149

    if(NULL == (sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
    {
150
        LOGE(" ## sessionIdentifierJni(): failure - invalid inbound group session instance");
151
152
153
    }
    else
    {
154
155
        // get the size to alloc
        size_t lengthSessionId = olm_inbound_group_session_id_length(sessionPtr);
pedroGitt's avatar
pedroGitt committed
156
        LOGD(" ## sessionIdentifierJni(): inbound group session lengthSessionId=%lu",static_cast<long unsigned int>(lengthSessionId));
157

158
        if(NULL == (sessionIdPtr = (uint8_t*)malloc((lengthSessionId+1)*sizeof(uint8_t))))
159
        {
160
           LOGE(" ## sessionIdentifierJni(): failure - inbound group session identifier allocation OOM");
161
162
163
        }
        else
        {
164
165
166
            size_t result = olm_inbound_group_session_id(sessionPtr, sessionIdPtr, lengthSessionId);
            if (result == olm_error())
            {
167
                LOGE(" ## sessionIdentifierJni(): failure - get inbound group session identifier failure Msg=%s",(const char *)olm_inbound_group_session_last_error(sessionPtr));
168
169
170
171
172
            }
            else
            {
                // update length
                sessionIdPtr[result] = static_cast<char>('\0');
pedroGitt's avatar
pedroGitt committed
173
                LOGD(" ## sessionIdentifierJni(): success - inbound group session result=%lu sessionId=%s",static_cast<long unsigned int>(result), (char*)sessionIdPtr);
174
175
176
                returnValueStr = env->NewStringUTF((const char*)sessionIdPtr);
            }
            free(sessionIdPtr);
177
178
179
180
181
182
        }
    }

    return returnValueStr;
}

183

184
JNIEXPORT jstring OLM_INBOUND_GROUP_SESSION_FUNC_DEF(decryptMessageJni)(JNIEnv *env, jobject thiz, jstring aEncryptedMsg, jobject aDecryptIndex, jobject aErrorMsg, jboolean aIsUtf8ConversionRequired)
185
186
187
188
189
190
{
    jstring decryptedMsgRetValue = 0;
    OlmInboundGroupSession *sessionPtr = NULL;
    const char *encryptedMsgPtr = NULL;
    uint8_t *plainTextMsgPtr = NULL;
    uint8_t *tempEncryptedPtr = NULL;
191
192
193
    uint32_t messageIndex = 0;
    jclass indexObjJClass = 0;
    jfieldID indexMsgFieldId;
194
195
196
197
    jclass errorMsgJClass = 0;
    jmethodID errorMsgMethodId = 0;
    jstring errorJstring = 0;
    const char *errorMsgPtr = NULL;
198

199
    LOGD("## decryptMessageJni(): inbound group session IN");
200
201
202

    if(NULL == (sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
    {
203
        LOGE(" ## decryptMessageJni(): failure - invalid inbound group session ptr=NULL");
204
205
206
    }
    else if(0 == aEncryptedMsg)
    {
207
        LOGE(" ## decryptMessageJni(): failure - invalid encrypted message");
208
    }
209
210
211
212
    else if(0 == aDecryptIndex)
    {
        LOGE(" ## decryptMessageJni(): failure - invalid index object");
    }
213
214
215
216
217
218
219
220
221
222
223
224
    else if(0 == aErrorMsg)
    {
        LOGE(" ## decryptMessageJni(): failure - invalid error object");
    }
    else if(0 == (errorMsgJClass = env->GetObjectClass(aErrorMsg)))
    {
        LOGE(" ## decryptMessageJni(): failure - unable to get error class");
    }
    else if(0 == (errorMsgMethodId = env->GetMethodID(errorMsgJClass, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;")))
    {
        LOGE(" ## decryptMessageJni(): failure - unable to get error method ID");
    }
225
226
    else if(0 == (encryptedMsgPtr = env->GetStringUTFChars(aEncryptedMsg, 0)))
    {
227
        LOGE(" ## decryptMessageJni(): failure - encrypted message JNI allocation OOM");
228
    }
229
230
231
232
233
234
235
236
    else if(0 == (indexObjJClass = env->GetObjectClass(aDecryptIndex)))
    {
        LOGE("## decryptMessageJni(): failure - unable to get index class");
    }
    else if(0 == (indexMsgFieldId = env->GetFieldID(indexObjJClass,"mIndex","J")))
    {
        LOGE("## decryptMessageJni(): failure - unable to get index type field");
    }
237
238
239
240
241
242
243
244
    else
    {
        // get encrypted message length
        size_t encryptedMsgLength = (size_t)env->GetStringUTFLength(aEncryptedMsg);

        // create a dedicated temp buffer to be used in next Olm API calls
        if(NULL == (tempEncryptedPtr = static_cast<uint8_t*>(malloc(encryptedMsgLength*sizeof(uint8_t)))))
        {
245
            LOGE(" ## decryptMessageJni(): failure - tempEncryptedPtr allocation OOM");
246
247
248
249
        }
        else
        {
            memcpy(tempEncryptedPtr, encryptedMsgPtr, encryptedMsgLength);
pedroGitt's avatar
pedroGitt committed
250
            LOGD(" ## decryptMessageJni(): encryptedMsgLength=%lu encryptedMsg=%s",static_cast<long unsigned int>(encryptedMsgLength),encryptedMsgPtr);
251
252
253
254
255
256
257

            // get max plaintext length
            size_t maxPlainTextLength = olm_group_decrypt_max_plaintext_length(sessionPtr,
                                                                               tempEncryptedPtr,
                                                                               encryptedMsgLength);
            if(maxPlainTextLength == olm_error())
            {
258
259
260
261
262
263
                errorMsgPtr = olm_inbound_group_session_last_error(sessionPtr);
                LOGE(" ## decryptMessageJni(): failure - olm_group_decrypt_max_plaintext_length Msg=%s",errorMsgPtr);
                if(0 != (errorJstring = env->NewStringUTF(errorMsgPtr)))
                {
                    env->CallObjectMethod(aErrorMsg, errorMsgMethodId, errorJstring);
                }
264
265
266
            }
            else
            {
pedroGitt's avatar
pedroGitt committed
267
                LOGD(" ## decryptMessageJni(): maxPlaintextLength=%lu",static_cast<long unsigned int>(maxPlainTextLength));
268
269

                // allocate output decrypted message
270
                plainTextMsgPtr = static_cast<uint8_t*>(malloc((maxPlainTextLength+1)*sizeof(uint8_t)));
271
272
273
274
275
276
277

                // decrypt, but before reload encrypted buffer (previous one was destroyed)
                memcpy(tempEncryptedPtr, encryptedMsgPtr, encryptedMsgLength);
                size_t plaintextLength = olm_group_decrypt(sessionPtr,
                                                           tempEncryptedPtr,
                                                           encryptedMsgLength,
                                                           plainTextMsgPtr,
278
279
                                                           maxPlainTextLength,
                                                           &messageIndex);
280
281
                if(plaintextLength == olm_error())
                {
282
283
284
285
286
287
288
                    errorMsgPtr = olm_inbound_group_session_last_error(sessionPtr);
                    LOGE(" ## decryptMessageJni(): failure - olm_group_decrypt Msg=%s",errorMsgPtr);

                    if(0 != (errorJstring = env->NewStringUTF(errorMsgPtr)))
                    {
                        env->CallObjectMethod(aErrorMsg, errorMsgMethodId, errorJstring);
                    }
289
290
291
                }
                else
                {
292
293
294
                    // update index
                    env->SetLongField(aDecryptIndex, indexMsgFieldId, (jlong)messageIndex);

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
                    // UTF-8 conversion workaround for issue on Android versions older than Marshmallow (23)
                    if(aIsUtf8ConversionRequired)
                    {
                        decryptedMsgRetValue = javaCStringToUtf8(env, plainTextMsgPtr, plaintextLength);
                        if(0 == decryptedMsgRetValue)
                        {
                            LOGE(" ## decryptMessageJni(): UTF-8 Conversion failure - javaCStringToUtf8() returns null");
                        }
                        else
                        {
                            LOGD(" ## decryptMessageJni(): UTF-8 Conversion - decrypted returnedLg=%lu OK",static_cast<long unsigned int>(plaintextLength));
                        }
                    }
                    else
                    {
                        // update decrypted buffer size
                        plainTextMsgPtr[plaintextLength] = static_cast<char>('\0');

                        LOGD(" ## decryptMessageJni(): decrypted returnedLg=%lu plainTextMsgPtr=%s",static_cast<long unsigned int>(plaintextLength), (char*)plainTextMsgPtr);
                        decryptedMsgRetValue = env->NewStringUTF((const char*)plainTextMsgPtr);
                    }
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
                }
            }
        }
    }

    // free alloc
    if(NULL != encryptedMsgPtr)
    {
        env->ReleaseStringUTFChars(aEncryptedMsg, encryptedMsgPtr);
    }

    if(NULL != tempEncryptedPtr)
    {
        free(tempEncryptedPtr);
    }

    if(NULL != plainTextMsgPtr)
    {
        free(plainTextMsgPtr);
    }

    return decryptedMsgRetValue;
}


341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/**
* Serialize and encrypt session instance into a base64 string.<br>
* @param aKey key used to encrypt the serialized session data
* @param[out] aErrorMsg error message set if operation failed
* @return a base64 string if operation succeed, null otherwise
**/
JNIEXPORT jstring OLM_INBOUND_GROUP_SESSION_FUNC_DEF(serializeDataWithKeyJni)(JNIEnv *env, jobject thiz, jstring aKey, jobject aErrorMsg)
{
    jstring pickledDataRetValue = 0;
    jclass errorMsgJClass = 0;
    jmethodID errorMsgMethodId = 0;
    jstring errorJstring = 0;
    const char *keyPtr = NULL;
    void *pickledPtr = NULL;
    OlmInboundGroupSession* sessionPtr = NULL;

    LOGD("## inbound group session serializeDataWithKeyJni(): IN");

    if(NULL == (sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
    {
        LOGE(" ## serializeDataWithKeyJni(): failure - invalid session ptr");
    }
    else if(0 == aKey)
    {
        LOGE(" ## serializeDataWithKeyJni(): failure - invalid key");
    }
    else if(0 == aErrorMsg)
    {
        LOGE(" ## serializeDataWithKeyJni(): failure - invalid error object");
    }
    else if(0 == (errorMsgJClass = env->GetObjectClass(aErrorMsg)))
    {
        LOGE(" ## serializeDataWithKeyJni(): failure - unable to get error class");
    }
    else if(0 == (errorMsgMethodId = env->GetMethodID(errorMsgJClass, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;")))
    {
        LOGE(" ## serializeDataWithKeyJni(): failure - unable to get error method ID");
    }
    else if(NULL == (keyPtr = env->GetStringUTFChars(aKey, 0)))
    {
        LOGE(" ## serializeDataWithKeyJni(): failure - keyPtr JNI allocation OOM");
    }
    else
    {
        size_t pickledLength = olm_pickle_inbound_group_session_length(sessionPtr);
        size_t keyLength = (size_t)env->GetStringUTFLength(aKey);
pedroGitt's avatar
pedroGitt committed
387
        LOGD(" ## serializeDataWithKeyJni(): pickledLength=%lu keyLength=%lu", static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
        LOGD(" ## serializeDataWithKeyJni(): key=%s",(char const *)keyPtr);

        if(NULL == (pickledPtr = (void*)malloc((pickledLength+1)*sizeof(uint8_t))))
        {
            LOGE(" ## serializeDataWithKeyJni(): failure - pickledPtr buffer OOM");
        }
        else
        {
            size_t result = olm_pickle_inbound_group_session(sessionPtr,
                                                             (void const *)keyPtr,
                                                              keyLength,
                                                              (void*)pickledPtr,
                                                              pickledLength);
            if(result == olm_error())
            {
                const char *errorMsgPtr = olm_inbound_group_session_last_error(sessionPtr);
                LOGE(" ## serializeDataWithKeyJni(): failure - olm_pickle_outbound_group_session() Msg=%s",errorMsgPtr);

                if(0 != (errorJstring = env->NewStringUTF(errorMsgPtr)))
                {
                    env->CallObjectMethod(aErrorMsg, errorMsgMethodId, errorJstring);
                }
            }
            else
            {
                // build success output
                (static_cast<char*>(pickledPtr))[pickledLength] = static_cast<char>('\0');
                pickledDataRetValue = env->NewStringUTF((const char*)pickledPtr);
pedroGitt's avatar
pedroGitt committed
416
                LOGD(" ## serializeDataWithKeyJni(): success - result=%lu pickled=%s", static_cast<long unsigned int>(result), static_cast<char*>(pickledPtr));
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
            }
        }
    }

    // free alloc
    if(NULL != keyPtr)
    {
     env->ReleaseStringUTFChars(aKey, keyPtr);
    }

    if(NULL != pickledPtr)
    {
        free(pickledPtr);
    }

    return pickledDataRetValue;
}


JNIEXPORT jstring OLM_INBOUND_GROUP_SESSION_FUNC_DEF(initWithSerializedDataJni)(JNIEnv *env, jobject thiz, jstring aSerializedData, jstring aKey)
{
    OlmInboundGroupSession* sessionPtr = NULL;
    jstring errorMessageRetValue = 0;
    const char *keyPtr = NULL;
    const char *pickledPtr = NULL;
442

443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
    LOGD("## initWithSerializedDataJni(): IN");

    if(NULL == (sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
    {
        LOGE(" ## initWithSerializedDataJni(): failure - session failure OOM");
    }
    else if(0 == aKey)
    {
        LOGE(" ## initWithSerializedDataJni(): failure - invalid key");
    }
    else if(0 == aSerializedData)
    {
        LOGE(" ## initWithSerializedDataJni(): failure - serialized data");
    }
    else if(NULL == (keyPtr = env->GetStringUTFChars(aKey, 0)))
    {
        LOGE(" ## initWithSerializedDataJni(): failure - keyPtr JNI allocation OOM");
    }
    else if(NULL == (pickledPtr = env->GetStringUTFChars(aSerializedData, 0)))
    {
        LOGE(" ## initWithSerializedDataJni(): failure - pickledPtr JNI allocation OOM");
    }
    else
    {
        size_t pickledLength = (size_t)env->GetStringUTFLength(aSerializedData);
        size_t keyLength = (size_t)env->GetStringUTFLength(aKey);
pedroGitt's avatar
pedroGitt committed
469
        LOGD(" ## initWithSerializedDataJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
        LOGD(" ## initWithSerializedDataJni(): key=%s",(char const *)keyPtr);
        LOGD(" ## initWithSerializedDataJni(): pickled=%s",(char const *)pickledPtr);

        size_t result = olm_unpickle_inbound_group_session(sessionPtr,
                                                           (void const *)keyPtr,
                                                           keyLength,
                                                           (void*)pickledPtr,
                                                           pickledLength);
        if(result == olm_error())
        {
            const char *errorMsgPtr = olm_inbound_group_session_last_error(sessionPtr);
            LOGE(" ## initWithSerializedDataJni(): failure - olm_unpickle_inbound_group_session() Msg=%s",errorMsgPtr);
            errorMessageRetValue = env->NewStringUTF(errorMsgPtr);
        }
        else
        {
pedroGitt's avatar
pedroGitt committed
486
            LOGD(" ## initWithSerializedDataJni(): success - result=%lu ", static_cast<long unsigned int>(result));
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
        }
    }

    // free alloc
    if(NULL != keyPtr)
    {
        env->ReleaseStringUTFChars(aKey, keyPtr);
    }

    if(NULL != pickledPtr)
    {
        env->ReleaseStringUTFChars(aSerializedData, pickledPtr);
    }

    return errorMessageRetValue;
}