Merge branch 'master' into 'security-basecamp'
[platform/upstream/iotivity.git] / resource / csdk / connectivity / samples / android / casample / sampleService / src / main / jni / ResourceModel.c
1 #include <jni.h>
2 #include <android/log.h>
3 #include <stdio.h>
4 #include <dlfcn.h>
5 #include <stdlib.h>
6 #include <string.h>
7
8 #include "cainterface.h"
9 #include "cacommon.h"
10
11 #include "org_iotivity_ca_service_RMInterface.h"
12
13 #define  LOG_TAG   "JNI_INTERFACE_SAMPLE"
14 #define  LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
15 #define  LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
16
17 /**
18  * @def RS_IDENTITY
19  * @brief
20  */
21 #define IDENTITY     ("1111111111111111")
22 /* @def RS_CLIENT_PSK
23  * @brief
24  */
25 #define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
26
27 #define PORT_LENGTH 5
28 #define SECURE_DEFAULT_PORT 5684
29 #define RESOURCE_URI_LENGTH 14
30 #define OPTION_INFO_LENGTH 1024
31 #define NETWORK_INFO_LENGTH 1024
32
33 typedef struct
34 {
35     char ipAddress[CA_IPADDR_SIZE];
36     uint16_t port;
37 } addressSet_t;
38
39 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo);
40 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo);
41 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
42 void get_resource_uri(const char *URI, char *resourceURI, uint32_t length);
43 uint32_t get_secure_information(CAPayload_t payLoad);
44 CAResult_t get_network_type(uint32_t selectedNetwork);
45 void callback(char *subject, char *receivedData);
46 CAResult_t get_remote_address(CATransportAdapter_t transportType, const char *address);
47 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
48
49 uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
50 CATransportAdapter_t g_selectedNwType = CA_ADAPTER_IP;
51 static CAToken_t g_lastRequestToken = NULL;
52 static uint8_t g_lastRequestTokenLength = 0;
53
54 static const char COAP_PREFIX[] =  "coap://";
55 static const char COAPS_PREFIX[] = "coaps://";
56 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
57 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
58
59 static const char SECURE_INFO_DATA[]
60                                    = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
61                                      "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
62                                      "%d}}]}";
63 static const char NORMAL_INFO_DATA[]
64                                    = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
65                                      "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
66
67 static jobject g_responseListenerObject = NULL;
68 static JavaVM *g_jvm;
69
70 static CAEndpoint_t *g_clientEndpoint = NULL;
71 static char *g_resourceUri = NULL;
72 static CAToken_t g_clientToken = NULL;
73 static uint8_t g_clientTokenLength = 0;
74
75 static uint16_t g_clientMsgId = 0;
76 static char *g_remoteAddress = NULL;
77
78 // init
79 JNIEXPORT void JNICALL
80 Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
81                                                                    jobject listener)
82 {
83     LOGI("setNativeResponseListener");
84     g_responseListenerObject = (*env)->NewGlobalRef(env, obj);
85 }
86
87 #ifdef __WITH_DTLS__
88 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
89
90 void clearDtlsCredentialInfo()
91 {
92     LOGI("clearDtlsCredentialInfo IN");
93     if (pskCredsBlob)
94     {
95         // Initialize sensitive data to zeroes before freeing.
96         if (NULL != pskCredsBlob->creds)
97         {
98             memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds)*(pskCredsBlob->num));
99             free(pskCredsBlob->creds);
100         }
101
102         memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
103         free(pskCredsBlob);
104         pskCredsBlob = NULL;
105     }
106     LOGI("clearDtlsCredentialInfo OUT");
107 }
108
109 // Internal API. Invoked by OC stack to retrieve credentials from this module
110 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
111 {
112     LOGI("CAGetDtlsPskCredentials IN");
113     *credInfo = (CADtlsPskCredsBlob_t *) malloc(sizeof(CADtlsPskCredsBlob_t));
114     if (NULL == *credInfo)
115     {
116         LOGE("Failed to allocate credential blob.");
117         return;
118     }
119
120     int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
121     (*credInfo)->creds = (OCDtlsPskCreds *) malloc(credLen);
122     if (NULL == (*credInfo)->creds)
123     {
124         LOGE("Failed to allocate crentials.");
125         free(*credInfo);
126         *credInfo = NULL;
127         return;
128     }
129
130     memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
131     (*credInfo)->num = pskCredsBlob->num;
132     memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
133
134     LOGI("CAGetDtlsPskCredentials OUT");
135 }
136
137 CAResult_t SetCredentials()
138 {
139     LOGI("SetCredentials IN");
140     pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
141     if (NULL == pskCredsBlob)
142     {
143         LOGE("Memory allocation failed!");
144         return CA_MEMORY_ALLOC_FAILED;
145     }
146     memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
147
148     pskCredsBlob->num = 1;
149
150     pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) *(pskCredsBlob->num));
151     if (NULL == pskCredsBlob->creds)
152     {
153         LOGE("Memory allocation failed!");
154         return CA_MEMORY_ALLOC_FAILED;
155     }
156     memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
157     memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
158
159     LOGI("SetCredentials OUT");
160     return CA_STATUS_OK;
161 }
162 #endif
163
164 JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
165 {
166     LOGI("JNI_OnLoad");
167
168     JNIEnv* env;
169     if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
170     {
171         return -1;
172     }
173     g_jvm = jvm; /* cache the JavaVM pointer */
174
175     CANativeJNISetJavaVM(g_jvm);
176
177     return JNI_VERSION_1_6;
178 }
179
180 void JNI_OnUnload(JavaVM *jvm, void *reserved)
181 {
182     LOGI("JNI_OnUnload");
183
184     JNIEnv* env;
185     if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
186     {
187         return;
188     }
189     g_jvm = 0;
190     return;
191 }
192
193 JNIEXPORT void JNICALL
194 Java_org_iotivity_ca_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
195 {
196     LOGI("RMInitialize");
197
198     //Currently set context for Android Platform
199     CANativeJNISetContext(env, context);
200
201     CAResult_t res = CAInitialize();
202
203     if (CA_STATUS_OK != res)
204     {
205         LOGE("Could not Initialize");
206     }
207
208 #ifdef __WITH_DTLS__
209     if (CA_STATUS_OK != SetCredentials())
210     {
211         LOGE("SetCredentials failed");
212         return;
213     }
214
215     res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
216     if(CA_STATUS_OK != res)
217     {
218         LOGE("Set credential handler fail");
219         return;
220     }
221 #endif
222 }
223
224 JNIEXPORT void JNICALL
225 Java_org_iotivity_ca_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
226 {
227     LOGI("RMTerminate");
228     CADestroyToken(g_lastRequestToken);
229     CATerminate();
230 }
231
232 JNIEXPORT void JNICALL
233 Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
234 {
235     LOGI("RMStartListeningServer");
236
237     if (CA_STATUS_OK != CAStartListeningServer())
238     {
239         LOGE("Could not start Listening server");
240     }
241 }
242
243 JNIEXPORT void JNICALL
244 Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
245 {
246     LOGI("RMStartDiscoveryServer");
247
248     if (CA_STATUS_OK != CAStartDiscoveryServer())
249     {
250         LOGE("Could not start discovery server");
251     }
252 }
253
254 JNIEXPORT void JNICALL
255 Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
256 {
257     LOGI("RMRegisterHandler");
258
259     CARegisterHandler(request_handler, response_handler, error_handler);
260 }
261
262 JNIEXPORT void JNICALL
263 Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
264                                                        jstring payload, jint selectedNetwork,
265                                                        jint isSecured, jint msgType)
266 {
267     LOGI("selectedNetwork - %d", selectedNetwork);
268     CAResult_t res = get_network_type(selectedNetwork);
269     if (CA_STATUS_OK != res)
270     {
271         return;
272     }
273
274     const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
275     LOGI("RMSendRequest - %s", strUri);
276
277     CATransportFlags_t flags;
278     addressSet_t address = {};
279     parsing_coap_uri(strUri, &address, &flags);
280
281     //create remote endpoint
282     CAEndpoint_t* endpoint = NULL;
283     res = CACreateEndpoint(flags, g_selectedNwType, (const char*)address.ipAddress,
284                            address.port, &endpoint);
285     if (CA_STATUS_OK != res)
286     {
287         LOGE("Could not create remote end point");
288         (*env)->ReleaseStringUTFChars(env, uri, strUri);
289         return;
290     }
291
292     CAMessageType_t messageType = msgType;
293
294     // create token
295     CAToken_t token = NULL;
296     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
297
298     res = CAGenerateToken(&token, tokenLength);
299     if ((CA_STATUS_OK != res) || (!token))
300     {
301         LOGE("token generate error!!");
302         // destroy remote endpoint
303         CADestroyEndpoint(endpoint);
304         (*env)->ReleaseStringUTFChars(env, uri, strUri);
305         return;
306     }
307
308     char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
309
310     get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
311     (*env)->ReleaseStringUTFChars(env, uri, strUri);
312
313     CAInfo_t requestData = { 0 };
314     requestData.token = token;
315     requestData.tokenLength = tokenLength;
316
317     if (1 == isSecured)
318     {
319         uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
320         requestData.payload = (CAPayload_t) malloc(length);
321         if (NULL == requestData.payload)
322         {
323             LOGE("Memory allocation failed!");
324             // destroy token
325             CADestroyToken(token);
326             // destroy remote endpoint
327             CADestroyEndpoint(endpoint);
328             return;
329         }
330         snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
331         requestData.payloadSize = length;
332     }
333     else
334     {
335         uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
336         requestData.payload = (CAPayload_t) malloc(length);
337         if (NULL == requestData.payload)
338         {
339             LOGE("Memory allocation failed!");
340             // destroy token
341             CADestroyToken(token);
342             // destroy remote endpoint
343             CADestroyEndpoint(endpoint);
344             return;
345         }
346         snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
347         requestData.payloadSize = length;
348     }
349
350     requestData.type = messageType;
351     requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
352     if (NULL == requestData.resourceUri)
353     {
354         LOGE("Memory allocation failed!");
355         // destroy token
356         CADestroyToken(token);
357         // destroy remote endpoint
358         CADestroyEndpoint(endpoint);
359         free(requestData.payload);
360         return;
361     }
362     memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
363
364     CARequestInfo_t requestInfo = { 0 };
365     requestInfo.method = CA_GET;
366     requestInfo.isMulticast = false;
367     requestInfo.info = requestData;
368
369     // send request
370     if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
371     {
372         LOGE("Could not send request");
373     }
374
375     // destroy token
376     CADestroyToken(token);
377
378     // destroy remote endpoint
379     CADestroyEndpoint(endpoint);
380
381     free(requestData.payload);
382     free(requestData.resourceUri);
383 }
384
385 JNIEXPORT void JNICALL
386 Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
387                                                            jint selectedNetwork)
388 {
389     LOGI("selectedNetwork - %d", selectedNetwork);
390     CAResult_t res = get_network_type(selectedNetwork);
391     if (CA_STATUS_OK != res)
392     {
393         return;
394     }
395
396     // create remote endpoint
397     CAEndpoint_t *endpoint = NULL;
398     res = CACreateEndpoint(CA_IPV4, g_selectedNwType, NULL, 0, &endpoint);
399
400     if (CA_STATUS_OK != res)
401     {
402         LOGE("create remote endpoint error, error code: %d", res);
403         return;
404     }
405
406     // create token
407     CAToken_t token = NULL;
408     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
409
410     res = CAGenerateToken(&token, tokenLength);
411     if ((CA_STATUS_OK != res) || (!token))
412     {
413         LOGE("token generate error!!");
414         // destroy remote endpoint
415         CADestroyEndpoint(endpoint);
416         return;
417     }
418
419     LOGI("generated token %s", token);
420
421     CAInfo_t requestData = { 0 };
422     requestData.token = token;
423     requestData.tokenLength = tokenLength;
424     requestData.payload = (CAPayload_t) "TempJsonPayload";
425     requestData.payloadSize = strlen((const char *) requestData.payload);
426     requestData.type = CA_MSG_NONCONFIRM;
427
428     const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
429     LOGI("resourceUri - %s", strUri);
430     requestData.resourceUri = (CAURI_t)strUri;
431
432     uint8_t optionNum = 2;
433     CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
434                                                              sizeof(CAHeaderOption_t) * optionNum);
435     if (NULL == headerOpt)
436     {
437         LOGE("Memory allocation failed");
438         // destroy remote endpoint
439         CADestroyEndpoint(endpoint);
440         return;
441     }
442
443     char* FirstOptionData = "Hello";
444     headerOpt[0].optionID = 3000;
445     memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
446     headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
447
448     char* SecondOptionData2 = "World";
449     headerOpt[1].optionID = 3001;
450     memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
451     headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
452
453     requestData.numOptions = optionNum;
454     requestData.options = headerOpt;
455
456     CARequestInfo_t requestInfo = { 0 };
457     requestInfo.method = CA_GET;
458     requestInfo.isMulticast = true;
459     requestInfo.info = requestData;
460
461     // send request to all
462     res = CASendRequest(endpoint, &requestInfo);
463     if (CA_STATUS_OK != res)
464     {
465         LOGE("Could not send request to all");
466         //destroy token
467         CADestroyToken(token);
468     }
469     else
470     {
471         CADestroyToken(g_lastRequestToken);
472         g_lastRequestToken = token;
473         g_lastRequestTokenLength = tokenLength;
474     }
475
476     //ReleaseStringUTFChars for strUri
477     (*env)->ReleaseStringUTFChars(env, uri, strUri);
478
479     free(headerOpt);
480
481     // destroy remote endpoint
482     CADestroyEndpoint(endpoint);
483 }
484
485 JNIEXPORT void JNICALL
486 Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
487                                                         jint selectedNetwork,
488                                                         jint isSecured, jint msgType,
489                                                         jint responseValue)
490 {
491     LOGI("RMSendResponse");
492
493     LOGI("selectedNetwork - %d", selectedNetwork);
494
495     CAResult_t res = get_network_type(selectedNetwork);
496     if (CA_STATUS_OK != res)
497     {
498         LOGE("Not supported network type");
499         return;
500     }
501
502     if (NULL == g_clientEndpoint)
503     {
504         LOGE("No Request received");
505         return;
506     }
507
508     CAMessageType_t messageType = msgType;
509
510     CAInfo_t responseData = { 0 };
511     responseData.type = messageType;
512     responseData.messageId = g_clientMsgId;
513     responseData.resourceUri = (CAURI_t)g_resourceUri;
514
515     CAResponseInfo_t responseInfo = { 0 };
516
517     if (msgType != CA_MSG_RESET)
518     {
519         responseData.token = g_clientToken;
520         responseData.tokenLength = g_clientTokenLength;
521         responseInfo.result = responseValue;
522
523         if (1 == isSecured)
524         {
525             uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
526             responseData.payload = (CAPayload_t) malloc(length);
527             sprintf(responseData.payload, SECURE_INFO_DATA, g_resourceUri,
528                     g_localSecurePort);
529             responseData.payloadSize = length;
530         }
531         else
532         {
533             uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
534             responseData.payload = (CAPayload_t) malloc(length);
535             sprintf(responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
536             responseData.payloadSize = length;
537         }
538     }
539     //msgType is RESET
540     else
541     {
542         responseInfo.result = CA_EMPTY;
543     }
544
545     responseInfo.info = responseData;
546
547     // send response
548     res = CASendResponse(g_clientEndpoint, &responseInfo);
549     if (CA_STATUS_OK != res)
550     {
551         LOGE("Could not send response");
552     }
553
554     // destroy token
555     CADestroyToken(g_clientToken);
556     g_clientToken = NULL;
557     g_clientTokenLength = 0;
558
559     // destroy remote endpoint
560     CADestroyEndpoint(g_clientEndpoint);
561     g_clientEndpoint = NULL;
562 }
563
564 JNIEXPORT void JNICALL
565 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
566                                                             jstring payload, jint selectedNetwork,
567                                                             jint isSecured, jint msgType,
568                                                             jint responseValue)
569 {
570     LOGI("selectedNetwork - %d", selectedNetwork);
571
572     CAResult_t res = get_network_type(selectedNetwork);
573     if (CA_STATUS_OK != res)
574     {
575         LOGE("Not supported network type");
576         return;
577     }
578
579     const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
580     LOGI("RMSendNotification - %s", strUri);
581
582     CATransportFlags_t flags;
583     addressSet_t address = {};
584     parsing_coap_uri(strUri, &address, &flags);
585
586     //create remote endpoint
587     CAEndpoint_t* endpoint = NULL;
588     if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
589                                          (const char*)address.ipAddress,
590                                          address.port, &endpoint))
591     {
592         //ReleaseStringUTFChars for strUri
593         (*env)->ReleaseStringUTFChars(env, uri, strUri);
594         LOGE("Could not create remote end point");
595         return;
596     }
597
598     char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
599     get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
600
601     //ReleaseStringUTFChars for strUri
602     (*env)->ReleaseStringUTFChars(env, uri, strUri);
603
604     CAMessageType_t messageType = msgType;
605
606     // create token
607     CAToken_t token = NULL;
608     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
609
610     res = CAGenerateToken(&token, tokenLength);
611     if ((CA_STATUS_OK != res) || (!token))
612     {
613         LOGE("token generate error!");
614         CADestroyEndpoint(endpoint);
615         return;
616     }
617
618     CAInfo_t responseData = { 0 };
619     responseData.token = token;
620     responseData.tokenLength = tokenLength;
621     responseData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
622     if (NULL == responseData.resourceUri)
623     {
624         LOGE("Memory allocation failed!");
625         // destroy token
626         CADestroyToken(token);
627         // destroy remote endpoint
628         CADestroyEndpoint(endpoint);
629         return;
630     }
631     memcpy(responseData.resourceUri, resourceURI, sizeof(resourceURI));
632
633     if (1 == isSecured)
634     {
635         uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
636         responseData.payload = (CAPayload_t) malloc(length);
637         if (NULL == responseData.payload)
638         {
639             LOGE("Memory allocation failed!");
640             // destroy token
641             CADestroyToken(token);
642             // destroy remote endpoint
643             CADestroyEndpoint(endpoint);
644
645             free(responseData.resourceUri);
646             return;
647         }
648         snprintf(responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
649         responseData.payloadSize = length;
650     }
651     else
652     {
653         uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
654         responseData.payload = (CAPayload_t) malloc(length);
655         if (NULL == responseData.payload)
656         {
657             LOGE("Memory allocation failed!");
658             // destroy token
659             CADestroyToken(token);
660             // destroy remote endpoint
661             CADestroyEndpoint(endpoint);
662
663             free(responseData.resourceUri);
664             return;
665         }
666         snprintf(responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
667         responseData.payloadSize = length;
668     }
669
670     responseData.type = messageType;
671
672     CAResponseInfo_t responseInfo = { 0 };
673     responseInfo.result = responseValue;
674     responseInfo.info = responseData;
675
676     // send notification
677     if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
678     {
679         LOGE("Could not send notification");
680     }
681
682     LOGI("Send Notification");
683
684     // destroy token
685     CADestroyToken(token);
686
687     // destroy remote endpoint
688     CADestroyEndpoint(endpoint);
689
690     free(responseData.payload);
691     free(responseData.resourceUri);
692 }
693
694 JNIEXPORT void JNICALL
695 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
696                                                          jint networkType)
697 {
698     LOGI("RMSelectNetwork Type : %d", networkType);
699
700     if (CA_STATUS_OK != CASelectNetwork(networkType))
701     {
702         LOGE("Could not select network");
703     }
704 }
705
706 JNIEXPORT void JNICALL
707 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
708                                                            jint networkType)
709 {
710     LOGI("RMUnSelectNetwork Type : %d", networkType);
711
712     if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
713     {
714         LOGE("Could not unselect network");
715     }
716 }
717
718 JNIEXPORT void JNICALL
719 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
720 {
721     LOGI("RMGetNetworkInfomation");
722
723     CAEndpoint_t *tempInfo = NULL;
724     uint32_t tempSize = 0;
725
726     CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
727     if (CA_STATUS_OK != res)
728     {
729         LOGE("Could not start get network information");
730         free(tempInfo);
731         return;
732     }
733
734     LOGI("################## Network Information #######################");
735     callback("######## Network Information", "#######");
736     LOGI("Network info total size is %d", tempSize);
737
738     uint32_t index;
739     for (index = 0; index < tempSize; index++)
740     {
741         res = get_remote_address(tempInfo[index].adapter, tempInfo[index].addr);
742         if (CA_STATUS_OK != res)
743         {
744             free(tempInfo);
745             return;
746         }
747         if (NULL != g_responseListenerObject)
748         {
749             char networkInfo[NETWORK_INFO_LENGTH];
750             LOGI("Type: %d", tempInfo[index].adapter);
751             sprintf(networkInfo, "%d",tempInfo[index].adapter);
752             callback("Type :", networkInfo);
753             if (CA_ADAPTER_IP == tempInfo[index].adapter)
754             {
755                 LOGI("Port: %d", tempInfo[index].port);
756                 sprintf(networkInfo, "%d",tempInfo[index].port);
757                 callback("Port: ", networkInfo);
758             }
759             LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
760             LOGI("Address: %s", g_remoteAddress);
761             callback("Address: ", g_remoteAddress);
762             free(g_remoteAddress);
763         }
764         if (tempInfo[index].flags & CA_SECURE)
765         {
766             g_localSecurePort = tempInfo[index].port;
767         }
768     }
769
770     // free
771     free(tempInfo);
772
773     LOGI("##############################################################");
774 }
775
776 JNIEXPORT void JNICALL
777 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
778 {
779     LOGI("RMHandleRequestResponse");
780
781     if (CA_STATUS_OK != CAHandleRequestResponse())
782     {
783         LOGE("Could not handle request and response");
784     }
785 }
786
787 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
788 {
789
790     if (!object)
791     {
792         LOGE("Remote endpoint is NULL!");
793         return;
794     }
795
796     if (!requestInfo)
797     {
798         LOGE("Request info is NULL!");
799         return;
800     }
801
802     if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
803             (strncmp(g_lastRequestToken, requestInfo->info.token,
804                      requestInfo->info.tokenLength) == 0))
805     {
806         LOGI("token is same. received request of it's own. skip.. ");
807         return;
808     }
809
810     CAResult_t res = get_remote_address(object->adapter, object->addr);
811     if (CA_STATUS_OK != res)
812     {
813         return;
814     }
815
816     LOGI("##########received request from remote device #############");
817     LOGI("Remote Address: %s", g_remoteAddress);
818     LOGI("Remote Port: %d", object->port);
819     LOGI("Uri: %s", requestInfo->info.resourceUri);
820     LOGI("Data: %s", requestInfo->info.payload);
821     LOGI("Token: %s", requestInfo->info.token);
822     LOGI("Code: %d", requestInfo->method);
823     LOGI("MessageType: %d", requestInfo->info.type);
824
825     if (NULL != g_responseListenerObject)
826     {
827         char *cloneUri = NULL;
828         uint32_t len = 0;
829
830         if (NULL != requestInfo->info.resourceUri)
831         {
832             len = strlen(requestInfo->info.resourceUri);
833             cloneUri = (char *)malloc(sizeof(char) * (len + 1));
834
835             if (NULL == cloneUri)
836             {
837                 LOGE("cloneUri Out of memory");
838                 free(g_remoteAddress);
839                 return;
840             }
841
842             memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
843             callback("Uri: ", cloneUri);
844         }
845
846         len = strlen(g_remoteAddress);
847         char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
848
849         if (NULL == cloneRemoteAddress)
850         {
851             LOGE("cloneRemoteAddress Out of memory");
852             free(g_remoteAddress);
853             free(cloneUri);
854             return;
855         }
856
857         memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
858
859         callback("Remote Address: ", cloneRemoteAddress);
860         free(cloneRemoteAddress);
861         free(g_remoteAddress);
862
863         char portInfo[PORT_LENGTH] = { 0, };
864         sprintf(portInfo, "%d", object->port);
865         callback("Remote Port: ", portInfo);
866
867         //clone g_clientEndpoint
868         g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
869         if (NULL == g_clientEndpoint)
870         {
871             LOGE("g_clientEndpoint Out of memory");
872             free(cloneUri);
873             return;
874         }
875         memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
876
877         if (NULL != cloneUri)
878         {
879             len = strlen(cloneUri);
880             g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
881             if (NULL == g_resourceUri)
882             {
883                 LOGE("g_clientEndpoint->resourceUri Out of memory");
884                 free(g_clientEndpoint);
885                 free(cloneUri);
886                 return;
887             }
888             memcpy(g_resourceUri, cloneUri, len + 1);
889             free(cloneUri);
890         }
891         //clone g_clientToken
892         len = requestInfo->info.tokenLength;
893
894         g_clientToken = (char *) malloc(sizeof(char) * len);
895         if (NULL == g_clientToken)
896         {
897             LOGE("g_clientToken Out of memory");
898             free(g_clientEndpoint);
899             return;
900         }
901
902         if (NULL != requestInfo->info.token)
903         {
904             memcpy(g_clientToken, requestInfo->info.token, len);
905             g_clientTokenLength = len;
906
907         }
908
909         //clone g_clientMsgId
910         g_clientMsgId = requestInfo->info.messageId;
911
912         if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
913         {
914             len = requestInfo->info.payloadSize;
915             char *clonePayload = (char *) malloc(len + 1);
916             if (NULL == clonePayload)
917             {
918                 LOGE("clonePayload Out of memory");
919                 free(g_clientEndpoint);
920                 return;
921             }
922
923             memcpy(clonePayload, requestInfo->info.payload, len);
924             clonePayload[len] = '\0';
925
926             callback("Data: ", clonePayload);
927             free(clonePayload);
928         }
929     }
930
931     if (requestInfo->info.options)
932     {
933         uint32_t len = requestInfo->info.numOptions;
934         uint32_t i;
935
936         LOGI("Option count: %d", requestInfo->info.numOptions);
937
938         for (i = 0; i < len; i++)
939         {
940             LOGI("Option %d", i + 1);
941             LOGI("ID : %d", requestInfo->info.options[i].optionID);
942             LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
943                  requestInfo->info.options[i].optionData);
944
945             if (NULL != g_responseListenerObject)
946             {
947                 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
948                 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
949                         requestInfo->info.options[i].optionID,
950                         requestInfo->info.options[i].optionLength);
951
952                 callback("Option info: ", optionInfo);
953
954                 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
955                 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
956                 if (NULL == cloneOptionData)
957                 {
958                     LOGE("cloneOptionData Out of memory");
959                     free(g_clientEndpoint);
960                     return;
961                 }
962
963                 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
964                        optionDataLen + 1);
965
966                 callback("Option Data: ", cloneOptionData);
967                 free(cloneOptionData);
968             }
969         }
970     }
971     LOGI("############################################################");
972
973     //Check if this has secure communication information
974     if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
975     {
976         uint32_t securePort = get_secure_information(requestInfo->info.payload);
977         if (0 < securePort) //Set the remote endpoint secure details and send response
978         {
979             LOGI("This is secure resource...");
980
981             CAEndpoint_t *endpoint = NULL;
982             if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
983                         object->adapter, object->addr, securePort, &endpoint))
984             {
985                 LOGE("Failed to create duplicate of remote endpoint!");
986                 return;
987             }
988             object = endpoint;
989         }
990     }
991 }
992
993 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
994 {
995
996     CAResult_t res = get_remote_address(object->adapter, object->addr);
997     if (CA_STATUS_OK != res)
998     {
999         return;
1000     }
1001
1002     LOGI("##########Received response from remote device #############");
1003     LOGI("Uri: %s", responseInfo->info.resourceUri);
1004     LOGI("Remote Address: %s", g_remoteAddress);
1005     LOGI("Remote Port: %d", object->port);
1006     LOGI("response result: %d", responseInfo->result);
1007     LOGI("Data: %s", responseInfo->info.payload);
1008     LOGI("Token: %s", responseInfo->info.token);
1009     LOGI("MessageType: %d", responseInfo->info.type);
1010
1011     if (NULL != g_responseListenerObject)
1012     {
1013         uint32_t len = 0;
1014
1015         if (NULL != responseInfo->info.resourceUri)
1016         {
1017             len = strlen(responseInfo->info.resourceUri);
1018             char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1019
1020             if (NULL == cloneUri)
1021             {
1022                 LOGE("cloneUri Out of memory");
1023                 free(g_remoteAddress);
1024                 return;
1025             }
1026
1027             memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1028
1029             callback("Uri: ", cloneUri);
1030             free(cloneUri);
1031         }
1032
1033         len = strlen(g_remoteAddress);
1034         char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1035
1036         if (NULL == cloneRemoteAddress)
1037         {
1038             LOGE("cloneRemoteAddress Out of memory");
1039             free(g_remoteAddress);
1040             return;
1041         }
1042
1043         memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1044
1045         callback("Remote Address: ", cloneRemoteAddress);
1046         free(cloneRemoteAddress);
1047         free(g_remoteAddress);
1048
1049         char portInfo[PORT_LENGTH] = { 0, };
1050         sprintf(portInfo, "%d", object->port);
1051         callback("Remote Port: ", portInfo);
1052
1053         if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1054         {
1055             len = responseInfo->info.payloadSize;
1056             char *clonePayload = (char *) malloc(len + 1);
1057             if (NULL == clonePayload)
1058             {
1059                 LOGE("clonePayload Out of memory");
1060                 return;
1061             }
1062
1063             memcpy(clonePayload, responseInfo->info.payload, len);
1064             clonePayload[len] = '\0';
1065
1066             callback("Data: ", clonePayload);
1067             free(clonePayload);
1068         }
1069     }
1070
1071     if (responseInfo->info.options)
1072     {
1073         uint32_t len = responseInfo->info.numOptions;
1074         uint32_t i;
1075         for (i = 0; i < len; i++)
1076         {
1077             LOGI("Option %d", i + 1);
1078             LOGI("ID : %d", responseInfo->info.options[i].optionID);
1079             LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1080                  responseInfo->info.options[i].optionData);
1081
1082             if (NULL != g_responseListenerObject)
1083             {
1084                 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1085                 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1086                         responseInfo->info.options[i].optionID,
1087                         responseInfo->info.options[i].optionLength);
1088
1089                 callback("Option info: ", optionInfo);
1090
1091                 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1092                 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1093                 if (NULL == cloneOptionData)
1094                 {
1095                     LOGE("cloneOptionData Out of memory");
1096                     return;
1097                 }
1098                 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1099                        optionDataLen + 1);
1100                 callback("Option Data: ", cloneOptionData);
1101                 free(cloneOptionData);
1102             }
1103         }
1104     }
1105     LOGI("############################################################");
1106
1107     //Check if this has secure communication information
1108     if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1109     {
1110         uint32_t securePort = get_secure_information(responseInfo->info.payload);
1111         if (0 < securePort) //Set the remote endpoint secure details and send response
1112         {
1113             LOGI("This is secure resource...");
1114         }
1115     }
1116 }
1117
1118 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1119 {
1120     printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1121
1122     if(errorInfo)
1123     {
1124         const CAInfo_t *info = &errorInfo->info;
1125         LOGI("Error Handler, ErrorInfo :");
1126         LOGI("Error Handler result    : %d", errorInfo->result);
1127         LOGI("Error Handler token     : %s", info->token);
1128         LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1129         LOGI("Error Handler resourceUri : %s", info->resourceUri);
1130         LOGI("Error Handler type      : %d", info->type);
1131         LOGI("Error Handler payload   : %s", info->payload);
1132
1133         if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1134         {
1135             LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1136         }
1137         else if(CA_SEND_FAILED == errorInfo->result)
1138         {
1139             LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1140         }
1141         else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1142         {
1143             LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1144         }
1145         else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1146         {
1147             LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1148         }
1149         else if(CA_STATUS_FAILED == errorInfo->result)
1150         {
1151             LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1152         }
1153     }
1154     LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1155
1156     return;
1157 }
1158
1159 void get_resource_uri(const char *URI, char *resourceURI, uint32_t length)
1160 {
1161     const char *startPos = URI;
1162     const char *temp = strstr(URI, "://");
1163     if (NULL != temp)
1164     {
1165         startPos = strchr(temp + 3, '/');
1166         if (!startPos)
1167         {
1168             LOGE("Resource URI is missing");
1169             return;
1170         }
1171     }
1172
1173     const char *endPos = strchr(startPos, '?');
1174     if (!endPos)
1175     {
1176         endPos = URI + strlen(URI);
1177     }
1178     --endPos;
1179
1180     if (endPos - startPos <= length)
1181     {
1182         memcpy(resourceURI, startPos + 1, endPos - startPos);
1183     }
1184
1185     LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1186 }
1187
1188 uint32_t get_secure_information(CAPayload_t payLoad)
1189 {
1190     LOGI("entering get_secure_information");
1191
1192     if (!payLoad)
1193     {
1194         LOGE("Payload is NULL");
1195         return -1;
1196     }
1197
1198     const char *subString = NULL;
1199     if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
1200     {
1201         LOGE("This is not secure resource");
1202         return -1;
1203     }
1204
1205     if (NULL == (subString = strstr(payLoad, "\"port\":")))
1206     {
1207         LOGE("This secure resource does not have port information");
1208         return -1;
1209     }
1210
1211     const char *startPos = strstr(subString, ":");
1212     if (!startPos)
1213     {
1214         LOGE("Parsing failed !");
1215         return -1;
1216     }
1217
1218     const char *endPos = strstr(startPos, "}");
1219     if (!endPos)
1220     {
1221         LOGE("Parsing failed !");
1222         return -1;
1223     }
1224
1225     char portStr[6] = { 0 };
1226     memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1227
1228     LOGI("secured port is: %s", portStr);
1229     return atoi(portStr);
1230 }
1231
1232 CAResult_t get_network_type(uint32_t selectedNetwork)
1233 {
1234
1235     uint32_t number = selectedNetwork;
1236
1237     if (!(number & 0xf))
1238     {
1239         return CA_NOT_SUPPORTED;
1240     }
1241     if (number & CA_ADAPTER_IP)
1242     {
1243         g_selectedNwType = CA_ADAPTER_IP;
1244         return CA_STATUS_OK;
1245     }
1246     if (number & CA_ADAPTER_RFCOMM_BTEDR)
1247     {
1248         g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1249         return CA_STATUS_OK;
1250     }
1251     if (number & CA_ADAPTER_GATT_BTLE)
1252     {
1253         g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1254         return CA_STATUS_OK;
1255     }
1256
1257     return CA_NOT_SUPPORTED;
1258 }
1259
1260 void callback(char *subject, char *receivedData)
1261 {
1262     JNIEnv* env = NULL;
1263     uint32_t status = (*g_jvm)->GetEnv(g_jvm, (void **) &env, JNI_VERSION_1_6);
1264     uint32_t res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1265
1266     jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1267     jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1268                                         "(Ljava/lang/String;Ljava/lang/String;)V");
1269
1270     jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1271     jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1272     (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1273
1274 }
1275
1276 CAResult_t get_remote_address(CATransportAdapter_t transportType, const char *address)
1277 {
1278     uint32_t len = strlen(address);
1279
1280     g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1281     if (NULL == g_remoteAddress)
1282     {
1283         LOGE("g_remoteAddress Out of memory");
1284         return CA_MEMORY_ALLOC_FAILED;
1285     }
1286
1287     memcpy(g_remoteAddress, address, len + 1);
1288
1289     return CA_STATUS_OK;
1290 }
1291
1292
1293 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1294 {
1295     if (NULL == uri || NULL == address)
1296     {
1297         LOGE("parameter is null");
1298         return;
1299     }
1300
1301     // parse uri
1302     // #1. check prefix
1303     uint8_t startIndex = 0;
1304     if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1305     {
1306         LOGI("uri has '%s' prefix", COAPS_PREFIX);
1307         startIndex = COAPS_PREFIX_LEN;
1308         *flags = CA_SECURE;
1309     }
1310     else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1311     {
1312         LOGI("uri has '%s' prefix", COAP_PREFIX);
1313         startIndex = COAP_PREFIX_LEN;
1314         *flags = CA_IPV4;
1315     }
1316
1317     // #2. copy uri for parse
1318     int32_t len = strlen(uri) - startIndex;
1319
1320     if (len <= 0)
1321     {
1322         LOGE("uri length is 0!");
1323         return;
1324     }
1325
1326     char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1327     if (NULL == cloneUri)
1328     {
1329         LOGE("Out of memory");
1330         return;
1331     }
1332
1333     memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1334     cloneUri[len] = '\0';
1335
1336     char *pAddress = cloneUri;
1337     char *pResourceUri = NULL;
1338
1339     int32_t i = 0;
1340     for (i = 0; i < len; i++)
1341     {
1342         if (cloneUri[i] == '/')
1343         {
1344             // separate
1345             cloneUri[i] = 0;
1346             pResourceUri = &cloneUri[i + 1];
1347             break;
1348         }
1349     }
1350     LOGI("pAddress : %s", pAddress);
1351
1352     int res = get_address_set(pAddress, address);
1353     if (res == -1)
1354     {
1355         LOGE("address parse error");
1356
1357         free(cloneUri);
1358         return;
1359     }
1360     return;
1361 }
1362
1363 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1364 {
1365     if (NULL == pAddress || NULL == outAddress)
1366     {
1367         LOGE("parameter is null");
1368         return -1;
1369     }
1370
1371     int32_t len = strlen(pAddress);
1372     int32_t isIp = 0;
1373     int32_t ipLen = 0;
1374
1375     int32_t i = 0;
1376     for (i = 0; i < len; i++)
1377     {
1378         if (pAddress[i] == '.')
1379         {
1380             isIp = 1;
1381         }
1382
1383         // found port number start index
1384         if (isIp && pAddress[i] == ':')
1385         {
1386             ipLen = i;
1387             break;
1388         }
1389     }
1390
1391     if (isIp)
1392     {
1393         if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1394         {
1395             strncpy(outAddress->ipAddress, pAddress, ipLen);
1396             outAddress->ipAddress[ipLen] = '\0';
1397         }
1398         else if (!ipLen && len < sizeof(outAddress->ipAddress))
1399         {
1400             strncpy(outAddress->ipAddress, pAddress, len);
1401             outAddress->ipAddress[len] = '\0';
1402         }
1403         else
1404         {
1405             LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1406             return -1;
1407         }
1408
1409         if (ipLen > 0)
1410         {
1411             outAddress->port = atoi(pAddress + ipLen + 1);
1412         }
1413     }
1414     else
1415     {
1416         strncpy(outAddress->ipAddress, pAddress, len);
1417         outAddress->ipAddress[len] = '\0';
1418     }
1419
1420     return isIp;
1421 }