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 #include "doxmresource.h"
35 #include "srmutility.h"
37 #define TAG "UNITTEST_SERVER_2"
41 /* Structure to represent a LED resource */
42 typedef struct LEDRESOURCE{
43 OCResourceHandle handle;
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];
55 char *gResourceUri= (char *)"/a/led";
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";
62 static char SVR_DB_FILE_NAME[] = "oic_svr_db_server_justworks.dat";
64 /* Function that creates a new LED resource by calling the
65 * OCCreateResource() method.
67 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
69 /* This method converts the payload to JSON format */
70 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
72 /* Following methods process the PUT, GET, POST
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);
83 /* Entity Handler callback functions */
85 OCEntityHandlerCb (OCEntityHandlerFlag flag,
86 OCEntityHandlerRequest *entityHandlerRequest,
89 const char *getResult(OCStackResult result) {
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";
126 case OC_STACK_PRESENCE_STOPPED:
127 return "OC_STACK_PRESENCE_STOPPED";
130 return "OC_STACK_ERROR";
136 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
138 OCRepPayload* payload = OCRepPayloadCreate();
141 OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
145 OCRepPayloadSetUri(payload, uri);
146 OCRepPayloadSetPropBool(payload, "state", state);
147 OCRepPayloadSetPropInt(payload, "power", power);
152 //This function takes the request as an input and returns the response
153 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
155 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
157 OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
161 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
163 LEDResource *currLEDResource = &LED;
165 if (ehRequest->resource == gLedInstance[0].handle)
167 currLEDResource = &gLedInstance[0];
168 gResourceUri = (char *) "/a/led/0";
170 else if (ehRequest->resource == gLedInstance[1].handle)
172 currLEDResource = &gLedInstance[1];
173 gResourceUri = (char *) "/a/led/1";
176 if(OC_REST_PUT == ehRequest->method)
178 // Get pointer to query
180 if(OCRepPayloadGetPropInt(input, "power", &pow))
182 currLEDResource->power =pow;
186 if(OCRepPayloadGetPropBool(input, "state", &state))
188 currLEDResource->state = state;
192 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
195 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
196 OCRepPayload **payload)
198 OCEntityHandlerResult ehResult;
200 OCRepPayload *getResp = constructResponse(ehRequest);
209 ehResult = OC_EH_ERROR;
215 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
216 OCRepPayload **payload)
218 OCEntityHandlerResult ehResult;
220 OCRepPayload *putResp = constructResponse(ehRequest);
229 ehResult = OC_EH_ERROR;
235 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
236 OCEntityHandlerResponse *response, OCRepPayload **payload)
238 OCRepPayload *respPLPost_led = NULL;
239 OCEntityHandlerResult ehResult = OC_EH_OK;
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)
252 if (ehRequest->resource == LED.handle)
254 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
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);
261 respPLPost_led = OCRepPayloadCreate();
262 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
263 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
265 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
267 OIC_LOG (INFO, TAG, "Created new LED instance");
268 gLedInstance[gCurrLedInstance].state = 0;
269 gLedInstance[gCurrLedInstance].power = 0;
271 strncpy ((char *)response->resourceUri, newLedUri, sizeof(response->resourceUri));
272 ehResult = OC_EH_RESOURCE_CREATED;
277 respPLPost_led = constructResponse(ehRequest);
282 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
284 if (ehRequest->resource == gLedInstance[i].handle)
288 respPLPost_led = constructResponse(ehRequest);
293 respPLPost_led = constructResponse(ehRequest);
299 if (respPLPost_led != NULL)
301 *payload = respPLPost_led;
306 OIC_LOG_V (INFO, TAG, "Payload was NULL");
307 ehResult = OC_EH_ERROR;
313 OCEntityHandlerResult
314 OCEntityHandlerCb (OCEntityHandlerFlag flag,
315 OCEntityHandlerRequest *entityHandlerRequest,
318 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
320 OCEntityHandlerResult ehResult = OC_EH_ERROR;
322 OCEntityHandlerResponse response;
323 memset(&response, 0, sizeof(response));
326 if (!entityHandlerRequest)
328 OIC_LOG (ERROR, TAG, "Invalid request pointer");
332 OCRepPayload* payload = NULL;
334 if (flag & OC_REQUEST_FLAG)
336 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
337 if (entityHandlerRequest)
339 if (OC_REST_GET == entityHandlerRequest->method)
341 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
342 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
344 else if (OC_REST_PUT == entityHandlerRequest->method)
346 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
347 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
349 else if (OC_REST_POST == entityHandlerRequest->method)
351 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
352 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
356 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
357 entityHandlerRequest->method);
358 ehResult = OC_EH_ERROR;
361 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
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;
376 if (OCDoResponse(&response) != OC_STACK_OK)
378 OIC_LOG(ERROR, TAG, "Error sending response");
379 ehResult = OC_EH_ERROR;
385 OCPayloadDestroy(response.payload);
389 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
390 void handleSigInt(int signum)
392 if (signum == SIGINT)
398 static void GetCurrentWorkingDirectory(char* buf, size_t bufsize)
400 char cwd[1024] = {0};
401 const char* unittest_path = "resource/csdk/security/provisioning/unittest";
402 if(getcwd(cwd, sizeof(cwd)) != NULL)
404 if(strstr(cwd, unittest_path) == NULL)
406 #if defined __linux__
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);
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);
414 #endif //defined __linux__
418 snprintf(buf, bufsize, "%s/", cwd);
423 FILE* server_fopen(const char *path, const char *mode)
425 if (0 == strcmp(path, OC_SECURITY_DB_DAT_FILE_NAME))
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);
435 return fopen(path, mode);
440 * Generate default SVR DB path
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
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.
451 static OCStackResult GenerateDefaultDbPath(const char *cwd, char *path, size_t path_len)
453 const char FOLDER_OUT[] = "out";
454 const char FOLDER_UNITTEST[] = "unittest";
455 const char FOLDER_SAMPLE[] = "sample";
458 const char slash = '\\';
460 const char slash = '/';
463 const char slash_str[2] = {slash, 0};
468 snprintf(out, sizeof(out), "%c%s%c", slash, FOLDER_OUT, slash);
470 char *start = strstr((char*)cwd, out);
473 OIC_LOG_V(ERROR, TAG, "Can't find %s folder while parsing current working directory\n", FOLDER_OUT);
474 return OC_STACK_ERROR;
476 start++; //Go to next symbol after slash
479 for (int i = 0; i < 4; i++)
481 end = strchr(end, slash);
484 OIC_LOG_V(ERROR, TAG, "Can't find slash number %d while parsing current working directory\n", i);
485 return OC_STACK_ERROR;
487 end++; //Go to next symbol after slash
490 //Cut "unittest" string at the end
491 char *last = strstr(end, FOLDER_UNITTEST);
494 OIC_LOG_V(ERROR, TAG, "Can't find %s folder while parsing current working directory\n", FOLDER_UNITTEST);
495 return OC_STACK_ERROR;
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));
510 struct timespec timeout;
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);
519 char default_svrdb_path[1024] = {0};
520 if (OC_STACK_OK != GenerateDefaultDbPath(cwd, default_svrdb_path, sizeof(default_svrdb_path)))
522 OIC_LOG(ERROR, TAG, "Can't generate default db path");
526 //Copy default SVR DB to current folder
527 snprintf(cmd, sizeof(cmd), "cp %s %s", default_svrdb_path, CRED_FILE);
530 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
532 // Initialize Persistent Storage for SVR database
533 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
535 OCRegisterPersistentStorageHandler(&ps);
537 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
539 OIC_LOG(ERROR, TAG, "OCStack init error");
543 //Set another device ID to 2nd server
544 //Because it uses the same DB as 1st one but uuid should be different
546 ConvertStrToUuid("11111111-1234-1234-1234-123456789012", &uuid);
548 if (OC_STACK_OK != SetDoxmDeviceID(&uuid))
550 OIC_LOG(WARNING, TAG, "Can't change deviceID in server 2");
554 * Declare and create the example resource: LED
556 createLEDResource(gResourceUri, &LED, false, 0);
559 timeout.tv_nsec = 100000000L;
561 // Break from loop with Ctrl-C
562 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
563 signal(SIGINT, handleSigInt);
566 if (OCProcess() != OC_STACK_OK)
568 OIC_LOG(ERROR, TAG, "OCStack process error");
571 nanosleep(&timeout, NULL);
574 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
576 if (OCStop() != OC_STACK_OK)
578 OIC_LOG(ERROR, TAG, "OCStack process error");
584 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
588 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
592 ledResource->state = resourceState;
593 ledResource->power= resourcePower;
594 OCStackResult res = OCCreateResource(&(ledResource->handle),
596 OC_RSRVD_INTERFACE_DEFAULT,
600 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
601 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));