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)
652 LOGI("selectedNetwork - %d", selectedNetwork);
655 LOGI("Invalid input parameter");
661 LOGE("payload is NULL");
666 LOGE("Invalid input parameter : uri");
670 CAResult_t res = get_network_type(selectedNetwork);
671 if (CA_STATUS_OK != res)
673 LOGE("Not supported network type");
677 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
678 LOGI("RMSendNotification - %s", strUri);
680 CATransportFlags_t flags;
681 addressSet_t address = {{0}, 0};
682 parsing_coap_uri(strUri, &address, &flags);
684 //create remote endpoint
685 CAEndpoint_t* endpoint = NULL;
686 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
687 (const char*)address.ipAddress,
688 address.port, &endpoint))
690 //ReleaseStringUTFChars for strUri
691 (*env)->ReleaseStringUTFChars(env, uri, strUri);
692 LOGE("Could not create remote end point");
696 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
697 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
699 //ReleaseStringUTFChars for strUri
700 (*env)->ReleaseStringUTFChars(env, uri, strUri);
702 CAMessageType_t messageType = msgType;
705 CAToken_t token = NULL;
706 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
708 res = CAGenerateToken(&token, tokenLength);
709 if ((CA_STATUS_OK != res) || (!token))
711 LOGE("token generate error!");
712 CADestroyEndpoint(endpoint);
716 CAInfo_t requestData = { 0 };
717 requestData.token = token;
718 requestData.tokenLength = tokenLength;
719 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
720 if (NULL == requestData.resourceUri)
722 LOGE("Memory allocation failed!");
724 CADestroyToken(token);
725 // destroy remote endpoint
726 CADestroyEndpoint(endpoint);
729 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
733 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
734 requestData.payload = (CAPayload_t) malloc(length);
735 if (NULL == requestData.payload)
737 LOGE("Memory allocation failed!");
739 CADestroyToken(token);
740 // destroy remote endpoint
741 CADestroyEndpoint(endpoint);
743 free(requestData.resourceUri);
746 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
747 requestData.payloadSize = length;
751 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
752 requestData.payload = (CAPayload_t) malloc(length);
753 if (NULL == requestData.payload)
755 LOGE("Memory allocation failed!");
757 CADestroyToken(token);
758 // destroy remote endpoint
759 CADestroyEndpoint(endpoint);
761 free(requestData.resourceUri);
764 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
765 requestData.payloadSize = length;
768 requestData.type = messageType;
770 CARequestInfo_t requestInfo = { 0 };
771 requestInfo.method = CA_GET;
772 requestInfo.info = requestData;
775 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
777 LOGE("Could not send notification");
780 LOGI("Send Notification");
783 CADestroyToken(token);
785 // destroy remote endpoint
786 CADestroyEndpoint(endpoint);
788 free(requestData.payload);
789 free(requestData.resourceUri);
792 JNIEXPORT void JNICALL
793 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
796 LOGI("RMSelectNetwork Type : %d", networkType);
799 LOGI("Invalid input parameter");
803 if (CA_STATUS_OK != CASelectNetwork(networkType))
805 LOGE("Could not select network");
809 JNIEXPORT void JNICALL
810 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
813 LOGI("RMUnSelectNetwork Type : %d", networkType);
816 LOGI("Invalid input parameter");
820 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
822 LOGE("Could not unselect network");
826 JNIEXPORT void JNICALL
827 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
829 LOGI("RMGetNetworkInfomation");
832 LOGI("Invalid input parameter");
836 CAEndpoint_t *tempInfo = NULL;
837 uint32_t tempSize = 0;
839 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
840 if (CA_STATUS_OK != res)
842 LOGE("Could not start get network information");
847 LOGI("################## Network Information #######################");
848 callback("######## Network Information", "#######");
849 LOGI("Network info total size is %d", tempSize);
852 for (index = 0; index < tempSize; index++)
854 res = get_remote_address(tempInfo[index].addr);
855 if (CA_STATUS_OK != res)
860 if (NULL != g_responseListenerObject)
862 char networkInfo[NETWORK_INFO_LENGTH];
863 LOGI("Type: %d", tempInfo[index].adapter);
864 sprintf(networkInfo, "%d",tempInfo[index].adapter);
865 callback("Type :", networkInfo);
866 if (CA_ADAPTER_IP == tempInfo[index].adapter)
868 LOGI("Port: %d", tempInfo[index].port);
869 sprintf(networkInfo, "%d",tempInfo[index].port);
870 callback("Port: ", networkInfo);
872 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
873 LOGI("Address: %s", g_remoteAddress);
874 callback("Address: ", g_remoteAddress);
875 free(g_remoteAddress);
877 if (tempInfo[index].flags & CA_SECURE)
879 g_localSecurePort = tempInfo[index].port;
886 LOGI("##############################################################");
889 JNIEXPORT void JNICALL
890 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
892 LOGI("RMHandleRequestResponse");
895 LOGI("Invalid input parameter");
899 if (CA_STATUS_OK != CAHandleRequestResponse())
901 LOGE("Could not handle request and response");
905 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
910 LOGE("Remote endpoint is NULL!");
916 LOGE("Request info is NULL!");
920 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
921 (strncmp(g_lastRequestToken, requestInfo->info.token,
922 requestInfo->info.tokenLength) == 0))
924 LOGI("token is same. received request of it's own. skip.. ");
928 CAResult_t res = get_remote_address(object->addr);
929 if (CA_STATUS_OK != res)
934 LOGI("##########received request from remote device #############");
935 LOGI("Remote Address: %s", g_remoteAddress);
936 LOGI("Remote Port: %d", object->port);
937 LOGI("Uri: %s", requestInfo->info.resourceUri);
938 LOGI("Data: %s", requestInfo->info.payload);
939 LOGI("Token: %s", requestInfo->info.token);
940 LOGI("Code: %d", requestInfo->method);
941 LOGI("MessageType: %d", requestInfo->info.type);
943 if (NULL != g_responseListenerObject)
945 char *cloneUri = NULL;
948 if (NULL != requestInfo->info.resourceUri)
950 len = strlen(requestInfo->info.resourceUri);
951 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
953 if (NULL == cloneUri)
955 LOGE("cloneUri Out of memory");
956 free(g_remoteAddress);
960 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
961 callback("Uri: ", cloneUri);
964 len = strlen(g_remoteAddress);
965 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
967 if (NULL == cloneRemoteAddress)
969 LOGE("cloneRemoteAddress Out of memory");
970 free(g_remoteAddress);
975 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
977 callback("Remote Address: ", cloneRemoteAddress);
978 free(cloneRemoteAddress);
979 free(g_remoteAddress);
981 char portInfo[PORT_LENGTH] = { 0, };
982 sprintf(portInfo, "%d", object->port);
983 callback("Remote Port: ", portInfo);
985 //clone g_clientEndpoint
986 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
987 if (NULL == g_clientEndpoint)
989 LOGE("g_clientEndpoint Out of memory");
993 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
995 if (NULL != cloneUri)
997 len = strlen(cloneUri);
998 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
999 if (NULL == g_resourceUri)
1001 LOGE("g_clientEndpoint->resourceUri Out of memory");
1002 free(g_clientEndpoint);
1006 memcpy(g_resourceUri, cloneUri, len + 1);
1009 //clone g_clientToken
1010 len = requestInfo->info.tokenLength;
1012 g_clientToken = (char *) malloc(sizeof(char) * len);
1013 if (NULL == g_clientToken)
1015 LOGE("g_clientToken Out of memory");
1016 free(g_clientEndpoint);
1020 if (NULL != requestInfo->info.token)
1022 memcpy(g_clientToken, requestInfo->info.token, len);
1023 g_clientTokenLength = len;
1027 //clone g_clientMsgId
1028 g_clientMsgId = requestInfo->info.messageId;
1030 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1032 len = requestInfo->info.payloadSize;
1033 char *clonePayload = (char *) malloc(len + 1);
1034 if (NULL == clonePayload)
1036 LOGE("clonePayload Out of memory");
1037 free(g_clientEndpoint);
1041 memcpy(clonePayload, requestInfo->info.payload, len);
1042 clonePayload[len] = '\0';
1044 if (len > BIG_PAYLOAD_LENGTH)
1046 saveFile(clonePayload, len);
1050 callback("Data: ", clonePayload);
1056 if (requestInfo->info.options)
1058 uint32_t len = requestInfo->info.numOptions;
1061 LOGI("Option count: %d", requestInfo->info.numOptions);
1063 for (i = 0; i < len; i++)
1065 LOGI("Option %d", i + 1);
1066 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1067 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1068 requestInfo->info.options[i].optionData);
1070 if (NULL != g_responseListenerObject)
1072 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1073 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1074 requestInfo->info.options[i].optionID,
1075 requestInfo->info.options[i].optionLength);
1077 callback("Option info: ", optionInfo);
1079 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1080 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1081 if (NULL == cloneOptionData)
1083 LOGE("cloneOptionData Out of memory");
1084 free(g_clientEndpoint);
1088 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1091 callback("Option Data: ", cloneOptionData);
1092 free(cloneOptionData);
1096 LOGI("############################################################");
1098 //Check if this has secure communication information
1099 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1101 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1102 if (0 < securePort) //Set the remote endpoint secure details and send response
1104 LOGI("This is secure resource...");
1106 CAEndpoint_t *endpoint = NULL;
1107 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1108 object->adapter, object->addr, securePort, &endpoint))
1110 LOGE("Failed to create duplicate of remote endpoint!");
1118 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1120 if (!object || !responseInfo)
1122 LOGE("Invalid input parameter");
1126 CAResult_t res = get_remote_address(object->addr);
1127 if (CA_STATUS_OK != res)
1132 LOGI("##########Received response from remote device #############");
1133 LOGI("Uri: %s", responseInfo->info.resourceUri);
1134 LOGI("Remote Address: %s", g_remoteAddress);
1135 LOGI("Remote Port: %d", object->port);
1136 LOGI("response result: %d", responseInfo->result);
1137 LOGI("Data: %s", responseInfo->info.payload);
1138 LOGI("Token: %s", responseInfo->info.token);
1139 LOGI("MessageType: %d", responseInfo->info.type);
1141 if (NULL != g_responseListenerObject)
1145 if (NULL != responseInfo->info.resourceUri)
1147 len = strlen(responseInfo->info.resourceUri);
1148 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1150 if (NULL == cloneUri)
1152 LOGE("cloneUri Out of memory");
1153 free(g_remoteAddress);
1157 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1159 callback("Uri: ", cloneUri);
1163 len = strlen(g_remoteAddress);
1164 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1166 if (NULL == cloneRemoteAddress)
1168 LOGE("cloneRemoteAddress Out of memory");
1169 free(g_remoteAddress);
1173 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1175 callback("Remote Address: ", cloneRemoteAddress);
1176 free(cloneRemoteAddress);
1177 free(g_remoteAddress);
1179 char portInfo[PORT_LENGTH] = { 0, };
1180 sprintf(portInfo, "%d", object->port);
1181 callback("Remote Port: ", portInfo);
1183 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1185 len = responseInfo->info.payloadSize;
1186 char *clonePayload = (char *) malloc(len + 1);
1187 if (NULL == clonePayload)
1189 LOGE("clonePayload Out of memory");
1193 memcpy(clonePayload, responseInfo->info.payload, len);
1194 clonePayload[len] = '\0';
1196 if (len > BIG_PAYLOAD_LENGTH)
1198 saveFile(clonePayload, len);
1202 callback("Data: ", clonePayload);
1208 if (responseInfo->info.options)
1210 uint32_t len = responseInfo->info.numOptions;
1212 for (i = 0; i < len; i++)
1214 LOGI("Option %d", i + 1);
1215 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1216 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1217 responseInfo->info.options[i].optionData);
1219 if (NULL != g_responseListenerObject)
1221 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1222 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1223 responseInfo->info.options[i].optionID,
1224 responseInfo->info.options[i].optionLength);
1226 callback("Option info: ", optionInfo);
1228 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1229 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1230 if (NULL == cloneOptionData)
1232 LOGE("cloneOptionData Out of memory");
1235 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1237 callback("Option Data: ", cloneOptionData);
1238 free(cloneOptionData);
1242 LOGI("############################################################");
1244 //Check if this has secure communication information
1245 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1247 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1248 if (0 < securePort) //Set the remote endpoint secure details and send response
1250 LOGI("This is secure resource...");
1255 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1257 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1261 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1262 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1267 const CAInfo_t *info = &errorInfo->info;
1268 LOGI("Error Handler, ErrorInfo :");
1269 LOGI("Error Handler result : %d", errorInfo->result);
1270 LOGI("Error Handler token : %s", info->token);
1271 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1272 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1273 LOGI("Error Handler type : %d", info->type);
1274 LOGI("Error Handler payload : %s", info->payload);
1276 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1278 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1280 else if(CA_SEND_FAILED == errorInfo->result)
1282 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1284 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1286 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1288 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1290 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1292 else if(CA_STATUS_FAILED == errorInfo->result)
1294 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1297 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1302 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1304 const char *startPos = URI;
1305 const char *temp = strstr(URI, "://");
1308 startPos = strchr(temp + 3, '/');
1311 LOGE("Resource URI is missing");
1316 const char *endPos = strchr(startPos, '?');
1319 endPos = URI + strlen(URI);
1323 if (endPos - startPos <= length)
1325 memcpy(resourceURI, startPos + 1, endPos - startPos);
1328 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1331 uint32_t get_secure_information(CAPayload_t payLoad)
1333 LOGI("entering get_secure_information");
1337 LOGE("Payload is NULL");
1341 const char *subString = NULL;
1342 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1344 LOGE("This is not secure resource");
1348 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1350 LOGE("This secure resource does not have port information");
1354 const char *startPos = strstr(subString, ":");
1357 LOGE("Parsing failed !");
1361 const char *endPos = strstr(startPos, "}");
1364 LOGE("Parsing failed !");
1368 char portStr[6] = { 0 };
1369 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1371 LOGI("secured port is: %s", portStr);
1372 return atoi(portStr);
1375 CAResult_t get_network_type(uint32_t selectedNetwork)
1378 uint32_t number = selectedNetwork;
1380 if (!(number & 0xf))
1382 return CA_NOT_SUPPORTED;
1384 if (number & CA_ADAPTER_IP)
1386 g_selectedNwType = CA_ADAPTER_IP;
1387 return CA_STATUS_OK;
1389 if (number & CA_ADAPTER_RFCOMM_BTEDR)
1391 g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1392 return CA_STATUS_OK;
1394 if (number & CA_ADAPTER_GATT_BTLE)
1396 g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1397 return CA_STATUS_OK;
1400 return CA_NOT_SUPPORTED;
1403 void callback(char *subject, char *receivedData)
1405 bool isAttached = false;
1408 if (!g_responseListenerObject)
1410 LOGE("g_responseListenerObject is NULL, cannot have callback");
1414 jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1417 LOGI("Could not get JNIEnv pointer");
1418 res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1422 LOGE("AttachCurrentThread has failed");
1428 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1431 LOGE("could not get class");
1435 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1436 "(Ljava/lang/String;Ljava/lang/String;)V");
1439 LOGE("could not get Method ID");
1443 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1446 LOGE("NewStringUTF failed");
1450 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1453 LOGE("NewStringUTF failed");
1457 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1462 (*g_jvm)->DetachCurrentThread(g_jvm);
1463 LOGI("DetachCurrentThread");
1467 CAResult_t get_remote_address(const char *address)
1469 uint32_t len = strlen(address);
1471 g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1472 if (NULL == g_remoteAddress)
1474 LOGE("g_remoteAddress Out of memory");
1475 return CA_MEMORY_ALLOC_FAILED;
1478 memcpy(g_remoteAddress, address, len + 1);
1480 return CA_STATUS_OK;
1484 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1486 if (NULL == uri || NULL == address)
1488 LOGE("parameter is null");
1494 uint8_t startIndex = 0;
1495 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1497 LOGI("uri has '%s' prefix", COAPS_PREFIX);
1498 startIndex = COAPS_PREFIX_LEN;
1501 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1503 LOGI("uri has '%s' prefix", COAP_PREFIX);
1504 startIndex = COAP_PREFIX_LEN;
1508 // #2. copy uri for parse
1509 size_t len = strlen(uri) - startIndex;
1513 LOGE("uri length is 0!");
1517 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1518 if (NULL == cloneUri)
1520 LOGE("Out of memory");
1524 OICStrcpy(cloneUri, len+1, &uri[startIndex]);
1527 //filter out the resource uri
1528 char *pUrl = strtok_r(cloneUri, "/", &pstr);
1532 LOGI("pAddress : %s", pUrl);
1533 int res = get_address_set(pUrl, address);
1536 LOGE("address parse error");
1543 LOGE("strtok_r error, could not get the address");
1549 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1551 if (NULL == pAddress || NULL == outAddress)
1553 LOGE("parameter is null");
1557 size_t len = strlen(pAddress);
1561 for (size_t i = 0; i < len; i++)
1563 if (pAddress[i] == '.')
1568 // found port number start index
1569 if (isIp && pAddress[i] == ':')
1578 if(ipLen && (ipLen < sizeof(outAddress->ipAddress)))
1580 strncpy(outAddress->ipAddress, pAddress, ipLen);
1581 outAddress->ipAddress[ipLen] = '\0';
1583 else if (!ipLen && (len < sizeof(outAddress->ipAddress)))
1585 strncpy(outAddress->ipAddress, pAddress, len);
1586 outAddress->ipAddress[len] = '\0';
1590 LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1596 outAddress->port = atoi(pAddress + ipLen + 1);
1601 strncpy(outAddress->ipAddress, pAddress, len);
1602 outAddress->ipAddress[len] = '\0';
1608 void delete_global_references(JNIEnv *env, jobject obj)
1610 LOGI("delete_global_references");
1613 LOGI("Invalid input parameter");
1617 (*env)->DeleteGlobalRef(env, g_responseListenerObject);
1621 bool read_file(const char* name, char** bytes, size_t* length)
1625 LOGE("parameter is null");
1634 file = fopen(name, "rt");
1637 fprintf(stderr, "Unable to open file %s", name);
1642 fseek(file, 0, SEEK_END);
1643 fileLen = ftell(file);
1644 fseek(file, 0, SEEK_SET);
1646 LOGI("file size: %d", fileLen);
1649 buffer = calloc(1, sizeof(char) * fileLen + 1);
1652 fprintf(stderr, "Memory error!");
1657 // Read file contents into buffer
1658 size_t ret = fread(buffer, fileLen, 1, file);
1661 printf("Failed to read data from file, %s\n", name);
1669 LOGI("file bytes: %s", buffer);
1677 void saveFile(const char *payload, size_t payloadSize)
1680 uint32_t day = gettodaydate();
1683 time_t current_time;
1684 struct tm * time_info;
1685 char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
1687 time(¤t_time);
1688 time_info = localtime(¤t_time);
1690 strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
1692 uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
1693 char* path = calloc(1, sizeof(char) * path_length);
1696 sprintf(path, RECEIVED_FILE_PATH, day, timeString);
1697 LOGI("received file path: %s", path);
1699 FILE *fp = fopen(path, "wt");
1700 fwrite(payload, 1, payloadSize, fp);
1703 callback("File Path: ", path);
1707 LOGE("path Out of memory");
1711 uint32_t gettodaydate()
1718 date = localtime(&clock);
1719 ldate = date->tm_year * 100000;
1720 ldate += (date->tm_mon + 1) * 1000;
1721 ldate += date->tm_mday * 10;
1722 ldate += date->tm_wday;