replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / sample / sampleserver_justworks_protectedDB.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 "iotivity_config.h"
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #ifdef HAVE_PTHREAD_H
31 #include <pthread.h>
32 #endif
33 #include <signal.h>
34 #include "ocstack.h"
35 #include "ocpayload.h"
36 #include "pinoxmcommon.h"
37
38 #ifdef HAVE_WINDOWS_H
39 #include <windows.h>
40 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
41 #ifdef ERROR
42 #undef ERROR
43 #endif //ERROR
44 #endif //HAVE_WINDOWS_H
45 #include "platform_features.h"
46 #include "logger.h"
47
48
49 #define TAG "SAMPLE_JUSTWORKS"
50
51 int gQuitFlag = 0;
52
53 /* Structure to represent a LED resource */
54 typedef struct LEDRESOURCE{
55     OCResourceHandle handle;
56     bool state;
57     int power;
58 } LEDResource;
59
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];
66
67 char *gResourceUri= (char *)"/a/led";
68
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";
76
77 /* Function that creates a new LED resource by calling the
78  * OCCreateResource() method.
79  */
80 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
81
82 /* This method converts the payload to JSON format */
83 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
84
85 /* Following methods process the PUT, GET, POST
86  * requests
87  */
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;
97
98
99 /* Entity Handler callback functions */
100 OCEntityHandlerResult
101 OCEntityHandlerCb (OCEntityHandlerFlag flag,
102         OCEntityHandlerRequest *entityHandlerRequest,
103         void* callbackParam);
104
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
109                          };
110
111 const char *getResult(OCStackResult result) {
112     switch (result) {
113     case OC_STACK_OK:
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";
147     #ifdef WITH_PRESENCE
148     case OC_STACK_PRESENCE_STOPPED:
149         return "OC_STACK_PRESENCE_STOPPED";
150     #endif
151     case OC_STACK_ERROR:
152         return "OC_STACK_ERROR";
153     default:
154         return "UNKNOWN";
155     }
156 }
157
158 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
159 {
160     OCRepPayload* payload = OCRepPayloadCreate();
161     if(!payload)
162     {
163         OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
164         return NULL;
165     }
166
167     OCRepPayloadSetUri(payload, uri);
168     OCRepPayloadSetPropBool(payload, "state", state);
169     OCRepPayloadSetPropInt(payload, "power", power);
170
171     return payload;
172 }
173
174 //This function takes the request as an input and returns the response
175 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
176 {
177     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
178     {
179         OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
180         return NULL;
181     }
182
183     OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
184
185     LEDResource *currLEDResource = &LED;
186
187     if (ehRequest->resource == gLedInstance[0].handle)
188     {
189         currLEDResource = &gLedInstance[0];
190         gResourceUri = (char *) "/a/led/0";
191     }
192     else if (ehRequest->resource == gLedInstance[1].handle)
193     {
194         currLEDResource = &gLedInstance[1];
195         gResourceUri = (char *) "/a/led/1";
196     }
197
198     if(OC_REST_PUT == ehRequest->method)
199     {
200         // Get pointer to query
201         int64_t pow;
202         if(OCRepPayloadGetPropInt(input, "power", &pow))
203         {
204             currLEDResource->power =pow;
205         }
206
207         bool state;
208         if(OCRepPayloadGetPropBool(input, "state", &state))
209         {
210             currLEDResource->state = state;
211         }
212     }
213
214     return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
215 }
216
217 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
218         OCRepPayload **payload)
219 {
220     OCEntityHandlerResult ehResult;
221
222     OCRepPayload *getResp = constructResponse(ehRequest);
223
224     if(getResp)
225     {
226         *payload = getResp;
227         ehResult = OC_EH_OK;
228     }
229     else
230     {
231         ehResult = OC_EH_ERROR;
232     }
233
234     return ehResult;
235 }
236
237 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
238         OCRepPayload **payload)
239 {
240     OCEntityHandlerResult ehResult;
241
242     OCRepPayload *putResp = constructResponse(ehRequest);
243
244     if(putResp)
245     {
246         *payload = putResp;
247         ehResult = OC_EH_OK;
248     }
249     else
250     {
251         ehResult = OC_EH_ERROR;
252     }
253
254     return ehResult;
255 }
256
257 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
258         OCEntityHandlerResponse *response, OCRepPayload **payload)
259 {
260     OCRepPayload *respPLPost_led = NULL;
261     OCEntityHandlerResult ehResult = OC_EH_OK;
262
263     /*
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)
272      */
273
274     if (ehRequest->resource == LED.handle)
275     {
276         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
277         {
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);
282
283             respPLPost_led = OCRepPayloadCreate();
284             OCRepPayloadSetUri(respPLPost_led, gResourceUri);
285             OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
286
287             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
288             {
289                 OIC_LOG (INFO, TAG, "Created new LED instance");
290                 gLedInstance[gCurrLedInstance].state = 0;
291                 gLedInstance[gCurrLedInstance].power = 0;
292                 gCurrLedInstance++;
293                 strncpy ((char *)response->resourceUri, newLedUri, sizeof(response->resourceUri));
294                 ehResult = OC_EH_RESOURCE_CREATED;
295             }
296         }
297         else
298         {
299             respPLPost_led = constructResponse(ehRequest);
300         }
301     }
302     else
303     {
304         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
305         {
306             if (ehRequest->resource == gLedInstance[i].handle)
307             {
308                 if (i == 0)
309                 {
310                     respPLPost_led = constructResponse(ehRequest);
311                     break;
312                 }
313                 else if (i == 1)
314                 {
315                     respPLPost_led = constructResponse(ehRequest);
316                 }
317             }
318         }
319     }
320
321     if (respPLPost_led != NULL)
322     {
323         *payload = respPLPost_led;
324         ehResult = OC_EH_OK;
325     }
326     else
327     {
328         OIC_LOG_V (INFO, TAG, "Payload was NULL");
329         ehResult = OC_EH_ERROR;
330     }
331
332     return ehResult;
333 }
334
335 OCEntityHandlerResult
336 OCEntityHandlerCb (OCEntityHandlerFlag flag,
337         OCEntityHandlerRequest *entityHandlerRequest,
338         void* callbackParam)
339 {
340     OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
341     (void)callbackParam;
342     OCEntityHandlerResult ehResult = OC_EH_ERROR;
343
344     OCEntityHandlerResponse response;
345     memset(&response, 0, sizeof(response));
346
347     // Validate pointer
348     if (!entityHandlerRequest)
349     {
350         OIC_LOG (ERROR, TAG, "Invalid request pointer");
351         return OC_EH_ERROR;
352     }
353
354     OCRepPayload* payload = NULL;
355
356     if (flag & OC_REQUEST_FLAG)
357     {
358         OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
359         if (entityHandlerRequest)
360         {
361             if (OC_REST_GET == entityHandlerRequest->method)
362             {
363                 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
364                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
365             }
366             else if (OC_REST_PUT == entityHandlerRequest->method)
367             {
368                 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
369                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
370             }
371             else if (OC_REST_POST == entityHandlerRequest->method)
372             {
373                 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
374                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
375             }
376             else
377             {
378                 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
379                         entityHandlerRequest->method);
380                 ehResult = OC_EH_ERROR;
381             }
382
383             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
384             {
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;
396
397                 // Send the response
398                 if (OCDoResponse(&response) != OC_STACK_OK)
399                 {
400                     OIC_LOG(ERROR, TAG, "Error sending response");
401                     ehResult = OC_EH_ERROR;
402                 }
403             }
404         }
405     }
406
407     OCPayloadDestroy(response.payload);
408     return ehResult;
409 }
410
411 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
412 void handleSigInt(int signum)
413 {
414     if (signum == SIGINT)
415     {
416         gQuitFlag = 1;
417     }
418 }
419
420 FILE* plain_fopen(const char *path, const char *mode)
421 {
422     (void)path;
423     return fopen(SVR_DB_PLAIN_FILE, mode);
424 }
425
426 int plain_unlink(const char *path)
427 {
428     OIC_LOG(INFO, TAG, "plain DB is removed");
429     (void)path;
430     return unlink(SVR_DB_PLAIN_FILE);
431 }
432
433 FILE* encrypted_fopen(const char *path, const char *mode)
434 {
435     (void)path;
436     return fopen(SVR_DB_ENCRYPTED_FILE, mode);
437 }
438
439 FILE* rescue_fopen(const char *path, const char *mode)
440 {
441     (void)path;
442     return fopen(RESCUE_FILE, mode);
443 }
444
445 int main()
446 {
447     OCStackResult ret;
448     struct timespec timeout;
449
450     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
451
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};
456
457     ret = OCSetSecurePSI(key, &psPlain, &psEnc, &psRescue);
458     if (OC_STACK_OK != ret)
459     {
460         OIC_LOG(ERROR, TAG, "OCSetSecurePSI() error");
461         return 1;
462     }
463
464     ret = OCRegisterPersistentStorageHandler(&psEnc);
465     if (OC_STACK_OK != ret)
466     {
467         OIC_LOG(ERROR, TAG, "OCRegisterPersistentStorageHandler() error");
468         return 1;
469     }
470
471     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
472     {
473         OIC_LOG(ERROR, TAG, "OCStack init error");
474         return 1;
475     }
476
477     /*
478      * Declare and create the example resource: LED
479      */
480     createLEDResource(gResourceUri, &LED, false, 0);
481
482     timeout.tv_sec  = 0;
483     timeout.tv_nsec = 100000000L;
484
485     // Break from loop with Ctrl-C
486     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
487     signal(SIGINT, handleSigInt);
488     while (!gQuitFlag)
489     {
490         if (OCProcess() != OC_STACK_OK)
491         {
492             OIC_LOG(ERROR, TAG, "OCStack process error");
493             return 1;
494         }
495         nanosleep(&timeout, NULL);
496     }
497
498     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
499
500     if (OCStop() != OC_STACK_OK)
501     {
502         OIC_LOG(ERROR, TAG, "OCStack process error");
503     }
504
505     return 0;
506 }
507
508 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
509 {
510     if (!uri)
511     {
512         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
513         return -1;
514     }
515
516     ledResource->state = resourceState;
517     ledResource->power= resourcePower;
518     OCStackResult res = OCCreateResource(&(ledResource->handle),
519             "core.led",
520             OC_RSRVD_INTERFACE_DEFAULT,
521             uri,
522             OCEntityHandlerCb,
523             NULL,
524             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
525     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
526
527     return 0;
528 }