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