61db06ac9a8169cec2d6cd28473cbb0dcae6537b
[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 "iotivity_config.h"
22 #include <stdio.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #ifdef HAVE_WINDOWS_H
29 #include <windows.h>
30 #endif
31 #include <signal.h>
32 #ifdef HAVE_PTHREAD_H
33 #include <pthread.h>
34 #endif
35 #include "ocstack.h"
36 #include "logger.h"
37 #include "ocpayload.h"
38 #include "ocserverbasicops.h"
39 #include "common.h"
40
41
42 int gQuitFlag = 0;
43
44 static LEDResource LED;
45 // This variable determines instance number of the LED resource.
46 // Used by POST method to create a new instance of LED resource.
47 static int gCurrLedInstance = 0;
48 #define SAMPLE_MAX_NUM_POST_INSTANCE  2
49 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
50
51 char *gResourceUri= (char *)"/a/led";
52
53 //Secure Virtual Resource database for Iotivity Server
54 //It contains Server's Identity and the PSK credentials
55 //of other devices which the server trusts
56 static char CRED_FILE[] = "oic_svr_db_server.dat";
57
58 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
59 {
60     OCRepPayload* payload = OCRepPayloadCreate();
61     if(!payload)
62     {
63         OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
64         return nullptr;
65     }
66
67     OCRepPayloadSetUri(payload, uri);
68     OCRepPayloadSetPropBool(payload, "state", state);
69     OCRepPayloadSetPropInt(payload, "power", power);
70
71     return payload;
72 }
73
74 //This function takes the request as an input and returns the response
75 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
76 {
77     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
78     {
79         OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
80         return nullptr;
81     }
82
83     OCRepPayload* input = reinterpret_cast<OCRepPayload*>(ehRequest->payload);
84
85     LEDResource *currLEDResource = &LED;
86
87     if (ehRequest->resource == gLedInstance[0].handle)
88     {
89         currLEDResource = &gLedInstance[0];
90         gResourceUri = (char *) "/a/led/0";
91     }
92     else if (ehRequest->resource == gLedInstance[1].handle)
93     {
94         currLEDResource = &gLedInstance[1];
95         gResourceUri = (char *) "/a/led/1";
96     }
97
98     if(OC_REST_PUT == ehRequest->method)
99     {
100         // Get pointer to query
101         int64_t pow;
102         if(OCRepPayloadGetPropInt(input, "power", &pow))
103         {
104             currLEDResource->power =pow;
105         }
106
107         bool state;
108         if(OCRepPayloadGetPropBool(input, "state", &state))
109         {
110             currLEDResource->state = state;
111         }
112     }
113
114     return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
115 }
116
117 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
118         OCRepPayload **payload)
119 {
120     OCEntityHandlerResult ehResult;
121
122     OCRepPayload *getResp = constructResponse(ehRequest);
123
124     if(getResp)
125     {
126         *payload = getResp;
127         ehResult = OC_EH_OK;
128     }
129     else
130     {
131         ehResult = OC_EH_ERROR;
132     }
133
134     return ehResult;
135 }
136
137 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
138         OCRepPayload **payload)
139 {
140     OCEntityHandlerResult ehResult;
141
142     OCRepPayload *putResp = constructResponse(ehRequest);
143
144     if(putResp)
145     {
146         *payload = putResp;
147         ehResult = OC_EH_OK;
148     }
149     else
150     {
151         ehResult = OC_EH_ERROR;
152     }
153
154     return ehResult;
155 }
156
157 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
158         OCEntityHandlerResponse *response, OCRepPayload **payload)
159 {
160     OCRepPayload *respPLPost_led = nullptr;
161     OCEntityHandlerResult ehResult = OC_EH_OK;
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             respPLPost_led = OCRepPayloadCreate();
184             OCRepPayloadSetUri(respPLPost_led, gResourceUri);
185             OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
186
187             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
188             {
189                 OIC_LOG (INFO, TAG, "Created new LED instance");
190                 gLedInstance[gCurrLedInstance].state = 0;
191                 gLedInstance[gCurrLedInstance].power = 0;
192                 gCurrLedInstance++;
193                 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
194                 ehResult = OC_EH_RESOURCE_CREATED;
195             }
196         }
197         else
198         {
199             respPLPost_led = constructResponse(ehRequest);
200         }
201     }
202     else
203     {
204         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
205         {
206             if (ehRequest->resource == gLedInstance[i].handle)
207             {
208                 if (i == 0)
209                 {
210                     respPLPost_led = constructResponse(ehRequest);
211                     break;
212                 }
213                 else if (i == 1)
214                 {
215                     respPLPost_led = constructResponse(ehRequest);
216                 }
217             }
218         }
219     }
220
221     if (respPLPost_led != NULL)
222     {
223         *payload = respPLPost_led;
224         ehResult = OC_EH_OK;
225     }
226     else
227     {
228         OIC_LOG_V (INFO, TAG, "Payload was NULL");
229         ehResult = OC_EH_ERROR;
230     }
231
232     return ehResult;
233 }
234
235 OCEntityHandlerResult
236 OCEntityHandlerCb (OCEntityHandlerFlag flag,
237         OCEntityHandlerRequest *entityHandlerRequest,
238         void* /*callbackParam*/)
239 {
240     OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
241
242     OCEntityHandlerResult ehResult = OC_EH_ERROR;
243     OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
244     // Validate pointer
245     if (!entityHandlerRequest)
246     {
247         OIC_LOG (ERROR, TAG, "Invalid request pointer");
248         return OC_EH_ERROR;
249     }
250
251     OCRepPayload* payload = nullptr;
252
253     if (flag & OC_REQUEST_FLAG)
254     {
255         OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
256         if (entityHandlerRequest)
257         {
258             if (OC_REST_GET == entityHandlerRequest->method)
259             {
260                 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
261                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
262             }
263             else if (OC_REST_PUT == entityHandlerRequest->method)
264             {
265                 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
266                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
267             }
268             else if (OC_REST_POST == entityHandlerRequest->method)
269             {
270                 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
271                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
272             }
273             else
274             {
275                 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
276                         entityHandlerRequest->method);
277                 ehResult = OC_EH_ERROR;
278             }
279
280             if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
281             {
282                 // Format the response.  Note this requires some info about the request
283                 response.requestHandle = entityHandlerRequest->requestHandle;
284                 response.resourceHandle = entityHandlerRequest->resource;
285                 response.ehResult = ehResult;
286                 response.payload = reinterpret_cast<OCPayload*>(payload);
287                 response.numSendVendorSpecificHeaderOptions = 0;
288                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
289                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
290                 // Indicate that response is NOT in a persistent buffer
291                 response.persistentBufferFlag = 0;
292
293                 // Send the response
294                 if (OCDoResponse(&response) != OC_STACK_OK)
295                 {
296                     OIC_LOG(ERROR, TAG, "Error sending response");
297                     ehResult = OC_EH_ERROR;
298                 }
299             }
300         }
301     }
302
303     OCPayloadDestroy(response.payload);
304     return ehResult;
305 }
306
307 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
308 void handleSigInt(int signum)
309 {
310     if (signum == SIGINT)
311     {
312         gQuitFlag = 1;
313     }
314 }
315
316 FILE* server_fopen(const char *path, const char *mode)
317 {
318     (void)path;
319     return fopen(CRED_FILE, mode);
320 }
321
322 int main(int /*argc*/, char* /*argv*/[])
323 {
324     struct timespec timeout;
325
326     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
327
328     // Initialize Persistent Storage for SVR database
329     OCPersistentStorage ps = { server_fopen, fread, fwrite, fclose, unlink };
330     OCRegisterPersistentStorageHandler(&ps);
331
332     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
333     {
334         OIC_LOG(ERROR, TAG, "OCStack init error");
335         return 0;
336     }
337
338     /*
339      * Declare and create the example resource: LED
340      */
341     createLEDResource(gResourceUri, &LED, false, 0);
342
343     timeout.tv_sec  = 0;
344     timeout.tv_nsec = 100000000L;
345
346     // Break from loop with Ctrl-C
347     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
348     signal(SIGINT, handleSigInt);
349     while (!gQuitFlag)
350     {
351         if (OCProcess() != OC_STACK_OK)
352         {
353             OIC_LOG(ERROR, TAG, "OCStack process error");
354             return 0;
355         }
356         nanosleep(&timeout, NULL);
357     }
358
359     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
360
361     if (OCStop() != OC_STACK_OK)
362     {
363         OIC_LOG(ERROR, TAG, "OCStack process error");
364     }
365
366     return 0;
367 }
368
369 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
370 {
371     if (!uri)
372     {
373         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
374         return -1;
375     }
376
377     ledResource->state = resourceState;
378     ledResource->power= resourcePower;
379     OCStackResult res = OCCreateResource(&(ledResource->handle),
380             "core.led",
381             OC_RSRVD_INTERFACE_DEFAULT,
382             uri,
383             OCEntityHandlerCb,
384             NULL,
385             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
386     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
387
388     return 0;
389 }
390