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