olm_account.cpp 23.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
 * Copyright 2016 OpenMarket Ltd
 *
 * 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_account.h"

pedroGitt's avatar
pedroGitt committed
19
20
using namespace AndroidOlmSdk;

21
22
23
24
25
26
27
/*jstring serializeDataWithKey(JNIEnv *env, jobject thiz,
                                jstring aKey,
                                jobject aErrorMsg,
                                olmPickleLengthFuncPtr<OlmAccount*> aGetLengthFunc,
                                olmPickleFuncPtr<OlmAccount*> aGetPickleFunc,
                                olmLastErrorFuncPtr<OlmAccount*> aGetLastErrorFunc);*/

28
29
/**
* Init memory allocation for account creation.
30
* @return valid memory allocation, NULL otherwise
31
32
33
34
35
36
37
38
39
**/
OlmAccount* initializeAccountMemory()
{
    OlmAccount* accountPtr = NULL;
    size_t accountSize = olm_account_size();

    if(NULL != (accountPtr=(OlmAccount*)malloc(accountSize)))
    { // init account object
      accountPtr = olm_account(accountPtr);
pedroGitt's avatar
pedroGitt committed
40
      LOGD("## initializeAccountMemory(): success - OLM account size=%lu",static_cast<long unsigned int>(accountSize));
41
42
43
44
45
46
47
48
49
    }
    else
    {
      LOGE("## initializeAccountMemory(): failure - OOM");
    }

    return accountPtr;
}

50
51
52
53
54
55
56
57
58
59
60

JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(createNewAccountJni)(JNIEnv *env, jobject thiz)
{
    LOGD("## createNewAccountJni(): IN");
    OlmAccount* accountPtr = initializeAccountMemory();

    LOGD(" ## createNewAccountJni(): success - accountPtr=%p (jlong)(intptr_t)accountPtr=%lld",accountPtr,(jlong)(intptr_t)accountPtr);
    return (jlong)(intptr_t)accountPtr;
}


61
62
63
64
65
/**
 * Release the account allocation made by initializeAccountMemory().<br>
 * This method MUST be called when java counter part account instance is done.
 *
 */
pedroGitt's avatar
pedroGitt committed
66
JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(releaseAccountJni)(JNIEnv *env, jobject thiz)
67
68
69
{
  OlmAccount* accountPtr = NULL;

70
  LOGD("## releaseAccountJni(): IN");
71
72
73

  if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
  {
74
      LOGE(" ## releaseAccountJni(): failure - invalid Account ptr=NULL");
75
76
  }
  else
pedroGitt's avatar
pedroGitt committed
77
  {
78
    LOGD(" ## releaseAccountJni(): accountPtr=%p",accountPtr);
pedroGitt's avatar
pedroGitt committed
79
80
    olm_clear_account(accountPtr);

81
    LOGD(" ## releaseAccountJni(): IN");
pedroGitt's avatar
pedroGitt committed
82
    // even if free(NULL) does not crash, logs are performed for debug purpose
83
    free(accountPtr);
84
    LOGD(" ## releaseAccountJni(): OUT");
85
86
87
88
89
90
  }
}

