Add PIN based OxM for security provisioning
[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, PCF("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, PCF("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
315     OCEntityHandlerResult ehResult = OC_EH_ERROR;
316     OCEntityHandlerResponse response = {};
317
318     // Validate pointer
319     if (!entityHandlerRequest)
320     {
321         OC_LOG (ERROR, TAG, "Invalid request pointer");
322         return OC_EH_ERROR;
323     }
324
325     OCRepPayload* payload = NULL;
326
327     if (flag & OC_REQUEST_FLAG)
328     {
329         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
330         if (entityHandlerRequest)
331         {
332             if (OC_REST_GET == entityHandlerRequest->method)
333             {
334                 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
335                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
336             }
337             else if (OC_REST_PUT == entityHandlerRequest->method)
338             {
339                 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
340                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
341             }
342             else if (OC_REST_POST == entityHandlerRequest->method)
343             {
344                 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
345                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
346             }
347             else
348             {
349                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
350                         entityHandlerRequest->method);
351                 ehResult = OC_EH_ERROR;
352             }
353
354             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
355             {
356                 // Format the response.  Note this requires some info about the request
357                 response.requestHandle = entityHandlerRequest->requestHandle;
358                 response.resourceHandle = entityHandlerRequest->resource;
359                 response.ehResult = ehResult;
360                 response.payload = (OCPayload*)(payload);
361                 response.numSendVendorSpecificHeaderOptions = 0;
362                 memset(response.sendVendorSpecificHeaderOptions, 0,
363                        sizeof(response.sendVendorSpecificHeaderOptions));
364                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
365                 // Indicate that response is NOT in a persistent buffer
366                 response.persistentBufferFlag = 0;
367
368                 // Send the response
369                 if (OCDoResponse(&response) != OC_STACK_OK)
370                 {
371                     OC_LOG(ERROR, TAG, "Error sending response");
372                     ehResult = OC_EH_ERROR;
373                 }
374             }
375         }
376     }
377
378     OCPayloadDestroy(response.payload);
379     return ehResult;
380 }
381
382 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
383 void handleSigInt(int signum)
384 {
385     if (signum == SIGINT)
386     {
387         gQuitFlag = 1;
388     }
389 }
390
391 FILE* server_fopen(const char *path, const char *mode)
392 {
393     (void)path;
394     return fopen(CRED_FILE, mode);
395 }
396
397 void GeneratePinCB(char* pin, size_t pinSize)
398 {
399     if(NULL == pin || pinSize <= 0)
400     {
401         OC_LOG(INFO, TAG, "Invalid PIN");
402         return;
403     }
404
405     OC_LOG(INFO, TAG, "============================");
406     OC_LOG_V(INFO, TAG, "    PIN CODE : %s", pin);
407     OC_LOG(INFO, TAG, "============================");
408 }
409
410 int main(int argc, char* argv[])
411 {
412     struct timespec timeout;
413
414     OC_LOG(DEBUG, TAG, "OCServer is starting...");
415
416     // Initialize Persistent Storage for SVR database
417     OCPersistentStorage ps = {};
418     ps.open = server_fopen;
419     ps.read = fread;
420     ps.write = fwrite;
421     ps.close = fclose;
422     ps.unlink = unlink;
423     OCRegisterPersistentStorageHandler(&ps);
424
425     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
426     {
427         OC_LOG(ERROR, TAG, "OCStack init error");
428         return 0;
429     }
430
431    /**
432      * If server supported random pin based ownership transfer,
433      * callback of print PIN should be registered before runing server.
434      */
435     SetGeneratePinCB(&GeneratePinCB);
436
437     /*
438      * Declare and create the example resource: LED
439      */
440     createLEDResource(gResourceUri, &LED, false, 0);
441
442     timeout.tv_sec  = 0;
443     timeout.tv_nsec = 100000000L;
444
445     // Break from loop with Ctrl-C
446     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
447     signal(SIGINT, handleSigInt);
448     while (!gQuitFlag)
449     {
450         if (OCProcess() != OC_STACK_OK)
451         {
452             OC_LOG(ERROR, TAG, "OCStack process error");
453             return 0;
454         }
455         nanosleep(&timeout, NULL);
456     }
457
458     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
459
460     if (OCStop() != OC_STACK_OK)
461     {
462         OC_LOG(ERROR, TAG, "OCStack process error");
463     }
464
465     return 0;
466 }
467
468 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
469 {
470     if (!uri)
471     {
472         OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
473         return -1;
474     }
475
476     ledResource->state = resourceState;
477     ledResource->power= resourcePower;
478     OCStackResult res = OCCreateResource(&(ledResource->handle),
479             "core.led",
480             OC_RSRVD_INTERFACE_DEFAULT,
481             uri,
482             OCEntityHandlerCb,
483             NULL,
484             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
485     OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
486
487     return 0;
488 }