c347a425bc7affcb0056b98fe156722bf7d0e150
[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
47
48 #define TAG "SAMPLE_MANUFACTURER_CERT"
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 manufacturer certificate
70 static char CRED_FILE[] = "oic_svr_db_server_mfg.dat";
71
72 /* Function that creates a new LED resource by calling the
73  * OCCreateResource() method.
74  */
75 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
76
77 /* This method converts the payload to JSON format */
78 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
79
80 /* Following methods process the PUT, GET, POST
81  * requests
82  */
83 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
84                                          OCRepPayload **payload);
85 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
86                                          OCRepPayload **payload);
87 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
88                                         OCEntityHandlerResponse *response,
89                                         OCRepPayload **payload);
90
91 /* Entity Handler callback functions */
92 OCEntityHandlerResult
93 OCEntityHandlerCb (OCEntityHandlerFlag flag,
94         OCEntityHandlerRequest *entityHandlerRequest,
95         void* callbackParam);
96
97 const char *getResult(OCStackResult result) {
98     switch (result) {
99     case OC_STACK_OK:
100         return "OC_STACK_OK";
101     case OC_STACK_RESOURCE_CREATED:
102         return "OC_STACK_RESOURCE_CREATED";
103     case OC_STACK_RESOURCE_DELETED:
104         return "OC_STACK_RESOURCE_DELETED";
105     case OC_STACK_INVALID_URI:
106         return "OC_STACK_INVALID_URI";
107     case OC_STACK_INVALID_QUERY:
108         return "OC_STACK_INVALID_QUERY";
109     case OC_STACK_INVALID_IP:
110         return "OC_STACK_INVALID_IP";
111     case OC_STACK_INVALID_PORT:
112         return "OC_STACK_INVALID_PORT";
113     case OC_STACK_INVALID_CALLBACK:
114         return "OC_STACK_INVALID_CALLBACK";
115     case OC_STACK_INVALID_METHOD:
116         return "OC_STACK_INVALID_METHOD";
117     case OC_STACK_NO_MEMORY:
118         return "OC_STACK_NO_MEMORY";
119     case OC_STACK_COMM_ERROR:
120         return "OC_STACK_COMM_ERROR";
121     case OC_STACK_INVALID_PARAM:
122         return "OC_STACK_INVALID_PARAM";
123     case OC_STACK_NOTIMPL:
124         return "OC_STACK_NOTIMPL";
125     case OC_STACK_NO_RESOURCE:
126         return "OC_STACK_NO_RESOURCE";
127     case OC_STACK_RESOURCE_ERROR:
128         return "OC_STACK_RESOURCE_ERROR";
129     case OC_STACK_SLOW_RESOURCE:
130         return "OC_STACK_SLOW_RESOURCE";
131     case OC_STACK_NO_OBSERVERS:
132         return "OC_STACK_NO_OBSERVERS";
133     #ifdef WITH_PRESENCE
134     case OC_STACK_PRESENCE_STOPPED:
135         return "OC_STACK_PRESENCE_STOPPED";
136     #endif
137     case OC_STACK_ERROR:
138         return "OC_STACK_ERROR";
139     default:
140         return "UNKNOWN";
141     }
142 }
143
144 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
145 {
146     OCRepPayload* payload = OCRepPayloadCreate();
147     if(!payload)
148     {
149         OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
150         return NULL;
151     }
152
153     OCRepPayloadSetUri(payload, uri);
154     OCRepPayloadSetPropBool(payload, "state", state);
155     OCRepPayloadSetPropInt(payload, "power", power);
156
157     return payload;
158 }
159
160 //This function takes the request as an input and returns the response
161 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
162 {
163     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
164     {
165         OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
166         return NULL;
167     }
168
169     OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
170
171     LEDResource *currLEDResource = &LED;
172
173     if (ehRequest->resource == gLedInstance[0].handle)
174     {
175         currLEDResource = &gLedInstance[0];
176         gResourceUri = (char *) "/a/led/0";
177     }
178     else if (ehRequest->resource == gLedInstance[1].handle)
179     {
180         currLEDResource = &gLedInstance[1];
181         gResourceUri = (char *) "/a/led/1";
182     }
183
184     if(OC_REST_PUT == ehRequest->method)
185     {
186         // Get pointer to query
187         int64_t pow;
188         if(OCRepPayloadGetPropInt(input, "power", &pow))
189         {
190             currLEDResource->power =pow;
191         }
192
193         bool state;
194         if(OCRepPayloadGetPropBool(input, "state", &state))
195         {
196             currLEDResource->state = state;
197         }
198     }
199
200     return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
201 }
202
203 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
204         OCRepPayload **payload)
205 {
206     OCEntityHandlerResult ehResult;
207
208     OCRepPayload *getResp = constructResponse(ehRequest);
209
210     if(getResp)
211     {
212         *payload = getResp;
213         ehResult = OC_EH_OK;
214     }
215     else
216     {
217         ehResult = OC_EH_ERROR;
218     }
219
220     return ehResult;
221 }
222
223 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
224         OCRepPayload **payload)
225 {
226     OCEntityHandlerResult ehResult;
227
228     OCRepPayload *putResp = constructResponse(ehRequest);
229
230     if(putResp)
231     {
232         *payload = putResp;
233         ehResult = OC_EH_OK;
234     }
235     else
236     {
237         ehResult = OC_EH_ERROR;
238     }
239
240     return ehResult;
241 }
242
243 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
244         OCEntityHandlerResponse *response, OCRepPayload **payload)
245 {
246     OCRepPayload *respPLPost_led = NULL;
247     OCEntityHandlerResult ehResult = OC_EH_OK;
248
249     /*
250      * The entity handler determines how to process a POST request.
251      * Per the REST paradigm, POST can also be used to update representation of existing
252      * resource or create a new resource.
253      * In the sample below, if the POST is for /a/led then a new instance of the LED
254      * resource is created with default representation (if representation is included in
255      * POST payload it can be used as initial values) as long as the instance is
256      * lesser than max new instance count. Once max instance count is reached, POST on
257      * /a/led updated the representation of /a/led (just like PUT)
258      */
259
260     if (ehRequest->resource == LED.handle)
261     {
262         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
263         {
264             // Create new LED instance
265             char newLedUri[15] = "/a/led/";
266             int newLedUriLength = strlen(newLedUri);
267             snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
268
269             respPLPost_led = OCRepPayloadCreate();
270             OCRepPayloadSetUri(respPLPost_led, gResourceUri);
271             OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
272
273             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
274             {
275                 OIC_LOG (INFO, TAG, "Created new LED instance");
276                 gLedInstance[gCurrLedInstance].state = 0;
277                 gLedInstance[gCurrLedInstance].power = 0;
278                 gCurrLedInstance++;
279                 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
280                 ehResult = OC_EH_RESOURCE_CREATED;
281             }
282         }
283         else
284         {
285             respPLPost_led = constructResponse(ehRequest);
286         }
287     }
288     else
289     {
290         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
291         {
292             if (ehRequest->resource == gLedInstance[i].handle)
293             {
294                 if (i == 0)
295                 {
296                     respPLPost_led = constructResponse(ehRequest);
297                     break;
298                 }
299                 else if (i == 1)
300                 {
301                     respPLPost_led = constructResponse(ehRequest);
302                 }
303             }
304         }
305     }
306
307     if (respPLPost_led != NULL)
308     {
309         *payload = respPLPost_led;
310         ehResult = OC_EH_OK;
311     }
312     else
313     {
314         OIC_LOG_V (INFO, TAG, "Payload was NULL");
315         ehResult = OC_EH_ERROR;
316     }
317
318     return ehResult;
319 }
320
321 OCEntityHandlerResult
322 OCEntityHandlerCb (OCEntityHandlerFlag flag,
323         OCEntityHandlerRequest *entityHandlerRequest,
324         void* callbackParam)
325 {
326     OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
327     (void)callbackParam;
328     OCEntityHandlerResult ehResult = OC_EH_ERROR;
329
330     OCEntityHandlerResponse response;
331     memset(&response, 0, sizeof(response));
332
333     // Validate pointer
334     if (!entityHandlerRequest)
335     {
336         OIC_LOG (ERROR, TAG, "Invalid request pointer");
337         return OC_EH_ERROR;
338     }
339
340     OCRepPayload* payload = NULL;
341
342     if (flag & OC_REQUEST_FLAG)
343     {
344         OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
345         if (entityHandlerRequest)
346         {
347             if (OC_REST_GET == entityHandlerRequest->method)
348             {
349                 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
350                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
351             }
352             else if (OC_REST_PUT == entityHandlerRequest->method)
353             {
354                 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
355                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
356             }
357             else if (OC_REST_POST == entityHandlerRequest->method)
358             {
359                 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
360                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
361             }
362             else
363             {
364                 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
365                         entityHandlerRequest->method);
366                 ehResult = OC_EH_ERROR;
367             }
368
369             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
370             {
371                 // Format the response.  Note this requires some info about the request
372                 response.requestHandle = entityHandlerRequest->requestHandle;
373                 response.resourceHandle = entityHandlerRequest->resource;
374                 response.ehResult = ehResult;
375                 response.payload = (OCPayload*)(payload);
376                 response.numSendVendorSpecificHeaderOptions = 0;
377                 memset(response.sendVendorSpecificHeaderOptions, 0,
378                        sizeof(response.sendVendorSpecificHeaderOptions));
379                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
380                 // Indicate that response is NOT in a persistent buffer
381                 response.persistentBufferFlag = 0;
382
383                 // Send the response
384                 if (OCDoResponse(&response) != OC_STACK_OK)
385                 {
386                     OIC_LOG(ERROR, TAG, "Error sending response");
387                     ehResult = OC_EH_ERROR;
388                 }
389             }
390         }
391     }
392
393     OCPayloadDestroy(response.payload);
394     return ehResult;
395 }
396
397 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
398 void handleSigInt(int signum)
399 {
400     if (signum == SIGINT)
401     {
402         gQuitFlag = 1;
403     }
404 }
405
406 FILE* server_fopen(const char *path, const char *mode)
407 {
408     (void)path;
409     return fopen(CRED_FILE, mode);
410 }
411
412 int main()
413 {
414     struct timespec timeout;
415
416     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
417
418     // Initialize Persistent Storage for SVR database
419     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
420
421     OCRegisterPersistentStorageHandler(&ps);
422
423     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
424     {
425         OIC_LOG(ERROR, TAG, "OCStack init error");
426         return 0;
427     }
428
429     /*
430      * Declare and create the example resource: LED
431      */
432     createLEDResource(gResourceUri, &LED, false, 0);
433
434     timeout.tv_sec  = 0;
435     timeout.tv_nsec = 100000000L;
436
437     // Break from loop with Ctrl-C
438     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
439     signal(SIGINT, handleSigInt);
440     while (!gQuitFlag)
441     {
442         if (OCProcess() != OC_STACK_OK)
443         {
444             OIC_LOG(ERROR, TAG, "OCStack process error");
445             return 0;
446         }
447         nanosleep(&timeout, NULL);
448     }
449
450     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
451
452     if (OCStop() != OC_STACK_OK)
453     {
454         OIC_LOG(ERROR, TAG, "OCStack process error");
455     }
456
457     return 0;
458 }
459
460 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
461 {
462     if (!uri)
463     {
464         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
465         return -1;
466     }
467
468     ledResource->state = resourceState;
469     ledResource->power= resourcePower;
470     OCStackResult res = OCCreateResource(&(ledResource->handle),
471             "core.led",
472             OC_RSRVD_INTERFACE_DEFAULT,
473             uri,
474             OCEntityHandlerCb,
475             NULL,
476             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
477     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
478
479     return 0;
480 }