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