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__)
20 // Iotivity Device Identity.
21 const unsigned char IDENTITY[] = ("1111111111111111");
23 // PSK between this device and peer device.
24 const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
27 #define SECURE_DEFAULT_PORT 5684
28 #define RESOURCE_URI_LENGTH 14
29 #define OPTION_INFO_LENGTH 1024
30 #define NETWORK_INFO_LENGTH 1024
31 #define BIG_PAYLOAD_LENGTH 1024
32 #define RECEIVED_FILE_NAME_PREFIX_LENGTH 7
33 #define RECEIVED_FILE_NAME_LENGTH 14
37 char ipAddress[CA_IPADDR_SIZE];
41 static void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo);
42 static void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo);
43 static void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
44 static void get_resource_uri(const char *URI, char *resourceURI, int32_t length);
45 static uint32_t get_secure_information(CAPayload_t payLoad);
46 static CAResult_t get_network_type(uint32_t selectedNetwork);
47 static void callback(char *subject, char *receivedData);
48 static CAResult_t get_remote_address(const char *address);
49 static void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
50 static void delete_global_references(JNIEnv *env, jobject obj);
51 static int get_address_set(const char *pAddress, addressSet_t* outAddress);
52 bool read_file(const char* name, char** bytes, size_t* length);
53 uint32_t gettodaydate();
54 void saveFile(const char *payload, size_t payloadSize);
56 uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
57 CATransportAdapter_t g_selectedNwType = CA_ADAPTER_IP;
58 static CAToken_t g_lastRequestToken = NULL;
59 static uint8_t g_lastRequestTokenLength = 0;
61 static const char COAP_PREFIX[] = "coap://";
62 static const char COAPS_PREFIX[] = "coaps://";
63 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
64 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
66 static const char RECEIVED_FILE_PATH[] = "/storage/emulated/0/Download/%d%s.txt";
68 static const char SECURE_INFO_DATA[]
69 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
70 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
72 static const char NORMAL_INFO_DATA[]
73 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
74 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
76 static jobject g_responseListenerObject = NULL;
79 static CAEndpoint_t *g_clientEndpoint = NULL;
80 static char *g_resourceUri = NULL;
81 static CAToken_t g_clientToken = NULL;
82 static uint8_t g_clientTokenLength = 0;
84 static uint16_t g_clientMsgId = 0;
85 static char *g_remoteAddress = NULL;
88 JNIEXPORT void JNICALL
89 Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
92 LOGI("setNativeResponseListener");
93 if (!env || !obj || !listener)
95 LOGI("Invalid input parameter");
99 g_responseListenerObject = (*env)->NewGlobalRef(env, listener);
103 // Internal API. Invoked by OC stack to retrieve credentials from this module
104 int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
105 const unsigned char *desc, size_t desc_len,
106 unsigned char *result, size_t result_length)
108 LOGI("CAGetDtlsPskCredentials IN");
119 case CA_DTLS_PSK_HINT:
120 case CA_DTLS_PSK_IDENTITY:
122 if (result_length < sizeof(IDENTITY))
124 LOGE("ERROR : Wrong value for result for storing IDENTITY");
128 memcpy(result, IDENTITY, sizeof(IDENTITY));
129 ret = sizeof(IDENTITY);
132 case CA_DTLS_PSK_KEY:
134 if ((desc_len == sizeof(IDENTITY)) &&
135 memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
137 if (result_length < sizeof(RS_CLIENT_PSK))
139 LOGE("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
143 memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
144 ret = sizeof(RS_CLIENT_PSK);
150 LOGE("Wrong value passed for PSK_CRED_TYPE.");
154 LOGI("CAGetDtlsPskCredentials OUT\n");
160 JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
166 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
170 g_jvm = jvm; /* cache the JavaVM pointer */
172 CANativeJNISetJavaVM(g_jvm);
174 return JNI_VERSION_1_6;
177 void JNI_OnUnload(JavaVM *jvm, void *reserved)
179 LOGI("JNI_OnUnload");
183 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
191 JNIEXPORT void JNICALL
192 Java_org_iotivity_ca_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
194 LOGI("RMInitialize");
195 if (!env || !obj || !context)
197 LOGI("Invalid input parameter");
201 //Currently set context for Android Platform
202 CANativeJNISetContext(env, context);
204 CAResult_t res = CAInitialize();
206 if (CA_STATUS_OK != res)
208 LOGE("Could not Initialize");
212 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
213 if(CA_STATUS_OK != res)
215 LOGE("Set credential handler fail");
221 JNIEXPORT void JNICALL
222 Java_org_iotivity_ca_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
227 LOGI("Invalid input parameter");
231 CADestroyToken(g_lastRequestToken);
233 delete_global_references(env, obj);
236 JNIEXPORT void JNICALL
237 Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
239 LOGI("RMStartListeningServer");
242 LOGI("Invalid input parameter");
246 if (CA_STATUS_OK != CAStartListeningServer())
248 LOGE("Could not start Listening server");
252 JNIEXPORT void JNICALL
253 Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
255 LOGI("RMStartDiscoveryServer");
258 LOGI("Invalid input parameter");
262 if (CA_STATUS_OK != CAStartDiscoveryServer())
264 LOGE("Could not start discovery server");
268 JNIEXPORT void JNICALL
269 Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
271 LOGI("RMRegisterHandler");
274 LOGI("Invalid input parameter");
278 CARegisterHandler(request_handler, response_handler, error_handler);
281 JNIEXPORT void JNICALL
282 Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
283 jstring payload, jint selectedNetwork,
284 jint isSecured, jint msgType,
287 LOGI("selectedNetwork - %d", selectedNetwork);
290 LOGI("Invalid input parameter");
296 LOGE("Invalid input parameter : uri");
300 CAResult_t res = get_network_type(selectedNetwork);
301 if (CA_STATUS_OK != res)
306 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
307 LOGI("RMSendRequest - %s", strUri);
309 CATransportFlags_t flags;
310 addressSet_t address = {{0}, 0};
311 parsing_coap_uri(strUri, &address, &flags);
313 //create remote endpoint
314 CAEndpoint_t* endpoint = NULL;
315 res = CACreateEndpoint(flags, g_selectedNwType, (const char*)(address.ipAddress),
316 address.port, &endpoint);
317 if (CA_STATUS_OK != res)
319 LOGE("Could not create remote end point");
320 (*env)->ReleaseStringUTFChars(env, uri, strUri);
324 CAMessageType_t messageType = msgType;
327 CAToken_t token = NULL;
328 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
330 res = CAGenerateToken(&token, tokenLength);
331 if ((CA_STATUS_OK != res) || (!token))
333 LOGE("token generate error!!");
334 // destroy remote endpoint
335 CADestroyEndpoint(endpoint);
336 (*env)->ReleaseStringUTFChars(env, uri, strUri);
340 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
342 get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
343 (*env)->ReleaseStringUTFChars(env, uri, strUri);
345 CAInfo_t requestData = { 0 };
346 requestData.token = token;
347 requestData.tokenLength = tokenLength;
349 size_t payloadLength = 0;
352 const char* path = NULL;
355 path = (*env)->GetStringUTFChars(env, payload, NULL);
358 char* bigData = NULL;
359 bool result = read_file(path, &bigData, &payloadLength);
362 LOGE("read has failed");
363 (*env)->ReleaseStringUTFChars(env, payload, path);
364 CADestroyToken(token);
365 CADestroyEndpoint(endpoint);
368 (*env)->ReleaseStringUTFChars(env, payload, path);
370 requestData.payload = (CAPayload_t) malloc(payloadLength);
371 if (NULL == requestData.payload)
373 LOGE("Memory allocation failed!");
375 CADestroyToken(token);
376 // destroy remote endpoint
377 CADestroyEndpoint(endpoint);
380 memcpy(requestData.payload, bigData, payloadLength);
381 requestData.payloadSize = payloadLength;
389 payloadLength = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
390 requestData.payload = (CAPayload_t) malloc(payloadLength);
391 if (NULL == requestData.payload)
393 LOGE("Memory allocation failed!");
395 CADestroyToken(token);
396 // destroy remote endpoint
397 CADestroyEndpoint(endpoint);
400 snprintf((char *) requestData.payload, payloadLength, SECURE_INFO_DATA,
401 resourceURI, g_localSecurePort);
402 requestData.payloadSize = payloadLength;
406 payloadLength = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
407 requestData.payload = (CAPayload_t) malloc(payloadLength);
408 if (NULL == requestData.payload)
410 LOGE("Memory allocation failed!");
412 CADestroyToken(token);
413 // destroy remote endpoint
414 CADestroyEndpoint(endpoint);
417 snprintf((char *) requestData.payload, payloadLength, NORMAL_INFO_DATA, resourceURI);
418 requestData.payloadSize = payloadLength;
422 requestData.type = messageType;
423 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
424 if (NULL == requestData.resourceUri)
426 LOGE("Memory allocation failed!");
428 CADestroyToken(token);
429 // destroy remote endpoint
430 CADestroyEndpoint(endpoint);
431 free(requestData.payload);
434 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
436 CARequestInfo_t requestInfo = { 0 };
437 requestInfo.method = CA_GET;
438 requestInfo.isMulticast = false;
439 requestInfo.info = requestData;
442 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
444 LOGE("Could not send request");
448 CADestroyToken(token);
450 // destroy remote endpoint
451 CADestroyEndpoint(endpoint);
453 free(requestData.payload);
454 free(requestData.resourceUri);
457 JNIEXPORT void JNICALL
458 Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
459 jint selectedNetwork)
461 LOGI("selectedNetwork - %d", selectedNetwork);
464 LOGI("Invalid input parameter");
468 CAResult_t res = get_network_type(selectedNetwork);
469 if (CA_STATUS_OK != res)
474 // create remote endpoint
475 CAEndpoint_t *endpoint = NULL;
476 res = CACreateEndpoint(CA_IPV4, g_selectedNwType, NULL, 0, &endpoint);
478 if (CA_STATUS_OK != res)
480 LOGE("create remote endpoint error, error code: %d", res);
485 CAToken_t token = NULL;
486 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
488 res = CAGenerateToken(&token, tokenLength);
489 if ((CA_STATUS_OK != res) || (!token))
491 LOGE("token generate error!!");
492 // destroy remote endpoint
493 CADestroyEndpoint(endpoint);
497 LOGI("generated token %s", token);
499 CAInfo_t requestData = { 0 };
500 requestData.token = token;
501 requestData.tokenLength = tokenLength;
502 requestData.payload = (CAPayload_t) "TempJsonPayload";
503 requestData.payloadSize = strlen((const char *) requestData.payload);
504 requestData.type = CA_MSG_NONCONFIRM;
506 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
507 LOGI("resourceUri - %s", strUri);
508 requestData.resourceUri = (CAURI_t)strUri;
510 uint8_t optionNum = 2;
511 CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
512 sizeof(CAHeaderOption_t) * optionNum);
513 if (NULL == headerOpt)
515 LOGE("Memory allocation failed");
516 // destroy remote endpoint
517 CADestroyEndpoint(endpoint);
521 char* FirstOptionData = "Hello";
522 headerOpt[0].optionID = 3000;
523 memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
524 headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
526 char* SecondOptionData2 = "World";
527 headerOpt[1].optionID = 3001;
528 memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
529 headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
531 requestData.numOptions = optionNum;
532 requestData.options = headerOpt;
534 CARequestInfo_t requestInfo = { 0 };
535 requestInfo.method = CA_GET;
536 requestInfo.isMulticast = true;
537 requestInfo.info = requestData;
539 // send request to all
540 res = CASendRequest(endpoint, &requestInfo);
541 if (CA_STATUS_OK != res)
543 LOGE("Could not send request to all");
545 CADestroyToken(token);
549 CADestroyToken(g_lastRequestToken);
550 g_lastRequestToken = token;
551 g_lastRequestTokenLength = tokenLength;
554 //ReleaseStringUTFChars for strUri
555 (*env)->ReleaseStringUTFChars(env, uri, strUri);
559 // destroy remote endpoint
560 CADestroyEndpoint(endpoint);
563 JNIEXPORT void JNICALL
564 Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
565 jint selectedNetwork,
566 jint isSecured, jint msgType,
569 LOGI("RMSendResponse");
572 LOGI("Invalid input parameter");
576 LOGI("selectedNetwork - %d", selectedNetwork);
578 CAResult_t res = get_network_type(selectedNetwork);
579 if (CA_STATUS_OK != res)
581 LOGE("Not supported network type");
585 if (NULL == g_clientEndpoint)
587 LOGE("No Request received");
591 CAMessageType_t messageType = msgType;
593 CAInfo_t responseData = { 0 };
594 responseData.type = messageType;
595 responseData.messageId = g_clientMsgId;
596 responseData.resourceUri = (CAURI_t)g_resourceUri;
598 CAResponseInfo_t responseInfo = { 0 };
600 if (msgType != CA_MSG_RESET)
602 responseData.token = g_clientToken;
603 responseData.tokenLength = g_clientTokenLength;
604 responseInfo.result = responseValue;
608 uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
609 responseData.payload = (CAPayload_t) malloc(length);
610 sprintf((char *) responseData.payload, SECURE_INFO_DATA, g_resourceUri,
612 responseData.payloadSize = length;
616 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
617 responseData.payload = (CAPayload_t) malloc(length);
618 sprintf((char *) responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
619 responseData.payloadSize = length;
625 responseInfo.result = CA_EMPTY;
628 responseInfo.info = responseData;
631 res = CASendResponse(g_clientEndpoint, &responseInfo);
632 if (CA_STATUS_OK != res)
634 LOGE("Could not send response");
638 CADestroyToken(g_clientToken);
639 g_clientToken = NULL;
640 g_clientTokenLength = 0;
642 // destroy remote endpoint
643 CADestroyEndpoint(g_clientEndpoint);
644 g_clientEndpoint = NULL;
647 JNIEXPORT void JNICALL
648 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
649 jstring payload, jint selectedNetwork,
650 jint isSecured, jint msgType,
653 LOGI("selectedNetwork - %d", selectedNetwork);
656 LOGI("Invalid input parameter");
662 LOGE("payload is NULL");
667 LOGE("Invalid input parameter : uri");
671 CAResult_t res = get_network_type(selectedNetwork);
672 if (CA_STATUS_OK != res)
674 LOGE("Not supported network type");
678 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
679 LOGI("RMSendNotification - %s", strUri);
681 CATransportFlags_t flags;
682 addressSet_t address = {{0}, 0};
683 parsing_coap_uri(strUri, &address, &flags);
685 //create remote endpoint
686 CAEndpoint_t* endpoint = NULL;
687 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
688 (const char*)address.ipAddress,
689 address.port, &endpoint))
691 //ReleaseStringUTFChars for strUri
692 (*env)->ReleaseStringUTFChars(env, uri, strUri);
693 LOGE("Could not create remote end point");
697 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
698 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
700 //ReleaseStringUTFChars for strUri
701 (*env)->ReleaseStringUTFChars(env, uri, strUri);
703 CAMessageType_t messageType = msgType;
706 CAToken_t token = NULL;
707 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
709 res = CAGenerateToken(&token, tokenLength);
710 if ((CA_STATUS_OK != res) || (!token))
712 LOGE("token generate error!");
713 CADestroyEndpoint(endpoint);
717 CAInfo_t responseData = { 0 };
718 responseData.token = token;
719 responseData.tokenLength = tokenLength;
720 responseData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
721 if (NULL == responseData.resourceUri)
723 LOGE("Memory allocation failed!");
725 CADestroyToken(token);
726 // destroy remote endpoint
727 CADestroyEndpoint(endpoint);
730 memcpy(responseData.resourceUri, resourceURI, sizeof(resourceURI));
734 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
735 responseData.payload = (CAPayload_t) malloc(length);
736 if (NULL == responseData.payload)
738 LOGE("Memory allocation failed!");
740 CADestroyToken(token);
741 // destroy remote endpoint
742 CADestroyEndpoint(endpoint);
744 free(responseData.resourceUri);
747 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
748 responseData.payloadSize = length;
752 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
753 responseData.payload = (CAPayload_t) malloc(length);
754 if (NULL == responseData.payload)
756 LOGE("Memory allocation failed!");
758 CADestroyToken(token);
759 // destroy remote endpoint
760 CADestroyEndpoint(endpoint);
762 free(responseData.resourceUri);
765 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
766 responseData.payloadSize = length;
769 responseData.type = messageType;
771 CAResponseInfo_t responseInfo = { 0 };
772 responseInfo.result = responseValue;
773 responseInfo.info = responseData;
776 if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
778 LOGE("Could not send notification");
781 LOGI("Send Notification");
784 CADestroyToken(token);
786 // destroy remote endpoint
787 CADestroyEndpoint(endpoint);
789 free(responseData.payload);
790 free(responseData.resourceUri);
793 JNIEXPORT void JNICALL
794 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
797 LOGI("RMSelectNetwork Type : %d", networkType);
800 LOGI("Invalid input parameter");
804 if (CA_STATUS_OK != CASelectNetwork(networkType))
806 LOGE("Could not select network");
810 JNIEXPORT void JNICALL
811 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
814 LOGI("RMUnSelectNetwork Type : %d", networkType);
817 LOGI("Invalid input parameter");
821 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
823 LOGE("Could not unselect network");
827 JNIEXPORT void JNICALL
828 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
830 LOGI("RMGetNetworkInfomation");
833 LOGI("Invalid input parameter");
837 CAEndpoint_t *tempInfo = NULL;
838 uint32_t tempSize = 0;
840 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
841 if (CA_STATUS_OK != res)
843 LOGE("Could not start get network information");
848 LOGI("################## Network Information #######################");
849 callback("######## Network Information", "#######");
850 LOGI("Network info total size is %d", tempSize);
853 for (index = 0; index < tempSize; index++)
855 res = get_remote_address(tempInfo[index].addr);
856 if (CA_STATUS_OK != res)
861 if (NULL != g_responseListenerObject)
863 char networkInfo[NETWORK_INFO_LENGTH];
864 LOGI("Type: %d", tempInfo[index].adapter);
865 sprintf(networkInfo, "%d",tempInfo[index].adapter);
866 callback("Type :", networkInfo);
867 if (CA_ADAPTER_IP == tempInfo[index].adapter)
869 LOGI("Port: %d", tempInfo[index].port);
870 sprintf(networkInfo, "%d",tempInfo[index].port);
871 callback("Port: ", networkInfo);
873 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
874 LOGI("Address: %s", g_remoteAddress);
875 callback("Address: ", g_remoteAddress);
876 free(g_remoteAddress);
878 if (tempInfo[index].flags & CA_SECURE)
880 g_localSecurePort = tempInfo[index].port;
887 LOGI("##############################################################");
890 JNIEXPORT void JNICALL
891 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
893 LOGI("RMHandleRequestResponse");
896 LOGI("Invalid input parameter");
900 if (CA_STATUS_OK != CAHandleRequestResponse())
902 LOGE("Could not handle request and response");
906 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
911 LOGE("Remote endpoint is NULL!");
917 LOGE("Request info is NULL!");
921 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
922 (strncmp(g_lastRequestToken, requestInfo->info.token,
923 requestInfo->info.tokenLength) == 0))
925 LOGI("token is same. received request of it's own. skip.. ");
929 CAResult_t res = get_remote_address(object->addr);
930 if (CA_STATUS_OK != res)
935 LOGI("##########received request from remote device #############");
936 LOGI("Remote Address: %s", g_remoteAddress);
937 LOGI("Remote Port: %d", object->port);
938 LOGI("Uri: %s", requestInfo->info.resourceUri);
939 LOGI("Data: %s", requestInfo->info.payload);
940 LOGI("Token: %s", requestInfo->info.token);
941 LOGI("Code: %d", requestInfo->method);
942 LOGI("MessageType: %d", requestInfo->info.type);
944 if (NULL != g_responseListenerObject)
946 char *cloneUri = NULL;
949 if (NULL != requestInfo->info.resourceUri)
951 len = strlen(requestInfo->info.resourceUri);
952 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
954 if (NULL == cloneUri)
956 LOGE("cloneUri Out of memory");
957 free(g_remoteAddress);
961 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
962 callback("Uri: ", cloneUri);
965 len = strlen(g_remoteAddress);
966 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
968 if (NULL == cloneRemoteAddress)
970 LOGE("cloneRemoteAddress Out of memory");
971 free(g_remoteAddress);
976 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
978 callback("Remote Address: ", cloneRemoteAddress);
979 free(cloneRemoteAddress);
980 free(g_remoteAddress);
982 char portInfo[PORT_LENGTH] = { 0, };
983 sprintf(portInfo, "%d", object->port);
984 callback("Remote Port: ", portInfo);
986 //clone g_clientEndpoint
987 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
988 if (NULL == g_clientEndpoint)
990 LOGE("g_clientEndpoint Out of memory");
994 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
996 if (NULL != cloneUri)
998 len = strlen(cloneUri);
999 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
1000 if (NULL == g_resourceUri)
1002 LOGE("g_clientEndpoint->resourceUri Out of memory");
1003 free(g_clientEndpoint);
1007 memcpy(g_resourceUri, cloneUri, len + 1);
1010 //clone g_clientToken
1011 len = requestInfo->info.tokenLength;
1013 g_clientToken = (char *) malloc(sizeof(char) * len);
1014 if (NULL == g_clientToken)
1016 LOGE("g_clientToken Out of memory");
1017 free(g_clientEndpoint);
1021 if (NULL != requestInfo->info.token)
1023 memcpy(g_clientToken, requestInfo->info.token, len);
1024 g_clientTokenLength = len;
1028 //clone g_clientMsgId
1029 g_clientMsgId = requestInfo->info.messageId;
1031 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1033 len = requestInfo->info.payloadSize;
1034 char *clonePayload = (char *) malloc(len + 1);
1035 if (NULL == clonePayload)
1037 LOGE("clonePayload Out of memory");
1038 free(g_clientEndpoint);
1042 memcpy(clonePayload, requestInfo->info.payload, len);
1043 clonePayload[len] = '\0';
1045 if (len > BIG_PAYLOAD_LENGTH)
1047 saveFile(clonePayload, len);
1051 callback("Data: ", clonePayload);
1057 if (requestInfo->info.options)
1059 uint32_t len = requestInfo->info.numOptions;
1062 LOGI("Option count: %d", requestInfo->info.numOptions);
1064 for (i = 0; i < len; i++)
1066 LOGI("Option %d", i + 1);
1067 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1068 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1069 requestInfo->info.options[i].optionData);
1071 if (NULL != g_responseListenerObject)
1073 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1074 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1075 requestInfo->info.options[i].optionID,
1076 requestInfo->info.options[i].optionLength);
1078 callback("Option info: ", optionInfo);
1080 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1081 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1082 if (NULL == cloneOptionData)
1084 LOGE("cloneOptionData Out of memory");
1085 free(g_clientEndpoint);
1089 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1092 callback("Option Data: ", cloneOptionData);
1093 free(cloneOptionData);
1097 LOGI("############################################################");
1099 //Check if this has secure communication information
1100 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1102 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1103 if (0 < securePort) //Set the remote endpoint secure details and send response
1105 LOGI("This is secure resource...");
1107 CAEndpoint_t *endpoint = NULL;
1108 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1109 object->adapter, object->addr, securePort, &endpoint))
1111 LOGE("Failed to create duplicate of remote endpoint!");
1119 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1121 if (!object || !responseInfo)
1123 LOGE("Invalid input parameter");
1127 CAResult_t res = get_remote_address(object->addr);
1128 if (CA_STATUS_OK != res)
1133 LOGI("##########Received response from remote device #############");
1134 LOGI("Uri: %s", responseInfo->info.resourceUri);
1135 LOGI("Remote Address: %s", g_remoteAddress);
1136 LOGI("Remote Port: %d", object->port);
1137 LOGI("response result: %d", responseInfo->result);
1138 LOGI("Data: %s", responseInfo->info.payload);
1139 LOGI("Token: %s", responseInfo->info.token);
1140 LOGI("MessageType: %d", responseInfo->info.type);
1142 if (NULL != g_responseListenerObject)
1146 if (NULL != responseInfo->info.resourceUri)
1148 len = strlen(responseInfo->info.resourceUri);
1149 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1151 if (NULL == cloneUri)
1153 LOGE("cloneUri Out of memory");
1154 free(g_remoteAddress);
1158 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1160 callback("Uri: ", cloneUri);
1164 len = strlen(g_remoteAddress);
1165 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1167 if (NULL == cloneRemoteAddress)
1169 LOGE("cloneRemoteAddress Out of memory");
1170 free(g_remoteAddress);
1174 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1176 callback("Remote Address: ", cloneRemoteAddress);
1177 free(cloneRemoteAddress);
1178 free(g_remoteAddress);
1180 char portInfo[PORT_LENGTH] = { 0, };
1181 sprintf(portInfo, "%d", object->port);
1182 callback("Remote Port: ", portInfo);
1184 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1186 len = responseInfo->info.payloadSize;
1187 char *clonePayload = (char *) malloc(len + 1);
1188 if (NULL == clonePayload)
1190 LOGE("clonePayload Out of memory");
1194 memcpy(clonePayload, responseInfo->info.payload, len);
1195 clonePayload[len] = '\0';
1197 if (len > BIG_PAYLOAD_LENGTH)
1199 saveFile(clonePayload, len);
1203 callback("Data: ", clonePayload);
1209 if (responseInfo->info.options)
1211 uint32_t len = responseInfo->info.numOptions;
1213 for (i = 0; i < len; i++)
1215 LOGI("Option %d", i + 1);
1216 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1217 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1218 responseInfo->info.options[i].optionData);
1220 if (NULL != g_responseListenerObject)
1222 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1223 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1224 responseInfo->info.options[i].optionID,
1225 responseInfo->info.options[i].optionLength);
1227 callback("Option info: ", optionInfo);
1229 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1230 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1231 if (NULL == cloneOptionData)
1233 LOGE("cloneOptionData Out of memory");
1236 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1238 callback("Option Data: ", cloneOptionData);
1239 free(cloneOptionData);
1243 LOGI("############################################################");
1245 //Check if this has secure communication information
1246 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1248 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1249 if (0 < securePort) //Set the remote endpoint secure details and send response
1251 LOGI("This is secure resource...");
1256 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1258 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1262 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1263 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1268 const CAInfo_t *info = &errorInfo->info;
1269 LOGI("Error Handler, ErrorInfo :");
1270 LOGI("Error Handler result : %d", errorInfo->result);
1271 LOGI("Error Handler token : %s", info->token);
1272 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1273 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1274 LOGI("Error Handler type : %d", info->type);
1275 LOGI("Error Handler payload : %s", info->payload);
1277 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1279 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1281 else if(CA_SEND_FAILED == errorInfo->result)
1283 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1285 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1287 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1289 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1291 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1293 else if(CA_STATUS_FAILED == errorInfo->result)
1295 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1298 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1303 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1305 const char *startPos = URI;
1306 const char *temp = strstr(URI, "://");
1309 startPos = strchr(temp + 3, '/');
1312 LOGE("Resource URI is missing");
1317 const char *endPos = strchr(startPos, '?');
1320 endPos = URI + strlen(URI);
1324 if (endPos - startPos <= length)
1326 memcpy(resourceURI, startPos + 1, endPos - startPos);
1329 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1332 uint32_t get_secure_information(CAPayload_t payLoad)
1334 LOGI("entering get_secure_information");
1338 LOGE("Payload is NULL");
1342 const char *subString = NULL;
1343 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1345 LOGE("This is not secure resource");
1349 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1351 LOGE("This secure resource does not have port information");
1355 const char *startPos = strstr(subString, ":");
1358 LOGE("Parsing failed !");
1362 const char *endPos = strstr(startPos, "}");
1365 LOGE("Parsing failed !");
1369 char portStr[6] = { 0 };
1370 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1372 LOGI("secured port is: %s", portStr);
1373 return atoi(portStr);
1376 CAResult_t get_network_type(uint32_t selectedNetwork)
1379 uint32_t number = selectedNetwork;
1381 if (!(number & 0xf))
1383 return CA_NOT_SUPPORTED;
1385 if (number & CA_ADAPTER_IP)
1387 g_selectedNwType = CA_ADAPTER_IP;
1388 return CA_STATUS_OK;
1390 if (number & CA_ADAPTER_RFCOMM_BTEDR)
1392 g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1393 return CA_STATUS_OK;
1395 if (number & CA_ADAPTER_GATT_BTLE)
1397 g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1398 return CA_STATUS_OK;
1401 return CA_NOT_SUPPORTED;
1404 void callback(char *subject, char *receivedData)
1406 bool isAttached = false;
1409 if (!g_responseListenerObject)
1411 LOGE("g_responseListenerObject is NULL, cannot have callback");
1415 jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1418 LOGI("Could not get JNIEnv pointer");
1419 res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1423 LOGE("AttachCurrentThread has failed");
1429 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1432 LOGE("could not get class");
1436 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1437 "(Ljava/lang/String;Ljava/lang/String;)V");
1440 LOGE("could not get Method ID");
1444 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1447 LOGE("NewStringUTF failed");
1451 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1454 LOGE("NewStringUTF failed");
1458 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1463 (*g_jvm)->DetachCurrentThread(g_jvm);
1464 LOGI("DetachCurrentThread");
1468 CAResult_t get_remote_address(const char *address)
1470 uint32_t len = strlen(address);
1472 g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1473 if (NULL == g_remoteAddress)
1475 LOGE("g_remoteAddress Out of memory");
1476 return CA_MEMORY_ALLOC_FAILED;
1479 memcpy(g_remoteAddress, address, len + 1);
1481 return CA_STATUS_OK;
1485 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1487 if (NULL == uri || NULL == address)
1489 LOGE("parameter is null");
1495 uint8_t startIndex = 0;
1496 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1498 LOGI("uri has '%s' prefix", COAPS_PREFIX);
1499 startIndex = COAPS_PREFIX_LEN;
1502 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1504 LOGI("uri has '%s' prefix", COAP_PREFIX);
1505 startIndex = COAP_PREFIX_LEN;
1509 // #2. copy uri for parse
1510 size_t len = strlen(uri) - startIndex;
1514 LOGE("uri length is 0!");
1518 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1519 if (NULL == cloneUri)
1521 LOGE("Out of memory");
1525 OICStrcpy(cloneUri, len+1, &uri[startIndex]);
1528 //filter out the resource uri
1529 char *pUrl = strtok_r(cloneUri, "/", &pstr);
1533 LOGI("pAddress : %s", pUrl);
1534 int res = get_address_set(pUrl, address);
1537 LOGE("address parse error");
1544 LOGE("strtok_r error, could not get the address");
1550 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1552 if (NULL == pAddress || NULL == outAddress)
1554 LOGE("parameter is null");
1558 size_t len = strlen(pAddress);
1562 for (size_t i = 0; i < len; i++)
1564 if (pAddress[i] == '.')
1569 // found port number start index
1570 if (isIp && pAddress[i] == ':')
1579 if(ipLen && (ipLen < sizeof(outAddress->ipAddress)))
1581 strncpy(outAddress->ipAddress, pAddress, ipLen);
1582 outAddress->ipAddress[ipLen] = '\0';
1584 else if (!ipLen && (len < sizeof(outAddress->ipAddress)))
1586 strncpy(outAddress->ipAddress, pAddress, len);
1587 outAddress->ipAddress[len] = '\0';
1591 LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1597 outAddress->port = atoi(pAddress + ipLen + 1);
1602 strncpy(outAddress->ipAddress, pAddress, len);
1603 outAddress->ipAddress[len] = '\0';
1609 void delete_global_references(JNIEnv *env, jobject obj)
1611 LOGI("delete_global_references");
1614 LOGI("Invalid input parameter");
1618 (*env)->DeleteGlobalRef(env, g_responseListenerObject);
1622 bool read_file(const char* name, char** bytes, size_t* length)
1626 LOGE("parameter is null");
1635 file = fopen(name, "rt");
1638 fprintf(stderr, "Unable to open file %s", name);
1643 fseek(file, 0, SEEK_END);
1644 fileLen = ftell(file);
1645 fseek(file, 0, SEEK_SET);
1647 LOGI("file size: %d", fileLen);
1650 buffer = calloc(1, sizeof(char) * fileLen + 1);
1653 fprintf(stderr, "Memory error!");
1658 // Read file contents into buffer
1659 size_t ret = fread(buffer, fileLen, 1, file);
1662 printf("Failed to read data from file, %s\n", name);
1670 LOGI("file bytes: %s", buffer);
1678 void saveFile(const char *payload, size_t payloadSize)
1681 uint32_t day = gettodaydate();
1684 time_t current_time;
1685 struct tm * time_info;
1686 char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
1688 time(¤t_time);
1689 time_info = localtime(¤t_time);
1691 strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
1693 uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
1694 char* path = calloc(1, sizeof(char) * path_length);
1697 sprintf(path, RECEIVED_FILE_PATH, day, timeString);
1698 LOGI("received file path: %s", path);
1700 FILE *fp = fopen(path, "wt");
1701 fwrite(payload, 1, payloadSize, fp);
1704 callback("File Path: ", path);
1708 LOGE("path Out of memory");
1712 uint32_t gettodaydate()
1719 date = localtime(&clock);
1720 ldate = date->tm_year * 100000;
1721 ldate += (date->tm_mon + 1) * 1000;
1722 ldate += date->tm_mday * 10;
1723 ldate += date->tm_wday;