/**
* Initialize a new account and return it to JAVA side.<br>
* Since a C prt is returned as a jlong, special care will be taken
91
* to make the cast (OlmAccount* => jlong) platform independent.
92
93
* @return the initialized OlmAccount* instance if init succeed, NULL otherwise
**/
pedroGitt's avatar
pedroGitt committed
94
JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(initNewAccountJni)(JNIEnv *env, jobject thiz)
95
{
pedroGitt's avatar
pedroGitt committed
96
97
    OlmAccount *accountPtr = NULL;
    uint8_t *randomBuffPtr = NULL;
98
    size_t accountRetCode;
pedroGitt's avatar
pedroGitt committed
99
    size_t randomSize;
100
101
102
103
104
105
106
107

    // init account memory allocation
    if(NULL == (accountPtr = initializeAccountMemory()))
    {
        LOGE("## initNewAccount(): failure - init account OOM");
    }
    else
    {
108
        // get random buffer size
109
        randomSize = olm_create_account_random_length(accountPtr);
pedroGitt's avatar
pedroGitt committed
110
        LOGD("## initNewAccount(): randomSize=%lu", static_cast<long unsigned int>(randomSize));
111
112
113

        // allocate random buffer
        if((0!=randomSize) && !setRandomInBuffer(&randomBuffPtr, randomSize))
114
        {
pedroGitt's avatar
pedroGitt committed
115
            LOGE("## initNewAccount(): failure - random buffer init");
116
117
        }
        else
pedroGitt's avatar
pedroGitt committed
118
        {
119
            // create account
pedroGitt's avatar
pedroGitt committed
120
            accountRetCode = olm_create_account(accountPtr, (void*)randomBuffPtr, randomSize);
121
            if(accountRetCode == olm_error()) {
122
                LOGE("## initNewAccount(): failure - account creation failed Msg=%s", (const char *)olm_account_last_error(accountPtr));
123
124
125
126
127
128
129
             }

            LOGD("## initNewAccount(): success - OLM account created");
            LOGD("## initNewAccount(): success - accountPtr=%p (jlong)(intptr_t)accountPtr=%lld",accountPtr,(jlong)(intptr_t)accountPtr);
        }
    }

pedroGitt's avatar
pedroGitt committed
130
131
132
133
134
    if(NULL != randomBuffPtr)
    {
        free(randomBuffPtr);
    }

135
136
137
    return (jlong)(intptr_t)accountPtr;
}

pedroGitt's avatar
pedroGitt committed
138
139


140
141
142
143
144
145
146
147
// *********************************************************************
// ************************* IDENTITY KEYS API *************************
// *********************************************************************
/**
* Get identity keys: Ed25519 fingerprint key and Curve25519 identity key.<br>
* The keys are returned in the byte array.
* @return a valid byte array if operation succeed, null otherwise
**/
pedroGitt's avatar
pedroGitt committed
148
JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(identityKeysJni)(JNIEnv *env, jobject thiz)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
{
    OlmAccount* accountPtr = NULL;
    size_t identityKeysLength;
    uint8_t *identityKeysBytesPtr;
    size_t keysResult;
    jbyteArray byteArrayRetValue = NULL;

    LOGD("## identityKeys(): accountPtr =%p",accountPtr);

    if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    {
        LOGE("## identityKeys(): failure - invalid Account ptr=NULL");
    }
    else
    {   // identity keys allocation
        identityKeysLength = olm_account_identity_keys_length(accountPtr);
165
        if(NULL == (identityKeysBytesPtr=(uint8_t*)malloc(identityKeysLength*sizeof(uint8_t))))
166
167
168
169
170
171
172
        {
            LOGE("## identityKeys(): failure - identity keys array OOM");
        }
        else
        {   // retrieve key pairs in identityKeysBytesPtr
            keysResult = olm_account_identity_keys(accountPtr, identityKeysBytesPtr, identityKeysLength);
            if(keysResult == olm_error()) {
173
                LOGE("## identityKeys(): failure - error getting identity keys Msg=%s",(const char *)olm_account_last_error(accountPtr));
174
175
176
177
178
179
180
181
182
183
            }
            else
            {   // allocate the byte array to be returned to java
                if(NULL == (byteArrayRetValue=env->NewByteArray(identityKeysLength)))
                {
                    LOGE("## identityKeys(): failure - return byte array OOM");
                }
                else
                {
                    env->SetByteArrayRegion(byteArrayRetValue, 0/*offset*/, identityKeysLength, (const jbyte*)identityKeysBytesPtr);
pedroGitt's avatar
pedroGitt committed
184
                    LOGD("## identityKeys(): success - result=%lu", static_cast<long unsigned int>(keysResult));
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
                }
            }

            free(identityKeysBytesPtr);
        }
    }

    return byteArrayRetValue;
}

