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