replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlientbasicops.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH 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 //      http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
19
20 #include "iotivity_config.h"
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <signal.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #ifdef HAVE_WINDOWS_H
29 #include <windows.h>
30 #endif
31 #include <stdint.h>
32 #include <sstream>
33 #include <iostream>
34 #include <getopt.h>
35
36 #include "ocstack.h"
37 #include "logger.h"
38 #include "occlientbasicops.h"
39 #include "ocpayload.h"
40 #include "payload_logging.h"
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include "common.h"
44
45 #define MAX_IP_ADDR_ST_SZ  16 //string size of "155.255.255.255" (15 + 1)
46 #define MAX_PORT_ST_SZ  6     //string size of "65535" (5 + 1)
47
48 static int UnicastDiscovery = 0;
49 static int TestCase = 0;
50 static int Connectivity = 0;
51
52 //The following variable determines the interface protocol (IP, etc)
53 //to be used for sending unicast messages. Default set to IP.
54 static OCConnectivityType ConnType = CT_ADAPTER_IP;
55 static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
56
57 int gQuitFlag = 0;
58
59 struct ResourceNode *resourceList;
60 /*
61  * SIGINT handler: set gQuitFlag to 1 for graceful termination
62  * */
63 void handleSigInt(int signum)
64 {
65     if (signum == SIGINT)
66     {
67         gQuitFlag = 1;
68     }
69 }
70
71 OCPayload* putPayload()
72 {
73     OCRepPayload* payload = OCRepPayloadCreate();
74
75     if(!payload)
76     {
77         std::cout << "Failed to create put payload object"<<std::endl;
78         std::exit(1);
79     }
80
81     OCRepPayloadSetPropInt(payload, "power", 15);
82     OCRepPayloadSetPropBool(payload, "state", true);
83
84     return (OCPayload*) payload;
85 }
86
87 static void PrintUsage()
88 {
89     OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
90     OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
91     OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
92     OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
93             " Initiate Nonconfirmable Get/Put/Post Requests");
94     OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate "
95             "Confirmable Get/Put/Post Requests");
96     OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
97     OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
98 }
99
100 /*
101  * Returns the first resource in the list
102  */
103 const ResourceNode * getResource()
104 {
105     return resourceList;
106 }
107
108 OCStackResult InvokeOCDoResource(std::ostringstream &query,
109                                  OCMethod method,
110                                  const OCDevAddr *dest,
111                                  OCQualityOfService qos,
112                                  OCClientResponseHandler cb,
113                                  OCHeaderOption * options, uint8_t numOptions)
114 {
115     OCStackResult ret;
116     OCCallbackData cbData;
117
118     cbData.cb = cb;
119     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
120     cbData.cd = NULL;
121
122     OCPayload* payload = (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL;
123
124     ret = OCDoRequest(NULL, method, query.str().c_str(), dest,
125                       payload, CT_DEFAULT, qos, &cbData, options, numOptions);
126
127     OCPayloadDestroy(payload);
128
129     if (ret != OC_STACK_OK)
130     {
131         OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d",
132                  ret, method);
133     }
134
135     return ret;
136 }
137
138 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
139                                   OCClientResponse * clientResponse)
140 {
141     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
142     {
143         OIC_LOG(INFO, TAG, "<====Callback Context for PUT received successfully====>");
144     }
145     else
146     {
147         OIC_LOG(ERROR, TAG, "<====Callback Context for PUT fail====>");
148     }
149
150     if(clientResponse)
151     {
152         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
153         OIC_LOG(INFO, TAG, ("=============> Put Response"));
154     }
155     else
156     {
157         OIC_LOG(ERROR, TAG, "<====PUT Callback fail to receive clientResponse====>\n");
158     }
159     return OC_STACK_DELETE_TRANSACTION;
160 }
161
162 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
163                                    OCClientResponse *clientResponse)
164 {
165     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
166     {
167         OIC_LOG(INFO, TAG, "<====Callback Context for POST received successfully====>");
168     }
169     else
170     {
171         OIC_LOG(ERROR, TAG, "<====Callback Context for POST fail====>");
172     }
173
174     if(clientResponse)
175     {
176         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
177         OIC_LOG(INFO, TAG, ("=============> Post Response"));
178     }
179     else
180     {
181         OIC_LOG(ERROR, TAG, "<====POST Callback fail to receive clientResponse====>\n");
182     }
183
184     return OC_STACK_DELETE_TRANSACTION;
185 }
186
187 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
188                                   OCClientResponse * clientResponse)
189 {
190     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
191     {
192         OIC_LOG(INFO, TAG, "<====Callback Context for GET received successfully====>");
193     }
194     else
195     {
196         OIC_LOG(ERROR, TAG, "<====Callback Context for GET fail====>");
197     }
198
199     if (clientResponse)
200     {
201         OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
202         OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
203         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
204         OIC_LOG(INFO, TAG, ("=============> Get Response"));
205
206         if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0 )
207         {
208             OIC_LOG (INFO, TAG, "Received vendor specific options");
209             uint8_t i = 0;
210             OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
211             for (i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
212             {
213                 if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)
214                 {
215                     OIC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
216                             ((OCHeaderOption)rcvdOptions[i]).optionID );
217
218                     OIC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
219                         MAX_HEADER_OPTION_DATA_LENGTH);
220                 }
221             }
222         }
223     }
224     else
225     {
226         OIC_LOG(ERROR, TAG, "<====GET Callback fail to receive clientResponse====>\n");
227     }
228     return OC_STACK_DELETE_TRANSACTION;
229 }
230
231 /*
232  * This is a function called back when a device is discovered
233  */
234 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
235                                         OCClientResponse * clientResponse)
236 {
237     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
238     {
239         OIC_LOG(INFO, TAG, "\n<====Callback Context for DISCOVERY query "
240                "received successfully====>");
241     }
242     else
243     {
244         OIC_LOG(ERROR, TAG, "\n<====Callback Context for DISCOVERY fail====>");
245     }
246
247     if (clientResponse)
248     {
249         OIC_LOG_V(INFO, TAG,
250                 "Device =============> Discovered @ %s:%d",
251                 clientResponse->devAddr.addr,
252                 clientResponse->devAddr.port);
253         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
254
255         collectUniqueResource(clientResponse);
256     }
257     else
258     {
259         OIC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
260     }
261     return (UnicastDiscovery) ?
262            OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
263 }
264
265 int InitPutRequest(OCQualityOfService qos)
266 {
267     std::ostringstream query;
268     //Get most recently inserted resource
269     const ResourceNode * resource  = getResource();
270
271     if(!resource)
272     {
273         OIC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
274         return -1;
275     }
276     query << resource->uri;
277     OIC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
278
279     return (InvokeOCDoResource(query, OC_REST_PUT, &resource->endpoint,
280            ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
281             putReqCB, NULL, 0));
282 }
283
284 int InitPostRequest(OCQualityOfService qos)
285 {
286     OCStackResult result;
287     std::ostringstream query;
288     //Get most recently inserted resource
289     const ResourceNode *resource  = getResource();
290
291     if(!resource)
292     {
293         OIC_LOG_V(ERROR, TAG, "Resource null, can't do POST request\n");
294         return -1;
295     }
296
297     query << resource->uri;
298     OIC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
299
300     // First POST operation (to create an LED instance)
301     result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
302             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
303             postReqCB, NULL, 0);
304     if (OC_STACK_OK != result)
305     {
306         // Error can happen if for example, network connectivity is down
307         OIC_LOG(ERROR, TAG, "First POST call did not succeed");
308     }
309
310     // Second POST operation (to create an LED instance)
311     result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
312             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
313             postReqCB, NULL, 0);
314     if (OC_STACK_OK != result)
315     {
316         OIC_LOG(ERROR, TAG, "Second POST call did not succeed");
317     }
318
319     // This POST operation will update the original resourced /a/led
320     return (InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
321                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
322                 postReqCB, NULL, 0));
323 }
324
325 int InitGetRequest(OCQualityOfService qos)
326 {
327     std::ostringstream query;
328     //Get most recently inserted resource
329     const ResourceNode * resource  = getResource();
330
331     if(!resource)
332     {
333         OIC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
334         return -1;
335     }
336     query << resource->uri;
337     OIC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
338
339     return (InvokeOCDoResource(query, OC_REST_GET, &resource->endpoint,
340             (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
341 }
342
343 int InitDiscovery()
344 {
345     OCStackResult ret;
346     OCCallbackData cbData;
347     char queryUri[200];
348     char ipaddr[100] = { '\0' };
349
350     if (UnicastDiscovery)
351     {
352         OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
353         OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
354         OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
355
356         if (fgets(ipaddr, sizeof (ipaddr), stdin))
357         {
358             StripNewLineChar(ipaddr); //Strip newline char from ipaddr
359         }
360         else
361         {
362             OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
363             return OC_STACK_INVALID_PARAM;
364         }
365     }
366
367     snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
368
369     cbData.cb = discoveryReqCB;
370     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
371     cbData.cd = NULL;
372
373     ret = OCDoRequest(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
374                       OC_LOW_QOS, &cbData, NULL, 0);
375     if (ret != OC_STACK_OK)
376     {
377         OIC_LOG(ERROR, TAG, "OCStack resource error");
378     }
379     return ret;
380 }
381
382 void queryResource()
383 {
384     switch(TestCase)
385     {
386         case TEST_DISCOVER_REQ:
387             break;
388         case TEST_NON_CON_OP:
389             InitGetRequest(OC_LOW_QOS);
390             InitPutRequest(OC_LOW_QOS);
391             InitPostRequest(OC_LOW_QOS);
392             break;
393         case TEST_CON_OP:
394             InitGetRequest(OC_HIGH_QOS);
395             InitPutRequest(OC_HIGH_QOS);
396             InitPostRequest(OC_HIGH_QOS);
397             break;
398         default:
399             PrintUsage();
400             break;
401     }
402 }
403
404
405 void collectUniqueResource(const OCClientResponse * clientResponse)
406 {
407     OCDiscoveryPayload* pay = (OCDiscoveryPayload*) clientResponse->payload;
408     OCResourcePayload* res = pay->resources;
409
410     // Including the NUL terminator, length of UUID string of the form:
411     //   "a62389f7-afde-00b6-cd3e-12b97d2fcf09"
412 #   define UUID_LENGTH 37
413
414     char sidStr[UUID_LENGTH];
415
416     while(res) {
417
418         int ret = snprintf(sidStr, UUID_LENGTH,
419                 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
420                 pay->sid[0], pay->sid[1], pay->sid[2], pay->sid[3],
421                 pay->sid[4], pay->sid[5], pay->sid[6], pay->sid[7],
422                 pay->sid[8], pay->sid[9], pay->sid[10], pay->sid[11],
423                 pay->sid[12], pay->sid[13], pay->sid[14], pay->sid[15]
424                 );
425
426         if (ret == UUID_LENGTH - 1)
427         {
428             if(insertResource(sidStr, res->uri, clientResponse) == 1)
429             {
430                 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is new");
431                 printResourceList();
432                 queryResource();
433             }
434             else {
435                 OIC_LOG_V(INFO,TAG,"%s%s%s%s\n",sidStr, ":", res->uri, " is old");
436             }
437         }
438         else
439         {
440             OIC_LOG(ERROR, TAG, "Could Not Retrieve the Server ID");
441         }
442
443         res = res->next;
444     }
445 }
446
447 /* This function searches for the resource(sid:uri) in the ResourceList.
448  * If the Resource is found in the list then it returns 0 else insert
449  * the resource to front of the list and returns 1.
450  */
451 int insertResource(const char * sid, char const * uri,
452             const OCClientResponse * clientResponse)
453 {
454     ResourceNode * iter = resourceList;
455     char * sid_cpy =  OICStrdup(sid);
456     char * uri_cpy = OICStrdup(uri);
457
458     //Checking if the resource(sid:uri) is new
459     while(iter)
460     {
461         if((strcmp(iter->sid, sid) == 0) && (strcmp(iter->uri, uri) == 0))
462         {
463             OICFree(sid_cpy);
464             OICFree(uri_cpy);
465             return 0;
466         }
467         else
468         {
469             iter = iter->next;
470         }
471     }
472
473     //Creating new ResourceNode
474     if((iter = (ResourceNode *) OICMalloc(sizeof(ResourceNode))))
475     {
476         iter->sid = sid_cpy;
477         iter->uri = uri_cpy;
478         iter->endpoint = clientResponse->devAddr;
479         iter->next = NULL;
480     }
481     else
482     {
483         OIC_LOG(ERROR, TAG, "Memory not allocated to ResourceNode");
484         OICFree(sid_cpy);
485         OICFree(uri_cpy);
486         return -1;
487     }
488
489     //Adding new ResourceNode to front of the ResourceList
490     if(!resourceList)
491     {
492         resourceList = iter;
493     }
494     else
495     {
496         iter->next = resourceList;
497         resourceList = iter;
498     }
499     return 1;
500 }
501
502 void printResourceList()
503 {
504     ResourceNode * iter;
505     iter = resourceList;
506     OIC_LOG(INFO, TAG, "Resource List: ");
507     while(iter)
508     {
509         OIC_LOG(INFO, TAG, "*****************************************************");
510         OIC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
511         OIC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
512         OIC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
513         OIC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
514         switch (iter->endpoint.adapter)
515         {
516             case OC_ADAPTER_IP:
517                 OIC_LOG(INFO, TAG, "connType = Default (IPv4)");
518                 break;
519             case OC_ADAPTER_GATT_BTLE:
520                 OIC_LOG(INFO, TAG, "connType = BLE");
521                 break;
522             case OC_ADAPTER_RFCOMM_BTEDR:
523                 OIC_LOG(INFO, TAG, "connType = BT");
524                 break;
525             default:
526                 OIC_LOG(INFO, TAG, "connType = Invalid connType");
527                 break;
528         }
529         OIC_LOG(INFO, TAG, "*****************************************************");
530         iter = iter->next;
531     }
532 }
533
534 void freeResourceList()
535 {
536     OIC_LOG(INFO, TAG, "Freeing ResourceNode List");
537     ResourceNode * temp;
538     while(resourceList)
539     {
540
541         temp = resourceList;
542         resourceList = resourceList->next;
543         OICFree((void *)temp->sid);
544         OICFree((void *)temp->uri);
545         OICFree(temp);
546     }
547     resourceList = NULL;
548 }
549
550 int main(int argc, char* argv[])
551 {
552     int opt;
553     resourceList = NULL;
554     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
555     {
556         switch(opt)
557         {
558             case 'u':
559                 UnicastDiscovery = atoi(optarg);
560                 break;
561             case 't':
562                 TestCase = atoi(optarg);
563                 break;
564             case 'c':
565                 Connectivity = atoi(optarg);
566                 break;
567             default:
568                 PrintUsage();
569                 return -1;
570         }
571     }
572
573     if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
574         (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
575         (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
576     {
577         PrintUsage();
578         return -1;
579     }
580
581     /* Initialize OCStack*/
582     if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
583     {
584         OIC_LOG(ERROR, TAG, "OCStack init error");
585         return 0;
586     }
587
588     if(Connectivity == CT_ADAPTER_DEFAULT || Connectivity ==  CT_IP)
589     {
590         ConnType =  CT_ADAPTER_IP;//CT_DEFAULT;
591     }
592     else
593     {
594         OIC_LOG(INFO, TAG, "Default Connectivity type selected");
595         PrintUsage();
596     }
597
598     InitDiscovery();
599
600     // Break from loop with Ctrl+C
601     signal(SIGINT, handleSigInt);
602
603     while (!gQuitFlag)
604     {
605         if (OCProcess() != OC_STACK_OK)
606         {
607             OIC_LOG(ERROR, TAG, "OCStack process error");
608             return 0;
609         }
610         sleep(2);
611     }
612
613     freeResourceList();
614     OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
615     if (OCStop() != OC_STACK_OK)
616     {
617         OIC_LOG(ERROR, TAG, "OCStack stop error");
618     }
619     return 0;
620 }
621
622