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