Fix strcpy in occlientcoll
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / SimpleClientServer / occlientcoll.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 "iotivity_config.h"
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <signal.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_WINDOWS_H
30 #include <windows.h>
31 #endif
32 #include <ocstack.h>
33 #include <iostream>
34 #include <sstream>
35 #include <getopt.h>
36 #include "ocpayload.h"
37 #include "payload_logging.h"
38 #include "logger.h"
39 #include "common.h"
40 #include "oic_string.h"
41
42 std::string getQueryStrForGetPut();
43
44 #define TAG ("occlient")
45 #define DEFAULT_CONTEXT_VALUE 0x99
46 #ifndef MAX_LENGTH_IPv4_ADDR
47 #define MAX_LENGTH_IPv4_ADDR 16
48 #endif
49
50 typedef enum
51 {
52     TEST_INVALID = 0,
53     TEST_GET_DEFAULT,
54     TEST_GET_BATCH,
55     TEST_GET_LINK_LIST,
56     TEST_PUT_DEFAULT,
57     TEST_PUT_BATCH,
58     TEST_PUT_LINK_LIST,
59     TEST_UNKNOWN_RESOURCE_GET_DEFAULT,
60     TEST_UNKNOWN_RESOURCE_GET_BATCH,
61     TEST_UNKNOWN_RESOURCE_GET_LINK_LIST,
62     MAX_TESTS
63 } CLIENT_TEST;
64
65 /**
66  * List of connectivity types that can be initiated from the client
67  * Required for user input validation
68  */
69 typedef enum {
70     CT_ADAPTER_DEFAULT = 0,
71     CT_IP,
72     MAX_CT
73 } CLIENT_ConnectivityType_TYPE;
74
75 unsigned static int TestType = TEST_INVALID;
76 unsigned static int ConnectivityType = 0;
77
78 typedef struct
79 {
80     char text[30];
81     CLIENT_TEST test;
82 } testToTextMap;
83
84 testToTextMap queryInterface[] = {
85         {"invalid", TEST_INVALID},
86         {"?if=oic.if.baseline", TEST_GET_DEFAULT},
87         {"?if=oic.if.b", TEST_GET_BATCH},
88         {"?if=oic.if.ll", TEST_GET_LINK_LIST},
89         {"?if=oic.if.baseline", TEST_UNKNOWN_RESOURCE_GET_DEFAULT},
90         {"?if=oic.if.b", TEST_UNKNOWN_RESOURCE_GET_BATCH},
91         {"?if=oic.if.ll", TEST_UNKNOWN_RESOURCE_GET_LINK_LIST},
92         {"?if=oic.if.baseline", TEST_PUT_DEFAULT},
93         {"?if=oic.if.b", TEST_PUT_BATCH},
94         {"?if=oic.if.ll", TEST_PUT_LINK_LIST},
95 };
96
97
98 //The following variable determines the interface protocol (IP, etc)
99 //to be used for sending unicast messages. Default set to IP.
100 static OCConnectivityType ConnType = CT_ADAPTER_IP;
101 static const char * RESOURCE_DISCOVERY_QUERY = "/oic/res";
102
103 // The handle for the observe registration
104 OCDoHandle gObserveDoHandle;
105 // After this crosses a threshold client deregisters for further observations
106 int gNumObserveNotifies = 1;
107
108 int gQuitFlag = 0;
109 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
110 void handleSigInt(int signum)
111 {
112     if (signum == SIGINT)
113     {
114         gQuitFlag = 1;
115     }
116 }
117
118 // Forward Declaration
119 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse);
120 int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse);
121 int InitObserveRequest(OCClientResponse * clientResponse);
122 int InitPutRequest(OCClientResponse * clientResponse);
123 int InitGetRequest(OCClientResponse * clientResponse);
124 int InitDiscovery();
125
126 OCPayload* putPayload()
127 {
128     OCRepPayload* payload = OCRepPayloadCreate();
129
130     if(!payload)
131     {
132         std::cout << "Failed to create put payload object"<<std::endl;
133         std::exit(1);
134     }
135
136     OCRepPayloadSetPropInt(payload, "power", 15);
137     OCRepPayloadSetPropBool(payload, "state", true);
138
139     return (OCPayload*) payload;
140 }
141
142 void PrintUsage()
143 {
144     OIC_LOG(INFO, TAG, "Usage : occlientcoll -t <Test Case> -c <CA connectivity Type>");
145     OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
146     OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
147     OIC_LOG(INFO, TAG, "Test Case 1 : Discover Resources && Initiate GET Request on an "\
148             "available resource using default interface.");
149     OIC_LOG(INFO, TAG, "Test Case 2 : Discover Resources && Initiate GET Request on an "\
150                  "available resource using batch interface.");
151     OIC_LOG(INFO, TAG, "Test Case 3 : Discover Resources && Initiate GET Request on an "\
152                  "available resource using link list interface.");
153     OIC_LOG(INFO, TAG, "Test Case 4 : Discover Resources && Initiate GET & PUT Request on an "\
154                  "available resource using default interface.");
155     OIC_LOG(INFO, TAG, "Test Case 5 : Discover Resources && Initiate GET & PUT Request on an "\
156                  "available resource using batch interface.");
157     OIC_LOG(INFO, TAG, "Test Case 6 : Discover Resources && Initiate GET & PUT Request on an "\
158                  "available resource using link list interface.");
159     OIC_LOG(INFO, TAG, "Test Case 7 : Discover Resources && Initiate GET Request on an "\
160                  "unavailable resource using default interface.");
161     OIC_LOG(INFO, TAG, "Test Case 8 : Discover Resources && Initiate GET Request on an "\
162                  "unavailable resource using batch interface.");
163     OIC_LOG(INFO, TAG, "Test Case 9 : Discover Resources && Initiate GET Request on an "\
164                  "unavailable resource using link list interface.");
165 }
166
167 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
168                                   OCClientResponse * clientResponse)
169 {
170     if(clientResponse == NULL)
171     {
172         OIC_LOG(INFO, TAG, "The clientResponse is NULL");
173         return   OC_STACK_DELETE_TRANSACTION;
174     }
175     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
176     {
177         OIC_LOG_V(INFO, TAG, "Callback Context for PUT query recvd successfully");
178         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
179     }
180
181     return OC_STACK_KEEP_TRANSACTION;
182 }
183
184 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
185                                   OCClientResponse * clientResponse)
186 {
187     OIC_LOG_V(INFO, TAG, "StackResult: %s",
188             getResult(clientResponse->result));
189     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
190     {
191         OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
192         if(clientResponse->sequenceNumber == 0)
193         {
194             OIC_LOG_V(INFO, TAG, "Callback Context for GET query recvd successfully");
195             OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
196         }
197         else
198         {
199             OIC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d",
200                     gNumObserveNotifies);
201             OIC_LOG_PAYLOAD(INFO, clientResponse->payload);;
202             gNumObserveNotifies++;
203             if (gNumObserveNotifies == 3)
204             {
205                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
206                 {
207                     OIC_LOG(ERROR, TAG, "Observe cancel error");
208                 }
209             }
210         }
211     }
212     if(TestType == TEST_PUT_DEFAULT || TestType == TEST_PUT_BATCH || TestType == TEST_PUT_LINK_LIST)
213     {
214         InitPutRequest(clientResponse);
215     }
216     return OC_STACK_KEEP_TRANSACTION;
217 }
218
219 // This is a function called back when a device is discovered
220 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
221                                         OCClientResponse * clientResponse)
222 {
223     OIC_LOG(INFO, TAG,
224             "Entering discoveryReqCB (Application Layer CB)");
225     OIC_LOG_V(INFO, TAG, "StackResult: %s",
226             getResult(clientResponse->result));
227
228     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
229     {
230         OIC_LOG_V(INFO, TAG, "Callback Context recvd successfully");
231     }
232
233     OIC_LOG_V(INFO, TAG,
234             "Device =============> Discovered @ %s:%d",
235             clientResponse->devAddr.addr,
236             clientResponse->devAddr.port);
237     OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
238
239     ConnType = clientResponse->connType;
240
241     if(TestType == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TestType == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\
242             TestType == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST)
243     {
244         InitGetRequestToUnavailableResource(clientResponse);
245     }
246     else
247     {
248         InitGetRequest(clientResponse);
249     }
250     return OC_STACK_KEEP_TRANSACTION;
251 }
252
253
254 int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse)
255 {
256     OCStackResult ret;
257     OCCallbackData cbData;
258     std::ostringstream getQuery;
259     getQuery << "/SomeUnknownResource";
260     cbData.cb = getReqCB;
261     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
262     cbData.cd = NULL;
263
264     ret = OCDoResource(NULL, OC_REST_GET, getQuery.str().c_str(),
265                        &clientResponse->devAddr, 0, ConnType, OC_LOW_QOS,
266                        &cbData, NULL, 0);
267     if (ret != OC_STACK_OK)
268     {
269         OIC_LOG(ERROR, TAG, "OCStack resource error");
270     }
271     return ret;
272 }
273
274
275 int InitObserveRequest(OCClientResponse * clientResponse)
276 {
277     OCStackResult ret;
278     OCCallbackData cbData;
279     OCDoHandle handle;
280     std::ostringstream obsReg;
281     obsReg << getQueryStrForGetPut();
282     cbData.cb = getReqCB;
283     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
284     cbData.cd = NULL;
285     OIC_LOG_V(INFO, TAG, "OBSERVE payload from client =");
286     OCPayload* payload = putPayload();
287     OIC_LOG_PAYLOAD(INFO, payload);
288     OCPayloadDestroy(payload);
289
290     ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(),
291                        &clientResponse->devAddr, 0, ConnType,
292                        OC_LOW_QOS, &cbData, NULL, 0);
293     if (ret != OC_STACK_OK)
294     {
295         OIC_LOG(ERROR, TAG, "OCStack resource error");
296     }
297     else
298     {
299         gObserveDoHandle = handle;
300     }
301     return ret;
302 }
303
304
305 int InitPutRequest(OCClientResponse * clientResponse)
306 {
307     OCStackResult ret;
308     OCCallbackData cbData;
309     //* Make a PUT query*/
310     std::ostringstream getQuery;
311     getQuery << "coap://" << clientResponse->devAddr.addr << ":" <<
312             clientResponse->devAddr.port <<
313             "/a/room" << queryInterface[TestType].text;
314     cbData.cb = putReqCB;
315     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
316     cbData.cd = NULL;
317     OIC_LOG_V(INFO, TAG, "PUT payload from client = ");
318     OCPayload* payload = putPayload();
319     OIC_LOG_PAYLOAD(INFO, payload);
320     OCPayloadDestroy(payload);
321
322     ret = OCDoResource(NULL, OC_REST_PUT, getQuery.str().c_str(),
323                        &clientResponse->devAddr, putPayload(), ConnType,
324                        OC_LOW_QOS, &cbData, NULL, 0);
325     if (ret != OC_STACK_OK)
326     {
327         OIC_LOG(ERROR, TAG, "OCStack resource error");
328     }
329     return ret;
330 }
331
332
333 int InitGetRequest(OCClientResponse * clientResponse)
334 {
335     OCStackResult ret;
336     OCCallbackData cbData;
337
338     //* Make a GET query*/
339     std::ostringstream getQuery;
340     getQuery << "/a/room" << queryInterface[TestType].text;
341
342     std::cout << "Get Query: " << getQuery.str() << std::endl;
343
344     cbData.cb = getReqCB;
345     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
346     cbData.cd = NULL;
347     ret = OCDoResource(NULL, OC_REST_GET, getQuery.str().c_str(),
348                        &clientResponse->devAddr, 0, ConnType, OC_LOW_QOS,
349                        &cbData, NULL, 0);
350     if (ret != OC_STACK_OK)
351     {
352         OIC_LOG(ERROR, TAG, "OCStack resource error");
353     }
354     return ret;
355 }
356
357 int InitDiscovery()
358 {
359     OCStackResult ret;
360     OCCallbackData cbData;
361     /* Start a discovery query*/
362     char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
363
364     OICStrcpy(szQueryUri, sizeof(RESOURCE_DISCOVERY_QUERY), RESOURCE_DISCOVERY_QUERY);
365
366     cbData.cb = discoveryReqCB;
367     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
368     cbData.cd = NULL;
369     ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, ConnType,
370                         OC_LOW_QOS,
371             &cbData, NULL, 0);
372     if (ret != OC_STACK_OK)
373     {
374         OIC_LOG(ERROR, TAG, "OCStack resource error");
375     }
376     return ret;
377 }
378
379 int main(int argc, char* argv[])
380 {
381     int opt;
382
383     while ((opt = getopt(argc, argv, "t:c:")) != -1)
384     {
385         switch (opt)
386         {
387             case 't':
388                 TestType = atoi(optarg);
389                 break;
390             case 'c':
391                 ConnectivityType = atoi(optarg);
392                 break;
393             default:
394                 PrintUsage();
395                 return -1;
396         }
397     }
398     if ((TestType <= TEST_INVALID || TestType >= MAX_TESTS) ||
399         ConnectivityType >= MAX_CT)
400     {
401         PrintUsage();
402         return -1;
403     }
404
405     /* Initialize OCStack*/
406     if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
407     {
408         OIC_LOG(ERROR, TAG, "OCStack init error");
409         return 0;
410     }
411
412     if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
413     {
414         ConnType = CT_ADAPTER_IP;
415     }
416     else
417     {
418         OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
419         ConnType = CT_ADAPTER_IP;
420     }
421
422     InitDiscovery();
423
424     // Break from loop with Ctrl+C
425     OIC_LOG(INFO, TAG, "Entering occlient main loop...");
426     signal(SIGINT, handleSigInt);
427     while (!gQuitFlag)
428     {
429
430         if (OCProcess() != OC_STACK_OK)
431         {
432             OIC_LOG(ERROR, TAG, "OCStack process error");
433             return 0;
434         }
435
436         sleep(2);
437     } OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
438
439     if (OCStop() != OC_STACK_OK)
440     {
441         OIC_LOG(ERROR, TAG, "OCStack stop error");
442     }
443
444     return 0;
445 }
446
447 std::string getQueryStrForGetPut()
448 {
449     return "/a/room";
450 }
451