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