replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / sample / sampleserver_justworks.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_PTHREAD_H
31 #include <pthread.h>
32 #endif
33 #include <signal.h>
34 #include "ocstack.h"
35 #include "ocpayload.h"
36 #include "pinoxmcommon.h"
37 #include "srmutility.h"
38
39 #ifdef HAVE_WINDOWS_H
40 #include <windows.h>
41 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
42 #ifdef ERROR
43 #undef ERROR
44 #endif //ERROR
45 #endif //HAVE_WINDOWS_H
46 #include "platform_features.h"
47 #include "logger.h"
48
49
50 #define TAG "SAMPLE_JUSTWORKS"
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 PSK credentials
72 //of other devices which the server trusts
73 static char CRED_FILE[] = "oic_svr_db_server_justworks.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, sizeof(response->resourceUri));
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 FILE* server_fopen(const char *path, const char *mode)
410 {
411     (void)path;
412     return fopen(CRED_FILE, mode);
413 }
414
415 static void OtmEventHandler(void *ctx, const char *addr, uint16_t port,
416         const char* ownerId, OCOtmEvent_t event)
417 {
418     (void)ctx;
419     printf("--------------------------------------\n");
420     printf("Get OTM event.\n");
421     printf("Address : %s\n", addr);
422     printf("Port : %d\n", port);
423     printf("Owner ID : %s\n", ownerId);
424
425     switch (event)
426     {
427         case OIC_OTM_READY:
428             printf("State : OIC_OTM_READY\n");
429             break;
430         case OIC_OTM_STARTED:
431             printf("State : OIC_OTM_STARTED\n");
432             break;
433         case OIC_OTM_DONE:
434             printf("State : OIC_OTM_DONE\n");
435             break;
436         case OIC_OTM_ERROR:
437             printf("State : OIC_OTM_ERROR\n");
438             break;
439         default:
440             printf("State : Unknown state.\n");
441             break;
442     }
443     printf("--------------------------------------\n");
444 }
445
446 int main()
447 {
448     struct timespec timeout;
449
450     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
451
452     //This function should be invoked before invoke OCInit
453     OCSetOtmEventHandler(NULL, OtmEventHandler);
454
455     // Initialize Persistent Storage for SVR database
456     OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink, NULL, NULL};
457
458     OCRegisterPersistentStorageHandler(&ps);
459
460     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
461     {
462         OIC_LOG(ERROR, TAG, "OCStack init error");
463         return 0;
464     }
465
466     /*
467      * Declare and create the example resource: LED
468      */
469     createLEDResource(gResourceUri, &LED, false, 0);
470
471     timeout.tv_sec  = 0;
472     timeout.tv_nsec = 100000000L;
473
474     // Break from loop with Ctrl-C
475     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
476     signal(SIGINT, handleSigInt);
477     while (!gQuitFlag)
478     {
479         if (OCProcess() != OC_STACK_OK)
480         {
481             OIC_LOG(ERROR, TAG, "OCStack process error");
482             return 0;
483         }
484         nanosleep(&timeout, NULL);
485     }
486
487     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
488
489     if (OCStop() != OC_STACK_OK)
490     {
491         OIC_LOG(ERROR, TAG, "OCStack process error");
492     }
493
494     return 0;
495 }
496
497 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
498 {
499     if (!uri)
500     {
501         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
502         return -1;
503     }
504
505     ledResource->state = resourceState;
506     ledResource->power= resourcePower;
507     OCStackResult res = OCCreateResource(&(ledResource->handle),
508             "core.led",
509             OC_RSRVD_INTERFACE_DEFAULT,
510             uri,
511             OCEntityHandlerCb,
512             NULL,
513             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
514     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
515
516     return 0;
517 }