// *********************************************************************
// ************************* ONE TIME KEYS API *************************
// *********************************************************************
/**
 * Get the maximum number of "one time keys" the account can store.
 *
**/
pedroGitt's avatar
pedroGitt committed
202
JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(maxOneTimeKeysJni)(JNIEnv *env, jobject thiz)
203
204
205
206
207
208
209
210
211
212
213
214
{
    OlmAccount* accountPtr = NULL;
    size_t maxKeys = -1;

    if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    {
        LOGE("## maxOneTimeKey(): failure - invalid Account ptr=NULL");
    }
    else
    {
        maxKeys = olm_account_max_number_of_one_time_keys(accountPtr);
    }
pedroGitt's avatar
pedroGitt committed
215
    LOGD("## maxOneTimeKey(): Max keys=%lu", static_cast<long unsigned int>(maxKeys));
216
217
218
219
220
221
222
223
224

    return (jlong)maxKeys;
}

/**
 * Generate "one time keys".
 * @param aNumberOfKeys number of keys to generate
 * @return ERROR_CODE_OK if operation succeed, ERROR_CODE_KO otherwise
**/
pedroGitt's avatar
pedroGitt committed
225
JNIEXPORT jint OLM_ACCOUNT_FUNC_DEF(generateOneTimeKeysJni)(JNIEnv *env, jobject thiz, jint aNumberOfKeys)
226
{
pedroGitt's avatar
pedroGitt committed
227
228
    OlmAccount *accountPtr = NULL;
    uint8_t *randomBufferPtr = NULL;
229
    jint retCode = ERROR_CODE_KO;
pedroGitt's avatar
pedroGitt committed
230
    size_t randomLength;
231
232
233
234
235
    size_t result;


    if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    {
pedroGitt's avatar
pedroGitt committed
236
        LOGE("## generateOneTimeKeysJni(): failure - invalid Account ptr");
237
238
239
    }
    else
    {   // keys memory allocation
240
        randomLength = olm_account_generate_one_time_keys_random_length(accountPtr, (size_t)aNumberOfKeys);
pedroGitt's avatar
pedroGitt committed
241
        LOGD("## generateOneTimeKeysJni(): randomLength=%lu", static_cast<long unsigned int>(randomLength));
pedroGitt's avatar
pedroGitt committed
242

243
        if((0!=randomLength) && !setRandomInBuffer(&randomBufferPtr, randomLength))
244
        {
pedroGitt's avatar
pedroGitt committed
245
            LOGE("## generateOneTimeKeysJni(): failure - random buffer init");
246
247
        }
        else
pedroGitt's avatar
pedroGitt committed
248
        {
pedroGitt's avatar
pedroGitt committed
249
            LOGD("## generateOneTimeKeysJni(): accountPtr =%p aNumberOfKeys=%d",accountPtr, aNumberOfKeys);
pedroGitt's avatar
pedroGitt committed
250
251

            // retrieve key pairs in keysBytesPtr
252
            result = olm_account_generate_one_time_keys(accountPtr, (size_t)aNumberOfKeys, (void*)randomBufferPtr, randomLength);
253
            if(result == olm_error()) {
pedroGitt's avatar
pedroGitt committed
254
                LOGE("## generateOneTimeKeysJni(): failure - error generating one time keys Msg=%s",(const char *)olm_account_last_error(accountPtr));
255
256
257
258
            }
            else
            {
                retCode = ERROR_CODE_OK;
pedroGitt's avatar
pedroGitt committed
259
                LOGD("## generateOneTimeKeysJni(): success - result=%lu", static_cast<long unsigned int>(result));
260
261
262
263
            }
        }
    }

pedroGitt's avatar
pedroGitt committed
264
265
266
267
268
    if(NULL != randomBufferPtr)
    {
        free(randomBufferPtr);
    }

269
270
271
272
    return retCode;
}

