Fix provisioning unit tests
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / unittest / sampleserver2.cpp
1 /******************************************************************
2 *
3 * Copyright 2015 Samsung Electronics 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 //NOTE :  This sample server is generated based on ocserverbasicops.cpp
22 ///////////////////////////////////////////////////////////////////////
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <pthread.h>
29 #include "ocstack.h"
30 #include "logger.h"
31 #include "ocpayload.h"
32 #include "oic_string.h"
33
34 #include "doxmresource.h"
35 #include "srmutility.h"
36
37 #define TAG "UNITTEST_SERVER_2"
38
39 int gQuitFlag = 0;
40
41 /* Structure to represent a LED resource */
42 typedef struct LEDRESOURCE{
43     OCResourceHandle handle;
44     bool state;
45     int power;
46 } LEDResource;
47
48 static LEDResource LED;
49 // This variable determines instance number of the LED resource.
50 // Used by POST method to create a new instance of LED resource.
51 static int gCurrLedInstance = 0;
52 #define SAMPLE_MAX_NUM_POST_INSTANCE  2
53 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
54
55 char *gResourceUri= (char *)"/a/led";
56
57 //Secure Virtual Resource database for Iotivity Server
58 //It contains Server's Identity and the PSK credentials
59 //of other devices which the server trusts
60 static char CRED_FILE[] = "oic_svr_db_server2.dat";
61
62 static char SVR_DB_FILE_NAME[] = "oic_svr_db_server_justworks.dat";
63
64 /* Function that creates a new LED resource by calling the
65  * OCCreateResource() method.
66  */
67 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
68
69 /* This method converts the payload to JSON format */
70 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
71
72 /* Following methods process the PUT, GET, POST
73  * requests
74  */
75 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
76                                          OCRepPayload **payload);
77 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
78                                          OCRepPayload **payload);
79 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
80                                         OCEntityHandlerResponse *response,
81                                         OCRepPayload **payload);
82
83 /* Entity Handler callback functions */
84 OCEntityHandlerResult
85 OCEntityHandlerCb (OCEntityHandlerFlag flag,
86         OCEntityHandlerRequest *entityHandlerRequest,
87         void* callbackParam);
88
89 const char *getResult(OCStackResult result) {
90     switch (result) {
91     case OC_STACK_OK:
92         return "OC_STACK_OK";
93     case OC_STACK_RESOURCE_CREATED:
94         return "OC_STACK_RESOURCE_CREATED";
95     case OC_STACK_RESOURCE_DELETED:
96         return "OC_STACK_RESOURCE_DELETED";
97     case OC_STACK_INVALID_URI:
98         return "OC_STACK_INVALID_URI";
99     case OC_STACK_INVALID_QUERY:
100         return "OC_STACK_INVALID_QUERY";
101     case OC_STACK_INVALID_IP:
102         return "OC_STACK_INVALID_IP";
103     case OC_STACK_INVALID_PORT:
104         return "OC_STACK_INVALID_PORT";
105     case OC_STACK_INVALID_CALLBACK:
106         return "OC_STACK_INVALID_CALLBACK";
107     case OC_STACK_INVALID_METHOD:
108         return "OC_STACK_INVALID_METHOD";
109     case OC_STACK_NO_MEMORY:
110         return "OC_STACK_NO_MEMORY";
111     case OC_STACK_COMM_ERROR:
112         return "OC_STACK_COMM_ERROR";
113     case OC_STACK_INVALID_PARAM:
114         return "OC_STACK_INVALID_PARAM";
115     case OC_STACK_NOTIMPL:
116         return "OC_STACK_NOTIMPL";
117     case OC_STACK_NO_RESOURCE:
118         return "OC_STACK_NO_RESOURCE";
119     case OC_STACK_RESOURCE_ERROR:
120         return "OC_STACK_RESOURCE_ERROR";
121     case OC_STACK_SLOW_RESOURCE:
122         return "OC_STACK_SLOW_RESOURCE";
123     case OC_STACK_NO_OBSERVERS:
124         return "OC_STACK_NO_OBSERVERS";
125     #ifdef WITH_PRESENCE
126     case OC_STACK_PRESENCE_STOPPED:
127         return "OC_STACK_PRESENCE_STOPPED";
128     #endif
129     case OC_STACK_ERROR:
130         return "OC_STACK_ERROR";
131     default:
132         return "UNKNOWN";
133     }
134 }
135
136 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
137 {
138     OCRepPayload* payload = OCRepPayloadCreate();
139     if(!payload)
140     {
141         OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
142         return NULL;
143     }
144
145     OCRepPayloadSetUri(payload, uri);
146     OCRepPayloadSetPropBool(payload, "state", state);
147     OCRepPayloadSetPropInt(payload, "power", power);
148
149     return payload;
150 }
151
152 //This function takes the request as an input and returns the response
153 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
154 {
155     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
156     {
157         OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
158         return NULL;
159     }
160
161     OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
162
163     LEDResource *currLEDResource = &LED;
164
165     if (ehRequest->resource == gLedInstance[0].handle)
166     {
167         currLEDResource = &gLedInstance[0];
168         gResourceUri = (char *) "/a/led/0";
169     }
170     else if (ehRequest->resource == gLedInstance[1].handle)
171     {
172         currLEDResource = &gLedInstance[1];
173         gResourceUri = (char *) "/a/led/1";
174     }
175
176     if(OC_REST_PUT == ehRequest->method)
177     {
178         // Get pointer to query
179         int64_t pow;
180         if(OCRepPayloadGetPropInt(input, "power", &pow))
181         {
182             currLEDResource->power =pow;
183         }
184
185         bool state;
186         if(OCRepPayloadGetPropBool(input, "state", &state))
187         {
188             currLEDResource->state = state;
189         }
190     }
191
192     return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
193 }
194
195 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
196         OCRepPayload **payload)
197 {
198     OCEntityHandlerResult ehResult;
199
200     OCRepPayload *getResp = constructResponse(ehRequest);
201
202     if(getResp)
203     {
204         *payload = getResp;
205         ehResult = OC_EH_OK;
206     }
207     else
208     {
209         ehResult = OC_EH_ERROR;
210     }
211
212     return ehResult;
213 }
214
215 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
216         OCRepPayload **payload)
217 {
218     OCEntityHandlerResult ehResult;
219
220     OCRepPayload *putResp = constructResponse(ehRequest);
221
222     if(putResp)
223     {
224         *payload = putResp;
225         ehResult = OC_EH_OK;
226     }
227     else
228     {
229         ehResult = OC_EH_ERROR;
230     }
231
232     return ehResult;
233 }
234
235 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
236         OCEntityHandlerResponse *response, OCRepPayload **payload)
237 {
238     OCRepPayload *respPLPost_led = NULL;
239     OCEntityHandlerResult ehResult = OC_EH_OK;
240
241     /*
242      * The entity handler determines how to process a POST request.
243      * Per the REST paradigm, POST can also be used to update representation of existing
244      * resource or create a new resource.
245      * In the sample below, if the POST is for /a/led then a new instance of the LED
246      * resource is created with default representation (if representation is included in
247      * POST payload it can be used as initial values) as long as the instance is
248      * lesser than max new instance count. Once max instance count is reached, POST on
249      * /a/led updated the representation of /a/led (just like PUT)
250      */
251
252     if (ehRequest->resource == LED.handle)
253     {
254         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
255         {
256             // Create new LED instance
257             char newLedUri[15] = "/a/led/";
258             int newLedUriLength = strlen(newLedUri);
259             snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
260
261             respPLPost_led = OCRepPayloadCreate();
262             OCRepPayloadSetUri(respPLPost_led, gResourceUri);
263             OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
264
265             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
266             {
267                 OIC_LOG (INFO, TAG, "Created new LED instance");
268                 gLedInstance[gCurrLedInstance].state = 0;
269                 gLedInstance[gCurrLedInstance].power = 0;
270                 gCurrLedInstance++;
271                 strncpy ((char *)response->resourceUri, newLedUri, sizeof(response->resourceUri));
272                 ehResult = OC_EH_RESOURCE_CREATED;
273             }
274         }
275         else
276         {
277             respPLPost_led = constructResponse(ehRequest);
278         }
279     }
280     else
281     {
282         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
283         {
284             if (ehRequest->resource == gLedInstance[i].handle)
285             {
286                 if (i == 0)
287                 {
288                     respPLPost_led = constructResponse(ehRequest);
289                     break;
290                 }
291                 else if (i == 1)
292                 {
293                     respPLPost_led = constructResponse(ehRequest);
294                 }
295             }
296         }
297     }
298
299     if (respPLPost_led != NULL)
300     {
301         *payload = respPLPost_led;
302         ehResult = OC_EH_OK;
303     }
304     else
305     {
306         OIC_LOG_V (INFO, TAG, "Payload was NULL");
307         ehResult = OC_EH_ERROR;
308     }
309
310     return ehResult;
311 }
312
313 OCEntityHandlerResult
314 OCEntityHandlerCb (OCEntityHandlerFlag flag,
315         OCEntityHandlerRequest *entityHandlerRequest,
316         void* callbackParam)
317 {
318     OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
319     (void)callbackParam;
320     OCEntityHandlerResult ehResult = OC_EH_ERROR;
321
322     OCEntityHandlerResponse response;
323     memset(&response, 0, sizeof(response));
324
325     // Validate pointer
326     if (!entityHandlerRequest)
327     {
328         OIC_LOG (ERROR, TAG, "Invalid request pointer");
329         return OC_EH_ERROR;
330     }
331
332     OCRepPayload* payload = NULL;
333
334     if (flag & OC_REQUEST_FLAG)
335     {
336         OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
337         if (entityHandlerRequest)
338         {
339             if (OC_REST_GET == entityHandlerRequest->method)
340             {
341                 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
342                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
343             }
344             else if (OC_REST_PUT == entityHandlerRequest->method)
345             {
346                 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
347                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
348             }
349             else if (OC_REST_POST == entityHandlerRequest->method)
350             {
351                 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
352                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
353             }
354             else
355             {
356                 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
357                         entityHandlerRequest->method);
358                 ehResult = OC_EH_ERROR;
359             }
360
361             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
362             {
363                 // Format the response.  Note this requires some info about the request
364                 response.requestHandle = entityHandlerRequest->requestHandle;
365                 response.resourceHandle = entityHandlerRequest->resource;
366                 response.ehResult = ehResult;
367                 response.payload = (OCPayload*)(payload);
368                 response.numSendVendorSpecificHeaderOptions = 0;
369                 memset(response.sendVendorSpecificHeaderOptions, 0,
370                        sizeof(response.sendVendorSpecificHeaderOptions));
371                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
372                 // Indicate that response is NOT in a persistent buffer
373                 response.persistentBufferFlag = 0;
374
375                 // Send the response
376                 if (OCDoResponse(&response) != OC_STACK_OK)
377                 {
378                     OIC_LOG(ERROR, TAG, "Error sending response");
379                     ehResult = OC_EH_ERROR;
380                 }
381             }
382         }
383     }
384
385     OCPayloadDestroy(response.payload);
386     return ehResult;
387 }
388
389 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
390 void handleSigInt(int signum)
391 {
392     if (signum == SIGINT)
393     {
394         gQuitFlag = 1;
395     }
396 }
397
398 static void GetCurrentWorkingDirectory(char* buf, size_t bufsize)
399 {
400     char cwd[1024] = {0};
401     const char* unittest_path = "resource/csdk/security/provisioning/unittest";
402     if(getcwd(cwd, sizeof(cwd)) != NULL)
403     {
404         if(strstr(cwd, unittest_path) == NULL)
405         {
406 #if defined __linux__
407 #if __x86_64__
408         snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
409         snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
410 #else
411         snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
412         snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
413 #endif //__x86_64__
414 #endif //defined __linux__
415         }
416         else
417         {
418             snprintf(buf, bufsize, "%s/", cwd);
419         }
420     }
421 }
422
423 FILE* server_fopen(const char *path, const char *mode)
424 {
425     if (0 == strcmp(path, OC_SECURITY_DB_DAT_FILE_NAME))
426     {
427         char cwd[1024] = { 0 };
428         char cred_path[1024] = { 0 };
429         GetCurrentWorkingDirectory(cwd, sizeof(cwd));
430         snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
431         return fopen(cred_path, mode);
432     }
433     else
434     {
435         return fopen(path, mode);
436     }
437 }
438
439 /**
440  * Generate default SVR DB path
441  *
442  * Exclude "out/<OS>/<platform>/<release>/" from current working directory path
443  * Replace "unittest" by "sample" at the end of current working directory path
444  * Add proper db file name to the end of path
445  *
446  * @param[in]  cwd  - current working directory
447  * @param[out] path - generated default database path
448  * @param[in] path_len - allocated length for variable path
449  * @return OC_STACK_OK for success.
450  */
451 static OCStackResult GenerateDefaultDbPath(const char *cwd, char *path, size_t path_len)
452 {
453     const char FOLDER_OUT[]      = "out";
454     const char FOLDER_UNITTEST[] = "unittest";
455     const char FOLDER_SAMPLE[]   = "sample";
456
457 #ifdef _WIN32
458     const char slash = '\\';
459 #else
460     const char slash = '/';
461 #endif
462
463     const char slash_str[2] = {slash, 0};
464
465     path[0] = 0;
466
467     char out[5] = {0};
468     snprintf(out, sizeof(out), "%c%s%c", slash, FOLDER_OUT, slash);
469
470     char *start = strstr((char*)cwd, out);
471     if (NULL == start)
472     {
473         OIC_LOG_V(ERROR, TAG, "Can't find %s folder while parsing current working directory\n", FOLDER_OUT);
474         return OC_STACK_ERROR;
475     }
476     start++; //Go to next symbol after slash
477
478     char *end = start;
479     for (int i = 0; i < 4; i++)
480     {
481         end = strchr(end, slash);
482         if (NULL == end)
483         {
484             OIC_LOG_V(ERROR, TAG, "Can't find slash number %d while parsing current working directory\n", i);
485             return OC_STACK_ERROR;
486         }
487         end++; //Go to next symbol after slash
488     }
489
490     //Cut "unittest" string at the end
491     char *last = strstr(end, FOLDER_UNITTEST);
492     if (NULL == last)
493     {
494         OIC_LOG_V(ERROR, TAG, "Can't find %s folder while parsing current working directory\n", FOLDER_UNITTEST);
495         return OC_STACK_ERROR;
496     }
497
498     //Generate default svr db path
499     OICStrcatPartial(path, path_len, cwd, start - cwd); //copy iotivity root path
500     OICStrcatPartial(path, path_len, end, last - end); //copy 'resource/.../provisioning' path
501     OICStrcatPartial(path, path_len, FOLDER_SAMPLE, sizeof(FOLDER_SAMPLE));
502     OICStrcatPartial(path, path_len, slash_str, sizeof(slash_str));
503     OICStrcatPartial(path, path_len, SVR_DB_FILE_NAME, sizeof(SVR_DB_FILE_NAME));
504
505     return OC_STACK_OK;
506 }
507
508 int main()
509 {
510     struct timespec timeout;
511
512     //Delete previous SVR DB, if exist.
513     char cwd[1024] = {0};
514     char cmd[1024] = {0};
515     GetCurrentWorkingDirectory(cwd, sizeof(cwd));
516     snprintf(cmd, sizeof(cmd), "rm -rf %s%s", cwd, CRED_FILE);
517     system(cmd);
518
519     char default_svrdb_path[1024] = {0};
520     if (OC_STACK_OK != GenerateDefaultDbPath(cwd, default_svrdb_path, sizeof(default_svrdb_path)))
521     {
522         OIC_LOG(ERROR, TAG, "Can't generate default db path");
523         return 0;
524     }
525
526     //Copy default SVR DB to current folder
527     snprintf(cmd, sizeof(cmd), "cp %s %s", default_svrdb_path, CRED_FILE);
528     system(cmd);
529
530     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
531
532     // Initialize Persistent Storage for SVR database
533     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
534
535     OCRegisterPersistentStorageHandler(&ps);
536
537     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
538     {
539         OIC_LOG(ERROR, TAG, "OCStack init error");
540         return 0;
541     }
542
543     //Set another device ID to 2nd server
544     //Because it uses the same DB as 1st one but uuid should be different
545     OicUuid_t uuid;
546     ConvertStrToUuid("11111111-1234-1234-1234-123456789012", &uuid);
547
548     if (OC_STACK_OK != SetDoxmDeviceID(&uuid))
549     {
550         OIC_LOG(WARNING, TAG, "Can't change deviceID in server 2");
551     }
552
553     /*
554      * Declare and create the example resource: LED
555      */
556     createLEDResource(gResourceUri, &LED, false, 0);
557
558     timeout.tv_sec  = 0;
559     timeout.tv_nsec = 100000000L;
560
561     // Break from loop with Ctrl-C
562     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
563     signal(SIGINT, handleSigInt);
564     while (!gQuitFlag)
565     {
566         if (OCProcess() != OC_STACK_OK)
567         {
568             OIC_LOG(ERROR, TAG, "OCStack process error");
569             return 0;
570         }
571         nanosleep(&timeout, NULL);
572     }
573
574     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
575
576     if (OCStop() != OC_STACK_OK)
577     {
578         OIC_LOG(ERROR, TAG, "OCStack process error");
579     }
580
581     return 0;
582 }
583
584 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
585 {
586     if (!uri)
587     {
588         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
589         return -1;
590     }
591
592     ledResource->state = resourceState;
593     ledResource->power= resourcePower;
594     OCStackResult res = OCCreateResource(&(ledResource->handle),
595             "core.led",
596             OC_RSRVD_INTERFACE_DEFAULT,
597             uri,
598             OCEntityHandlerCb,
599             NULL,
600             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
601     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
602
603     return 0;
604 }