Merge branch 'master' into windows-port
[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.dat";
49
50 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
51 {
52     OCRepPayload* payload = OCRepPayloadCreate();
53     if(!payload)
54     {
55         OIC_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         OIC_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                 OIC_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         OIC_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     OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
233
234     OCEntityHandlerResult ehResult = OC_EH_ERROR;
235     OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, { },{ 0 }, false };
236     // Validate pointer
237     if (!entityHandlerRequest)
238     {
239         OIC_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         OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
248         if (entityHandlerRequest)
249         {
250             if (OC_REST_GET == entityHandlerRequest->method)
251             {
252                 OIC_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                 OIC_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                 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
263                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
264             }
265             else
266             {
267                 OIC_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                     OIC_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     OIC_LOG(DEBUG, TAG, "OCServer is starting...");
319
320     // Initialize Persistent Storage for SVR database
321     OCPersistentStorage ps = { server_fopen, fread, fwrite, fclose, unlink };
322     OCRegisterPersistentStorageHandler(&ps);
323
324     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
325     {
326         OIC_LOG(ERROR, TAG, "OCStack init error");
327         return 0;
328     }
329
330     /*
331      * Declare and create the example resource: LED
332      */
333     createLEDResource(gResourceUri, &LED, false, 0);
334
335     timeout.tv_sec  = 0;
336     timeout.tv_nsec = 100000000L;
337
338     // Break from loop with Ctrl-C
339     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
340     signal(SIGINT, handleSigInt);
341     while (!gQuitFlag)
342     {
343         if (OCProcess() != OC_STACK_OK)
344         {
345             OIC_LOG(ERROR, TAG, "OCStack process error");
346             return 0;
347         }
348         nanosleep(&timeout, NULL);
349     }
350
351     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
352
353     if (OCStop() != OC_STACK_OK)
354     {
355         OIC_LOG(ERROR, TAG, "OCStack process error");
356     }
357
358     return 0;
359 }
360
361 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
362 {
363     if (!uri)
364     {
365         OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
366         return -1;
367     }
368
369     ledResource->state = resourceState;
370     ledResource->power= resourcePower;
371     OCStackResult res = OCCreateResource(&(ledResource->handle),
372             "core.led",
373             OC_RSRVD_INTERFACE_DEFAULT,
374             uri,
375             OCEntityHandlerCb,
376             NULL,
377             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
378     OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
379
380     return 0;
381 }
382