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