Updated resource discovery parsing logic for new 'policy' node
[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 "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 static int IPV4_ADDR_SIZE = 16;
39 static char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oic/res";
40 static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
41
42 static std::string putPayload = "{\"oic\":[{\"rep\":{\"state\":\"off\",\"power\":10}}]}";
43 static std::string coapServerIP;
44 static std::string coapServerPort;
45 static std::string coapServerResource;
46 static int coapSecureResource;
47 static OCConnectivityType ocConnType;
48
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[] = "oic_svr_db_client.json";
54
55
56 int gQuitFlag = 0;
57
58 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
59 void handleSigInt(int signum)
60 {
61     if (signum == SIGINT)
62     {
63         gQuitFlag = 1;
64     }
65 }
66
67 static void PrintUsage()
68 {
69     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
70     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
71     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
72     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
73             " Initiate Nonconfirmable Get/Put/Post Requests");
74     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
75 }
76
77 OCStackResult InvokeOCDoResource(std::ostringstream &query,
78         OCMethod method, OCQualityOfService qos,
79         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
80 {
81     OCStackResult ret;
82     OCCallbackData cbData;
83
84     cbData.cb = cb;
85     cbData.context = NULL;
86     cbData.cd = NULL;
87
88     ret = OCDoResource(NULL, method, query.str().c_str(), 0,
89             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
90             ocConnType, 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         ocConnType = clientResponse->connType;
162
163         if (parseClientResponse(clientResponse) != -1)
164         {
165             switch(TEST_CASE)
166             {
167                 case TEST_NON_CON_OP:
168                     InitGetRequest(OC_LOW_QOS);
169                     InitPutRequest(OC_LOW_QOS);
170                     //InitPostRequest(OC_LOW_QOS);
171                     break;
172                 case TEST_CON_OP:
173                     InitGetRequest(OC_HIGH_QOS);
174                     InitPutRequest(OC_HIGH_QOS);
175                     //InitPostRequest(OC_HIGH_QOS);
176                     break;
177             }
178         }
179     }
180
181     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
182
183 }
184
185 int InitPutRequest(OCQualityOfService qos)
186 {
187     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
188     std::ostringstream query;
189     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
190         << ":" << coapServerPort  << coapServerResource;
191     return (InvokeOCDoResource(query, OC_REST_PUT,
192             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: 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     char szQueryUri[MAX_URI_LENGTH] = { 0 };
244     OCConnectivityType discoveryReqConnType;
245
246     if (UNICAST_DISCOVERY)
247     {
248         char ipv4addr[IPV4_ADDR_SIZE];
249         printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
250         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
251         {
252             //Strip newline char from ipv4addr
253             StripNewLineChar(ipv4addr);
254             snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
255         }
256         else
257         {
258             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
259             return OC_STACK_INVALID_PARAM;
260         }
261         discoveryReqConnType = OC_IPV4;
262     }
263     else
264     {
265         //Send discovery request on Wifi and Ethernet interface
266         discoveryReqConnType = OC_ALL;
267         strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
268     }
269
270     cbData.cb = discoveryReqCB;
271     cbData.context = NULL;
272     cbData.cd = NULL;
273
274     /* Start a discovery query*/
275     OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
276         (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
277         szQueryUri);
278
279     ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0,
280             discoveryReqConnType, OC_LOW_QOS,
281             &cbData, NULL, 0);
282     if (ret != OC_STACK_OK)
283     {
284         OC_LOG(ERROR, TAG, "OCStack resource error");
285     }
286     return ret;
287 }
288
289 FILE* client_fopen(const char *path, const char *mode)
290 {
291     (void)path;
292     return fopen(CRED_FILE, mode);
293 }
294
295 int main(int argc, char* argv[])
296 {
297     int opt;
298     struct timespec timeout;
299
300     while ((opt = getopt(argc, argv, "u:t:")) != -1)
301     {
302         switch(opt)
303         {
304             case 'u':
305                 UNICAST_DISCOVERY = atoi(optarg);
306                 break;
307             case 't':
308                 TEST_CASE = atoi(optarg);
309                 break;
310             default:
311                 PrintUsage();
312                 return -1;
313         }
314     }
315
316     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
317             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
318     {
319         PrintUsage();
320         return -1;
321     }
322
323     // Initialize Persistent Storage for SVR database
324     OCPersistentStorage ps = {};
325     ps.open = client_fopen;
326     ps.read = fread;
327     ps.write = fwrite;
328     ps.close = fclose;
329     ps.unlink = unlink;
330     OCRegisterPersistentStorageHandler(&ps);
331
332     /* Initialize OCStack*/
333     if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
334     {
335         OC_LOG(ERROR, TAG, "OCStack init error");
336         return 0;
337     }
338
339     InitDiscovery();
340
341     timeout.tv_sec  = 0;
342     timeout.tv_nsec = 100000000L;
343
344     // Break from loop with Ctrl+C
345     OC_LOG(INFO, TAG, "Entering occlient main loop...");
346     signal(SIGINT, handleSigInt);
347     while (!gQuitFlag)
348     {
349         if (OCProcess() != OC_STACK_OK)
350         {
351             OC_LOG(ERROR, TAG, "OCStack process error");
352             return 0;
353         }
354
355         nanosleep(&timeout, NULL);
356     }
357     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
358
359     if (OCStop() != OC_STACK_OK)
360     {
361         OC_LOG(ERROR, TAG, "OCStack stop error");
362     }
363
364     return 0;
365 }
366
367 std::string getIPAddrTBServer(OCClientResponse * clientResponse)
368 {
369     if(!clientResponse) return "";
370     if(!clientResponse->addr) return "";
371     uint8_t a, b, c, d = 0;
372     if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
373
374     char ipaddr[16] = {'\0'};
375     // ostringstream not working correctly here, hence snprintf
376     snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
377     return std::string (ipaddr);
378 }
379
380
381 std::string getPortTBServer(OCClientResponse * clientResponse)
382 {
383     if(!clientResponse) return "";
384     if(!clientResponse->addr) return "";
385     uint16_t p = 0;
386     if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
387     std::ostringstream ss;
388     ss << p;
389     return ss.str();
390 }
391
392 int parseClientResponse(OCClientResponse * clientResponse)
393 {
394     int port = -1;
395     cJSON * root = NULL;
396     cJSON * oc = NULL;
397
398     // Initialize all global variables
399     coapServerResource.clear();
400     coapServerPort.clear();
401     coapServerIP.clear();
402     coapSecureResource = 0;
403
404     root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
405     if (!root)
406     {
407         return -1;
408     }
409
410     oc = cJSON_GetObjectItem(root,"oic");
411     if (!oc)
412     {
413         return -1;
414     }
415
416     if (oc->type == cJSON_Array)
417     {
418         int numRsrcs =  cJSON_GetArraySize(oc);
419         for(int i = 0; i < numRsrcs; i++)
420         {
421             cJSON * resource = cJSON_GetArrayItem(oc, i);
422             if (cJSON_GetObjectItem(resource, "href"))
423             {
424                 coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
425             }
426             else
427             {
428                 coapServerResource = "";
429             }
430             OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
431
432             cJSON * prop = cJSON_GetObjectItem(resource,"prop");
433             if (prop)
434             {
435                 cJSON * policy = cJSON_GetObjectItem(prop,"p");
436                 if (policy)
437                 {
438                     // If this is a secure resource, the info about the port at which the
439                     // resource is hosted on server is embedded inside discovery JSON response
440                     if (cJSON_GetObjectItem(policy, "sec"))
441                     {
442                         if ((cJSON_GetObjectItem(policy, "sec")->valueint) == 1)
443                         {
444                             coapSecureResource = 1;
445                         }
446                     }
447                     OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
448                     if (cJSON_GetObjectItem(policy, "port"))
449                     {
450                         port = cJSON_GetObjectItem(policy, "port")->valueint;
451                         OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
452
453                         std::ostringstream ss;
454                         ss << port;
455                         coapServerPort = ss.str();
456                     }
457                 }
458             }
459
460             // If we discovered a secure resource, exit from here
461             if (coapSecureResource)
462             {
463                 break;
464             }
465         }
466     }
467     cJSON_Delete(root);
468
469     coapServerIP = getIPAddrTBServer(clientResponse);
470     if (port == -1)
471     {
472         coapServerPort = getPortTBServer(clientResponse);
473         OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
474     }
475     return 0;
476 }
477