Fixed a large amount of memory leaks/ Null pointer dereferences
[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 "oic_string.h"
33 #include "common.h"
34
35 #define TAG "occlientbasicops"
36 static int UNICAST_DISCOVERY = 0;
37 static int TEST_CASE = 0;
38 static int CONN_TYPE = 0;
39
40 static int IPV4_ADDR_SIZE = 24;
41 static char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
42 static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
43 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
44
45 static std::string coapServerIP;
46 static std::string coapServerPort;
47 static std::string coapServerResource;
48 static int coapSecureResource;
49 static OCConnectivityType ocConnType;
50
51
52 //Secure Virtual Resource database for Iotivity Client application
53 //It contains Client's Identity and the PSK credentials
54 //of other devices which the client trusts
55 static char CRED_FILE[] = "oic_svr_db_client.json";
56
57
58 int gQuitFlag = 0;
59
60 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
61 void handleSigInt(int signum)
62 {
63     if (signum == SIGINT)
64     {
65         gQuitFlag = 1;
66     }
67 }
68
69 OCPayload* putPayload()
70 {
71     OCRepPayload* payload = OCRepPayloadCreate();
72
73     if(!payload)
74     {
75         std::cout << "Failed to create put payload object"<<std::endl;
76         std::exit(1);
77     }
78
79     OCRepPayloadSetPropInt(payload, "power", 15);
80     OCRepPayloadSetPropBool(payload, "state", true);
81
82     return (OCPayload*) payload;
83 }
84
85 static void PrintUsage()
86 {
87     OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
88     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
89     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
90     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
91             " Initiate Nonconfirmable Get/Put/Post Requests");
92     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
93     OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
94     OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
95 }
96
97 OCStackResult InvokeOCDoResource(std::ostringstream &query,
98         OCMethod method, OCQualityOfService qos,
99         OCClientResponseHandler cb, 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(), 0,
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         OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
115     }
116
117     return ret;
118 }
119
120 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
121 {
122     OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
123
124     if(clientResponse)
125     {
126         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
127         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
128         OC_LOG(INFO, TAG, PCF("=============> Put Response"));
129     }
130     return OC_STACK_DELETE_TRANSACTION;
131 }
132
133 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
134 {
135     OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
136
137     if(clientResponse)
138     {
139         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
140         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
141         OC_LOG(INFO, TAG, PCF("=============> Post Response"));
142     }
143     return OC_STACK_DELETE_TRANSACTION;
144 }
145
146 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
147 {
148     OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
149
150     if(clientResponse)
151     {
152         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
153         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
154         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
155         OC_LOG(INFO, TAG, PCF("=============> 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* ctx, OCDoHandle handle,
162         OCClientResponse * clientResponse)
163 {
164     OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
165
166     if (clientResponse)
167     {
168         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
169         OC_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             OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
177
178             ocConnType = clientResponse->connType;
179
180             if (parseClientResponse(clientResponse) != -1)
181             {
182                 switch(TEST_CASE)
183                 {
184                     case TEST_NON_CON_OP:
185                         InitGetRequest(OC_LOW_QOS);
186                         InitPutRequest(OC_LOW_QOS);
187                         //InitPostRequest(OC_LOW_QOS);
188                         break;
189                     case TEST_CON_OP:
190                         InitGetRequest(OC_HIGH_QOS);
191                         InitPutRequest(OC_HIGH_QOS);
192                         //InitPostRequest(OC_HIGH_QOS);
193                         break;
194                 }
195             }
196         }
197     }
198
199     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
200
201 }
202
203 int InitPutRequest(OCQualityOfService qos)
204 {
205     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
206     std::ostringstream query;
207     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
208         << ":" << coapServerPort  << coapServerResource;
209     return (InvokeOCDoResource(query, OC_REST_PUT,
210             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
211 }
212
213 int InitPostRequest(OCQualityOfService qos)
214 {
215     OCStackResult result;
216     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
217     std::ostringstream query;
218     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
219         << ":" << coapServerPort << coapServerResource;
220
221     // First POST operation (to create an LED instance)
222     result = InvokeOCDoResource(query, OC_REST_POST,
223             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
224             postReqCB, NULL, 0);
225     if (OC_STACK_OK != result)
226     {
227         // Error can happen if for example, network connectivity is down
228         OC_LOG(INFO, TAG, "First POST call did not succeed");
229     }
230
231     // Second POST operation (to create an LED instance)
232     result = InvokeOCDoResource(query, OC_REST_POST,
233             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
234             postReqCB, NULL, 0);
235     if (OC_STACK_OK != result)
236     {
237         OC_LOG(INFO, TAG, "Second POST call did not succeed");
238     }
239
240     // This POST operation will update the original resourced /a/led
241     return (InvokeOCDoResource(query, OC_REST_POST,
242                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
243                 postReqCB, NULL, 0));
244 }
245
246 int InitGetRequest(OCQualityOfService qos)
247 {
248     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
249     std::ostringstream query;
250     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
251         << ":" << coapServerPort << coapServerResource;
252
253     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
254             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
255 }
256
257 int InitDiscovery()
258 {
259     OCStackResult ret;
260     OCMethod method;
261     OCCallbackData cbData;
262     char szQueryUri[MAX_URI_LENGTH] = { 0 };
263
264     if (UNICAST_DISCOVERY)
265     {
266         char ipv4addr[IPV4_ADDR_SIZE];
267         OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
268                 "(Ex: 11.12.13.14:1234)\n");
269         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
270         {
271             //Strip newline char from ipv4addr
272             StripNewLineChar(ipv4addr);
273             snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
274         }
275         else
276         {
277             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
278             return OC_STACK_INVALID_PARAM;
279         }
280         method = OC_REST_GET;
281     }
282     else
283     {
284         //Send discovery request on Wifi and Ethernet interface
285         discoveryReqConnType = CT_DEFAULT;
286         OICStrcpy(szQueryUri, sizeof(szQueryUri), MULTICAST_DISCOVERY_QUERY);
287         method = OC_REST_DISCOVER;
288     }
289
290     cbData.cb = discoveryReqCB;
291     cbData.context = NULL;
292     cbData.cd = NULL;
293
294     /* Start a discovery query*/
295     OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
296         (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
297         szQueryUri);
298
299     ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
300             discoveryReqConnType, OC_LOW_QOS,
301             &cbData, NULL, 0);
302     if (ret != OC_STACK_OK)
303     {
304         OC_LOG(ERROR, TAG, "OCStack resource error");
305     }
306     return ret;
307 }
308
309 FILE* client_fopen(const char *path, const char *mode)
310 {
311     (void)path;
312     return fopen(CRED_FILE, mode);
313 }
314
315 int main(int argc, char* argv[])
316 {
317     int opt;
318     struct timespec timeout;
319
320     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
321     {
322         switch(opt)
323         {
324             case 'u':
325                 UNICAST_DISCOVERY = atoi(optarg);
326                 break;
327             case 't':
328                 TEST_CASE = atoi(optarg);
329                 break;
330             case 'c':
331                 CONN_TYPE = atoi(optarg);
332                 break;
333             default:
334                 PrintUsage();
335                 return -1;
336         }
337     }
338
339     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
340             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
341             (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
342     {
343         PrintUsage();
344         return -1;
345     }
346
347
348     if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE ==  CT_IP)
349     {
350         discoveryReqConnType = CT_DEFAULT;
351     }
352     else
353     {
354         OC_LOG(INFO, TAG, "Using Default Connectivity type");
355         PrintUsage();
356     }
357
358
359     // Initialize Persistent Storage for SVR database
360     OCPersistentStorage ps = {};
361     ps.open = client_fopen;
362     ps.read = fread;
363     ps.write = fwrite;
364     ps.close = fclose;
365     ps.unlink = unlink;
366     OCRegisterPersistentStorageHandler(&ps);
367
368     /* Initialize OCStack*/
369     if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
370     {
371         OC_LOG(ERROR, TAG, "OCStack init error");
372         return 0;
373     }
374
375     InitDiscovery();
376
377     timeout.tv_sec  = 0;
378     timeout.tv_nsec = 100000000L;
379
380     // Break from loop with Ctrl+C
381     OC_LOG(INFO, TAG, "Entering occlient main loop...");
382     signal(SIGINT, handleSigInt);
383     while (!gQuitFlag)
384     {
385         if (OCProcess() != OC_STACK_OK)
386         {
387             OC_LOG(ERROR, TAG, "OCStack process error");
388             return 0;
389         }
390
391         nanosleep(&timeout, NULL);
392     }
393     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
394
395     if (OCStop() != OC_STACK_OK)
396     {
397         OC_LOG(ERROR, TAG, "OCStack stop error");
398     }
399
400     return 0;
401 }
402
403 std::string getPortTBServer(OCClientResponse * clientResponse)
404 {
405     if(!clientResponse) return "";
406     std::ostringstream ss;
407     ss << clientResponse->devAddr.port;
408     return ss.str();
409 }
410
411 int parseClientResponse(OCClientResponse * clientResponse)
412 {
413     OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
414
415     // Initialize all global variables
416     coapServerResource.clear();
417     coapServerPort.clear();
418     coapServerIP.clear();
419     coapSecureResource = 0;
420
421     while(res)
422     {
423         coapServerResource.assign(res->uri);
424         OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
425
426         if(res->secure)
427         {
428             coapSecureResource = 1;
429         }
430
431         OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
432
433         std::ostringstream ss;
434         ss << res->port;
435         coapServerPort = ss.str();
436         std::cout<<"PORT: "<<coapServerPort;
437
438         // If we discovered a secure resource, exit from here
439         if (coapSecureResource)
440         {
441             break;
442         }
443
444         res = res->next;
445     }
446
447     coapServerIP = clientResponse->devAddr.addr;
448
449     if(coapServerPort.length() == 0 || coapServerPort == "0")
450     {
451         coapServerPort = getPortTBServer(clientResponse);
452         OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
453     }
454
455     return 0;
456 }
457