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