0f4fc25ed2cf2f7652b17a19042ba82c8172e040
[platform/upstream/iotivity.git] / resource / csdk / connectivity / samples / linux / sample_main.c
1 /* ****************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <stdbool.h>
27
28 #include "cacommon.h"
29 #include "cainterface.h"
30 #include "oic_string.h"
31 #ifdef __WITH_DTLS__
32 #include "ocsecurityconfig.h"
33 #endif
34
35 #define MAX_BUF_LEN 1024
36 #define MAX_OPT_LEN 16
37
38 #define PORT_LENGTH 5
39
40 #define SECURE_DEFAULT_PORT 5684
41
42 #define RESOURCE_URI_LENGTH 14
43
44 #define SYSTEM_INVOKE_ERROR 127
45 #define SYSTEM_ERROR -1
46
47 #define BLOCK_SIZE(arg) (1 << ((arg) + 4))
48
49 /**
50  * @def RS_IDENTITY
51  * @brief
52  */
53 #define IDENTITY     ("1111111111111111")
54 /* @def RS_CLIENT_PSK
55  * @brief
56  */
57 #define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
58
59 int g_received;
60 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
61 CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
62 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
63
64 typedef struct
65 {
66     char ipAddress[CA_IPADDR_SIZE];
67     uint16_t port;
68 } addressSet_t;
69
70 char get_menu();
71 void process();
72 CAResult_t get_network_type();
73 CAResult_t get_input_data(char *buf, int32_t length);
74
75 bool select_payload_type();
76 CAPayload_t get_binary_payload(size_t *payloadLength);
77 bool read_file(const char* name, CAPayload_t* bytes, size_t* length);
78 void create_file(CAPayload_t bytes, size_t length);
79
80 void start_listening_server();
81 void start_discovery_server();
82 void send_request();
83 void send_request_all();
84 void send_notification();
85 void select_network();
86 void unselect_network();
87 void handle_request_response();
88 void get_network_info();
89 void send_secure_request();
90
91 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
92 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
93 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
94 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
95 void get_resource_uri(char *URI, char *resourceURI, int length);
96 int get_secure_information(CAPayload_t payLoad);
97 bool get_address_set(const char *pAddress, addressSet_t* outAddress);
98 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
99 CAHeaderOption_t* get_option_data(CAInfo_t* requestData);
100
101 static CAToken_t g_last_request_token = NULL;
102
103 static const char COAP_PREFIX[] =  "coap://";
104 static const char COAPS_PREFIX[] = "coaps://";
105 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
106 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
107
108 static const char SECURE_INFO_DATA[] =
109                                     "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
110                                      "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
111                                      "%d}}]}";
112 static const char NORMAL_INFO_DATA[] =
113                                     "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
114                                      "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
115
116 #ifdef __WITH_DTLS__
117 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
118
119 void clearDtlsCredentialInfo()
120 {
121     printf("clearDtlsCredentialInfo IN\n");
122     if (pskCredsBlob)
123     {
124         // Initialize sensitive data to zeroes before freeing.
125         if (pskCredsBlob->creds)
126         {
127             memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
128             free(pskCredsBlob->creds);
129         }
130
131         memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
132         free(pskCredsBlob);
133         pskCredsBlob = NULL;
134     }
135     printf("clearDtlsCredentialInfo OUT\n");
136 }
137
138 // Internal API. Invoked by CA stack to retrieve credentials from this module
139 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
140 {
141     printf("CAGetDtlsPskCredentials IN\n");
142     if(!credInfo)
143     {
144         printf("Invalid credential container");
145         return;
146     }
147
148     *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
149     if (NULL == *credInfo)
150     {
151         printf("Failed to allocate credential blob.");
152         return;
153     }
154
155     size_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
156     (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
157     if (NULL == (*credInfo)->creds)
158     {
159         printf("Failed to allocate credentials.");
160         free(*credInfo);
161         *credInfo = NULL;
162         return;
163     }
164
165     memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
166     (*credInfo)->num = pskCredsBlob->num;
167     memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
168
169     printf("CAGetDtlsPskCredentials OUT\n");
170 }
171
172
173 CAResult_t SetCredentials()
174 {
175     printf("SetCredentials IN\n");
176     pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
177     if (NULL == pskCredsBlob)
178     {
179         printf("Memory allocation failed!\n");
180         return CA_MEMORY_ALLOC_FAILED;
181      }
182     memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
183
184
185     pskCredsBlob->num = 1;
186
187     pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
188     if (NULL == pskCredsBlob->creds)
189     {
190         printf("Memory allocation failed!\n");
191         free(pskCredsBlob);
192         return CA_MEMORY_ALLOC_FAILED;
193     }
194
195     memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
196     memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
197
198     printf("SetCredentials OUT\n");
199     return CA_STATUS_OK;
200 }
201 #endif
202
203 int main()
204 {
205     int ret = system("clear");
206     // shell invoke error: 127, others: -1
207     if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
208     {
209         printf("Terminal Clear Error: %d\n", ret);
210         return -1;
211     }
212
213     printf("=============================================\n");
214     printf("\t\tsample main\n");
215     printf("=============================================\n");
216
217     CAResult_t res = CAInitialize();
218     if (CA_STATUS_OK != res)
219     {
220         printf("CAInitialize fail\n");
221         return -1;
222     }
223
224     /*
225     * Read DTLS PSK credentials from persistent storage and
226     * set in the OC stack.
227     */
228 #ifdef __WITH_DTLS__
229     res = SetCredentials();
230     if (CA_STATUS_OK != res)
231     {
232         printf("SetCredentials failed\n");
233         return -1;
234     }
235
236     res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
237     if (CA_STATUS_OK != res)
238     {
239         printf("Set credential handler fail\n");
240         return -1;
241     }
242 #endif
243
244     // set handler.
245     CARegisterHandler(request_handler, response_handler, error_handler);
246
247     process();
248
249     CADestroyToken(g_last_request_token);
250
251     g_last_request_token = NULL;
252
253     CATerminate();
254 #ifdef __WITH_DTLS__
255     clearDtlsCredentialInfo();
256 #endif
257     return 0;
258 }
259
260 void process()
261 {
262     while (1)
263     {
264         char menu = get_menu();
265
266         switch (menu)
267         {
268             case 'm': // menu
269             case 'M':
270                 break;
271
272             case 'q': // quit
273             case 'Q':
274                 printf("quit..!!\n");
275                 return;
276
277             case 's': // start server
278             case 'S':
279                 start_listening_server();
280                 break;
281
282             case 't': // send request
283             case 'T':
284                 send_request_all();
285                 break;
286
287             case 'c': // start client
288             case 'C':
289                 start_discovery_server();
290                 break;
291
292             case 'r': // send request
293             case 'R':
294                 send_request();
295                 break;
296
297             case 'b': // send notification
298             case 'B':
299                 send_notification();
300                 break;
301
302             case 'n': // select network
303             case 'N':
304                 select_network();
305                 break;
306
307             case 'x': // unselect network
308             case 'X':
309                 unselect_network();
310                 break;
311
312             case 'h': // handle request response
313             case 'H':
314                 handle_request_response();
315                 break;
316
317             case 'w':
318             case 'W':
319                 g_received = 0;
320                 start_discovery_server();
321                 send_secure_request();
322                 while (g_received == 0)
323                 {
324                     sleep(1);
325                     handle_request_response();
326                 }
327                 break;
328
329             case 'z':
330             case 'Z':
331                 start_listening_server();
332                 while (1)
333                 {
334                     sleep(1);
335                     handle_request_response();
336                 }
337                 break;
338
339             case 'g': // get network information
340             case 'G':
341                 get_network_info();
342                 break;
343
344             default:
345                 printf("not supported menu!!\n");
346                 break;
347         }
348     }
349 }
350
351 void start_listening_server()
352 {
353     printf("start listening server!!\n");
354
355     CAResult_t res = CAStartListeningServer();
356     if (CA_STATUS_OK != res)
357     {
358         printf("start listening server fail, error code : %d\n", res);
359     }
360     else
361     {
362         printf("start listening server success\n");
363     }
364 }
365
366 void start_discovery_server()
367 {
368     printf("start discovery client!!\n");
369
370     CAResult_t res = CAStartDiscoveryServer();
371     if (CA_STATUS_OK != res)
372     {
373         printf("start discovery client fail, error code : %d\n", res);
374     }
375     else
376     {
377         printf("start discovery client success\n");
378     }
379 }
380
381 bool select_payload_type()
382 {
383     char buf[MAX_BUF_LEN]={0};
384     printf("\n=============================================\n");
385     printf("Normal Payload  : 0\nBig Payload   : 1\n");
386     printf("select Payload type : ");
387
388     CAResult_t res = get_input_data(buf, sizeof(buf));
389     if (CA_STATUS_OK != res)
390     {
391         printf("Payload type selection error\n");
392         printf("Default: Using normal Payload\n");
393         return false;
394     }
395
396     return (buf[0] == '1') ? true : false;
397 }
398
399 CAPayload_t get_binary_payload(size_t *payloadLength)
400 {
401     CAPayload_t binaryPayload = NULL;
402     bool result = read_file("sample_input.txt", &binaryPayload, payloadLength);
403     if (false == result)
404     {
405         return NULL;
406     }
407
408     return binaryPayload;
409 }
410
411 void send_request()
412 {
413     CAResult_t res = get_network_type();
414     if (CA_STATUS_OK != res)
415     {
416         return;
417     }
418
419     printf("Do you want to send secure request ?.... enter (0/1): ");
420
421     char secureRequest[MAX_BUF_LEN] = {0};
422     if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
423     {
424         return;
425     }
426
427     if (strcmp(secureRequest, "1") == 0)
428     {
429         printf("Enter the URI like below....\n");
430         printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
431     }
432     else if (strcmp(secureRequest, "0") == 0)
433     {
434         printf("Enter the URI like below....\n");
435         printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
436         printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
437     }
438     else
439     {
440         printf("Input data is wrong value\n");
441         return;
442     }
443
444     char uri[MAX_BUF_LEN] = {'\0'};
445     if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
446     {
447         return;
448     }
449
450     // create remote endpoint
451     CAEndpoint_t *endpoint = NULL;
452     CATransportFlags_t flags;
453
454     printf("URI : %s\n", uri);
455     addressSet_t address = {{}, 0};
456     parsing_coap_uri(uri, &address, &flags);
457
458     res = CACreateEndpoint(flags, g_selected_nw_type,
459                            (const char*)address.ipAddress, address.port, &endpoint);
460     if (CA_STATUS_OK != res || !endpoint)
461     {
462         printf("Failed to create remote endpoint, error code : %d\n", res);
463         return;
464     }
465
466     printf("\n=============================================\n");
467     printf("0:CON, 1:NON\n");
468     printf("select message type : ");
469
470     char buf[MAX_BUF_LEN] = { 0 };
471     if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
472     {
473         CADestroyEndpoint(endpoint);
474         return;
475     }
476
477     CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
478
479     // create token
480     CAToken_t token = NULL;
481     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
482
483     res = CAGenerateToken(&token, tokenLength);
484     if ((CA_STATUS_OK != res) || (!token))
485     {
486         printf("Token generate error, error code : %d\n", res);
487         CADestroyEndpoint(endpoint);
488         return;
489     }
490
491     printf("Generated token %s\n", token);
492
493     // extract relative resourceuri from give uri
494     char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
495     get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
496     printf("resourceURI : %s\n", resourceURI);
497
498     // create request data
499     CAInfo_t requestData = { .type = msgType,
500                              .messageId = 0,
501                              .token = token,
502                              .tokenLength = tokenLength,
503                              .options = NULL,
504                              .numOptions = 0,
505                              .payload = NULL,
506                              .payloadSize = 0,
507                              .resourceUri = (CAURI_t)resourceURI };
508
509     if (strcmp(secureRequest, "1") == 0)
510     {
511         size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
512         requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
513         if (NULL == requestData.payload)
514         {
515             printf("Memory allocation fail\n");
516             CADestroyEndpoint(endpoint);
517             CADestroyToken(token);
518             return;
519         }
520         snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
521                  (const char *) resourceURI, g_local_secure_port);
522         requestData.payloadSize = length;
523     }
524     else
525     {
526         bool useBigPayload = select_payload_type();
527         if (useBigPayload)
528         {
529             size_t payloadLength = 0;
530             CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
531             if (!binaryPayload)
532             {
533                 free(binaryPayload);
534                 CADestroyToken(token);
535                 CADestroyEndpoint(endpoint);
536                 return;
537             }
538
539             requestData.payload = (CAPayload_t) malloc(payloadLength);
540             if (NULL == requestData.payload)
541             {
542                 printf("Memory allocation failed!");
543                 free(binaryPayload);
544                 CADestroyToken(token);
545                 CADestroyEndpoint(endpoint);
546                 return;
547             }
548             memcpy(requestData.payload, binaryPayload, payloadLength);
549             requestData.payloadSize = payloadLength;
550
551             // memory free
552             free(binaryPayload);
553         }
554         else
555         {
556             size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
557             requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
558             if (NULL == requestData.payload)
559             {
560                 printf("Memory allocation fail\n");
561                 CADestroyEndpoint(endpoint);
562                 CADestroyToken(token);
563                 return;
564             }
565             snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
566                      (const char *) resourceURI);
567             requestData.payloadSize = length;
568         }
569     }
570
571     CAHeaderOption_t* headerOpt = get_option_data(&requestData);
572
573     CARequestInfo_t requestInfo = { .method = CA_GET,
574                                     .info = requestData,
575                                     .isMulticast = false };
576
577     // send request
578     res = CASendRequest(endpoint, &requestInfo);
579     if (CA_STATUS_OK != res)
580     {
581         printf("Could not send request : %d\n", res);
582     }
583
584     if (headerOpt)
585     {
586         free(headerOpt);
587     }
588
589     //destroy token
590     CADestroyToken(token);
591     // destroy remote endpoint
592     CADestroyEndpoint(endpoint);
593     free(requestData.payload);
594
595     printf("=============================================\n");
596 }
597
598 void send_secure_request()
599 {
600     char uri[MAX_BUF_LEN];
601     char ipv4addr[CA_IPADDR_SIZE];
602
603     printf("\n=============================================\n");
604     printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
605
606     if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
607     {
608         return;
609     }
610     snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);
611
612     // create remote endpoint
613     CAEndpoint_t *endpoint = NULL;
614     CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
615     if (CA_STATUS_OK != res)
616     {
617         printf("Failed to create remote endpoint, error code: %d\n", res);
618         goto exit;
619     }
620
621     // create token
622     CAToken_t token = NULL;
623     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
624
625     res = CAGenerateToken(&token, tokenLength);
626     if (CA_STATUS_OK != res)
627     {
628         printf("Token generate error, error code : %d\n", res);
629         goto exit;
630     }
631
632     printf("Generated token %s\n", token);
633
634     // create request data
635     CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
636                              .messageId = 0,
637                              .token = token,
638                              .tokenLength = tokenLength,
639                              .options = NULL,
640                              .numOptions = 0,
641                              .payload = NULL,
642                              .payloadSize = 0,
643                              .resourceUri = NULL };
644
645     CARequestInfo_t requestInfo = { .method = CA_GET,
646                                     .info = requestData,
647                                     .isMulticast = false };
648
649     // send request
650     CASendRequest(endpoint, &requestInfo);
651
652 exit:
653     // cleanup
654     CADestroyToken(token);
655     CADestroyEndpoint(endpoint);
656     printf("=============================================\n");
657 }
658
659
660 void send_request_all()
661 {
662     CAResult_t res = get_network_type();
663     if (CA_STATUS_OK != res)
664     {
665         return;
666     }
667
668     printf("\n=============================================\n");
669     printf("ex) /a/light\n");
670     printf("resource uri : ");
671
672     char resourceURI[MAX_BUF_LEN] = { 0 };
673     if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
674     {
675         return;
676     }
677
678     // create remote endpoint
679     CAEndpoint_t *group = NULL;
680     res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &group);
681     if (CA_STATUS_OK != res)
682     {
683         printf("Create remote endpoint error, error code: %d\n", res);
684         return;
685     }
686
687     // create token
688     CAToken_t token = NULL;
689     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
690
691     res = CAGenerateToken(&token, tokenLength);
692     if ((CA_STATUS_OK != res) || (!token))
693     {
694         printf("Token generate error!!\n");
695         CADestroyEndpoint(group);
696         return;
697     }
698
699     printf("generated token %s\n", token);
700
701     // create request data
702     CAPayload_t payload = (CAPayload_t) "TempJsonPayload";
703     size_t payloadSize = strlen((const char *) payload);
704
705     CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
706                              .messageId = 0,
707                              .token = token,
708                              .tokenLength = tokenLength,
709                              .options = NULL,
710                              .numOptions = 0,
711                              .payload = payload,
712                              .payloadSize = payloadSize,
713                              .resourceUri = (CAURI_t) resourceURI };
714
715     CARequestInfo_t requestInfo = { .method = CA_GET,
716                                     .info = requestData,
717                                     .isMulticast = true };
718
719     CAHeaderOption_t* headerOpt = get_option_data(&requestData);
720
721     // send request
722     res = CASendRequest(group, &requestInfo);
723     if (CA_STATUS_OK != res)
724     {
725         printf("Could not send request to all\n");
726         CADestroyToken(token);
727     }
728     else
729     {
730         CADestroyToken(g_last_request_token);
731         g_last_request_token = token;
732     }
733
734     if (headerOpt)
735     {
736         free(headerOpt);
737     }
738
739     // destroy remote endpoint
740     CADestroyEndpoint(group);
741
742     printf("=============================================\n");
743 }
744
745 void send_notification()
746 {
747     CAResult_t res = get_network_type();
748     if (CA_STATUS_OK != res)
749     {
750         return;
751     }
752
753     printf("\n=============================================\n");
754     printf("Enter the URI like below....\n");
755     printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
756     printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
757     printf("uri : ");
758
759     char uri[MAX_BUF_LEN] = { 0 };
760     if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
761     {
762         return;
763     }
764
765     printf("\n=============================================\n");
766     printf("\tselect message type\n");
767     printf("CON     : 0\n");
768     printf("NON     : 1\n");
769     printf("ACK     : 2\n");
770     printf("RESET   : 3\n");
771     printf("select : ");
772
773     char messageTypeBuf[MAX_BUF_LEN] = { 0 };
774     if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
775     {
776         return;
777     }
778
779     int messageType = messageTypeBuf[0] - '0';
780
781     CATransportFlags_t flags;
782     addressSet_t address = {{}, 0};
783     parsing_coap_uri(uri, &address, &flags);
784
785     // create remote endpoint
786     CAEndpoint_t *endpoint = NULL;
787     res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
788     if (CA_STATUS_OK != res)
789     {
790         printf("Create remote endpoint error, error code: %d\n", res);
791         return;
792     }
793
794     // create token
795     CAToken_t token = NULL;
796     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
797
798     res = CAGenerateToken(&token, tokenLength);
799     if ((CA_STATUS_OK != res) || (!token))
800     {
801         printf("Token generate error!!\n");
802         CADestroyEndpoint(endpoint);
803         return;
804     }
805
806     printf("Generated token %s\n", token);
807
808     // create response data
809     CAPayload_t payload = (CAPayload_t) "TempNotificationData";
810     size_t payloadSize = strlen((const char *) payload);
811
812     CAInfo_t respondData = { .type = messageType,
813                              .messageId = 0,
814                              .token = token,
815                              .tokenLength = tokenLength,
816                              .options = NULL,
817                              .numOptions = 0,
818                              .payload = payload,
819                              .payloadSize = payloadSize,
820                              .resourceUri = (CAURI_t)uri };
821
822     CAResponseInfo_t responseInfo = { .result = CA_CONTENT,
823                                       .info = respondData };
824
825     // send request
826     res = CASendNotification(endpoint, &responseInfo);
827     if (CA_STATUS_OK != res)
828     {
829         printf("Send notification error, error code: %d\n", res);
830     }
831     else
832     {
833         printf("Send notification success\n");
834     }
835
836     // destroy token
837     CADestroyToken(token);
838     // destroy remote endpoint
839     CADestroyEndpoint(endpoint);
840
841     printf("\n=============================================\n");
842 }
843
844 void select_network()
845 {
846     printf("\n=============================================\n");
847     printf("\tselect network\n");
848     printf("IP     : 0\n");
849     printf("GATT   : 1\n");
850     printf("RFCOMM : 2\n");
851     printf("select : ");
852
853     char buf[MAX_BUF_LEN] = { 0 };
854     if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
855     {
856         return;
857     }
858
859     int number = buf[0] - '0';
860
861     if (number < 0 || number > 3)
862     {
863         printf("Invalid network type\n");
864         return;
865     }
866
867     CAResult_t res = CASelectNetwork(1 << number);
868     if (CA_STATUS_OK != res)
869     {
870         printf("Select network error\n");
871     }
872     else
873     {
874         printf("Select network success\n");
875     }
876
877     printf("=============================================\n");
878 }
879
880 void unselect_network()
881 {
882     printf("\n=============================================\n");
883     printf("\tunselect enabled network\n");
884     printf("IP     : 0\n");
885     printf("GATT   : 1\n");
886     printf("RFCOMM : 2\n");
887     printf("select : ");
888
889     char buf[MAX_BUF_LEN] = { 0 };
890     if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
891     {
892         return;
893     }
894
895     int number = buf[0] - '0';
896
897     if (number < 0 || number > 3)
898     {
899         printf("Invalid network type\n");
900         return;
901     }
902
903     CAResult_t res = CAUnSelectNetwork(1 << number);
904     if (CA_STATUS_OK != res)
905     {
906         printf("Unselect network error\n");
907     }
908     else
909     {
910         printf("Unselect network success\n");
911     }
912
913     printf("=============================================\n");
914 }
915
916 char get_menu()
917 {
918     printf("\n=============================================\n");
919     printf("\t\tMenu\n");
920     printf("\ts : start server\n");
921     printf("\tc : start client\n");
922     printf("\tr : send request\n");
923     printf("\tt : send request to all\n");
924     printf("\tb : send notification\n");
925     printf("\tn : select network\n");
926     printf("\tx : unselect network\n");
927     printf("\tg : get network information\n");
928     printf("\th : handle request response\n");
929     printf("\tz : run static server\n");
930     printf("\tw : send secure request\n");
931     printf("\tq : quit\n");
932     printf("=============================================\n");
933     printf("select : ");
934
935     char buf[MAX_BUF_LEN] = { 0 };
936     if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
937     {
938         printf("Failed to get input data\n");
939     }
940
941     return buf[0];
942 }
943
944 void handle_request_response()
945 {
946     printf("Handle_request_response\n");
947
948     CAResult_t res = CAHandleRequestResponse();
949     if (CA_STATUS_OK != res)
950     {
951         printf("Handle request error, error code: %d\n", res);
952     }
953     else
954     {
955         printf("Handle request success\n");
956     }
957 }
958
959 void get_network_info()
960 {
961     CAEndpoint_t *tempInfo = NULL;
962     uint32_t tempSize = 0;
963
964     CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
965     if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
966     {
967         printf("Network not connected\n");
968         free(tempInfo);
969         return;
970     }
971
972     printf("################## Network Information #######################\n");
973     printf("Network info total size is %d\n\n", tempSize);
974
975     for (uint32_t index = 0; index  < tempSize; index++)
976     {
977         printf("Type: %d\n", tempInfo[index].adapter);
978         printf("Address: %s\n", tempInfo[index].addr);
979         if (CA_ADAPTER_IP == tempInfo[index].adapter)
980         {
981             printf("Port: %d\n", tempInfo[index].port);
982         }
983         printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
984
985         if (tempInfo[index].flags & CA_SECURE)
986         {
987             g_local_secure_port = tempInfo[index].port;
988             printf("Secured: in global %d\n\n", g_local_secure_port);
989         }
990     }
991
992     free(tempInfo);
993     printf("##############################################################");
994 }
995
996 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
997 {
998     if (NULL == object || NULL == requestInfo)
999     {
1000         printf("Input parameter is NULL\n");
1001         return;
1002     }
1003
1004     if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
1005         && (memcmp(g_last_request_token, requestInfo->info.token,
1006                    CA_MAX_TOKEN_LEN) == 0))
1007     {
1008         printf("token is same. received request of it's own. skip.. \n");
1009         return;
1010     }
1011
1012     printf("##########received request from remote device #############\n");
1013     if (CA_ADAPTER_IP == object->adapter)
1014     {
1015         printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1016                object->port, object->flags & CA_SECURE);
1017     }
1018     else
1019     {
1020         printf("Remote Address: %s \n", object->addr);
1021     }
1022     printf("Data: %s\n", requestInfo->info.payload);
1023     printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
1024
1025     if (requestInfo->info.options)
1026     {
1027         uint32_t len = requestInfo->info.numOptions;
1028         uint32_t i;
1029         for (i = 0; i < len; i++)
1030         {
1031             printf("Option %d\n", i + 1);
1032             printf("ID : %d\n", requestInfo->info.options[i].optionID);
1033             printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1034                    requestInfo->info.options[i].optionData);
1035         }
1036     }
1037     printf("############################################################\n");
1038
1039     //Check if this has secure communication information
1040     if (requestInfo->info.payload &&
1041             (CA_ADAPTER_IP == object->adapter))
1042     {
1043         int securePort = get_secure_information(requestInfo->info.payload);
1044         if (0 < securePort) //Set the remote endpoint secure details and send response
1045         {
1046             printf("This is secure resource...\n");
1047
1048             CAEndpoint_t *endpoint = NULL;
1049             if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1050                                                  object->port, &endpoint))
1051             {
1052                 printf("Failed to create duplicate of remote endpoint!\n");
1053                 return;
1054             }
1055             endpoint->flags = CA_SECURE;
1056             object = endpoint;
1057         }
1058     }
1059
1060     // if received message is bulk data, create output file
1061     if ((requestInfo->info.payload) &&
1062             (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1063     {
1064         create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
1065     }
1066
1067     printf("Send response with URI\n");
1068     send_response(object, &requestInfo->info);
1069
1070     g_received = 1;
1071 }
1072
1073 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1074 {
1075     printf("##########Received response from remote device #############\n");
1076     if (CA_ADAPTER_IP == object->adapter)
1077     {
1078         printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1079                object->port, object->flags & CA_SECURE);
1080     }
1081     else
1082     {
1083         printf("Remote Address: %s \n", object->addr);
1084     }
1085     printf("response result : %d\n", responseInfo->result);
1086     printf("Data: %s\n", responseInfo->info.payload);
1087     printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1088     printf("Token: %s\n", responseInfo->info.token);
1089     if (responseInfo->info.options)
1090     {
1091         uint32_t len = responseInfo->info.numOptions;
1092         uint32_t i;
1093         for (i = 0; i < len; i++)
1094         {
1095             printf("Option %d\n", i + 1);
1096             printf("ID : %d\n", responseInfo->info.options[i].optionID);
1097             printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1098                    responseInfo->info.options[i].optionData);
1099         }
1100     }
1101     printf("############################################################\n");
1102     g_received = 1;
1103
1104     //Check if this has secure communication information
1105     if (responseInfo->info.payload)
1106     {
1107         int securePort = get_secure_information(responseInfo->info.payload);
1108         if (0 < securePort) //Set the remote endpoint secure details and send response
1109         {
1110             printf("This is secure resource...\n");
1111         }
1112     }
1113
1114     // if received message is bulk data, create output file
1115     if ((responseInfo->info.payload) &&
1116             (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1117     {
1118         create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
1119     }
1120 }
1121
1122 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1123 {
1124     (void)rep;
1125     printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1126
1127     if(errorInfo)
1128     {
1129         const CAInfo_t *info = &errorInfo->info;
1130         printf("Error Handler, ErrorInfo :\n");
1131         printf("Error Handler result    : %d\n", errorInfo->result);
1132         printf("Error Handler token     : %s\n", info->token);
1133         printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1134         printf("Error Handler type      : %d\n", info->type);
1135         printf("Error Handler resourceUri : %s\n", info->resourceUri);
1136         printf("Error Handler payload   : %s\n", info->payload);
1137
1138         if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1139         {
1140             printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1141         }
1142         else if(CA_SEND_FAILED == errorInfo->result)
1143         {
1144             printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1145         }
1146         else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1147         {
1148             printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1149         }
1150         else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1151         {
1152             printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1153         }
1154         else if(CA_STATUS_FAILED == errorInfo->result)
1155         {
1156             printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1157         }
1158     }
1159     printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1160
1161     return;
1162 }
1163
1164 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1165 {
1166     printf("entering send_response\n");
1167
1168     printf("\n=============================================\n");
1169     printf("\tselect message type\n");
1170     printf("CON     : 0\n");
1171     printf("NON     : 1\n");
1172     printf("ACK     : 2\n");
1173     printf("RESET   : 3\n");
1174     printf("select : ");
1175
1176     char buf[MAX_BUF_LEN] = { 0 };
1177     if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1178     {
1179         return;
1180     }
1181
1182     int messageType = buf[0] - '0';
1183     if (0 > messageType || 3 < messageType)
1184     {
1185         printf("Invalid message type\n");
1186         return;
1187     }
1188
1189     int responseCode = 0 ;
1190     char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1191     if (CA_MSG_RESET != messageType)
1192     {
1193         printf("\n=============================================\n");
1194         printf("\tselect response code\n");
1195         printf("EMPTY                    :   0\n");
1196         printf("SUCCESS                  : 200\n");
1197         printf("CREATED                  : 201\n");
1198         printf("DELETED                  : 202\n");
1199         printf("VALID                    : 203\n");
1200         printf("CHANGED                  : 204\n");
1201         printf("CONTENT                  : 205\n");
1202         printf("BAD_REQ                  : 400\n");
1203         printf("BAD_OPT                  : 402\n");
1204         printf("NOT_FOUND                : 404\n");
1205         printf("INTERNAL_SERVER_ERROR    : 500\n");
1206         printf("RETRANSMIT_TIMEOUT       : 504\n");
1207         printf("select : ");
1208
1209         if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1210         {
1211             return;
1212         }
1213         responseCode = atoi(responseCodeBuf);
1214     }
1215
1216     // create response data
1217     uint16_t messageId = (info != NULL) ? info->messageId : 0;
1218     CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;
1219
1220     CAInfo_t responseData = { .type = messageType,
1221                               .messageId = messageId,
1222                               .token = NULL,
1223                               .tokenLength = 0,
1224                               .options = NULL,
1225                               .numOptions = 0,
1226                               .payload = NULL,
1227                               .payloadSize = 0,
1228                               .resourceUri = resourceUri };
1229
1230     if(CA_MSG_RESET != messageType)
1231     {
1232         responseData.token = (info != NULL) ? info->token : NULL;
1233         responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1234
1235         if (endpoint->flags & CA_SECURE)
1236         {
1237             if(!responseData.resourceUri)
1238             {
1239                printf("resourceUri not available in SECURE\n");
1240                return;
1241             }
1242             printf("Sending response on secure communication\n");
1243
1244             uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
1245             responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
1246             if (NULL == responseData.payload)
1247             {
1248                 printf("Memory allocation fail\n");
1249                 return;
1250             }
1251             snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1252                      (const char *) responseData.resourceUri, g_local_secure_port);
1253             responseData.payloadSize = length;
1254         }
1255         else
1256         {
1257             printf("Sending response on non-secure communication\n");
1258
1259             bool useBigPayload = select_payload_type();
1260             if (useBigPayload)
1261             {
1262                 size_t payloadLength = 0;
1263                 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
1264                 if (NULL == binaryPayload)
1265                 {
1266                     free(binaryPayload);
1267                     return;
1268                 }
1269
1270                 responseData.payload = (CAPayload_t) malloc(payloadLength);
1271                 if (NULL == responseData.payload)
1272                 {
1273                     printf("Memory allocation failed!");
1274                     free(binaryPayload);
1275                     return;
1276                 }
1277                 memcpy(responseData.payload, binaryPayload, payloadLength);
1278                 responseData.payloadSize = payloadLength;
1279
1280                 // memory free
1281                 free(binaryPayload);
1282             }
1283             else
1284             {
1285                 if(!responseData.resourceUri)
1286                 {
1287                    printf("resourceUri not available in NON-SECURE\n");
1288                    return;
1289                 }
1290                 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1291                 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1292                 if (NULL == responseData.payload)
1293                 {
1294                     printf("Memory allocation fail\n");
1295                     return;
1296                 }
1297                 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1298                          (const char *) responseData.resourceUri);
1299                 responseData.payloadSize = length;
1300             }
1301         }
1302     }
1303
1304     CAResponseInfo_t responseInfo = { .result = responseCode,
1305                                       .info = responseData };
1306
1307     // send response (transportType from remoteEndpoint of request Info)
1308     CAResult_t res = CASendResponse(endpoint, &responseInfo);
1309     if (CA_STATUS_OK != res)
1310     {
1311         printf("Send response error\n");
1312     }
1313     else
1314     {
1315         printf("Send response success\n");
1316     }
1317
1318     if (responseData.payload)
1319     {
1320         free(responseData.payload);
1321     }
1322
1323     printf("=============================================\n");
1324 }
1325
1326 int get_secure_information(CAPayload_t payLoad)
1327 {
1328     printf("Entering get_secure_information\n");
1329
1330     if (!payLoad)
1331     {
1332         printf("Payload is NULL\n");
1333         return -1;
1334     }
1335
1336     char *subString = NULL;
1337     if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1338     {
1339         printf("This is not secure resource\n");
1340         return -1;
1341     }
1342
1343     if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1344     {
1345         printf("This secure resource does not have port information\n");
1346         return -1;
1347     }
1348
1349     char *startPos = strstr(subString, ":");
1350     if (!startPos)
1351     {
1352         printf("Parsing failed !\n");
1353         return -1;
1354     }
1355
1356     char *endPos = strstr(startPos, "}");
1357     if (!endPos)
1358     {
1359         printf("Parsing failed !\n");
1360         return -1;
1361     }
1362
1363     char portStr[6] = {0};
1364     OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
1365     printf("secured port is: %s\n", portStr);
1366     return atoi(portStr);
1367 }
1368
1369 void get_resource_uri(char *URI, char *resourceURI, int length)
1370 {
1371     char *startPos = URI;
1372     char *temp = NULL;
1373     if (NULL != (temp = strstr(URI, "://")))
1374     {
1375         startPos = strchr(temp + 3, '/');
1376         if (!startPos)
1377         {
1378             printf("Resource URI is missing\n");
1379             return;
1380         }
1381     }
1382
1383     char *endPos = strchr(startPos, '?');
1384     if (!endPos)
1385     {
1386         endPos = URI + strlen(URI);
1387     }
1388     endPos -= 1;
1389
1390     if (endPos - startPos <= length)
1391     {
1392         OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos);
1393     }
1394
1395     printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1396 }
1397
1398 CAResult_t get_network_type()
1399 {
1400     char buf[MAX_BUF_LEN] = { 0 };
1401
1402     printf("\n=============================================\n");
1403     printf("\tselect network type\n");
1404     printf("IP     : 0\n");
1405     printf("GATT   : 1\n");
1406     printf("RFCOMM : 2\n");
1407     printf("select : ");
1408
1409     if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1410     {
1411         return CA_NOT_SUPPORTED ;
1412     }
1413
1414     int number = buf[0] - '0';
1415
1416     number = (number < 0 || number > 3) ? 0 : 1 << number;
1417
1418     if (number == 1)
1419     {
1420         g_selected_nw_type = CA_ADAPTER_IP;
1421         return CA_STATUS_OK;
1422     }
1423     if (number == 2)
1424     {
1425         g_selected_nw_type = CA_ADAPTER_GATT_BTLE;
1426         return CA_STATUS_OK;
1427     }
1428     if (number == 3)
1429     {
1430         g_selected_nw_type = CA_ADAPTER_RFCOMM_BTEDR;
1431         return CA_STATUS_OK;
1432     }
1433
1434     return CA_NOT_SUPPORTED;
1435 }
1436
1437 CAResult_t get_input_data(char *buf, int32_t length)
1438 {
1439     if (!fgets(buf, length, stdin))
1440     {
1441         printf("fgets error\n");
1442         return CA_STATUS_FAILED;
1443     }
1444
1445     char *p = NULL;
1446     if ( (p = strchr(buf, '\n')) != NULL )
1447     {
1448         *p = '\0';
1449     }
1450
1451     return CA_STATUS_OK;
1452 }
1453
1454 CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
1455 {
1456     char optionNumBuf[MAX_BUF_LEN] = { 0 };
1457     char optionData[MAX_OPT_LEN] = { 0 } ;
1458
1459     printf("Option Num : ");
1460     if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
1461     {
1462         return NULL;
1463     }
1464     int optionNum = atoi(optionNumBuf);
1465
1466     CAHeaderOption_t * headerOpt = NULL;
1467     if (0 >= optionNum)
1468     {
1469         printf("there is no headerOption!\n");
1470         return NULL;
1471     }
1472     else if (optionNum > MAX_OPT_LEN)
1473     {
1474         printf("Too many header options!\n");
1475         return NULL;
1476     }
1477     else
1478     {
1479         headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
1480         if (NULL == headerOpt)
1481         {
1482             printf("Memory allocation failed!\n");
1483             return NULL;
1484         }
1485
1486         int i;
1487         for (i = 0; i < optionNum; i++)
1488         {
1489             char getOptionID[MAX_BUF_LEN] = { 0 } ;
1490
1491             printf("[%d] Option ID : ", i + 1);
1492             if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
1493             {
1494                 free(headerOpt);
1495                 return NULL;
1496             }
1497             int optionID = atoi(getOptionID);
1498             headerOpt[i].optionID = optionID;
1499
1500             printf("[%d] Option Data : ", i + 1);
1501             if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
1502             {
1503                 free(headerOpt);
1504                 return NULL;
1505             }
1506
1507             OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);
1508
1509             headerOpt[i].optionLength = (uint16_t) strlen(optionData);
1510         }
1511         requestData->numOptions = optionNum;
1512         requestData->options = headerOpt;
1513     }
1514     return headerOpt;
1515 }
1516
1517 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1518 {
1519     if (NULL == uri)
1520     {
1521         printf("parameter is null\n");
1522         return;
1523     }
1524
1525     // parse uri
1526     // #1. check prefix
1527     uint8_t startIndex = 0;
1528     if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1529     {
1530         printf("uri has '%s' prefix\n", COAPS_PREFIX);
1531         startIndex = COAPS_PREFIX_LEN;
1532         *flags = CA_SECURE;
1533     }
1534     else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1535     {
1536         printf("uri has '%s' prefix\n", COAP_PREFIX);
1537         startIndex = COAP_PREFIX_LEN;
1538         *flags = CA_IPV4;
1539     }
1540
1541     // #2. copy uri for parse
1542     int32_t len = strlen(uri) - startIndex;
1543
1544     if (len <= 0)
1545     {
1546         printf("uri length is 0!\n");
1547         return;
1548     }
1549
1550     char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1551     if (NULL == cloneUri)
1552     {
1553         printf("Out of memory\n");
1554         return;
1555     }
1556
1557     memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1558     cloneUri[len] = '\0';
1559
1560     char *pAddress = cloneUri;
1561     printf("pAddress : %s\n", pAddress);
1562
1563     if (!get_address_set(pAddress, address))
1564     {
1565         printf("address parse error\n");
1566
1567         free(cloneUri);
1568         return;
1569     }
1570     free(cloneUri);
1571     return;
1572 }
1573
1574 bool get_address_set(const char *pAddress, addressSet_t* outAddress)
1575 {
1576     if (NULL == pAddress)
1577     {
1578         printf("parameter is null !\n");
1579         return false;
1580     }
1581
1582     size_t len = strlen(pAddress);
1583     bool isIp = false;
1584     size_t ipLen = 0;
1585
1586     for (size_t i = 0; i < len; i++)
1587     {
1588         if (pAddress[i] == '.')
1589         {
1590             isIp = true;
1591         }
1592
1593         // found port number start index
1594         if (isIp && pAddress[i] == ':')
1595         {
1596             ipLen = i;
1597             break;
1598         }
1599     }
1600
1601     if (isIp)
1602     {
1603         if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1604         {
1605             OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1606                              pAddress, ipLen);
1607         }
1608         else if (!ipLen && len < sizeof(outAddress->ipAddress))
1609         {
1610             OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1611                              pAddress, len);
1612         }
1613         else
1614         {
1615             printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen);
1616             return false;
1617         }
1618
1619         if (ipLen > 0)
1620         {
1621             outAddress->port = atoi(pAddress + ipLen + 1);
1622         }
1623         return true;
1624     }
1625     else
1626     {
1627         return false;
1628     }
1629 }
1630
1631 void create_file(CAPayload_t bytes, size_t length)
1632 {
1633     FILE *fp = fopen("sample_output.txt", "wb");
1634     if (fp)
1635     {
1636         fwrite(bytes, 1, length, fp);
1637         fclose(fp);
1638     }
1639 }
1640
1641 bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
1642 {
1643     if (NULL == name)
1644     {
1645         printf("parameter is null\n");
1646         return false;
1647     }
1648
1649     FILE* file = NULL;
1650     CAPayload_t buffer = NULL;
1651     unsigned long fileLen = 0;
1652
1653     // Open file
1654     file = fopen(name, "rb");
1655     if (!file)
1656     {
1657         fprintf(stderr, "Unable to open file, %s\n", name);
1658         return false;
1659     }
1660
1661     // Get file length
1662     fseek(file, 0, SEEK_END);
1663     fileLen = ftell(file);
1664     fseek(file, 0, SEEK_SET);
1665
1666     // Allocate memory
1667     buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
1668     if (!buffer)
1669     {
1670         fprintf(stderr, "Memory error\n");
1671         fclose(file);
1672         return false;
1673     }
1674
1675     // Read file contents into buffer
1676     size_t ret = fread(buffer, fileLen, 1, file);
1677     if (ret != 1)
1678     {
1679         printf("Failed to read data from file, %s\n", name);
1680         fclose(file);
1681         free(buffer);
1682         return false;
1683     }
1684
1685     fclose(file);
1686
1687     *bytes = buffer;
1688     *length = fileLen;
1689
1690     return true;
1691 }