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