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)
30 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
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 = (unsigned char *) 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)
342 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
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)
384 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
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, coap_udp);
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) || defined(WITH_ARDUINO)
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);
517 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
521 memp_free(MEMP_COAP_RESOURCE, resource);
523 #else /* not (WITH_POSIX || WITH_LWIP || WITH_ARDUINO) */
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 = (coap_subscription_t *) list_head(resource->subscribers);
641 s; s = (coap_subscription_t *) list_item_next((void *) s))
643 if (coap_address_equals(&s->subscriber, peer)
645 || (token->length == s->token_length
646 && memcmp(token->s, s->token, token->length) == 0)))
653 coap_subscription_t *
654 coap_add_observer(coap_resource_t *resource, const coap_address_t *observer, const str *token)
656 coap_subscription_t *s;
660 /* Check if there is already a subscription for this peer. */
661 s = coap_find_observer(resource, observer, token);
663 /* We are done if subscription was found. */
667 /* s points to a different subscription, so we have to create
669 s = COAP_MALLOC_TYPE(subscription);
674 coap_subscription_init(s);
675 memcpy(&s->subscriber, observer, sizeof(coap_address_t));
677 if (token && token->length)
679 s->token_length = token->length;
680 memcpy(s->token, token->s, min(s->token_length, 8));
683 /* add subscriber to resource */
684 list_add(resource->subscribers, s);
689 void coap_touch_observer(coap_context_t *context, const coap_address_t *observer, const str *token)
692 coap_subscription_t *s;
695 #ifdef COAP_RESOURCES_NOHASH
696 LL_FOREACH(context->resources, r)
699 coap_resource_t *tmp;
700 HASH_ITER(hh, context->resources, r, tmp)
703 s = coap_find_observer(r, observer, token);
709 #else /* WITH_CONTIKI */
710 r = (coap_resource_t *)resource_storage.mem;
711 for (i = 0; i < resource_storage.num; ++i, ++r)
713 if (resource_storage.count[i])
715 s = coap_find_observer(r, observer, token);
722 #endif /* WITH_CONTIKI */
725 void coap_delete_observer(coap_resource_t *resource, const coap_address_t *observer,
728 coap_subscription_t *s;
730 s = coap_find_observer(resource, observer, token);
734 list_remove(resource->subscribers, s);
736 COAP_FREE_TYPE(subscription, s);
740 static void coap_notify_observers(coap_context_t *context, coap_resource_t *r)
742 coap_method_handler_t h;
743 coap_subscription_t *obs;
745 coap_pdu_t *response;
747 if (r->observable && (r->dirty || r->partiallydirty))
749 r->partiallydirty = 0;
751 /* retrieve GET handler, prepare response */
752 h = r->handler[COAP_REQUEST_GET - 1];
753 assert(h); /* we do not allow subscriptions if no
754 * GET handler is defined */
756 for (obs = (coap_subscription_t *) list_head(r->subscribers);
757 obs; obs = (coap_subscription_t *) list_item_next((void *) obs))
759 if (r->dirty == 0 && obs->dirty == 0)
760 /* running this resource due to partiallydirty,
761 * but this observation's notification was already enqueued */
764 coap_tid_t tid = COAP_INVALID_TID;
766 /* initialize response */
767 response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0, COAP_MAX_PDU_SIZE, coap_udp);
771 r->partiallydirty = 1;
772 debug("coap_check_notify: pdu init failed, resource stays partially dirty\n");
776 if (!coap_add_token(response, obs->token_length, obs->token, coap_udp))
779 r->partiallydirty = 1;
780 debug("coap_check_notify: cannot add token, resource stays partially dirty\n");
781 coap_delete_pdu(response);
785 token.length = obs->token_length;
786 token.s = obs->token;
788 response->hdr->coap_hdr_udp_t.id = coap_new_message_id(context);
789 if (obs->non && obs->non_cnt < COAP_OBS_MAX_NON)
791 response->hdr->coap_hdr_udp_t.type = COAP_MESSAGE_NON;
795 response->hdr->coap_hdr_udp_t.type = COAP_MESSAGE_CON;
797 /* fill with observer-specific data */
798 h(context, r, &obs->subscriber, NULL, &token, response);
800 if (response->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON)
802 tid = coap_send_confirmed(context, &obs->subscriber, response);
807 tid = coap_send(context, &obs->subscriber, response);
811 if (COAP_INVALID_TID == tid || response->hdr->coap_hdr_udp_t.type != COAP_MESSAGE_CON)
812 coap_delete_pdu(response);
813 if (COAP_INVALID_TID == tid)
815 debug("coap_check_notify: sending failed, resource stays partially dirty\n");
817 r->partiallydirty = 1;
822 /* Increment value for next Observe use. */
828 void coap_check_notify(coap_context_t *context)
833 #ifdef COAP_RESOURCES_NOHASH
834 LL_FOREACH(context->resources, r)
837 coap_resource_t *tmp;
838 HASH_ITER(hh, context->resources, r, tmp)
841 coap_notify_observers(context, r);
843 #else /* WITH_CONTIKI */
846 r = (coap_resource_t *)resource_storage.mem;
847 for (i = 0; i < resource_storage.num; ++i, ++r)
849 if (resource_storage.count[i])
851 coap_notify_observers(context, r);
854 #endif /* WITH_CONTIKI */
858 * Checks the failure counter for (peer, token) and removes peer from
859 * the list of observers for the given resource when COAP_OBS_MAX_FAIL
862 * @param context The CoAP context to use
863 * @param resource The resource to check for (peer, token)
864 * @param peer The observer's address
865 * @param token The token that has been used for subscription.
867 static void coap_remove_failed_observers(coap_context_t *context, coap_resource_t *resource,
868 const coap_address_t *peer, const str *token)
870 coap_subscription_t *obs;
872 for (obs = (coap_subscription_t *) list_head(resource->subscribers);
873 obs; obs = (coap_subscription_t *) list_item_next((void *) obs))
875 if (coap_address_equals(peer, &obs->subscriber) && token->length == obs->token_length
876 && memcmp(token->s, obs->token, token->length) == 0)
879 /* count failed notifies and remove when
880 * COAP_MAX_FAILED_NOTIFY is reached */
881 if (obs->fail_cnt < COAP_OBS_MAX_FAIL)
885 list_remove(resource->subscribers, obs);
889 if (LOG_DEBUG <= coap_get_log_level())
891 #ifndef INET6_ADDRSTRLEN
892 #define INET6_ADDRSTRLEN 40
894 unsigned char addr[INET6_ADDRSTRLEN + 8];
896 if (coap_print_addr(&obs->subscriber, addr, INET6_ADDRSTRLEN + 8))
897 debug("** removed observer %s\n", addr);
900 coap_cancel_all_messages(context, &obs->subscriber, obs->token, obs->token_length);
902 COAP_FREE_TYPE(subscription, obs);
905 break; /* break loop if observer was found */
909 void coap_handle_failed_notify(coap_context_t *context, const coap_address_t *peer,
916 #ifdef COAP_RESOURCES_NOHASH
917 LL_FOREACH(context->resources, r)
920 coap_resource_t *tmp;
921 HASH_ITER(hh, context->resources, r, tmp)
924 coap_remove_failed_observers(context, r, peer, token);
926 #else /* WITH_CONTIKI */
929 r = (coap_resource_t *)resource_storage.mem;
930 for (i = 0; i < resource_storage.num; ++i, ++r)
932 if (resource_storage.count[i])
934 coap_remove_failed_observers(context, r, peer, token);
937 #endif /* WITH_CONTIKI */
939 #endif /* WITHOUT_NOTIFY */