Merge tizen_5.0 codes into tizen_4.0
[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(void * ctx)
410 {
411     OC_UNUSED(ctx);
412     for (;;)
413     {
414         int userConfirm;
415
416         printf("   > Press 1 for confirmation\n");
417         printf("   > Press 0 otherwise\n");
418
419         for (int ret=0; 1!=ret; )
420         {
421             ret = scanf("%d", &userConfirm);
422             for (; 0x20<=getchar(); );  // for removing overflow garbage
423                                         // '0x20<=code' is character region
424         }
425         if (1 == userConfirm)
426         {
427             break;
428         }
429         else if (0 == userConfirm)
430         {
431             return OC_STACK_USER_DENIED_REQ;
432         }
433         printf("   Entered Wrong Number. Please Enter Again\n");
434     }
435     return OC_STACK_OK;
436 }
437
438 void confirmNoCertCB(CACertificateVerificationStatus_t status)
439 {
440     if (CA_CERTIFICATE_VERIFY_SUCCESS_MUTUAL == status)
441     {
442         printf("   > Peer certificate verification successful");
443     }
444     else if (CA_CERTIFICATE_VERIFY_NO_CERT == status)
445     {
446         printf("   > Peer has not provided certificate\n");
447     }
448     else if (CA_CERTIFICATE_VERIFY_FAILED == status)
449     {
450         printf("   > Peer certificate verification failed\n");
451     }
452     return;
453 }
454
455 void informOxmSelCB(OicSecOxm_t oxmSel)\r
456 {\r
457     printf("   > OXM selected: 0x%x\n", oxmSel);\r
458 }\r
459 \r
460 FILE* server_fopen(const char *path, const char *mode)
461 {
462     (void)path;
463     return fopen(CRED_FILE, mode);
464 }
465
466 int main(int argc, char **argv)
467 {
468     struct timespec timeout;
469
470     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
471
472     int opt;
473     char cert_file[4096] = {0,};
474     char key_file[4096] = {0,};
475     char key_pass[32] = {0,};
476
477     // Set options
478     while ((opt = getopt(argc, argv, "c:k:p:")) != -1)
479     {
480         switch (opt)
481         {
482             case 'c':
483                 strncpy(cert_file, optarg, sizeof(cert_file) - 1);
484                 printf("Set own certificate file : %s\n", cert_file);
485                 break;
486             case 'k':
487                 strncpy(key_file, optarg, sizeof(key_file) - 1);
488                 printf("Set private key file : %s\n", key_file);
489                 break;
490             case 'p':
491                 strncpy(key_pass, optarg, sizeof(key_pass) - 1);
492                 printf("Set private key password : %s\n", key_pass);
493                 break;
494             default:
495                 printf("Not set any options\n");
496         }
497     }
498
499     // Initialize Persistent Storage for SVR database
500     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink, NULL, NULL};
501
502     SetUserConfirmCB(NULL, confirmCB);
503     SetInformOxmSelCB(informOxmSelCB);
504     CAsetCertificateVerificationCallback(confirmNoCertCB);
505
506     OCRegisterPersistentStorageHandler(&ps);
507
508     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
509     {
510         OIC_LOG(ERROR, TAG, "OCStack init error");
511         return 0;
512     }
513
514     // Register HW secure storage callback
515     if (0 < strlen(cert_file) && 0 < strlen(key_file))
516     {
517         if (0 == SSemulSetCertkeyFilepath(cert_file, key_file, key_pass))
518         {
519             if (0 != SetHwPkixCallbacks(HWGetKeyContext,
520                                                           HWFreeKeyContext,
521                                                           HWGetOwnCertificateChain,
522                                                           HWSetupPkContext))
523             {
524                 printf("Fail to regist HW Pkix Callbacks");
525             }
526         }
527         else
528         {
529             printf("Fail to set cert/key file path");
530         }
531     }
532     else
533     {
534         printf("\n    [ Not set any mfg cert options ]\n");
535         printf("    Possible options: %s [-c certificate file path]"
536                 " [-k key file path] [-p key password]\n\n", argv[0]);
537     }
538
539     /*
540      * Declare and create the example resource: LED
541      */
542     createLEDResource(gResourceUri, &LED, false, 0);
543
544     timeout.tv_sec  = 0;
545     timeout.tv_nsec = 100000000L;
546
547     // Break from loop with Ctrl-C
548     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
549     signal(SIGINT, handleSigInt);
550     while (!gQuitFlag)
551     {
552         if (OCProcess() != OC_STACK_OK)
553         {
554             OIC_LOG(ERROR, TAG, "OCStack process error");
555             return 0;
556         }
557         nanosleep(&timeout, NULL);
558     }
559
560     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
561
562     if (OCStop() != OC_STACK_OK)
563     {
564         OIC_LOG(ERROR, TAG, "OCStack process error");
565     }
566
567     return 0;
568 }
569
570 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
571 {
572     if (!uri)
573     {
574         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
575         return -1;
576     }
577
578     ledResource->state = resourceState;
579     ledResource->power= resourcePower;
580     OCStackResult res = OCCreateResource(&(ledResource->handle),
581             "core.led",
582             OC_RSRVD_INTERFACE_DEFAULT,
583             uri,
584             OCEntityHandlerCb,
585             NULL,
586             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
587     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
588
589     return 0;
590 }