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 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
622 g_resourceUri, g_localSecurePort);
623 responseData.payloadSize = length;
627 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
628 responseData.payload = (CAPayload_t) malloc(length);
629 snprintf((char *) responseData.payload, length, 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;
651 free(responseData.payload);
654 JNIEXPORT void JNICALL
655 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
656 jstring payload, jint selectedNetwork,
657 jint isSecured, jint msgType)
659 LOGI("selectedNetwork - %d", selectedNetwork);
662 LOGI("Invalid input parameter");
668 LOGE("payload is NULL");
673 LOGE("Invalid input parameter : uri");
677 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
678 CAResult_t res = get_network_type(selectedNetwork, &flags);
679 if (CA_STATUS_OK != res)
681 LOGE("Not supported network type");
685 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
686 LOGI("RMSendNotification - %s", strUri);
688 addressSet_t address = {{0}, 0};
689 parsing_coap_uri(strUri, &address, &flags);
691 //create remote endpoint
692 CAEndpoint_t* endpoint = NULL;
693 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
694 (const char*)address.ipAddress,
695 address.port, &endpoint))
697 //ReleaseStringUTFChars for strUri
698 (*env)->ReleaseStringUTFChars(env, uri, strUri);
699 LOGE("Could not create remote end point");
703 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
704 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
706 //ReleaseStringUTFChars for strUri
707 (*env)->ReleaseStringUTFChars(env, uri, strUri);
709 CAMessageType_t messageType = msgType;
712 CAToken_t token = NULL;
713 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
715 res = CAGenerateToken(&token, tokenLength);
716 if ((CA_STATUS_OK != res) || (!token))
718 LOGE("token generate error!");
719 CADestroyEndpoint(endpoint);
723 CAInfo_t requestData = { 0 };
724 requestData.token = token;
725 requestData.tokenLength = tokenLength;
726 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
727 if (NULL == requestData.resourceUri)
729 LOGE("Memory allocation failed!");
731 CADestroyToken(token);
732 // destroy remote endpoint
733 CADestroyEndpoint(endpoint);
736 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
740 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
741 requestData.payload = (CAPayload_t) malloc(length);
742 if (NULL == requestData.payload)
744 LOGE("Memory allocation failed!");
746 CADestroyToken(token);
747 // destroy remote endpoint
748 CADestroyEndpoint(endpoint);
750 free(requestData.resourceUri);
753 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
754 resourceURI, g_localSecurePort);
755 requestData.payloadSize = length;
759 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
760 requestData.payload = (CAPayload_t) malloc(length);
761 if (NULL == requestData.payload)
763 LOGE("Memory allocation failed!");
765 CADestroyToken(token);
766 // destroy remote endpoint
767 CADestroyEndpoint(endpoint);
769 free(requestData.resourceUri);
772 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
773 requestData.payloadSize = length;
776 requestData.type = messageType;
778 CARequestInfo_t requestInfo = { 0 };
779 requestInfo.method = CA_GET;
780 requestInfo.info = requestData;
783 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
785 LOGE("Could not send notification");
788 LOGI("Send Notification");
791 CADestroyToken(token);
793 // destroy remote endpoint
794 CADestroyEndpoint(endpoint);
796 free(requestData.payload);
797 free(requestData.resourceUri);
800 JNIEXPORT void JNICALL
801 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
804 LOGI("RMSelectNetwork Type : %d", networkType);
807 LOGI("Invalid input parameter");
811 if (CA_STATUS_OK != CASelectNetwork(networkType))
813 LOGE("Could not select network");
817 JNIEXPORT void JNICALL
818 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
821 LOGI("RMUnSelectNetwork Type : %d", networkType);
824 LOGI("Invalid input parameter");
828 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
830 LOGE("Could not unselect network");
834 JNIEXPORT void JNICALL
835 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
837 LOGI("RMGetNetworkInfomation");
840 LOGI("Invalid input parameter");
844 CAEndpoint_t *tempInfo = NULL;
845 uint32_t tempSize = 0;
847 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
848 if (CA_STATUS_OK != res)
850 LOGE("Could not start get network information");
855 LOGI("################## Network Information #######################");
856 callback("######## Network Information", "#######");
857 LOGI("Network info total size is %d", tempSize);
860 for (index = 0; index < tempSize; index++)
862 res = get_remote_address(tempInfo[index].addr);
863 if (CA_STATUS_OK != res)
868 if (NULL != g_responseListenerObject)
870 char networkInfo[NETWORK_INFO_LENGTH];
871 LOGI("Type: %d", tempInfo[index].adapter);
872 snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].adapter);
873 callback("Type :", networkInfo);
874 if (CA_ADAPTER_IP == tempInfo[index].adapter)
876 LOGI("Port: %d", tempInfo[index].port);
877 snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].port);
878 callback("Port: ", networkInfo);
880 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
881 LOGI("Address: %s", g_remoteAddress);
882 callback("Address: ", g_remoteAddress);
883 free(g_remoteAddress);
885 if (tempInfo[index].flags & CA_SECURE)
887 g_localSecurePort = tempInfo[index].port;
894 LOGI("##############################################################");
897 JNIEXPORT void JNICALL
898 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
900 LOGI("RMHandleRequestResponse");
903 LOGI("Invalid input parameter");
907 if (CA_STATUS_OK != CAHandleRequestResponse())
909 LOGE("Could not handle request and response");
913 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
918 LOGE("Remote endpoint is NULL!");
924 LOGE("Request info is NULL!");
928 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
929 (strncmp(g_lastRequestToken, requestInfo->info.token,
930 requestInfo->info.tokenLength) == 0))
932 LOGI("token is same. received request of it's own. skip.. ");
936 CAResult_t res = get_remote_address(object->addr);
937 if (CA_STATUS_OK != res)
942 LOGI("##########received request from remote device #############");
943 LOGI("Remote Address: %s", g_remoteAddress);
944 LOGI("Remote Port: %d", object->port);
945 LOGI("Uri: %s", requestInfo->info.resourceUri);
946 LOGI("Data: %s", requestInfo->info.payload);
947 LOGI("Token: %s", requestInfo->info.token);
948 LOGI("Code: %d", requestInfo->method);
949 LOGI("MessageType: %d", requestInfo->info.type);
951 if (NULL != g_responseListenerObject)
953 char *cloneUri = NULL;
956 if (NULL != requestInfo->info.resourceUri)
958 len = strlen(requestInfo->info.resourceUri);
959 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
961 if (NULL == cloneUri)
963 LOGE("cloneUri Out of memory");
964 free(g_remoteAddress);
968 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
969 callback("Uri: ", cloneUri);
972 len = strlen(g_remoteAddress);
973 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
975 if (NULL == cloneRemoteAddress)
977 LOGE("cloneRemoteAddress Out of memory");
978 free(g_remoteAddress);
983 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
985 callback("Remote Address: ", cloneRemoteAddress);
986 free(cloneRemoteAddress);
987 free(g_remoteAddress);
989 char portInfo[PORT_LENGTH] = { 0, };
990 snprintf(portInfo, PORT_LENGTH, "%d", object->port);
991 callback("Remote Port: ", portInfo);
993 //clone g_clientEndpoint
994 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
995 if (NULL == g_clientEndpoint)
997 LOGE("g_clientEndpoint Out of memory");
1001 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
1003 if (NULL != cloneUri)
1005 len = strlen(cloneUri);
1006 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
1007 if (NULL == g_resourceUri)
1009 LOGE("g_clientEndpoint->resourceUri Out of memory");
1010 free(g_clientEndpoint);
1014 memcpy(g_resourceUri, cloneUri, len + 1);
1017 //clone g_clientToken
1018 len = requestInfo->info.tokenLength;
1020 g_clientToken = (char *) malloc(sizeof(char) * len);
1021 if (NULL == g_clientToken)
1023 LOGE("g_clientToken Out of memory");
1024 free(g_clientEndpoint);
1028 if (NULL != requestInfo->info.token)
1030 memcpy(g_clientToken, requestInfo->info.token, len);
1031 g_clientTokenLength = len;
1035 //clone g_clientMsgId
1036 g_clientMsgId = requestInfo->info.messageId;
1038 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1040 len = requestInfo->info.payloadSize;
1041 char *clonePayload = (char *) malloc(len + 1);
1042 if (NULL == clonePayload)
1044 LOGE("clonePayload Out of memory");
1045 free(g_clientEndpoint);
1049 memcpy(clonePayload, requestInfo->info.payload, len);
1050 clonePayload[len] = '\0';
1052 if (len > BIG_PAYLOAD_LENGTH)
1054 saveFile(clonePayload, len);
1058 callback("Data: ", clonePayload);
1064 if (requestInfo->info.options)
1066 uint32_t len = requestInfo->info.numOptions;
1069 LOGI("Option count: %d", requestInfo->info.numOptions);
1071 for (i = 0; i < len; i++)
1073 LOGI("Option %d", i + 1);
1074 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1075 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1076 requestInfo->info.options[i].optionData);
1078 if (NULL != g_responseListenerObject)
1080 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1081 snprintf(optionInfo, OPTION_INFO_LENGTH,
1082 "Num[%d] - ID : %d, Option Length : %d", i + 1,
1083 requestInfo->info.options[i].optionID,
1084 requestInfo->info.options[i].optionLength);
1086 callback("Option info: ", optionInfo);
1088 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1089 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1090 if (NULL == cloneOptionData)
1092 LOGE("cloneOptionData Out of memory");
1093 free(g_clientEndpoint);
1097 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1100 callback("Option Data: ", cloneOptionData);
1101 free(cloneOptionData);
1105 LOGI("############################################################");
1107 //Check if this has secure communication information
1108 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1110 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1111 if (0 < securePort) //Set the remote endpoint secure details and send response
1113 LOGI("This is secure resource...");
1115 CAEndpoint_t *endpoint = NULL;
1116 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1117 object->adapter, object->addr, securePort, &endpoint))
1119 LOGE("Failed to create duplicate of remote endpoint!");
1127 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1129 if (!object || !responseInfo)
1131 LOGE("Invalid input parameter");
1135 CAResult_t res = get_remote_address(object->addr);
1136 if (CA_STATUS_OK != res)
1141 LOGI("##########Received response from remote device #############");
1142 LOGI("Uri: %s", responseInfo->info.resourceUri);
1143 LOGI("Remote Address: %s", g_remoteAddress);
1144 LOGI("Remote Port: %d", object->port);
1145 LOGI("response result: %d", responseInfo->result);
1146 LOGI("Data: %s", responseInfo->info.payload);
1147 LOGI("Token: %s", responseInfo->info.token);
1148 LOGI("MessageType: %d", responseInfo->info.type);
1150 if (NULL != g_responseListenerObject)
1154 if (NULL != responseInfo->info.resourceUri)
1156 len = strlen(responseInfo->info.resourceUri);
1157 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1159 if (NULL == cloneUri)
1161 LOGE("cloneUri Out of memory");
1162 free(g_remoteAddress);
1166 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1168 callback("Uri: ", cloneUri);
1172 len = strlen(g_remoteAddress);
1173 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1175 if (NULL == cloneRemoteAddress)
1177 LOGE("cloneRemoteAddress Out of memory");
1178 free(g_remoteAddress);
1182 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1184 callback("Remote Address: ", cloneRemoteAddress);
1185 free(cloneRemoteAddress);
1186 free(g_remoteAddress);
1188 char portInfo[PORT_LENGTH] = { 0, };
1189 snprintf(portInfo, PORT_LENGTH, "%d", object->port);
1190 callback("Remote Port: ", portInfo);
1192 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1194 len = responseInfo->info.payloadSize;
1195 char *clonePayload = (char *) malloc(len + 1);
1196 if (NULL == clonePayload)
1198 LOGE("clonePayload Out of memory");
1202 memcpy(clonePayload, responseInfo->info.payload, len);
1203 clonePayload[len] = '\0';
1205 if (len > BIG_PAYLOAD_LENGTH)
1207 saveFile(clonePayload, len);
1211 callback("Data: ", clonePayload);
1217 if (responseInfo->info.options)
1219 uint32_t len = responseInfo->info.numOptions;
1221 for (i = 0; i < len; i++)
1223 LOGI("Option %d", i + 1);
1224 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1225 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1226 responseInfo->info.options[i].optionData);
1228 if (NULL != g_responseListenerObject)
1230 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1231 snprintf(optionInfo, OPTION_INFO_LENGTH,
1232 "Num[%d] - ID : %d, Option Length : %d", i + 1,
1233 responseInfo->info.options[i].optionID,
1234 responseInfo->info.options[i].optionLength);
1236 callback("Option info: ", optionInfo);
1238 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1239 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1240 if (NULL == cloneOptionData)
1242 LOGE("cloneOptionData Out of memory");
1245 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1247 callback("Option Data: ", cloneOptionData);
1248 free(cloneOptionData);
1252 LOGI("############################################################");
1254 //Check if this has secure communication information
1255 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1257 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1258 if (0 < securePort) //Set the remote endpoint secure details and send response
1260 LOGI("This is secure resource...");
1265 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1267 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1271 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1272 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1277 const CAInfo_t *info = &errorInfo->info;
1278 LOGI("Error Handler, ErrorInfo :");
1279 LOGI("Error Handler result : %d", errorInfo->result);
1280 LOGI("Error Handler token : %s", info->token);
1281 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1282 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1283 LOGI("Error Handler type : %d", info->type);
1284 LOGI("Error Handler payload : %s", info->payload);
1286 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1288 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1290 else if(CA_SEND_FAILED == errorInfo->result)
1292 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1294 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1296 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1298 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1300 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1302 else if(CA_STATUS_FAILED == errorInfo->result)
1304 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1307 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1312 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1314 const char *startPos = URI;
1315 const char *temp = strstr(URI, "://");
1318 startPos = strchr(temp + 3, '/');
1321 LOGE("Resource URI is missing");
1326 const char *endPos = strchr(startPos, '?');
1329 endPos = URI + strlen(URI);
1333 if (endPos - startPos <= length)
1335 memcpy(resourceURI, startPos + 1, endPos - startPos);
1338 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1341 uint32_t get_secure_information(CAPayload_t payLoad)
1343 LOGI("entering get_secure_information");
1347 LOGE("Payload is NULL");
1351 const char *subString = NULL;
1352 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1354 LOGE("This is not secure resource");
1358 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1360 LOGE("This secure resource does not have port information");
1364 const char *startPos = strstr(subString, ":");
1367 LOGE("Parsing failed !");
1371 const char *endPos = strstr(startPos, "}");
1374 LOGE("Parsing failed !");
1378 char portStr[6] = { 0 };
1379 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1381 LOGI("secured port is: %s", portStr);
1382 return atoi(portStr);
1385 CAResult_t get_network_type(uint32_t selectedNetwork, CATransportFlags_t *flags)
1387 uint32_t number = selectedNetwork;
1393 case CA_ADAPTER_GATT_BTLE:
1394 case CA_ADAPTER_RFCOMM_BTEDR:
1395 case CA_ADAPTER_TCP:
1396 g_selectedNwType = number;
1397 return CA_STATUS_OK;
1399 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;
1506 else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1508 LOGI("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1509 startIndex = COAP_TCP_PREFIX_LEN;
1513 // #2. copy uri for parse
1514 size_t len = strlen(uri) - startIndex;
1518 LOGE("uri length is 0!");
1522 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1523 if (NULL == cloneUri)
1525 LOGE("Out of memory");
1529 OICStrcpy(cloneUri, len+1, &uri[startIndex]);
1532 //filter out the resource uri
1533 char *pUrl = strtok_r(cloneUri, "/", &pstr);
1537 LOGI("pAddress : %s", pUrl);
1538 int res = get_address_set(pUrl, address);
1541 LOGE("address parse error");
1548 LOGE("strtok_r error, could not get the address");
1554 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1556 if (NULL == pAddress || NULL == outAddress)
1558 LOGE("parameter is null");
1562 size_t len = strlen(pAddress);
1566 for (size_t i = 0; i < len; i++)
1568 if (pAddress[i] == '.')
1573 // found port number start index
1574 if (isIp && pAddress[i] == ':')
1583 if(ipLen && (ipLen < sizeof(outAddress->ipAddress)))
1585 strncpy(outAddress->ipAddress, pAddress, ipLen);
1586 outAddress->ipAddress[ipLen] = '\0';
1588 else if (!ipLen && (len < sizeof(outAddress->ipAddress)))
1590 strncpy(outAddress->ipAddress, pAddress, len);
1591 outAddress->ipAddress[len] = '\0';
1595 LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1601 outAddress->port = atoi(pAddress + ipLen + 1);
1606 strncpy(outAddress->ipAddress, pAddress, len);
1607 outAddress->ipAddress[len] = '\0';
1613 void delete_global_references(JNIEnv *env, jobject obj)
1615 LOGI("delete_global_references");
1618 LOGI("Invalid input parameter");
1622 (*env)->DeleteGlobalRef(env, g_responseListenerObject);
1626 bool read_file(const char* name, char** bytes, size_t* length)
1630 LOGE("parameter is null");
1639 file = fopen(name, "rt");
1642 fprintf(stderr, "Unable to open file %s", name);
1647 fseek(file, 0, SEEK_END);
1648 fileLen = ftell(file);
1651 fprintf(stderr, "Failed to read file length");
1655 fseek(file, 0, SEEK_SET);
1657 LOGI("file size: %ld", fileLen);
1660 buffer = calloc(1, sizeof(char) * fileLen + 1);
1663 fprintf(stderr, "Memory error!");
1668 // Read file contents into buffer
1669 size_t ret = fread(buffer, fileLen, 1, file);
1672 printf("Failed to read data from file, %s\n", name);
1680 LOGI("file bytes: %s", buffer);
1688 void saveFile(const char *payload, size_t payloadSize)
1691 uint32_t day = gettodaydate();
1694 time_t current_time;
1695 struct tm * time_info;
1696 char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
1698 time(¤t_time);
1699 time_info = localtime(¤t_time);
1701 strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
1703 uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
1704 char* path = calloc(1, sizeof(char) * path_length);
1707 snprintf(path, path_length, RECEIVED_FILE_PATH, day, timeString);
1708 LOGI("received file path: %s", path);
1710 FILE *fp = fopen(path, "wt");
1711 fwrite(payload, 1, payloadSize, fp);
1714 callback("File Path: ", path);
1718 LOGE("path Out of memory");
1722 uint32_t gettodaydate()
1729 date = localtime(&clock);
1730 ldate = date->tm_year * 100000;
1731 ldate += (date->tm_mon + 1) * 1000;
1732 ldate += date->tm_mday * 10;
1733 ldate += date->tm_wday;