QR Code Random Pin CB
[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_TIME_H
31 #include <time.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
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_randompin.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 #ifdef MULTIPLE_OWNER
146
147 #include <assert.h>
148 #include <thread>
149 #include <chrono>
150
151 static bool volatile g_LoopFlag;
152 static std::thread* oc_process_thread;
153
154 static void oc_process_loop()
155 {
156     while(g_LoopFlag)
157     {
158         if (OCProcess() != OC_STACK_OK)
159         {
160             OIC_LOG(ERROR, TAG, "OCStack process error");
161             g_LoopFlag = false;
162             break;
163         }
164         std::this_thread::sleep_for(std::chrono::milliseconds(100));
165     }
166 }
167
168 static void StartOCProcessThread()
169 {
170     g_LoopFlag = true;
171     oc_process_thread = new std::thread(oc_process_loop);
172 }
173
174 static void StopOCProcessThread()
175 {
176     assert(oc_process_thread->joinable() == true);
177     g_LoopFlag = false;
178     oc_process_thread->join();
179 }
180 #endif //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, sizeof(response->resourceUri));
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 void ClosePinDisplayCB(void)
464 {
465     OIC_LOG(INFO, TAG, "============================");
466     OIC_LOG(INFO, TAG, "    PIN DISPLAY CLOSED.");
467     OIC_LOG(INFO, TAG, "============================");
468 }
469
470 int main()
471 {
472     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
473
474     // Initialize Persistent Storage for SVR database
475     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink, NULL, NULL};
476     OCRegisterPersistentStorageHandler(&ps);
477
478     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
479     {
480         OIC_LOG(ERROR, TAG, "OCStack init error");
481         return 0;
482     }
483
484     /**
485      * If server supported random pin based ownership transfer,
486      * callback of print PIN should be registered before runing server.
487      */
488     SetGeneratePinCB(GeneratePinCB);
489
490     /**
491      * Set preconfigured PIN code
492      */
493     //SetPin("78563412", 8);
494
495     /**
496      * If ther server supports random pin based OTM,
497      * the callback to close PIN display can be registered.
498      * This callback will be invoked when random PIN based OTM is done.
499      */
500     SetClosePinDisplayCB(ClosePinDisplayCB);
501
502     /**
503      * Random PIN generation policy can be changed through SetRandomPinPolicy() API.
504      * first param : byte length of random PIN ( 4 <= first param <= 32)
505      * second param : PIN type (This is bitmask)
506      */
507     if(OC_STACK_OK != SetRandomPinPolicy(8, NUM_PIN))
508     {
509         OIC_LOG(ERROR, TAG, "Failed to setting PIN policy");
510         return 0;
511     }
512
513     /*
514      * Declare and create the example resource: LED
515      */
516     createLEDResource(gResourceUri, &LED, false, 0);
517
518     // Break from loop with Ctrl-C
519     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
520     signal(SIGINT, handleSigInt);
521
522 #ifdef MULTIPLE_OWNER
523     StartOCProcessThread();
524
525     while(!gQuitFlag)
526     {
527         printf("Press 'G' to generate random PIN...\n");
528         printf("Press 'E' to exit...\n");
529         char in = getchar();
530         if('G' == in || 'g' == in)
531         {
532             char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
533             GeneratePin(ranPin, sizeof(ranPin));
534         }
535         if('E' == in || 'e' == in)
536         {
537             break;
538         }
539     }
540
541     StopOCProcessThread();
542 #else
543     struct timespec timeout;
544     timeout.tv_sec  = 0;
545     timeout.tv_nsec = 100000000L;
546
547     while (!gQuitFlag)
548     {
549         if (OCProcess() != OC_STACK_OK)
550         {
551             OIC_LOG(ERROR, TAG, "OCStack process error");
552             return 0;
553         }
554         nanosleep(&timeout, NULL);
555     }
556 #endif //MULTIPLE_OWNER
557
558     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
559
560     if (OCStop() != OC_STACK_OK)
561     {
562         OIC_LOG(ERROR, TAG, "OCStack process error");
563     }
564
565     return 0;
566 }
567
568 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
569 {
570     if (!uri)
571     {
572         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
573         return -1;
574     }
575
576     ledResource->state = resourceState;
577     ledResource->power= resourcePower;
578     OCStackResult res = OCCreateResource(&(ledResource->handle),
579             "core.led",
580             OC_RSRVD_INTERFACE_DEFAULT,
581             uri,
582             OCEntityHandlerCb,
583             NULL,
584             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
585     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
586
587     return 0;
588 }