replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / secure / 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 //
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 "iotivity_config.h"
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <signal.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_WINDOWS_H
30 #include <windows.h>
31 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
32 #ifdef ERROR
33 #undef ERROR
34 #endif
35 #endif
36 #include <iostream>
37 #include <sstream>
38 #include <getopt.h>
39 #include "ocstack.h"
40 #include "logger.h"
41 #include "occlientbasicops.h"
42 #include "ocpayload.h"
43 #include "payload_logging.h"
44 #include "oic_string.h"
45 #include "common.h"
46
47 #define TAG "occlientbasicops"
48 static int UnicastDiscovery = 0;
49 static int TestCase = 0;
50 static int ConnType = 0;
51 static int DevOwner = 0;
52 static int WithTcp = 0;
53
54 static char DISCOVERY_QUERY[] = "%s/oic/res";
55 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
56 static OCDevAddr endpoint;
57
58 static std::string coapServerResource;
59 static int coapSecureResource;
60 static OCConnectivityType ocConnType;
61
62 //Secure Virtual Resource database for Iotivity Client application
63 //It contains Client's Identity and the PSK credentials
64 //of other devices which the client trusts
65 static char CRED_FILE_DEVOWNER[] = "oic_svr_db_client_devowner.dat";
66 static char CRED_FILE_NONDEVOWNER[] = "oic_svr_db_client_nondevowner.dat";
67 const char * OIC_RSRC_DOXM_URI =  "/oic/sec/doxm";
68 const char * OIC_RSRC_PSTAT_URI = "/oic/sec/pstat";
69
70 int gQuitFlag = 0;
71
72 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
73 void handleSigInt(int signum)
74 {
75     if (signum == SIGINT)
76     {
77         gQuitFlag = 1;
78     }
79 }
80
81 OCPayload* putPayload()
82 {
83     OCRepPayload* payload = OCRepPayloadCreate();
84
85     if(!payload)
86     {
87         std::cout << "Failed to create put payload object"<<std::endl;
88         std::exit(1);
89     }
90
91     OCRepPayloadSetPropInt(payload, "power", 15);
92     OCRepPayloadSetPropBool(payload, "state", true);
93
94     return (OCPayload*) payload;
95 }
96
97 static void PrintUsage()
98 {
99     OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
100     OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
101     OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
102     OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
103             " Initiate Nonconfirmable Get/Put/Post Requests");
104     OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
105     OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
106     OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
107     OIC_LOG(INFO, TAG, "-d 0 : Client as Non Device Owner");
108     OIC_LOG(INFO, TAG, "-d 1 : Client as Device Owner");
109     OIC_LOG(INFO, TAG, "-p 0 : Use UDP protocol");
110     OIC_LOG(INFO, TAG, "-p 1 : Use TCP protocol");
111 }
112
113 OCStackResult InvokeOCDoResource(std::ostringstream &query,
114                                  OCMethod method,
115                                  const OCDevAddr *dest,
116                                  OCQualityOfService qos,
117                                  OCClientResponseHandler cb,
118                                  OCHeaderOption * options, uint8_t numOptions)
119 {
120     OCStackResult ret;
121     OCCallbackData cbData;
122
123     cbData.cb = cb;
124     cbData.context = NULL;
125     cbData.cd = NULL;
126
127     OCPayload* payload = (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL;
128
129     ret = OCDoRequest(NULL, method, query.str().c_str(), dest,
130                       payload, ocConnType, qos, &cbData, options, numOptions);
131
132     OCPayloadDestroy(payload);
133
134     if (ret != OC_STACK_OK)
135     {
136         OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
137     }
138
139     return ret;
140 }
141
142 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
143 {
144     OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
145
146     if(clientResponse)
147     {
148         OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
149         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
150         OIC_LOG(INFO, TAG, "=============> Put Response");
151     }
152     return OC_STACK_DELETE_TRANSACTION;
153 }
154
155 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
156 {
157     OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
158
159     if(clientResponse)
160     {
161         OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
162         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
163         OIC_LOG(INFO, TAG, "=============> Post Response");
164     }
165     return OC_STACK_DELETE_TRANSACTION;
166 }
167
168 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
169 {
170     OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
171
172     if(clientResponse)
173     {
174         OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
175         OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
176         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
177         OIC_LOG(INFO, TAG, "=============> Get Response");
178     }
179     return OC_STACK_DELETE_TRANSACTION;
180 }
181
182 // This is a function called back when a device is discovered
183 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
184         OCClientResponse * clientResponse)
185 {
186     OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
187
188     if (clientResponse)
189     {
190         OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
191         OIC_LOG_V(INFO, TAG,
192                 "Device =============> Discovered @ %s:%d",
193                 clientResponse->devAddr.addr,
194                 clientResponse->devAddr.port);
195
196         if (clientResponse->result == OC_STACK_OK)
197         {
198             OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
199
200             ocConnType = clientResponse->connType;
201             endpoint = clientResponse->devAddr;
202
203             if (parseClientResponse(clientResponse) != -1)
204             {
205                 switch(TestCase)
206                 {
207                     case TEST_NON_CON_OP:
208                         InitGetRequest(OC_LOW_QOS);
209                         InitPutRequest(OC_LOW_QOS);
210                         InitPostRequest(OC_LOW_QOS);
211                         break;
212                     case TEST_CON_OP:
213                         InitGetRequest(OC_HIGH_QOS);
214                         InitPutRequest(OC_HIGH_QOS);
215                         InitPostRequest(OC_HIGH_QOS);
216                         break;
217                 }
218             }
219         }
220     }
221
222     return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
223
224 }
225 int InitPutRequest(OCQualityOfService qos)
226 {
227     OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
228     std::ostringstream query;
229     query << coapServerResource;
230     if(WithTcp)
231     {
232         endpoint.adapter = OC_ADAPTER_TCP;
233     }
234     endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
235     return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
236             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
237 }
238
239 int InitPostRequest(OCQualityOfService qos)
240 {
241     OCStackResult result;
242
243     OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
244     std::ostringstream query;
245     query << coapServerResource;
246     if(WithTcp)
247     {
248         endpoint.adapter = OC_ADAPTER_TCP;
249     }
250     endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
251
252     // First POST operation (to create an LED instance)
253     result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
254             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
255             postReqCB, NULL, 0);
256     if (OC_STACK_OK != result)
257     {
258         // Error can happen if for example, network connectivity is down
259         OIC_LOG(INFO, TAG, "First POST call did not succeed");
260     }
261
262     // Second POST operation (to create an LED instance)
263     result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
264             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
265             postReqCB, NULL, 0);
266     if (OC_STACK_OK != result)
267     {
268         OIC_LOG(INFO, TAG, "Second POST call did not succeed");
269     }
270
271     // This POST operation will update the original resourced /a/led (as long as
272     // the server is set to max 2 /lcd resources)
273     result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
274             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
275             postReqCB, NULL, 0);
276     if (OC_STACK_OK != result)
277     {
278         OIC_LOG(INFO, TAG, "Third POST call did not succeed");
279     }
280     return result;
281 }
282
283 int InitGetRequest(OCQualityOfService qos)
284 {
285     OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
286     std::ostringstream query;
287     query << coapServerResource;
288     if(WithTcp)
289     {
290         endpoint.adapter = OC_ADAPTER_TCP;
291     }
292     endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
293
294     return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
295                 ((qos == OC_HIGH_QOS)?  OC_HIGH_QOS:OC_LOW_QOS),
296                 getReqCB, NULL, 0));
297 }
298
299 int InitDiscovery()
300 {
301     OCStackResult ret;
302     OCCallbackData cbData;
303     char queryUri[200];
304     char ipaddr[100] = { '\0' };
305
306     if (UnicastDiscovery)
307     {
308         OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
309         OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
310         OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
311
312         if (fgets(ipaddr, sizeof (ipaddr), stdin))
313         {
314             StripNewLineChar(ipaddr); //Strip newline char from ipaddr
315         }
316         else
317         {
318             OIC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
319             return OC_STACK_INVALID_PARAM;
320         }
321     }
322     snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
323
324     cbData.cb = discoveryReqCB;
325     cbData.context = NULL;
326     cbData.cd = NULL;
327
328     /* Start a discovery query*/
329     OIC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
330         (UnicastDiscovery) ? "Unicast" : "Multicast",
331         queryUri);
332
333     ret = OCDoRequest(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
334                       OC_LOW_QOS, &cbData, NULL, 0);
335     if (ret != OC_STACK_OK)
336     {
337         OIC_LOG(ERROR, TAG, "OCStack resource error");
338     }
339     return ret;
340 }
341
342 FILE* client_fopen_devowner(const char *path, const char *mode)
343 {
344     (void)path;
345     return fopen(CRED_FILE_DEVOWNER, mode);
346 }
347
348 FILE* client_fopen_nondevowner(const char *path, const char *mode)
349 {
350     (void)path;
351     return fopen(CRED_FILE_NONDEVOWNER, mode);
352 }
353 int main(int argc, char* argv[])
354 {
355     int opt;
356     struct timespec timeout;
357     OCPersistentStorage ps;
358
359     while ((opt = getopt(argc, argv, "u:t:c:d:p:")) != -1)
360     {
361         switch(opt)
362         {
363             case 'u':
364                 UnicastDiscovery = atoi(optarg);
365                 break;
366             case 't':
367                 TestCase = atoi(optarg);
368                 break;
369             case 'c':
370                 ConnType = atoi(optarg);
371                 break;
372             case 'd':
373                 DevOwner = atoi(optarg);
374                 break;
375             case 'p':
376             {
377                 WithTcp = atoi(optarg);
378                 if(WithTcp > 1)
379                 {
380                     PrintUsage();
381                     return -1;
382                 }
383             }
384                 break;
385             default:
386                 PrintUsage();
387                 return -1;
388         }
389     }
390
391     if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
392             (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
393             (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
394     {
395         PrintUsage();
396         return -1;
397     }
398
399
400     if(ConnType == CT_ADAPTER_DEFAULT || ConnType ==  CT_IP)
401     {
402         discoveryReqConnType = CT_DEFAULT;
403     }
404     else
405     {
406         OIC_LOG(INFO, TAG, "Using Default Connectivity type");
407         PrintUsage();
408     }
409
410
411     // Initialize Persistent Storage for SVR database
412     if (DevOwner)
413         ps = { client_fopen_devowner, fread, fwrite, fclose, unlink };
414     else
415         ps = { client_fopen_nondevowner, fread, fwrite, fclose, unlink };
416     OCRegisterPersistentStorageHandler(&ps);
417
418     /* Initialize OCStack*/
419     if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
420     {
421         OIC_LOG(ERROR, TAG, "OCStack init error");
422         return 0;
423     }
424
425     InitDiscovery();
426
427     timeout.tv_sec  = 0;
428     timeout.tv_nsec = 100000000L;
429
430     // Break from loop with Ctrl+C
431     OIC_LOG(INFO, TAG, "Entering occlient main loop...");
432     signal(SIGINT, handleSigInt);
433     while (!gQuitFlag)
434     {
435         if (OCProcess() != OC_STACK_OK)
436         {
437             OIC_LOG(ERROR, TAG, "OCStack process error");
438             return 0;
439         }
440
441         nanosleep(&timeout, NULL);
442     }
443     OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
444
445     if (OCStop() != OC_STACK_OK)
446     {
447         OIC_LOG(ERROR, TAG, "OCStack stop error");
448     }
449
450     return 0;
451 }
452
453 int parseClientResponse(OCClientResponse * clientResponse)
454 {
455     OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
456
457     // Initialize all global variables
458     coapServerResource.clear();
459     coapSecureResource = 0;
460
461     while (res)
462     {
463         coapServerResource.assign(res->uri);
464         OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
465         if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_DOXM_URI))
466         {
467             OIC_LOG(INFO,TAG,"Skip: doxm is secure virtual resource");
468             res = res->next;
469             continue;
470         }
471         if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_PSTAT_URI))
472         {
473             OIC_LOG(INFO,TAG,"Skip: pstat is secure virtual resource");
474             res = res->next;
475             continue;
476         }
477         if (res->secure)
478         {
479             if(WithTcp)
480             {
481 #ifdef TCP_ADAPTER
482                 OIC_LOG_V(INFO,TAG,"SECUREPORT tcp: %d",res->tcpPort);
483                 endpoint.port = res->tcpPort;
484 #endif
485             }
486             else
487             {
488                 OIC_LOG_V(INFO,TAG,"SECUREPORT udp: %d",res->port);
489                 endpoint.port = res->port;
490             }
491             coapSecureResource = 1;
492         }
493
494         OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
495
496         // If we discovered a secure resource, exit from here
497         if (coapSecureResource)
498         {
499             break;
500         }
501
502         res = res->next;
503     }
504
505     return 0;
506 }
507