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