Merge branch 'master' into ra.to.merge
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / sample / sampleserver_justworks.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
33 #define TAG "SAMPLE_JUSTWORKS"
34
35 int gQuitFlag = 0;
36
37 /* Structure to represent a LED resource */
38 typedef struct LEDRESOURCE{
39     OCResourceHandle handle;
40     bool state;
41     int power;
42 } LEDResource;
43
44 static LEDResource LED;
45 // This variable determines instance number of the LED resource.
46 // Used by POST method to create a new instance of LED resource.
47 static int gCurrLedInstance = 0;
48 #define SAMPLE_MAX_NUM_POST_INSTANCE  2
49 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
50
51 char *gResourceUri= (char *)"/a/led";
52
53 //Secure Virtual Resource database for Iotivity Server
54 //It contains Server's Identity and the PSK credentials
55 //of other devices which the server trusts
56 static char CRED_FILE[] = "oic_svr_db_server_justworks.json";
57
58 /* Function that creates a new LED resource by calling the
59  * OCCreateResource() method.
60  */
61 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
62
63 /* This method converts the payload to JSON format */
64 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
65
66 /* Following methods process the PUT, GET, POST
67  * requests
68  */
69 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
70                                          OCRepPayload **payload);
71 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
72                                          OCRepPayload **payload);
73 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
74                                         OCEntityHandlerResponse *response,
75                                         OCRepPayload **payload);
76
77 /* Entity Handler callback functions */
78 OCEntityHandlerResult
79 OCEntityHandlerCb (OCEntityHandlerFlag flag,
80         OCEntityHandlerRequest *entityHandlerRequest,
81         void* callbackParam);
82
83 const char *getResult(OCStackResult result) {
84     switch (result) {
85     case OC_STACK_OK:
86         return "OC_STACK_OK";
87     case OC_STACK_RESOURCE_CREATED:
88         return "OC_STACK_RESOURCE_CREATED";
89     case OC_STACK_RESOURCE_DELETED:
90         return "OC_STACK_RESOURCE_DELETED";
91     case OC_STACK_INVALID_URI:
92         return "OC_STACK_INVALID_URI";
93     case OC_STACK_INVALID_QUERY:
94         return "OC_STACK_INVALID_QUERY";
95     case OC_STACK_INVALID_IP:
96         return "OC_STACK_INVALID_IP";
97     case OC_STACK_INVALID_PORT:
98         return "OC_STACK_INVALID_PORT";
99     case OC_STACK_INVALID_CALLBACK:
100         return "OC_STACK_INVALID_CALLBACK";
101     case OC_STACK_INVALID_METHOD:
102         return "OC_STACK_INVALID_METHOD";
103     case OC_STACK_NO_MEMORY:
104         return "OC_STACK_NO_MEMORY";
105     case OC_STACK_COMM_ERROR:
106         return "OC_STACK_COMM_ERROR";
107     case OC_STACK_INVALID_PARAM:
108         return "OC_STACK_INVALID_PARAM";
109     case OC_STACK_NOTIMPL:
110         return "OC_STACK_NOTIMPL";
111     case OC_STACK_NO_RESOURCE:
112         return "OC_STACK_NO_RESOURCE";
113     case OC_STACK_RESOURCE_ERROR:
114         return "OC_STACK_RESOURCE_ERROR";
115     case OC_STACK_SLOW_RESOURCE:
116         return "OC_STACK_SLOW_RESOURCE";
117     case OC_STACK_NO_OBSERVERS:
118         return "OC_STACK_NO_OBSERVERS";
119     #ifdef WITH_PRESENCE
120     case OC_STACK_PRESENCE_STOPPED:
121         return "OC_STACK_PRESENCE_STOPPED";
122     #endif
123     case OC_STACK_ERROR:
124         return "OC_STACK_ERROR";
125     default:
126         return "UNKNOWN";
127     }
128 }
129
130 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
131 {
132     OCRepPayload* payload = OCRepPayloadCreate();
133     if(!payload)
134     {
135         OC_LOG(ERROR, TAG, "Failed to allocate Payload");
136         return NULL;
137     }
138
139     OCRepPayloadSetUri(payload, uri);
140     OCRepPayloadSetPropBool(payload, "state", state);
141     OCRepPayloadSetPropInt(payload, "power", power);
142
143     return payload;
144 }
145
146 //This function takes the request as an input and returns the response
147 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
148 {
149     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
150     {
151         OC_LOG(ERROR, TAG, "Incoming payload not a representation");
152         return NULL;
153     }
154
155     OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
156
157     LEDResource *currLEDResource = &LED;
158
159     if (ehRequest->resource == gLedInstance[0].handle)
160     {
161         currLEDResource = &gLedInstance[0];
162         gResourceUri = (char *) "/a/led/0";
163     }
164     else if (ehRequest->resource == gLedInstance[1].handle)
165     {
166         currLEDResource = &gLedInstance[1];
167         gResourceUri = (char *) "/a/led/1";
168     }
169
170     if(OC_REST_PUT == ehRequest->method)
171     {
172         // Get pointer to query
173         int64_t pow;
174         if(OCRepPayloadGetPropInt(input, "power", &pow))
175         {
176             currLEDResource->power =pow;
177         }
178
179         bool state;
180         if(OCRepPayloadGetPropBool(input, "state", &state))
181         {
182             currLEDResource->state = state;
183         }
184     }
185
186     return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
187 }
188
189 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
190         OCRepPayload **payload)
191 {
192     OCEntityHandlerResult ehResult;
193
194     OCRepPayload *getResp = constructResponse(ehRequest);
195
196     if(getResp)
197     {
198         *payload = getResp;
199         ehResult = OC_EH_OK;
200     }
201     else
202     {
203         ehResult = OC_EH_ERROR;
204     }
205
206     return ehResult;
207 }
208
209 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
210         OCRepPayload **payload)
211 {
212     OCEntityHandlerResult ehResult;
213
214     OCRepPayload *putResp = constructResponse(ehRequest);
215
216     if(putResp)
217     {
218         *payload = putResp;
219         ehResult = OC_EH_OK;
220     }
221     else
222     {
223         ehResult = OC_EH_ERROR;
224     }
225
226     return ehResult;
227 }
228
229 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
230         OCEntityHandlerResponse *response, OCRepPayload **payload)
231 {
232     OCRepPayload *respPLPost_led = NULL;
233     OCEntityHandlerResult ehResult = OC_EH_OK;
234
235     /*
236      * The entity handler determines how to process a POST request.
237      * Per the REST paradigm, POST can also be used to update representation of existing
238      * resource or create a new resource.
239      * In the sample below, if the POST is for /a/led then a new instance of the LED
240      * resource is created with default representation (if representation is included in
241      * POST payload it can be used as initial values) as long as the instance is
242      * lesser than max new instance count. Once max instance count is reached, POST on
243      * /a/led updated the representation of /a/led (just like PUT)
244      */
245
246     if (ehRequest->resource == LED.handle)
247     {
248         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
249         {
250             // Create new LED instance
251             char newLedUri[15] = "/a/led/";
252             int newLedUriLength = strlen(newLedUri);
253             snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
254
255             respPLPost_led = OCRepPayloadCreate();
256             OCRepPayloadSetUri(respPLPost_led, gResourceUri);
257             OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
258
259             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
260             {
261                 OC_LOG (INFO, TAG, "Created new LED instance");
262                 gLedInstance[gCurrLedInstance].state = 0;
263                 gLedInstance[gCurrLedInstance].power = 0;
264                 gCurrLedInstance++;
265                 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
266                 ehResult = OC_EH_RESOURCE_CREATED;
267             }
268         }
269         else
270         {
271             respPLPost_led = constructResponse(ehRequest);
272         }
273     }
274     else
275     {
276         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
277         {
278             if (ehRequest->resource == gLedInstance[i].handle)
279             {
280                 if (i == 0)
281                 {
282                     respPLPost_led = constructResponse(ehRequest);
283                     break;
284                 }
285                 else if (i == 1)
286                 {
287                     respPLPost_led = constructResponse(ehRequest);
288                 }
289             }
290         }
291     }
292
293     if (respPLPost_led != NULL)
294     {
295         *payload = respPLPost_led;
296         ehResult = OC_EH_OK;
297     }
298     else
299     {
300         OC_LOG_V (INFO, TAG, "Payload was NULL");
301         ehResult = OC_EH_ERROR;
302     }
303
304     return ehResult;
305 }
306
307 OCEntityHandlerResult
308 OCEntityHandlerCb (OCEntityHandlerFlag flag,
309         OCEntityHandlerRequest *entityHandlerRequest,
310         void* callbackParam)
311 {
312     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
313     (void)callbackParam;
314     OCEntityHandlerResult ehResult = OC_EH_ERROR;
315
316     OCEntityHandlerResponse response;
317     memset(&response, 0, sizeof(response));
318
319     // Validate pointer
320     if (!entityHandlerRequest)
321     {
322         OC_LOG (ERROR, TAG, "Invalid request pointer");
323         return OC_EH_ERROR;
324     }
325
326     OCRepPayload* payload = NULL;
327
328     if (flag & OC_REQUEST_FLAG)
329     {
330         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
331         if (entityHandlerRequest)
332         {
333             if (OC_REST_GET == entityHandlerRequest->method)
334             {
335                 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
336                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
337             }
338             else if (OC_REST_PUT == entityHandlerRequest->method)
339             {
340                 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
341                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
342             }
343             else if (OC_REST_POST == entityHandlerRequest->method)
344             {
345                 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
346                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
347             }
348             else
349             {
350                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
351                         entityHandlerRequest->method);
352                 ehResult = OC_EH_ERROR;
353             }
354
355             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
356             {
357                 // Format the response.  Note this requires some info about the request
358                 response.requestHandle = entityHandlerRequest->requestHandle;
359                 response.resourceHandle = entityHandlerRequest->resource;
360                 response.ehResult = ehResult;
361                 response.payload = (OCPayload*)(payload);
362                 response.numSendVendorSpecificHeaderOptions = 0;
363                 memset(response.sendVendorSpecificHeaderOptions, 0,
364                        sizeof(response.sendVendorSpecificHeaderOptions));
365                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
366                 // Indicate that response is NOT in a persistent buffer
367                 response.persistentBufferFlag = 0;
368
369                 // Send the response
370                 if (OCDoResponse(&response) != OC_STACK_OK)
371                 {
372                     OC_LOG(ERROR, TAG, "Error sending response");
373                     ehResult = OC_EH_ERROR;
374                 }
375             }
376         }
377     }
378
379     OCPayloadDestroy(response.payload);
380     return ehResult;
381 }
382
383 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
384 void handleSigInt(int signum)
385 {
386     if (signum == SIGINT)
387     {
388         gQuitFlag = 1;
389     }
390 }
391
392 FILE* server_fopen(const char *path, const char *mode)
393 {
394     (void)path;
395     return fopen(CRED_FILE, mode);
396 }
397
398 int main()
399 {
400     struct timespec timeout;
401
402     OC_LOG(DEBUG, TAG, "OCServer is starting...");
403
404     // Initialize Persistent Storage for SVR database
405     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
406
407     OCRegisterPersistentStorageHandler(&ps);
408
409     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
410     {
411         OC_LOG(ERROR, TAG, "OCStack init error");
412         return 0;
413     }
414
415     /*
416      * Declare and create the example resource: LED
417      */
418     createLEDResource(gResourceUri, &LED, false, 0);
419
420     timeout.tv_sec  = 0;
421     timeout.tv_nsec = 100000000L;
422
423     // Break from loop with Ctrl-C
424     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
425     signal(SIGINT, handleSigInt);
426     while (!gQuitFlag)
427     {
428         if (OCProcess() != OC_STACK_OK)
429         {
430             OC_LOG(ERROR, TAG, "OCStack process error");
431             return 0;
432         }
433         nanosleep(&timeout, NULL);
434     }
435
436     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
437
438     if (OCStop() != OC_STACK_OK)
439     {
440         OC_LOG(ERROR, TAG, "OCStack process error");
441     }
442
443     return 0;
444 }
445
446 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
447 {
448     if (!uri)
449     {
450         OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
451         return -1;
452     }
453
454     ledResource->state = resourceState;
455     ledResource->power= resourcePower;
456     OCStackResult res = OCCreateResource(&(ledResource->handle),
457             "core.led",
458             OC_RSRVD_INTERFACE_DEFAULT,
459             uri,
460             OCEntityHandlerCb,
461             NULL,
462             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
463     OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
464
465     return 0;
466 }