/**
273
 * Get "one time keys".<br>
274
275
276
 * Return the public parts of the unpublished "one time keys" for the account
 * @return a valid byte array if operation succeed, null otherwise
**/
pedroGitt's avatar
pedroGitt committed
277
JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(oneTimeKeysJni)(JNIEnv *env, jobject thiz)
278
279
280
281
282
283
284
{
    OlmAccount* accountPtr = NULL;
    size_t keysLength;
    uint8_t *keysBytesPtr;
    size_t keysResult;
    jbyteArray byteArrayRetValue = NULL;

pedroGitt's avatar
pedroGitt committed
285
    LOGD("## oneTimeKeysJni(): IN");
286
287
288

    if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    {
pedroGitt's avatar
pedroGitt committed
289
        LOGE("## oneTimeKeysJni(): failure - invalid Account ptr");
290
291
292
293
294
295
    }
    else
    {   // keys memory allocation
        keysLength = olm_account_one_time_keys_length(accountPtr);
        if(NULL == (keysBytesPtr=(uint8_t *)malloc(keysLength*sizeof(uint8_t))))
        {
pedroGitt's avatar
pedroGitt committed
296
            LOGE("## oneTimeKeysJni(): failure - one time keys array OOM");
297
298
299
300
301
        }
        else
        {   // retrieve key pairs in keysBytesPtr
            keysResult = olm_account_one_time_keys(accountPtr, keysBytesPtr, keysLength);
            if(keysResult == olm_error()) {
302
                LOGE("## oneTimeKeysJni(): failure - error getting one time keys Msg=%s",(const char *)olm_account_last_error(accountPtr));
303
304
305
306
307
            }
            else
            {   // allocate the byte array to be returned to java
                if(NULL == (byteArrayRetValue=env->NewByteArray(keysLength)))
                {
pedroGitt's avatar
pedroGitt committed
308
                    LOGE("## oneTimeKeysJni(): failure - return byte array OOM");
309
310
311
312
                }
                else
                {
                    env->SetByteArrayRegion(byteArrayRetValue, 0/*offset*/, keysLength, (const jbyte*)keysBytesPtr);
pedroGitt's avatar
pedroGitt committed
313
                    LOGD("## oneTimeKeysJni(): success");
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
                }
            }

            free(keysBytesPtr);
        }
    }

    return byteArrayRetValue;
}

/**
 * Remove the "one time keys"  that the session used from the account.
 * Return the public parts of the unpublished "one time keys" for the account
 * @param aNativeOlmSessionId session instance
 * @return ERROR_CODE_OK if operation succeed, ERROR_CODE_NO_MATCHING_ONE_TIME_KEYS if no matching keys, ERROR_CODE_KO otherwise
**/
330
JNIEXPORT jint OLM_ACCOUNT_FUNC_DEF(removeOneTimeKeysForSessionJni)(JNIEnv *env, jobject thiz, jlong aNativeOlmSessionId)
331
332
333
334
335
336
337
338
{
    jint retCode = ERROR_CODE_KO;
    OlmAccount* accountPtr = NULL;
    OlmSession* sessionPtr = (OlmSession*)aNativeOlmSessionId;
    size_t result;

    if(NULL == sessionPtr)
    {
339
        LOGE("## removeOneTimeKeysForSessionJni(): failure - invalid session ptr");
340
341
342
    }
    else if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    {
343
        LOGE("## removeOneTimeKeysForSessionJni(): failure - invalid account ptr");
344
345
346
347
348
349
    }
    else
    {
        result = olm_remove_one_time_keys(accountPtr, sessionPtr);
        if(result == olm_error())
        {   // the account doesn't have any matching "one time keys"..
350
            LOGW("## removeOneTimeKeysForSessionJni(): failure - removing one time keys Msg=%s",(const char *)olm_account_last_error(accountPtr));
351
352
353
354
355
356

            retCode = ERROR_CODE_NO_MATCHING_ONE_TIME_KEYS;
        }
        else
        {
            retCode = ERROR_CODE_OK;
357
            LOGD("## removeOneTimeKeysForSessionJni(): success");
358
359
360
361
362
363
364
365
366
367
        }
    }

    return retCode;
}

