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