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