Asynchronous User Confirm
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / sample / sampleserver_mfg.cpp
1 /******************************************************************
2 *
3 * Copyright 2016 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
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 #include "pkix_interface.h"
47 #include "hw_emul/hw_interface.h"
48 #include "oxmverifycommon.h"
49 #include "casecurityinterface.h"
50
51 #define TAG "SAMPLE_MANUFACTURER_CERT"
52
53 int gQuitFlag = 0;
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 manufacturer certificate
73 static char CRED_FILE[] = "oic_svr_db_server_mfg.dat";
74
75 /* Function that creates a new LED resource by calling the
76  * OCCreateResource() method.
77  */
78 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
79
80 /* This method converts the payload to JSON format */
81 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
82
83 /* Following methods process the PUT, GET, POST
84  * requests
85  */
86 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
87                                          OCRepPayload **payload);
88 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
89                                          OCRepPayload **payload);
90 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
91                                         OCEntityHandlerResponse *response,
92                                         OCRepPayload **payload);
93
94 /* Entity Handler callback functions */
95 OCEntityHandlerResult
96 OCEntityHandlerCb (OCEntityHandlerFlag flag,
97         OCEntityHandlerRequest *entityHandlerRequest,
98         void* callbackParam);
99
100 const char *getResult(OCStackResult result) {
101     switch (result) {
102     case OC_STACK_OK:
103         return "OC_STACK_OK";
104     case OC_STACK_RESOURCE_CREATED:
105         return "OC_STACK_RESOURCE_CREATED";
106     case OC_STACK_RESOURCE_DELETED:
107         return "OC_STACK_RESOURCE_DELETED";
108     case OC_STACK_INVALID_URI:
109         return "OC_STACK_INVALID_URI";
110     case OC_STACK_INVALID_QUERY:
111         return "OC_STACK_INVALID_QUERY";
112     case OC_STACK_INVALID_IP:
113         return "OC_STACK_INVALID_IP";
114     case OC_STACK_INVALID_PORT:
115         return "OC_STACK_INVALID_PORT";
116     case OC_STACK_INVALID_CALLBACK:
117         return "OC_STACK_INVALID_CALLBACK";
118     case OC_STACK_INVALID_METHOD:
119         return "OC_STACK_INVALID_METHOD";
120     case OC_STACK_NO_MEMORY:
121         return "OC_STACK_NO_MEMORY";
122     case OC_STACK_COMM_ERROR:
123         return "OC_STACK_COMM_ERROR";
124     case OC_STACK_INVALID_PARAM:
125         return "OC_STACK_INVALID_PARAM";
126     case OC_STACK_NOTIMPL:
127         return "OC_STACK_NOTIMPL";
128     case OC_STACK_NO_RESOURCE:
129         return "OC_STACK_NO_RESOURCE";
130     case OC_STACK_RESOURCE_ERROR:
131         return "OC_STACK_RESOURCE_ERROR";
132     case OC_STACK_SLOW_RESOURCE:
133         return "OC_STACK_SLOW_RESOURCE";
134     case OC_STACK_NO_OBSERVERS:
135         return "OC_STACK_NO_OBSERVERS";
136     #ifdef WITH_PRESENCE
137     case OC_STACK_PRESENCE_STOPPED:
138         return "OC_STACK_PRESENCE_STOPPED";
139     #endif
140     case OC_STACK_ERROR:
141         return "OC_STACK_ERROR";
142     default:
143         return "UNKNOWN";
144     }
145 }
146
147 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
148 {
149     OCRepPayload* payload = OCRepPayloadCreate();
150     if(!payload)
151     {
152         OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
153         return NULL;
154     }
155
156     OCRepPayloadSetUri(payload, uri);
157     OCRepPayloadSetPropBool(payload, "state", state);
158     OCRepPayloadSetPropInt(payload, "power", power);
159
160     return payload;
161 }
162
163 //This function takes the request as an input and returns the response
164 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
165 {
166     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
167     {
168         OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
169         return NULL;
170     }
171
172     OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
173
174     LEDResource *currLEDResource = &LED;
175
176     if (ehRequest->resource == gLedInstance[0].handle)
177     {
178         currLEDResource = &gLedInstance[0];
179         gResourceUri = (char *) "/a/led/0";
180     }
181     else if (ehRequest->resource == gLedInstance[1].handle)
182     {
183         currLEDResource = &gLedInstance[1];
184         gResourceUri = (char *) "/a/led/1";
185     }
186
187     if(OC_REST_PUT == ehRequest->method)
188     {
189         // Get pointer to query
190         int64_t pow;
191         if(OCRepPayloadGetPropInt(input, "power", &pow))
192         {
193             currLEDResource->power =pow;
194         }
195
196         bool state;
197         if(OCRepPayloadGetPropBool(input, "state", &state))
198         {
199             currLEDResource->state = state;
200         }
201     }
202
203     return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
204 }
205
206 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
207         OCRepPayload **payload)
208 {
209     OCEntityHandlerResult ehResult;
210
211     OCRepPayload *getResp = constructResponse(ehRequest);
212
213     if(getResp)
214     {
215         *payload = getResp;
216         ehResult = OC_EH_OK;
217     }
218     else
219     {
220         ehResult = OC_EH_ERROR;
221     }
222
223     return ehResult;
224 }
225
226 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
227         OCRepPayload **payload)
228 {
229     OCEntityHandlerResult ehResult;
230
231     OCRepPayload *putResp = constructResponse(ehRequest);
232
233     if(putResp)
234     {
235         *payload = putResp;
236         ehResult = OC_EH_OK;
237     }
238     else
239     {
240         ehResult = OC_EH_ERROR;
241     }
242
243     return ehResult;
244 }
245
246 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
247         OCEntityHandlerResponse *response, OCRepPayload **payload)
248 {
249     OCRepPayload *respPLPost_led = NULL;
250     OCEntityHandlerResult ehResult = OC_EH_OK;
251
252     /*
253      * The entity handler determines how to process a POST request.
254      * Per the REST paradigm, POST can also be used to update representation of existing
255      * resource or create a new resource.
256      * In the sample below, if the POST is for /a/led then a new instance of the LED
257      * resource is created with default representation (if representation is included in
258      * POST payload it can be used as initial values) as long as the instance is
259      * lesser than max new instance count. Once max instance count is reached, POST on
260      * /a/led updated the representation of /a/led (just like PUT)
261      */
262
263     if (ehRequest->resource == LED.handle)
264     {
265         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
266         {
267             // Create new LED instance
268             char newLedUri[15] = "/a/led/";
269             int newLedUriLength = strlen(newLedUri);
270             snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
271
272             respPLPost_led = OCRepPayloadCreate();
273             OCRepPayloadSetUri(respPLPost_led, gResourceUri);
274             OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
275
276             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
277             {
278                 OIC_LOG (INFO, TAG, "Created new LED instance");
279                 gLedInstance[gCurrLedInstance].state = 0;
280                 gLedInstance[gCurrLedInstance].power = 0;
281                 gCurrLedInstance++;
282                 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
283                 ehResult = OC_EH_RESOURCE_CREATED;
284             }
285         }
286         else
287         {
288             respPLPost_led = constructResponse(ehRequest);
289         }
290     }
291     else
292     {
293         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
294         {
295             if (ehRequest->resource == gLedInstance[i].handle)
296             {
297                 if (i == 0)
298                 {
299                     respPLPost_led = constructResponse(ehRequest);
300                     break;
301                 }
302                 else if (i == 1)
303                 {
304                     respPLPost_led = constructResponse(ehRequest);
305                 }
306             }
307         }
308     }
309
310     if (respPLPost_led != NULL)
311     {
312         *payload = respPLPost_led;
313         ehResult = OC_EH_OK;
314     }
315     else
316     {
317         OIC_LOG_V (INFO, TAG, "Payload was NULL");
318         ehResult = OC_EH_ERROR;
319     }
320
321     return ehResult;
322 }
323
324 OCEntityHandlerResult
325 OCEntityHandlerCb (OCEntityHandlerFlag flag,
326         OCEntityHandlerRequest *entityHandlerRequest,
327         void* callbackParam)
328 {
329     OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
330     (void)callbackParam;
331     OCEntityHandlerResult ehResult = OC_EH_ERROR;
332
333     OCEntityHandlerResponse response;
334     memset(&response, 0, sizeof(response));
335
336     // Validate pointer
337     if (!entityHandlerRequest)
338     {
339         OIC_LOG (ERROR, TAG, "Invalid request pointer");
340         return OC_EH_ERROR;
341     }
342
343     OCRepPayload* payload = NULL;
344
345     if (flag & OC_REQUEST_FLAG)
346     {
347         OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
348         if (entityHandlerRequest)
349         {
350             if (OC_REST_GET == entityHandlerRequest->method)
351             {
352                 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
353                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
354             }
355             else if (OC_REST_PUT == entityHandlerRequest->method)
356             {
357                 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
358                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
359             }
360             else if (OC_REST_POST == entityHandlerRequest->method)
361             {
362                 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
363                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
364             }
365             else
366             {
367                 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
368                         entityHandlerRequest->method);
369                 ehResult = OC_EH_ERROR;
370             }
371
372             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
373             {
374                 // Format the response.  Note this requires some info about the request
375                 response.requestHandle = entityHandlerRequest->requestHandle;
376                 response.resourceHandle = entityHandlerRequest->resource;
377                 response.ehResult = ehResult;
378                 response.payload = (OCPayload*)(payload);
379                 response.numSendVendorSpecificHeaderOptions = 0;
380                 memset(response.sendVendorSpecificHeaderOptions, 0,
381                        sizeof(response.sendVendorSpecificHeaderOptions));
382                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
383                 // Indicate that response is NOT in a persistent buffer
384                 response.persistentBufferFlag = 0;
385
386                 // Send the response
387                 if (OCDoResponse(&response) != OC_STACK_OK)
388                 {
389                     OIC_LOG(ERROR, TAG, "Error sending response");
390                     ehResult = OC_EH_ERROR;
391                 }
392             }
393         }
394     }
395
396     OCPayloadDestroy(response.payload);
397     return ehResult;
398 }
399
400 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
401 void handleSigInt(int signum)
402 {
403     if (signum == SIGINT)
404     {
405         gQuitFlag = 1;
406     }
407 }
408
409 OCStackResult confirmCB_thread()
410 {
411     for (;;)
412     {
413         int userConfirm;
414
415         printf("   > Press 1 for confirmation\n");
416         printf("   > Press 0 otherwise\n");
417
418         for (int ret=0; 1!=ret; )
419         {
420             ret = scanf("%d", &userConfirm);
421             for (; 0x20<=getchar(); );  // for removing overflow garbage
422                                         // '0x20<=code' is character region
423         }
424         if (1 == userConfirm)
425         {
426             SendUserConfirm(true);
427             break;
428         }
429         else if (0 == userConfirm)
430         {
431             SendUserConfirm(false);
432             break;
433         }
434         printf("   Entered Wrong Number. Please Enter Again\n");
435     }
436     return OC_STACK_OK;
437 }
438
439 OCStackResult confirmCB(void * ctx)
440 {
441     OC_UNUSED(ctx);
442     pthread_t threadId;
443     pthread_create (&threadId, NULL, &confirmCB_thread, NULL);
444     return OC_STACK_OK;
445 }
446
447 void confirmNoCertCB(CACertificateVerificationStatus_t status)
448 {
449     if (CA_CERTIFICATE_VERIFY_SUCCESS_MUTUAL == status)
450     {
451         printf("   > Peer certificate verification successful");
452     }
453     else if (CA_CERTIFICATE_VERIFY_NO_CERT == status)
454     {
455         printf("   > Peer has not provided certificate\n");
456     }
457     else if (CA_CERTIFICATE_VERIFY_FAILED == status)
458     {
459         printf("   > Peer certificate verification failed\n");
460     }
461     return;
462 }
463
464 void informOxmSelCB(OicSecOxm_t oxmSel)\r
465 {\r
466     printf("   > OXM selected: 0x%x\n", oxmSel);\r
467 }\r
468 \r
469 FILE* server_fopen(const char *path, const char *mode)
470 {
471     (void)path;
472     return fopen(CRED_FILE, mode);
473 }
474
475 int main(int argc, char **argv)
476 {
477     struct timespec timeout;
478
479     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
480
481     int opt;
482     char cert_file[4096] = {0,};
483     char key_file[4096] = {0,};
484     char key_pass[32] = {0,};
485
486     // Set options
487     while ((opt = getopt(argc, argv, "c:k:p:")) != -1)
488     {
489         switch (opt)
490         {
491             case 'c':
492                 strncpy(cert_file, optarg, sizeof(cert_file) - 1);
493                 printf("Set own certificate file : %s\n", cert_file);
494                 break;
495             case 'k':
496                 strncpy(key_file, optarg, sizeof(key_file) - 1);
497                 printf("Set private key file : %s\n", key_file);
498                 break;
499             case 'p':
500                 strncpy(key_pass, optarg, sizeof(key_pass) - 1);
501                 printf("Set private key password : %s\n", key_pass);
502                 break;
503             default:
504                 printf("Not set any options\n");
505         }
506     }
507
508     // Initialize Persistent Storage for SVR database
509     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink, NULL, NULL};
510
511     SetAsyncUserConfirmCB(NULL, confirmCB);
512     SetInformOxmSelCB(informOxmSelCB);
513     CAsetCertificateVerificationCallback(confirmNoCertCB);
514
515     OCRegisterPersistentStorageHandler(&ps);
516
517     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
518     {
519         OIC_LOG(ERROR, TAG, "OCStack init error");
520         return 0;
521     }
522
523     // Register HW secure storage callback
524     if (0 < strlen(cert_file) && 0 < strlen(key_file))
525     {
526         if (0 == SSemulSetCertkeyFilepath(cert_file, key_file, key_pass))
527         {
528             if (0 != SetHwPkixCallbacks(HWGetKeyContext,
529                                                           HWFreeKeyContext,
530                                                           HWGetOwnCertificateChain,
531                                                           HWSetupPkContext))
532             {
533                 printf("Fail to regist HW Pkix Callbacks");
534             }
535         }
536         else
537         {
538             printf("Fail to set cert/key file path");
539         }
540     }
541     else
542     {
543         printf("\n    [ Not set any mfg cert options ]\n");
544         printf("    Possible options: %s [-c certificate file path]"
545                 " [-k key file path] [-p key password]\n\n", argv[0]);
546     }
547
548     /*
549      * Declare and create the example resource: LED
550      */
551     createLEDResource(gResourceUri, &LED, false, 0);
552
553     timeout.tv_sec  = 0;
554     timeout.tv_nsec = 100000000L;
555
556     // Break from loop with Ctrl-C
557     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
558     signal(SIGINT, handleSigInt);
559     while (!gQuitFlag)
560     {
561         if (OCProcess() != OC_STACK_OK)
562         {
563             OIC_LOG(ERROR, TAG, "OCStack process error");
564             return 0;
565         }
566         nanosleep(&timeout, NULL);
567     }
568
569     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
570
571     if (OCStop() != OC_STACK_OK)
572     {
573         OIC_LOG(ERROR, TAG, "OCStack process error");
574     }
575
576     return 0;
577 }
578
579 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
580 {
581     if (!uri)
582     {
583         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
584         return -1;
585     }
586
587     ledResource->state = resourceState;
588     ledResource->power= resourcePower;
589     OCStackResult res = OCCreateResource(&(ledResource->handle),
590             "core.led",
591             OC_RSRVD_INTERFACE_DEFAULT,
592             uri,
593             OCEntityHandlerCb,
594             NULL,
595             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
596     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
597
598     return 0;
599 }