1 /******************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
20 ///////////////////////////////////////////////////////////////////////
21 //NOTE : This sample server is generated based on ocserverbasicops.cpp
22 ///////////////////////////////////////////////////////////////////////
31 #include "ocpayload.h"
32 #include "oic_string.h"
34 #define TAG "UNITTEST_SERVER_1"
38 /* Structure to represent a LED resource */
39 typedef struct LEDRESOURCE{
40 OCResourceHandle handle;
45 static LEDResource LED;
46 // This variable determines instance number of the LED resource.
47 // Used by POST method to create a new instance of LED resource.
48 static int gCurrLedInstance = 0;
49 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
50 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
52 char *gResourceUri= (char *)"/a/led";
54 //Secure Virtual Resource database for Iotivity Server
55 //It contains Server's Identity and the PSK credentials
56 //of other devices which the server trusts
57 static char CRED_FILE[] = "oic_svr_db_server1.dat";
59 static char SVR_DB_FILE_NAME[] = "oic_svr_db_server_justworks.dat";
61 /* Function that creates a new LED resource by calling the
62 * OCCreateResource() method.
64 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
66 /* This method converts the payload to JSON format */
67 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
69 /* Following methods process the PUT, GET, POST
72 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
73 OCRepPayload **payload);
74 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
75 OCRepPayload **payload);
76 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
77 OCEntityHandlerResponse *response,
78 OCRepPayload **payload);
80 /* Entity Handler callback functions */
82 OCEntityHandlerCb (OCEntityHandlerFlag flag,
83 OCEntityHandlerRequest *entityHandlerRequest,
86 const char *getResult(OCStackResult result) {
90 case OC_STACK_RESOURCE_CREATED:
91 return "OC_STACK_RESOURCE_CREATED";
92 case OC_STACK_RESOURCE_DELETED:
93 return "OC_STACK_RESOURCE_DELETED";
94 case OC_STACK_INVALID_URI:
95 return "OC_STACK_INVALID_URI";
96 case OC_STACK_INVALID_QUERY:
97 return "OC_STACK_INVALID_QUERY";
98 case OC_STACK_INVALID_IP:
99 return "OC_STACK_INVALID_IP";
100 case OC_STACK_INVALID_PORT:
101 return "OC_STACK_INVALID_PORT";
102 case OC_STACK_INVALID_CALLBACK:
103 return "OC_STACK_INVALID_CALLBACK";
104 case OC_STACK_INVALID_METHOD:
105 return "OC_STACK_INVALID_METHOD";
106 case OC_STACK_NO_MEMORY:
107 return "OC_STACK_NO_MEMORY";
108 case OC_STACK_COMM_ERROR:
109 return "OC_STACK_COMM_ERROR";
110 case OC_STACK_INVALID_PARAM:
111 return "OC_STACK_INVALID_PARAM";
112 case OC_STACK_NOTIMPL:
113 return "OC_STACK_NOTIMPL";
114 case OC_STACK_NO_RESOURCE:
115 return "OC_STACK_NO_RESOURCE";
116 case OC_STACK_RESOURCE_ERROR:
117 return "OC_STACK_RESOURCE_ERROR";
118 case OC_STACK_SLOW_RESOURCE:
119 return "OC_STACK_SLOW_RESOURCE";
120 case OC_STACK_NO_OBSERVERS:
121 return "OC_STACK_NO_OBSERVERS";
123 case OC_STACK_PRESENCE_STOPPED:
124 return "OC_STACK_PRESENCE_STOPPED";
127 return "OC_STACK_ERROR";
133 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
135 OCRepPayload* payload = OCRepPayloadCreate();
138 OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
142 OCRepPayloadSetUri(payload, uri);
143 OCRepPayloadSetPropBool(payload, "state", state);
144 OCRepPayloadSetPropInt(payload, "power", power);
149 //This function takes the request as an input and returns the response
150 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
152 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
154 OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
158 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
160 LEDResource *currLEDResource = &LED;
162 if (ehRequest->resource == gLedInstance[0].handle)
164 currLEDResource = &gLedInstance[0];
165 gResourceUri = (char *) "/a/led/0";
167 else if (ehRequest->resource == gLedInstance[1].handle)
169 currLEDResource = &gLedInstance[1];
170 gResourceUri = (char *) "/a/led/1";
173 if(OC_REST_PUT == ehRequest->method)
175 // Get pointer to query
177 if(OCRepPayloadGetPropInt(input, "power", &pow))
179 currLEDResource->power =pow;
183 if(OCRepPayloadGetPropBool(input, "state", &state))
185 currLEDResource->state = state;
189 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
192 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
193 OCRepPayload **payload)
195 OCEntityHandlerResult ehResult;
197 OCRepPayload *getResp = constructResponse(ehRequest);
206 ehResult = OC_EH_ERROR;
212 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
213 OCRepPayload **payload)
215 OCEntityHandlerResult ehResult;
217 OCRepPayload *putResp = constructResponse(ehRequest);
226 ehResult = OC_EH_ERROR;
232 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
233 OCEntityHandlerResponse *response, OCRepPayload **payload)
235 OCRepPayload *respPLPost_led = NULL;
236 OCEntityHandlerResult ehResult = OC_EH_OK;
239 * The entity handler determines how to process a POST request.
240 * Per the REST paradigm, POST can also be used to update representation of existing
241 * resource or create a new resource.
242 * In the sample below, if the POST is for /a/led then a new instance of the LED
243 * resource is created with default representation (if representation is included in
244 * POST payload it can be used as initial values) as long as the instance is
245 * lesser than max new instance count. Once max instance count is reached, POST on
246 * /a/led updated the representation of /a/led (just like PUT)
249 if (ehRequest->resource == LED.handle)
251 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
253 // Create new LED instance
254 char newLedUri[15] = "/a/led/";
255 int newLedUriLength = strlen(newLedUri);
256 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
258 respPLPost_led = OCRepPayloadCreate();
259 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
260 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
262 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
264 OIC_LOG (INFO, TAG, "Created new LED instance");
265 gLedInstance[gCurrLedInstance].state = 0;
266 gLedInstance[gCurrLedInstance].power = 0;
268 strncpy ((char *)response->resourceUri, newLedUri, sizeof(response->resourceUri));
269 ehResult = OC_EH_RESOURCE_CREATED;
274 respPLPost_led = constructResponse(ehRequest);
279 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
281 if (ehRequest->resource == gLedInstance[i].handle)
285 respPLPost_led = constructResponse(ehRequest);
290 respPLPost_led = constructResponse(ehRequest);
296 if (respPLPost_led != NULL)
298 *payload = respPLPost_led;
303 OIC_LOG_V (INFO, TAG, "Payload was NULL");
304 ehResult = OC_EH_ERROR;
310 OCEntityHandlerResult
311 OCEntityHandlerCb (OCEntityHandlerFlag flag,
312 OCEntityHandlerRequest *entityHandlerRequest,
315 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
317 OCEntityHandlerResult ehResult = OC_EH_ERROR;
319 OCEntityHandlerResponse response;
320 memset(&response, 0, sizeof(response));
323 if (!entityHandlerRequest)
325 OIC_LOG (ERROR, TAG, "Invalid request pointer");
329 OCRepPayload* payload = NULL;
331 if (flag & OC_REQUEST_FLAG)
333 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
334 if (entityHandlerRequest)
336 if (OC_REST_GET == entityHandlerRequest->method)
338 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
339 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
341 else if (OC_REST_PUT == entityHandlerRequest->method)
343 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
344 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
346 else if (OC_REST_POST == entityHandlerRequest->method)
348 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
349 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
353 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
354 entityHandlerRequest->method);
355 ehResult = OC_EH_ERROR;
358 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
360 // Format the response. Note this requires some info about the request
361 response.requestHandle = entityHandlerRequest->requestHandle;
362 response.resourceHandle = entityHandlerRequest->resource;
363 response.ehResult = ehResult;
364 response.payload = (OCPayload*)(payload);
365 response.numSendVendorSpecificHeaderOptions = 0;
366 memset(response.sendVendorSpecificHeaderOptions, 0,
367 sizeof(response.sendVendorSpecificHeaderOptions));
368 memset(response.resourceUri, 0, sizeof(response.resourceUri));
369 // Indicate that response is NOT in a persistent buffer
370 response.persistentBufferFlag = 0;
373 if (OCDoResponse(&response) != OC_STACK_OK)
375 OIC_LOG(ERROR, TAG, "Error sending response");
376 ehResult = OC_EH_ERROR;
382 OCPayloadDestroy(response.payload);
386 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
387 void handleSigInt(int signum)
389 if (signum == SIGINT)
395 static void GetCurrentWorkingDirectory(char* buf, size_t bufsize)
397 char cwd[1024] = {0};
398 const char* unittest_path = "resource/csdk/security/provisioning/unittest";
399 if(getcwd(cwd, sizeof(cwd)) != NULL)
401 if(strstr(cwd, unittest_path) == NULL)
403 #if defined __linux__
405 snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
406 snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
408 snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
409 snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
411 #endif //defined __linux__
415 snprintf(buf, bufsize, "%s/", cwd);
420 FILE* server_fopen(const char *path, const char *mode)
422 if (0 == strcmp(path, OC_SECURITY_DB_DAT_FILE_NAME))
424 char cwd[1024] = { 0 };
425 char cred_path[1024] = { 0 };
426 GetCurrentWorkingDirectory(cwd, sizeof(cwd));
427 snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
428 return fopen(cred_path, mode);
432 return fopen(path, mode);
437 * Generate default SVR DB path
439 * Exclude "out/<OS>/<platform>/<release>/" from current working directory path
440 * Replace "unittest" by "sample" at the end of current working directory path
441 * Add proper db file name to the end of path
443 * @param[in] cwd - current working directory
444 * @param[out] path - generated default database path
445 * @param[in] path_len - allocated length for variable path
446 * @return OC_STACK_OK for success.
448 static OCStackResult GenerateDefaultDbPath(const char *cwd, char *path, size_t path_len)
450 const char FOLDER_OUT[] = "out";
451 const char FOLDER_UNITTEST[] = "unittest";
452 const char FOLDER_SAMPLE[] = "sample";
455 const char slash = '\\';
457 const char slash = '/';
460 const char slash_str[2] = {slash, 0};
465 snprintf(out, sizeof(out), "%c%s%c", slash, FOLDER_OUT, slash);
467 char *start = strstr((char*)cwd, out);
470 OIC_LOG_V(ERROR, TAG, "Can't find %s folder while parsing current working directory\n", FOLDER_OUT);
471 return OC_STACK_ERROR;
473 start++; //Go to next symbol after slash
476 for (int i = 0; i < 4; i++)
478 end = strchr(end, slash);
481 OIC_LOG_V(ERROR, TAG, "Can't find slash number %d while parsing current working directory\n", i);
482 return OC_STACK_ERROR;
484 end++; //Go to next symbol after slash
487 //Cut "unittest" string at the end
488 char *last = strstr(end, FOLDER_UNITTEST);
491 OIC_LOG_V(ERROR, TAG, "Can't find %s folder while parsing current working directory\n", FOLDER_UNITTEST);
492 return OC_STACK_ERROR;
495 //Generate default svr db path
496 OICStrcatPartial(path, path_len, cwd, start - cwd); //copy iotivity root path
497 OICStrcatPartial(path, path_len, end, last - end); //copy 'resource/.../provisioning' path
498 OICStrcatPartial(path, path_len, FOLDER_SAMPLE, sizeof(FOLDER_SAMPLE));
499 OICStrcatPartial(path, path_len, slash_str, sizeof(slash_str));
500 OICStrcatPartial(path, path_len, SVR_DB_FILE_NAME, sizeof(SVR_DB_FILE_NAME));
507 struct timespec timeout;
509 //Delete previous SVR DB, if exist.
510 char cwd[1024] = {0};
511 char cmd[1024] = {0};
512 GetCurrentWorkingDirectory(cwd, sizeof(cwd));
513 snprintf(cmd, sizeof(cmd), "rm -rf %s%s", cwd, CRED_FILE);
516 char default_svrdb_path[1024] = {0};
517 if (OC_STACK_OK != GenerateDefaultDbPath(cwd, default_svrdb_path, sizeof(default_svrdb_path)))
519 OIC_LOG(ERROR, TAG, "Can't generate default db path");
523 //Copy default SVR DB to current folder
524 snprintf(cmd, sizeof(cmd), "cp %s %s", default_svrdb_path, CRED_FILE);
527 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
529 // Initialize Persistent Storage for SVR database
530 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
532 OCRegisterPersistentStorageHandler(&ps);
534 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
536 OIC_LOG(ERROR, TAG, "OCStack init error");
541 * Declare and create the example resource: LED
543 createLEDResource(gResourceUri, &LED, false, 0);
546 timeout.tv_nsec = 100000000L;
548 // Break from loop with Ctrl-C
549 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
550 signal(SIGINT, handleSigInt);
553 if (OCProcess() != OC_STACK_OK)
555 OIC_LOG(ERROR, TAG, "OCStack process error");
558 nanosleep(&timeout, NULL);
561 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
563 if (OCStop() != OC_STACK_OK)
565 OIC_LOG(ERROR, TAG, "OCStack process error");
571 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
575 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
579 ledResource->state = resourceState;
580 ledResource->power= resourcePower;
581 OCStackResult res = OCCreateResource(&(ledResource->handle),
583 OC_RSRVD_INTERFACE_DEFAULT,
587 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
588 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));