/**
 * Mark the current set of "one time keys" as being published.
 * @return ERROR_CODE_OK if operation succeed, ERROR_CODE_KO otherwise
**/
368
JNIEXPORT jint OLM_ACCOUNT_FUNC_DEF(markOneTimeKeysAsPublishedJni)(JNIEnv *env, jobject thiz)
369
370
371
372
373
374
375
{
    jint retCode = ERROR_CODE_OK;
    OlmAccount* accountPtr = NULL;
    size_t result;

    if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    {
376
        LOGE("## markOneTimeKeysAsPublishedJni(): failure - invalid account ptr");
377
378
379
380
381
382
383
        retCode = ERROR_CODE_KO;
    }
    else
    {
        result = olm_account_mark_keys_as_published(accountPtr);
        if(result == olm_error())
        {
384
            LOGW("## markOneTimeKeysAsPublishedJni(): failure - Msg=%s",(const char *)olm_account_last_error(accountPtr));
385
386
387
388
            retCode = ERROR_CODE_KO;
        }
        else
        {
pedroGitt's avatar
pedroGitt committed
389
            LOGD("## markOneTimeKeysAsPublishedJni(): success - retCode=%lu",static_cast<long unsigned int>(result));
390
391
392
393
394
395
396
        }
    }

    return retCode;
}

/**
397
398
 * Sign a message with the ed25519 key (fingerprint) for this account.<br>
 * The signed message is returned by the function.
399
 * @param aMessage message to sign
400
 * @return the signed message, null otherwise
401
**/
402
JNIEXPORT jstring OLM_ACCOUNT_FUNC_DEF(signMessageJni)(JNIEnv *env, jobject thiz, jstring aMessage)
403
404
405
{
    OlmAccount* accountPtr = NULL;
    size_t signatureLength;
406
    void* signedMsgPtr;
407
408
409
410
411
    size_t resultSign;
    jstring signedMsgRetValue = NULL;

    if(NULL == aMessage)
    {
412
        LOGE("## signMessageJni(): failure - invalid aMessage param");
413
414
415
    }
    else if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    {
416
        LOGE("## signMessageJni(): failure - invalid account ptr");
417
418
419
420
421
422
423
    }
    else
    {
        // convert message from JAVA to C string
        const char* messageToSign = env->GetStringUTFChars(aMessage, 0);
        if(NULL == messageToSign)
        {
424
            LOGE("## signMessageJni(): failure - message JNI allocation OOM");
425
426
427
428
429
430
431
        }
        else
        {
            int messageLength = env->GetStringUTFLength(aMessage);

            // signature memory allocation
            signatureLength = olm_account_signature_length(accountPtr);
pedroGitt's avatar
pedroGitt committed
432
            if(NULL == (signedMsgPtr = (void*)malloc((signatureLength+1)*sizeof(uint8_t))))
433
            {
434
                LOGE("## signMessageJni(): failure - signature allocation OOM");
435
436
437
            }
            else
            {   // sign message
438
439
440
441
442
                resultSign = olm_account_sign(accountPtr,
                                             (void*)messageToSign,
                                             (size_t)messageLength,
                                             signedMsgPtr,
                                             signatureLength);
443
444
                if(resultSign == olm_error())
                {
445
                    LOGE("## signMessageJni(): failure - error signing message Msg=%s",(const char *)olm_account_last_error(accountPtr));
446
447
                }
                else
448
                {
pedroGitt's avatar
pedroGitt committed
449
450
                    // info: signatureLength is always equal to resultSign
                    (static_cast<char*>(signedMsgPtr))[signatureLength] = static_cast<char>('\0');
451
                    // convert to jstring
452
                    signedMsgRetValue = env->NewStringUTF((const char*)signedMsgPtr); // UTF8
pedroGitt's avatar
pedroGitt committed
453
                    LOGD("## signMessageJni(): success - retCode=%lu signatureLength=%lu", static_cast<long unsigned int>(resultSign), static_cast<long unsigned int>(signatureLength));
454
455
                }

456
                free(signedMsgPtr);
457
458
459
460
461
462
463
464
465
466
467
            }

            // release messageToSign
            env->ReleaseStringUTFChars(aMessage, messageToSign);
        }
    }

    return signedMsgRetValue;
}


pedroGitt's avatar
pedroGitt committed
468
JNIEXPORT jstring OLM_MANAGER_FUNC_DEF(getOlmLibVersion)(JNIEnv* env, jobject thiz)
469
470
471
472
473
474
475
476
477
478
479
480
481
482
{
  uint8_t majorVer=0, minorVer=0, patchVer=0;
  jstring returnValueStr=0;
  char buff[150];

  olm_get_library_version(&majorVer, &minorVer, &patchVer);
  LOGD("## getOlmLibVersion(): Major=%d Minor=%d Patch=%d", majorVer, minorVer, patchVer);

  snprintf(buff, sizeof(buff), " V%d.%d.%d", majorVer, minorVer, patchVer);
  returnValueStr = env->NewStringUTF((const char*)buff);

  return returnValueStr;
}

