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