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