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 (CA_MSG_RESET == msgType ||
601 (CA_MSG_ACKNOWLEDGE == msgType && CA_EMPTY == responseValue))
603 printf("RESET or ACK/EMPTY. there will be not payload/option\n");
604 responseInfo.result = CA_EMPTY;
608 responseData.token = g_clientToken;
609 responseData.tokenLength = g_clientTokenLength;
610 responseInfo.result = responseValue;
614 uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
615 responseData.payload = (CAPayload_t) malloc(length);
616 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
617 g_resourceUri, g_localSecurePort);
618 responseData.payloadSize = length;
622 uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
623 responseData.payload = (CAPayload_t) malloc(length);
624 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, g_resourceUri);
625 responseData.payloadSize = length;
629 responseInfo.info = responseData;
632 res = CASendResponse(g_clientEndpoint, &responseInfo);
633 if (CA_STATUS_OK != res)
635 LOGE("Could not send response");
639 CADestroyToken(g_clientToken);
640 g_clientToken = NULL;
641 g_clientTokenLength = 0;
643 // destroy remote endpoint
644 CADestroyEndpoint(g_clientEndpoint);
645 g_clientEndpoint = NULL;
646 free(responseData.payload);
649 JNIEXPORT void JNICALL
650 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
651 jstring payload, jint selectedNetwork,
652 jint isSecured, jint msgType)
654 LOGI("selectedNetwork - %d", selectedNetwork);
657 LOGI("Invalid input parameter");
663 LOGE("payload is NULL");
668 LOGE("Invalid input parameter : uri");
672 CAResult_t res = get_network_type(selectedNetwork);
673 if (CA_STATUS_OK != res)
675 LOGE("Not supported network type");
679 const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
680 LOGI("RMSendNotification - %s", strUri);
682 CATransportFlags_t flags;
683 addressSet_t address = {{0}, 0};
684 parsing_coap_uri(strUri, &address, &flags);
686 //create remote endpoint
687 CAEndpoint_t* endpoint = NULL;
688 if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
689 (const char*)address.ipAddress,
690 address.port, &endpoint))
692 //ReleaseStringUTFChars for strUri
693 (*env)->ReleaseStringUTFChars(env, uri, strUri);
694 LOGE("Could not create remote end point");
698 char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
699 get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
701 //ReleaseStringUTFChars for strUri
702 (*env)->ReleaseStringUTFChars(env, uri, strUri);
704 CAMessageType_t messageType = msgType;
707 CAToken_t token = NULL;
708 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
710 res = CAGenerateToken(&token, tokenLength);
711 if ((CA_STATUS_OK != res) || (!token))
713 LOGE("token generate error!");
714 CADestroyEndpoint(endpoint);
718 CAInfo_t requestData = { 0 };
719 requestData.token = token;
720 requestData.tokenLength = tokenLength;
721 requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
722 if (NULL == requestData.resourceUri)
724 LOGE("Memory allocation failed!");
726 CADestroyToken(token);
727 // destroy remote endpoint
728 CADestroyEndpoint(endpoint);
731 memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
735 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
736 requestData.payload = (CAPayload_t) malloc(length);
737 if (NULL == requestData.payload)
739 LOGE("Memory allocation failed!");
741 CADestroyToken(token);
742 // destroy remote endpoint
743 CADestroyEndpoint(endpoint);
745 free(requestData.resourceUri);
748 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
749 resourceURI, g_localSecurePort);
750 requestData.payloadSize = length;
754 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
755 requestData.payload = (CAPayload_t) malloc(length);
756 if (NULL == requestData.payload)
758 LOGE("Memory allocation failed!");
760 CADestroyToken(token);
761 // destroy remote endpoint
762 CADestroyEndpoint(endpoint);
764 free(requestData.resourceUri);
767 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
768 requestData.payloadSize = length;
771 requestData.type = messageType;
773 CARequestInfo_t requestInfo = { 0 };
774 requestInfo.method = CA_GET;
775 requestInfo.info = requestData;
778 if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
780 LOGE("Could not send notification");
783 LOGI("Send Notification");
786 CADestroyToken(token);
788 // destroy remote endpoint
789 CADestroyEndpoint(endpoint);
791 free(requestData.payload);
792 free(requestData.resourceUri);
795 JNIEXPORT void JNICALL
796 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
799 LOGI("RMSelectNetwork Type : %d", networkType);
802 LOGI("Invalid input parameter");
806 if (CA_STATUS_OK != CASelectNetwork(networkType))
808 LOGE("Could not select network");
812 JNIEXPORT void JNICALL
813 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
816 LOGI("RMUnSelectNetwork Type : %d", networkType);
819 LOGI("Invalid input parameter");
823 if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
825 LOGE("Could not unselect network");
829 JNIEXPORT void JNICALL
830 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
832 LOGI("RMGetNetworkInfomation");
835 LOGI("Invalid input parameter");
839 CAEndpoint_t *tempInfo = NULL;
840 uint32_t tempSize = 0;
842 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
843 if (CA_STATUS_OK != res)
845 LOGE("Could not start get network information");
850 LOGI("################## Network Information #######################");
851 callback("######## Network Information", "#######");
852 LOGI("Network info total size is %d", tempSize);
855 for (index = 0; index < tempSize; index++)
857 res = get_remote_address(tempInfo[index].addr);
858 if (CA_STATUS_OK != res)
863 if (NULL != g_responseListenerObject)
865 char networkInfo[NETWORK_INFO_LENGTH];
866 LOGI("Type: %d", tempInfo[index].adapter);
867 snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].adapter);
868 callback("Type :", networkInfo);
869 if (CA_ADAPTER_IP == tempInfo[index].adapter)
871 LOGI("Port: %d", tempInfo[index].port);
872 snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].port);
873 callback("Port: ", networkInfo);
875 LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
876 LOGI("Address: %s", g_remoteAddress);
877 callback("Address: ", g_remoteAddress);
878 free(g_remoteAddress);
880 if (tempInfo[index].flags & CA_SECURE)
882 g_localSecurePort = tempInfo[index].port;
889 LOGI("##############################################################");
892 JNIEXPORT void JNICALL
893 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
895 LOGI("RMHandleRequestResponse");
898 LOGI("Invalid input parameter");
902 if (CA_STATUS_OK != CAHandleRequestResponse())
904 LOGE("Could not handle request and response");
908 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
913 LOGE("Remote endpoint is NULL!");
919 LOGE("Request info is NULL!");
923 if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
924 (strncmp(g_lastRequestToken, requestInfo->info.token,
925 requestInfo->info.tokenLength) == 0))
927 LOGI("token is same. received request of it's own. skip.. ");
931 CAResult_t res = get_remote_address(object->addr);
932 if (CA_STATUS_OK != res)
937 LOGI("##########received request from remote device #############");
938 LOGI("Remote Address: %s", g_remoteAddress);
939 LOGI("Remote Port: %d", object->port);
940 LOGI("Uri: %s", requestInfo->info.resourceUri);
941 LOGI("Data: %s", requestInfo->info.payload);
942 LOGI("Token: %s", requestInfo->info.token);
943 LOGI("Code: %d", requestInfo->method);
944 LOGI("MessageType: %d", requestInfo->info.type);
946 if (NULL != g_responseListenerObject)
948 char *cloneUri = NULL;
951 if (NULL != requestInfo->info.resourceUri)
953 len = strlen(requestInfo->info.resourceUri);
954 cloneUri = (char *)malloc(sizeof(char) * (len + 1));
956 if (NULL == cloneUri)
958 LOGE("cloneUri Out of memory");
959 free(g_remoteAddress);
963 memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
964 callback("Uri: ", cloneUri);
967 len = strlen(g_remoteAddress);
968 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
970 if (NULL == cloneRemoteAddress)
972 LOGE("cloneRemoteAddress Out of memory");
973 free(g_remoteAddress);
978 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
980 callback("Remote Address: ", cloneRemoteAddress);
981 free(cloneRemoteAddress);
982 free(g_remoteAddress);
984 char portInfo[PORT_LENGTH] = { 0, };
985 snprintf(portInfo, PORT_LENGTH, "%d", object->port);
986 callback("Remote Port: ", portInfo);
988 //clone g_clientEndpoint
989 g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
990 if (NULL == g_clientEndpoint)
992 LOGE("g_clientEndpoint Out of memory");
996 memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
998 if (NULL != cloneUri)
1000 len = strlen(cloneUri);
1001 g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
1002 if (NULL == g_resourceUri)
1004 LOGE("g_clientEndpoint->resourceUri Out of memory");
1005 free(g_clientEndpoint);
1009 memcpy(g_resourceUri, cloneUri, len + 1);
1012 //clone g_clientToken
1013 len = requestInfo->info.tokenLength;
1015 g_clientToken = (char *) malloc(sizeof(char) * len);
1016 if (NULL == g_clientToken)
1018 LOGE("g_clientToken Out of memory");
1019 free(g_clientEndpoint);
1023 if (NULL != requestInfo->info.token)
1025 memcpy(g_clientToken, requestInfo->info.token, len);
1026 g_clientTokenLength = len;
1030 //clone g_clientMsgId
1031 g_clientMsgId = requestInfo->info.messageId;
1033 if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1035 len = requestInfo->info.payloadSize;
1036 char *clonePayload = (char *) malloc(len + 1);
1037 if (NULL == clonePayload)
1039 LOGE("clonePayload Out of memory");
1040 free(g_clientEndpoint);
1044 memcpy(clonePayload, requestInfo->info.payload, len);
1045 clonePayload[len] = '\0';
1047 if (len > BIG_PAYLOAD_LENGTH)
1049 saveFile(clonePayload, len);
1053 callback("Data: ", clonePayload);
1059 if (requestInfo->info.options)
1061 uint32_t len = requestInfo->info.numOptions;
1064 LOGI("Option count: %d", requestInfo->info.numOptions);
1066 for (i = 0; i < len; i++)
1068 LOGI("Option %d", i + 1);
1069 LOGI("ID : %d", requestInfo->info.options[i].optionID);
1070 LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1071 requestInfo->info.options[i].optionData);
1073 if (NULL != g_responseListenerObject)
1075 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1076 snprintf(optionInfo, OPTION_INFO_LENGTH,
1077 "Num[%d] - ID : %d, Option Length : %d", i + 1,
1078 requestInfo->info.options[i].optionID,
1079 requestInfo->info.options[i].optionLength);
1081 callback("Option info: ", optionInfo);
1083 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1084 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1085 if (NULL == cloneOptionData)
1087 LOGE("cloneOptionData Out of memory");
1088 free(g_clientEndpoint);
1092 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1095 callback("Option Data: ", cloneOptionData);
1096 free(cloneOptionData);
1100 LOGI("############################################################");
1102 //Check if this has secure communication information
1103 if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1105 uint32_t securePort = get_secure_information(requestInfo->info.payload);
1106 if (0 < securePort) //Set the remote endpoint secure details and send response
1108 LOGI("This is secure resource...");
1110 CAEndpoint_t *endpoint = NULL;
1111 if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1112 object->adapter, object->addr, securePort, &endpoint))
1114 LOGE("Failed to create duplicate of remote endpoint!");
1122 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1124 if (!object || !responseInfo)
1126 LOGE("Invalid input parameter");
1130 CAResult_t res = get_remote_address(object->addr);
1131 if (CA_STATUS_OK != res)
1136 LOGI("##########Received response from remote device #############");
1137 LOGI("Uri: %s", responseInfo->info.resourceUri);
1138 LOGI("Remote Address: %s", g_remoteAddress);
1139 LOGI("Remote Port: %d", object->port);
1140 LOGI("response result: %d", responseInfo->result);
1141 LOGI("Data: %s", responseInfo->info.payload);
1142 LOGI("Token: %s", responseInfo->info.token);
1143 LOGI("MessageType: %d", responseInfo->info.type);
1145 if (NULL != g_responseListenerObject)
1149 if (NULL != responseInfo->info.resourceUri)
1151 len = strlen(responseInfo->info.resourceUri);
1152 char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1154 if (NULL == cloneUri)
1156 LOGE("cloneUri Out of memory");
1157 free(g_remoteAddress);
1161 memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1163 callback("Uri: ", cloneUri);
1167 len = strlen(g_remoteAddress);
1168 char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1170 if (NULL == cloneRemoteAddress)
1172 LOGE("cloneRemoteAddress Out of memory");
1173 free(g_remoteAddress);
1177 memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1179 callback("Remote Address: ", cloneRemoteAddress);
1180 free(cloneRemoteAddress);
1181 free(g_remoteAddress);
1183 char portInfo[PORT_LENGTH] = { 0, };
1184 snprintf(portInfo, PORT_LENGTH, "%d", object->port);
1185 callback("Remote Port: ", portInfo);
1187 if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1189 len = responseInfo->info.payloadSize;
1190 char *clonePayload = (char *) malloc(len + 1);
1191 if (NULL == clonePayload)
1193 LOGE("clonePayload Out of memory");
1197 memcpy(clonePayload, responseInfo->info.payload, len);
1198 clonePayload[len] = '\0';
1200 if (len > BIG_PAYLOAD_LENGTH)
1202 saveFile(clonePayload, len);
1206 callback("Data: ", clonePayload);
1212 if (responseInfo->info.options)
1214 uint32_t len = responseInfo->info.numOptions;
1216 for (i = 0; i < len; i++)
1218 LOGI("Option %d", i + 1);
1219 LOGI("ID : %d", responseInfo->info.options[i].optionID);
1220 LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1221 responseInfo->info.options[i].optionData);
1223 if (NULL != g_responseListenerObject)
1225 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1226 snprintf(optionInfo, OPTION_INFO_LENGTH,
1227 "Num[%d] - ID : %d, Option Length : %d", i + 1,
1228 responseInfo->info.options[i].optionID,
1229 responseInfo->info.options[i].optionLength);
1231 callback("Option info: ", optionInfo);
1233 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1234 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1235 if (NULL == cloneOptionData)
1237 LOGE("cloneOptionData Out of memory");
1240 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1242 callback("Option Data: ", cloneOptionData);
1243 free(cloneOptionData);
1247 LOGI("############################################################");
1249 //Check if this has secure communication information
1250 if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1252 uint32_t securePort = get_secure_information(responseInfo->info.payload);
1253 if (0 < securePort) //Set the remote endpoint secure details and send response
1255 LOGI("This is secure resource...");
1260 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1262 LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1266 LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1267 LOGI("Error Handler, Adapter Type : %s", rep->addr);
1272 const CAInfo_t *info = &errorInfo->info;
1273 LOGI("Error Handler, ErrorInfo :");
1274 LOGI("Error Handler result : %d", errorInfo->result);
1275 LOGI("Error Handler token : %s", info->token);
1276 LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1277 LOGI("Error Handler resourceUri : %s", info->resourceUri);
1278 LOGI("Error Handler type : %d", info->type);
1279 LOGI("Error Handler payload : %s", info->payload);
1281 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1283 LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1285 else if(CA_SEND_FAILED == errorInfo->result)
1287 LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1289 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1291 LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1293 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1295 LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1297 else if(CA_STATUS_FAILED == errorInfo->result)
1299 LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1302 LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1307 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1309 const char *startPos = URI;
1310 const char *temp = strstr(URI, "://");
1313 startPos = strchr(temp + 3, '/');
1316 LOGE("Resource URI is missing");
1321 const char *endPos = strchr(startPos, '?');
1324 endPos = URI + strlen(URI);
1328 if (endPos - startPos <= length)
1330 memcpy(resourceURI, startPos + 1, endPos - startPos);
1333 LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1336 uint32_t get_secure_information(CAPayload_t payLoad)
1338 LOGI("entering get_secure_information");
1342 LOGE("Payload is NULL");
1346 const char *subString = NULL;
1347 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1349 LOGE("This is not secure resource");
1353 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1355 LOGE("This secure resource does not have port information");
1359 const char *startPos = strstr(subString, ":");
1362 LOGE("Parsing failed !");
1366 const char *endPos = strstr(startPos, "}");
1369 LOGE("Parsing failed !");
1373 char portStr[6] = { 0 };
1374 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1376 LOGI("secured port is: %s", portStr);
1377 return atoi(portStr);
1380 CAResult_t get_network_type(uint32_t selectedNetwork)
1383 uint32_t number = selectedNetwork;
1385 if (!(number & 0xf))
1387 return CA_NOT_SUPPORTED;
1389 if (number & CA_ADAPTER_IP)
1391 g_selectedNwType = CA_ADAPTER_IP;
1392 return CA_STATUS_OK;
1394 if (number & CA_ADAPTER_RFCOMM_BTEDR)
1396 g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1397 return CA_STATUS_OK;
1399 if (number & CA_ADAPTER_GATT_BTLE)
1401 g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1402 return CA_STATUS_OK;
1405 return CA_NOT_SUPPORTED;
1408 void callback(char *subject, char *receivedData)
1410 bool isAttached = false;
1413 if (!g_responseListenerObject)
1415 LOGE("g_responseListenerObject is NULL, cannot have callback");
1419 jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1422 LOGI("Could not get JNIEnv pointer");
1423 res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1427 LOGE("AttachCurrentThread has failed");
1433 jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1436 LOGE("could not get class");
1440 jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1441 "(Ljava/lang/String;Ljava/lang/String;)V");
1444 LOGE("could not get Method ID");
1448 jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1451 LOGE("NewStringUTF failed");
1455 jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1458 LOGE("NewStringUTF failed");
1462 (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1467 (*g_jvm)->DetachCurrentThread(g_jvm);
1468 LOGI("DetachCurrentThread");
1472 CAResult_t get_remote_address(const char *address)
1474 uint32_t len = strlen(address);
1476 g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1477 if (NULL == g_remoteAddress)
1479 LOGE("g_remoteAddress Out of memory");
1480 return CA_MEMORY_ALLOC_FAILED;
1483 memcpy(g_remoteAddress, address, len + 1);
1485 return CA_STATUS_OK;
1489 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1491 if (NULL == uri || NULL == address)
1493 LOGE("parameter is null");
1499 uint8_t startIndex = 0;
1500 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1502 LOGI("uri has '%s' prefix", COAPS_PREFIX);
1503 startIndex = COAPS_PREFIX_LEN;
1506 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1508 LOGI("uri has '%s' prefix", COAP_PREFIX);
1509 startIndex = COAP_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: %d", 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;