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