Imported Upstream version 1.0.0
[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
998     if (requestInfo->info.options)
999     {
1000         uint32_t len = requestInfo->info.numOptions;
1001         uint32_t i;
1002         for (i = 0; i < len; i++)
1003         {
1004             printf("Option %d\n", i + 1);
1005             printf("ID : %d\n", requestInfo->info.options[i].optionID);
1006             printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1007                    requestInfo->info.options[i].optionData);
1008         }
1009     }
1010     printf("############################################################\n");
1011
1012     //Check if this has secure communication information
1013     if (requestInfo->info.payload &&
1014             (CA_ADAPTER_IP == object->adapter))
1015     {
1016         int securePort = get_secure_information(requestInfo->info.payload);
1017         if (0 < securePort) //Set the remote endpoint secure details and send response
1018         {
1019             printf("This is secure resource...\n");
1020
1021             CAEndpoint_t *endpoint = NULL;
1022             if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1023                                                  object->port, &endpoint))
1024             {
1025                 printf("Failed to create duplicate of remote endpoint!\n");
1026                 return;
1027             }
1028             endpoint->flags = CA_SECURE;
1029             object = endpoint;
1030         }
1031     }
1032
1033 #ifdef WITH_BWT
1034     // if received message is bulk data, create output file
1035     if ((requestInfo->info.payload) &&
1036             (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1037     {
1038         create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
1039     }
1040 #endif
1041
1042     printf("Send response with URI\n");
1043     send_response(object, &requestInfo->info);
1044
1045     g_received = 1;
1046 }
1047
1048 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1049 {
1050     printf("##########Received response from remote device #############\n");
1051     if (CA_ADAPTER_IP == object->adapter)
1052     {
1053         printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1054                object->port, object->flags & CA_SECURE);
1055     }
1056     else
1057     {
1058         printf("Remote Address: %s \n", object->addr);
1059     }
1060     printf("response result : %d\n", responseInfo->result);
1061     printf("Data: %s\n", responseInfo->info.payload);
1062     printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1063     printf("Token: %s\n", responseInfo->info.token);
1064     if (responseInfo->info.options)
1065     {
1066         uint32_t len = responseInfo->info.numOptions;
1067         uint32_t i;
1068         for (i = 0; i < len; i++)
1069         {
1070             printf("Option %d\n", i + 1);
1071             printf("ID : %d\n", responseInfo->info.options[i].optionID);
1072             printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1073                    responseInfo->info.options[i].optionData);
1074         }
1075     }
1076     printf("############################################################\n");
1077     g_received = 1;
1078
1079     //Check if this has secure communication information
1080     if (responseInfo->info.payload)
1081     {
1082         int securePort = get_secure_information(responseInfo->info.payload);
1083         if (0 < securePort) //Set the remote endpoint secure details and send response
1084         {
1085             printf("This is secure resource...\n");
1086         }
1087     }
1088
1089 #ifdef WITH_BWT
1090     // if received message is bulk data, create output file
1091     if ((responseInfo->info.payload) &&
1092             (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1093     {
1094         create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
1095     }
1096 #endif
1097 }
1098
1099 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1100 {
1101     (void)rep;
1102     printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1103
1104     if(errorInfo)
1105     {
1106         const CAInfo_t *info = &errorInfo->info;
1107         printf("Error Handler, ErrorInfo :\n");
1108         printf("Error Handler result    : %d\n", errorInfo->result);
1109         printf("Error Handler token     : %s\n", info->token);
1110         printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1111         printf("Error Handler type      : %d\n", info->type);
1112         printf("Error Handler resourceUri : %s\n", info->resourceUri);
1113         printf("Error Handler payload   : %s\n", info->payload);
1114
1115         if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1116         {
1117             printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1118         }
1119         else if(CA_SEND_FAILED == errorInfo->result)
1120         {
1121             printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1122         }
1123         else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1124         {
1125             printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1126         }
1127         else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1128         {
1129             printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1130         }
1131         else if(CA_STATUS_FAILED == errorInfo->result)
1132         {
1133             printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1134         }
1135     }
1136     printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1137
1138     return;
1139 }
1140
1141 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1142 {
1143     printf("entering send_response\n");
1144
1145     printf("\n=============================================\n");
1146     printf("\tselect message type\n");
1147     printf("CON     : 0\n");
1148     printf("NON     : 1\n");
1149     printf("ACK     : 2\n");
1150     printf("RESET   : 3\n");
1151     printf("select : ");
1152
1153     char buf[MAX_BUF_LEN] = { 0 };
1154     if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1155     {
1156         return;
1157     }
1158
1159     int messageType = buf[0] - '0';
1160     if (0 > messageType || 3 < messageType)
1161     {
1162         printf("Invalid message type\n");
1163         return;
1164     }
1165
1166     int responseCode = 0 ;
1167     char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1168     if (CA_MSG_RESET != messageType)
1169     {
1170         printf("\n=============================================\n");
1171         printf("\tselect response code\n");
1172         printf("EMPTY                    :   0\n");
1173         printf("CREATED                  : 201\n");
1174         printf("DELETED                  : 202\n");
1175         printf("VALID                    : 203\n");
1176         printf("CHANGED                  : 204\n");
1177         printf("CONTENT                  : 205\n");
1178         printf("BAD_REQ                  : 400\n");
1179         printf("BAD_OPT                  : 402\n");
1180         printf("NOT_FOUND                : 404\n");
1181         printf("INTERNAL_SERVER_ERROR    : 500\n");
1182         printf("RETRANSMIT_TIMEOUT       : 504\n");
1183         printf("select : ");
1184
1185         if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1186         {
1187             return;
1188         }
1189         responseCode = atoi(responseCodeBuf);
1190     }
1191
1192     // create response data
1193     uint16_t messageId = (info != NULL) ? info->messageId : 0;
1194     CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;
1195
1196     CAInfo_t responseData = { .type = messageType,
1197                               .messageId = messageId,
1198                               .token = NULL,
1199                               .tokenLength = 0,
1200                               .options = NULL,
1201                               .numOptions = 0,
1202                               .payload = NULL,
1203                               .payloadSize = 0,
1204                               .resourceUri = resourceUri };
1205
1206     if(CA_MSG_RESET != messageType)
1207     {
1208         responseData.token = (info != NULL) ? info->token : NULL;
1209         responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1210
1211         if (endpoint->flags & CA_SECURE)
1212         {
1213             if(!responseData.resourceUri)
1214             {
1215                printf("resourceUri not available in SECURE\n");
1216                return;
1217             }
1218             printf("Sending response on secure communication\n");
1219
1220             uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
1221             responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
1222             if (NULL == responseData.payload)
1223             {
1224                 printf("Memory allocation fail\n");
1225                 return;
1226             }
1227             snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1228                      (const char *) responseData.resourceUri, g_local_secure_port);
1229             responseData.payloadSize = length;
1230         }
1231         else
1232         {
1233             printf("Sending response on non-secure communication\n");
1234
1235             bool useBigPayload = select_payload_type();
1236             if (useBigPayload)
1237             {
1238                 size_t payloadLength = 0;
1239                 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
1240                 if (NULL == binaryPayload)
1241                 {
1242                     free(binaryPayload);
1243                     return;
1244                 }
1245
1246                 responseData.payload = (CAPayload_t) malloc(payloadLength);
1247                 if (NULL == responseData.payload)
1248                 {
1249                     printf("Memory allocation failed!");
1250                     free(binaryPayload);
1251                     return;
1252                 }
1253                 memcpy(responseData.payload, binaryPayload, payloadLength);
1254                 responseData.payloadSize = payloadLength;
1255
1256                 // memory free
1257                 free(binaryPayload);
1258             }
1259             else
1260             {
1261                 if(!responseData.resourceUri)
1262                 {
1263                    printf("resourceUri not available in NON-SECURE\n");
1264                    return;
1265                 }
1266                 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1267                 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1268                 if (NULL == responseData.payload)
1269                 {
1270                     printf("Memory allocation fail\n");
1271                     return;
1272                 }
1273                 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1274                          (const char *) responseData.resourceUri);
1275                 responseData.payloadSize = length;
1276             }
1277         }
1278     }
1279
1280     CAResponseInfo_t responseInfo = { .result = responseCode,
1281                                       .info = responseData };
1282
1283     // send response (transportType from remoteEndpoint of request Info)
1284     CAResult_t res = CASendResponse(endpoint, &responseInfo);
1285     if (CA_STATUS_OK != res)
1286     {
1287         printf("Send response error\n");
1288     }
1289     else
1290     {
1291         printf("Send response success\n");
1292     }
1293
1294     if (responseData.payload)
1295     {
1296         free(responseData.payload);
1297     }
1298
1299     printf("=============================================\n");
1300 }
1301
1302 int get_secure_information(CAPayload_t payLoad)
1303 {
1304     printf("Entering get_secure_information\n");
1305
1306     if (!payLoad)
1307     {
1308         printf("Payload is NULL\n");
1309         return -1;
1310     }
1311
1312     char *subString = NULL;
1313     if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1314     {
1315         printf("This is not secure resource\n");
1316         return -1;
1317     }
1318
1319     if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1320     {
1321         printf("This secure resource does not have port information\n");
1322         return -1;
1323     }
1324
1325     char *startPos = strstr(subString, ":");
1326     if (!startPos)
1327     {
1328         printf("Parsing failed !\n");
1329         return -1;
1330     }
1331
1332     char *endPos = strstr(startPos, "}");
1333     if (!endPos)
1334     {
1335         printf("Parsing failed !\n");
1336         return -1;
1337     }
1338
1339     char portStr[6] = {0};
1340     OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
1341     printf("secured port is: %s\n", portStr);
1342     return atoi(portStr);
1343 }
1344
1345 void get_resource_uri(char *URI, char *resourceURI, int length)
1346 {
1347     char *startPos = URI;
1348     char *temp = NULL;
1349     if (NULL != (temp = strstr(URI, "://")))
1350     {
1351         startPos = strchr(temp + 3, '/');
1352         if (!startPos)
1353         {
1354             printf("Resource URI is missing\n");
1355             return;
1356         }
1357     }
1358
1359     char *endPos = strchr(startPos, '?');
1360     if (!endPos)
1361     {
1362         endPos = URI + strlen(URI);
1363     }
1364     endPos -= 1;
1365
1366     if (endPos - startPos <= length)
1367     {
1368         OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos);
1369     }
1370
1371     printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1372 }
1373
1374 CAResult_t get_network_type()
1375 {
1376     char buf[MAX_BUF_LEN] = { 0 };
1377
1378     printf("\n=============================================\n");
1379     printf("\tselect network type\n");
1380     printf("IP     : 0\n");
1381     printf("GATT   : 1\n");
1382     printf("RFCOMM : 2\n");
1383     printf("TCP    : 4\n");
1384     printf("select : ");
1385
1386     if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1387     {
1388         return CA_NOT_SUPPORTED ;
1389     }
1390
1391     int number = buf[0] - '0';
1392
1393     number = (number < 0 || number > 4) ? 0 : 1 << number;
1394
1395     switch (number)
1396     {
1397         case CA_ADAPTER_IP:
1398         case CA_ADAPTER_GATT_BTLE:
1399         case CA_ADAPTER_RFCOMM_BTEDR:
1400         case CA_ADAPTER_TCP:
1401             g_selected_nw_type = number;
1402             return CA_STATUS_OK;
1403         default:
1404             return CA_NOT_SUPPORTED;
1405     }
1406 }
1407
1408 CAResult_t get_input_data(char *buf, int32_t length)
1409 {
1410     if (!fgets(buf, length, stdin))
1411     {
1412         printf("fgets error\n");
1413         return CA_STATUS_FAILED;
1414     }
1415
1416     char *p = NULL;
1417     if ( (p = strchr(buf, '\n')) != NULL )
1418     {
1419         *p = '\0';
1420     }
1421
1422     return CA_STATUS_OK;
1423 }
1424
1425 CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
1426 {
1427     char optionNumBuf[MAX_BUF_LEN] = { 0 };
1428     char optionData[MAX_OPT_LEN] = { 0 } ;
1429
1430     printf("Option Num : ");
1431     if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
1432     {
1433         return NULL;
1434     }
1435     int optionNum = atoi(optionNumBuf);
1436
1437     CAHeaderOption_t * headerOpt = NULL;
1438     if (0 >= optionNum)
1439     {
1440         printf("there is no headerOption!\n");
1441         return NULL;
1442     }
1443     else if (optionNum > MAX_OPT_LEN)
1444     {
1445         printf("Too many header options!\n");
1446         return NULL;
1447     }
1448     else
1449     {
1450         headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
1451         if (NULL == headerOpt)
1452         {
1453             printf("Memory allocation failed!\n");
1454             return NULL;
1455         }
1456
1457         int i;
1458         for (i = 0; i < optionNum; i++)
1459         {
1460             char getOptionID[MAX_BUF_LEN] = { 0 } ;
1461
1462             printf("[%d] Option ID : ", i + 1);
1463             if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
1464             {
1465                 free(headerOpt);
1466                 return NULL;
1467             }
1468             int optionID = atoi(getOptionID);
1469             headerOpt[i].optionID = optionID;
1470
1471             printf("[%d] Option Data : ", i + 1);
1472             if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
1473             {
1474                 free(headerOpt);
1475                 return NULL;
1476             }
1477
1478             OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);
1479
1480             headerOpt[i].optionLength = (uint16_t) strlen(optionData);
1481         }
1482         requestData->numOptions = optionNum;
1483         requestData->options = headerOpt;
1484     }
1485     return headerOpt;
1486 }
1487
1488 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1489 {
1490     if (NULL == uri)
1491     {
1492         printf("parameter is null\n");
1493         return;
1494     }
1495
1496     // parse uri
1497     // #1. check prefix
1498     uint8_t startIndex = 0;
1499     if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1500     {
1501         printf("uri has '%s' prefix\n", COAPS_PREFIX);
1502         startIndex = COAPS_PREFIX_LEN;
1503         *flags = CA_SECURE;
1504     }
1505     else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1506     {
1507         printf("uri has '%s' prefix\n", COAP_PREFIX);
1508         startIndex = COAP_PREFIX_LEN;
1509         *flags = CA_IPV4;
1510     }
1511     else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1512     {
1513         printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1514         startIndex = COAP_TCP_PREFIX_LEN;
1515         *flags = CA_IPV4;
1516     }
1517
1518     // #2. copy uri for parse
1519     int32_t len = strlen(uri) - startIndex;
1520
1521     if (len <= 0)
1522     {
1523         printf("uri length is 0!\n");
1524         return;
1525     }
1526
1527     char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1528     if (NULL == cloneUri)
1529     {
1530         printf("Out of memory\n");
1531         return;
1532     }
1533
1534     memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1535     cloneUri[len] = '\0';
1536
1537     char *pAddress = cloneUri;
1538     printf("pAddress : %s\n", pAddress);
1539
1540     if (!get_address_set(pAddress, address))
1541     {
1542         printf("address parse error\n");
1543
1544         free(cloneUri);
1545         return;
1546     }
1547     free(cloneUri);
1548     return;
1549 }
1550
1551 bool get_address_set(const char *pAddress, addressSet_t* outAddress)
1552 {
1553     if (NULL == pAddress)
1554     {
1555         printf("parameter is null !\n");
1556         return false;
1557     }
1558
1559     size_t len = strlen(pAddress);
1560     bool isIp = false;
1561     size_t ipLen = 0;
1562
1563     for (size_t i = 0; i < len; i++)
1564     {
1565         if (pAddress[i] == '.')
1566         {
1567             isIp = true;
1568         }
1569
1570         // found port number start index
1571         if (isIp && pAddress[i] == ':')
1572         {
1573             ipLen = i;
1574             break;
1575         }
1576     }
1577
1578     if (isIp)
1579     {
1580         if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1581         {
1582             OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1583                              pAddress, ipLen);
1584         }
1585         else if (!ipLen && len < sizeof(outAddress->ipAddress))
1586         {
1587             OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1588                              pAddress, len);
1589         }
1590         else
1591         {
1592             printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen);
1593             return false;
1594         }
1595
1596         if (ipLen > 0)
1597         {
1598             outAddress->port = atoi(pAddress + ipLen + 1);
1599         }
1600         return true;
1601     }
1602     else
1603     {
1604         return false;
1605     }
1606 }
1607
1608 void create_file(CAPayload_t bytes, size_t length)
1609 {
1610     FILE *fp = fopen("sample_output.txt", "wb");
1611     if (fp)
1612     {
1613         fwrite(bytes, 1, length, fp);
1614         fclose(fp);
1615     }
1616 }
1617
1618 bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
1619 {
1620     if (NULL == name)
1621     {
1622         printf("parameter is null\n");
1623         return false;
1624     }
1625
1626     FILE* file = NULL;
1627     CAPayload_t buffer = NULL;
1628     unsigned long fileLen = 0;
1629
1630     // Open file
1631     file = fopen(name, "rb");
1632     if (!file)
1633     {
1634         fprintf(stderr, "Unable to open file, %s\n", name);
1635         return false;
1636     }
1637
1638     // Get file length
1639     fseek(file, 0, SEEK_END);
1640     fileLen = ftell(file);
1641     fseek(file, 0, SEEK_SET);
1642
1643     // Allocate memory
1644     buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
1645     if (!buffer)
1646     {
1647         fprintf(stderr, "Memory error\n");
1648         fclose(file);
1649         return false;
1650     }
1651
1652     // Read file contents into buffer
1653     size_t ret = fread(buffer, fileLen, 1, file);
1654     if (ret != 1)
1655     {
1656         printf("Failed to read data from file, %s\n", name);
1657         fclose(file);
1658         free(buffer);
1659         return false;
1660     }
1661
1662     fclose(file);
1663
1664     *bytes = buffer;
1665     *length = fileLen;
1666
1667     return true;
1668 }