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