60108c3582b94265c1a4543a76d04547519d5755
[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 "cacommon.h"
27 #include "cainterface.h"
28 #ifdef __WITH_DTLS__
29 #include "ocsecurityconfig.h"
30 #endif
31
32 #define MAX_BUF_LEN 1024
33 #define MAX_OPT_LEN 16
34 #define TRUE 1
35 #define FALSE 0
36
37 /**
38  * @def RS_IDENTITY
39  * @brief
40  */
41 #define IDENTITY     ("1111111111111111")
42 /* @def RS_CLIENT_PSK
43  * @brief
44  */
45 #define RS_CLIENT_PSK   ("AAAAAAAAAAAAAAAA")
46
47
48 int gReceived;
49 CABool_t gLocalUnicastPort;
50 CABool_t gLocalSecurePort;
51 CAConnectivityType_t gSelectedNwType = CA_ETHERNET;
52 const char* gMessageType[] = {"CON", "NON", "ACK", "RESET"};
53
54 char get_menu();
55 void process();
56 CAResult_t get_network_type();
57
58 void start_listening_server();
59 void start_discovery_server();
60 void find_resource();
61 void send_request();
62 void send_request_all();
63 void advertise_resource();
64 void send_notification();
65 void select_network();
66 void unselect_network();
67 void handle_request_response();
68 void find_fixed_resource();
69 void get_network_info();
70 void send_secure_request();
71
72 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
73 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
74 void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token);
75 void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info);
76 void get_resource_uri(char *URI, char *resourceURI, int length);
77 int get_secure_information(CAPayload_t payLoad);
78
79 static CAToken_t gLastRequestToken = NULL;
80 static const char *gSecureInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
81                                      "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
82 static const char *gNormalInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
83                                      "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
84
85 #ifdef __WITH_DTLS__
86 static OCDtlsPskCredsBlob *pskCredsBlob = NULL;
87
88 void clearDtlsCredentialInfo()
89 {
90     printf("clearDtlsCredentialInfo IN\n");
91     if (pskCredsBlob)
92     {
93         // Zero out sensitive data before freeing.
94         if (pskCredsBlob->num)
95         {
96             memset(pskCredsBlob, 0,
97                 sizeof(OCDtlsPskCredsBlob) + (sizeof(OCDtlsPskCreds)*(pskCredsBlob->num - 1)));
98         }
99         free(pskCredsBlob);
100         pskCredsBlob = NULL;
101     }
102     printf("clearDtlsCredentialInfo OUT\n");
103 }
104
105 // Internal API. Invoked by OC stack to retrieve credentials from this module
106 void OCGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo)
107 {
108     printf("OCGetDtlsPskCredentials IN\n");
109
110     *credInfo = pskCredsBlob;
111
112     printf("OCGetDtlsPskCredentials OUT\n");
113 }
114 // Internal API. Invoked by OC stack to retrieve credentials from this module
115 void CAGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo)
116 {
117     printf("CAGetDtlsPskCredentials IN\n");
118
119     *credInfo = pskCredsBlob;
120
121     printf("CAGetDtlsPskCredentials OUT\n");
122 }
123 int32_t SetCredentials()
124 {
125     printf("SetCredentials IN\n");
126     pskCredsBlob = (OCDtlsPskCredsBlob *)malloc(sizeof(OCDtlsPskCredsBlob));
127
128     memset(pskCredsBlob, 0x0, sizeof(OCDtlsPskCredsBlob));
129     memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
130
131     pskCredsBlob->num = 1;
132
133     pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
134
135     memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
136     memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
137
138     printf("SetCredentials OUT\n");
139     return 1;
140 }
141 #endif
142
143 int main()
144 {
145     system("clear");
146
147     printf("=============================================\n");
148     printf("\t\tsample main\n");
149     printf("=============================================\n");
150
151     CAResult_t res;
152     /*
153     * Read DTLS PSK credentials from persistent storage and
154     * set in the OC stack.
155     */
156 #ifdef __WITH_DTLS__
157     if (SetCredentials() == 0)
158     {
159         printf("SetCredentials failed\n");
160         return 0;
161     }
162
163     res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
164     if(res != CA_STATUS_OK)
165     {
166         printf("Set credential handler fail\n");
167         return 0;
168     }
169 #endif
170     res = CAInitialize();
171     if (res != CA_STATUS_OK)
172     {
173         printf("CAInitialize fail\n");
174         return 0;
175     }
176
177 #if 0
178     // network enable
179     // default
180     printf("select default network(WIFI)\n");
181     res = CASelectNetwork(CA_WIFI);
182     if (res != CA_STATUS_OK)
183     {
184         printf("CASelectNetwork fail\n");
185         return 0;
186     }
187 #endif
188
189     // set handler.
190     CARegisterHandler(request_handler, response_handler);
191
192     process();
193
194     if (gLastRequestToken != NULL)
195     {
196         CADestroyToken(gLastRequestToken);
197     }
198     gLastRequestToken = NULL;
199
200     CATerminate();
201 #ifdef __WITH_DTLS__
202     clearDtlsCredentialInfo();
203 #endif
204     return 0;
205 }
206
207 void process()
208 {
209     while (1)
210     {
211         char menu = get_menu();
212
213         switch (menu)
214         {
215             case 'm': // menu
216             case 'M':
217                 continue;
218
219             case 'q': // quit
220             case 'Q':
221                 printf("quit..!!\n");
222                 return;
223
224             case 's': // start server
225             case 'S':
226                 start_listening_server();
227                 break;
228
229             case 't': // send request
230             case 'T':
231                 send_request_all();
232                 break;
233
234             case 'c': // start client
235             case 'D':
236                 start_discovery_server();
237                 break;
238
239             case 'f': // find resource
240             case 'F':
241                 find_resource();
242                 break;
243
244             case 'r': // send request
245             case 'R':
246                 send_request();
247                 break;
248
249             case 'a': // advertise resource
250             case 'A':
251                 advertise_resource();
252                 break;
253
254             case 'b': // send notification
255             case 'B':
256                 send_notification();
257                 break;
258
259             case 'n': // select network
260             case 'N':
261                 select_network();
262                 break;
263
264             case 'x': // unselect network
265             case 'X':
266                 unselect_network();
267                 break;
268
269             case 'h': // handle request response
270             case 'H':
271                 handle_request_response();
272                 break;
273             case 'y':
274             case 'Y':
275                 while (1)
276                 {
277                     gReceived = 0;
278                     find_fixed_resource();
279                     while (gReceived == 0)
280                     {
281                         sleep(1);
282                         handle_request_response();
283
284                     }
285                 }
286                 break;
287
288             case 'w':
289             case 'W':
290                 gReceived = 0;
291                 start_discovery_server();
292                 send_secure_request();
293                 while (gReceived == 0)
294                 {
295                     sleep(1);
296                     handle_request_response();
297                 }
298
299                 break;
300
301             case 'z':
302             case 'Z':
303                 start_listening_server();
304                 while (1)
305                 {
306                     sleep(1);
307                     handle_request_response();
308                 }
309                 break;
310
311             case 'g': // get network information
312             case 'G':
313                 get_network_info();
314                 break;
315
316             default:
317                 printf("not supported menu!!\n");
318                 break;
319         }
320     }
321
322 }
323
324
325
326 void start_listening_server()
327 {
328     printf("start listening server!!\n");
329
330     CAResult_t res = CAStartListeningServer();
331     if (res != CA_STATUS_OK)
332     {
333         printf("start listening server fail\n");
334     }
335     else
336     {
337         printf("start listening server success\n");
338     }
339 }
340
341 void start_discovery_server()
342 {
343     printf("start discovery client!!\n");
344
345     CAResult_t res = CAStartDiscoveryServer();
346     if (res != CA_STATUS_OK)
347     {
348         printf("start discovery client fail\n");
349     }
350     else
351     {
352         printf("start discovery client success\n");
353     }
354 }
355
356 void find_fixed_resource()
357 {
358     char buf[MAX_BUF_LEN] =
359     { 0, };
360     strcpy(buf, "/a/light");
361
362     // create token
363     CAToken_t token = NULL;
364     CAResult_t res = CAGenerateToken(&token);
365     if (res != CA_STATUS_OK)
366     {
367         printf("token generate error!!");
368         token = NULL;
369     }
370
371     printf("generated token %s\n", (token != NULL) ? token : "");
372
373     res = CAFindResource(buf, token);
374     if (res != CA_STATUS_OK)
375     {
376         printf("find resource error!!\n");
377     }
378     else
379     {
380         printf("find resource to %s URI\n", buf);
381     }
382
383     // delete token
384     /*
385      if (token != NULL)
386      {
387      CADestroyToken(token);
388      }
389      */
390
391     printf("=============================================\n");
392 }
393
394 void find_resource()
395 {
396     char buf[MAX_BUF_LEN];
397
398     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
399
400     printf("\n=============================================\n");
401     printf("ex) /a/light\n");
402     printf("reference uri : ");
403
404     if(gets(buf) == NULL)
405         return;
406
407     // create token
408     CAToken_t token = NULL;
409     CAResult_t res = CAGenerateToken(&token);
410     if (res != CA_STATUS_OK)
411     {
412         printf("token generate error!!\n");
413         token = NULL;
414     }
415
416     printf("generated token %s\n", (token != NULL) ? token : "");
417
418     res = CAFindResource(buf, token);
419     if (res != CA_STATUS_OK)
420     {
421         printf("find resource error!!\n");
422     }
423     else
424     {
425         printf("find resource to %s URI\n", buf);
426
427         if (gLastRequestToken != NULL)
428         {
429             CADestroyToken(gLastRequestToken);
430         }
431
432         gLastRequestToken = token;
433     }
434
435     // delete token
436     /*
437      if (token != NULL)
438      {
439      CADestroyToken(token);
440      }
441      */
442
443     printf("=============================================\n");
444 }
445
446 void send_request()
447 {
448     char secureRequest[2] = {0};
449     CAResult_t res;
450
451     res = get_network_type();
452     if (res != CA_STATUS_OK)
453     {
454         return;
455     }
456
457     printf("Do you want to send secure request ?.... enter (0/1): ");
458     if( gets(secureRequest) == NULL)
459         return;
460     if ('1' == secureRequest[0])
461     {
462         printf("Enter the URI like below....\n");
463         printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
464     }
465     else
466     {
467         printf("Enter the URI like below....\n");
468         printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
469         printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
470     }
471
472     char uri[MAX_BUF_LEN] = {'\0'};
473     if( gets(uri) == NULL)
474         return ;
475
476     // create remote endpoint
477     CARemoteEndpoint_t *endpoint = NULL;
478     if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, gSelectedNwType, &endpoint)
479         || !endpoint)
480     {
481         printf("Failed to create remote endpoint!\n");
482         CADestroyRemoteEndpoint(endpoint);
483         return;
484     }
485
486     //endpoint->connectivityType = gSelectedNwType;
487
488     char buf[MAX_BUF_LEN];
489     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
490
491     printf("\n=============================================\n");
492     printf("0:CON, 1:NON\n");
493     printf("select message type : ");
494
495     if( gets(buf) == NULL)
496         return ;
497
498     CAMessageType_t msgType = (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0;
499
500     // create token
501     CAToken_t token = NULL;
502     if (CA_STATUS_OK != CAGenerateToken(&token))
503     {
504         printf("token generate error!!\n");
505         token = NULL;
506     }
507
508     printf("generated token %s\n", (token != NULL) ? token : "");
509
510     // extract relative resourceuri from give uri
511     char resourceURI[15] = {0};
512
513     printf("URI : %s\n", uri);
514     get_resource_uri(uri, resourceURI, 14);
515
516     // create request data
517     CAInfo_t requestData;
518     memset(&requestData, 0, sizeof(CAInfo_t));
519     requestData.token = token;
520     if ('1' == secureRequest[0])
521     {
522         int length = strlen(gSecureInfoData) + strlen(resourceURI) + 1;
523         requestData.payload = (CAPayload_t) malloc(length);
524         sprintf(requestData.payload, gSecureInfoData, resourceURI, gLocalSecurePort);
525     }
526     else
527     {
528         int length = strlen(gNormalInfoData) + strlen(resourceURI) + 1;
529         requestData.payload = (CAPayload_t) malloc(length);
530         sprintf(requestData.payload, gNormalInfoData, resourceURI);
531     }
532     requestData.type = msgType;
533
534     CARequestInfo_t requestInfo;
535     memset(&requestInfo, 0, sizeof(CARequestInfo_t));
536     requestInfo.method = CA_GET;
537     requestInfo.info = requestData;
538
539     // send request
540     CASendRequest(endpoint, &requestInfo);
541
542     if (token != NULL)
543     {
544         CADestroyToken(token);
545     }
546     if (requestData.payload != NULL)
547     {
548         free(requestData.payload);
549     }
550     // destroy remote endpoint
551     CADestroyRemoteEndpoint(endpoint);
552     printf("=============================================\n");
553 }
554
555 void send_secure_request()
556 {
557     char uri[MAX_BUF_LEN];
558     char ipv4addr[CA_IPADDR_SIZE];
559
560     printf("\n=============================================\n");
561     printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
562
563     fgets(ipv4addr, CA_IPADDR_SIZE, stdin);
564     snprintf(uri, MAX_BUF_LEN, "coaps://%s:5684/a/light", ipv4addr);
565
566     // create remote endpoint
567     CARemoteEndpoint_t *endpoint = NULL;
568     if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, CA_ETHERNET, &endpoint))
569     {
570         printf("Failed to create remote endpoint!\n");
571         goto exit;
572     }
573
574     // create token
575     CAToken_t token = NULL;
576     if (CA_STATUS_OK != CAGenerateToken(&token))
577     {
578         printf("Failed to generate token !\n");
579         goto exit;
580     }
581
582     // create request data
583     CAMessageType_t msgType = CA_MSG_NONCONFIRM;
584     CAInfo_t requestData;
585     memset(&requestData, 0, sizeof(CAInfo_t));
586     requestData.token = token;
587     requestData.type = msgType;
588
589     CARequestInfo_t requestInfo;
590     memset(&requestInfo, 0, sizeof(CARequestInfo_t));
591     requestInfo.method = CA_GET;
592     requestInfo.info = requestData;
593
594     // send request
595     CASendRequest(endpoint, &requestInfo);
596
597 exit:
598     // cleanup
599     CADestroyToken(token);
600     CADestroyRemoteEndpoint(endpoint);
601     printf("=============================================\n");
602 }
603
604
605 void send_request_all()
606 {
607     char buf[MAX_BUF_LEN];
608     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
609
610     CAResult_t res;
611
612     res = get_network_type();
613     if (res != CA_STATUS_OK)
614     {
615         return;
616     }
617
618     printf("\n=============================================\n");
619     printf("10.11.12.13:4545/resource_uri ( for IP )\n");
620     printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
621     printf("uri : ");
622
623     if( gets(buf) == NULL)
624         return ;
625
626     // create remote endpoint
627     CARemoteEndpoint_t *endpoint = NULL;
628     res = CACreateRemoteEndpoint(buf, gSelectedNwType, &endpoint);
629
630     if (res != CA_STATUS_OK)
631     {
632         printf("create remote endpoint error!!\n");
633         CADestroyRemoteEndpoint(endpoint);
634         return;
635     }
636
637
638     CAGroupEndpoint_t *group = NULL;
639     group = (CAGroupEndpoint_t *)malloc(sizeof(CAGroupEndpoint_t));
640     group->connectivityType = endpoint->connectivityType;
641     group->resourceUri = endpoint->resourceUri;
642
643
644     // create token
645     CAToken_t token = NULL;
646     res = CAGenerateToken(&token);
647
648     if (res != CA_STATUS_OK)
649     {
650         printf("token generate error!!\n");
651         token = NULL;
652     }
653
654     printf("generated token %s\n", (token != NULL) ? token : "");
655
656     CAInfo_t requestData;
657     memset(&requestData, 0, sizeof(CAInfo_t));
658     requestData.token = token;
659     requestData.payload = "Temp Json Payload";
660         requestData.type = CA_MSG_NONCONFIRM;
661
662     CARequestInfo_t requestInfo;
663     memset(&requestInfo, 0, sizeof(CARequestInfo_t));
664     requestInfo.method = CA_GET;
665     requestInfo.info = requestData;
666
667     // send request
668     // CASendRequest(endpoint, &requestInfo);
669     CASendRequestToAll(group, &requestInfo);
670
671     if (token != NULL)
672     {
673         CADestroyToken(token);
674     }
675
676     // destroy remote endpoint
677     if (endpoint != NULL)
678     {
679         CADestroyRemoteEndpoint(endpoint);
680     }
681
682     free(group);
683
684     printf("=============================================\n");
685 }
686
687 void advertise_resource()
688 {
689     char buf[MAX_BUF_LEN];
690
691     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
692
693     printf("\n=============================================\n");
694     printf("uri : ");
695
696     scanf("%s", buf);
697
698     int optionNum = 0;
699     char optionData[MAX_OPT_LEN];
700
701     printf("Option Num : ");
702     scanf("%d", &optionNum);
703     CAHeaderOption_t *headerOpt;
704     headerOpt = (CAHeaderOption_t *) malloc(sizeof(CAHeaderOption_t) * optionNum);
705     if (NULL == headerOpt)
706     {
707         printf("Memory allocation failed!\n");
708         return;
709     }
710     memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
711
712     int i;
713     for (i = 0; i < optionNum; i++)
714     {
715         int optionID = 0;
716         printf("[%d] Option ID : ", i + 1);
717         scanf("%d", &optionID);
718         headerOpt[i].optionID = optionID;
719
720         memset(optionData, 0, sizeof(char) * MAX_OPT_LEN);
721         printf("[%d] Option Data : ", i + 1);
722         scanf("%s", optionData);
723         memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
724         printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
725
726         headerOpt[i].optionLength = (uint16_t) strlen(optionData);
727     }
728     printf("\n=============================================\n");
729
730     // create token
731     CAToken_t token = NULL;
732     CAResult_t res = CAGenerateToken(&token);
733     if (res != CA_STATUS_OK)
734     {
735         printf("token generate error!!\n");
736         token = NULL;
737     }
738
739     printf("generated token %s\n", (token != NULL) ? token : "");
740
741     CAAdvertiseResource(buf, token, headerOpt, (uint8_t) optionNum);
742
743     // delete token
744     if (token != NULL)
745     {
746         CADestroyToken(token);
747     }
748
749     free(headerOpt);
750
751 }
752
753 void send_notification()
754 {
755     char buf[MAX_BUF_LEN];
756     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
757
758     CAResult_t res;
759
760     res = get_network_type();
761     if (res != CA_STATUS_OK)
762     {
763         return;
764     }
765
766     printf("\n=============================================\n");
767     printf("10.11.12.13:4545/resource_uri ( for IP )\n");
768     printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
769     printf("uri : ");
770
771     if( gets(buf) == NULL)
772         return ;
773
774     // create remote endpoint
775     CARemoteEndpoint_t *endpoint = NULL;
776     res = CACreateRemoteEndpoint(buf, gSelectedNwType, &endpoint);
777
778     if (res != CA_STATUS_OK)
779     {
780         printf("create remote endpoint error!!\n");
781         CADestroyRemoteEndpoint(endpoint);
782         return;
783     }
784
785     CAInfo_t respondeData;
786     memset(&respondeData, 0, sizeof(CAInfo_t));
787     respondeData.token = "client token";
788     respondeData.payload = "Temp Notification Data";
789
790     CAResponseInfo_t responseInfo;
791     memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
792     responseInfo.result = CA_SUCCESS;
793     responseInfo.info = respondeData;
794
795     // send request
796     res = CASendNotification(endpoint, &responseInfo);
797     if (res != CA_STATUS_OK)
798     {
799         printf("send notification error\n");
800     }
801     else
802     {
803         printf("send notification success\n");
804     }
805
806     // destroy remote endpoint
807     if (endpoint != NULL)
808     {
809         CADestroyRemoteEndpoint(endpoint);
810     }
811
812     printf("\n=============================================\n");
813 }
814
815 void select_network()
816 {
817     char buf[MAX_BUF_LEN];
818
819     printf("\n=============================================\n");
820     printf("\tselect network\n");
821     printf("ETHERNET : 0\n");
822     printf("WIFI : 1\n");
823     printf("EDR : 2\n");
824     printf("LE : 3\n");
825     printf("select : ");
826
827     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
828     if( gets(buf) == NULL)
829         return;
830
831     int number = buf[0] - '0';
832
833     number = (number < 0 || number > 3) ? 0 : number;
834
835     CAResult_t res = CASelectNetwork(1 << number);
836     if (res != CA_STATUS_OK)
837     {
838         printf("select network error\n");
839         gSelectedNwType = 1 << number;
840     }
841     else
842     {
843         printf("select network success\n");
844     }
845
846     printf("=============================================\n");
847 }
848
849 void unselect_network()
850 {
851     char buf[MAX_BUF_LEN];
852
853     printf("\n=============================================\n");
854     printf("\tunselect enabled network\n");
855     printf("ETHERNET : 0\n");
856     printf("WIFI : 1\n");
857     printf("EDR : 2\n");
858     printf("LE : 3\n");
859     printf("select : ");
860
861     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
862     if( gets(buf) == NULL)
863         return ;
864
865     int number = buf[0] - '0';
866
867     number = (number < 0 || number > 3) ? 1 : number;
868
869     CAResult_t res = CAUnSelectNetwork(1 << number);
870     if (res != CA_STATUS_OK)
871     {
872         printf("unselect network error\n");
873     }
874     else
875     {
876         printf("unselect network success\n");
877     }
878
879     printf("=============================================\n");
880 }
881
882 char get_menu()
883 {
884     char buf[MAX_BUF_LEN];
885
886     printf("\n=============================================\n");
887     printf("\t\tMenu\n");
888     printf("\ts : start server\n");
889     printf("\tc : start client\n");
890     printf("\tf : find resource\n");
891     printf("\tr : send request\n");
892     printf("\tt : send request to all\n");
893     printf("\ta : advertise resource\n");
894     printf("\tb : send notification\n");
895     printf("\tn : select network\n");
896     printf("\tx : unselect network\n");
897     printf("\tg : get network information\n");
898     printf("\th : handle request response\n");
899     printf("\ty : run static client\n");
900     printf("\tz : run static server\n");
901     printf("\tw : send secure request\n");
902     printf("\tq : quit\n");
903     printf("=============================================\n");
904     printf("select : ");
905
906     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
907
908     if( gets(buf) == NULL)
909         return 'q';
910
911     return buf[0];
912 }
913
914 void handle_request_response()
915 {
916     printf("handle_request_response\n");
917
918     CAResult_t res = CAHandleRequestResponse();
919     if (res != CA_STATUS_OK)
920     {
921         printf("handle request error\n");
922     }
923     else
924     {
925         printf("handle request success\n");
926     }
927 }
928
929 void get_network_info()
930 {
931     int index;
932
933     CALocalConnectivity_t *tempInfo = NULL;
934     uint32_t tempSize = 0;
935
936     CAGetNetworkInformation(&tempInfo, &tempSize);
937     if (tempInfo == NULL || tempSize <= 0)
938     {
939         printf("network not connected\n");
940         return;
941     }
942
943     printf("################## Network Information #######################\n");
944     printf("network info total size is %d\n\n", tempSize);
945
946     for (index = 0; index < tempSize; index++)
947     {
948         printf("Type: %d\n", tempInfo[index].type);
949         printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
950         printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
951         printf("Secured: %d\n\n", tempInfo[index].isSecured);
952
953         if (CA_TRUE == tempInfo[index].isSecured)
954         {
955             gLocalSecurePort = tempInfo[index].addressInfo.IP.port;
956         }
957         else
958         {
959             gLocalUnicastPort = tempInfo[index].addressInfo.IP.port;
960         }
961     }
962
963     free(tempInfo);
964     printf("##############################################################");
965 }
966
967 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
968 {
969     if (!object)
970     {
971         printf("Remote endpoint is NULL!");
972         return;
973     }
974
975     if (!requestInfo)
976     {
977         printf("Request info is NULL!");
978         return;
979     }
980
981     printf("##########received request from remote device #############\n");
982     printf("Uri: %s\n", object->resourceUri);
983     printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
984            object->addressInfo.IP.port, object->isSecured);
985
986     printf("Data: %s\n", requestInfo->info.payload);
987     printf("Message type: %s\n", gMessageType[requestInfo->info.type]);
988     if (gLastRequestToken != NULL && requestInfo->info.token != NULL
989         && (strcmp((char *)gLastRequestToken, requestInfo->info.token) == 0))
990     {
991         printf("token is same. received request of it's own. skip.. \n");
992         return;
993     }
994
995     if (requestInfo->info.options)
996     {
997         uint32_t len = requestInfo->info.numOptions;
998         uint32_t i;
999         for (i = 0; i < len; i++)
1000         {
1001             printf("Option %d\n", i + 1);
1002             printf("ID : %d\n", requestInfo->info.options[i].optionID);
1003             printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1004                    requestInfo->info.options[i].optionData);
1005         }
1006     }
1007     printf("############################################################\n");
1008
1009     //Check if this has secure communication information
1010     if (requestInfo->info.payload)
1011     {
1012         int securePort = get_secure_information(requestInfo->info.payload);
1013         if (0 < securePort) //Set the remote endpoint secure details and send response
1014         {
1015             printf("This is secure resource...\n");
1016             char *uri = NULL;
1017             int length = 0;
1018
1019             length = 8; //length of "coaps://"
1020             length += strlen(object->addressInfo.IP.ipAddress) + 5; // length of "ipaddress:port"
1021             length += strlen(object->resourceUri) + 1;
1022
1023             uri = calloc(1, sizeof(char) * length);
1024             if (!uri)
1025             {
1026                 printf("Failed to create new uri\n");
1027                 return;
1028             }
1029             sprintf(uri, "coaps://%s:%d/%s", object->addressInfo.IP.ipAddress,
1030                     securePort, object->resourceUri);
1031
1032             CARemoteEndpoint_t *endpoint = NULL;
1033             if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->connectivityType, &endpoint))
1034             {
1035                 printf("Failed to create duplicate of remote endpoint!\n");
1036                 return;
1037             }
1038             //endpoint->connectivityType = object->connectivityType;
1039             endpoint->isSecured = CA_TRUE;
1040             object = endpoint;
1041
1042             free(uri);
1043         }
1044     }
1045
1046     printf("send response with URI\n");
1047     send_response(object, &requestInfo->info);
1048
1049     gReceived = 1;
1050 }
1051
1052 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1053 {
1054     printf("##########Received response from remote device #############\n");
1055     printf("Uri: %s\n", object->resourceUri);
1056     printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
1057            object->addressInfo.IP.port, object->isSecured);
1058     printf("response result : %d\n", responseInfo->result);
1059     printf("Data: %s\n", responseInfo->info.payload);
1060     printf("Message type: %s\n", gMessageType[responseInfo->info.type]);
1061     printf("Token: %s\n", responseInfo->info.token);
1062     if (responseInfo->info.options)
1063     {
1064         uint32_t len = responseInfo->info.numOptions;
1065         uint32_t i;
1066         for (i = 0; i < len; i++)
1067         {
1068             printf("Option %d\n", i + 1);
1069             printf("ID : %d\n", responseInfo->info.options[i].optionID);
1070             printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1071                    responseInfo->info.options[i].optionData);
1072         }
1073     }
1074     printf("############################################################\n");
1075     gReceived = 1;
1076
1077     //Check if this has secure communication information
1078     if (responseInfo->info.payload)
1079     {
1080         int securePort = get_secure_information(responseInfo->info.payload);
1081         if (0 < securePort) //Set the remote endpoint secure details and send response
1082         {
1083             printf("This is secure resource...\n");
1084         }
1085     }
1086 }
1087
1088 void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
1089 {
1090     char buf[MAX_BUF_LEN];
1091
1092     printf("entering send_response\n");
1093
1094     printf("\n=============================================\n");
1095     printf("\tselect message type\n");
1096     printf("CA_MSG_CONFIRM      : 0\n");
1097     printf("CA_MSG_NONCONFIRM   : 1\n");
1098     printf("CA_MSG_ACKNOWLEDGE  : 2\n");
1099     printf("CA_MSG_RESET        : 3\n");
1100     printf("select : ");
1101
1102     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
1103     gets(buf);
1104
1105     int messageType = buf[0] - '0';
1106     int responseCode = 231 ;
1107     if(messageType != 3)
1108     {
1109
1110         printf("\n=============================================\n");
1111         printf("\tselect response code\n");
1112         printf("CA_SUCCESS              : 200\n");
1113         printf("CA_CREATED              : 201\n");
1114         printf("CA_DELETED              : 202\n");
1115         printf("CA_EMPTY                : 231\n");
1116         printf("CA_BAD_REQ              : 400\n");
1117         printf("CA_BAD_OPT              : 402\n");
1118         printf("CA_NOT_FOUND            : 404\n");
1119         printf("CA_RETRANSMIT_TIMEOUT   : 531\n");
1120         printf("select : ");
1121         scanf("%d", &responseCode);
1122     }
1123     CAInfo_t responseData;
1124     memset(&responseData, 0, sizeof(CAInfo_t));
1125     responseData.type = messageType;
1126     responseData.messageId = (info != NULL) ? info->messageId : 0;
1127     if(messageType != 3)
1128     {
1129         responseData.token = (info != NULL) ? info->token : "";
1130         responseData.payload = "response payload";
1131     }
1132     CAResponseInfo_t responseInfo;
1133     memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
1134     responseInfo.result = responseCode;
1135     responseInfo.info = responseData;
1136
1137     if (CA_TRUE == endpoint->isSecured)
1138         printf("Sending response on secure communication\n");
1139     else
1140         printf("Sending response on non-secure communication\n");
1141
1142     // send request (connectivityType from remoteEndpoint of request Info)
1143     CAResult_t res = CASendResponse(endpoint, &responseInfo);
1144     if (res != CA_STATUS_OK)
1145 {
1146         printf("send response error\n");
1147     }
1148     else
1149     {
1150         printf("send response success\n");
1151     }
1152
1153     printf("=============================================\n");
1154 }
1155
1156 void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token)
1157 {
1158
1159     printf("\n=============================================\n");
1160
1161     CAInfo_t requestData;
1162     memset(&requestData, 0, sizeof(CAInfo_t));
1163     requestData.token = token;
1164     requestData.payload = "Temp Json Payload";
1165
1166     CARequestInfo_t requestInfo;
1167     memset(&requestInfo, 0, sizeof(CARequestInfo_t));
1168     requestInfo.method = CA_GET;
1169     requestInfo.info = requestData;
1170
1171     // send request
1172     endpoint->connectivityType = CA_WIFI;
1173
1174     CAResult_t res = CASendRequest(endpoint, &requestInfo);
1175     if (res != CA_STATUS_OK)
1176     {
1177         printf("send request error\n");
1178     }
1179     else
1180     {
1181         printf("send request success\n");
1182     }
1183
1184     printf("=============================================\n");
1185
1186 }
1187
1188 int get_secure_information(CAPayload_t payLoad)
1189 {
1190     printf("entering get_secure_information\n");
1191
1192     if (!payLoad)
1193     {
1194         printf("Payload is NULL\n");
1195         return -1;
1196     }
1197
1198     char *subString = NULL;
1199     if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
1200     {
1201         printf("This is not secure resource\n");
1202         return -1;
1203     }
1204
1205     if (NULL == (subString = strstr(payLoad, "\"port\":")))
1206     {
1207         printf("This secure resource does not have port information\n");
1208         return -1;
1209     }
1210
1211     char *startPos = strstr(subString, ":");
1212     if (!startPos)
1213     {
1214         printf("Parsing failed !\n");
1215         return -1;
1216     }
1217
1218     char *endPos = strstr(startPos, "}");
1219     if (!endPos)
1220     {
1221         printf("Parsing failed !\n");
1222         return -1;
1223     }
1224
1225     char portStr[4] = {0};
1226     memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1227
1228     printf("secured port is: %s\n", portStr);
1229     return atoi(portStr);
1230 }
1231
1232 void get_resource_uri(char *URI, char *resourceURI, int length)
1233 {
1234     char *startPos = URI;
1235     char *temp = NULL;
1236     if (NULL != (temp = strstr(URI, "://")))
1237     {
1238         startPos = strchr(temp + 3, '/');
1239         if (!startPos)
1240         {
1241             printf("Resource URI is missing\n");
1242             return;
1243         }
1244     }
1245
1246     char *endPos = strchr(startPos, '?');
1247     if (!endPos)
1248     {
1249         endPos = URI + strlen(URI);
1250     }
1251     endPos -= 1;
1252
1253     if (endPos - startPos <= length)
1254         memcpy(resourceURI, startPos + 1, endPos - startPos);
1255
1256     printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1257 }
1258
1259 CAResult_t get_network_type()
1260 {
1261     char buf[MAX_BUF_LEN];
1262
1263     printf("\n=============================================\n");
1264     printf("\tselect network type\n");
1265     printf("ETHERNET : 0\n");
1266     printf("WIFI : 1\n");
1267     printf("EDR : 2\n");
1268     printf("LE : 3\n");
1269     printf("select : ");
1270
1271     memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
1272     if( gets(buf) == NULL)
1273         return CA_NOT_SUPPORTED ;
1274
1275     int number = buf[0] - '0';
1276
1277     number = (number < 0 || number > 3) ? 0 : 1 << number;
1278
1279     if (!(number & 0xf))
1280     {
1281         return CA_NOT_SUPPORTED;
1282     }
1283     if (number & CA_ETHERNET)
1284     {
1285         gSelectedNwType = CA_ETHERNET;
1286         return CA_STATUS_OK;
1287     }
1288     if (number & CA_WIFI)
1289     {
1290         gSelectedNwType = CA_WIFI;
1291         return CA_STATUS_OK;
1292     }
1293     if (number & CA_EDR)
1294     {
1295         gSelectedNwType = CA_EDR;
1296         return CA_STATUS_OK;
1297     }
1298     if (number & CA_LE)
1299     {
1300         gSelectedNwType = CA_LE;
1301         return CA_STATUS_OK;
1302     }
1303
1304     printf("\n=============================================\n");
1305
1306     return CA_STATUS_FAILED;
1307 }