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);
395 (*env)->ReleaseStringUTFChars(env, payload, path);
397 requestData.payload = (CAPayload_t) malloc(payloadLength);
398 if (NULL == requestData.payload)
400 LOGE("Memory allocation failed!");
402 CADestroyToken(token);
403 // destroy remote endpoint
404 CADestroyEndpoint(endpoint);
407 memcpy(requestData.payload, bigData, payloadLength);
408 requestData.payloadSize = payloadLength;
416 payloadLength = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
417 requestData.payload = (CAPayload_t) malloc(payloadLength);
418 if (NULL == requestData.payload)
420 LOGE("Memory allocation failed!");
422 CADestroyToken(token);
423 // destroy remote endpoint
424 CADestroyEndpoint(endpoint);
427 snprintf((char *) requestData.payload, payloadLength, SECURE_INFO_DATA,
428 resourceURI, g_localSecurePort);
429 requestData.payloadSize = payloadLength;
433 payloadLength = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
434 requestData.payload = (CAPayload_t) malloc(payloadLength);
435 if (NULL == requestData.payload)
437 LOGE("Memory allocation failed!");
439 CADestroyToken(token);
440 // destroy remote endpoint
441 CADestroyEndpoint(endpoint);
444 snprintf((char *) requestData.payload, payloadLength, NORMAL_INFO_DATA, resourceURI);
445 requestData.payloadSize = payloadLength;
449 requestData.type = messageType;
450 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
451 if (NULL == requestData.resourceUri)
453 LOGE("Memory allocation failed!");
455 CADestroyToken(token);
456 // destroy remote endpoint
457 CADestroyEndpoint(endpoint);
458 free(requestData.payload);
461 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
463 CARequestInfo_t requestInfo = { 0 };
464 requestInfo.method = CA_GET;
465 requestInfo.isMulticast = false;
466 requestInfo.info = requestData;
469 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
471 LOGE("Could not send request");
475 CADestroyToken(token);
477 // destroy remote endpoint
478 CADestroyEndpoint(endpoint);
480 free(requestData.payload);
481 free(requestData.resourceUri);
484 JNIEXPORT void JNICALL
485 Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
486 jint selectedNetwork)
488 LOGI("selectedNetwork - %d", selectedNetwork);
491 LOGI("Invalid input parameter");
495 CAResult_t res = get_network_type(selectedNetwork);
496 if (CA_STATUS_OK != res)
501 // create remote endpoint
502 CAEndpoint_t *endpoint = NULL;
503 res = CACreateEndpoint(CA_IPV4, g_selectedNwType, NULL, 0, &endpoint);
505 if (CA_STATUS_OK != res)
507 LOGE("create remote endpoint error, error code: %d", res);
512 CAToken_t token = NULL;
513 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
515 res = CAGenerateToken(&token, tokenLength);
516 if ((CA_STATUS_OK != res) || (!token))
518 LOGE("token generate error!!");
519 // destroy remote endpoint
520 CADestroyEndpoint(endpoint);
524 LOGI("generated token %s", token);
526 CAInfo_t requestData = { 0 };
527 requestData.token = token;
528 requestData.tokenLength = tokenLength;
529 requestData.payload = (CAPayload_t) "TempJsonPayload";
530 requestData.payloadSize = strlen((const char *) requestData.payload);
531 requestData.type = CA_MSG_NONCONFIRM;
533 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
534 LOGI("resourceUri - %s", strUri);
535 requestData.resourceUri = (CAURI_t)strUri;
537 uint8_t optionNum = 2;
538 CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
539 sizeof(CAHeaderOption_t) * optionNum);
540 if (NULL == headerOpt)
542 LOGE("Memory allocation failed");
543 // destroy remote endpoint
544 CADestroyEndpoint(endpoint);
548 char* FirstOptionData = "Hello";
549 headerOpt[0].optionID = 3000;
550 memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
551 headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
553 char* SecondOptionData2 = "World";
554 headerOpt[1].optionID = 3001;
555 memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
556 headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
558 requestData.numOptions = optionNum;
559 requestData.options = headerOpt;
561 CARequestInfo_t requestInfo = { 0 };
562 requestInfo.method = CA_GET;
563 requestInfo.isMulticast = true;
564 requestInfo.info = requestData;
566 // send request to all
567 res = CASendRequest(endpoint, &requestInfo);
568 if (CA_STATUS_OK != res)
570 LOGE("Could not send request to all");
572 CADestroyToken(token);
576 CADestroyToken(g_lastRequestToken);
577 g_lastRequestToken = token;
578 g_lastRequestTokenLength = tokenLength;
581 //ReleaseStringUTFChars for strUri
582 (*env)->ReleaseStringUTFChars(env, uri, strUri);
586 // destroy remote endpoint
587 CADestroyEndpoint(endpoint);
590 JNIEXPORT void JNICALL
591 Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
592 jint selectedNetwork,
593 jint isSecured, jint msgType,
596 LOGI("RMSendResponse");
599 LOGI("Invalid input parameter");
603 LOGI("selectedNetwork - %d", selectedNetwork);
605 CAResult_t res = get_network_type(selectedNetwork);
606 if (CA_STATUS_OK != res)
608 LOGE("Not supported network type");
612 if (NULL == g_clientEndpoint)
614 LOGE("No Request received");
618 CAMessageType_t messageType = msgType;
620 CAInfo_t responseData = { 0 };
621 responseData.type = messageType;
622 responseData.messageId = g_clientMsgId;
623 responseData.resourceUri = (CAURI_t)g_resourceUri;
625 CAResponseInfo_t responseInfo = { 0 };
627 if (msgType != CA_MSG_RESET)
629 responseData.token = g_clientToken;
630 responseData.tokenLength = g_clientTokenLength;
631 responseInfo.result = responseValue;
635 uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
636 responseData.payload = (CAPayload_t) malloc(length);
637 sprintf((char *) responseData.payload, SECURE_INFO_DATA, g_resourceUri,
639 responseData.payloadSize = length;
643 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
644 responseData.payload = (CAPayload_t) malloc(length);
645 sprintf((char *) responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
646 responseData.payloadSize = length;
652 responseInfo.result = CA_EMPTY;
655 responseInfo.info = responseData;
658 res = CASendResponse(g_clientEndpoint, &responseInfo);
659 if (CA_STATUS_OK != res)
661 LOGE("Could not send response");
665 CADestroyToken(g_clientToken);
666 g_clientToken = NULL;
667 g_clientTokenLength = 0;
669 // destroy remote endpoint
670 CADestroyEndpoint(g_clientEndpoint);
671 g_clientEndpoint = NULL;
674 JNIEXPORT void JNICALL
675 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
676 jstring payload, jint selectedNetwork,
677 jint isSecured, jint msgType,
680 LOGI("selectedNetwork - %d", selectedNetwork);
683 LOGI("Invalid input parameter");
689 LOGE("payload is NULL");
694 LOGE("Invalid input parameter : uri");
698 CAResult_t res = get_network_type(selectedNetwork);
699 if (CA_STATUS_OK != res)
701 LOGE("Not supported network type");
705 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
706 LOGI("RMSendNotification - %s", strUri);
708 CATransportFlags_t flags;
709 addressSet_t address = {{0}, 0};
710 parsing_coap_uri(strUri, &address, &flags);
712 //create remote endpoint
713 CAEndpoint_t* endpoint = NULL;
714 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
715 (const char*)address.ipAddress,
716 address.port, &endpoint))
718 //ReleaseStringUTFChars for strUri
719 (*env)->ReleaseStringUTFChars(env, uri, strUri);
720 LOGE("Could not create remote end point");
724 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
725 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
727 //ReleaseStringUTFChars for strUri
728 (*env)->ReleaseStringUTFChars(env, uri, strUri);
730 CAMessageType_t messageType = msgType;
733 CAToken_t token = NULL;
734 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
736 res = CAGenerateToken(&token, tokenLength);
737 if ((CA_STATUS_OK != res) || (!token))
739 LOGE("token generate error!");
740 CADestroyEndpoint(endpoint);
744 CAInfo_t responseData = { 0 };
745 responseData.token = token;
746 responseData.tokenLength = tokenLength;
747 responseData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
748 if (NULL == responseData.resourceUri)
750 LOGE("Memory allocation failed!");
752 CADestroyToken(token);
753 // destroy remote endpoint
754 CADestroyEndpoint(endpoint);
757 memcpy(responseData.resourceUri, resourceURI, sizeof(resourceURI));
761 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
762 responseData.payload = (CAPayload_t) malloc(length);
763 if (NULL == responseData.payload)
765 LOGE("Memory allocation failed!");
767 CADestroyToken(token);
768 // destroy remote endpoint
769 CADestroyEndpoint(endpoint);
771 free(responseData.resourceUri);
774 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
775 responseData.payloadSize = length;
779 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
780 responseData.payload = (CAPayload_t) malloc(length);
781 if (NULL == responseData.payload)
783 LOGE("Memory allocation failed!");
785 CADestroyToken(token);
786 // destroy remote endpoint
787 CADestroyEndpoint(endpoint);
789 free(responseData.resourceUri);
792 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
793 responseData.payloadSize = length;
796 responseData.type = messageType;
798 CAResponseInfo_t responseInfo = { 0 };
799 responseInfo.result = responseValue;
800 responseInfo.info = responseData;
803 if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
805 LOGE("Could not send notification");
808 LOGI("Send Notification");
811 CADestroyToken(token);
813 // destroy remote endpoint
814 CADestroyEndpoint(endpoint);
816 free(responseData.payload);
817 free(responseData.resourceUri);
820 JNIEXPORT void JNICALL
821 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
824 LOGI("RMSelectNetwork Type : %d", networkType);
827 LOGI("Invalid input parameter");
831 if (CA_STATUS_OK != CASelectNetwork(networkType))
833 LOGE("Could not select network");
837 JNIEXPORT void JNICALL
838 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
841 LOGI("RMUnSelectNetwork Type : %d", networkType);
844 LOGI("Invalid input parameter");
848 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
850 LOGE("Could not unselect network");
854 JNIEXPORT void JNICALL
855 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
857 LOGI("RMGetNetworkInfomation");
860 LOGI("Invalid input parameter");
864 CAEndpoint_t *tempInfo = NULL;
865 uint32_t tempSize = 0;
867 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
868 if (CA_STATUS_OK != res)
870 LOGE("Could not start get network information");
875 LOGI("################## Network Information #######################");
876 callback("######## Network Information", "#######");
877 LOGI("Network info total size is %d", tempSize);
880 for (index = 0; index < tempSize; index++)
882 res = get_remote_address(tempInfo[index].addr);
883 if (CA_STATUS_OK != res)
888 if (NULL != g_responseListenerObject)
890 char networkInfo[NETWORK_INFO_LENGTH];
891 LOGI("Type: %d", tempInfo[index].adapter);
892 sprintf(networkInfo, "%d",tempInfo[index].adapter);
893 callback("Type :", networkInfo);
894 if (CA_ADAPTER_IP == tempInfo[index].adapter)
896 LOGI("Port: %d", tempInfo[index].port);
897 sprintf(networkInfo, "%d",tempInfo[index].port);
898 callback("Port: ", networkInfo);
900 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
901 LOGI("Address: %s", g_remoteAddress);
902 callback("Address: ", g_remoteAddress);
903 free(g_remoteAddress);
905 if (tempInfo[index].flags & CA_SECURE)
907 g_localSecurePort = tempInfo[index].port;
914 LOGI("##############################################################");
917 JNIEXPORT void JNICALL
918 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
920 LOGI("RMHandleRequestResponse");
923 LOGI("Invalid input parameter");
927 if (CA_STATUS_OK != CAHandleRequestResponse())
929 LOGE("Could not handle request and response");
933 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
938 LOGE("Remote endpoint is NULL!");
944 LOGE("Request info is NULL!");
948 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
949 (strncmp(g_lastRequestToken, requestInfo->info.token,
950 requestInfo->info.tokenLength) == 0))
952 LOGI("token is same. received request of it's own. skip.. ");
956 CAResult_t res = get_remote_address(object->addr);
957 if (CA_STATUS_OK != res)
962 LOGI("##########received request from remote device #############");
963 LOGI("Remote Address: %s", g_remoteAddress);
964 LOGI("Remote Port: %d", object->port);
965 LOGI("Uri: %s", requestInfo->info.resourceUri);
966 LOGI("Data: %s", requestInfo->info.payload);
967 LOGI("Token: %s", requestInfo->info.token);
968 LOGI("Code: %d", requestInfo->method);
969 LOGI("MessageType: %d", requestInfo->info.type);
971 if (NULL != g_responseListenerObject)
973 char *cloneUri = NULL;
976 if (NULL != requestInfo->info.resourceUri)
978 len = strlen(requestInfo->info.resourceUri);
979 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
981 if (NULL == cloneUri)
983 LOGE("cloneUri Out of memory");
984 free(g_remoteAddress);
988 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
989 callback("Uri: ", cloneUri);
992 len = strlen(g_remoteAddress);
993 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
995 if (NULL == cloneRemoteAddress)
997 LOGE("cloneRemoteAddress Out of memory");
998 free(g_remoteAddress);
1003 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1005 callback("Remote Address: ", cloneRemoteAddress);
1006 free(cloneRemoteAddress);
1007 free(g_remoteAddress);
1009 char portInfo[PORT_LENGTH] = { 0, };
1010 sprintf(portInfo, "%d", object->port);
1011 callback("Remote Port: ", portInfo);
1013 //clone g_clientEndpoint
1014 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
1015 if (NULL == g_clientEndpoint)
1017 LOGE("g_clientEndpoint Out of memory");
1021 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
1023 if (NULL != cloneUri)
1025 len = strlen(cloneUri);
1026 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
1027 if (NULL == g_resourceUri)
1029 LOGE("g_clientEndpoint->resourceUri Out of memory");
1030 free(g_clientEndpoint);
1034 memcpy(g_resourceUri, cloneUri, len + 1);
1037 //clone g_clientToken
1038 len = requestInfo->info.tokenLength;
1040 g_clientToken = (char *) malloc(sizeof(char) * len);
1041 if (NULL == g_clientToken)
1043 LOGE("g_clientToken Out of memory");
1044 free(g_clientEndpoint);
1048 if (NULL != requestInfo->info.token)
1050 memcpy(g_clientToken, requestInfo->info.token, len);
1051 g_clientTokenLength = len;
1055 //clone g_clientMsgId
1056 g_clientMsgId = requestInfo->info.messageId;
1058 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1060 len = requestInfo->info.payloadSize;
1061 char *clonePayload = (char *) malloc(len + 1);
1062 if (NULL == clonePayload)
1064 LOGE("clonePayload Out of memory");
1065 free(g_clientEndpoint);
1069 memcpy(clonePayload, requestInfo->info.payload, len);
1070 clonePayload[len] = '\0';
1072 if (len > BIG_PAYLOAD_LENGTH)
1074 saveFile(clonePayload, len);
1078 callback("Data: ", clonePayload);
1084 if (requestInfo->info.options)
1086 uint32_t len = requestInfo->info.numOptions;
1089 LOGI("Option count: %d", requestInfo->info.numOptions);
1091 for (i = 0; i < len; i++)
1093 LOGI("Option %d", i + 1);
1094 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1095 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1096 requestInfo->info.options[i].optionData);
1098 if (NULL != g_responseListenerObject)
1100 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1101 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1102 requestInfo->info.options[i].optionID,
1103 requestInfo->info.options[i].optionLength);
1105 callback("Option info: ", optionInfo);
1107 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1108 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1109 if (NULL == cloneOptionData)
1111 LOGE("cloneOptionData Out of memory");
1112 free(g_clientEndpoint);
1116 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1119 callback("Option Data: ", cloneOptionData);
1120 free(cloneOptionData);
1124 LOGI("############################################################");
1126 //Check if this has secure communication information
1127 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1129 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1130 if (0 < securePort) //Set the remote endpoint secure details and send response
1132 LOGI("This is secure resource...");
1134 CAEndpoint_t *endpoint = NULL;
1135 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1136 object->adapter, object->addr, securePort, &endpoint))
1138 LOGE("Failed to create duplicate of remote endpoint!");
1146 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1148 if (!object || !responseInfo)
1150 LOGE("Invalid input parameter");
1154 CAResult_t res = get_remote_address(object->addr);
1155 if (CA_STATUS_OK != res)
1160 LOGI("##########Received response from remote device #############");
1161 LOGI("Uri: %s", responseInfo->info.resourceUri);
1162 LOGI("Remote Address: %s", g_remoteAddress);
1163 LOGI("Remote Port: %d", object->port);
1164 LOGI("response result: %d", responseInfo->result);
1165 LOGI("Data: %s", responseInfo->info.payload);
1166 LOGI("Token: %s", responseInfo->info.token);
1167 LOGI("MessageType: %d", responseInfo->info.type);
1169 if (NULL != g_responseListenerObject)
1173 if (NULL != responseInfo->info.resourceUri)
1175 len = strlen(responseInfo->info.resourceUri);
1176 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1178 if (NULL == cloneUri)
1180 LOGE("cloneUri Out of memory");
1181 free(g_remoteAddress);
1185 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1187 callback("Uri: ", cloneUri);
1191 len = strlen(g_remoteAddress);
1192 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1194 if (NULL == cloneRemoteAddress)
1196 LOGE("cloneRemoteAddress Out of memory");
1197 free(g_remoteAddress);
1201 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1203 callback("Remote Address: ", cloneRemoteAddress);
1204 free(cloneRemoteAddress);
1205 free(g_remoteAddress);
1207 char portInfo[PORT_LENGTH] = { 0, };
1208 sprintf(portInfo, "%d", object->port);
1209 callback("Remote Port: ", portInfo);
1211 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1213 len = responseInfo->info.payloadSize;
1214 char *clonePayload = (char *) malloc(len + 1);
1215 if (NULL == clonePayload)
1217 LOGE("clonePayload Out of memory");
1221 memcpy(clonePayload, responseInfo->info.payload, len);
1222 clonePayload[len] = '\0';
1224 if (len > BIG_PAYLOAD_LENGTH)
1226 saveFile(clonePayload, len);
1230 callback("Data: ", clonePayload);
1236 if (responseInfo->info.options)
1238 uint32_t len = responseInfo->info.numOptions;
1240 for (i = 0; i < len; i++)
1242 LOGI("Option %d", i + 1);
1243 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1244 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1245 responseInfo->info.options[i].optionData);
1247 if (NULL != g_responseListenerObject)
1249 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1250 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1251 responseInfo->info.options[i].optionID,
1252 responseInfo->info.options[i].optionLength);
1254 callback("Option info: ", optionInfo);
1256 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1257 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1258 if (NULL == cloneOptionData)
1260 LOGE("cloneOptionData Out of memory");
1263 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1265 callback("Option Data: ", cloneOptionData);
1266 free(cloneOptionData);
1270 LOGI("############################################################");
1272 //Check if this has secure communication information
1273 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1275 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1276 if (0 < securePort) //Set the remote endpoint secure details and send response
1278 LOGI("This is secure resource...");
1283 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1285 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1289 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1290 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1295 const CAInfo_t *info = &errorInfo->info;
1296 LOGI("Error Handler, ErrorInfo :");
1297 LOGI("Error Handler result : %d", errorInfo->result);
1298 LOGI("Error Handler token : %s", info->token);
1299 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1300 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1301 LOGI("Error Handler type : %d", info->type);
1302 LOGI("Error Handler payload : %s", info->payload);
1304 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1306 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1308 else if(CA_SEND_FAILED == errorInfo->result)
1310 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1312 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1314 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1316 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1318 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1320 else if(CA_STATUS_FAILED == errorInfo->result)
1322 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1325 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1330 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1332 const char *startPos = URI;
1333 const char *temp = strstr(URI, "://");
1336 startPos = strchr(temp + 3, '/');
1339 LOGE("Resource URI is missing");
1344 const char *endPos = strchr(startPos, '?');
1347 endPos = URI + strlen(URI);
1351 if (endPos - startPos <= length)
1353 memcpy(resourceURI, startPos + 1, endPos - startPos);
1356 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1359 uint32_t get_secure_information(CAPayload_t payLoad)
1361 LOGI("entering get_secure_information");
1365 LOGE("Payload is NULL");
1369 const char *subString = NULL;
1370 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1372 LOGE("This is not secure resource");
1376 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1378 LOGE("This secure resource does not have port information");
1382 const char *startPos = strstr(subString, ":");
1385 LOGE("Parsing failed !");
1389 const char *endPos = strstr(startPos, "}");
1392 LOGE("Parsing failed !");
1396 char portStr[6] = { 0 };
1397 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1399 LOGI("secured port is: %s", portStr);
1400 return atoi(portStr);
1403 CAResult_t get_network_type(uint32_t selectedNetwork)
1406 uint32_t number = selectedNetwork;
1408 if (!(number & 0xf))
1410 return CA_NOT_SUPPORTED;
1412 if (number & CA_ADAPTER_IP)
1414 g_selectedNwType = CA_ADAPTER_IP;
1415 return CA_STATUS_OK;
1417 if (number & CA_ADAPTER_RFCOMM_BTEDR)
1419 g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1420 return CA_STATUS_OK;
1422 if (number & CA_ADAPTER_GATT_BTLE)
1424 g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1425 return CA_STATUS_OK;
1428 return CA_NOT_SUPPORTED;
1431 void callback(char *subject, char *receivedData)
1433 bool isAttached = false;
1436 if (!g_responseListenerObject)
1438 LOGE("g_responseListenerObject is NULL, cannot have callback");
1442 jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1445 LOGI("Could not get JNIEnv pointer");
1446 res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1450 LOGE("AttachCurrentThread has failed");
1456 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1459 LOGE("could not get class");
1463 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1464 "(Ljava/lang/String;Ljava/lang/String;)V");
1467 LOGE("could not get Method ID");
1471 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1474 LOGE("NewStringUTF failed");
1478 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1481 LOGE("NewStringUTF failed");
1485 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1490 (*g_jvm)->DetachCurrentThread(g_jvm);
1491 LOGI("DetachCurrentThread");
1495 CAResult_t get_remote_address(const char *address)
1497 uint32_t len = strlen(address);
1499 g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1500 if (NULL == g_remoteAddress)
1502 LOGE("g_remoteAddress Out of memory");
1503 return CA_MEMORY_ALLOC_FAILED;
1506 memcpy(g_remoteAddress, address, len + 1);
1508 return CA_STATUS_OK;
1512 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1514 if (NULL == uri || NULL == address)
1516 LOGE("parameter is null");
1522 uint8_t startIndex = 0;
1523 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1525 LOGI("uri has '%s' prefix", COAPS_PREFIX);
1526 startIndex = COAPS_PREFIX_LEN;
1529 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1531 LOGI("uri has '%s' prefix", COAP_PREFIX);
1532 startIndex = COAP_PREFIX_LEN;
1536 // #2. copy uri for parse
1537 size_t len = strlen(uri) - startIndex;
1541 LOGE("uri length is 0!");
1545 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1546 if (NULL == cloneUri)
1548 LOGE("Out of memory");
1552 OICStrcpy(cloneUri, len+1, &uri[startIndex]);
1555 //filter out the resource uri
1556 char *pUrl = strtok_r(cloneUri, "/", &pstr);
1560 LOGI("pAddress : %s", pUrl);
1561 int res = get_address_set(pUrl, address);
1564 LOGE("address parse error");
1571 LOGE("strtok_r error, could not get the address");
1577 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1579 if (NULL == pAddress || NULL == outAddress)
1581 LOGE("parameter is null");
1585 size_t len = strlen(pAddress);
1589 for (size_t i = 0; i < len; i++)
1591 if (pAddress[i] == '.')
1596 // found port number start index
1597 if (isIp && pAddress[i] == ':')
1606 if(ipLen && (ipLen < sizeof(outAddress->ipAddress)))
1608 strncpy(outAddress->ipAddress, pAddress, ipLen);
1609 outAddress->ipAddress[ipLen] = '\0';
1611 else if (!ipLen && (len < sizeof(outAddress->ipAddress)))
1613 strncpy(outAddress->ipAddress, pAddress, len);
1614 outAddress->ipAddress[len] = '\0';
1618 LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1624 outAddress->port = atoi(pAddress + ipLen + 1);
1629 strncpy(outAddress->ipAddress, pAddress, len);
1630 outAddress->ipAddress[len] = '\0';
1636 void delete_global_references(JNIEnv *env, jobject obj)
1638 LOGI("delete_global_references");
1641 LOGI("Invalid input parameter");
1645 (*env)->DeleteGlobalRef(env, g_responseListenerObject);
1649 bool read_file(const char* name, char** bytes, size_t* length)
1653 LOGE("parameter is null");
1662 file = fopen(name, "rt");
1665 fprintf(stderr, "Unable to open file %s", name);
1670 fseek(file, 0, SEEK_END);
1671 fileLen = ftell(file);
1672 fseek(file, 0, SEEK_SET);
1674 LOGI("file size: %d", fileLen);
1677 buffer = calloc(1, sizeof(char) * fileLen + 1);
1680 fprintf(stderr, "Memory error!");
1685 // Read file contents into buffer
1686 fread(buffer, fileLen, 1, file);
1689 LOGI("file bytes: %s", buffer);
1697 void saveFile(const char *payload, size_t payloadSize)
1700 uint32_t day = gettodaydate();
1703 time_t current_time;
1704 struct tm * time_info;
1705 char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
1707 time(¤t_time);
1708 time_info = localtime(¤t_time);
1710 strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
1712 uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
1713 char* path = calloc(1, sizeof(char) * path_length);
1716 sprintf(path, RECEIVED_FILE_PATH, day, timeString);
1717 LOGI("received file path: %s", path);
1719 FILE *fp = fopen(path, "wt");
1720 fwrite(payload, 1, payloadSize, fp);
1723 callback("File Path: ", path);
1727 LOGE("path Out of memory");
1731 uint32_t gettodaydate()
1738 date = localtime(&clock);
1739 ldate = date->tm_year * 100000;
1740 ldate += (date->tm_mon + 1) * 1000;
1741 ldate += date->tm_mday * 10;
1742 ldate += date->tm_wday;