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