/*
* Copyright 2016 OpenMarket Ltd
* Copyright 2016 Vector Creations 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_inbound_group_session.h"
using namespace AndroidOlmSdk;
/**
* Release the session allocation made by initializeInboundGroupSessionMemory().
* 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;
LOGD("## releaseSessionJni(): InBound group session IN");
if (!(sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
{
LOGE("## releaseSessionJni(): failure - invalid inbound group session instance");
}
else
{
LOGD(" ## releaseSessionJni(): sessionPtr=%p", sessionPtr);
#ifdef ENABLE_JNI_LOG
size_t retCode = olm_clear_inbound_group_session(sessionPtr);
LOGD(" ## releaseSessionJni(): clear_inbound_group_session=%lu",static_cast(retCode));
#else
olm_clear_inbound_group_session(sessionPtr);
#endif
LOGD(" ## releaseSessionJni(): free IN");
free(sessionPtr);
LOGD(" ## releaseSessionJni(): free OUT");
}
}
/**
* Initialize a new inbound group session and return it to JAVA side.
* 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
**/
JNIEXPORT jlong OLM_INBOUND_GROUP_SESSION_FUNC_DEF(createNewSessionJni)(JNIEnv *env, jobject thiz)
{
OlmInboundGroupSession* sessionPtr = NULL;
size_t sessionSize = 0;
LOGD("## createNewSessionJni(): inbound group session IN");
sessionSize = olm_inbound_group_session_size();
if (!sessionSize)
{
LOGE(" ## createNewSessionJni(): failure - inbound group session size = 0");
}
else if ((sessionPtr = (OlmInboundGroupSession*)malloc(sessionSize)))
{
sessionPtr = olm_inbound_group_session(sessionPtr);
LOGD(" ## createNewSessionJni(): success - inbound group session size=%lu",static_cast(sessionSize));
}
else
{
LOGE(" ## createNewSessionJni(): failure - inbound group session OOM");
}
return (jlong)(intptr_t)sessionPtr;
}
/**
* Create a new in-bound session.
* @param aSessionKey session key from an outbound session
*/
JNIEXPORT void OLM_INBOUND_GROUP_SESSION_FUNC_DEF(initInboundGroupSessionJni)(JNIEnv *env, jobject thiz, jbyteArray aSessionKeyBuffer)
{
const char* errorMessage = NULL;
OlmInboundGroupSession *sessionPtr = NULL;
jbyte* sessionKeyPtr = NULL;
size_t sessionResult;
LOGD("## initInboundGroupSessionJni(): inbound group session IN");
if (!(sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
{
LOGE(" ## initInboundGroupSessionJni(): failure - invalid inbound group session instance");
errorMessage = "invalid inbound group session instance";
}
else if (!aSessionKeyBuffer)
{
LOGE(" ## initInboundGroupSessionJni(): failure - invalid aSessionKey");
errorMessage = "invalid aSessionKey";
}
else if (!(sessionKeyPtr = env->GetByteArrayElements(aSessionKeyBuffer, 0)))
{
LOGE(" ## initInboundGroupSessionJni(): failure - session key JNI allocation OOM");
errorMessage = "Session key JNI allocation OOM";
}
else
{
size_t sessionKeyLength = (size_t)env->GetArrayLength(aSessionKeyBuffer);
LOGD(" ## initInboundGroupSessionJni(): sessionKeyLength=%lu",static_cast(sessionKeyLength));
sessionResult = olm_init_inbound_group_session(sessionPtr, (const uint8_t*)sessionKeyPtr, sessionKeyLength);
if (sessionResult == olm_error()) {
errorMessage = olm_inbound_group_session_last_error(sessionPtr);
LOGE(" ## initInboundGroupSessionJni(): failure - init inbound session creation Msg=%s", errorMessage);
}
else
{
LOGD(" ## initInboundGroupSessionJni(): success - result=%lu", static_cast(sessionResult));
}
}
// free local alloc
if (sessionKeyPtr)
{
env->ReleaseByteArrayElements(aSessionKeyBuffer, sessionKeyPtr, JNI_ABORT);
}
if (errorMessage)
{
env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
}
}
/**
* Get a base64-encoded identifier for this inbound group session.
*/
JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(sessionIdentifierJni)(JNIEnv *env, jobject thiz)
{
const char* errorMessage = NULL;
OlmInboundGroupSession *sessionPtr = NULL;
jbyteArray returnValue = 0;
LOGD("## sessionIdentifierJni(): inbound group session IN");
if (!(sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
{
LOGE(" ## sessionIdentifierJni(): failure - invalid inbound group session instance");
errorMessage = "invalid inbound group session instance";
}
else
{
// get the size to alloc
size_t lengthSessionId = olm_inbound_group_session_id_length(sessionPtr);
LOGD(" ## sessionIdentifierJni(): inbound group session lengthSessionId=%lu",static_cast(lengthSessionId));
uint8_t *sessionIdPtr = (uint8_t*)malloc((lengthSessionId+1)*sizeof(uint8_t));
if (!sessionIdPtr)
{
LOGE(" ## sessionIdentifierJni(): failure - inbound group session identifier allocation OOM");
errorMessage = "inbound group session identifier allocation OOM";
}
else
{
size_t result = olm_inbound_group_session_id(sessionPtr, sessionIdPtr, lengthSessionId);
if (result == olm_error())
{
errorMessage = (const char *)olm_inbound_group_session_last_error(sessionPtr);
LOGE(" ## sessionIdentifierJni(): failure - get inbound group session identifier failure Msg=%s",(const char *)olm_inbound_group_session_last_error(sessionPtr));
}
else
{
sessionIdPtr[result] = static_cast('\0');
LOGD(" ## sessionIdentifierJni(): success - inbound group session result=%lu sessionId=%s",static_cast(result), (char*)sessionIdPtr);
returnValue = env->NewByteArray(result);
env->SetByteArrayRegion(returnValue, 0 , result, (jbyte*)sessionIdPtr);
}
free(sessionIdPtr);
}
}
if (errorMessage)
{
env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
}
return returnValue;
}
JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(decryptMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aEncryptedMsgBuffer, jobject aDecryptionResult)
{
jbyteArray decryptedMsgBuffer = 0;
const char* errorMessage = NULL;
OlmInboundGroupSession *sessionPtr = NULL;
jbyte *encryptedMsgPtr = NULL;
jclass indexObjJClass = 0;
jfieldID indexMsgFieldId;
LOGD("## decryptMessageJni(): inbound group session IN");
if (!(sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
{
LOGE(" ## decryptMessageJni(): failure - invalid inbound group session ptr=NULL");
errorMessage = "invalid inbound group session ptr=NULL";
}
else if (!aEncryptedMsgBuffer)
{
LOGE(" ## decryptMessageJni(): failure - invalid encrypted message");
errorMessage = "invalid encrypted message";
}
else if (!aDecryptionResult)
{
LOGE(" ## decryptMessageJni(): failure - invalid index object");
errorMessage = "invalid index object";
}
else if (!(encryptedMsgPtr = env->GetByteArrayElements(aEncryptedMsgBuffer, 0)))
{
LOGE(" ## decryptMessageJni(): failure - encrypted message JNI allocation OOM");
errorMessage = "encrypted message JNI allocation OOM";
}
else if (!(indexObjJClass = env->GetObjectClass(aDecryptionResult)))
{
LOGE("## decryptMessageJni(): failure - unable to get index class");
errorMessage = "unable to get index class";
}
else if (!(indexMsgFieldId = env->GetFieldID(indexObjJClass,"mIndex","J")))
{
LOGE("## decryptMessageJni(): failure - unable to get index type field");
errorMessage = "unable to get index type field";
}
else
{
// get encrypted message length
size_t encryptedMsgLength = (size_t)env->GetArrayLength(aEncryptedMsgBuffer);
uint8_t *tempEncryptedPtr = static_cast(malloc(encryptedMsgLength*sizeof(uint8_t)));
// create a dedicated temp buffer to be used in next Olm API calls
if (!tempEncryptedPtr)
{
LOGE(" ## decryptMessageJni(): failure - tempEncryptedPtr allocation OOM");
errorMessage = "tempEncryptedPtr allocation OOM";
}
else
{
memcpy(tempEncryptedPtr, encryptedMsgPtr, encryptedMsgLength);
LOGD(" ## decryptMessageJni(): encryptedMsgLength=%lu encryptedMsg=%s",static_cast(encryptedMsgLength),encryptedMsgPtr);
// get max plaintext length
size_t maxPlainTextLength = olm_group_decrypt_max_plaintext_length(sessionPtr,
tempEncryptedPtr,
encryptedMsgLength);
if (maxPlainTextLength == olm_error())
{
errorMessage = olm_inbound_group_session_last_error(sessionPtr);
LOGE(" ## decryptMessageJni(): failure - olm_group_decrypt_max_plaintext_length Msg=%s", errorMessage);
}
else
{
LOGD(" ## decryptMessageJni(): maxPlaintextLength=%lu",static_cast(maxPlainTextLength));
uint32_t messageIndex = 0;
// allocate output decrypted message
uint8_t *plainTextMsgPtr = static_cast(malloc((maxPlainTextLength+1)*sizeof(uint8_t)));
// decrypt, but before reload encrypted buffer (previous one was destroyed)
memcpy(tempEncryptedPtr, encryptedMsgPtr, encryptedMsgLength);
size_t plaintextLength = olm_group_decrypt(sessionPtr,
tempEncryptedPtr,
encryptedMsgLength,
plainTextMsgPtr,
maxPlainTextLength,
&messageIndex);
if (plaintextLength == olm_error())
{
errorMessage = olm_inbound_group_session_last_error(sessionPtr);
LOGE(" ## decryptMessageJni(): failure - olm_group_decrypt Msg=%s", errorMessage);
}
else
{
// update index
env->SetLongField(aDecryptionResult, indexMsgFieldId, (jlong)messageIndex);
decryptedMsgBuffer = env->NewByteArray(plaintextLength);
env->SetByteArrayRegion(decryptedMsgBuffer, 0 , plaintextLength, (jbyte*)plainTextMsgPtr);
LOGD(" ## decryptMessageJni(): UTF-8 Conversion - decrypted returnedLg=%lu OK",static_cast(plaintextLength));
}
if (plainTextMsgPtr)
{
free(plainTextMsgPtr);
}
}
if (tempEncryptedPtr)
{
free(tempEncryptedPtr);
}
}
}
// free alloc
if (encryptedMsgPtr)
{
env->ReleaseByteArrayElements(aEncryptedMsgBuffer, encryptedMsgPtr, JNI_ABORT);
}
if (errorMessage)
{
env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
}
return decryptedMsgBuffer;
}
/**
* Serialize and encrypt session instance into a base64 string.
* @param aKeyBuffer key used to encrypt the serialized session data
* @return a base64 string if operation succeed, null otherwise
**/
JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKeyBuffer)
{
const char* errorMessage = NULL;
jbyteArray pickledDataRet = 0;
jbyte* keyPtr = NULL;
OlmInboundGroupSession* sessionPtr = NULL;
LOGD("## inbound group session serializeJni(): IN");
if (!(sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
{
LOGE(" ## serializeJni(): failure - invalid session ptr");
errorMessage = "invalid session ptr";
}
else if (!aKeyBuffer)
{
LOGE(" ## serializeJni(): failure - invalid key");
errorMessage = "invalid key";
}
else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
{
LOGE(" ## serializeJni(): failure - keyPtr JNI allocation OOM");
errorMessage = "keyPtr JNI allocation OOM";
}
else
{
size_t pickledLength = olm_pickle_inbound_group_session_length(sessionPtr);
size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
LOGD(" ## serializeJni(): pickledLength=%lu keyLength=%lu", static_cast(pickledLength), static_cast(keyLength));
LOGD(" ## serializeJni(): key=%s",(char const *)keyPtr);
void *pickledPtr = malloc((pickledLength+1)*sizeof(uint8_t));
if (!pickledPtr)
{
LOGE(" ## serializeJni(): failure - pickledPtr buffer OOM");
errorMessage = "pickledPtr buffer OOM";
}
else
{
size_t result = olm_pickle_inbound_group_session(sessionPtr,
(void const *)keyPtr,
keyLength,
(void*)pickledPtr,
pickledLength);
if (result == olm_error())
{
errorMessage = olm_inbound_group_session_last_error(sessionPtr);
LOGE(" ## serializeJni(): failure - olm_pickle_outbound_group_session() Msg=%s", errorMessage);
}
else
{
(static_cast(pickledPtr))[pickledLength] = static_cast('\0');
LOGD(" ## serializeJni(): success - result=%lu pickled=%s", static_cast(result), static_cast(pickledPtr));
pickledDataRet = env->NewByteArray(pickledLength);
env->SetByteArrayRegion(pickledDataRet, 0 , pickledLength, (jbyte*)pickledPtr);
}
free(pickledPtr);
}
}
// free alloc
if (keyPtr)
{
env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
}
if (errorMessage)
{
env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
}
return pickledDataRet;
}
JNIEXPORT jstring OLM_INBOUND_GROUP_SESSION_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedDataBuffer, jbyteArray aKeyBuffer)
{
OlmInboundGroupSession* sessionPtr = NULL;
jstring errorMessageRetValue = 0;
jbyte* keyPtr = NULL;
jbyte* pickledPtr = NULL;
LOGD("## deserializeJni(): IN");
if (!(sessionPtr = (OlmInboundGroupSession*)getInboundGroupSessionInstanceId(env,thiz)))
{
LOGE(" ## deserializeJni(): failure - session failure OOM");
}
else if (!aKeyBuffer)
{
LOGE(" ## deserializeJni(): failure - invalid key");
}
else if (!aSerializedDataBuffer)
{
LOGE(" ## deserializeJni(): failure - serialized data");
}
else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
{
LOGE(" ## deserializeJni(): failure - keyPtr JNI allocation OOM");
}
else if (!(pickledPtr = env->GetByteArrayElements(aSerializedDataBuffer, 0)))
{
LOGE(" ## deserializeJni(): failure - pickledPtr JNI allocation OOM");
}
else
{
size_t pickledLength = (size_t)env->GetArrayLength(aSerializedDataBuffer);
size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
LOGD(" ## deserializeJni(): pickledLength=%lu keyLength=%lu",static_cast(pickledLength), static_cast(keyLength));
LOGD(" ## deserializeJni(): key=%s",(char const *)keyPtr);
LOGD(" ## deserializeJni(): 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(" ## deserializeJni(): failure - olm_unpickle_inbound_group_session() Msg=%s",errorMsgPtr);
errorMessageRetValue = env->NewStringUTF(errorMsgPtr);
}
else
{
LOGD(" ## deserializeJni(): success - result=%lu ", static_cast(result));
}
}
// free alloc
if (keyPtr)
{
env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
}
if (pickledPtr)
{
env->ReleaseByteArrayElements(aSerializedDataBuffer, pickledPtr, JNI_ABORT);
}
return errorMessageRetValue;
}