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 ///////////////////////////////////////////////////////////////////////
23 #include "iotivity_config.h"
35 #include "ocpayload.h"
36 #include "pinoxmcommon.h"
40 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
44 #endif //HAVE_WINDOWS_H
45 #include "platform_features.h"
49 #define TAG "SAMPLE_JUSTWORKS"
53 /* Structure to represent a LED resource */
54 typedef struct LEDRESOURCE{
55 OCResourceHandle handle;
60 static LEDResource LED;
61 // This variable determines instance number of the LED resource.
62 // Used by POST method to create a new instance of LED resource.
63 static int gCurrLedInstance = 0;
64 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
65 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
67 char *gResourceUri= (char *)"/a/led";
69 //Secure Virtual Resource database for Iotivity Server
70 //It contains Server's Identity and the PSK credentials
71 //of other devices which the server trusts
72 //static char CRED_FILE[] = "oic_svr_db_server_justworks_protectedDB.dat";
73 static char RESCUE_FILE[] = "oic_svr_db_server_justworks_default.dat";
74 static char SVR_DB_PLAIN_FILE[] = "oic_svr_db_server_justworks_protectedDB_plain.dat";
75 static char SVR_DB_ENCRYPTED_FILE[] = "oic_svr_db_server_justworks_protectedDB_encrypted.dat";
77 /* Function that creates a new LED resource by calling the
78 * OCCreateResource() method.
80 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
82 /* This method converts the payload to JSON format */
83 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
85 /* Following methods process the PUT, GET, POST
88 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
89 OCRepPayload **payload);
90 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
91 OCRepPayload **payload);
92 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
93 OCEntityHandlerResponse *response,
94 OCRepPayload **payload);
95 // Initialize Persistent Storage for SVR database
96 OCPersistentStorage *ps = NULL;
99 /* Entity Handler callback functions */
100 OCEntityHandlerResult
101 OCEntityHandlerCb (OCEntityHandlerFlag flag,
102 OCEntityHandlerRequest *entityHandlerRequest,
103 void* callbackParam);
105 unsigned char key[32] = { 0xa5, 0x84, 0x99, 0x8d, 0x0d, 0xbd, 0xb1, 0x54,
106 0xbb, 0xc5, 0x4f, 0xed, 0x86, 0x9a, 0x66, 0x11,
107 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
108 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5
111 const char *getResult(OCStackResult result) {
114 return "OC_STACK_OK";
115 case OC_STACK_RESOURCE_CREATED:
116 return "OC_STACK_RESOURCE_CREATED";
117 case OC_STACK_RESOURCE_DELETED:
118 return "OC_STACK_RESOURCE_DELETED";
119 case OC_STACK_INVALID_URI:
120 return "OC_STACK_INVALID_URI";
121 case OC_STACK_INVALID_QUERY:
122 return "OC_STACK_INVALID_QUERY";
123 case OC_STACK_INVALID_IP:
124 return "OC_STACK_INVALID_IP";
125 case OC_STACK_INVALID_PORT:
126 return "OC_STACK_INVALID_PORT";
127 case OC_STACK_INVALID_CALLBACK:
128 return "OC_STACK_INVALID_CALLBACK";
129 case OC_STACK_INVALID_METHOD:
130 return "OC_STACK_INVALID_METHOD";
131 case OC_STACK_NO_MEMORY:
132 return "OC_STACK_NO_MEMORY";
133 case OC_STACK_COMM_ERROR:
134 return "OC_STACK_COMM_ERROR";
135 case OC_STACK_INVALID_PARAM:
136 return "OC_STACK_INVALID_PARAM";
137 case OC_STACK_NOTIMPL:
138 return "OC_STACK_NOTIMPL";
139 case OC_STACK_NO_RESOURCE:
140 return "OC_STACK_NO_RESOURCE";
141 case OC_STACK_RESOURCE_ERROR:
142 return "OC_STACK_RESOURCE_ERROR";
143 case OC_STACK_SLOW_RESOURCE:
144 return "OC_STACK_SLOW_RESOURCE";
145 case OC_STACK_NO_OBSERVERS:
146 return "OC_STACK_NO_OBSERVERS";
148 case OC_STACK_PRESENCE_STOPPED:
149 return "OC_STACK_PRESENCE_STOPPED";
152 return "OC_STACK_ERROR";
158 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
160 OCRepPayload* payload = OCRepPayloadCreate();
163 OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
167 OCRepPayloadSetUri(payload, uri);
168 OCRepPayloadSetPropBool(payload, "state", state);
169 OCRepPayloadSetPropInt(payload, "power", power);
174 //This function takes the request as an input and returns the response
175 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
177 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
179 OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
183 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
185 LEDResource *currLEDResource = &LED;
187 if (ehRequest->resource == gLedInstance[0].handle)
189 currLEDResource = &gLedInstance[0];
190 gResourceUri = (char *) "/a/led/0";
192 else if (ehRequest->resource == gLedInstance[1].handle)
194 currLEDResource = &gLedInstance[1];
195 gResourceUri = (char *) "/a/led/1";
198 if(OC_REST_PUT == ehRequest->method)
200 // Get pointer to query
202 if(OCRepPayloadGetPropInt(input, "power", &pow))
204 currLEDResource->power =pow;
208 if(OCRepPayloadGetPropBool(input, "state", &state))
210 currLEDResource->state = state;
214 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
217 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
218 OCRepPayload **payload)
220 OCEntityHandlerResult ehResult;
222 OCRepPayload *getResp = constructResponse(ehRequest);
231 ehResult = OC_EH_ERROR;
237 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
238 OCRepPayload **payload)
240 OCEntityHandlerResult ehResult;
242 OCRepPayload *putResp = constructResponse(ehRequest);
251 ehResult = OC_EH_ERROR;
257 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
258 OCEntityHandlerResponse *response, OCRepPayload **payload)
260 OCRepPayload *respPLPost_led = NULL;
261 OCEntityHandlerResult ehResult = OC_EH_OK;
264 * The entity handler determines how to process a POST request.
265 * Per the REST paradigm, POST can also be used to update representation of existing
266 * resource or create a new resource.
267 * In the sample below, if the POST is for /a/led then a new instance of the LED
268 * resource is created with default representation (if representation is included in
269 * POST payload it can be used as initial values) as long as the instance is
270 * lesser than max new instance count. Once max instance count is reached, POST on
271 * /a/led updated the representation of /a/led (just like PUT)
274 if (ehRequest->resource == LED.handle)
276 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
278 // Create new LED instance
279 char newLedUri[15] = "/a/led/";
280 int newLedUriLength = strlen(newLedUri);
281 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
283 respPLPost_led = OCRepPayloadCreate();
284 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
285 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
287 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
289 OIC_LOG (INFO, TAG, "Created new LED instance");
290 gLedInstance[gCurrLedInstance].state = 0;
291 gLedInstance[gCurrLedInstance].power = 0;
293 strncpy ((char *)response->resourceUri, newLedUri, sizeof(response->resourceUri));
294 ehResult = OC_EH_RESOURCE_CREATED;
299 respPLPost_led = constructResponse(ehRequest);
304 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
306 if (ehRequest->resource == gLedInstance[i].handle)
310 respPLPost_led = constructResponse(ehRequest);
315 respPLPost_led = constructResponse(ehRequest);
321 if (respPLPost_led != NULL)
323 *payload = respPLPost_led;
328 OIC_LOG_V (INFO, TAG, "Payload was NULL");
329 ehResult = OC_EH_ERROR;
335 OCEntityHandlerResult
336 OCEntityHandlerCb (OCEntityHandlerFlag flag,
337 OCEntityHandlerRequest *entityHandlerRequest,
340 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
342 OCEntityHandlerResult ehResult = OC_EH_ERROR;
344 OCEntityHandlerResponse response;
345 memset(&response, 0, sizeof(response));
348 if (!entityHandlerRequest)
350 OIC_LOG (ERROR, TAG, "Invalid request pointer");
354 OCRepPayload* payload = NULL;
356 if (flag & OC_REQUEST_FLAG)
358 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
359 if (entityHandlerRequest)
361 if (OC_REST_GET == entityHandlerRequest->method)
363 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
364 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
366 else if (OC_REST_PUT == entityHandlerRequest->method)
368 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
369 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
371 else if (OC_REST_POST == entityHandlerRequest->method)
373 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
374 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
378 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
379 entityHandlerRequest->method);
380 ehResult = OC_EH_ERROR;
383 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
385 // Format the response. Note this requires some info about the request
386 response.requestHandle = entityHandlerRequest->requestHandle;
387 response.resourceHandle = entityHandlerRequest->resource;
388 response.ehResult = ehResult;
389 response.payload = (OCPayload*)(payload);
390 response.numSendVendorSpecificHeaderOptions = 0;
391 memset(response.sendVendorSpecificHeaderOptions, 0,
392 sizeof(response.sendVendorSpecificHeaderOptions));
393 memset(response.resourceUri, 0, sizeof(response.resourceUri));
394 // Indicate that response is NOT in a persistent buffer
395 response.persistentBufferFlag = 0;
398 if (OCDoResponse(&response) != OC_STACK_OK)
400 OIC_LOG(ERROR, TAG, "Error sending response");
401 ehResult = OC_EH_ERROR;
407 OCPayloadDestroy(response.payload);
411 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
412 void handleSigInt(int signum)
414 if (signum == SIGINT)
420 FILE* plain_fopen(const char *path, const char *mode)
423 return fopen(SVR_DB_PLAIN_FILE, mode);
426 int plain_unlink(const char *path)
428 OIC_LOG(INFO, TAG, "plain DB is removed");
430 return unlink(SVR_DB_PLAIN_FILE);
433 FILE* encrypted_fopen(const char *path, const char *mode)
436 return fopen(SVR_DB_ENCRYPTED_FILE, mode);
439 FILE* rescue_fopen(const char *path, const char *mode)
442 return fopen(RESCUE_FILE, mode);
448 struct timespec timeout;
450 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
452 OCPersistentStorage psPlain = {plain_fopen, fread, NULL, fclose, plain_unlink, NULL, NULL};
453 OCPersistentStorage psEnc = {encrypted_fopen, fread, fwrite, fclose,
454 unlink, OCEncrypt, OCDecrypt};
455 OCPersistentStorage psRescue = {rescue_fopen, fread, NULL, fclose, NULL, NULL, NULL};
457 ret = OCSetSecurePSI(key, &psPlain, &psEnc, &psRescue);
458 if (OC_STACK_OK != ret)
460 OIC_LOG(ERROR, TAG, "OCSetSecurePSI() error");
464 ret = OCRegisterPersistentStorageHandler(&psEnc);
465 if (OC_STACK_OK != ret)
467 OIC_LOG(ERROR, TAG, "OCRegisterPersistentStorageHandler() error");
471 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
473 OIC_LOG(ERROR, TAG, "OCStack init error");
478 * Declare and create the example resource: LED
480 createLEDResource(gResourceUri, &LED, false, 0);
483 timeout.tv_nsec = 100000000L;
485 // Break from loop with Ctrl-C
486 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
487 signal(SIGINT, handleSigInt);
490 if (OCProcess() != OC_STACK_OK)
492 OIC_LOG(ERROR, TAG, "OCStack process error");
495 nanosleep(&timeout, NULL);
498 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
500 if (OCStop() != OC_STACK_OK)
502 OIC_LOG(ERROR, TAG, "OCStack process error");
508 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
512 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
516 ledResource->state = resourceState;
517 ledResource->power= resourcePower;
518 OCStackResult res = OCCreateResource(&(ledResource->handle),
520 OC_RSRVD_INTERFACE_DEFAULT,
524 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
525 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));