Merge branch 'master' into notification-service
[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
57 int gQuitFlag = 0;
58
59 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
60 void handleSigInt(int signum)
61 {
62     if (signum == SIGINT)
63     {
64         gQuitFlag = 1;
65     }
66 }
67
68 OCPayload* putPayload()
69 {
70     OCRepPayload* payload = OCRepPayloadCreate();
71
72     if(!payload)
73     {
74         std::cout << "Failed to create put payload object"<<std::endl;
75         std::exit(1);
76     }
77
78     OCRepPayloadSetPropInt(payload, "power", 15);
79     OCRepPayloadSetPropBool(payload, "state", true);
80
81     return (OCPayload*) payload;
82 }
83
84 static void PrintUsage()
85 {
86     OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
87     OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
88     OIC_LOG(INFO, TAG, "-t 1 : Discover Resources");
89     OIC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
90             " Initiate Nonconfirmable Get/Put/Post Requests");
91     OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
92     OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
93     OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
94     OIC_LOG(INFO, TAG, "-d 0 : Client as Device Owner");
95     OIC_LOG(INFO, TAG, "-d 1 : Client as Non Device Owner");
96 }
97
98 OCStackResult InvokeOCDoResource(std::ostringstream &query,
99                                  OCMethod method,
100                                  const OCDevAddr *dest,
101                                  OCQualityOfService qos,
102                                  OCClientResponseHandler cb,
103                                  OCHeaderOption * options, uint8_t numOptions)
104 {
105     OCStackResult ret;
106     OCCallbackData cbData;
107
108     cbData.cb = cb;
109     cbData.context = NULL;
110     cbData.cd = NULL;
111
112     ret = OCDoResource(NULL, method, query.str().c_str(), dest,
113             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
114             ocConnType, qos, &cbData, options, numOptions);
115
116     if (ret != OC_STACK_OK)
117     {
118         OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
119     }
120
121     return ret;
122 }
123
124 OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
125 {
126     OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
127
128     if(clientResponse)
129     {
130         OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
131         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
132         OIC_LOG(INFO, TAG, ("=============> Put Response"));
133     }
134     return OC_STACK_DELETE_TRANSACTION;
135 }
136
137 OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
138 {
139     OIC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
140
141     if(clientResponse)
142     {
143         OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
144         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
145         OIC_LOG(INFO, TAG, ("=============> Post Response"));
146     }
147     return OC_STACK_DELETE_TRANSACTION;
148 }
149
150 OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
151 {
152     OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
153
154     if(clientResponse)
155     {
156         OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
157         OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
158         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
159         OIC_LOG(INFO, TAG, ("=============> Get Response"));
160     }
161     return OC_STACK_DELETE_TRANSACTION;
162 }
163
164 // This is a function called back when a device is discovered
165 OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
166         OCClientResponse * clientResponse)
167 {
168     OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
169
170     if (clientResponse)
171     {
172         OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
173         OIC_LOG_V(INFO, TAG,
174                 "Device =============> Discovered @ %s:%d",
175                 clientResponse->devAddr.addr,
176                 clientResponse->devAddr.port);
177
178         if (clientResponse->result == OC_STACK_OK)
179         {
180             OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
181
182             ocConnType = clientResponse->connType;
183             endpoint = clientResponse->devAddr;
184
185             if (parseClientResponse(clientResponse) != -1)
186             {
187                 switch(TestCase)
188                 {
189                     case TEST_NON_CON_OP:
190                         InitGetRequest(OC_LOW_QOS);
191                         InitPutRequest(OC_LOW_QOS);
192                         //InitPostRequest(OC_LOW_QOS);
193                         break;
194                     case TEST_CON_OP:
195                         InitGetRequest(OC_HIGH_QOS);
196                         InitPutRequest(OC_HIGH_QOS);
197                         //InitPostRequest(OC_HIGH_QOS);
198                         break;
199                 }
200             }
201         }
202     }
203
204     return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
205
206 }
207
208 int InitPutRequest(OCQualityOfService qos)
209 {
210     OIC_LOG_V(INFO, TAG, "Executing %s", __func__);
211     std::ostringstream query;
212     query << coapServerResource;
213     endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
214     return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
215             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
216 }
217
218 int InitPostRequest(OCQualityOfService qos)
219 {
220     OCStackResult result;
221
222     OIC_LOG_V(INFO, TAG, "Executing %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, "Executing %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 (res->secure)
427         {
428         OIC_LOG_V(INFO,TAG,"SECUREPORT: %d",res->port);
429             endpoint.port = res->port;
430             coapSecureResource = 1;
431         }
432
433         OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
434
435         // If we discovered a secure resource, exit from here
436         if (coapSecureResource)
437         {
438             break;
439         }
440
441         res = res->next;
442     }
443
444     return 0;
445 }
446