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