iotivity 0.9.0
[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 "cJSON.h"
30 #include "ocserverbasicops.h"
31 #include "common.h"
32
33 int gQuitFlag = 0;
34
35 static LEDResource LED;
36 // This variable determines instance number of the LED resource.
37 // Used by POST method to create a new instance of LED resource.
38 static int gCurrLedInstance = 0;
39 #define SAMPLE_MAX_NUM_POST_INSTANCE  2
40 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
41
42 char *gResourceUri= (char *)"/a/led";
43
44 static uint16_t OC_WELL_KNOWN_PORT = 5683;
45
46 //File containing Server's Identity and the PSK credentials
47 //of other devices which the server trusts
48 //This can be generated using 'gen_sec_bin' application
49 static char CRED_FILE[] = "server_cred.bin";
50
51 //This function takes the request as an input and returns the response
52 //in JSON format.
53 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
54 {
55     cJSON *json = cJSON_CreateObject();
56     cJSON *format;
57     char *jsonResponse;
58     LEDResource *currLEDResource = &LED;
59
60     if (ehRequest->resource == gLedInstance[0].handle)
61     {
62         currLEDResource = &gLedInstance[0];
63         gResourceUri = (char *) "a/led/0";
64     }
65     else if (ehRequest->resource == gLedInstance[1].handle)
66     {
67         currLEDResource = &gLedInstance[1];
68         gResourceUri = (char *) "a/led/1";
69     }
70
71     if(OC_REST_PUT == ehRequest->method)
72     {
73         cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
74         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
75                 "on") ? true:false);
76         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
77         cJSON_Delete(putJson);
78     }
79
80     cJSON_AddStringToObject(json,"href",gResourceUri);
81     cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
82     cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
83     cJSON_AddNumberToObject(format, "power", currLEDResource->power);
84
85     jsonResponse = cJSON_Print(json);
86     cJSON_Delete(json);
87     return jsonResponse;
88 }
89
90 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
91                         char *payload, size_t maxPayloadSize)
92 {
93     OCEntityHandlerResult ehResult;
94
95     char *getResp = constructJsonResponse(ehRequest);
96     if (maxPayloadSize > strlen (getResp))
97     {
98         strcpy(payload, getResp);
99         ehResult = OC_EH_OK;
100     }
101     else
102     {
103         OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
104                 maxPayloadSize);
105         ehResult = OC_EH_ERROR;
106     }
107
108     free(getResp);
109
110     return ehResult;
111 }
112
113 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
114                         char *payload, size_t maxPayloadSize)
115 {
116     OCEntityHandlerResult ehResult;
117
118     char *putResp = constructJsonResponse(ehRequest);
119     if (maxPayloadSize > strlen (putResp))
120     {
121         strcpy(payload, putResp);
122         ehResult = OC_EH_OK;
123     }
124     else
125     {
126         OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
127                 maxPayloadSize);
128         ehResult = OC_EH_ERROR;
129     }
130
131     free(putResp);
132
133     return ehResult;
134 }
135
136 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
137                         char *payload, size_t maxPayloadSize)
138 {
139     char *respPLPost_led = NULL;
140     cJSON *json;
141     cJSON *format;
142     OCEntityHandlerResult ehResult;
143
144     /*
145      * The entity handler determines how to process a POST request.
146      * Per the REST paradigm, POST can also be used to update representation of existing
147      * resource or create a new resource.
148      * In the sample below, if the POST is for /a/led then a new instance of the LED
149      * resource is created with default representation (if representation is included in
150      * POST payload it can be used as initial values) as long as the instance is
151      * lesser than max new instance count. Once max instance count is reached, POST on
152      * /a/led updated the representation of /a/led (just like PUT)
153      */
154
155     if (ehRequest->resource == LED.handle)
156     {
157         if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
158         {
159             // Create new LED instance
160             char newLedUri[15] = "/a/led/";
161             int newLedUriLength = strlen(newLedUri);
162             snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
163
164             json = cJSON_CreateObject();
165
166             cJSON_AddStringToObject(json,"href",gResourceUri);
167             cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
168             cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
169
170             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
171             {
172                 OC_LOG (INFO, TAG, "Created new LED instance");
173                 gLedInstance[gCurrLedInstance].state = 0;
174                 gLedInstance[gCurrLedInstance].power = 0;
175                 gCurrLedInstance++;
176                 respPLPost_led = cJSON_Print(json);
177             }
178
179             cJSON_Delete(json);
180         }
181         else
182         {
183             respPLPost_led = constructJsonResponse(ehRequest);
184         }
185     }
186     else
187     {
188         for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
189         {
190             if (ehRequest->resource == gLedInstance[i].handle)
191             {
192                 if (i == 0)
193                 {
194                     respPLPost_led = constructJsonResponse(ehRequest);
195                     break;
196                 }
197                 else if (i == 1)
198                 {
199                     respPLPost_led = constructJsonResponse(ehRequest);
200                 }
201             }
202         }
203     }
204
205     if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led)))
206     {
207         strcpy(payload, respPLPost_led);
208         ehResult = OC_EH_OK;
209     }
210     else
211     {
212         OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
213                 maxPayloadSize);
214         ehResult = OC_EH_ERROR;
215     }
216
217     free(respPLPost_led);
218
219     return ehResult;
220 }
221
222 OCEntityHandlerResult
223 OCEntityHandlerCb (OCEntityHandlerFlag flag,
224         OCEntityHandlerRequest *entityHandlerRequest)
225 {
226     OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
227
228     OCEntityHandlerResult ehResult = OC_EH_ERROR;
229     OCEntityHandlerResponse response;
230     char payload[MAX_RESPONSE_LENGTH];
231
232     if (flag & OC_INIT_FLAG)
233     {
234         OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG");
235         ehResult = OC_EH_OK;
236     }
237     if (flag & OC_REQUEST_FLAG)
238     {
239         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
240         if (entityHandlerRequest)
241         {
242             if (OC_REST_GET == entityHandlerRequest->method)
243             {
244                 OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
245                 ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload));
246             }
247             else if (OC_REST_PUT == entityHandlerRequest->method)
248             {
249                 OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
250                 ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload));
251             }
252             else if (OC_REST_POST == entityHandlerRequest->method)
253             {
254                 OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
255                 ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload));
256             }
257             else
258             {
259                 OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
260                         entityHandlerRequest->method);
261             }
262
263             if (ehResult == OC_EH_OK)
264             {
265                 // Format the response.  Note this requires some info about the request
266                 response.requestHandle = entityHandlerRequest->requestHandle;
267                 response.resourceHandle = entityHandlerRequest->resource;
268                 response.ehResult = ehResult;
269                 response.payload = (unsigned char *)payload;
270                 response.payloadSize = strlen(payload);
271                 response.numSendVendorSpecificHeaderOptions = 0;
272                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
273                 memset(response.resourceUri, 0, sizeof(response.resourceUri));
274                 // Indicate that response is NOT in a persistent buffer
275                 response.persistentBufferFlag = 0;
276
277                 // Send the response
278                 if (OCDoResponse(&response) != OC_STACK_OK)
279                 {
280                     OC_LOG(ERROR, TAG, "Error sending response");
281                     ehResult = OC_EH_ERROR;
282                 }
283             }
284         }
285     }
286     return ehResult;
287 }
288
289 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
290 void handleSigInt(int signum)
291 {
292     if (signum == SIGINT)
293     {
294         gQuitFlag = 1;
295     }
296 }
297
298 int main(int argc, char* argv[])
299 {
300     uint8_t addr[20] = {0};
301     uint8_t* paddr = NULL;
302     uint16_t port = OC_WELL_KNOWN_PORT;
303     uint8_t ifname[] = "eth0";
304     struct timespec timeout;
305
306     OC_LOG(DEBUG, TAG, "OCServer is starting...");
307     /*Get Ip address on defined interface and initialize coap on it with random port number
308      * this port number will be used as a source port in all coap communications*/
309     if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
310                 sizeof(addr)) == ERR_SUCCESS)
311     {
312         OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port);
313         paddr = addr;
314     }
315
316     if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK)
317     {
318         OC_LOG(ERROR, TAG, "OCStack init error");
319         return 0;
320     }
321
322     /*
323      * Read DTLS PSK credentials from persistent storage and
324      * set in the OC stack.
325      */
326     if (SetCredentials(CRED_FILE) != OC_STACK_OK)
327     {
328         OC_LOG(ERROR, TAG, "SetCredentials failed");
329         return 0;
330     }
331     /*
332      * Declare and create the example resource: LED
333      */
334     createLEDResource(gResourceUri, &LED, false, 0);
335
336     timeout.tv_sec  = 0;
337     timeout.tv_nsec = 100000000L;
338
339     // Break from loop with Ctrl-C
340     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
341     signal(SIGINT, handleSigInt);
342     while (!gQuitFlag)
343     {
344         if (OCProcess() != OC_STACK_OK)
345         {
346             OC_LOG(ERROR, TAG, "OCStack process error");
347             return 0;
348         }
349         nanosleep(&timeout, NULL);
350     }
351
352     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
353
354     if (OCStop() != OC_STACK_OK)
355     {
356         OC_LOG(ERROR, TAG, "OCStack process error");
357     }
358
359     return 0;
360 }
361
362 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
363 {
364     if (!uri)
365     {
366         OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
367         return -1;
368     }
369
370     ledResource->state = resourceState;
371     ledResource->power= resourcePower;
372     OCStackResult res = OCCreateResource(&(ledResource->handle),
373             "core.led",
374             "oc.mi.def",
375             uri,
376             OCEntityHandlerCb,
377             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
378     OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
379
380     return 0;
381 }