olm_jni_helper.cpp 8.68 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * Created by pedrocon on 06/10/2016.
 */
/*
 * 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.
 */

pedroGitt's avatar
pedroGitt committed
20
#include "olm_jni_helper.h"
21
#include "olm/olm.h"
22
#include <sys/time.h>
pedroGitt's avatar
pedroGitt committed
23
24

using namespace AndroidOlmSdk;
25
26
27
28
29
30
31

/**
* Init a buffer with a given number of random values.
* @param aBuffer2Ptr the buffer to be initialized
* @param aRandomSize the number of random values to apply
* @return true if operation succeed, false otherwise
**/
32
bool setRandomInBuffer(JNIEnv *env, uint8_t **aBuffer2Ptr, size_t aRandomSize)
33
34
{
    bool retCode = false;
35
    struct timeval timeValue;
36
    int bufferLen = aRandomSize*sizeof(uint8_t);
37

38
39
    if(NULL == aBuffer2Ptr)
    {
pedroGitt's avatar
pedroGitt committed
40
        LOGE("## setRandomInBuffer(): failure - aBuffer=NULL");
41
42
43
    }
    else if(0 == aRandomSize)
    {
pedroGitt's avatar
pedroGitt committed
44
        LOGE("## setRandomInBuffer(): failure - random size=0");
45
    }
46
    else if(NULL == (*aBuffer2Ptr = (uint8_t*)malloc(bufferLen)))
47
    {
pedroGitt's avatar
pedroGitt committed
48
        LOGE("## setRandomInBuffer(): failure - alloc mem OOM");
49
50
51
    }
    else
    {
pedroGitt's avatar
pedroGitt committed
52
        LOGD("## setRandomInBuffer(): randomSize=%lu",static_cast<long unsigned int>(aRandomSize));
53

54
        bool secureRandomSucceeds = false;
55

56
57
58
59
60
61
62
        // clear the buffer
        memset(*aBuffer2Ptr, 0, bufferLen);

        // use the secureRandom class
        jclass cls = env->FindClass("java/security/SecureRandom");

        if (cls)
63
        {
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
            jobject newObj = 0;
            jmethodID constructor = env->GetMethodID(cls, "<init>", "()V");
            jmethodID nextByteMethod = env->GetMethodID(cls, "nextBytes", "([B)V");

            if (constructor)
            {
                newObj = env->NewObject(cls, constructor);
                jbyteArray tempByteArray = env->NewByteArray(bufferLen);

                if (newObj && tempByteArray)
                {
                    env->CallVoidMethod(newObj, nextByteMethod, tempByteArray);

                    jbyte* buffer = env->GetByteArrayElements(tempByteArray,0);

                    if (buffer)
                    {
                        memcpy(*aBuffer2Ptr, buffer, bufferLen);
                        secureRandomSucceeds = true;
                    }
                }

                if (tempByteArray)
                {
                    env->DeleteLocalRef(tempByteArray);
                }

                if (newObj)
                {
                    env->DeleteLocalRef(newObj);
                }
            }
96
97
        }

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        if (!secureRandomSucceeds)
        {
            LOGE("## setRandomInBuffer(): SecureRandom failed, use a fallback");

            gettimeofday(&timeValue, NULL);
            srand(timeValue.tv_usec); // init seed

            for(size_t i=0;i<aRandomSize;i++)
            {
                (*aBuffer2Ptr)[i] = (uint8_t)(rand()%ACCOUNT_CREATION_RANDOM_MODULO);
            }
        }

        // debug purpose
        /*for(int i = 0; i < aRandomSize; i++)
        {
            LOGD("## setRandomInBuffer(): randomBuffPtr[%ld]=%d",i, (*aBuffer2Ptr)[i]);
        }*/

117
118
119
120
121
122
123
        retCode = true;
    }
    return retCode;
}


/**
124
* Read the instance ID of the calling object.
125
126
* @param aJniEnv pointer pointing on the JNI function table
* @param aJavaObject reference to the object on which the method is invoked
127
* @param aCallingClass java calling clas name
128
129
* @return the instance ID if operation succeed, -1 if instance ID was not found.
**/
130
jlong getInstanceId(JNIEnv* aJniEnv, jobject aJavaObject, const char *aCallingClass)
131
{
pedroGitt's avatar
pedroGitt committed
132
  jlong instanceId = 0;
133
134
  jfieldID instanceIdField;
  jclass loaderClass;
135
  jclass requiredClass = 0;
136
137
138

  if(NULL!=aJniEnv)
  {
139
    requiredClass = aJniEnv->FindClass(aCallingClass);
140
141
142

    if((0 != requiredClass) && (JNI_TRUE != aJniEnv->IsInstanceOf(aJavaObject, requiredClass)))
    {
pedroGitt's avatar
pedroGitt committed
143
        LOGE("## getAccountInstanceId() failure - invalid instance of");
144
145
    }
    else if(0 != (loaderClass=aJniEnv->GetObjectClass(aJavaObject)))
146
    {
147
      if(0 != (instanceIdField=aJniEnv->GetFieldID(loaderClass, "mNativeId", "J")))
148
149
150
      {
        instanceId = aJniEnv->GetLongField(aJavaObject, instanceIdField);
        aJniEnv->DeleteLocalRef(loaderClass);
151
        LOGD("## getInstanceId(): read from java instanceId=%lld",instanceId);
152
153
154
      }
      else
      {
155
        LOGE("## getInstanceId() ERROR! GetFieldID=null");
156
157
158
159
      }
    }
    else
    {
160
      LOGE("## getInstanceId() ERROR! GetObjectClass=null");
161
162
163
164
    }
  }
  else
  {
165
    LOGE("## getInstanceId() ERROR! aJniEnv=NULL");
166
  }
167
  LOGD("## getInstanceId() success - instanceId=%p (jlong)(intptr_t)instanceId=%lld",(void*)instanceId, (jlong)(intptr_t)instanceId);
168
169
170
171
  return instanceId;
}

