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,
198 LOGI("RMInitialize");
199 if (!env || !obj || !context || !activity)
201 LOGI("Invalid input parameter");
205 //Currently set context for Android Platform
206 CANativeJNISetContext(env, context);
207 CANativeSetActivity(env, activity);
209 CAResult_t res = CAInitialize();
211 if (CA_STATUS_OK != res)
213 LOGE("Could not Initialize");
217 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
218 if(CA_STATUS_OK != res)
220 LOGE("Set credential handler fail");
226 JNIEXPORT void JNICALL
227 Java_org_iotivity_ca_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
232 LOGI("Invalid input parameter");
236 CADestroyToken(g_lastRequestToken);
238 delete_global_references(env, obj);
241 JNIEXPORT void JNICALL
242 Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
244 LOGI("RMStartListeningServer");
247 LOGI("Invalid input parameter");
251 if (CA_STATUS_OK != CAStartListeningServer())
253 LOGE("Could not start Listening server");
257 JNIEXPORT void JNICALL
258 Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
260 LOGI("RMStartDiscoveryServer");
263 LOGI("Invalid input parameter");
267 if (CA_STATUS_OK != CAStartDiscoveryServer())
269 LOGE("Could not start discovery server");
273 JNIEXPORT void JNICALL
274 Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
276 LOGI("RMRegisterHandler");
279 LOGI("Invalid input parameter");
283 CARegisterHandler(request_handler, response_handler, error_handler);
286 JNIEXPORT void JNICALL
287 Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
288 jstring payload, jint selectedNetwork,
289 jint isSecured, jint msgType,
292 LOGI("selectedNetwork - %d", selectedNetwork);
295 LOGI("Invalid input parameter");
301 LOGE("Invalid input parameter : uri");
305 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
306 CAResult_t res = get_network_type(selectedNetwork, &flags);
307 if (CA_STATUS_OK != res)
312 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
313 LOGI("RMSendRequest - %s", strUri);
315 addressSet_t address = {{0}, 0};
316 parsing_coap_uri(strUri, &address, &flags);
318 //create remote endpoint
319 CAEndpoint_t* endpoint = NULL;
320 res = CACreateEndpoint(flags, g_selectedNwType, (const char*)(address.ipAddress),
321 address.port, &endpoint);
322 if (CA_STATUS_OK != res)
324 LOGE("Could not create remote end point");
325 (*env)->ReleaseStringUTFChars(env, uri, strUri);
329 CAMessageType_t messageType = msgType;
332 CAToken_t token = NULL;
333 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
335 res = CAGenerateToken(&token, tokenLength);
336 if ((CA_STATUS_OK != res) || (!token))
338 LOGE("token generate error!!");
339 // destroy remote endpoint
340 CADestroyEndpoint(endpoint);
341 (*env)->ReleaseStringUTFChars(env, uri, strUri);
345 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
347 get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
348 (*env)->ReleaseStringUTFChars(env, uri, strUri);
350 CAInfo_t requestData = { 0 };
351 requestData.token = token;
352 requestData.tokenLength = tokenLength;
354 size_t payloadLength = 0;
357 const char* path = NULL;
360 path = (*env)->GetStringUTFChars(env, payload, NULL);
363 char* bigData = NULL;
364 bool result = read_file(path, &bigData, &payloadLength);
367 LOGE("read has failed");
368 (*env)->ReleaseStringUTFChars(env, payload, path);
369 CADestroyToken(token);
370 CADestroyEndpoint(endpoint);
373 (*env)->ReleaseStringUTFChars(env, payload, path);
375 requestData.payload = (CAPayload_t) malloc(payloadLength);
376 if (NULL == requestData.payload)
378 LOGE("Memory allocation failed!");
380 CADestroyToken(token);
381 // destroy remote endpoint
382 CADestroyEndpoint(endpoint);
385 memcpy(requestData.payload, bigData, payloadLength);
386 requestData.payloadSize = payloadLength;
394 payloadLength = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
395 requestData.payload = (CAPayload_t) malloc(payloadLength);
396 if (NULL == requestData.payload)
398 LOGE("Memory allocation failed!");
400 CADestroyToken(token);
401 // destroy remote endpoint
402 CADestroyEndpoint(endpoint);
405 snprintf((char *) requestData.payload, payloadLength, SECURE_INFO_DATA,
406 resourceURI, g_localSecurePort);
407 requestData.payloadSize = payloadLength;
411 payloadLength = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
412 requestData.payload = (CAPayload_t) malloc(payloadLength);
413 if (NULL == requestData.payload)
415 LOGE("Memory allocation failed!");
417 CADestroyToken(token);
418 // destroy remote endpoint
419 CADestroyEndpoint(endpoint);
422 snprintf((char *) requestData.payload, payloadLength, NORMAL_INFO_DATA, resourceURI);
423 requestData.payloadSize = payloadLength;
427 requestData.type = messageType;
428 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
429 if (NULL == requestData.resourceUri)
431 LOGE("Memory allocation failed!");
433 CADestroyToken(token);
434 // destroy remote endpoint
435 CADestroyEndpoint(endpoint);
436 free(requestData.payload);
439 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
441 CARequestInfo_t requestInfo = { 0 };
442 requestInfo.method = CA_GET;
443 requestInfo.isMulticast = false;
444 requestInfo.info = requestData;
447 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
449 LOGE("Could not send request");
453 CADestroyToken(token);
455 // destroy remote endpoint
456 CADestroyEndpoint(endpoint);
458 free(requestData.payload);
459 free(requestData.resourceUri);
460 LOGI("send request success");
463 JNIEXPORT void JNICALL
464 Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
465 jint selectedNetwork)
467 LOGI("selectedNetwork - %d", selectedNetwork);
470 LOGI("Invalid input parameter");
474 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
475 CAResult_t res = get_network_type(selectedNetwork, &flags);
476 if (CA_STATUS_OK != res)
478 LOGE("Not supported network type");
482 // create remote endpoint
483 CAEndpoint_t *endpoint = NULL;
484 res = CACreateEndpoint(flags, g_selectedNwType, NULL, 0, &endpoint);
486 if (CA_STATUS_OK != res)
488 LOGE("create remote endpoint error, error code: %d", res);
493 CAToken_t token = NULL;
494 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
496 res = CAGenerateToken(&token, tokenLength);
497 if ((CA_STATUS_OK != res) || (!token))
499 LOGE("token generate error!!");
500 // destroy remote endpoint
501 CADestroyEndpoint(endpoint);
505 LOGI("generated token %s", token);
507 CAInfo_t requestData = { 0 };
508 requestData.token = token;
509 requestData.tokenLength = tokenLength;
510 requestData.payload = (CAPayload_t) "TempJsonPayload";
511 requestData.payloadSize = strlen((const char *) requestData.payload);
512 requestData.type = CA_MSG_NONCONFIRM;
514 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
515 LOGI("resourceUri - %s", strUri);
516 requestData.resourceUri = (CAURI_t)strUri;
518 uint8_t optionNum = 2;
519 CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
520 sizeof(CAHeaderOption_t) * optionNum);
521 if (NULL == headerOpt)
523 LOGE("Memory allocation failed");
524 // destroy remote endpoint
525 CADestroyEndpoint(endpoint);
529 char* FirstOptionData = "Hello";
530 headerOpt[0].optionID = 3000;
531 memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
532 headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
534 char* SecondOptionData2 = "World";
535 headerOpt[1].optionID = 3001;
536 memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
537 headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
539 requestData.numOptions = optionNum;
540 requestData.options = headerOpt;
542 CARequestInfo_t requestInfo = { 0 };
543 requestInfo.method = CA_GET;
544 requestInfo.isMulticast = true;
545 requestInfo.info = requestData;
547 // send request to all
548 res = CASendRequest(endpoint, &requestInfo);
549 if (CA_STATUS_OK != res)
551 LOGE("Could not send request to all");
553 CADestroyToken(token);
557 CADestroyToken(g_lastRequestToken);
558 g_lastRequestToken = token;
559 g_lastRequestTokenLength = tokenLength;
562 //ReleaseStringUTFChars for strUri
563 (*env)->ReleaseStringUTFChars(env, uri, strUri);
567 // destroy remote endpoint
568 CADestroyEndpoint(endpoint);
571 JNIEXPORT void JNICALL
572 Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
573 jint selectedNetwork,
574 jint isSecured, jint msgType,
577 LOGI("RMSendResponse");
580 LOGI("Invalid input parameter");
584 LOGI("selectedNetwork - %d", selectedNetwork);
586 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
587 CAResult_t res = get_network_type(selectedNetwork, &flags);
588 if (CA_STATUS_OK != res)
590 LOGE("Not supported network type");
594 if (NULL == g_clientEndpoint)
596 LOGE("No Request received");
600 CAMessageType_t messageType = msgType;
602 CAInfo_t responseData = { 0 };
603 responseData.type = messageType;
604 responseData.messageId = g_clientMsgId;
605 responseData.resourceUri = (CAURI_t)g_resourceUri;
607 CAResponseInfo_t responseInfo = { 0 };
609 if (CA_MSG_RESET == msgType ||
610 (CA_MSG_ACKNOWLEDGE == msgType && CA_EMPTY == responseValue))
612 printf("RESET or ACK/EMPTY. there will be not payload/option\n");
613 responseInfo.result = CA_EMPTY;
617 responseData.token = g_clientToken;
618 responseData.tokenLength = g_clientTokenLength;
619 responseInfo.result = responseValue;
623 uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
624 responseData.payload = (CAPayload_t) malloc(length);
625 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
626 g_resourceUri, g_localSecurePort);
627 responseData.payloadSize = length;
631 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
632 responseData.payload = (CAPayload_t) malloc(length);
633 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, g_resourceUri);
634 responseData.payloadSize = length;
638 responseInfo.info = responseData;
641 res = CASendResponse(g_clientEndpoint, &responseInfo);
642 if (CA_STATUS_OK != res)
644 LOGE("Could not send response");
648 CADestroyToken(g_clientToken);
649 g_clientToken = NULL;
650 g_clientTokenLength = 0;
652 // destroy remote endpoint
653 CADestroyEndpoint(g_clientEndpoint);
654 g_clientEndpoint = NULL;
655 free(responseData.payload);
658 JNIEXPORT void JNICALL
659 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
660 jstring payload, jint selectedNetwork,
661 jint isSecured, jint msgType)
663 LOGI("selectedNetwork - %d", selectedNetwork);
666 LOGI("Invalid input parameter");
672 LOGE("payload is NULL");
677 LOGE("Invalid input parameter : uri");
681 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
682 CAResult_t res = get_network_type(selectedNetwork, &flags);
683 if (CA_STATUS_OK != res)
685 LOGE("Not supported network type");
689 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
690 LOGI("RMSendNotification - %s", strUri);
692 addressSet_t address = {{0}, 0};
693 parsing_coap_uri(strUri, &address, &flags);
695 //create remote endpoint
696 CAEndpoint_t* endpoint = NULL;
697 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
698 (const char*)address.ipAddress,
699 address.port, &endpoint))
701 //ReleaseStringUTFChars for strUri
702 (*env)->ReleaseStringUTFChars(env, uri, strUri);
703 LOGE("Could not create remote end point");
707 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
708 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
710 //ReleaseStringUTFChars for strUri
711 (*env)->ReleaseStringUTFChars(env, uri, strUri);
713 CAMessageType_t messageType = msgType;
716 CAToken_t token = NULL;
717 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
719 res = CAGenerateToken(&token, tokenLength);
720 if ((CA_STATUS_OK != res) || (!token))
722 LOGE("token generate error!");
723 CADestroyEndpoint(endpoint);
727 CAInfo_t requestData = { 0 };
728 requestData.token = token;
729 requestData.tokenLength = tokenLength;
730 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
731 if (NULL == requestData.resourceUri)
733 LOGE("Memory allocation failed!");
735 CADestroyToken(token);
736 // destroy remote endpoint
737 CADestroyEndpoint(endpoint);
740 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
744 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
745 requestData.payload = (CAPayload_t) malloc(length);
746 if (NULL == requestData.payload)
748 LOGE("Memory allocation failed!");
750 CADestroyToken(token);
751 // destroy remote endpoint
752 CADestroyEndpoint(endpoint);
754 free(requestData.resourceUri);
757 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
758 resourceURI, g_localSecurePort);
759 requestData.payloadSize = length;
763 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
764 requestData.payload = (CAPayload_t) malloc(length);
765 if (NULL == requestData.payload)
767 LOGE("Memory allocation failed!");
769 CADestroyToken(token);
770 // destroy remote endpoint
771 CADestroyEndpoint(endpoint);
773 free(requestData.resourceUri);
776 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
777 requestData.payloadSize = length;
780 requestData.type = messageType;
782 CARequestInfo_t requestInfo = { 0 };
783 requestInfo.method = CA_GET;
784 requestInfo.info = requestData;
787 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
789 LOGE("Could not send notification");
792 LOGI("Send Notification");
795 CADestroyToken(token);
797 // destroy remote endpoint
798 CADestroyEndpoint(endpoint);
800 free(requestData.payload);
801 free(requestData.resourceUri);
804 JNIEXPORT void JNICALL
805 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
808 LOGI("RMSelectNetwork Type : %d", networkType);
811 LOGI("Invalid input parameter");
815 if (CA_STATUS_OK != CASelectNetwork(networkType))
817 LOGE("Could not select network");
821 JNIEXPORT void JNICALL
822 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
825 LOGI("RMUnSelectNetwork Type : %d", networkType);
828 LOGI("Invalid input parameter");
832 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
834 LOGE("Could not unselect network");
838 JNIEXPORT void JNICALL
839 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
841 LOGI("RMGetNetworkInfomation");
844 LOGI("Invalid input parameter");
848 CAEndpoint_t *tempInfo = NULL;
849 uint32_t tempSize = 0;
851 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
852 if (CA_STATUS_OK != res)
854 LOGE("Could not start get network information");
859 LOGI("################## Network Information #######################");
860 callback("######## Network Information", "#######");
861 LOGI("Network info total size is %d", tempSize);
864 for (index = 0; index < tempSize; index++)
866 res = get_remote_address(tempInfo[index].addr);
867 if (CA_STATUS_OK != res)
872 if (NULL != g_responseListenerObject)
874 char networkInfo[NETWORK_INFO_LENGTH];
875 LOGI("Type: %d", tempInfo[index].adapter);
876 snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].adapter);
877 callback("Type :", networkInfo);
878 if (CA_ADAPTER_IP == tempInfo[index].adapter)
880 LOGI("Port: %d", tempInfo[index].port);
881 snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].port);
882 callback("Port: ", networkInfo);
884 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
885 LOGI("Address: %s", g_remoteAddress);
886 callback("Address: ", g_remoteAddress);
887 free(g_remoteAddress);
889 if (tempInfo[index].flags & CA_SECURE)
891 g_localSecurePort = tempInfo[index].port;
898 LOGI("##############################################################");
901 JNIEXPORT void JNICALL
902 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
904 LOGI("RMHandleRequestResponse");
907 LOGI("Invalid input parameter");
911 if (CA_STATUS_OK != CAHandleRequestResponse())
913 LOGE("Could not handle request and response");
917 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
922 LOGE("Remote endpoint is NULL!");
928 LOGE("Request info is NULL!");
932 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
933 (strncmp(g_lastRequestToken, requestInfo->info.token,
934 requestInfo->info.tokenLength) == 0))
936 LOGI("token is same. received request of it's own. skip.. ");
940 CAResult_t res = get_remote_address(object->addr);
941 if (CA_STATUS_OK != res)
946 LOGI("##########received request from remote device #############");
947 LOGI("Remote Address: %s", g_remoteAddress);
948 LOGI("Remote Port: %d", object->port);
949 LOGI("Uri: %s", requestInfo->info.resourceUri);
950 LOGI("Data: %s", requestInfo->info.payload);
951 LOGI("Token: %s", requestInfo->info.token);
952 LOGI("Code: %d", requestInfo->method);
953 LOGI("MessageType: %d", requestInfo->info.type);
955 if (NULL != g_responseListenerObject)
957 char *cloneUri = NULL;
960 if (NULL != requestInfo->info.resourceUri)
962 len = strlen(requestInfo->info.resourceUri);
963 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
965 if (NULL == cloneUri)
967 LOGE("cloneUri Out of memory");
968 free(g_remoteAddress);
972 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
973 callback("Uri: ", cloneUri);
976 len = strlen(g_remoteAddress);
977 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
979 if (NULL == cloneRemoteAddress)
981 LOGE("cloneRemoteAddress Out of memory");
982 free(g_remoteAddress);
987 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
989 callback("Remote Address: ", cloneRemoteAddress);
990 free(cloneRemoteAddress);
991 free(g_remoteAddress);
993 char portInfo[PORT_LENGTH] = { 0, };
994 snprintf(portInfo, PORT_LENGTH, "%d", object->port);
995 callback("Remote Port: ", portInfo);
997 //clone g_clientEndpoint
998 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
999 if (NULL == g_clientEndpoint)
1001 LOGE("g_clientEndpoint Out of memory");
1005 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
1007 if (NULL != cloneUri)
1009 len = strlen(cloneUri);
1010 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
1011 if (NULL == g_resourceUri)
1013 LOGE("g_clientEndpoint->resourceUri Out of memory");
1014 free(g_clientEndpoint);
1018 memcpy(g_resourceUri, cloneUri, len + 1);
1021 //clone g_clientToken
1022 len = requestInfo->info.tokenLength;
1024 g_clientToken = (char *) malloc(sizeof(char) * len);
1025 if (NULL == g_clientToken)
1027 LOGE("g_clientToken Out of memory");
1028 free(g_clientEndpoint);
1032 if (NULL != requestInfo->info.token)
1034 memcpy(g_clientToken, requestInfo->info.token, len);
1035 g_clientTokenLength = len;
1039 //clone g_clientMsgId
1040 g_clientMsgId = requestInfo->info.messageId;
1042 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1044 len = requestInfo->info.payloadSize;
1045 char *clonePayload = (char *) malloc(len + 1);
1046 if (NULL == clonePayload)
1048 LOGE("clonePayload Out of memory");
1049 free(g_clientEndpoint);
1053 memcpy(clonePayload, requestInfo->info.payload, len);
1054 clonePayload[len] = '\0';
1056 if (len > BIG_PAYLOAD_LENGTH)
1058 saveFile(clonePayload, len);
1062 callback("Data: ", clonePayload);
1068 if (requestInfo->info.options)
1070 uint32_t len = requestInfo->info.numOptions;
1073 LOGI("Option count: %d", requestInfo->info.numOptions);
1075 for (i = 0; i < len; i++)
1077 LOGI("Option %d", i + 1);
1078 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1079 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1080 requestInfo->info.options[i].optionData);
1082 if (NULL != g_responseListenerObject)
1084 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1085 snprintf(optionInfo, OPTION_INFO_LENGTH,
1086 "Num[%d] - ID : %d, Option Length : %d", i + 1,
1087 requestInfo->info.options[i].optionID,
1088 requestInfo->info.options[i].optionLength);
1090 callback("Option info: ", optionInfo);
1092 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1093 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1094 if (NULL == cloneOptionData)
1096 LOGE("cloneOptionData Out of memory");
1097 free(g_clientEndpoint);
1101 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1104 callback("Option Data: ", cloneOptionData);
1105 free(cloneOptionData);
1109 LOGI("############################################################");
1111 //Check if this has secure communication information
1112 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1114 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1115 if (0 < securePort) //Set the remote endpoint secure details and send response
1117 LOGI("This is secure resource...");
1119 CAEndpoint_t *endpoint = NULL;
1120 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1121 object->adapter, object->addr, securePort, &endpoint))
1123 LOGE("Failed to create duplicate of remote endpoint!");
1131 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1133 if (!object || !responseInfo)
1135 LOGE("Invalid input parameter");
1139 CAResult_t res = get_remote_address(object->addr);
1140 if (CA_STATUS_OK != res)
1145 LOGI("##########Received response from remote device #############");
1146 LOGI("Uri: %s", responseInfo->info.resourceUri);
1147 LOGI("Remote Address: %s", g_remoteAddress);
1148 LOGI("Remote Port: %d", object->port);
1149 LOGI("response result: %d", responseInfo->result);
1150 LOGI("Data: %s", responseInfo->info.payload);
1151 LOGI("Token: %s", responseInfo->info.token);
1152 LOGI("MessageType: %d", responseInfo->info.type);
1154 if (NULL != g_responseListenerObject)
1158 if (NULL != responseInfo->info.resourceUri)
1160 len = strlen(responseInfo->info.resourceUri);
1161 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1163 if (NULL == cloneUri)
1165 LOGE("cloneUri Out of memory");
1166 free(g_remoteAddress);
1170 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1172 callback("Uri: ", cloneUri);
1176 len = strlen(g_remoteAddress);
1177 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1179 if (NULL == cloneRemoteAddress)
1181 LOGE("cloneRemoteAddress Out of memory");
1182 free(g_remoteAddress);
1186 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1188 callback("Remote Address: ", cloneRemoteAddress);
1189 free(cloneRemoteAddress);
1190 free(g_remoteAddress);
1192 char portInfo[PORT_LENGTH] = { 0, };
1193 snprintf(portInfo, PORT_LENGTH, "%d", object->port);
1194 callback("Remote Port: ", portInfo);
1196 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1198 len = responseInfo->info.payloadSize;
1199 char *clonePayload = (char *) malloc(len + 1);
1200 if (NULL == clonePayload)
1202 LOGE("clonePayload Out of memory");
1206 memcpy(clonePayload, responseInfo->info.payload, len);
1207 clonePayload[len] = '\0';
1209 if (len > BIG_PAYLOAD_LENGTH)
1211 saveFile(clonePayload, len);
1215 callback("Data: ", clonePayload);
1221 if (responseInfo->info.options)
1223 uint32_t len = responseInfo->info.numOptions;
1225 for (i = 0; i < len; i++)
1227 LOGI("Option %d", i + 1);
1228 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1229 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1230 responseInfo->info.options[i].optionData);
1232 if (NULL != g_responseListenerObject)
1234 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1235 snprintf(optionInfo, OPTION_INFO_LENGTH,
1236 "Num[%d] - ID : %d, Option Length : %d", i + 1,
1237 responseInfo->info.options[i].optionID,
1238 responseInfo->info.options[i].optionLength);
1240 callback("Option info: ", optionInfo);
1242 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1243 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1244 if (NULL == cloneOptionData)
1246 LOGE("cloneOptionData Out of memory");
1249 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1251 callback("Option Data: ", cloneOptionData);
1252 free(cloneOptionData);
1256 LOGI("############################################################");
1258 //Check if this has secure communication information
1259 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1261 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1262 if (0 < securePort) //Set the remote endpoint secure details and send response
1264 LOGI("This is secure resource...");
1269 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1271 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1275 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1276 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1281 const CAInfo_t *info = &errorInfo->info;
1282 LOGI("Error Handler, ErrorInfo :");
1283 LOGI("Error Handler result : %d", errorInfo->result);
1284 LOGI("Error Handler token : %s", info->token);
1285 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1286 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1287 LOGI("Error Handler type : %d", info->type);
1288 LOGI("Error Handler payload : %s", info->payload);
1290 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1292 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1294 else if(CA_SEND_FAILED == errorInfo->result)
1296 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1298 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1300 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1302 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1304 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1306 else if(CA_STATUS_FAILED == errorInfo->result)
1308 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1311 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1316 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1318 const char *startPos = URI;
1319 const char *temp = strstr(URI, "://");
1322 startPos = strchr(temp + 3, '/');
1325 LOGE("Resource URI is missing");
1330 const char *endPos = strchr(startPos, '?');
1333 endPos = URI + strlen(URI);
1337 if (endPos - startPos <= length)
1339 memcpy(resourceURI, startPos + 1, endPos - startPos);
1342 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1345 uint32_t get_secure_information(CAPayload_t payLoad)
1347 LOGI("entering get_secure_information");
1351 LOGE("Payload is NULL");
1355 const char *subString = NULL;
1356 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1358 LOGE("This is not secure resource");
1362 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1364 LOGE("This secure resource does not have port information");
1368 const char *startPos = strstr(subString, ":");
1371 LOGE("Parsing failed !");
1375 const char *endPos = strstr(startPos, "}");
1378 LOGE("Parsing failed !");
1382 char portStr[6] = { 0 };
1383 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1385 LOGI("secured port is: %s", portStr);
1386 return atoi(portStr);
1389 CAResult_t get_network_type(uint32_t selectedNetwork, CATransportFlags_t *flags)
1392 uint32_t number = selectedNetwork;
1394 if (!(number & CA_ALL_ADAPTERS))
1396 LOGE("get_network_type Out of range");
1397 return CA_NOT_SUPPORTED;
1399 if ((number & CA_ADAPTER_IP) == CA_ADAPTER_IP)
1402 g_selectedNwType = CA_ADAPTER_IP;
1403 return CA_STATUS_OK;
1405 if ((number & CA_ADAPTER_RFCOMM_BTEDR) == CA_ADAPTER_RFCOMM_BTEDR)
1407 g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1408 return CA_STATUS_OK;
1410 if ((number & CA_ADAPTER_GATT_BTLE) == CA_ADAPTER_GATT_BTLE)
1412 g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1413 return CA_STATUS_OK;
1415 if ((number & CA_ADAPTER_TCP) == CA_ADAPTER_TCP)
1417 g_selectedNwType = CA_ADAPTER_TCP;
1418 return CA_STATUS_OK;
1420 if ((number & CA_ADAPTER_NFC) == CA_ADAPTER_NFC)
1422 g_selectedNwType = CA_ADAPTER_NFC;
1423 return CA_STATUS_OK;
1426 LOGE("Invalid transport");
1427 return CA_NOT_SUPPORTED;
1430 void callback(char *subject, char *receivedData)
1432 bool isAttached = false;
1435 if (!g_responseListenerObject)
1437 LOGE("g_responseListenerObject is NULL, cannot have callback");
1441 jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1444 LOGI("Could not get JNIEnv pointer");
1445 res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1449 LOGE("AttachCurrentThread has failed");
1455 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1458 LOGE("could not get class");
1462 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1463 "(Ljava/lang/String;Ljava/lang/String;)V");
1466 LOGE("could not get Method ID");
1470 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1473 LOGE("NewStringUTF failed");
1477 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1480 LOGE("NewStringUTF failed");
1484 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1489 (*g_jvm)->DetachCurrentThread(g_jvm);
1490 LOGI("DetachCurrentThread");
1494 CAResult_t get_remote_address(const char *address)
1496 uint32_t len = strlen(address);
1498 g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1499 if (NULL == g_remoteAddress)
1501 LOGE("g_remoteAddress Out of memory");
1502 return CA_MEMORY_ALLOC_FAILED;
1505 memcpy(g_remoteAddress, address, len + 1);
1507 return CA_STATUS_OK;
1511 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1513 if (NULL == uri || NULL == address)
1515 LOGE("parameter is null");
1521 uint8_t startIndex = 0;
1522 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1524 LOGI("uri has '%s' prefix", COAPS_PREFIX);
1525 startIndex = COAPS_PREFIX_LEN;
1528 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1530 LOGI("uri has '%s' prefix", COAP_PREFIX);
1531 startIndex = COAP_PREFIX_LEN;
1533 else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1535 LOGI("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1536 startIndex = COAP_TCP_PREFIX_LEN;
1540 // #2. copy uri for parse
1541 size_t len = strlen(uri) - startIndex;
1545 LOGE("uri length is 0!");
1549 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1550 if (NULL == cloneUri)
1552 LOGE("Out of memory");
1556 OICStrcpy(cloneUri, len+1, &uri[startIndex]);
1559 //filter out the resource uri
1560 char *pUrl = strtok_r(cloneUri, "/", &pstr);
1564 LOGI("pAddress : %s", pUrl);
1565 int res = get_address_set(pUrl, address);
1568 LOGE("address parse error");
1574 LOGE("strtok_r error, could not get the address");
1580 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1582 if (NULL == pAddress || NULL == outAddress)
1584 LOGE("parameter is null");
1588 size_t len = strlen(pAddress);
1592 for (size_t i = 0; i < len; i++)
1594 if (pAddress[i] == '.')
1599 // found port number start index
1600 if (isIp && pAddress[i] == ':')
1609 if(ipLen && (ipLen < sizeof(outAddress->ipAddress)))
1611 strncpy(outAddress->ipAddress, pAddress, ipLen);
1612 outAddress->ipAddress[ipLen] = '\0';
1614 else if (!ipLen && (len < sizeof(outAddress->ipAddress)))
1616 strncpy(outAddress->ipAddress, pAddress, len);
1617 outAddress->ipAddress[len] = '\0';
1621 LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1627 outAddress->port = atoi(pAddress + ipLen + 1);
1632 strncpy(outAddress->ipAddress, pAddress, len);
1633 outAddress->ipAddress[len] = '\0';
1639 void delete_global_references(JNIEnv *env, jobject obj)
1641 LOGI("delete_global_references");
1644 LOGI("Invalid input parameter");
1648 CADeleteGlobalReferences(env);
1649 (*env)->DeleteGlobalRef(env, g_responseListenerObject);
1653 bool read_file(const char* name, char** bytes, size_t* length)
1657 LOGE("parameter is null");
1666 file = fopen(name, "rt");
1669 fprintf(stderr, "Unable to open file %s", name);
1674 fseek(file, 0, SEEK_END);
1675 fileLen = ftell(file);
1678 fprintf(stderr, "Failed to read file length");
1682 fseek(file, 0, SEEK_SET);
1684 LOGI("file size: %ld", fileLen);
1687 buffer = calloc(1, sizeof(char) * fileLen + 1);
1690 fprintf(stderr, "Memory error!");
1695 // Read file contents into buffer
1696 size_t ret = fread(buffer, fileLen, 1, file);
1699 printf("Failed to read data from file, %s\n", name);
1707 LOGI("file bytes: %s", buffer);
1715 void saveFile(const char *payload, size_t payloadSize)
1718 uint32_t day = gettodaydate();
1721 time_t current_time;
1722 struct tm * time_info;
1723 char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
1725 time(¤t_time);
1726 time_info = localtime(¤t_time);
1728 strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
1730 uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
1731 char* path = calloc(1, sizeof(char) * path_length);
1734 snprintf(path, path_length, RECEIVED_FILE_PATH, day, timeString);
1735 LOGI("received file path: %s", path);
1737 FILE *fp = fopen(path, "wt");
1738 fwrite(payload, 1, payloadSize, fp);
1741 callback("File Path: ", path);
1745 LOGE("path Out of memory");
1749 uint32_t gettodaydate()
1756 date = localtime(&clock);
1757 ldate = date->tm_year * 100000;
1758 ldate += (date->tm_mon + 1) * 1000;
1759 ldate += date->tm_mday * 10;
1760 ldate += date->tm_wday;