2 #include <android/log.h>
9 #include "cainterface.h"
11 #include "caadapterutils.h"
12 #include "oic_string.h"
14 #include "org_iotivity_ca_service_RMInterface.h"
16 #define LOG_TAG "JNI_INTERFACE_SAMPLE"
17 #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
18 #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
24 #define IDENTITY ("1111111111111111")
28 #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
31 #define SECURE_DEFAULT_PORT 5684
32 #define RESOURCE_URI_LENGTH 14
33 #define OPTION_INFO_LENGTH 1024
34 #define NETWORK_INFO_LENGTH 1024
35 #define BIG_PAYLOAD_LENGTH 1024
36 #define RECEIVED_FILE_NAME_PREFIX_LENGTH 7
37 #define RECEIVED_FILE_NAME_LENGTH 14
41 char ipAddress[CA_IPADDR_SIZE];
45 static void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo);
46 static void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo);
47 static void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
48 static void get_resource_uri(const char *URI, char *resourceURI, int32_t length);
49 static uint32_t get_secure_information(CAPayload_t payLoad);
50 static CAResult_t get_network_type(uint32_t selectedNetwork);
51 static void callback(char *subject, char *receivedData);
52 static CAResult_t get_remote_address(const char *address);
53 static void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
54 static void delete_global_references(JNIEnv *env, jobject obj);
55 static int get_address_set(const char *pAddress, addressSet_t* outAddress);
56 bool read_file(const char* name, char** bytes, size_t* length);
57 uint32_t gettodaydate();
58 void saveFile(const char *payload, size_t payloadSize);
60 uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
61 CATransportAdapter_t g_selectedNwType = CA_ADAPTER_IP;
62 static CAToken_t g_lastRequestToken = NULL;
63 static uint8_t g_lastRequestTokenLength = 0;
65 static const char COAP_PREFIX[] = "coap://";
66 static const char COAPS_PREFIX[] = "coaps://";
67 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
68 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
70 static const char RECEIVED_FILE_PATH[] = "/storage/emulated/0/Download/%d%s.txt";
72 static const char SECURE_INFO_DATA[]
73 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
74 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
76 static const char NORMAL_INFO_DATA[]
77 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
78 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
80 static jobject g_responseListenerObject = NULL;
83 static CAEndpoint_t *g_clientEndpoint = NULL;
84 static char *g_resourceUri = NULL;
85 static CAToken_t g_clientToken = NULL;
86 static uint8_t g_clientTokenLength = 0;
88 static uint16_t g_clientMsgId = 0;
89 static char *g_remoteAddress = NULL;
92 JNIEXPORT void JNICALL
93 Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
96 LOGI("setNativeResponseListener");
97 if (!env || !obj || !listener)
99 LOGI("Invalid input parameter");
103 g_responseListenerObject = (*env)->NewGlobalRef(env, listener);
107 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
109 void clearDtlsCredentialInfo()
111 LOGI("clearDtlsCredentialInfo IN");
114 // Initialize sensitive data to zeroes before freeing.
115 if (NULL != pskCredsBlob->creds)
117 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds)*(pskCredsBlob->num));
118 free(pskCredsBlob->creds);
121 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
125 LOGI("clearDtlsCredentialInfo OUT");
128 // Internal API. Invoked by OC stack to retrieve credentials from this module
129 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
131 LOGI("CAGetDtlsPskCredentials IN");
132 *credInfo = (CADtlsPskCredsBlob_t *) malloc(sizeof(CADtlsPskCredsBlob_t));
133 if (NULL == *credInfo)
135 LOGE("Failed to allocate credential blob.");
139 int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
140 (*credInfo)->creds = (OCDtlsPskCreds *) malloc(credLen);
141 if (NULL == (*credInfo)->creds)
143 LOGE("Failed to allocate crentials.");
149 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
150 (*credInfo)->num = pskCredsBlob->num;
151 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
153 LOGI("CAGetDtlsPskCredentials OUT");
156 CAResult_t SetCredentials()
158 LOGI("SetCredentials IN");
159 pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
160 if (NULL == pskCredsBlob)
162 LOGE("Memory allocation failed!");
163 return CA_MEMORY_ALLOC_FAILED;
165 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
167 pskCredsBlob->num = 1;
169 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) *(pskCredsBlob->num));
170 if (NULL == pskCredsBlob->creds)
172 LOGE("Memory allocation failed!");
173 return CA_MEMORY_ALLOC_FAILED;
175 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
176 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
178 LOGI("SetCredentials OUT");
183 JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
189 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
193 g_jvm = jvm; /* cache the JavaVM pointer */
195 CANativeJNISetJavaVM(g_jvm);
197 return JNI_VERSION_1_6;
200 void JNI_OnUnload(JavaVM *jvm, void *reserved)
202 LOGI("JNI_OnUnload");
206 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
214 JNIEXPORT void JNICALL
215 Java_org_iotivity_ca_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
217 LOGI("RMInitialize");
218 if (!env || !obj || !context)
220 LOGI("Invalid input parameter");
224 //Currently set context for Android Platform
225 CANativeJNISetContext(env, context);
227 CAResult_t res = CAInitialize();
229 if (CA_STATUS_OK != res)
231 LOGE("Could not Initialize");
235 if (CA_STATUS_OK != SetCredentials())
237 LOGE("SetCredentials failed");
241 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
242 if(CA_STATUS_OK != res)
244 LOGE("Set credential handler fail");
250 JNIEXPORT void JNICALL
251 Java_org_iotivity_ca_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
256 LOGI("Invalid input parameter");
260 CADestroyToken(g_lastRequestToken);
262 delete_global_references(env, obj);
265 JNIEXPORT void JNICALL
266 Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
268 LOGI("RMStartListeningServer");
271 LOGI("Invalid input parameter");
275 if (CA_STATUS_OK != CAStartListeningServer())
277 LOGE("Could not start Listening server");
281 JNIEXPORT void JNICALL
282 Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
284 LOGI("RMStartDiscoveryServer");
287 LOGI("Invalid input parameter");
291 if (CA_STATUS_OK != CAStartDiscoveryServer())
293 LOGE("Could not start discovery server");
297 JNIEXPORT void JNICALL
298 Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
300 LOGI("RMRegisterHandler");
303 LOGI("Invalid input parameter");
307 CARegisterHandler(request_handler, response_handler, error_handler);
310 JNIEXPORT void JNICALL
311 Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
312 jstring payload, jint selectedNetwork,
313 jint isSecured, jint msgType,
316 LOGI("selectedNetwork - %d", selectedNetwork);
319 LOGI("Invalid input parameter");
325 LOGE("Invalid input parameter : uri");
329 CAResult_t res = get_network_type(selectedNetwork);
330 if (CA_STATUS_OK != res)
335 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
336 LOGI("RMSendRequest - %s", strUri);
338 CATransportFlags_t flags;
339 addressSet_t address = {{0}, 0};
340 parsing_coap_uri(strUri, &address, &flags);
342 //create remote endpoint
343 CAEndpoint_t* endpoint = NULL;
344 res = CACreateEndpoint(flags, g_selectedNwType, (const char*)(address.ipAddress),
345 address.port, &endpoint);
346 if (CA_STATUS_OK != res)
348 LOGE("Could not create remote end point");
349 (*env)->ReleaseStringUTFChars(env, uri, strUri);
353 CAMessageType_t messageType = msgType;
356 CAToken_t token = NULL;
357 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
359 res = CAGenerateToken(&token, tokenLength);
360 if ((CA_STATUS_OK != res) || (!token))
362 LOGE("token generate error!!");
363 // destroy remote endpoint
364 CADestroyEndpoint(endpoint);
365 (*env)->ReleaseStringUTFChars(env, uri, strUri);
369 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
371 get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
372 (*env)->ReleaseStringUTFChars(env, uri, strUri);
374 CAInfo_t requestData = { 0 };
375 requestData.token = token;
376 requestData.tokenLength = tokenLength;
378 size_t payloadLength = 0;
381 const char* path = NULL;
384 path = (*env)->GetStringUTFChars(env, payload, NULL);
387 char* bigData = NULL;
388 bool result = read_file(path, &bigData, &payloadLength);
391 LOGE("read has failed");
392 (*env)->ReleaseStringUTFChars(env, payload, path);
393 CADestroyToken(token);
394 CADestroyEndpoint(endpoint);
397 (*env)->ReleaseStringUTFChars(env, payload, path);
399 requestData.payload = (CAPayload_t) malloc(payloadLength);
400 if (NULL == requestData.payload)
402 LOGE("Memory allocation failed!");
404 CADestroyToken(token);
405 // destroy remote endpoint
406 CADestroyEndpoint(endpoint);
409 memcpy(requestData.payload, bigData, payloadLength);
410 requestData.payloadSize = payloadLength;
418 payloadLength = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
419 requestData.payload = (CAPayload_t) malloc(payloadLength);
420 if (NULL == requestData.payload)
422 LOGE("Memory allocation failed!");
424 CADestroyToken(token);
425 // destroy remote endpoint
426 CADestroyEndpoint(endpoint);
429 snprintf((char *) requestData.payload, payloadLength, SECURE_INFO_DATA,
430 resourceURI, g_localSecurePort);
431 requestData.payloadSize = payloadLength;
435 payloadLength = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
436 requestData.payload = (CAPayload_t) malloc(payloadLength);
437 if (NULL == requestData.payload)
439 LOGE("Memory allocation failed!");
441 CADestroyToken(token);
442 // destroy remote endpoint
443 CADestroyEndpoint(endpoint);
446 snprintf((char *) requestData.payload, payloadLength, NORMAL_INFO_DATA, resourceURI);
447 requestData.payloadSize = payloadLength;
451 requestData.type = messageType;
452 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
453 if (NULL == requestData.resourceUri)
455 LOGE("Memory allocation failed!");
457 CADestroyToken(token);
458 // destroy remote endpoint
459 CADestroyEndpoint(endpoint);
460 free(requestData.payload);
463 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
465 CARequestInfo_t requestInfo = { 0 };
466 requestInfo.method = CA_GET;
467 requestInfo.isMulticast = false;
468 requestInfo.info = requestData;
471 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
473 LOGE("Could not send request");
477 CADestroyToken(token);
479 // destroy remote endpoint
480 CADestroyEndpoint(endpoint);
482 free(requestData.payload);
483 free(requestData.resourceUri);
486 JNIEXPORT void JNICALL
487 Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
488 jint selectedNetwork)
490 LOGI("selectedNetwork - %d", selectedNetwork);
493 LOGI("Invalid input parameter");
497 CAResult_t res = get_network_type(selectedNetwork);
498 if (CA_STATUS_OK != res)
503 // create remote endpoint
504 CAEndpoint_t *endpoint = NULL;
505 res = CACreateEndpoint(CA_IPV4, g_selectedNwType, NULL, 0, &endpoint);
507 if (CA_STATUS_OK != res)
509 LOGE("create remote endpoint error, error code: %d", res);
514 CAToken_t token = NULL;
515 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
517 res = CAGenerateToken(&token, tokenLength);
518 if ((CA_STATUS_OK != res) || (!token))
520 LOGE("token generate error!!");
521 // destroy remote endpoint
522 CADestroyEndpoint(endpoint);
526 LOGI("generated token %s", token);
528 CAInfo_t requestData = { 0 };
529 requestData.token = token;
530 requestData.tokenLength = tokenLength;
531 requestData.payload = (CAPayload_t) "TempJsonPayload";
532 requestData.payloadSize = strlen((const char *) requestData.payload);
533 requestData.type = CA_MSG_NONCONFIRM;
535 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
536 LOGI("resourceUri - %s", strUri);
537 requestData.resourceUri = (CAURI_t)strUri;
539 uint8_t optionNum = 2;
540 CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
541 sizeof(CAHeaderOption_t) * optionNum);
542 if (NULL == headerOpt)
544 LOGE("Memory allocation failed");
545 // destroy remote endpoint
546 CADestroyEndpoint(endpoint);
550 char* FirstOptionData = "Hello";
551 headerOpt[0].optionID = 3000;
552 memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
553 headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
555 char* SecondOptionData2 = "World";
556 headerOpt[1].optionID = 3001;
557 memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
558 headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
560 requestData.numOptions = optionNum;
561 requestData.options = headerOpt;
563 CARequestInfo_t requestInfo = { 0 };
564 requestInfo.method = CA_GET;
565 requestInfo.isMulticast = true;
566 requestInfo.info = requestData;
568 // send request to all
569 res = CASendRequest(endpoint, &requestInfo);
570 if (CA_STATUS_OK != res)
572 LOGE("Could not send request to all");
574 CADestroyToken(token);
578 CADestroyToken(g_lastRequestToken);
579 g_lastRequestToken = token;
580 g_lastRequestTokenLength = tokenLength;
583 //ReleaseStringUTFChars for strUri
584 (*env)->ReleaseStringUTFChars(env, uri, strUri);
588 // destroy remote endpoint
589 CADestroyEndpoint(endpoint);
592 JNIEXPORT void JNICALL
593 Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
594 jint selectedNetwork,
595 jint isSecured, jint msgType,
598 LOGI("RMSendResponse");
601 LOGI("Invalid input parameter");
605 LOGI("selectedNetwork - %d", selectedNetwork);
607 CAResult_t res = get_network_type(selectedNetwork);
608 if (CA_STATUS_OK != res)
610 LOGE("Not supported network type");
614 if (NULL == g_clientEndpoint)
616 LOGE("No Request received");
620 CAMessageType_t messageType = msgType;
622 CAInfo_t responseData = { 0 };
623 responseData.type = messageType;
624 responseData.messageId = g_clientMsgId;
625 responseData.resourceUri = (CAURI_t)g_resourceUri;
627 CAResponseInfo_t responseInfo = { 0 };
629 if (msgType != CA_MSG_RESET)
631 responseData.token = g_clientToken;
632 responseData.tokenLength = g_clientTokenLength;
633 responseInfo.result = responseValue;
637 uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
638 responseData.payload = (CAPayload_t) malloc(length);
639 sprintf((char *) responseData.payload, SECURE_INFO_DATA, g_resourceUri,
641 responseData.payloadSize = length;
645 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
646 responseData.payload = (CAPayload_t) malloc(length);
647 sprintf((char *) responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
648 responseData.payloadSize = length;
654 responseInfo.result = CA_EMPTY;
657 responseInfo.info = responseData;
660 res = CASendResponse(g_clientEndpoint, &responseInfo);
661 if (CA_STATUS_OK != res)
663 LOGE("Could not send response");
667 CADestroyToken(g_clientToken);
668 g_clientToken = NULL;
669 g_clientTokenLength = 0;
671 // destroy remote endpoint
672 CADestroyEndpoint(g_clientEndpoint);
673 g_clientEndpoint = NULL;
676 JNIEXPORT void JNICALL
677 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
678 jstring payload, jint selectedNetwork,
679 jint isSecured, jint msgType,
682 LOGI("selectedNetwork - %d", selectedNetwork);
685 LOGI("Invalid input parameter");
691 LOGE("payload is NULL");
696 LOGE("Invalid input parameter : uri");
700 CAResult_t res = get_network_type(selectedNetwork);
701 if (CA_STATUS_OK != res)
703 LOGE("Not supported network type");
707 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
708 LOGI("RMSendNotification - %s", strUri);
710 CATransportFlags_t flags;
711 addressSet_t address = {{0}, 0};
712 parsing_coap_uri(strUri, &address, &flags);
714 //create remote endpoint
715 CAEndpoint_t* endpoint = NULL;
716 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
717 (const char*)address.ipAddress,
718 address.port, &endpoint))
720 //ReleaseStringUTFChars for strUri
721 (*env)->ReleaseStringUTFChars(env, uri, strUri);
722 LOGE("Could not create remote end point");
726 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
727 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
729 //ReleaseStringUTFChars for strUri
730 (*env)->ReleaseStringUTFChars(env, uri, strUri);
732 CAMessageType_t messageType = msgType;
735 CAToken_t token = NULL;
736 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
738 res = CAGenerateToken(&token, tokenLength);
739 if ((CA_STATUS_OK != res) || (!token))
741 LOGE("token generate error!");
742 CADestroyEndpoint(endpoint);
746 CAInfo_t responseData = { 0 };
747 responseData.token = token;
748 responseData.tokenLength = tokenLength;
749 responseData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
750 if (NULL == responseData.resourceUri)
752 LOGE("Memory allocation failed!");
754 CADestroyToken(token);
755 // destroy remote endpoint
756 CADestroyEndpoint(endpoint);
759 memcpy(responseData.resourceUri, resourceURI, sizeof(resourceURI));
763 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
764 responseData.payload = (CAPayload_t) malloc(length);
765 if (NULL == responseData.payload)
767 LOGE("Memory allocation failed!");
769 CADestroyToken(token);
770 // destroy remote endpoint
771 CADestroyEndpoint(endpoint);
773 free(responseData.resourceUri);
776 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
777 responseData.payloadSize = length;
781 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
782 responseData.payload = (CAPayload_t) malloc(length);
783 if (NULL == responseData.payload)
785 LOGE("Memory allocation failed!");
787 CADestroyToken(token);
788 // destroy remote endpoint
789 CADestroyEndpoint(endpoint);
791 free(responseData.resourceUri);
794 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
795 responseData.payloadSize = length;
798 responseData.type = messageType;
800 CAResponseInfo_t responseInfo = { 0 };
801 responseInfo.result = responseValue;
802 responseInfo.info = responseData;
805 if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
807 LOGE("Could not send notification");
810 LOGI("Send Notification");
813 CADestroyToken(token);
815 // destroy remote endpoint
816 CADestroyEndpoint(endpoint);
818 free(responseData.payload);
819 free(responseData.resourceUri);
822 JNIEXPORT void JNICALL
823 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
826 LOGI("RMSelectNetwork Type : %d", networkType);
829 LOGI("Invalid input parameter");
833 if (CA_STATUS_OK != CASelectNetwork(networkType))
835 LOGE("Could not select network");
839 JNIEXPORT void JNICALL
840 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
843 LOGI("RMUnSelectNetwork Type : %d", networkType);
846 LOGI("Invalid input parameter");
850 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
852 LOGE("Could not unselect network");
856 JNIEXPORT void JNICALL
857 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
859 LOGI("RMGetNetworkInfomation");
862 LOGI("Invalid input parameter");
866 CAEndpoint_t *tempInfo = NULL;
867 uint32_t tempSize = 0;
869 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
870 if (CA_STATUS_OK != res)
872 LOGE("Could not start get network information");
877 LOGI("################## Network Information #######################");
878 callback("######## Network Information", "#######");
879 LOGI("Network info total size is %d", tempSize);
882 for (index = 0; index < tempSize; index++)
884 res = get_remote_address(tempInfo[index].addr);
885 if (CA_STATUS_OK != res)
890 if (NULL != g_responseListenerObject)
892 char networkInfo[NETWORK_INFO_LENGTH];
893 LOGI("Type: %d", tempInfo[index].adapter);
894 sprintf(networkInfo, "%d",tempInfo[index].adapter);
895 callback("Type :", networkInfo);
896 if (CA_ADAPTER_IP == tempInfo[index].adapter)
898 LOGI("Port: %d", tempInfo[index].port);
899 sprintf(networkInfo, "%d",tempInfo[index].port);
900 callback("Port: ", networkInfo);
902 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
903 LOGI("Address: %s", g_remoteAddress);
904 callback("Address: ", g_remoteAddress);
905 free(g_remoteAddress);
907 if (tempInfo[index].flags & CA_SECURE)
909 g_localSecurePort = tempInfo[index].port;
916 LOGI("##############################################################");
919 JNIEXPORT void JNICALL
920 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
922 LOGI("RMHandleRequestResponse");
925 LOGI("Invalid input parameter");
929 if (CA_STATUS_OK != CAHandleRequestResponse())
931 LOGE("Could not handle request and response");
935 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
940 LOGE("Remote endpoint is NULL!");
946 LOGE("Request info is NULL!");
950 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
951 (strncmp(g_lastRequestToken, requestInfo->info.token,
952 requestInfo->info.tokenLength) == 0))
954 LOGI("token is same. received request of it's own. skip.. ");
958 CAResult_t res = get_remote_address(object->addr);
959 if (CA_STATUS_OK != res)
964 LOGI("##########received request from remote device #############");
965 LOGI("Remote Address: %s", g_remoteAddress);
966 LOGI("Remote Port: %d", object->port);
967 LOGI("Uri: %s", requestInfo->info.resourceUri);
968 LOGI("Data: %s", requestInfo->info.payload);
969 LOGI("Token: %s", requestInfo->info.token);
970 LOGI("Code: %d", requestInfo->method);
971 LOGI("MessageType: %d", requestInfo->info.type);
973 if (NULL != g_responseListenerObject)
975 char *cloneUri = NULL;
978 if (NULL != requestInfo->info.resourceUri)
980 len = strlen(requestInfo->info.resourceUri);
981 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
983 if (NULL == cloneUri)
985 LOGE("cloneUri Out of memory");
986 free(g_remoteAddress);
990 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
991 callback("Uri: ", cloneUri);
994 len = strlen(g_remoteAddress);
995 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
997 if (NULL == cloneRemoteAddress)
999 LOGE("cloneRemoteAddress Out of memory");
1000 free(g_remoteAddress);
1005 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1007 callback("Remote Address: ", cloneRemoteAddress);
1008 free(cloneRemoteAddress);
1009 free(g_remoteAddress);
1011 char portInfo[PORT_LENGTH] = { 0, };
1012 sprintf(portInfo, "%d", object->port);
1013 callback("Remote Port: ", portInfo);
1015 //clone g_clientEndpoint
1016 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
1017 if (NULL == g_clientEndpoint)
1019 LOGE("g_clientEndpoint Out of memory");
1023 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
1025 if (NULL != cloneUri)
1027 len = strlen(cloneUri);
1028 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
1029 if (NULL == g_resourceUri)
1031 LOGE("g_clientEndpoint->resourceUri Out of memory");
1032 free(g_clientEndpoint);
1036 memcpy(g_resourceUri, cloneUri, len + 1);
1039 //clone g_clientToken
1040 len = requestInfo->info.tokenLength;
1042 g_clientToken = (char *) malloc(sizeof(char) * len);
1043 if (NULL == g_clientToken)
1045 LOGE("g_clientToken Out of memory");
1046 free(g_clientEndpoint);
1050 if (NULL != requestInfo->info.token)
1052 memcpy(g_clientToken, requestInfo->info.token, len);
1053 g_clientTokenLength = len;
1057 //clone g_clientMsgId
1058 g_clientMsgId = requestInfo->info.messageId;
1060 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1062 len = requestInfo->info.payloadSize;
1063 char *clonePayload = (char *) malloc(len + 1);
1064 if (NULL == clonePayload)
1066 LOGE("clonePayload Out of memory");
1067 free(g_clientEndpoint);
1071 memcpy(clonePayload, requestInfo->info.payload, len);
1072 clonePayload[len] = '\0';
1074 if (len > BIG_PAYLOAD_LENGTH)
1076 saveFile(clonePayload, len);
1080 callback("Data: ", clonePayload);
1086 if (requestInfo->info.options)
1088 uint32_t len = requestInfo->info.numOptions;
1091 LOGI("Option count: %d", requestInfo->info.numOptions);
1093 for (i = 0; i < len; i++)
1095 LOGI("Option %d", i + 1);
1096 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1097 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1098 requestInfo->info.options[i].optionData);
1100 if (NULL != g_responseListenerObject)
1102 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1103 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1104 requestInfo->info.options[i].optionID,
1105 requestInfo->info.options[i].optionLength);
1107 callback("Option info: ", optionInfo);
1109 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1110 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1111 if (NULL == cloneOptionData)
1113 LOGE("cloneOptionData Out of memory");
1114 free(g_clientEndpoint);
1118 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1121 callback("Option Data: ", cloneOptionData);
1122 free(cloneOptionData);
1126 LOGI("############################################################");
1128 //Check if this has secure communication information
1129 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1131 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1132 if (0 < securePort) //Set the remote endpoint secure details and send response
1134 LOGI("This is secure resource...");
1136 CAEndpoint_t *endpoint = NULL;
1137 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1138 object->adapter, object->addr, securePort, &endpoint))
1140 LOGE("Failed to create duplicate of remote endpoint!");
1148 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1150 if (!object || !responseInfo)
1152 LOGE("Invalid input parameter");
1156 CAResult_t res = get_remote_address(object->addr);
1157 if (CA_STATUS_OK != res)
1162 LOGI("##########Received response from remote device #############");
1163 LOGI("Uri: %s", responseInfo->info.resourceUri);
1164 LOGI("Remote Address: %s", g_remoteAddress);
1165 LOGI("Remote Port: %d", object->port);
1166 LOGI("response result: %d", responseInfo->result);
1167 LOGI("Data: %s", responseInfo->info.payload);
1168 LOGI("Token: %s", responseInfo->info.token);
1169 LOGI("MessageType: %d", responseInfo->info.type);
1171 if (NULL != g_responseListenerObject)
1175 if (NULL != responseInfo->info.resourceUri)
1177 len = strlen(responseInfo->info.resourceUri);
1178 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1180 if (NULL == cloneUri)
1182 LOGE("cloneUri Out of memory");
1183 free(g_remoteAddress);
1187 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1189 callback("Uri: ", cloneUri);
1193 len = strlen(g_remoteAddress);
1194 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1196 if (NULL == cloneRemoteAddress)
1198 LOGE("cloneRemoteAddress Out of memory");
1199 free(g_remoteAddress);
1203 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1205 callback("Remote Address: ", cloneRemoteAddress);
1206 free(cloneRemoteAddress);
1207 free(g_remoteAddress);
1209 char portInfo[PORT_LENGTH] = { 0, };
1210 sprintf(portInfo, "%d", object->port);
1211 callback("Remote Port: ", portInfo);
1213 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1215 len = responseInfo->info.payloadSize;
1216 char *clonePayload = (char *) malloc(len + 1);
1217 if (NULL == clonePayload)
1219 LOGE("clonePayload Out of memory");
1223 memcpy(clonePayload, responseInfo->info.payload, len);
1224 clonePayload[len] = '\0';
1226 if (len > BIG_PAYLOAD_LENGTH)
1228 saveFile(clonePayload, len);
1232 callback("Data: ", clonePayload);
1238 if (responseInfo->info.options)
1240 uint32_t len = responseInfo->info.numOptions;
1242 for (i = 0; i < len; i++)
1244 LOGI("Option %d", i + 1);
1245 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1246 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1247 responseInfo->info.options[i].optionData);
1249 if (NULL != g_responseListenerObject)
1251 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1252 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1253 responseInfo->info.options[i].optionID,
1254 responseInfo->info.options[i].optionLength);
1256 callback("Option info: ", optionInfo);
1258 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1259 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1260 if (NULL == cloneOptionData)
1262 LOGE("cloneOptionData Out of memory");
1265 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1267 callback("Option Data: ", cloneOptionData);
1268 free(cloneOptionData);
1272 LOGI("############################################################");
1274 //Check if this has secure communication information
1275 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1277 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1278 if (0 < securePort) //Set the remote endpoint secure details and send response
1280 LOGI("This is secure resource...");
1285 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1287 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1291 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1292 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1297 const CAInfo_t *info = &errorInfo->info;
1298 LOGI("Error Handler, ErrorInfo :");
1299 LOGI("Error Handler result : %d", errorInfo->result);
1300 LOGI("Error Handler token : %s", info->token);
1301 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1302 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1303 LOGI("Error Handler type : %d", info->type);
1304 LOGI("Error Handler payload : %s", info->payload);
1306 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1308 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1310 else if(CA_SEND_FAILED == errorInfo->result)
1312 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1314 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1316 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1318 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1320 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1322 else if(CA_STATUS_FAILED == errorInfo->result)
1324 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1327 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1332 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1334 const char *startPos = URI;
1335 const char *temp = strstr(URI, "://");
1338 startPos = strchr(temp + 3, '/');
1341 LOGE("Resource URI is missing");
1346 const char *endPos = strchr(startPos, '?');
1349 endPos = URI + strlen(URI);
1353 if (endPos - startPos <= length)
1355 memcpy(resourceURI, startPos + 1, endPos - startPos);
1358 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1361 uint32_t get_secure_information(CAPayload_t payLoad)
1363 LOGI("entering get_secure_information");
1367 LOGE("Payload is NULL");
1371 const char *subString = NULL;
1372 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1374 LOGE("This is not secure resource");
1378 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1380 LOGE("This secure resource does not have port information");
1384 const char *startPos = strstr(subString, ":");
1387 LOGE("Parsing failed !");
1391 const char *endPos = strstr(startPos, "}");
1394 LOGE("Parsing failed !");
1398 char portStr[6] = { 0 };
1399 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1401 LOGI("secured port is: %s", portStr);
1402 return atoi(portStr);
1405 CAResult_t get_network_type(uint32_t selectedNetwork)
1408 uint32_t number = selectedNetwork;
1410 if (!(number & 0xf))
1412 return CA_NOT_SUPPORTED;
1414 if (number & CA_ADAPTER_IP)
1416 g_selectedNwType = CA_ADAPTER_IP;
1417 return CA_STATUS_OK;
1419 if (number & CA_ADAPTER_RFCOMM_BTEDR)
1421 g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1422 return CA_STATUS_OK;
1424 if (number & CA_ADAPTER_GATT_BTLE)
1426 g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1427 return CA_STATUS_OK;
1430 return CA_NOT_SUPPORTED;
1433 void callback(char *subject, char *receivedData)
1435 bool isAttached = false;
1438 if (!g_responseListenerObject)
1440 LOGE("g_responseListenerObject is NULL, cannot have callback");
1444 jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1447 LOGI("Could not get JNIEnv pointer");
1448 res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1452 LOGE("AttachCurrentThread has failed");
1458 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1461 LOGE("could not get class");
1465 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1466 "(Ljava/lang/String;Ljava/lang/String;)V");
1469 LOGE("could not get Method ID");
1473 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1476 LOGE("NewStringUTF failed");
1480 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1483 LOGE("NewStringUTF failed");
1487 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1492 (*g_jvm)->DetachCurrentThread(g_jvm);
1493 LOGI("DetachCurrentThread");
1497 CAResult_t get_remote_address(const char *address)
1499 uint32_t len = strlen(address);
1501 g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1502 if (NULL == g_remoteAddress)
1504 LOGE("g_remoteAddress Out of memory");
1505 return CA_MEMORY_ALLOC_FAILED;
1508 memcpy(g_remoteAddress, address, len + 1);
1510 return CA_STATUS_OK;
1514 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1516 if (NULL == uri || NULL == address)
1518 LOGE("parameter is null");
1524 uint8_t startIndex = 0;
1525 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1527 LOGI("uri has '%s' prefix", COAPS_PREFIX);
1528 startIndex = COAPS_PREFIX_LEN;
1531 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1533 LOGI("uri has '%s' prefix", COAP_PREFIX);
1534 startIndex = COAP_PREFIX_LEN;
1538 // #2. copy uri for parse
1539 size_t len = strlen(uri) - startIndex;
1543 LOGE("uri length is 0!");
1547 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1548 if (NULL == cloneUri)
1550 LOGE("Out of memory");
1554 OICStrcpy(cloneUri, len+1, &uri[startIndex]);
1557 //filter out the resource uri
1558 char *pUrl = strtok_r(cloneUri, "/", &pstr);
1562 LOGI("pAddress : %s", pUrl);
1563 int res = get_address_set(pUrl, address);
1566 LOGE("address parse error");
1573 LOGE("strtok_r error, could not get the address");
1579 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1581 if (NULL == pAddress || NULL == outAddress)
1583 LOGE("parameter is null");
1587 size_t len = strlen(pAddress);
1591 for (size_t i = 0; i < len; i++)
1593 if (pAddress[i] == '.')
1598 // found port number start index
1599 if (isIp && pAddress[i] == ':')
1608 if(ipLen && (ipLen < sizeof(outAddress->ipAddress)))
1610 strncpy(outAddress->ipAddress, pAddress, ipLen);
1611 outAddress->ipAddress[ipLen] = '\0';
1613 else if (!ipLen && (len < sizeof(outAddress->ipAddress)))
1615 strncpy(outAddress->ipAddress, pAddress, len);
1616 outAddress->ipAddress[len] = '\0';
1620 LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1626 outAddress->port = atoi(pAddress + ipLen + 1);
1631 strncpy(outAddress->ipAddress, pAddress, len);
1632 outAddress->ipAddress[len] = '\0';
1638 void delete_global_references(JNIEnv *env, jobject obj)
1640 LOGI("delete_global_references");
1643 LOGI("Invalid input parameter");
1647 (*env)->DeleteGlobalRef(env, g_responseListenerObject);
1651 bool read_file(const char* name, char** bytes, size_t* length)
1655 LOGE("parameter is null");
1664 file = fopen(name, "rt");
1667 fprintf(stderr, "Unable to open file %s", name);
1672 fseek(file, 0, SEEK_END);
1673 fileLen = ftell(file);
1674 fseek(file, 0, SEEK_SET);
1676 LOGI("file size: %d", fileLen);
1679 buffer = calloc(1, sizeof(char) * fileLen + 1);
1682 fprintf(stderr, "Memory error!");
1687 // Read file contents into buffer
1688 size_t ret = fread(buffer, fileLen, 1, file);
1691 printf("Failed to read data from file, %s\n", name);
1699 LOGI("file bytes: %s", buffer);
1707 void saveFile(const char *payload, size_t payloadSize)
1710 uint32_t day = gettodaydate();
1713 time_t current_time;
1714 struct tm * time_info;
1715 char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
1717 time(¤t_time);
1718 time_info = localtime(¤t_time);
1720 strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
1722 uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
1723 char* path = calloc(1, sizeof(char) * path_length);
1726 sprintf(path, RECEIVED_FILE_PATH, day, timeString);
1727 LOGI("received file path: %s", path);
1729 FILE *fp = fopen(path, "wt");
1730 fwrite(payload, 1, payloadSize, fp);
1733 callback("File Path: ", path);
1737 LOGE("path Out of memory");
1741 uint32_t gettodaydate()
1748 date = localtime(&clock);
1749 ldate = date->tm_year * 100000;
1750 ldate += (date->tm_mon + 1) * 1000;
1751 ldate += date->tm_mday * 10;
1752 ldate += date->tm_wday;