/**
172
* Read the account instance ID of the calling object.
173
174
* @param aJniEnv pointer pointing on the JNI function table
* @param aJavaObject reference to the object on which the method is invoked
175
* @return the instance ID if operation succeed, -1 if instance ID was not found.
176
**/
177
jlong getAccountInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
178
{
179
180
181
  jlong instanceId = getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_ACCOUNT);
  return instanceId;
}
182

183

184

185
186
187
188
189
190
191
192
193
/**
* Read the session instance ID of the calling object (aJavaObject).<br>
* @param aJniEnv pointer pointing on the JNI function table
* @param aJavaObject reference to the object on which the method is invoked
* @return the instance ID if read succeed, -1 otherwise.
**/
jlong getSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
{
  jlong instanceId = getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_SESSION);
194
195
196
197
198
199
200
201
202
203
204
  return instanceId;
}

/**
* Read the inbound group session instance ID of the calling object (aJavaObject).<br>
* @param aJniEnv pointer pointing on the JNI function table
* @param aJavaObject reference to the object on which the method is invoked
* @return the instance ID if read succeed, -1 otherwise.
**/
jlong getInboundGroupSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
{
205
  jlong instanceId = getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_INBOUND_GROUP_SESSION);
206
207
208
209
210
211
212
213
214
215
216
217
  return instanceId;
}


/**
* Read the outbound group session instance ID of the calling object (aJavaObject).<br>
* @param aJniEnv pointer pointing on the JNI function table
* @param aJavaObject reference to the object on which the method is invoked
* @return the instance ID if read succeed, -1 otherwise.
**/
jlong getOutboundGroupSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
{
218
  jlong instanceId = getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_OUTBOUND_GROUP_SESSION);
219
220
221
  return instanceId;
}

222
223
224
225
226
227
/**
* Read the utility instance ID of the calling object (aJavaObject).<br>
* @param aJniEnv pointer pointing on the JNI function table
* @param aJavaObject reference to the object on which the method is invoked
* @return the instance ID if read succeed, -1 otherwise.
**/
228
229
jlong getUtilityInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
{
230
  jlong instanceId = getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_UTILITY);
231
232
  return instanceId;
}
233

234

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/**
* Convert a C string into a UTF-8 format string.
* The conversion is performed in JAVA side to workaround the issue in  NewStringUTF().
* The problem is described here: https://github.com/eclipsesource/J2V8/issues/142
*/
jstring javaCStringToUtf8(JNIEnv *env, uint8_t *aCStringMsgPtr, size_t aMsgLength)
{
    jstring convertedRetValue = 0;
    jbyteArray tempByteArray = NULL;

    if((NULL == aCStringMsgPtr) || (NULL == env))
    {
        LOGE("## javaCStringToUtf8(): failure - invalid parameters (null)");
    }
    else if(NULL == (tempByteArray=env->NewByteArray(aMsgLength)))
    {
        LOGE("## javaCStringToUtf8(): failure - return byte array OOM");
    }
    else
    {
        env->SetByteArrayRegion(tempByteArray, 0, aMsgLength, (const jbyte*)aCStringMsgPtr);

        // UTF-8 conversion from JAVA
        jstring strEncode = (env)->NewStringUTF("UTF-8");
        jclass jClass = env->FindClass("java/lang/String");
        jmethodID cstor = env->GetMethodID(jClass, "<init>", "([BLjava/lang/String;)V");

        if((0!=jClass) && (0!=jClass) && (0!=strEncode))
        {
            convertedRetValue = (jstring) env->NewObject(jClass, cstor, tempByteArray, strEncode);
            LOGD(" ## javaCStringToUtf8(): succeed");
            env->DeleteLocalRef(tempByteArray);
        }
        else
        {
            LOGE(" ## javaCStringToUtf8(): failure - invalid Java references");
        }
    }

    return convertedRetValue;
}