Contiki-NG
Loading...
Searching...
No Matches
coap-engine.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2013, Institute for Pervasive Computing, ETH Zurich
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the Institute nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 * This file is part of the Contiki operating system.
30 */
31
32/**
33 * \file
34 * CoAP implementation Engine.
35 * \author
36 * Matthias Kovatsch <kovatsch@inf.ethz.ch>
37 */
38
39/**
40 * \addtogroup coap
41 * @{
42 */
43
44#include "coap-engine.h"
45#include "sys/cc.h"
46#include "lib/list.h"
47#include <stdio.h>
48#include <stdlib.h>
49#include <inttypes.h>
50#include <string.h>
51
52/* Log configuration */
53#include "coap-log.h"
54#define LOG_MODULE "coap-eng"
55#define LOG_LEVEL LOG_LEVEL_COAP
56
57static void process_callback(coap_timer_t *t);
58
59/*
60 * To be called by HTTP/COAP server as a callback function when a new service
61 * request appears. This function dispatches the corresponding CoAP service.
62 */
63static int invoke_coap_resource_service(coap_message_t *request,
64 coap_message_t *response,
65 uint8_t *buffer, uint16_t buffer_size,
66 int32_t *offset);
67
68/*---------------------------------------------------------------------------*/
69/*- Variables ---------------------------------------------------------------*/
70/*---------------------------------------------------------------------------*/
71LIST(coap_handlers);
72LIST(coap_resource_services);
73static uint8_t is_initialized = 0;
74
75/*---------------------------------------------------------------------------*/
76/*- CoAP service handlers---------------------------------------------------*/
77/*---------------------------------------------------------------------------*/
78void
79coap_add_handler(coap_handler_t *handler)
80{
81 list_add(coap_handlers, handler);
82}
83/*---------------------------------------------------------------------------*/
84void
85coap_remove_handler(coap_handler_t *handler)
86{
87 list_remove(coap_handlers, handler);
88}
89/*---------------------------------------------------------------------------*/
90coap_handler_status_t
91coap_call_handlers(coap_message_t *request, coap_message_t *response,
92 uint8_t *buffer, uint16_t buffer_size, int32_t *offset)
93{
94 coap_handler_status_t status;
95 coap_handler_t *r;
96 for(r = list_head(coap_handlers); r != NULL; r = r->next) {
97 if(r->handler) {
98 status = r->handler(request, response, buffer, buffer_size, offset);
99 if(status != COAP_HANDLER_STATUS_CONTINUE) {
100 /* Request handled. */
101
102 /* Check response code before doing observe! */
103 if(request->code == COAP_GET) {
104 coap_observe_handler(NULL, request, response);
105 }
106
107 return status;
108 }
109 }
110 }
111 return COAP_HANDLER_STATUS_CONTINUE;
112}
113/*---------------------------------------------------------------------------*/
114static inline coap_handler_status_t
115call_service(coap_message_t *request, coap_message_t *response,
116 uint8_t *buffer, uint16_t buffer_size, int32_t *offset)
117{
118 coap_handler_status_t status;
119 status = coap_call_handlers(request, response, buffer, buffer_size, offset);
120 if(status != COAP_HANDLER_STATUS_CONTINUE) {
121 return status;
122 }
123 status = invoke_coap_resource_service(request, response, buffer, buffer_size, offset);
124 if(status != COAP_HANDLER_STATUS_CONTINUE) {
125 return status;
126 }
127
128 coap_set_status_code(response, NOT_FOUND_4_04);
129
130 return COAP_HANDLER_STATUS_CONTINUE;
131}
132
133/*---------------------------------------------------------------------------*/
134/*- Server Part -------------------------------------------------------------*/
135/*---------------------------------------------------------------------------*/
136
137#if COAP_WELL_KNOWN_RESOURCE_ENABLED
138/* The discover resource is included by default for CoAP */
139extern coap_resource_t res_well_known_core;
140#endif
141
142/*---------------------------------------------------------------------------*/
143/*- Internal API ------------------------------------------------------------*/
144/*---------------------------------------------------------------------------*/
145int
146coap_receive(const coap_endpoint_t *src,
147 uint8_t *payload, uint16_t payload_length)
148{
149 /* static declaration reduces stack peaks and program code size */
150 static coap_message_t message[1]; /* this way the message can be treated as pointer as usual */
151 static coap_message_t response[1];
152 coap_transaction_t *transaction = NULL;
153 coap_handler_status_t status;
154
155 coap_status_code = coap_parse_message(message, payload, payload_length);
156 coap_set_src_endpoint(message, src);
157
158 if(coap_status_code == NO_ERROR) {
159
160 /*TODO duplicates suppression, if required by application */
161
162 LOG_DBG(" Parsed: v %u, t %u, tkl %u, c %u, mid %u\n", message->version,
163 message->type, message->token_len, message->code, message->mid);
164 LOG_DBG(" URL:");
165 LOG_DBG_COAP_STRING(message->uri_path, message->uri_path_len);
166 LOG_DBG_("\n");
167 LOG_DBG(" Payload: ");
168 LOG_DBG_COAP_STRING((const char *)message->payload, message->payload_len);
169 LOG_DBG_("\n");
170
171 /* handle requests */
172 if(message->code >= COAP_GET && message->code <= COAP_DELETE) {
173
174 /* use transaction buffer for response to confirmable request */
175 if((transaction = coap_new_transaction(message->mid, src))) {
176 uint32_t block_num = 0;
177 uint16_t block_size = COAP_MAX_BLOCK_SIZE;
178 uint32_t block_offset = 0;
179 int32_t new_offset = 0;
180
181 /* prepare response */
182 if(message->type == COAP_TYPE_CON) {
183 /* reliable CON requests are answered with an ACK */
184 coap_init_message(response, COAP_TYPE_ACK, CONTENT_2_05,
185 message->mid);
186 } else {
187 /* unreliable NON requests are answered with a NON as well */
188 coap_init_message(response, COAP_TYPE_NON, CONTENT_2_05,
189 coap_get_mid());
190 /* mirror token */
191 }
192 if(message->token_len) {
193 coap_set_token(response, message->token, message->token_len);
194 /* get offset for blockwise transfers */
195 }
196 if(coap_get_header_block2
197 (message, &block_num, NULL, &block_size, &block_offset)) {
198 LOG_DBG("Blockwise: block request %"PRIu32" (%u/%u) @ %"PRIu32" bytes\n",
199 block_num, block_size, COAP_MAX_BLOCK_SIZE, block_offset);
200 block_size = MIN(block_size, COAP_MAX_BLOCK_SIZE);
201 new_offset = block_offset;
202 }
203
204 if(new_offset < 0) {
205 LOG_DBG("Blockwise: block request offset overflow\n");
206 coap_status_code = BAD_OPTION_4_02;
207#if COAP_MESSAGE_ON_ERROR
208 coap_error_message = "BlockOutOfScope";
209#endif
210 status = COAP_HANDLER_STATUS_CONTINUE;
211 } else {
212 /* call CoAP framework and check if found and allowed */
213 status = call_service(message, response,
214 transaction->message + COAP_MAX_HEADER_SIZE,
215 block_size, &new_offset);
216 }
217
218 if(status != COAP_HANDLER_STATUS_CONTINUE) {
219
220 if(coap_status_code == NO_ERROR) {
221
222 /* TODO coap_handle_blockwise(request, response, start_offset, end_offset); */
223
224 /* resource is unaware of Block1 */
225 if(coap_is_option(message, COAP_OPTION_BLOCK1)
226 && response->code < BAD_REQUEST_4_00
227 && !coap_is_option(response, COAP_OPTION_BLOCK1)) {
228 LOG_DBG("Block1 NOT IMPLEMENTED\n");
229
230 coap_status_code = NOT_IMPLEMENTED_5_01;
231#if COAP_MESSAGE_ON_ERROR
232 coap_error_message = "NoBlock1Support";
233#endif
234
235 /* client requested Block2 transfer */
236 } else if(coap_is_option(message, COAP_OPTION_BLOCK2)) {
237
238 /* unchanged new_offset indicates that resource is unaware of blockwise transfer */
239 if(new_offset == block_offset) {
240 LOG_DBG("Blockwise: unaware resource with payload length %u/%u\n",
241 response->payload_len, block_size);
242 if(block_offset >= response->payload_len) {
243 LOG_DBG("handle_incoming_data(): block_offset >= response->payload_len\n");
244
245 response->code = BAD_OPTION_4_02;
246 coap_set_payload(response, "BlockOutOfScope", 15); /* a const char str[] and sizeof(str) produces larger code size */
247 } else {
248 coap_set_header_block2(response, block_num,
249 response->payload_len -
250 block_offset > block_size,
251 block_size);
252 coap_set_payload(response,
253 response->payload + block_offset,
254 MIN(response->payload_len -
255 block_offset, block_size));
256 } /* if(valid offset) */
257
258 /* resource provides chunk-wise data */
259 } else {
260 LOG_DBG("Blockwise: blockwise resource, new offset %"PRId32"\n",
261 new_offset);
262 coap_set_header_block2(response, block_num,
263 new_offset != -1
264 || response->payload_len >
265 block_size, block_size);
266
267 if(response->payload_len > block_size) {
268 coap_set_payload(response, response->payload,
269 block_size);
270 }
271 } /* if(resource aware of blockwise) */
272
273 /* Resource requested Block2 transfer */
274 } else if(new_offset != 0) {
275 LOG_DBG("Blockwise: no block option for blockwise resource, using block size %u\n",
276 COAP_MAX_BLOCK_SIZE);
277
278 coap_set_header_block2(response, 0, new_offset != -1,
279 COAP_MAX_BLOCK_SIZE);
280 coap_set_payload(response, response->payload,
281 MIN(response->payload_len,
282 COAP_MAX_BLOCK_SIZE));
283 } /* blockwise transfer handling */
284 } /* no errors/hooks */
285 /* successful service callback */
286 /* serialize response */
287 }
288 if(coap_status_code == NO_ERROR) {
289 if((transaction->message_len = coap_serialize_message(response,
290 transaction->
291 message)) ==
292 0) {
293 coap_status_code = PACKET_SERIALIZATION_ERROR;
294 }
295 }
296 } else {
297 coap_status_code = SERVICE_UNAVAILABLE_5_03;
298#if COAP_MESSAGE_ON_ERROR
299 coap_error_message = "NoFreeTraBuffer";
300#endif
301 } /* if(transaction buffer) */
302
303 /* handle responses */
304 } else {
305
306 if(message->type == COAP_TYPE_CON && message->code == 0) {
307 LOG_INFO("Received Ping\n");
308 coap_status_code = PING_RESPONSE;
309 } else if(message->type == COAP_TYPE_ACK) {
310 /* transactions are closed through lookup below */
311 LOG_DBG("Received ACK\n");
312 } else if(message->type == COAP_TYPE_RST) {
313 LOG_INFO("Received RST\n");
314 /* cancel possible subscriptions */
315 coap_remove_observer_by_mid(src, message->mid);
316 }
317
318 if((transaction = coap_get_transaction_by_mid(message->mid))) {
319 /* free transaction memory before callback, as it may create a new transaction */
320 coap_resource_response_handler_t callback = transaction->callback;
321 void *callback_data = transaction->callback_data;
322
323 coap_clear_transaction(transaction);
324
325 /* check if someone registered for the response */
326 if(callback) {
327 callback(callback_data, message);
328 }
329 }
330 /* if(ACKed transaction) */
331 transaction = NULL;
332
333#if COAP_OBSERVE_CLIENT
334 /* if observe notification */
335 if((message->type == COAP_TYPE_CON || message->type == COAP_TYPE_NON)
336 && coap_is_option(message, COAP_OPTION_OBSERVE)) {
337 LOG_DBG("Observe [%"PRId32"]\n", message->observe);
338 coap_handle_notification(src, message);
339 }
340#endif /* COAP_OBSERVE_CLIENT */
341 } /* request or response */
342 } /* parsed correctly */
343
344 /* if(parsed correctly) */
345 if(coap_status_code == NO_ERROR) {
346 if(transaction) {
347 coap_send_transaction(transaction);
348 }
349 } else if(coap_status_code == MANUAL_RESPONSE) {
350 LOG_DBG("Clearing transaction for manual response");
351 coap_clear_transaction(transaction);
352 } else {
353 coap_message_type_t reply_type = COAP_TYPE_ACK;
354
355#if COAP_MESSAGE_ON_ERROR
356 LOG_WARN("ERROR %u: %s\n", coap_status_code, coap_error_message);
357#else
358 LOG_WARN("ERROR %u\n", coap_status_code);
359#endif
360 coap_clear_transaction(transaction);
361
362 if(coap_status_code == PING_RESPONSE) {
363 coap_status_code = 0;
364 reply_type = COAP_TYPE_RST;
365 } else if(coap_status_code >= 192) {
366 /* set to sendable error code */
367 coap_status_code = INTERNAL_SERVER_ERROR_5_00;
368 /* reuse input buffer for error message */
369 }
370 coap_init_message(message, reply_type, coap_status_code,
371 message->mid);
372#if COAP_MESSAGE_ON_ERROR
373 coap_set_payload(message, coap_error_message,
374 strlen(coap_error_message));
375#endif
376 coap_sendto(src, payload, coap_serialize_message(message, payload));
377 }
378
379 /* if(new data) */
380 return coap_status_code;
381}
382/*---------------------------------------------------------------------------*/
383void
384coap_engine_init(void)
385{
386 /* avoid initializing twice */
387 if(is_initialized) {
388 return;
389 }
390 is_initialized = 1;
391
392 LOG_INFO("Starting CoAP engine...\n");
393
394 list_init(coap_handlers);
395 list_init(coap_resource_services);
396
397#if COAP_WELL_KNOWN_RESOURCE_ENABLED
398 coap_activate_resource(&res_well_known_core, ".well-known/core");
399#endif
400
402 coap_init_connection();
403}
404/*---------------------------------------------------------------------------*/
405/**
406 * \brief Makes a resource available under the given URI path
407 *
408 * The resource implementation must be imported first using the
409 * extern keyword. The build system takes care of compiling every
410 * *.c file in the ./resources/ sub-directory (see example Makefile).
411 */
412void
413coap_activate_resource(coap_resource_t *resource, const char *path)
414{
415 coap_periodic_resource_t *periodic;
416 resource->url = path;
417 list_add(coap_resource_services, resource);
418
419 LOG_INFO("Activating: %s\n", resource->url);
420
421 /* Only add periodic resources with a periodic_handler and a period > 0. */
422 if(resource->flags & IS_PERIODIC && resource->periodic
423 && resource->periodic->periodic_handler
424 && resource->periodic->period) {
425 LOG_DBG("Periodic resource: %p (%s)\n", resource->periodic, path);
426 periodic = resource->periodic;
427 coap_timer_set_callback(&periodic->periodic_timer, process_callback);
428 coap_timer_set_user_data(&periodic->periodic_timer, resource);
429 coap_timer_set(&periodic->periodic_timer, periodic->period);
430 }
431}
432/*---------------------------------------------------------------------------*/
433
434/*---------------------------------------------------------------------------*/
435/*- Internal API ------------------------------------------------------------*/
436/*---------------------------------------------------------------------------*/
437coap_resource_t *
439{
440 return list_head(coap_resource_services);
441}
442/*---------------------------------------------------------------------------*/
443coap_resource_t *
444coap_get_next_resource(coap_resource_t *resource)
445{
446 return list_item_next(resource);
447}
448/*---------------------------------------------------------------------------*/
449static int
450invoke_coap_resource_service(coap_message_t *request, coap_message_t *response,
451 uint8_t *buffer, uint16_t buffer_size,
452 int32_t *offset)
453{
454 uint8_t found = 0;
455 uint8_t allowed = 1;
456
457 coap_resource_t *resource = NULL;
458 const char *url = NULL;
459 int url_len, res_url_len;
460
461 url_len = coap_get_header_uri_path(request, &url);
462 for(resource = list_head(coap_resource_services);
463 resource; resource = resource->next) {
464
465 /* if the web service handles that kind of requests and urls matches */
466 res_url_len = strlen(resource->url);
467 if((url_len == res_url_len
468 || (url_len > res_url_len
469 && (resource->flags & HAS_SUB_RESOURCES)
470 && url[res_url_len] == '/'))
471 && strncmp(resource->url, url, res_url_len) == 0) {
472 coap_resource_flags_t method = coap_get_method_type(request);
473 found = 1;
474
475 LOG_INFO("/%s, method %u, resource->flags %u\n", resource->url,
476 (uint16_t)method, resource->flags);
477
478 if((method & METHOD_GET) && resource->get_handler != NULL) {
479 /* call handler function */
480 resource->get_handler(request, response, buffer, buffer_size, offset);
481 } else if((method & METHOD_POST) && resource->post_handler != NULL) {
482 /* call handler function */
483 resource->post_handler(request, response, buffer, buffer_size,
484 offset);
485 } else if((method & METHOD_PUT) && resource->put_handler != NULL) {
486 /* call handler function */
487 resource->put_handler(request, response, buffer, buffer_size, offset);
488 } else if((method & METHOD_DELETE) && resource->delete_handler != NULL) {
489 /* call handler function */
490 resource->delete_handler(request, response, buffer, buffer_size,
491 offset);
492 } else {
493 allowed = 0;
494 coap_set_status_code(response, METHOD_NOT_ALLOWED_4_05);
495 }
496 break;
497 }
498 }
499 if(!found) {
500 coap_set_status_code(response, NOT_FOUND_4_04);
501 } else if(allowed) {
502 /* final handler for special flags */
503 if(resource->flags & IS_OBSERVABLE) {
504 coap_observe_handler(resource, request, response);
505 }
506 }
507 return found & allowed;
508}
509/*---------------------------------------------------------------------------*/
510/* This callback occurs when t is expired */
511static void
512process_callback(coap_timer_t *t)
513{
514 coap_resource_t *resource;
515 resource = coap_timer_get_user_data(t);
516 if(resource != NULL && (resource->flags & IS_PERIODIC)
517 && resource->periodic != NULL && resource->periodic->period) {
518 LOG_DBG("Periodic: timer expired for /%s (period: %"PRIu32")\n",
519 resource->url, resource->periodic->period);
520
521 if(!is_initialized) {
522 /* CoAP has not yet been initialized. */
523 } else if(resource->periodic->periodic_handler) {
524 /* Call the periodic_handler function. */
525 resource->periodic->periodic_handler();
526 }
527
528 coap_timer_set(t, resource->periodic->period);
529 }
530}
531/*---------------------------------------------------------------------------*/
532/** @} */
Default definitions of C compiler quirk work-arounds.
CoAP engine implementation.
Log support for CoAP.
static void * coap_timer_get_user_data(coap_timer_t *timer)
Get user data that has been attached to a CoAP timer.
Definition coap-timer.h:118
static void coap_timer_set_user_data(coap_timer_t *timer, void *data)
Attach user data to a CoAP timer.
Definition coap-timer.h:130
void coap_timer_set(coap_timer_t *timer, uint64_t time)
Set a CoAP timer to expire after the specified time.
Definition coap-timer.c:103
static void coap_timer_set_callback(coap_timer_t *timer, void(*callback)(coap_timer_t *))
Set a callback function to be called when a CoAP timer expires.
Definition coap-timer.h:105
int coap_sendto(const coap_endpoint_t *ep, const uint8_t *data, uint16_t len)
Send a message to the specified CoAP endpoint.
Definition coap-uip.c:416
void coap_transport_init(void)
Initialize the CoAP transport.
Definition coap-uip.c:373
void coap_activate_resource(coap_resource_t *resource, const char *path)
Makes a resource available under the given URI path.
coap_resource_t * coap_get_next_resource(coap_resource_t *resource)
Returns the next registered CoAP resource.
coap_resource_flags_t
Resource flags for allowed methods and special functionalities.
coap_resource_t * coap_get_first_resource(void)
Returns the first of the registered CoAP resources.
static void list_init(list_t list)
Initialize a list.
Definition list.h:152
#define LIST(name)
Declare a linked list.
Definition list.h:90
static void * list_item_next(const void *item)
Get the next item following this item.
Definition list.h:294
void list_add(list_t list, void *item)
Add an item at the end of a list.
Definition list.c:71
void list_remove(list_t list, const void *item)
Remove a specific element from a list.
Definition list.c:134
static void * list_head(const_list_t list)
Get a pointer to the first element of a list.
Definition list.h:169
Linked list manipulation routines.