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, CATransportFlags_t *flags);
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 char COAP_TCP_PREFIX[] = "coap+tcp://";
65 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
66 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
67 static const uint16_t COAP_TCP_PREFIX_LEN = sizeof(COAP_TCP_PREFIX) - 1;
69 static const char RECEIVED_FILE_PATH[] = "/storage/emulated/0/Download/%d%s.txt";
71 static const char SECURE_INFO_DATA[]
72 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
73 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
75 static const char NORMAL_INFO_DATA[]
76 = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
77 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
79 static jobject g_responseListenerObject = NULL;
82 static CAEndpoint_t *g_clientEndpoint = NULL;
83 static char *g_resourceUri = NULL;
84 static CAToken_t g_clientToken = NULL;
85 static uint8_t g_clientTokenLength = 0;
87 static uint16_t g_clientMsgId = 0;
88 static char *g_remoteAddress = NULL;
91 JNIEXPORT void JNICALL
92 Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
95 LOGI("setNativeResponseListener");
96 if (!env || !obj || !listener)
98 LOGI("Invalid input parameter");
102 g_responseListenerObject = (*env)->NewGlobalRef(env, listener);
106 // Internal API. Invoked by OC stack to retrieve credentials from this module
107 int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
108 const unsigned char *desc, size_t desc_len,
109 unsigned char *result, size_t result_length)
111 LOGI("CAGetDtlsPskCredentials IN");
122 case CA_DTLS_PSK_HINT:
123 case CA_DTLS_PSK_IDENTITY:
125 if (result_length < sizeof(IDENTITY))
127 LOGE("ERROR : Wrong value for result for storing IDENTITY");
131 memcpy(result, IDENTITY, sizeof(IDENTITY));
132 ret = sizeof(IDENTITY);
135 case CA_DTLS_PSK_KEY:
137 if ((desc_len == sizeof(IDENTITY)) &&
138 memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
140 if (result_length < sizeof(RS_CLIENT_PSK))
142 LOGE("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
146 memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
147 ret = sizeof(RS_CLIENT_PSK);
153 LOGE("Wrong value passed for PSK_CRED_TYPE.");
157 LOGI("CAGetDtlsPskCredentials OUT\n");
163 JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
169 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
173 g_jvm = jvm; /* cache the JavaVM pointer */
175 CANativeJNISetJavaVM(g_jvm);
177 return JNI_VERSION_1_6;
180 void JNI_OnUnload(JavaVM *jvm, void *reserved)
182 LOGI("JNI_OnUnload");
186 if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
194 JNIEXPORT void JNICALL
195 Java_org_iotivity_ca_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
197 LOGI("RMInitialize");
198 if (!env || !obj || !context)
200 LOGI("Invalid input parameter");
204 //Currently set context for Android Platform
205 CANativeJNISetContext(env, context);
207 CAResult_t res = CAInitialize();
209 if (CA_STATUS_OK != res)
211 LOGE("Could not Initialize");
215 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
216 if(CA_STATUS_OK != res)
218 LOGE("Set credential handler fail");
224 JNIEXPORT void JNICALL
225 Java_org_iotivity_ca_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
230 LOGI("Invalid input parameter");
234 CADestroyToken(g_lastRequestToken);
236 delete_global_references(env, obj);
239 JNIEXPORT void JNICALL
240 Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
242 LOGI("RMStartListeningServer");
245 LOGI("Invalid input parameter");
249 if (CA_STATUS_OK != CAStartListeningServer())
251 LOGE("Could not start Listening server");
255 JNIEXPORT void JNICALL
256 Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
258 LOGI("RMStartDiscoveryServer");
261 LOGI("Invalid input parameter");
265 if (CA_STATUS_OK != CAStartDiscoveryServer())
267 LOGE("Could not start discovery server");
271 JNIEXPORT void JNICALL
272 Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
274 LOGI("RMRegisterHandler");
277 LOGI("Invalid input parameter");
281 CARegisterHandler(request_handler, response_handler, error_handler);
284 JNIEXPORT void JNICALL
285 Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
286 jstring payload, jint selectedNetwork,
287 jint isSecured, jint msgType,
290 LOGI("selectedNetwork - %d", selectedNetwork);
293 LOGI("Invalid input parameter");
299 LOGE("Invalid input parameter : uri");
303 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
304 CAResult_t res = get_network_type(selectedNetwork, &flags);
305 if (CA_STATUS_OK != res)
310 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
311 LOGI("RMSendRequest - %s", strUri);
313 addressSet_t address = {{0}, 0};
314 parsing_coap_uri(strUri, &address, &flags);
316 //create remote endpoint
317 CAEndpoint_t* endpoint = NULL;
318 res = CACreateEndpoint(flags, g_selectedNwType, (const char*)(address.ipAddress),
319 address.port, &endpoint);
320 if (CA_STATUS_OK != res)
322 LOGE("Could not create remote end point");
323 (*env)->ReleaseStringUTFChars(env, uri, strUri);
327 CAMessageType_t messageType = msgType;
330 CAToken_t token = NULL;
331 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
333 res = CAGenerateToken(&token, tokenLength);
334 if ((CA_STATUS_OK != res) || (!token))
336 LOGE("token generate error!!");
337 // destroy remote endpoint
338 CADestroyEndpoint(endpoint);
339 (*env)->ReleaseStringUTFChars(env, uri, strUri);
343 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
345 get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
346 (*env)->ReleaseStringUTFChars(env, uri, strUri);
348 CAInfo_t requestData = { 0 };
349 requestData.token = token;
350 requestData.tokenLength = tokenLength;
352 size_t payloadLength = 0;
355 const char* path = NULL;
358 path = (*env)->GetStringUTFChars(env, payload, NULL);
361 char* bigData = NULL;
362 bool result = read_file(path, &bigData, &payloadLength);
365 LOGE("read has failed");
366 (*env)->ReleaseStringUTFChars(env, payload, path);
367 CADestroyToken(token);
368 CADestroyEndpoint(endpoint);
371 (*env)->ReleaseStringUTFChars(env, payload, path);
373 requestData.payload = (CAPayload_t) malloc(payloadLength);
374 if (NULL == requestData.payload)
376 LOGE("Memory allocation failed!");
378 CADestroyToken(token);
379 // destroy remote endpoint
380 CADestroyEndpoint(endpoint);
383 memcpy(requestData.payload, bigData, payloadLength);
384 requestData.payloadSize = payloadLength;
392 payloadLength = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
393 requestData.payload = (CAPayload_t) malloc(payloadLength);
394 if (NULL == requestData.payload)
396 LOGE("Memory allocation failed!");
398 CADestroyToken(token);
399 // destroy remote endpoint
400 CADestroyEndpoint(endpoint);
403 snprintf((char *) requestData.payload, payloadLength, SECURE_INFO_DATA,
404 resourceURI, g_localSecurePort);
405 requestData.payloadSize = payloadLength;
409 payloadLength = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
410 requestData.payload = (CAPayload_t) malloc(payloadLength);
411 if (NULL == requestData.payload)
413 LOGE("Memory allocation failed!");
415 CADestroyToken(token);
416 // destroy remote endpoint
417 CADestroyEndpoint(endpoint);
420 snprintf((char *) requestData.payload, payloadLength, NORMAL_INFO_DATA, resourceURI);
421 requestData.payloadSize = payloadLength;
425 requestData.type = messageType;
426 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
427 if (NULL == requestData.resourceUri)
429 LOGE("Memory allocation failed!");
431 CADestroyToken(token);
432 // destroy remote endpoint
433 CADestroyEndpoint(endpoint);
434 free(requestData.payload);
437 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
439 CARequestInfo_t requestInfo = { 0 };
440 requestInfo.method = CA_GET;
441 requestInfo.isMulticast = false;
442 requestInfo.info = requestData;
445 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
447 LOGE("Could not send request");
451 CADestroyToken(token);
453 // destroy remote endpoint
454 CADestroyEndpoint(endpoint);
456 free(requestData.payload);
457 free(requestData.resourceUri);
460 JNIEXPORT void JNICALL
461 Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
462 jint selectedNetwork)
464 LOGI("selectedNetwork - %d", selectedNetwork);
467 LOGI("Invalid input parameter");
471 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
472 CAResult_t res = get_network_type(selectedNetwork, &flags);
473 if (CA_STATUS_OK != res)
478 // create remote endpoint
479 CAEndpoint_t *endpoint = NULL;
480 res = CACreateEndpoint(flags, g_selectedNwType, NULL, 0, &endpoint);
482 if (CA_STATUS_OK != res)
484 LOGE("create remote endpoint error, error code: %d", res);
489 CAToken_t token = NULL;
490 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
492 res = CAGenerateToken(&token, tokenLength);
493 if ((CA_STATUS_OK != res) || (!token))
495 LOGE("token generate error!!");
496 // destroy remote endpoint
497 CADestroyEndpoint(endpoint);
501 LOGI("generated token %s", token);
503 CAInfo_t requestData = { 0 };
504 requestData.token = token;
505 requestData.tokenLength = tokenLength;
506 requestData.payload = (CAPayload_t) "TempJsonPayload";
507 requestData.payloadSize = strlen((const char *) requestData.payload);
508 requestData.type = CA_MSG_NONCONFIRM;
510 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
511 LOGI("resourceUri - %s", strUri);
512 requestData.resourceUri = (CAURI_t)strUri;
514 uint8_t optionNum = 2;
515 CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
516 sizeof(CAHeaderOption_t) * optionNum);
517 if (NULL == headerOpt)
519 LOGE("Memory allocation failed");
520 // destroy remote endpoint
521 CADestroyEndpoint(endpoint);
525 char* FirstOptionData = "Hello";
526 headerOpt[0].optionID = 3000;
527 memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
528 headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
530 char* SecondOptionData2 = "World";
531 headerOpt[1].optionID = 3001;
532 memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
533 headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
535 requestData.numOptions = optionNum;
536 requestData.options = headerOpt;
538 CARequestInfo_t requestInfo = { 0 };
539 requestInfo.method = CA_GET;
540 requestInfo.isMulticast = true;
541 requestInfo.info = requestData;
543 // send request to all
544 res = CASendRequest(endpoint, &requestInfo);
545 if (CA_STATUS_OK != res)
547 LOGE("Could not send request to all");
549 CADestroyToken(token);
553 CADestroyToken(g_lastRequestToken);
554 g_lastRequestToken = token;
555 g_lastRequestTokenLength = tokenLength;
558 //ReleaseStringUTFChars for strUri
559 (*env)->ReleaseStringUTFChars(env, uri, strUri);
563 // destroy remote endpoint
564 CADestroyEndpoint(endpoint);
567 JNIEXPORT void JNICALL
568 Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
569 jint selectedNetwork,
570 jint isSecured, jint msgType,
573 LOGI("RMSendResponse");
576 LOGI("Invalid input parameter");
580 LOGI("selectedNetwork - %d", selectedNetwork);
582 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
583 CAResult_t res = get_network_type(selectedNetwork, &flags);
584 if (CA_STATUS_OK != res)
586 LOGE("Not supported network type");
590 if (NULL == g_clientEndpoint)
592 LOGE("No Request received");
596 CAMessageType_t messageType = msgType;
598 CAInfo_t responseData = { 0 };
599 responseData.type = messageType;
600 responseData.messageId = g_clientMsgId;
601 responseData.resourceUri = (CAURI_t)g_resourceUri;
603 CAResponseInfo_t responseInfo = { 0 };
605 if (CA_MSG_RESET == msgType ||
606 (CA_MSG_ACKNOWLEDGE == msgType && CA_EMPTY == responseValue))
608 printf("RESET or ACK/EMPTY. there will be not payload/option\n");
609 responseInfo.result = CA_EMPTY;
613 responseData.token = g_clientToken;
614 responseData.tokenLength = g_clientTokenLength;
615 responseInfo.result = responseValue;
619 uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
620 responseData.payload = (CAPayload_t) malloc(length);
621 sprintf((char *) responseData.payload, SECURE_INFO_DATA, g_resourceUri,
623 responseData.payloadSize = length;
627 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
628 responseData.payload = (CAPayload_t) malloc(length);
629 sprintf((char *) responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
630 responseData.payloadSize = length;
634 responseInfo.info = responseData;
637 res = CASendResponse(g_clientEndpoint, &responseInfo);
638 if (CA_STATUS_OK != res)
640 LOGE("Could not send response");
644 CADestroyToken(g_clientToken);
645 g_clientToken = NULL;
646 g_clientTokenLength = 0;
648 // destroy remote endpoint
649 CADestroyEndpoint(g_clientEndpoint);
650 g_clientEndpoint = NULL;
653 JNIEXPORT void JNICALL
654 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
655 jstring payload, jint selectedNetwork,
656 jint isSecured, jint msgType)
658 LOGI("selectedNetwork - %d", selectedNetwork);
661 LOGI("Invalid input parameter");
667 LOGE("payload is NULL");
672 LOGE("Invalid input parameter : uri");
676 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
677 CAResult_t res = get_network_type(selectedNetwork, &flags);
678 if (CA_STATUS_OK != res)
680 LOGE("Not supported network type");
684 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
685 LOGI("RMSendNotification - %s", strUri);
687 addressSet_t address = {{0}, 0};
688 parsing_coap_uri(strUri, &address, &flags);
690 //create remote endpoint
691 CAEndpoint_t* endpoint = NULL;
692 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
693 (const char*)address.ipAddress,
694 address.port, &endpoint))
696 //ReleaseStringUTFChars for strUri
697 (*env)->ReleaseStringUTFChars(env, uri, strUri);
698 LOGE("Could not create remote end point");
702 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
703 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
705 //ReleaseStringUTFChars for strUri
706 (*env)->ReleaseStringUTFChars(env, uri, strUri);
708 CAMessageType_t messageType = msgType;
711 CAToken_t token = NULL;
712 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
714 res = CAGenerateToken(&token, tokenLength);
715 if ((CA_STATUS_OK != res) || (!token))
717 LOGE("token generate error!");
718 CADestroyEndpoint(endpoint);
722 CAInfo_t requestData = { 0 };
723 requestData.token = token;
724 requestData.tokenLength = tokenLength;
725 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
726 if (NULL == requestData.resourceUri)
728 LOGE("Memory allocation failed!");
730 CADestroyToken(token);
731 // destroy remote endpoint
732 CADestroyEndpoint(endpoint);
735 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
739 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
740 requestData.payload = (CAPayload_t) malloc(length);
741 if (NULL == requestData.payload)
743 LOGE("Memory allocation failed!");
745 CADestroyToken(token);
746 // destroy remote endpoint
747 CADestroyEndpoint(endpoint);
749 free(requestData.resourceUri);
752 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
753 requestData.payloadSize = length;
757 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
758 requestData.payload = (CAPayload_t) malloc(length);
759 if (NULL == requestData.payload)
761 LOGE("Memory allocation failed!");
763 CADestroyToken(token);
764 // destroy remote endpoint
765 CADestroyEndpoint(endpoint);
767 free(requestData.resourceUri);
770 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
771 requestData.payloadSize = length;
774 requestData.type = messageType;
776 CARequestInfo_t requestInfo = { 0 };
777 requestInfo.method = CA_GET;
778 requestInfo.info = requestData;
781 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
783 LOGE("Could not send notification");
786 LOGI("Send Notification");
789 CADestroyToken(token);
791 // destroy remote endpoint
792 CADestroyEndpoint(endpoint);
794 free(requestData.payload);
795 free(requestData.resourceUri);
798 JNIEXPORT void JNICALL
799 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
802 LOGI("RMSelectNetwork Type : %d", networkType);
805 LOGI("Invalid input parameter");
809 if (CA_STATUS_OK != CASelectNetwork(networkType))
811 LOGE("Could not select network");
815 JNIEXPORT void JNICALL
816 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
819 LOGI("RMUnSelectNetwork Type : %d", networkType);
822 LOGI("Invalid input parameter");
826 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
828 LOGE("Could not unselect network");
832 JNIEXPORT void JNICALL
833 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
835 LOGI("RMGetNetworkInfomation");
838 LOGI("Invalid input parameter");
842 CAEndpoint_t *tempInfo = NULL;
843 uint32_t tempSize = 0;
845 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
846 if (CA_STATUS_OK != res)
848 LOGE("Could not start get network information");
853 LOGI("################## Network Information #######################");
854 callback("######## Network Information", "#######");
855 LOGI("Network info total size is %d", tempSize);
858 for (index = 0; index < tempSize; index++)
860 res = get_remote_address(tempInfo[index].addr);
861 if (CA_STATUS_OK != res)
866 if (NULL != g_responseListenerObject)
868 char networkInfo[NETWORK_INFO_LENGTH];
869 LOGI("Type: %d", tempInfo[index].adapter);
870 sprintf(networkInfo, "%d",tempInfo[index].adapter);
871 callback("Type :", networkInfo);
872 if (CA_ADAPTER_IP == tempInfo[index].adapter)
874 LOGI("Port: %d", tempInfo[index].port);
875 sprintf(networkInfo, "%d",tempInfo[index].port);
876 callback("Port: ", networkInfo);
878 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
879 LOGI("Address: %s", g_remoteAddress);
880 callback("Address: ", g_remoteAddress);
881 free(g_remoteAddress);
883 if (tempInfo[index].flags & CA_SECURE)
885 g_localSecurePort = tempInfo[index].port;
892 LOGI("##############################################################");
895 JNIEXPORT void JNICALL
896 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
898 LOGI("RMHandleRequestResponse");
901 LOGI("Invalid input parameter");
905 if (CA_STATUS_OK != CAHandleRequestResponse())
907 LOGE("Could not handle request and response");
911 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
916 LOGE("Remote endpoint is NULL!");
922 LOGE("Request info is NULL!");
926 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
927 (strncmp(g_lastRequestToken, requestInfo->info.token,
928 requestInfo->info.tokenLength) == 0))
930 LOGI("token is same. received request of it's own. skip.. ");
934 CAResult_t res = get_remote_address(object->addr);
935 if (CA_STATUS_OK != res)
940 LOGI("##########received request from remote device #############");
941 LOGI("Remote Address: %s", g_remoteAddress);
942 LOGI("Remote Port: %d", object->port);
943 LOGI("Uri: %s", requestInfo->info.resourceUri);
944 LOGI("Data: %s", requestInfo->info.payload);
945 LOGI("Token: %s", requestInfo->info.token);
946 LOGI("Code: %d", requestInfo->method);
947 LOGI("MessageType: %d", requestInfo->info.type);
949 if (NULL != g_responseListenerObject)
951 char *cloneUri = NULL;
954 if (NULL != requestInfo->info.resourceUri)
956 len = strlen(requestInfo->info.resourceUri);
957 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
959 if (NULL == cloneUri)
961 LOGE("cloneUri Out of memory");
962 free(g_remoteAddress);
966 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
967 callback("Uri: ", cloneUri);
970 len = strlen(g_remoteAddress);
971 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
973 if (NULL == cloneRemoteAddress)
975 LOGE("cloneRemoteAddress Out of memory");
976 free(g_remoteAddress);
981 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
983 callback("Remote Address: ", cloneRemoteAddress);
984 free(cloneRemoteAddress);
985 free(g_remoteAddress);
987 char portInfo[PORT_LENGTH] = { 0, };
988 sprintf(portInfo, "%d", object->port);
989 callback("Remote Port: ", portInfo);
991 //clone g_clientEndpoint
992 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
993 if (NULL == g_clientEndpoint)
995 LOGE("g_clientEndpoint Out of memory");
999 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
1001 if (NULL != cloneUri)
1003 len = strlen(cloneUri);
1004 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
1005 if (NULL == g_resourceUri)
1007 LOGE("g_clientEndpoint->resourceUri Out of memory");
1008 free(g_clientEndpoint);
1012 memcpy(g_resourceUri, cloneUri, len + 1);
1015 //clone g_clientToken
1016 len = requestInfo->info.tokenLength;
1018 g_clientToken = (char *) malloc(sizeof(char) * len);
1019 if (NULL == g_clientToken)
1021 LOGE("g_clientToken Out of memory");
1022 free(g_clientEndpoint);
1026 if (NULL != requestInfo->info.token)
1028 memcpy(g_clientToken, requestInfo->info.token, len);
1029 g_clientTokenLength = len;
1033 //clone g_clientMsgId
1034 g_clientMsgId = requestInfo->info.messageId;
1036 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1038 len = requestInfo->info.payloadSize;
1039 char *clonePayload = (char *) malloc(len + 1);
1040 if (NULL == clonePayload)
1042 LOGE("clonePayload Out of memory");
1043 free(g_clientEndpoint);
1047 memcpy(clonePayload, requestInfo->info.payload, len);
1048 clonePayload[len] = '\0';
1050 if (len > BIG_PAYLOAD_LENGTH)
1052 saveFile(clonePayload, len);
1056 callback("Data: ", clonePayload);
1062 if (requestInfo->info.options)
1064 uint32_t len = requestInfo->info.numOptions;
1067 LOGI("Option count: %d", requestInfo->info.numOptions);
1069 for (i = 0; i < len; i++)
1071 LOGI("Option %d", i + 1);
1072 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1073 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1074 requestInfo->info.options[i].optionData);
1076 if (NULL != g_responseListenerObject)
1078 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1079 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1080 requestInfo->info.options[i].optionID,
1081 requestInfo->info.options[i].optionLength);
1083 callback("Option info: ", optionInfo);
1085 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1086 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1087 if (NULL == cloneOptionData)
1089 LOGE("cloneOptionData Out of memory");
1090 free(g_clientEndpoint);
1094 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1097 callback("Option Data: ", cloneOptionData);
1098 free(cloneOptionData);
1102 LOGI("############################################################");
1104 //Check if this has secure communication information
1105 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1107 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1108 if (0 < securePort) //Set the remote endpoint secure details and send response
1110 LOGI("This is secure resource...");
1112 CAEndpoint_t *endpoint = NULL;
1113 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1114 object->adapter, object->addr, securePort, &endpoint))
1116 LOGE("Failed to create duplicate of remote endpoint!");
1124 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1126 if (!object || !responseInfo)
1128 LOGE("Invalid input parameter");
1132 CAResult_t res = get_remote_address(object->addr);
1133 if (CA_STATUS_OK != res)
1138 LOGI("##########Received response from remote device #############");
1139 LOGI("Uri: %s", responseInfo->info.resourceUri);
1140 LOGI("Remote Address: %s", g_remoteAddress);
1141 LOGI("Remote Port: %d", object->port);
1142 LOGI("response result: %d", responseInfo->result);
1143 LOGI("Data: %s", responseInfo->info.payload);
1144 LOGI("Token: %s", responseInfo->info.token);
1145 LOGI("MessageType: %d", responseInfo->info.type);
1147 if (NULL != g_responseListenerObject)
1151 if (NULL != responseInfo->info.resourceUri)
1153 len = strlen(responseInfo->info.resourceUri);
1154 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1156 if (NULL == cloneUri)
1158 LOGE("cloneUri Out of memory");
1159 free(g_remoteAddress);
1163 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1165 callback("Uri: ", cloneUri);
1169 len = strlen(g_remoteAddress);
1170 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1172 if (NULL == cloneRemoteAddress)
1174 LOGE("cloneRemoteAddress Out of memory");
1175 free(g_remoteAddress);
1179 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1181 callback("Remote Address: ", cloneRemoteAddress);
1182 free(cloneRemoteAddress);
1183 free(g_remoteAddress);
1185 char portInfo[PORT_LENGTH] = { 0, };
1186 sprintf(portInfo, "%d", object->port);
1187 callback("Remote Port: ", portInfo);
1189 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1191 len = responseInfo->info.payloadSize;
1192 char *clonePayload = (char *) malloc(len + 1);
1193 if (NULL == clonePayload)
1195 LOGE("clonePayload Out of memory");
1199 memcpy(clonePayload, responseInfo->info.payload, len);
1200 clonePayload[len] = '\0';
1202 if (len > BIG_PAYLOAD_LENGTH)
1204 saveFile(clonePayload, len);
1208 callback("Data: ", clonePayload);
1214 if (responseInfo->info.options)
1216 uint32_t len = responseInfo->info.numOptions;
1218 for (i = 0; i < len; i++)
1220 LOGI("Option %d", i + 1);
1221 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1222 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1223 responseInfo->info.options[i].optionData);
1225 if (NULL != g_responseListenerObject)
1227 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1228 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1229 responseInfo->info.options[i].optionID,
1230 responseInfo->info.options[i].optionLength);
1232 callback("Option info: ", optionInfo);
1234 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1235 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1236 if (NULL == cloneOptionData)
1238 LOGE("cloneOptionData Out of memory");
1241 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1243 callback("Option Data: ", cloneOptionData);
1244 free(cloneOptionData);
1248 LOGI("############################################################");
1250 //Check if this has secure communication information
1251 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1253 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1254 if (0 < securePort) //Set the remote endpoint secure details and send response
1256 LOGI("This is secure resource...");
1261 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1263 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1267 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1268 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1273 const CAInfo_t *info = &errorInfo->info;
1274 LOGI("Error Handler, ErrorInfo :");
1275 LOGI("Error Handler result : %d", errorInfo->result);
1276 LOGI("Error Handler token : %s", info->token);
1277 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1278 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1279 LOGI("Error Handler type : %d", info->type);
1280 LOGI("Error Handler payload : %s", info->payload);
1282 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1284 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1286 else if(CA_SEND_FAILED == errorInfo->result)
1288 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1290 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1292 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1294 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1296 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1298 else if(CA_STATUS_FAILED == errorInfo->result)
1300 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1303 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1308 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1310 const char *startPos = URI;
1311 const char *temp = strstr(URI, "://");
1314 startPos = strchr(temp + 3, '/');
1317 LOGE("Resource URI is missing");
1322 const char *endPos = strchr(startPos, '?');
1325 endPos = URI + strlen(URI);
1329 if (endPos - startPos <= length)
1331 memcpy(resourceURI, startPos + 1, endPos - startPos);
1334 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1337 uint32_t get_secure_information(CAPayload_t payLoad)
1339 LOGI("entering get_secure_information");
1343 LOGE("Payload is NULL");
1347 const char *subString = NULL;
1348 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1350 LOGE("This is not secure resource");
1354 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1356 LOGE("This secure resource does not have port information");
1360 const char *startPos = strstr(subString, ":");
1363 LOGE("Parsing failed !");
1367 const char *endPos = strstr(startPos, "}");
1370 LOGE("Parsing failed !");
1374 char portStr[6] = { 0 };
1375 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1377 LOGI("secured port is: %s", portStr);
1378 return atoi(portStr);
1381 CAResult_t get_network_type(uint32_t selectedNetwork, CATransportFlags_t *flags)
1383 uint32_t number = selectedNetwork;
1389 case CA_ADAPTER_GATT_BTLE:
1390 case CA_ADAPTER_RFCOMM_BTEDR:
1391 case CA_ADAPTER_TCP:
1392 g_selectedNwType = number;
1393 return CA_STATUS_OK;
1395 return CA_NOT_SUPPORTED;
1399 void callback(char *subject, char *receivedData)
1401 bool isAttached = false;
1404 if (!g_responseListenerObject)
1406 LOGE("g_responseListenerObject is NULL, cannot have callback");
1410 jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1413 LOGI("Could not get JNIEnv pointer");
1414 res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1418 LOGE("AttachCurrentThread has failed");
1424 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1427 LOGE("could not get class");
1431 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1432 "(Ljava/lang/String;Ljava/lang/String;)V");
1435 LOGE("could not get Method ID");
1439 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1442 LOGE("NewStringUTF failed");
1446 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1449 LOGE("NewStringUTF failed");
1453 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1458 (*g_jvm)->DetachCurrentThread(g_jvm);
1459 LOGI("DetachCurrentThread");
1463 CAResult_t get_remote_address(const char *address)
1465 uint32_t len = strlen(address);
1467 g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1468 if (NULL == g_remoteAddress)
1470 LOGE("g_remoteAddress Out of memory");
1471 return CA_MEMORY_ALLOC_FAILED;
1474 memcpy(g_remoteAddress, address, len + 1);
1476 return CA_STATUS_OK;
1480 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1482 if (NULL == uri || NULL == address)
1484 LOGE("parameter is null");
1490 uint8_t startIndex = 0;
1491 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1493 LOGI("uri has '%s' prefix", COAPS_PREFIX);
1494 startIndex = COAPS_PREFIX_LEN;
1497 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1499 LOGI("uri has '%s' prefix", COAP_PREFIX);
1500 startIndex = COAP_PREFIX_LEN;
1502 else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1504 LOGI("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1505 startIndex = COAP_TCP_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;