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