483
484
485
486
487
488
489
490
/**
* Serialize and encrypt account instance into a base64 string.<br>
* @param aKey key used to encrypt the serialized account data
* @param[out] aErrorMsg error message set if operation failed
* @return a base64 string if operation succeed, null otherwise
**/
JNIEXPORT jstring OLM_ACCOUNT_FUNC_DEF(serializeDataWithKeyJni)(JNIEnv *env, jobject thiz, jstring aKey, jobject aErrorMsg)
{
491
492
493
494
495
496
497
498
    /*jstring pickledDataRetValue = serializeDataWithKey(env,thiz,
                                                          aKey,
                                                          aErrorMsg,
                                                          olm_pickle_account_length,
                                                          olm_pickle_account,
                                                          olm_account_last_error);
    return pickledDataRetValue;*/

499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
    jstring pickledDataRetValue = 0;
    jclass errorMsgJClass = 0;
    jmethodID errorMsgMethodId = 0;
    jstring errorJstring = 0;
    const char *keyPtr = NULL;
    void *pickledPtr = NULL;
    OlmAccount* accountPtr = NULL;

    LOGD("## serializeDataWithKeyJni(): IN");

    if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    {
        LOGE(" ## serializeDataWithKeyJni(): failure - invalid account 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_account_length(accountPtr);
        size_t keyLength = (size_t)env->GetStringUTFLength(aKey);
pedroGitt's avatar
pedroGitt committed
537
        LOGD(" ## serializeDataWithKeyJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
        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_account(accountPtr,
                                               (void const *)keyPtr,
                                               keyLength,
                                               (void*)pickledPtr,
                                               pickledLength);
            if(result == olm_error())
            {
                const char *errorMsgPtr = olm_account_last_error(accountPtr);
                LOGE(" ## serializeDataWithKeyJni(): failure - olm_pickle_account() 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
566
                LOGD(" ## serializeDataWithKeyJni(): success - result=%lu pickled=%s", static_cast<long unsigned int>(result), static_cast<char*>(pickledPtr));
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
            }
        }
    }

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

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

    return pickledDataRetValue;
}


JNIEXPORT jstring OLM_ACCOUNT_FUNC_DEF(initWithSerializedDataJni)(JNIEnv *env, jobject thiz, jstring aSerializedData, jstring aKey)
{
    OlmAccount* accountPtr = NULL;
    jstring errorMessageRetValue = 0;
    const char *keyPtr = NULL;
    const char *pickledPtr = NULL;

    LOGD("## initWithSerializedDataJni(): IN");

    if(NULL == (accountPtr = (OlmAccount*)getAccountInstanceId(env,thiz)))
    //if(NULL == (accountPtr = initializeAccountMemory()))
    {
        LOGE(" ## initWithSerializedDataJni(): failure - account 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
620
        LOGD(" ## initWithSerializedDataJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
        LOGD(" ## initWithSerializedDataJni(): key=%s",(char const *)keyPtr);
        LOGD(" ## initWithSerializedDataJni(): pickled=%s",(char const *)pickledPtr);

        size_t result = olm_unpickle_account(accountPtr,
                                             (void const *)keyPtr,
                                             keyLength,
                                             (void*)pickledPtr,
                                             pickledLength);
        if(result == olm_error())
        {
            const char *errorMsgPtr = olm_account_last_error(accountPtr);
            LOGE(" ## initWithSerializedDataJni(): failure - olm_unpickle_account() Msg=%s",errorMsgPtr);
            errorMessageRetValue = env->NewStringUTF(errorMsgPtr);
        }
        else
        {
pedroGitt's avatar
pedroGitt committed
637
            LOGD(" ## initWithSerializedDataJni(): success - result=%lu ", static_cast<long unsigned int>(result));
638
639
640
641
642
643
644
645
646
647
648
649
650
        }
    }

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

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

652
653
    return errorMessageRetValue;
}