Imported Upstream version 0.9.1
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / secure / ocserverbasicops.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH 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 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <signal.h>
26 #include <pthread.h>
27 #include "ocstack.h"
28 #include "logger.h"
29 #include "cJSON.h"
30 #include "ocserverbasicops.h"
31 #include "common.h"
32
33 int gQuitFlag = 0;
34
35 static LEDResource LED;
36 // This variable determines instance number of the LED resource.
37 // Used by POST method to create a new instance of LED resource.
38 static int gCurrLedInstance = 0;
39 #define SAMPLE_MAX_NUM_POST_INSTANCE  2
40 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
41
42 char *gResourceUri= (char *)"/a/led";
43
44 //File containing Server's Identity and the PSK credentials
45 //of other devices which the server trusts
46 //This can be generated using 'gen_sec_bin' application
47 static char CRED_FILE[] = "server_cred.bin";
48
49 //This function takes the request as an input and returns the response
50 //in JSON format.
51 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
52 {
53     cJSON *json = cJSON_CreateObject();
54     cJSON *format;
55     char *jsonResponse;
56     LEDResource *currLEDResource = &LED;
57
58     if (ehRequest->resource == gLedInstance[0].handle)
59     {
60         currLEDResource = &gLedInstance[0];
61         gResourceUri = (char *) "a/led/0";
62     }
63     else if (ehRequest->resource == gLedInstance[1].handle)
64     {
65         currLEDResource = &gLedInstance[1];
66         gResourceUri = (char *) "a/led/1";
67     }
68
69     if(OC_REST_PUT == ehRequest->method)
70     {
71         cJSON *putJson = cJSON_Parse(ehRequest->reqJSONPayload);
72         if(!putJson)
73         {
74             OC_LOG_V(ERROR, TAG, "Failed to parse JSON: %s", ehRequest->reqJSONPayload);
75             return NULL;
76         }
77
78         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
79                 "on") ? true:false);
80         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
81         cJSON_Delete(putJson);
82     }
83
84     cJSON_AddStringToObject(json,"href",gResourceUri);
85     cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
86     cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
87     cJSON_AddNumberToObject(format, "power", currLEDResource->power);
88
89     jsonResponse = cJSON_Print(json);
90     cJSON_Delete(json);
91     return jsonResponse;
92 }
93
94 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
95                         char *payload, size_t maxPayloadSize)
96 {
97     OCEntityHandlerResult ehResult;
98
99     char *getResp = constructJsonResponse(ehRequest);
100     if(getResp)
101     {
102         if (maxPayloadSize > strlen (getResp))
103         {
104             strcpy(payload, getResp);
105             ehResult = OC_EH_OK;
106         }
107         else
108         {
109             OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
110                     maxPayloadSize);
111             ehResult = OC_EH_ERROR;
112         }
113
114         free(getResp);
115     }
116     else
117     {
118         ehResult = OC_EH_ERROR;
119     }
120
121     return ehResult;
122 }
123
124 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
125                         char *payload, size_t maxPayloadSize)
126 {
127     OCEntityHandlerResult ehResult;
128
129     char *putResp = constructJsonResponse(ehRequest);
130
131     if(putResp)
132     {
133         if (maxPayloadSize > strlen (putResp))
134         {
135             strcpy(payload, putResp);
136             ehResult = OC_EH_OK;
137         }
138         else
139         {
140             OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
141                     maxPayloadSize);
142             ehResult = OC_EH_ERROR;
143         }
144
145         free(putResp);
146     }
147     else
148     {
149         ehResult = OC_EH_ERROR;
150     }
151
152     return ehResult;
153 }
154
155 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
156                         char *payload, size_t maxPayloadSize)
157 {
158     char *respPLPost_led = NULL;
159     cJSON *json;
160     cJSON *format;
161     OCEntityHandlerResult ehResult;
162
163     /*
164      * The entity handler determines how to process a POST request.
165      * Per the REST paradigm, POST can also be used to update representation of existing
166      * resource or create a new resource.
167      * In the sample below, if the POST is for /a/led then a new instance of the LED
168      * resource is created with default representation (if representation is included in
169      * POST payload it can be used as initial values) as long as the instance is
170      * lesser than max new instance count. Once max instance count is reached, POST on
171      * /a/led updated the representation of /a/led (just like PUT)
172      */
173
174     if (ehRequest->resource == LED.handle)
175     {
176         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
177         {
178             // Create new LED instance
179             char newLedUri[15] = "/a/led/";
180             int newLedUriLength = strlen(newLedUri);
181             snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
182
183             json = cJSON_CreateObject();
184
185             cJSON_AddStringToObject(json,"href",gResourceUri);
186             cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
187             cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
188
189             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
190             {
191                 OC_LOG (INFO, TAG, "Created new LED instance");
192                 gLedInstance[gCurrLedInstance].state = 0;
193                 gLedInstance[gCurrLedInstance].power = 0;
194                 gCurrLedInstance++;
195                 respPLPost_led = cJSON_Print(json);
196             }
197
198             cJSON_Delete(json);
199         }
200         else
201         {
202             respPLPost_led = constructJsonResponse(ehRequest);
203         }
204     }
205     else
206     {
207         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
208         {
209             if (ehRequest->resource == gLedInstance[i].handle)
210             {
211                 if (i == 0)
212                 {
213                     respPLPost_led = constructJsonResponse(ehRequest);
214                     break;
215                 }
216                 else if (i == 1)
217                 {
218                     respPLPost_led = constructJsonResponse(ehRequest);
219                 }
220             }
221         }
222     }
223
224     if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led)))
225     {
226         strcpy(payload, respPLPost_led);
227         ehResult = OC_EH_OK;
228     }
229     else
230     {
231         OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
232                 maxPayloadSize);
233         ehResult = OC_EH_ERROR;
234     }
235
236     free(respPLPost_led);
237
238     return ehResult;
239 }
240
241 OCEntityHandlerResult
242 OCEntityHandlerCb (OCEntityHandlerFlag flag,
243         OCEntityHandlerRequest *entityHandlerRequest)
244 {
245     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
246
247     OCEntityHandlerResult ehResult = OC_EH_ERROR;
248     OCEntityHandlerResponse response;
249     char payload[MAX_RESPONSE_LENGTH] = {0};
250
251     if (flag & OC_REQUEST_FLAG)
252     {
253         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
254         if (entityHandlerRequest)
255         {
256             if (OC_REST_GET == entityHandlerRequest->method)
257             {
258                 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
259                 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload));
260             }
261             else if (OC_REST_PUT == entityHandlerRequest->method)
262             {
263                 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
264                 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload));
265             }
266             else if (OC_REST_POST == entityHandlerRequest->method)
267             {
268                 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
269                 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload));
270             }
271             else
272             {
273                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
274                         entityHandlerRequest->method);
275                 ehResult = OC_EH_ERROR;
276             }
277
278             if (ehResult == OC_EH_OK)
279             {
280                 // Format the response.  Note this requires some info about the request
281                 response.requestHandle = entityHandlerRequest->requestHandle;
282                 response.resourceHandle = entityHandlerRequest->resource;
283                 response.ehResult = ehResult;
284                 response.payload = payload;
285                 response.payloadSize = strlen(payload);
286                 response.numSendVendorSpecificHeaderOptions = 0;
287                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
288                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
289                 // Indicate that response is NOT in a persistent buffer
290                 response.persistentBufferFlag = 0;
291
292                 // Send the response
293                 if (OCDoResponse(&response) != OC_STACK_OK)
294                 {
295                     OC_LOG(ERROR, TAG, "Error sending response");
296                     ehResult = OC_EH_ERROR;
297                 }
298             }
299         }
300     }
301     return ehResult;
302 }
303
304 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
305 void handleSigInt(int signum)
306 {
307     if (signum == SIGINT)
308     {
309         gQuitFlag = 1;
310     }
311 }
312
313 int main(int argc, char* argv[])
314 {
315     struct timespec timeout;
316
317     OC_LOG(DEBUG, TAG, "OCServer is starting...");
318
319     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
320     {
321         OC_LOG(ERROR, TAG, "OCStack init error");
322         return 0;
323     }
324
325     /*
326      * Read DTLS PSK credentials from persistent storage and
327      * set in the OC stack.
328      */
329     if (SetCredentials(CRED_FILE) != OC_STACK_OK)
330     {
331         OC_LOG(ERROR, TAG, "SetCredentials failed");
332         return 0;
333     }
334     /*
335      * Declare and create the example resource: LED
336      */
337     createLEDResource(gResourceUri, &LED, false, 0);
338
339     timeout.tv_sec  = 0;
340     timeout.tv_nsec = 100000000L;
341
342     // Break from loop with Ctrl-C
343     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
344     signal(SIGINT, handleSigInt);
345     while (!gQuitFlag)
346     {
347         if (OCProcess() != OC_STACK_OK)
348         {
349             OC_LOG(ERROR, TAG, "OCStack process error");
350             return 0;
351         }
352         nanosleep(&timeout, NULL);
353     }
354
355     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
356
357     if (OCStop() != OC_STACK_OK)
358     {
359         OC_LOG(ERROR, TAG, "OCStack process error");
360     }
361
362     return 0;
363 }
364
365 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
366 {
367     if (!uri)
368     {
369         OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
370         return -1;
371     }
372
373     ledResource->state = resourceState;
374     ledResource->power= resourcePower;
375     OCStackResult res = OCCreateResource(&(ledResource->handle),
376             "core.led",
377             OC_RSRVD_INTERFACE_DEFAULT,
378             uri,
379             OCEntityHandlerCb,
380             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
381     OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
382
383     return 0;
384 }
385