2 #include <android/log.h>
8 #include "cainterface.h"
10 #include "caadapterutils.h"
12 #include "org_iotivity_ca_service_RMInterface.h"
14 #define LOG_TAG "JNI_INTERFACE_SAMPLE"
15 #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
16 #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
22 #define IDENTITY ("1111111111111111")
26 #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
29 #define SECURE_DEFAULT_PORT 5684
30 #define RESOURCE_URI_LENGTH 14
31 #define OPTION_INFO_LENGTH 1024
32 #define NETWORK_INFO_LENGTH 1024
36 char ipAddress[CA_IPADDR_SIZE];
40 static void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo);
41 static void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo);
42 static void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
43 static void get_resource_uri(const char *URI, char *resourceURI, int32_t length);
44 static uint32_t get_secure_information(CAPayload_t payLoad);
45 static CAResult_t get_network_type(uint32_t selectedNetwork);
46 static void callback(char *subject, char *receivedData);
47 static CAResult_t get_remote_address(const char *address);
48 static void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
49 static void delete_global_references(JNIEnv *env, jobject obj);
50 static int get_address_set(const char *pAddress, addressSet_t* outAddress);
52 uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
53 CATransportAdapter_t g_selectedNwType = CA_ADAPTER_IP;
54 static CAToken_t g_lastRequestToken = NULL;
55 static uint8_t g_lastRequestTokenLength = 0;
57 static const char COAP_PREFIX[] = "coap://";
58 static const char COAPS_PREFIX[] = "coaps://";
59 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
60 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
62 static const char SECURE_INFO_DATA[]
63 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
64 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
66 static const char NORMAL_INFO_DATA[]
67 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
68 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
70 static jobject g_responseListenerObject = NULL;
73 static CAEndpoint_t *g_clientEndpoint = NULL;
74 static char *g_resourceUri = NULL;
75 static CAToken_t g_clientToken = NULL;
76 static uint8_t g_clientTokenLength = 0;
78 static uint16_t g_clientMsgId = 0;
79 static char *g_remoteAddress = NULL;
82 JNIEXPORT void JNICALL
83 Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
86 LOGI("setNativeResponseListener");
87 if (!env || !obj || !listener)
89 LOGI("Invalid input parameter");
93 g_responseListenerObject = (*env)->NewGlobalRef(env, listener);
97 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
99 void clearDtlsCredentialInfo()
101 LOGI("clearDtlsCredentialInfo IN");
104 // Initialize sensitive data to zeroes before freeing.
105 if (NULL != pskCredsBlob->creds)
107 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds)*(pskCredsBlob->num));
108 free(pskCredsBlob->creds);
111 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
115 LOGI("clearDtlsCredentialInfo OUT");
118 // Internal API. Invoked by OC stack to retrieve credentials from this module
119 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
121 LOGI("CAGetDtlsPskCredentials IN");
122 *credInfo = (CADtlsPskCredsBlob_t *) malloc(sizeof(CADtlsPskCredsBlob_t));
123 if (NULL == *credInfo)
125 LOGE("Failed to allocate credential blob.");
129 int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
130 (*credInfo)->creds = (OCDtlsPskCreds *) malloc(credLen);
131 if (NULL == (*credInfo)->creds)
133 LOGE("Failed to allocate crentials.");
139 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
140 (*credInfo)->num = pskCredsBlob->num;
141 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
143 LOGI("CAGetDtlsPskCredentials OUT");
146 CAResult_t SetCredentials()
148 LOGI("SetCredentials IN");
149 pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
150 if (NULL == pskCredsBlob)
152 LOGE("Memory allocation failed!");
153 return CA_MEMORY_ALLOC_FAILED;
155 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
157 pskCredsBlob->num = 1;
159 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) *(pskCredsBlob->num));
160 if (NULL == pskCredsBlob->creds)
162 LOGE("Memory allocation failed!");
163 return CA_MEMORY_ALLOC_FAILED;
165 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
166 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
168 LOGI("SetCredentials OUT");
173 JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
178 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
182 g_jvm = jvm; /* cache the JavaVM pointer */
184 CANativeJNISetJavaVM(g_jvm);
186 return JNI_VERSION_1_6;
189 void JNI_OnUnload(JavaVM *jvm, void *reserved)
191 LOGI("JNI_OnUnload");
194 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
202 JNIEXPORT void JNICALL
203 Java_org_iotivity_ca_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
205 LOGI("RMInitialize");
206 if (!env || !obj || !context)
208 LOGI("Invalid input parameter");
212 //Currently set context for Android Platform
213 CANativeJNISetContext(env, context);
215 CAResult_t res = CAInitialize();
217 if (CA_STATUS_OK != res)
219 LOGE("Could not Initialize");
223 if (CA_STATUS_OK != SetCredentials())
225 LOGE("SetCredentials failed");
229 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
230 if(CA_STATUS_OK != res)
232 LOGE("Set credential handler fail");
238 JNIEXPORT void JNICALL
239 Java_org_iotivity_ca_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
244 LOGI("Invalid input parameter");
248 CADestroyToken(g_lastRequestToken);
250 delete_global_references(env, obj);
253 JNIEXPORT void JNICALL
254 Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
256 LOGI("RMStartListeningServer");
259 LOGI("Invalid input parameter");
263 if (CA_STATUS_OK != CAStartListeningServer())
265 LOGE("Could not start Listening server");
269 JNIEXPORT void JNICALL
270 Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
272 LOGI("RMStartDiscoveryServer");
275 LOGI("Invalid input parameter");
279 if (CA_STATUS_OK != CAStartDiscoveryServer())
281 LOGE("Could not start discovery server");
285 JNIEXPORT void JNICALL
286 Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
288 LOGI("RMRegisterHandler");
291 LOGI("Invalid input parameter");
295 CARegisterHandler(request_handler, response_handler, error_handler);
298 JNIEXPORT void JNICALL
299 Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
300 jstring payload, jint selectedNetwork,
301 jint isSecured, jint msgType)
303 LOGI("selectedNetwork - %d", selectedNetwork);
306 LOGI("Invalid input parameter");
312 LOGE("payload is NULL");
317 LOGE("Invalid input parameter : uri");
321 CAResult_t res = get_network_type(selectedNetwork);
322 if (CA_STATUS_OK != res)
327 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
328 LOGI("RMSendRequest - %s", strUri);
330 CATransportFlags_t flags;
331 addressSet_t address = {{0}, 0};
332 parsing_coap_uri(strUri, &address, &flags);
334 //create remote endpoint
335 CAEndpoint_t* endpoint = NULL;
336 res = CACreateEndpoint(flags, g_selectedNwType, (const char*)(address.ipAddress),
337 address.port, &endpoint);
338 if (CA_STATUS_OK != res)
340 LOGE("Could not create remote end point");
341 (*env)->ReleaseStringUTFChars(env, uri, strUri);
345 CAMessageType_t messageType = msgType;
348 CAToken_t token = NULL;
349 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
351 res = CAGenerateToken(&token, tokenLength);
352 if ((CA_STATUS_OK != res) || (!token))
354 LOGE("token generate error!!");
355 // destroy remote endpoint
356 CADestroyEndpoint(endpoint);
357 (*env)->ReleaseStringUTFChars(env, uri, strUri);
361 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
363 get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
364 (*env)->ReleaseStringUTFChars(env, uri, strUri);
366 CAInfo_t requestData = { 0 };
367 requestData.token = token;
368 requestData.tokenLength = tokenLength;
372 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
373 requestData.payload = (CAPayload_t) malloc(length);
374 if (NULL == requestData.payload)
376 LOGE("Memory allocation failed!");
378 CADestroyToken(token);
379 // destroy remote endpoint
380 CADestroyEndpoint(endpoint);
383 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
384 requestData.payloadSize = length;
388 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
389 requestData.payload = (CAPayload_t) malloc(length);
390 if (NULL == requestData.payload)
392 LOGE("Memory allocation failed!");
394 CADestroyToken(token);
395 // destroy remote endpoint
396 CADestroyEndpoint(endpoint);
399 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
400 requestData.payloadSize = length;
403 requestData.type = messageType;
404 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
405 if (NULL == requestData.resourceUri)
407 LOGE("Memory allocation failed!");
409 CADestroyToken(token);
410 // destroy remote endpoint
411 CADestroyEndpoint(endpoint);
412 free(requestData.payload);
415 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
417 CARequestInfo_t requestInfo = { 0 };
418 requestInfo.method = CA_GET;
419 requestInfo.isMulticast = false;
420 requestInfo.info = requestData;
423 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
425 LOGE("Could not send request");
429 CADestroyToken(token);
431 // destroy remote endpoint
432 CADestroyEndpoint(endpoint);
434 free(requestData.payload);
435 free(requestData.resourceUri);
438 JNIEXPORT void JNICALL
439 Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
440 jint selectedNetwork)
442 LOGI("selectedNetwork - %d", selectedNetwork);
445 LOGI("Invalid input parameter");
449 CAResult_t res = get_network_type(selectedNetwork);
450 if (CA_STATUS_OK != res)
455 // create remote endpoint
456 CAEndpoint_t *endpoint = NULL;
457 res = CACreateEndpoint(CA_IPV4, g_selectedNwType, NULL, 0, &endpoint);
459 if (CA_STATUS_OK != res)
461 LOGE("create remote endpoint error, error code: %d", res);
466 CAToken_t token = NULL;
467 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
469 res = CAGenerateToken(&token, tokenLength);
470 if ((CA_STATUS_OK != res) || (!token))
472 LOGE("token generate error!!");
473 // destroy remote endpoint
474 CADestroyEndpoint(endpoint);
478 LOGI("generated token %s", token);
480 CAInfo_t requestData = { 0 };
481 requestData.token = token;
482 requestData.tokenLength = tokenLength;
483 requestData.payload = (CAPayload_t) "TempJsonPayload";
484 requestData.payloadSize = strlen((const char *) requestData.payload);
485 requestData.type = CA_MSG_NONCONFIRM;
487 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
488 LOGI("resourceUri - %s", strUri);
489 requestData.resourceUri = (CAURI_t)strUri;
491 uint8_t optionNum = 2;
492 CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
493 sizeof(CAHeaderOption_t) * optionNum);
494 if (NULL == headerOpt)
496 LOGE("Memory allocation failed");
497 // destroy remote endpoint
498 CADestroyEndpoint(endpoint);
502 char* FirstOptionData = "Hello";
503 headerOpt[0].optionID = 3000;
504 memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
505 headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
507 char* SecondOptionData2 = "World";
508 headerOpt[1].optionID = 3001;
509 memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
510 headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
512 requestData.numOptions = optionNum;
513 requestData.options = headerOpt;
515 CARequestInfo_t requestInfo = { 0 };
516 requestInfo.method = CA_GET;
517 requestInfo.isMulticast = true;
518 requestInfo.info = requestData;
520 // send request to all
521 res = CASendRequest(endpoint, &requestInfo);
522 if (CA_STATUS_OK != res)
524 LOGE("Could not send request to all");
526 CADestroyToken(token);
530 CADestroyToken(g_lastRequestToken);
531 g_lastRequestToken = token;
532 g_lastRequestTokenLength = tokenLength;
535 //ReleaseStringUTFChars for strUri
536 (*env)->ReleaseStringUTFChars(env, uri, strUri);
540 // destroy remote endpoint
541 CADestroyEndpoint(endpoint);
544 JNIEXPORT void JNICALL
545 Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
546 jint selectedNetwork,
547 jint isSecured, jint msgType,
550 LOGI("RMSendResponse");
553 LOGI("Invalid input parameter");
557 LOGI("selectedNetwork - %d", selectedNetwork);
559 CAResult_t res = get_network_type(selectedNetwork);
560 if (CA_STATUS_OK != res)
562 LOGE("Not supported network type");
566 if (NULL == g_clientEndpoint)
568 LOGE("No Request received");
572 CAMessageType_t messageType = msgType;
574 CAInfo_t responseData = { 0 };
575 responseData.type = messageType;
576 responseData.messageId = g_clientMsgId;
577 responseData.resourceUri = (CAURI_t)g_resourceUri;
579 CAResponseInfo_t responseInfo = { 0 };
581 if (msgType != CA_MSG_RESET)
583 responseData.token = g_clientToken;
584 responseData.tokenLength = g_clientTokenLength;
585 responseInfo.result = responseValue;
589 uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
590 responseData.payload = (CAPayload_t) malloc(length);
591 sprintf((char *) responseData.payload, SECURE_INFO_DATA, g_resourceUri,
593 responseData.payloadSize = length;
597 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
598 responseData.payload = (CAPayload_t) malloc(length);
599 sprintf((char *) responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
600 responseData.payloadSize = length;
606 responseInfo.result = CA_EMPTY;
609 responseInfo.info = responseData;
612 res = CASendResponse(g_clientEndpoint, &responseInfo);
613 if (CA_STATUS_OK != res)
615 LOGE("Could not send response");
619 CADestroyToken(g_clientToken);
620 g_clientToken = NULL;
621 g_clientTokenLength = 0;
623 // destroy remote endpoint
624 CADestroyEndpoint(g_clientEndpoint);
625 g_clientEndpoint = NULL;
628 JNIEXPORT void JNICALL
629 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
630 jstring payload, jint selectedNetwork,
631 jint isSecured, jint msgType,
634 LOGI("selectedNetwork - %d", selectedNetwork);
637 LOGI("Invalid input parameter");
643 LOGE("payload is NULL");
648 LOGE("Invalid input parameter : uri");
652 CAResult_t res = get_network_type(selectedNetwork);
653 if (CA_STATUS_OK != res)
655 LOGE("Not supported network type");
659 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
660 LOGI("RMSendNotification - %s", strUri);
662 CATransportFlags_t flags;
663 addressSet_t address = {{0}, 0};
664 parsing_coap_uri(strUri, &address, &flags);
666 //create remote endpoint
667 CAEndpoint_t* endpoint = NULL;
668 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
669 (const char*)address.ipAddress,
670 address.port, &endpoint))
672 //ReleaseStringUTFChars for strUri
673 (*env)->ReleaseStringUTFChars(env, uri, strUri);
674 LOGE("Could not create remote end point");
678 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
679 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
681 //ReleaseStringUTFChars for strUri
682 (*env)->ReleaseStringUTFChars(env, uri, strUri);
684 CAMessageType_t messageType = msgType;
687 CAToken_t token = NULL;
688 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
690 res = CAGenerateToken(&token, tokenLength);
691 if ((CA_STATUS_OK != res) || (!token))
693 LOGE("token generate error!");
694 CADestroyEndpoint(endpoint);
698 CAInfo_t responseData = { 0 };
699 responseData.token = token;
700 responseData.tokenLength = tokenLength;
701 responseData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
702 if (NULL == responseData.resourceUri)
704 LOGE("Memory allocation failed!");
706 CADestroyToken(token);
707 // destroy remote endpoint
708 CADestroyEndpoint(endpoint);
711 memcpy(responseData.resourceUri, resourceURI, sizeof(resourceURI));
715 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
716 responseData.payload = (CAPayload_t) malloc(length);
717 if (NULL == responseData.payload)
719 LOGE("Memory allocation failed!");
721 CADestroyToken(token);
722 // destroy remote endpoint
723 CADestroyEndpoint(endpoint);
725 free(responseData.resourceUri);
728 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
729 responseData.payloadSize = length;
733 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
734 responseData.payload = (CAPayload_t) malloc(length);
735 if (NULL == responseData.payload)
737 LOGE("Memory allocation failed!");
739 CADestroyToken(token);
740 // destroy remote endpoint
741 CADestroyEndpoint(endpoint);
743 free(responseData.resourceUri);
746 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
747 responseData.payloadSize = length;
750 responseData.type = messageType;
752 CAResponseInfo_t responseInfo = { 0 };
753 responseInfo.result = responseValue;
754 responseInfo.info = responseData;
757 if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
759 LOGE("Could not send notification");
762 LOGI("Send Notification");
765 CADestroyToken(token);
767 // destroy remote endpoint
768 CADestroyEndpoint(endpoint);
770 free(responseData.payload);
771 free(responseData.resourceUri);
774 JNIEXPORT void JNICALL
775 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
778 LOGI("RMSelectNetwork Type : %d", networkType);
781 LOGI("Invalid input parameter");
785 if (CA_STATUS_OK != CASelectNetwork(networkType))
787 LOGE("Could not select network");
791 JNIEXPORT void JNICALL
792 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
795 LOGI("RMUnSelectNetwork Type : %d", networkType);
798 LOGI("Invalid input parameter");
802 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
804 LOGE("Could not unselect network");
808 JNIEXPORT void JNICALL
809 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
811 LOGI("RMGetNetworkInfomation");
814 LOGI("Invalid input parameter");
818 CAEndpoint_t *tempInfo = NULL;
819 uint32_t tempSize = 0;
821 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
822 if (CA_STATUS_OK != res)
824 LOGE("Could not start get network information");
829 LOGI("################## Network Information #######################");
830 callback("######## Network Information", "#######");
831 LOGI("Network info total size is %d", tempSize);
834 for (index = 0; index < tempSize; index++)
836 res = get_remote_address(tempInfo[index].addr);
837 if (CA_STATUS_OK != res)
842 if (NULL != g_responseListenerObject)
844 char networkInfo[NETWORK_INFO_LENGTH];
845 LOGI("Type: %d", tempInfo[index].adapter);
846 sprintf(networkInfo, "%d",tempInfo[index].adapter);
847 callback("Type :", networkInfo);
848 if (CA_ADAPTER_IP == tempInfo[index].adapter)
850 LOGI("Port: %d", tempInfo[index].port);
851 sprintf(networkInfo, "%d",tempInfo[index].port);
852 callback("Port: ", networkInfo);
854 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
855 LOGI("Address: %s", g_remoteAddress);
856 callback("Address: ", g_remoteAddress);
857 free(g_remoteAddress);
859 if (tempInfo[index].flags & CA_SECURE)
861 g_localSecurePort = tempInfo[index].port;
868 LOGI("##############################################################");
871 JNIEXPORT void JNICALL
872 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
874 LOGI("RMHandleRequestResponse");
877 LOGI("Invalid input parameter");
881 if (CA_STATUS_OK != CAHandleRequestResponse())
883 LOGE("Could not handle request and response");
887 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
892 LOGE("Remote endpoint is NULL!");
898 LOGE("Request info is NULL!");
902 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
903 (strncmp(g_lastRequestToken, requestInfo->info.token,
904 requestInfo->info.tokenLength) == 0))
906 LOGI("token is same. received request of it's own. skip.. ");
910 CAResult_t res = get_remote_address(object->addr);
911 if (CA_STATUS_OK != res)
916 LOGI("##########received request from remote device #############");
917 LOGI("Remote Address: %s", g_remoteAddress);
918 LOGI("Remote Port: %d", object->port);
919 LOGI("Uri: %s", requestInfo->info.resourceUri);
920 LOGI("Data: %s", requestInfo->info.payload);
921 LOGI("Token: %s", requestInfo->info.token);
922 LOGI("Code: %d", requestInfo->method);
923 LOGI("MessageType: %d", requestInfo->info.type);
925 if (NULL != g_responseListenerObject)
927 char *cloneUri = NULL;
930 if (NULL != requestInfo->info.resourceUri)
932 len = strlen(requestInfo->info.resourceUri);
933 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
935 if (NULL == cloneUri)
937 LOGE("cloneUri Out of memory");
938 free(g_remoteAddress);
942 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
943 callback("Uri: ", cloneUri);
946 len = strlen(g_remoteAddress);
947 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
949 if (NULL == cloneRemoteAddress)
951 LOGE("cloneRemoteAddress Out of memory");
952 free(g_remoteAddress);
957 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
959 callback("Remote Address: ", cloneRemoteAddress);
960 free(cloneRemoteAddress);
961 free(g_remoteAddress);
963 char portInfo[PORT_LENGTH] = { 0, };
964 sprintf(portInfo, "%d", object->port);
965 callback("Remote Port: ", portInfo);
967 //clone g_clientEndpoint
968 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
969 if (NULL == g_clientEndpoint)
971 LOGE("g_clientEndpoint Out of memory");
975 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
977 if (NULL != cloneUri)
979 len = strlen(cloneUri);
980 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
981 if (NULL == g_resourceUri)
983 LOGE("g_clientEndpoint->resourceUri Out of memory");
984 free(g_clientEndpoint);
988 memcpy(g_resourceUri, cloneUri, len + 1);
991 //clone g_clientToken
992 len = requestInfo->info.tokenLength;
994 g_clientToken = (char *) malloc(sizeof(char) * len);
995 if (NULL == g_clientToken)
997 LOGE("g_clientToken Out of memory");
998 free(g_clientEndpoint);
1002 if (NULL != requestInfo->info.token)
1004 memcpy(g_clientToken, requestInfo->info.token, len);
1005 g_clientTokenLength = len;
1009 //clone g_clientMsgId
1010 g_clientMsgId = requestInfo->info.messageId;
1012 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1014 len = requestInfo->info.payloadSize;
1015 char *clonePayload = (char *) malloc(len + 1);
1016 if (NULL == clonePayload)
1018 LOGE("clonePayload Out of memory");
1019 free(g_clientEndpoint);
1023 memcpy(clonePayload, requestInfo->info.payload, len);
1024 clonePayload[len] = '\0';
1026 callback("Data: ", clonePayload);
1031 if (requestInfo->info.options)
1033 uint32_t len = requestInfo->info.numOptions;
1036 LOGI("Option count: %d", requestInfo->info.numOptions);
1038 for (i = 0; i < len; i++)
1040 LOGI("Option %d", i + 1);
1041 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1042 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1043 requestInfo->info.options[i].optionData);
1045 if (NULL != g_responseListenerObject)
1047 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1048 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1049 requestInfo->info.options[i].optionID,
1050 requestInfo->info.options[i].optionLength);
1052 callback("Option info: ", optionInfo);
1054 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1055 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1056 if (NULL == cloneOptionData)
1058 LOGE("cloneOptionData Out of memory");
1059 free(g_clientEndpoint);
1063 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1066 callback("Option Data: ", cloneOptionData);
1067 free(cloneOptionData);
1071 LOGI("############################################################");
1073 //Check if this has secure communication information
1074 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1076 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1077 if (0 < securePort) //Set the remote endpoint secure details and send response
1079 LOGI("This is secure resource...");
1081 CAEndpoint_t *endpoint = NULL;
1082 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1083 object->adapter, object->addr, securePort, &endpoint))
1085 LOGE("Failed to create duplicate of remote endpoint!");
1093 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1095 if (!object || !responseInfo)
1097 LOGE("Invalid input parameter");
1101 CAResult_t res = get_remote_address(object->addr);
1102 if (CA_STATUS_OK != res)
1107 LOGI("##########Received response from remote device #############");
1108 LOGI("Uri: %s", responseInfo->info.resourceUri);
1109 LOGI("Remote Address: %s", g_remoteAddress);
1110 LOGI("Remote Port: %d", object->port);
1111 LOGI("response result: %d", responseInfo->result);
1112 LOGI("Data: %s", responseInfo->info.payload);
1113 LOGI("Token: %s", responseInfo->info.token);
1114 LOGI("MessageType: %d", responseInfo->info.type);
1116 if (NULL != g_responseListenerObject)
1120 if (NULL != responseInfo->info.resourceUri)
1122 len = strlen(responseInfo->info.resourceUri);
1123 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1125 if (NULL == cloneUri)
1127 LOGE("cloneUri Out of memory");
1128 free(g_remoteAddress);
1132 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1134 callback("Uri: ", cloneUri);
1138 len = strlen(g_remoteAddress);
1139 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1141 if (NULL == cloneRemoteAddress)
1143 LOGE("cloneRemoteAddress Out of memory");
1144 free(g_remoteAddress);
1148 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1150 callback("Remote Address: ", cloneRemoteAddress);
1151 free(cloneRemoteAddress);
1152 free(g_remoteAddress);
1154 char portInfo[PORT_LENGTH] = { 0, };
1155 sprintf(portInfo, "%d", object->port);
1156 callback("Remote Port: ", portInfo);
1158 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1160 len = responseInfo->info.payloadSize;
1161 char *clonePayload = (char *) malloc(len + 1);
1162 if (NULL == clonePayload)
1164 LOGE("clonePayload Out of memory");
1168 memcpy(clonePayload, responseInfo->info.payload, len);
1169 clonePayload[len] = '\0';
1171 callback("Data: ", clonePayload);
1176 if (responseInfo->info.options)
1178 uint32_t len = responseInfo->info.numOptions;
1180 for (i = 0; i < len; i++)
1182 LOGI("Option %d", i + 1);
1183 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1184 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1185 responseInfo->info.options[i].optionData);
1187 if (NULL != g_responseListenerObject)
1189 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1190 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1191 responseInfo->info.options[i].optionID,
1192 responseInfo->info.options[i].optionLength);
1194 callback("Option info: ", optionInfo);
1196 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1197 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1198 if (NULL == cloneOptionData)
1200 LOGE("cloneOptionData Out of memory");
1203 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1205 callback("Option Data: ", cloneOptionData);
1206 free(cloneOptionData);
1210 LOGI("############################################################");
1212 //Check if this has secure communication information
1213 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1215 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1216 if (0 < securePort) //Set the remote endpoint secure details and send response
1218 LOGI("This is secure resource...");
1223 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1225 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1229 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1230 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1235 const CAInfo_t *info = &errorInfo->info;
1236 LOGI("Error Handler, ErrorInfo :");
1237 LOGI("Error Handler result : %d", errorInfo->result);
1238 LOGI("Error Handler token : %s", info->token);
1239 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1240 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1241 LOGI("Error Handler type : %d", info->type);
1242 LOGI("Error Handler payload : %s", info->payload);
1244 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1246 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1248 else if(CA_SEND_FAILED == errorInfo->result)
1250 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1252 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1254 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1256 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1258 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1260 else if(CA_STATUS_FAILED == errorInfo->result)
1262 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1265 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1270 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1272 const char *startPos = URI;
1273 const char *temp = strstr(URI, "://");
1276 startPos = strchr(temp + 3, '/');
1279 LOGE("Resource URI is missing");
1284 const char *endPos = strchr(startPos, '?');
1287 endPos = URI + strlen(URI);
1291 if (endPos - startPos <= length)
1293 memcpy(resourceURI, startPos + 1, endPos - startPos);
1296 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1299 uint32_t get_secure_information(CAPayload_t payLoad)
1301 LOGI("entering get_secure_information");
1305 LOGE("Payload is NULL");
1309 const char *subString = NULL;
1310 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1312 LOGE("This is not secure resource");
1316 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1318 LOGE("This secure resource does not have port information");
1322 const char *startPos = strstr(subString, ":");
1325 LOGE("Parsing failed !");
1329 const char *endPos = strstr(startPos, "}");
1332 LOGE("Parsing failed !");
1336 char portStr[6] = { 0 };
1337 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1339 LOGI("secured port is: %s", portStr);
1340 return atoi(portStr);
1343 CAResult_t get_network_type(uint32_t selectedNetwork)
1346 uint32_t number = selectedNetwork;
1348 if (!(number & 0xf))
1350 return CA_NOT_SUPPORTED;
1352 if (number & CA_ADAPTER_IP)
1354 g_selectedNwType = CA_ADAPTER_IP;
1355 return CA_STATUS_OK;
1357 if (number & CA_ADAPTER_RFCOMM_BTEDR)
1359 g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1360 return CA_STATUS_OK;
1362 if (number & CA_ADAPTER_GATT_BTLE)
1364 g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1365 return CA_STATUS_OK;
1368 return CA_NOT_SUPPORTED;
1371 void callback(char *subject, char *receivedData)
1373 bool isAttached = false;
1375 jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1378 LOGI("Could not get JNIEnv pointer");
1379 res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1383 LOGE("AttachCurrentThread has failed");
1389 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1390 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1391 "(Ljava/lang/String;Ljava/lang/String;)V");
1394 LOGE("could not get Method ID");
1398 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1401 LOGE("NewStringUTF failed");
1405 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1408 LOGE("NewStringUTF failed");
1412 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1417 (*g_jvm)->DetachCurrentThread(g_jvm);
1418 LOGI("DetachCurrentThread");
1422 CAResult_t get_remote_address(const char *address)
1424 uint32_t len = strlen(address);
1426 g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1427 if (NULL == g_remoteAddress)
1429 LOGE("g_remoteAddress Out of memory");
1430 return CA_MEMORY_ALLOC_FAILED;
1433 memcpy(g_remoteAddress, address, len + 1);
1435 return CA_STATUS_OK;
1439 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1441 if (NULL == uri || NULL == address)
1443 LOGE("parameter is null");
1449 uint8_t startIndex = 0;
1450 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1452 LOGI("uri has '%s' prefix", COAPS_PREFIX);
1453 startIndex = COAPS_PREFIX_LEN;
1456 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1458 LOGI("uri has '%s' prefix", COAP_PREFIX);
1459 startIndex = COAP_PREFIX_LEN;
1463 // #2. copy uri for parse
1464 int32_t len = strlen(uri) - startIndex;
1468 LOGE("uri length is 0!");
1472 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1473 if (NULL == cloneUri)
1475 LOGE("Out of memory");
1479 memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1480 cloneUri[len] = '\0';
1482 char *pAddress = cloneUri;
1483 LOGI("pAddress : %s", pAddress);
1485 int res = get_address_set(pAddress, address);
1488 LOGE("address parse error");
1497 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1499 if (NULL == pAddress || NULL == outAddress)
1501 LOGE("parameter is null");
1505 size_t len = strlen(pAddress);
1509 for (size_t i = 0; i < len; i++)
1511 if (pAddress[i] == '.')
1516 // found port number start index
1517 if (isIp && pAddress[i] == ':')
1526 if(ipLen && (ipLen < sizeof(outAddress->ipAddress)))
1528 strncpy(outAddress->ipAddress, pAddress, ipLen);
1529 outAddress->ipAddress[ipLen] = '\0';
1531 else if (!ipLen && (len < sizeof(outAddress->ipAddress)))
1533 strncpy(outAddress->ipAddress, pAddress, len);
1534 outAddress->ipAddress[len] = '\0';
1538 LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1544 outAddress->port = atoi(pAddress + ipLen + 1);
1549 strncpy(outAddress->ipAddress, pAddress, len);
1550 outAddress->ipAddress[len] = '\0';
1556 void delete_global_references(JNIEnv *env, jobject obj)
1558 LOGI("delete_global_references");
1561 LOGI("Invalid input parameter");
1565 (*env)->DeleteGlobalRef(env, g_responseListenerObject);