Merge branch 'master' into resource-manipulation
[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_PAYLOAD(INFO, TAG, clientResponse->payload);
126         OC_LOG(INFO, TAG, PCF("=============> Put Response"));
127     }
128     return OC_STACK_DELETE_TRANSACTION;
129 }
130
131 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
132 {
133     OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
134
135     if(clientResponse)
136     {
137         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
138         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
139         OC_LOG(INFO, TAG, PCF("=============> Post Response"));
140     }
141     return OC_STACK_DELETE_TRANSACTION;
142 }
143
144 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
145 {
146     OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
147
148     if(clientResponse)
149     {
150         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
151         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
152         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
153         OC_LOG(INFO, TAG, PCF("=============> Get Response"));
154     }
155     return OC_STACK_DELETE_TRANSACTION;
156 }
157
158 // This is a function called back when a device is discovered
159 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
160         OCClientResponse * clientResponse)
161 {
162     OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
163
164     if (clientResponse)
165     {
166         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
167         OC_LOG_V(INFO, TAG,
168                 "Device =============> Discovered @ %s:%d",
169                 clientResponse->devAddr.addr,
170                 clientResponse->devAddr.port);
171         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
172
173         ocConnType = clientResponse->connType;
174
175         if (parseClientResponse(clientResponse) != -1)
176         {
177             switch(TEST_CASE)
178             {
179                 case TEST_NON_CON_OP:
180                     InitGetRequest(OC_LOW_QOS);
181                     InitPutRequest(OC_LOW_QOS);
182                     //InitPostRequest(OC_LOW_QOS);
183                     break;
184                 case TEST_CON_OP:
185                     InitGetRequest(OC_HIGH_QOS);
186                     InitPutRequest(OC_HIGH_QOS);
187                     //InitPostRequest(OC_HIGH_QOS);
188                     break;
189             }
190         }
191     }
192
193     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
194
195 }
196
197 int InitPutRequest(OCQualityOfService qos)
198 {
199     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
200     std::ostringstream query;
201     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
202         << ":" << coapServerPort  << coapServerResource;
203     return (InvokeOCDoResource(query, OC_REST_PUT,
204             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
205 }
206
207 int InitPostRequest(OCQualityOfService qos)
208 {
209     OCStackResult result;
210     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
211     std::ostringstream query;
212     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
213         << ":" << coapServerPort << coapServerResource;
214
215     // First POST operation (to create an LED instance)
216     result = InvokeOCDoResource(query, OC_REST_POST,
217             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
218             postReqCB, NULL, 0);
219     if (OC_STACK_OK != result)
220     {
221         // Error can happen if for example, network connectivity is down
222         OC_LOG(INFO, TAG, "First POST call did not succeed");
223     }
224
225     // Second POST operation (to create an LED instance)
226     result = InvokeOCDoResource(query, OC_REST_POST,
227             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
228             postReqCB, NULL, 0);
229     if (OC_STACK_OK != result)
230     {
231         OC_LOG(INFO, TAG, "Second POST call did not succeed");
232     }
233
234     // This POST operation will update the original resourced /a/led
235     return (InvokeOCDoResource(query, OC_REST_POST,
236                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
237                 postReqCB, NULL, 0));
238 }
239
240 int InitGetRequest(OCQualityOfService qos)
241 {
242     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
243     std::ostringstream query;
244     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
245         << ":" << coapServerPort << coapServerResource;
246
247     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
248             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
249 }
250
251 int InitDiscovery()
252 {
253     OCStackResult ret;
254     OCMethod method;
255     OCCallbackData cbData;
256     char szQueryUri[MAX_URI_LENGTH] = { 0 };
257
258     if (UNICAST_DISCOVERY)
259     {
260         char ipv4addr[IPV4_ADDR_SIZE];
261         OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
262                 "(Ex: 11.12.13.14:1234)\n");
263         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
264         {
265             //Strip newline char from ipv4addr
266             StripNewLineChar(ipv4addr);
267             snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
268         }
269         else
270         {
271             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
272             return OC_STACK_INVALID_PARAM;
273         }
274         method = OC_REST_GET;
275     }
276     else
277     {
278         //Send discovery request on Wifi and Ethernet interface
279         discoveryReqConnType = CT_DEFAULT;
280         strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
281         method = OC_REST_DISCOVER;
282     }
283
284     cbData.cb = discoveryReqCB;
285     cbData.context = NULL;
286     cbData.cd = NULL;
287
288     /* Start a discovery query*/
289     OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
290         (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
291         szQueryUri);
292
293     ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
294             discoveryReqConnType, OC_LOW_QOS,
295             &cbData, NULL, 0);
296     if (ret != OC_STACK_OK)
297     {
298         OC_LOG(ERROR, TAG, "OCStack resource error");
299     }
300     return ret;
301 }
302
303 FILE* client_fopen(const char *path, const char *mode)
304 {
305     (void)path;
306     return fopen(CRED_FILE, mode);
307 }
308
309 int main(int argc, char* argv[])
310 {
311     int opt;
312     struct timespec timeout;
313
314     while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
315     {
316         switch(opt)
317         {
318             case 'u':
319                 UNICAST_DISCOVERY = atoi(optarg);
320                 break;
321             case 't':
322                 TEST_CASE = atoi(optarg);
323                 break;
324             case 'c':
325                 CONN_TYPE = atoi(optarg);
326                 break;
327             default:
328                 PrintUsage();
329                 return -1;
330         }
331     }
332
333     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
334             (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
335             (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
336     {
337         PrintUsage();
338         return -1;
339     }
340
341
342     if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE ==  CT_IP)
343     {
344         discoveryReqConnType = CT_DEFAULT;
345     }
346     else
347     {
348         OC_LOG(INFO, TAG, "Using Default Connectivity type");
349         PrintUsage();
350     }
351
352
353     // Initialize Persistent Storage for SVR database
354     OCPersistentStorage ps = {};
355     ps.open = client_fopen;
356     ps.read = fread;
357     ps.write = fwrite;
358     ps.close = fclose;
359     ps.unlink = unlink;
360     OCRegisterPersistentStorageHandler(&ps);
361
362     /* Initialize OCStack*/
363     if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
364     {
365         OC_LOG(ERROR, TAG, "OCStack init error");
366         return 0;
367     }
368
369     InitDiscovery();
370
371     timeout.tv_sec  = 0;
372     timeout.tv_nsec = 100000000L;
373
374     // Break from loop with Ctrl+C
375     OC_LOG(INFO, TAG, "Entering occlient main loop...");
376     signal(SIGINT, handleSigInt);
377     while (!gQuitFlag)
378     {
379         if (OCProcess() != OC_STACK_OK)
380         {
381             OC_LOG(ERROR, TAG, "OCStack process error");
382             return 0;
383         }
384
385         nanosleep(&timeout, NULL);
386     }
387     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
388
389     if (OCStop() != OC_STACK_OK)
390     {
391         OC_LOG(ERROR, TAG, "OCStack stop error");
392     }
393
394     return 0;
395 }
396
397 std::string getPortTBServer(OCClientResponse * clientResponse)
398 {
399     if(!clientResponse) return "";
400     std::ostringstream ss;
401     ss << clientResponse->devAddr.port;
402     return ss.str();
403 }
404
405 int parseClientResponse(OCClientResponse * clientResponse)
406 {
407     OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
408
409     // Initialize all global variables
410     coapServerResource.clear();
411     coapServerPort.clear();
412     coapServerIP.clear();
413     coapSecureResource = 0;
414
415     while(res)
416     {
417         coapServerResource.assign(res->uri);
418         OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
419
420         if(res->secure)
421         {
422             coapSecureResource = 1;
423         }
424
425         OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
426
427         std::ostringstream ss;
428         ss << res->port;
429         coapServerPort = ss.str();
430         std::cout<<"PORT: "<<coapServerPort;
431
432         // If we discovered a secure resource, exit from here
433         if (coapSecureResource)
434         {
435             break;
436         }
437
438         res = res->next;
439     }
440
441     coapServerIP = clientResponse->devAddr.addr;
442
443     if(coapServerPort.length() == 0 || coapServerPort == "0")
444     {
445         coapServerPort = getPortTBServer(clientResponse);
446         OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
447     }
448
449     return 0;
450 }
451