Updated Iotivity to compile DTLS modules using SCons
[contrib/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 "cJSON.h"
32 #include "common.h"
33
34 #define TAG "occlientbasicops"
35 static int UNICAST_DISCOVERY = 0;
36 static int TEST_CASE = 0;
37
38 #ifdef CA_INT_DTLS
39 static int IPV4_ADDR_SIZE = 16;
40 #else
41 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
42 #endif
43 static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
44 static std::string coapServerIP;
45 static std::string coapServerPort;
46 static std::string coapServerResource;
47 static int coapSecureResource;
48
49 //File containing Client's Identity and the PSK credentials
50 //of other devices which the client trusts
51 //This can be generated using 'gen_sec_bin' application
52 static char CRED_FILE[] = "client_cred.bin";
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 static void PrintUsage()
67 {
68     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
69     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
70     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
71     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
72             " Initiate Nonconfirmable Get/Put/Post Requests");
73     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
74 }
75
76 OCStackResult InvokeOCDoResource(std::ostringstream &query,
77         OCMethod method, OCQualityOfService qos,
78         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
79 {
80     OCStackResult ret;
81     OCCallbackData cbData;
82     OCDoHandle handle;
83
84     cbData.cb = cb;
85     cbData.context = NULL;
86     cbData.cd = NULL;
87
88     ret = OCDoResource(&handle, method, query.str().c_str(), 0,
89             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
90 #ifdef CA_INT
91             (OC_WIFI),
92 #endif
93             qos, &cbData, options, numOptions);
94
95     if (ret != OC_STACK_OK)
96     {
97         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
98     }
99
100     return ret;
101 }
102
103 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
104 {
105     OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
106
107     if(clientResponse)
108     {
109         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
110         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
111     }
112     return OC_STACK_DELETE_TRANSACTION;
113 }
114
115 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
116 {
117     OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
118
119     if(clientResponse)
120     {
121         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
122         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
123                 clientResponse->resJSONPayload);
124     }
125     return OC_STACK_DELETE_TRANSACTION;
126 }
127
128 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
129 {
130     OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
131
132     if(clientResponse)
133     {
134         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
135         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
136         OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
137                 clientResponse->resJSONPayload);
138     }
139     return OC_STACK_DELETE_TRANSACTION;
140 }
141
142 // This is a function called back when a device is discovered
143 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
144         OCClientResponse * clientResponse)
145 {
146     uint8_t remoteIpAddr[4];
147     uint16_t remotePortNu;
148
149     OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
150
151     if (clientResponse)
152     {
153         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
154
155         OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
156                 remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
157         OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
158
159         OC_LOG_V(INFO, TAG,
160                 "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
161                 clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
162                 remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
163
164         if (parseClientResponse(clientResponse) != -1)
165         {
166             switch(TEST_CASE)
167             {
168                 case TEST_NON_CON_OP:
169                     InitGetRequest(OC_LOW_QOS);
170                     InitPutRequest();
171                     //InitPostRequest(OC_LOW_QOS);
172                     break;
173                 case TEST_CON_OP:
174                     InitGetRequest(OC_HIGH_QOS);
175                     InitPutRequest();
176                     //InitPostRequest(OC_HIGH_QOS);
177                     break;
178             }
179         }
180     }
181
182     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
183
184 }
185
186 int InitPutRequest()
187 {
188     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
189     std::ostringstream query;
190     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
191         << ":" << coapServerPort  << coapServerResource;
192     return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
193 }
194
195 int InitPostRequest(OCQualityOfService qos)
196 {
197     OCStackResult result;
198     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
199     std::ostringstream query;
200     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
201         << ":" << coapServerPort << coapServerResource;
202
203     // First POST operation (to create an LED instance)
204     result = InvokeOCDoResource(query, OC_REST_POST,
205             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
206             postReqCB, NULL, 0);
207     if (OC_STACK_OK != result)
208     {
209         // Error can happen if for example, network connectivity is down
210         OC_LOG(INFO, TAG, "First POST call did not succeed");
211     }
212
213     // Second POST operation (to create an LED instance)
214     result = InvokeOCDoResource(query, OC_REST_POST,
215             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
216             postReqCB, NULL, 0);
217     if (OC_STACK_OK != result)
218     {
219         OC_LOG(INFO, TAG, "Second POST call did not succeed");
220     }
221
222     // This POST operation will update the original resourced /a/led
223     return (InvokeOCDoResource(query, OC_REST_POST,
224                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
225                 postReqCB, NULL, 0));
226 }
227
228 int InitGetRequest(OCQualityOfService qos)
229 {
230     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
231     std::ostringstream query;
232     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
233         << ":" << coapServerPort << coapServerResource;
234
235     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
236             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
237 }
238
239 int InitDiscovery()
240 {
241     OCStackResult ret;
242     OCCallbackData cbData;
243     OCDoHandle handle;
244     /* Start a discovery query*/
245     char szQueryUri[MAX_URI_LENGTH] = { 0 };
246
247     if (UNICAST_DISCOVERY)
248     {
249 #ifdef CA_INT_DTLS
250         char ipv4addr[IPV4_ADDR_SIZE];
251
252         printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
253         fgets(ipv4addr, IPV4_ADDR_SIZE, stdin);
254         snprintf(szQueryUri, sizeof(szQueryUri), "coap://%s:5683/oc/core", ipv4addr);
255 #else
256         strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
257 #endif
258     }
259     else
260     {
261         strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
262     }
263     cbData.cb = discoveryReqCB;
264     cbData.context = NULL;
265     cbData.cd = NULL;
266     ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0,
267 #ifdef CA_INT
268             (OC_WIFI),
269 #endif
270             OC_LOW_QOS, &cbData, NULL, 0);
271     if (ret != OC_STACK_OK)
272     {
273         OC_LOG(ERROR, TAG, "OCStack resource error");
274     }
275     return ret;
276 }
277
278 int main(int argc, char* argv[])
279 {
280     uint8_t addr[20] = {0};
281     uint8_t* paddr = NULL;
282     uint16_t port = USE_RANDOM_PORT;
283     uint8_t ifname[] = "eth0";
284     int opt;
285     struct timespec timeout;
286
287     while ((opt = getopt(argc, argv, "u:t:")) != -1)
288     {
289         switch(opt)
290         {
291             case 'u':
292                 UNICAST_DISCOVERY = atoi(optarg);
293                 break;
294             case 't':
295                 TEST_CASE = atoi(optarg);
296                 break;
297             default:
298                 PrintUsage();
299                 return -1;
300         }
301     }
302
303     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
304             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
305     {
306         PrintUsage();
307         return -1;
308     }
309
310
311     /*Get Ip address on defined interface and initialize coap on it with random port number
312      * this port number will be used as a source port in all coap communications*/
313     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
314                 sizeof(addr)) == ERR_SUCCESS)
315     {
316         OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
317         paddr = addr;
318     }
319
320     /* Initialize OCStack*/
321     if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
322     {
323         OC_LOG(ERROR, TAG, "OCStack init error");
324         return 0;
325     }
326
327     /*
328      * Read DTLS PSK credentials from persistent storage and
329      * set in the OC stack.
330      */
331     if (SetCredentials(CRED_FILE) != OC_STACK_OK)
332     {
333         OC_LOG(ERROR, TAG, "SetCredentials failed");
334         return 0;
335     }
336
337     InitDiscovery();
338
339     timeout.tv_sec  = 0;
340     timeout.tv_nsec = 100000000L;
341
342     // Break from loop with Ctrl+C
343     OC_LOG(INFO, TAG, "Entering occlient main loop...");
344     signal(SIGINT, handleSigInt);
345     while (!gQuitFlag)
346     {
347         if (OCProcess() != OC_STACK_OK)
348         {
349             OC_LOG(ERROR, TAG, "OCStack process error");
350             return 0;
351         }
352
353         nanosleep(&timeout, NULL);
354     }
355     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
356
357     if (OCStop() != OC_STACK_OK)
358     {
359         OC_LOG(ERROR, TAG, "OCStack stop error");
360     }
361
362     return 0;
363 }
364
365 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
366 {
367     if(!clientResponse) return "";
368     if(!clientResponse->addr) return "";
369     uint8_t a, b, c, d = 0;
370     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
371
372     char ipaddr[16] = {'\0'};
373     // ostringstream not working correctly here, hence snprintf
374     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
375     return std::string (ipaddr);
376 }
377
378
379 std::string getPortTBServer(OCClientResponse * clientResponse)
380 {
381     if(!clientResponse) return "";
382     if(!clientResponse->addr) return "";
383     uint16_t p = 0;
384     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
385     std::ostringstream ss;
386     ss << p;
387     return ss.str();
388 }
389
390 int parseClientResponse(OCClientResponse * clientResponse)
391 {
392     int port = -1;
393     cJSON * root = NULL;
394     cJSON * oc = NULL;
395
396     // Initialize all global variables
397     coapServerResource.clear();
398     coapServerPort.clear();
399     coapServerIP.clear();
400     coapSecureResource = 0;
401
402     root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
403     if (!root)
404     {
405         return -1;
406     }
407
408     oc = cJSON_GetObjectItem(root,"oc");
409     if (!oc)
410     {
411         return -1;
412     }
413
414     if (oc->type == cJSON_Array)
415     {
416         if (cJSON_GetArraySize(oc) > 0)
417         {
418             cJSON * resource = cJSON_GetArrayItem(oc, 0);
419             if (cJSON_GetObjectItem(resource, "href"))
420             {
421                 coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
422             }
423             else
424             {
425                 coapServerResource = "";
426             }
427             OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
428
429             cJSON * prop = cJSON_GetObjectItem(resource,"prop");
430             if (prop)
431             {
432                 // If this is a secure resource, the info about the port at which the
433                 // resource is hosted on server is embedded inside discovery JSON response
434                 if (cJSON_GetObjectItem(prop, "sec"))
435                 {
436                     if ((cJSON_GetObjectItem(prop, "sec")->valueint) == 1)
437                     {
438                         coapSecureResource = 1;
439                     }
440                 }
441                 OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
442                 if (cJSON_GetObjectItem(prop, "port"))
443                 {
444                     port = cJSON_GetObjectItem(prop, "port")->valueint;
445                     OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
446
447                     std::ostringstream ss;
448                     ss << port;
449                     coapServerPort = ss.str();
450                 }
451             }
452         }
453     }
454     cJSON_Delete(root);
455
456     coapServerIP = getIPAddrTBServer(clientResponse);
457     if (port == -1)
458     {
459         coapServerPort = getPortTBServer(clientResponse);
460         OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
461     }
462     return 0;
463 }