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