1 /* resource.c -- generic resource handling
3 * Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
5 * This file is part of the CoAP library libcoap. Please see
6 * README for terms of use.
13 #include "subscribe.h"
17 /* mem.h is only needed for the string free calls for
18 * COAP_ATTR_FLAGS_RELEASE_NAME / COAP_ATTR_FLAGS_RELEASE_VALUE /
19 * COAP_RESOURCE_FLAGS_RELEASE_URI. not sure what those lines should actually
23 #include <lwip/memp.h>
25 #define COAP_MALLOC_TYPE(Type) \
26 ((coap_##Type##_t *)memp_malloc(MEMP_COAP_##Type))
27 #define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
34 #define COAP_MALLOC_TYPE(Type) \
35 ((coap_##Type##_t *)coap_malloc(sizeof(coap_##Type##_t)))
36 #define COAP_FREE_TYPE(Type, Object) coap_free(Object)
38 #endif /* WITH_POSIX */
42 MEMB(resource_storage, coap_resource_t, COAP_MAX_RESOURCES);
43 MEMB(attribute_storage, coap_attr_t, COAP_MAX_ATTRIBUTES);
44 MEMB(subscription_storage, coap_subscription_t, COAP_MAX_SUBSCRIBERS);
49 memb_init(&resource_storage);
50 memb_init(&attribute_storage);
51 memb_init(&subscription_storage);
54 static inline coap_subscription_t *
55 coap_malloc_subscription()
57 return memb_alloc(&subscription_storage);
61 coap_free_subscription(coap_subscription_t *subscription)
63 memb_free(&subscription_storage, subscription);
65 #endif /* WITH_CONTIKI */
67 #define min(a,b) ((a) < (b) ? (a) : (b))
69 /* Helper functions for conditional output of character sequences into
70 * a given buffer. The first Offset characters are skipped.
74 * Adds Char to Buf if Offset is zero. Otherwise, Char is not written
75 * and Offset is decremented.
77 #define PRINT_WITH_OFFSET(Buf,Offset,Char) \
78 if ((Offset) == 0) { \
79 (*(Buf)++) = (Char); \
85 * Adds Char to Buf if Offset is zero and Buf is less than Bufend.
87 #define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) { \
88 if ((Buf) < (Bufend)) { \
89 PRINT_WITH_OFFSET(Buf,Offset,Char); \
95 * Copies at most Length characters of Str to Buf. The first Offset
96 * characters are skipped. Output may be truncated to Bufend - Buf
99 #define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) { \
101 for (i = 0; i < (Length); i++) { \
102 PRINT_COND_WITH_OFFSET((Buf), (Bufend), (Offset), (Str)[i], (Result)); \
106 int match(const str *text, const str *pattern, int match_prefix, int match_substring)
111 if (text->length < pattern->length)
116 unsigned char *next_token = text->s;
117 size_t remaining_length = text->length;
118 while (remaining_length)
121 unsigned char *token = next_token;
122 next_token = memchr(token, ' ', remaining_length);
126 token_length = next_token - token;
127 remaining_length -= (token_length + 1);
132 token_length = remaining_length;
133 remaining_length = 0;
136 if ((match_prefix || pattern->length == token_length)
137 && memcmp(token, pattern->s, pattern->length) == 0)
143 return (match_prefix || pattern->length == text->length)
144 && memcmp(text->s, pattern->s, pattern->length) == 0;
148 * Prints the names of all known resources to @p buf. This function
149 * sets @p buflen to the number of bytes actually written and returns
150 * @c 1 on succes. On error, the value in @p buflen is undefined and
151 * the return value will be @c 0.
153 * @param context The context with the resource map.
154 * @param buf The buffer to write the result.
155 * @param buflen Must be initialized to the maximum length of @p buf and will be
156 * set to the length of the well-known response on return.
157 * @param offset The offset in bytes where the output shall start and is
158 * shifted accordingly with the characters that have been
159 * processed. This parameter is used to support the block
161 * @param query_filter A filter query according to <a href="http://tools.ietf.org/html/draft-ietf-core-link-format-11#section-4.1">Link Format</a>
163 * @return COAP_PRINT_STATUS_ERROR on error. Otherwise, the lower 28 bits are
164 * set to the number of bytes that have actually been written to
165 * @p buf. COAP_PRINT_STATUS_TRUNC is set when the output has been
168 #if defined(__GNUC__) && defined(WITHOUT_QUERY_FILTER)
170 print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen,
172 coap_opt_t *query_filter __attribute__ ((unused)))
174 #else /* not a GCC */
175 coap_print_status_t print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen,
176 size_t offset, coap_opt_t *query_filter)
180 unsigned char *p = buf;
181 const unsigned char *bufend = buf + *buflen;
182 size_t left, written = 0;
183 coap_print_status_t result;
184 const size_t old_offset = offset;
185 int subsequent_resource = 0;
186 #ifndef COAP_RESOURCES_NOHASH
187 coap_resource_t *tmp;
189 #ifndef WITHOUT_QUERY_FILTER
191 { 0, NULL }, query_pattern =
193 int flags = 0; /* MATCH_SUBSTRING, MATCH_PREFIX, MATCH_URI */
194 #define MATCH_URI 0x01
195 #define MATCH_PREFIX 0x02
196 #define MATCH_SUBSTRING 0x04
197 static const str _rt_attributes[] =
199 { 2, (unsigned char *) "rt" },
200 { 2, (unsigned char *) "if" },
201 { 3, (unsigned char *) "rel" },
203 #endif /* WITHOUT_QUERY_FILTER */
207 #endif /* WITH_CONTIKI */
209 #ifndef WITHOUT_QUERY_FILTER
210 /* split query filter, if any */
213 resource_param.s = COAP_OPT_VALUE(query_filter);
214 while (resource_param.length < COAP_OPT_LENGTH(query_filter)
215 && resource_param.s[resource_param.length] != '=')
216 resource_param.length++;
218 if (resource_param.length < COAP_OPT_LENGTH(query_filter))
220 const str *rt_attributes;
221 if (resource_param.length == 4 && memcmp(resource_param.s, "href", 4) == 0)
224 for (rt_attributes = _rt_attributes; rt_attributes->s; rt_attributes++)
226 if (resource_param.length == rt_attributes->length
227 && memcmp(resource_param.s, rt_attributes->s, rt_attributes->length) == 0)
229 flags |= MATCH_SUBSTRING;
234 /* rest is query-pattern */
235 query_pattern.s = COAP_OPT_VALUE(query_filter) + resource_param.length + 1;
237 assert((resource_param.length + 1) <= COAP_OPT_LENGTH(query_filter));
238 query_pattern.length = COAP_OPT_LENGTH(query_filter) - (resource_param.length + 1);
240 if ((query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI))
243 query_pattern.length--;
246 if (query_pattern.length && query_pattern.s[query_pattern.length - 1] == '*')
248 query_pattern.length--;
249 flags |= MATCH_PREFIX;
253 #endif /* WITHOUT_QUERY_FILTER */
257 #ifdef COAP_RESOURCES_NOHASH
258 LL_FOREACH(context->resources, r)
261 HASH_ITER(hh, context->resources, r, tmp)
264 #else /* WITH_CONTIKI */
265 r = (coap_resource_t *)resource_storage.mem;
266 for (i = 0; i < resource_storage.num; ++i, ++r)
268 if (!resource_storage.count[i])
270 #endif /* WITH_CONTIKI */
272 #ifndef WITHOUT_QUERY_FILTER
273 if (resource_param.length)
274 { /* there is a query filter */
276 if (flags & MATCH_URI)
277 { /* match resource URI */
278 if (!match(&r->uri, &query_pattern, (flags & MATCH_PREFIX) != 0,
279 (flags & MATCH_SUBSTRING) != 0))
283 { /* match attribute */
286 attr = coap_find_attr(r, resource_param.s, resource_param.length);
289 if (attr->value.s[0] == '"')
290 { /* if attribute has a quoted value, remove double quotes */
291 unquoted_val.length = attr->value.length - 2;
292 unquoted_val.s = attr->value.s + 1;
296 unquoted_val = attr->value;
298 if (!(match(&unquoted_val, &query_pattern, (flags & MATCH_PREFIX) != 0,
299 (flags & MATCH_SUBSTRING) != 0)))
303 #endif /* WITHOUT_QUERY_FILTER */
305 if (!subsequent_resource)
306 { /* this is the first resource */
307 subsequent_resource = 1;
311 PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written);
314 left = bufend - p; /* calculate available space */
315 result = coap_print_link(r, p, &left, &offset);
317 if (result & COAP_PRINT_STATUS_ERROR)
322 /* coap_print_link() returns the number of characters that
323 * where actually written to p. Now advance to its end. */
324 p += COAP_PRINT_OUTPUT_LENGTH(result);
330 if (result + old_offset - offset < *buflen)
332 result |= COAP_PRINT_STATUS_TRUNC;
338 coap_resource_init(const unsigned char *uri, size_t len, int flags)
343 r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t));
346 r = (coap_resource_t *)memp_malloc(MEMP_COAP_RESOURCE);
349 r = (coap_resource_t *)memb_alloc(&resource_storage);
353 memset(r, 0, sizeof(coap_resource_t));
356 LIST_STRUCT_INIT(r, link_attr);
357 #endif /* WITH_CONTIKI */
358 LIST_STRUCT_INIT(r, subscribers);
360 r->uri.s = (unsigned char *) uri;
363 coap_hash_path(r->uri.s, r->uri.length, r->key);
369 debug("coap_resource_init: no memory left\n");
376 coap_add_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen,
377 const unsigned char *val, size_t vlen, int flags)
381 if (!resource || !name)
385 attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t));
388 attr = (coap_attr_t *)memp_malloc(MEMP_COAP_RESOURCEATTR);
391 attr = (coap_attr_t *)memb_alloc(&attribute_storage);
396 attr->name.length = nlen;
397 attr->value.length = val ? vlen : 0;
399 attr->name.s = (unsigned char *) name;
400 attr->value.s = (unsigned char *) val;
404 /* add attribute to resource list */
406 LL_PREPEND(resource->link_attr, attr);
407 #else /* WITH_CONTIKI */
408 list_add(resource->link_attr, attr);
409 #endif /* WITH_CONTIKI */
413 debug("coap_add_attr: no memory left\n");
420 coap_find_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen)
424 if (!resource || !name)
428 LL_FOREACH(resource->link_attr, attr)
430 #else /* WITH_CONTIKI */
431 for (attr = list_head(resource->link_attr); attr;
432 attr = list_item_next(attr))
434 #endif /* WITH_CONTIKI */
435 if (attr->name.length == nlen && memcmp(attr->name.s, name, nlen) == 0)
442 void coap_delete_attr(coap_attr_t *attr)
446 if (attr->flags & COAP_ATTR_FLAGS_RELEASE_NAME)
447 coap_free(attr->name.s);
448 if (attr->flags & COAP_ATTR_FLAGS_RELEASE_VALUE)
449 coap_free(attr->value.s);
454 memp_free(MEMP_COAP_RESOURCEATTR, attr);
457 /* FIXME it looks like this was never implemented */
461 void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key)
463 coap_opt_iterator_t opt_iter;
464 coap_opt_filter_t filter;
467 memset(key, 0, sizeof(coap_key_t));
469 coap_option_filter_clear(filter);
470 coap_option_setb(filter, COAP_OPTION_URI_PATH);
472 coap_option_iterator_init((coap_pdu_t *) request, &opt_iter, filter);
473 while ((option = coap_option_next(&opt_iter)))
474 coap_hash(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), key);
477 void coap_add_resource(coap_context_t *context, coap_resource_t *resource)
480 #ifdef COAP_RESOURCES_NOHASH
481 LL_PREPEND(context->resources, resource);
483 HASH_ADD(hh, context->resources, key, sizeof(coap_key_t), resource);
485 #endif /* WITH_CONTIKI */
488 int coap_delete_resource(coap_context_t *context, coap_key_t key)
490 coap_resource_t *resource;
491 coap_attr_t *attr, *tmp;
493 coap_subscription_t *obs;
499 resource = coap_get_resource_from_key(context, key);
504 #if defined(WITH_POSIX) || defined(WITH_LWIP)
505 #ifdef COAP_RESOURCES_NOHASH
506 LL_DELETE(context->resources, resource);
508 HASH_DELETE(hh, context->resources, resource);
511 /* delete registered attributes */
512 LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr);
514 if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI)
515 coap_free(resource->uri.s);
521 memp_free(MEMP_COAP_RESOURCE, resource);
523 #else /* not (WITH_POSIX || WITH_LWIP) */
524 /* delete registered attributes */
525 while ((attr = list_pop(resource->link_attr)))
526 memb_free(&attribute_storage, attr);
528 /* delete subscribers */
529 while ((obs = list_pop(resource->subscribers)))
531 /* FIXME: notify observer that its subscription has been removed */
532 memb_free(&subscription_storage, obs);
535 memb_free(&resource_storage, resource);
536 #endif /* WITH_CONTIKI */
542 coap_get_resource_from_key(coap_context_t *context, coap_key_t key)
545 coap_resource_t *resource;
546 #ifdef COAP_RESOURCES_NOHASH
548 LL_FOREACH(context->resources, resource)
550 /* if you think you can outspart the compiler and speed things up by (eg by
551 * casting to uint32* and comparing alues), increment this counter: 1 */
552 if (memcmp(key, resource->key, sizeof(coap_key_t)) == 0)
557 HASH_FIND(hh, context->resources, key, sizeof(coap_key_t), resource);
561 #else /* WITH_CONTIKI */
563 coap_resource_t *ptr2;
565 /* the search function is basically taken from memb.c */
566 ptr2 = (coap_resource_t *)resource_storage.mem;
567 for (i = 0; i < resource_storage.num; ++i)
569 if (resource_storage.count[i] &&
570 (memcmp(ptr2->key, key, sizeof(coap_key_t)) == 0))
571 return (coap_resource_t *)ptr2;
576 #endif /* WITH_CONTIKI */
579 coap_print_status_t coap_print_link(const coap_resource_t *resource, unsigned char *buf,
580 size_t *len, size_t *offset)
582 unsigned char *p = buf;
583 const unsigned char *bufend = buf + *len;
585 coap_print_status_t result = 0;
586 const size_t old_offset = *offset;
589 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '<', *len);
590 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '/', *len);
592 COPY_COND_WITH_OFFSET(p, bufend, *offset, resource->uri.s, resource->uri.length, *len);
594 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '>', *len);
597 LL_FOREACH(resource->link_attr, attr)
599 #else /* WITH_CONTIKI */
600 for (attr = list_head(resource->link_attr); attr;
601 attr = list_item_next(attr))
603 #endif /* WITH_CONTIKI */
605 PRINT_COND_WITH_OFFSET(p, bufend, *offset, ';', *len);
607 COPY_COND_WITH_OFFSET(p, bufend, *offset, attr->name.s, attr->name.length, *len);
611 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '=', *len);
613 COPY_COND_WITH_OFFSET(p, bufend, *offset, attr->value.s, attr->value.length, *len);
617 if (resource->observable)
619 COPY_COND_WITH_OFFSET(p, bufend, *offset, ";obs", 4, *len);
623 if (result + old_offset - *offset < *len)
625 result |= COAP_PRINT_STATUS_TRUNC;
631 #ifndef WITHOUT_OBSERVE
632 coap_subscription_t *
633 coap_find_observer(coap_resource_t *resource, const coap_address_t *peer, const str *token)
635 coap_subscription_t *s;
640 for (s = list_head(resource->subscribers); s; s = list_item_next(s))
642 if (coap_address_equals(&s->subscriber, peer)
644 || (token->length == s->token_length
645 && memcmp(token->s, s->token, token->length) == 0)))
652 coap_subscription_t *
653 coap_add_observer(coap_resource_t *resource, const coap_address_t *observer, const str *token)
655 coap_subscription_t *s;
659 /* Check if there is already a subscription for this peer. */
660 s = coap_find_observer(resource, observer, token);
662 /* We are done if subscription was found. */
666 /* s points to a different subscription, so we have to create
668 s = COAP_MALLOC_TYPE(subscription);
673 coap_subscription_init(s);
674 memcpy(&s->subscriber, observer, sizeof(coap_address_t));
676 if (token && token->length)
678 s->token_length = token->length;
679 memcpy(s->token, token->s, min(s->token_length, 8));
682 /* add subscriber to resource */
683 list_add(resource->subscribers, s);
688 void coap_touch_observer(coap_context_t *context, const coap_address_t *observer, const str *token)
691 coap_subscription_t *s;
694 #ifdef COAP_RESOURCES_NOHASH
695 LL_FOREACH(context->resources, r)
698 coap_resource_t *tmp;
699 HASH_ITER(hh, context->resources, r, tmp)
702 s = coap_find_observer(r, observer, token);
708 #else /* WITH_CONTIKI */
709 r = (coap_resource_t *)resource_storage.mem;
710 for (i = 0; i < resource_storage.num; ++i, ++r)
712 if (resource_storage.count[i])
714 s = coap_find_observer(r, observer, token);
721 #endif /* WITH_CONTIKI */
724 void coap_delete_observer(coap_resource_t *resource, const coap_address_t *observer,
727 coap_subscription_t *s;
729 s = coap_find_observer(resource, observer, token);
733 list_remove(resource->subscribers, s);
735 COAP_FREE_TYPE(subscription, s);
739 static void coap_notify_observers(coap_context_t *context, coap_resource_t *r)
741 coap_method_handler_t h;
742 coap_subscription_t *obs;
744 coap_pdu_t *response;
746 if (r->observable && (r->dirty || r->partiallydirty))
748 r->partiallydirty = 0;
750 /* retrieve GET handler, prepare response */
751 h = r->handler[COAP_REQUEST_GET - 1];
752 assert(h); /* we do not allow subscriptions if no
753 * GET handler is defined */
755 for (obs = list_head(r->subscribers); obs; obs = list_item_next(obs))
757 if (r->dirty == 0 && obs->dirty == 0)
758 /* running this resource due to partiallydirty, but this observation's notification was already enqueued */
761 coap_tid_t tid = COAP_INVALID_TID;
763 /* initialize response */
764 response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0, COAP_MAX_PDU_SIZE);
768 r->partiallydirty = 1;
769 debug("coap_check_notify: pdu init failed, resource stays partially dirty\n");
773 if (!coap_add_token(response, obs->token_length, obs->token))
776 r->partiallydirty = 1;
777 debug("coap_check_notify: cannot add token, resource stays partially dirty\n");
778 coap_delete_pdu(response);
782 token.length = obs->token_length;
783 token.s = obs->token;
785 response->hdr->id = coap_new_message_id(context);
786 if (obs->non && obs->non_cnt < COAP_OBS_MAX_NON)
788 response->hdr->type = COAP_MESSAGE_NON;
792 response->hdr->type = COAP_MESSAGE_CON;
794 /* fill with observer-specific data */
795 h(context, r, &obs->subscriber, NULL, &token, response);
797 if (response->hdr->type == COAP_MESSAGE_CON)
799 tid = coap_send_confirmed(context, &obs->subscriber, response);
804 tid = coap_send(context, &obs->subscriber, response);
808 if (COAP_INVALID_TID == tid || response->hdr->type != COAP_MESSAGE_CON)
809 coap_delete_pdu(response);
810 if (COAP_INVALID_TID == tid)
812 debug("coap_check_notify: sending failed, resource stays partially dirty\n");
814 r->partiallydirty = 1;
819 /* Increment value for next Observe use. */
825 void coap_check_notify(coap_context_t *context)
830 #ifdef COAP_RESOURCES_NOHASH
831 LL_FOREACH(context->resources, r)
834 coap_resource_t *tmp;
835 HASH_ITER(hh, context->resources, r, tmp)
838 coap_notify_observers(context, r);
840 #else /* WITH_CONTIKI */
843 r = (coap_resource_t *)resource_storage.mem;
844 for (i = 0; i < resource_storage.num; ++i, ++r)
846 if (resource_storage.count[i])
848 coap_notify_observers(context, r);
851 #endif /* WITH_CONTIKI */
855 * Checks the failure counter for (peer, token) and removes peer from
856 * the list of observers for the given resource when COAP_OBS_MAX_FAIL
859 * @param context The CoAP context to use
860 * @param resource The resource to check for (peer, token)
861 * @param peer The observer's address
862 * @param token The token that has been used for subscription.
864 static void coap_remove_failed_observers(coap_context_t *context, coap_resource_t *resource,
865 const coap_address_t *peer, const str *token)
867 coap_subscription_t *obs;
869 for (obs = list_head(resource->subscribers); obs; obs = list_item_next(obs))
871 if (coap_address_equals(peer, &obs->subscriber) && token->length == obs->token_length
872 && memcmp(token->s, obs->token, token->length) == 0)
875 /* count failed notifies and remove when
876 * COAP_MAX_FAILED_NOTIFY is reached */
877 if (obs->fail_cnt < COAP_OBS_MAX_FAIL)
881 list_remove(resource->subscribers, obs);
885 if (LOG_DEBUG <= coap_get_log_level())
887 #ifndef INET6_ADDRSTRLEN
888 #define INET6_ADDRSTRLEN 40
890 unsigned char addr[INET6_ADDRSTRLEN + 8];
892 if (coap_print_addr(&obs->subscriber, addr, INET6_ADDRSTRLEN + 8))
893 debug("** removed observer %s\n", addr);
896 coap_cancel_all_messages(context, &obs->subscriber, obs->token, obs->token_length);
898 COAP_FREE_TYPE(subscription, obs);
901 break; /* break loop if observer was found */
905 void coap_handle_failed_notify(coap_context_t *context, const coap_address_t *peer,
912 #ifdef COAP_RESOURCES_NOHASH
913 LL_FOREACH(context->resources, r)
916 coap_resource_t *tmp;
917 HASH_ITER(hh, context->resources, r, tmp)
920 coap_remove_failed_observers(context, r, peer, token);
922 #else /* WITH_CONTIKI */
925 r = (coap_resource_t *)resource_storage.mem;
926 for (i = 0; i < resource_storage.num; ++i, ++r)
928 if (resource_storage.count[i])
930 coap_remove_failed_observers(context, r, peer, token);
933 #endif /* WITH_CONTIKI */
935 #endif /* WITHOUT_NOTIFY */