libcoap  4.3.0beta
resource.c
Go to the documentation of this file.
1 /* resource.c -- generic resource handling
2  *
3  * Copyright (C) 2010--2015 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8 
9 #include "coap_internal.h"
10 
11 #include <stdio.h>
12 #include <errno.h>
13 
14 #ifdef COAP_EPOLL_SUPPORT
15 #include <sys/epoll.h>
16 #include <sys/timerfd.h>
17 #endif /* COAP_EPOLL_SUPPORT */
18 
19 #if defined(WITH_LWIP)
20 /* mem.h is only needed for the string free calls for
21  * COAP_ATTR_FLAGS_RELEASE_NAME / COAP_ATTR_FLAGS_RELEASE_VALUE /
22  * COAP_RESOURCE_FLAGS_RELEASE_URI. not sure what those lines should actually
23  * do on lwip. */
24 
25 #include <lwip/memp.h>
26 
27 #define COAP_MALLOC_TYPE(Type) \
28  ((coap_##Type##_t *)memp_malloc(MEMP_COAP_##Type))
29 #define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
30 
31 #elif defined(WITH_CONTIKI)
32 #include "memb.h"
33 
34 #define COAP_MALLOC_TYPE(Type) \
35  ((coap_##Type##_t *)memb_alloc(&(Type##_storage)))
36 #define COAP_FREE_TYPE(Type, Object) memb_free(&(Type##_storage), (Object))
37 
38 MEMB(subscription_storage, coap_subscription_t, COAP_MAX_SUBSCRIBERS);
39 
40 void
41 coap_resources_init() {
42  memb_init(&subscription_storage);
43 }
44 
46 coap_malloc_subscription() {
47  return memb_alloc(&subscription_storage);
48 }
49 
51 coap_free_subscription(coap_subscription_t *subscription) {
52  memb_free(&subscription_storage, subscription);
53 }
54 
55 #else
56 #define COAP_MALLOC_TYPE(Type) \
57  ((coap_##Type##_t *)coap_malloc(sizeof(coap_##Type##_t)))
58 #define COAP_FREE_TYPE(Type, Object) coap_free(Object)
59 #endif
60 
61 #define COAP_PRINT_STATUS_MAX (~COAP_PRINT_STATUS_MASK)
62 
63 #ifndef min
64 #define min(a,b) ((a) < (b) ? (a) : (b))
65 #endif
66 
67 /* Helper functions for conditional output of character sequences into
68  * a given buffer. The first Offset characters are skipped.
69  */
70 
75 #define PRINT_WITH_OFFSET(Buf,Offset,Char) \
76  if ((Offset) == 0) { \
77  (*(Buf)++) = (Char); \
78  } else { \
79  (Offset)--; \
80  } \
81 
85 #define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) { \
86  if ((Buf) < (Bufend)) { \
87  PRINT_WITH_OFFSET(Buf,Offset,Char); \
88  } \
89  (Result)++; \
90  }
91 
97 #define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) { \
98  size_t i; \
99  for (i = 0; i < (Length); i++) { \
100  PRINT_COND_WITH_OFFSET((Buf), (Bufend), (Offset), (Str)[i], (Result)); \
101  } \
102  }
103 
104 static int
105 match(const coap_str_const_t *text, const coap_str_const_t *pattern, int match_prefix,
106  int match_substring
107 ) {
108  assert(text); assert(pattern);
109 
110  if (text->length < pattern->length)
111  return 0;
112 
113  if (match_substring) {
114  const uint8_t *next_token = text->s;
115  size_t remaining_length = text->length;
116  while (remaining_length) {
117  size_t token_length;
118  const uint8_t *token = next_token;
119  next_token = (unsigned char *)memchr(token, ' ', remaining_length);
120 
121  if (next_token) {
122  token_length = next_token - token;
123  remaining_length -= (token_length + 1);
124  next_token++;
125  } else {
126  token_length = remaining_length;
127  remaining_length = 0;
128  }
129 
130  if ((match_prefix || pattern->length == token_length) &&
131  memcmp(token, pattern->s, pattern->length) == 0)
132  return 1;
133  }
134  return 0;
135  }
136 
137  return (match_prefix || pattern->length == text->length) &&
138  memcmp(text->s, pattern->s, pattern->length) == 0;
139 }
140 
162 #if defined(__GNUC__) && defined(WITHOUT_QUERY_FILTER)
164 coap_print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen,
165  size_t offset,
166  coap_opt_t *query_filter __attribute__ ((unused))) {
167 #else /* not a GCC */
169 coap_print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen,
170  size_t offset, coap_opt_t *query_filter) {
171 #endif /* GCC */
172  size_t output_length = 0;
173  unsigned char *p = buf;
174  const uint8_t *bufend = buf + *buflen;
175  size_t left, written = 0;
176  coap_print_status_t result;
177  const size_t old_offset = offset;
178  int subsequent_resource = 0;
179 #ifndef WITHOUT_QUERY_FILTER
180  coap_str_const_t resource_param = { 0, NULL }, query_pattern = { 0, NULL };
181  int flags = 0; /* MATCH_SUBSTRING, MATCH_PREFIX, MATCH_URI */
182 #define MATCH_URI 0x01
183 #define MATCH_PREFIX 0x02
184 #define MATCH_SUBSTRING 0x04
185  static const coap_str_const_t _rt_attributes[] = {
186  {2, (const uint8_t *)"rt"},
187  {2, (const uint8_t *)"if"},
188  {3, (const uint8_t *)"rel"},
189  {0, NULL}};
190 #endif /* WITHOUT_QUERY_FILTER */
191 
192 #ifndef WITHOUT_QUERY_FILTER
193  /* split query filter, if any */
194  if (query_filter) {
195  resource_param.s = coap_opt_value(query_filter);
196  while (resource_param.length < coap_opt_length(query_filter)
197  && resource_param.s[resource_param.length] != '=')
198  resource_param.length++;
199 
200  if (resource_param.length < coap_opt_length(query_filter)) {
201  const coap_str_const_t *rt_attributes;
202  if (resource_param.length == 4 &&
203  memcmp(resource_param.s, "href", 4) == 0)
204  flags |= MATCH_URI;
205 
206  for (rt_attributes = _rt_attributes; rt_attributes->s; rt_attributes++) {
207  if (resource_param.length == rt_attributes->length &&
208  memcmp(resource_param.s, rt_attributes->s, rt_attributes->length) == 0) {
209  flags |= MATCH_SUBSTRING;
210  break;
211  }
212  }
213 
214  /* rest is query-pattern */
215  query_pattern.s =
216  coap_opt_value(query_filter) + resource_param.length + 1;
217 
218  assert((resource_param.length + 1) <= coap_opt_length(query_filter));
219  query_pattern.length =
220  coap_opt_length(query_filter) - (resource_param.length + 1);
221 
222  if ((query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) {
223  query_pattern.s++;
224  query_pattern.length--;
225  }
226 
227  if (query_pattern.length &&
228  query_pattern.s[query_pattern.length-1] == '*') {
229  query_pattern.length--;
230  flags |= MATCH_PREFIX;
231  }
232  }
233  }
234 #endif /* WITHOUT_QUERY_FILTER */
235 
236  RESOURCES_ITER(context->resources, r) {
237 
238 #ifndef WITHOUT_QUERY_FILTER
239  if (resource_param.length) { /* there is a query filter */
240 
241  if (flags & MATCH_URI) { /* match resource URI */
242  if (!match(r->uri_path, &query_pattern, (flags & MATCH_PREFIX) != 0,
243  (flags & MATCH_SUBSTRING) != 0))
244  continue;
245  } else { /* match attribute */
246  coap_attr_t *attr;
247  coap_str_const_t unquoted_val;
248  attr = coap_find_attr(r, &resource_param);
249  if (!attr || !attr->value) continue;
250  unquoted_val = *attr->value;
251  if (attr->value->s[0] == '"') { /* if attribute has a quoted value, remove double quotes */
252  unquoted_val.length -= 2;
253  unquoted_val.s += 1;
254  }
255  if (!(match(&unquoted_val, &query_pattern,
256  (flags & MATCH_PREFIX) != 0,
257  (flags & MATCH_SUBSTRING) != 0)))
258  continue;
259  }
260  }
261 #endif /* WITHOUT_QUERY_FILTER */
262 
263  if (!subsequent_resource) { /* this is the first resource */
264  subsequent_resource = 1;
265  } else {
266  PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written);
267  }
268 
269  left = bufend - p; /* calculate available space */
270  result = coap_print_link(r, p, &left, &offset);
271 
272  if (result & COAP_PRINT_STATUS_ERROR) {
273  break;
274  }
275 
276  /* coap_print_link() returns the number of characters that
277  * where actually written to p. Now advance to its end. */
278  p += COAP_PRINT_OUTPUT_LENGTH(result);
279  written += left;
280  }
281 
282  *buflen = written;
283  output_length = p - buf;
284 
285  if (output_length > COAP_PRINT_STATUS_MAX) {
287  }
288 
289  result = (coap_print_status_t)output_length;
290 
291  if (result + old_offset - offset < *buflen) {
292  result |= COAP_PRINT_STATUS_TRUNC;
293  }
294  return result;
295 }
296 
297 static coap_str_const_t null_path_value = {0, (const uint8_t*)""};
299 
301 coap_resource_init(coap_str_const_t *uri_path, int flags) {
302  coap_resource_t *r;
303 
305  if (r) {
306  memset(r, 0, sizeof(coap_resource_t));
307 
308  if (!(flags & COAP_RESOURCE_FLAGS_RELEASE_URI)) {
309  /* Need to take a copy if caller is not providing a release request */
310  if (uri_path)
311  uri_path = coap_new_str_const(uri_path->s, uri_path->length);
312  else
314  }
315  else if (!uri_path) {
316  /* Do not expecte this, but ... */
318  }
319 
320  if (uri_path)
321  r->uri_path = uri_path;
322 
323  r->flags = flags;
324  } else {
325  coap_log(LOG_DEBUG, "coap_resource_init: no memory left\n");
326  }
327 
328  return r;
329 }
330 
332  "- Unknown -";
333 
336  coap_resource_t *r;
337 
339  if (r) {
340  memset(r, 0, sizeof(coap_resource_t));
341  r->is_unknown = 1;
342  /* Something unlikely to be used, but it shows up in the logs */
344  coap_register_handler(r, COAP_REQUEST_PUT, put_handler);
345  } else {
346  coap_log(LOG_DEBUG, "coap_resource_unknown_init: no memory left\n");
347  }
348 
349  return r;
350 }
351 
353  "- Proxy URI -";
354 
357  size_t host_name_count, const char *host_name_list[]) {
358  coap_resource_t *r;
359 
360  if (host_name_count == 0) {
362  "coap_resource_proxy_uri_init: Must have one or more host names defined\n");
363  return NULL;
364  }
366  if (r) {
367  size_t i;
368  memset(r, 0, sizeof(coap_resource_t));
369  r->is_proxy_uri = 1;
370  /* Something unlikely to be used, but it shows up in the logs */
372  /* Preset all the handlers */
373  for (i = 0; i < (sizeof(r->handler) / sizeof(r->handler[0])); i++) {
374  r->handler[i] = handler;
375  }
376  if (host_name_count) {
377  r->proxy_name_list = coap_malloc(host_name_count *
378  sizeof(coap_str_const_t*));
379  if (r->proxy_name_list) {
380  for (i = 0; i < host_name_count; i++) {
381  r->proxy_name_list[i] =
382  coap_new_str_const((const uint8_t*)host_name_list[i],
383  strlen(host_name_list[i]));
384  if (!r->proxy_name_list[i]) {
386  "coap_resource_proxy_uri_init: unable to add host name\n");
387  if (i == 0) {
389  r->proxy_name_list = NULL;
390  }
391  break;
392  }
393  }
394  r->proxy_name_count = i;
395  }
396  }
397  } else {
398  coap_log(LOG_DEBUG, "coap_resource_proxy_uri_init: no memory left\n");
399  }
400 
401  return r;
402 }
403 
404 coap_attr_t *
406  coap_str_const_t *name,
407  coap_str_const_t *val,
408  int flags) {
409  coap_attr_t *attr;
410 
411  if (!resource || !name)
412  return NULL;
413 
415 
416  if (attr) {
417  if (!(flags & COAP_ATTR_FLAGS_RELEASE_NAME)) {
418  /* Need to take a copy if caller is not providing a release request */
419  name = coap_new_str_const(name->s, name->length);
420  }
421  attr->name = name;
422  if (val) {
423  if (!(flags & COAP_ATTR_FLAGS_RELEASE_VALUE)) {
424  /* Need to take a copy if caller is not providing a release request */
425  val = coap_new_str_const(val->s, val->length);
426  }
427  }
428  attr->value = val;
429 
430  attr->flags = flags;
431 
432  /* add attribute to resource list */
433  LL_PREPEND(resource->link_attr, attr);
434  } else {
435  coap_log(LOG_DEBUG, "coap_add_attr: no memory left\n");
436  }
437 
438  return attr;
439 }
440 
441 coap_attr_t *
443  coap_str_const_t *name) {
444  coap_attr_t *attr;
445 
446  if (!resource || !name)
447  return NULL;
448 
449  LL_FOREACH(resource->link_attr, attr) {
450  if (attr->name->length == name->length &&
451  memcmp(attr->name->s, name->s, name->length) == 0)
452  return attr;
453  }
454 
455  return NULL;
456 }
457 
458 void
460  if (!attr)
461  return;
463  if (attr->value) {
465  }
466 
467 #ifdef WITH_LWIP
468  memp_free(MEMP_COAP_RESOURCEATTR, attr);
469 #endif
470 #ifndef WITH_LWIP
472 #endif
473 }
474 
479 
480 static void coap_notify_observers(coap_context_t *context, coap_resource_t *r,
481  coap_deleting_resource_t deleting);
482 
483 static void
485  coap_attr_t *attr, *tmp;
486  coap_subscription_t *obs, *otmp;
487 
488  assert(resource);
489 
490  coap_resource_notify_observers(resource, NULL);
492 
493  /* delete registered attributes */
494  LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr);
495 
496  /* Either the application provided or libcoap copied - need to delete it */
497  coap_delete_str_const(resource->uri_path);
498 
499  /* free all elements from resource->subscribers */
500  LL_FOREACH_SAFE( resource->subscribers, obs, otmp ) {
502  if (obs->query)
504  COAP_FREE_TYPE( subscription, obs );
505  }
506  if (resource->proxy_name_count && resource->proxy_name_list) {
507  size_t i;
508 
509  for (i = 0; i < resource->proxy_name_count; i++) {
511  }
512  coap_free(resource->proxy_name_list);
513  }
514 
515 #ifdef WITH_LWIP
516  memp_free(MEMP_COAP_RESOURCE, resource);
517 #endif
518 #ifndef WITH_LWIP
519  coap_free_type(COAP_RESOURCE, resource);
520 #endif /* WITH_CONTIKI */
521 }
522 
523 void
525  if (resource->is_unknown) {
526  if (context->unknown_resource)
528  context->unknown_resource = resource;
529  }
530  else if (resource->is_proxy_uri) {
531  if (context->proxy_uri_resource)
533  context->proxy_uri_resource = resource;
534  }
535  else {
537  resource->uri_path);
538 
539  if (r) {
541  "coap_add_resource: Duplicate uri_path '%*.*s', old resource deleted\n",
542  (int)resource->uri_path->length, (int)resource->uri_path->length,
543  resource->uri_path->s);
544  coap_delete_resource(context, r);
545  }
546  RESOURCES_ADD(context->resources, resource);
547  }
548  assert(resource->context == NULL);
549  resource->context = context;
550 }
551 
552 int
554  if (!context || !resource)
555  return 0;
556 
557  if (resource->is_unknown && (context->unknown_resource == resource)) {
559  context->unknown_resource = NULL;
560  return 1;
561  }
562  if (resource->is_proxy_uri && (context->proxy_uri_resource == resource)) {
564  context->proxy_uri_resource = NULL;
565  return 1;
566  }
567 
568  /* remove resource from list */
569  RESOURCES_DELETE(context->resources, resource);
570 
571  /* and free its allocated memory */
572  coap_free_resource(resource);
573 
574  return 1;
575 }
576 
577 void
579  coap_resource_t *res;
580  coap_resource_t *rtmp;
581 
582  /* Cannot call RESOURCES_ITER because coap_free_resource() releases
583  * the allocated storage. */
584 
585  HASH_ITER(hh, context->resources, res, rtmp) {
586  HASH_DELETE(hh, context->resources, res);
587  coap_free_resource(res);
588  }
589 
590  context->resources = NULL;
591 
592  if (context->unknown_resource) {
594  context->unknown_resource = NULL;
595  }
596  if (context->proxy_uri_resource) {
598  context->proxy_uri_resource = NULL;
599  }
600 }
601 
604  coap_resource_t *result;
605 
606  RESOURCES_FIND(context->resources, uri_path, result);
607 
608  return result;
609 }
610 
613  unsigned char *buf, size_t *len, size_t *offset) {
614  unsigned char *p = buf;
615  const uint8_t *bufend = buf + *len;
616  coap_attr_t *attr;
617  coap_print_status_t result = 0;
618  size_t output_length = 0;
619  const size_t old_offset = *offset;
620 
621  *len = 0;
622  PRINT_COND_WITH_OFFSET(p, bufend, *offset, '<', *len);
623  PRINT_COND_WITH_OFFSET(p, bufend, *offset, '/', *len);
624 
625  COPY_COND_WITH_OFFSET(p, bufend, *offset,
626  resource->uri_path->s, resource->uri_path->length, *len);
627 
628  PRINT_COND_WITH_OFFSET(p, bufend, *offset, '>', *len);
629 
630  LL_FOREACH(resource->link_attr, attr) {
631 
632  PRINT_COND_WITH_OFFSET(p, bufend, *offset, ';', *len);
633 
634  COPY_COND_WITH_OFFSET(p, bufend, *offset,
635  attr->name->s, attr->name->length, *len);
636 
637  if (attr->value && attr->value->s) {
638  PRINT_COND_WITH_OFFSET(p, bufend, *offset, '=', *len);
639 
640  COPY_COND_WITH_OFFSET(p, bufend, *offset,
641  attr->value->s, attr->value->length, *len);
642  }
643 
644  }
645  if (resource->observable) {
646  COPY_COND_WITH_OFFSET(p, bufend, *offset, ";obs", 4, *len);
647  }
648 
649  output_length = p - buf;
650 
651  if (output_length > COAP_PRINT_STATUS_MAX) {
653  }
654 
655  result = (coap_print_status_t)output_length;
656 
657  if (result + old_offset - *offset < *len) {
658  result |= COAP_PRINT_STATUS_TRUNC;
659  }
660 
661  return result;
662 }
663 
664 void
666  coap_request_t method,
667  coap_method_handler_t handler) {
668  assert(resource);
669  assert(method > 0 && (size_t)(method-1) < sizeof(resource->handler)/sizeof(coap_method_handler_t));
670  resource->handler[method-1] = handler;
671 }
672 
673 #ifndef WITHOUT_OBSERVE
676  const coap_binary_t *token) {
678 
679  assert(resource);
680  assert(session);
681 
682  LL_FOREACH(resource->subscribers, s) {
683  if (s->session == session
684  && (!token || (token->length == s->token_length
685  && memcmp(token->s, s->token, token->length) == 0)))
686  return s;
687  }
688 
689  return NULL;
690 }
691 
692 static coap_subscription_t *
694  const coap_string_t *query) {
696 
697  assert(resource);
698  assert(session);
699 
700  LL_FOREACH(resource->subscribers, s) {
701  if (s->session == session
702  && ((!query && !s->query)
703  || (query && s->query && coap_string_equal(query, s->query))))
704  return s;
705  }
706 
707  return NULL;
708 }
709 
712  coap_session_t *session,
713  const coap_binary_t *token,
714  coap_string_t *query,
715  int has_block2,
716  coap_block_t block2,
717  uint8_t code) {
719 
720  assert( session );
721 
722  /* Check if there is already a subscription for this peer. */
723  s = coap_find_observer(resource, session, token);
724  if (!s) {
725  /*
726  * Cannot allow a duplicate to be created for the same query as application
727  * may not be cleaning up duplicates. If duplicate found, then original
728  * observer is deleted and a new one created with the new token
729  */
730  s = coap_find_observer_query(resource, session, query);
731  if (s) {
732  /* Delete old entry with old token */
733  coap_binary_t tmp_token = { s->token_length, s->token };
734  coap_delete_observer(resource, session, &tmp_token);
735  s = NULL;
736  }
737  }
738 
739  /* We are done if subscription was found. */
740  if (s) {
741  if (s->query)
743  s->query = query;
744  s->code = code;
745  return s;
746  }
747 
748  /* Create a new subscription */
749  s = COAP_MALLOC_TYPE(subscription);
750 
751  if (!s) {
752  /* query is not deleted so it can be used in the calling function
753  * which must give up ownership of query only if this function
754  * does not return NULL. */
755  return NULL;
756  }
757 
759  s->session = coap_session_reference( session );
760 
761  if (token && token->length) {
762  s->token_length = token->length;
763  memcpy(s->token, token->s, min(s->token_length, 8));
764  }
765 
766  s->query = query;
767 
768  s->has_block2 = has_block2;
769  s->block2 = block2;
770 
771  s->code = code;
772 
773  /* add subscriber to resource */
774  LL_PREPEND(resource->subscribers, s);
775 
776  coap_log(LOG_DEBUG, "create new subscription\n");
777 
778  return s;
779 }
780 
781 void
783  const coap_binary_t *token) {
785 
786  RESOURCES_ITER(context->resources, r) {
787  s = coap_find_observer(r, session, token);
788  if (s) {
789  s->fail_cnt = 0;
790  }
791  }
792 }
793 
794 int
796  const coap_binary_t *token) {
798 
799  s = coap_find_observer(resource, session, token);
800 
801  if ( s && coap_get_log_level() >= LOG_DEBUG ) {
802  char outbuf[2 * 8 + 1] = "";
803  unsigned int i;
804  for ( i = 0; i < s->token_length; i++ )
805  snprintf( &outbuf[2 * i], 3, "%02x", s->token[i] );
806  coap_log(LOG_DEBUG, "removed observer tid %s\n", outbuf);
807  }
808 
809  if (resource->subscribers && s) {
810  LL_DELETE(resource->subscribers, s);
811  coap_session_release( session );
812  if (s->query)
814  COAP_FREE_TYPE(subscription,s);
815  }
816 
817  return s != NULL;
818 }
819 
820 void
822  RESOURCES_ITER(context->resources, resource) {
823  coap_subscription_t *s, *tmp;
824  LL_FOREACH_SAFE(resource->subscribers, s, tmp) {
825  if (s->session == session) {
826  LL_DELETE(resource->subscribers, s);
827  coap_session_release(session);
828  if (s->query)
830  COAP_FREE_TYPE(subscription, s);
831  }
832  }
833  }
834 }
835 
836 static void
838  coap_deleting_resource_t deleting) {
840  coap_subscription_t *obs;
841  coap_binary_t token;
842  coap_pdu_t *response;
843 
844  if (r->observable && (r->dirty || r->partiallydirty)) {
845  r->partiallydirty = 0;
846 
847  LL_FOREACH(r->subscribers, obs) {
848  if (r->dirty == 0 && obs->dirty == 0) {
849  /*
850  * running this resource due to partiallydirty, but this observation's
851  * notification was already enqueued
852  */
853  context->observe_pending = 1;
854  continue;
855  }
856  if (obs->session->con_active >= COAP_DEFAULT_NSTART &&
858  (obs->non_cnt >= COAP_OBS_MAX_NON))) {
859  r->partiallydirty = 1;
860  obs->dirty = 1;
861  context->observe_pending = 1;
862  continue;
863  }
864 
866  obs->dirty = 0;
867  /* initialize response */
869  if (!response) {
870  obs->dirty = 1;
871  r->partiallydirty = 1;
872  context->observe_pending = 1;
874  "coap_check_notify: pdu init failed, resource stays "
875  "partially dirty\n");
876  continue;
877  }
878 
879  if (!coap_add_token(response, obs->token_length, obs->token)) {
880  obs->dirty = 1;
881  r->partiallydirty = 1;
882  context->observe_pending = 1;
884  "coap_check_notify: cannot add token, resource stays "
885  "partially dirty\n");
886  coap_delete_pdu(response);
887  continue;
888  }
889 
890  token.length = obs->token_length;
891  token.s = obs->token;
892 
893  obs->tid = response->tid = coap_new_message_id(obs->session);
894  if ((r->flags & COAP_RESOURCE_FLAGS_NOTIFY_CON) == 0 &&
896  obs->non_cnt < COAP_OBS_MAX_NON)) {
897  response->type = COAP_MESSAGE_NON;
898  } else {
899  response->type = COAP_MESSAGE_CON;
900  }
901  switch (deleting) {
903  /* fill with observer-specific data */
904 
905  h = r->handler[obs->code - 1];
906  assert(h); /* we do not allow subscriptions if no
907  * GET/FETCH handler is defined */
908  h(context, r, obs->session, NULL, &token, obs->query, response);
909  break;
911  default:
912  response->code = COAP_RESPONSE_CODE(404);
913  break;
914  }
915 
916  /* TODO: do not send response and remove observer when
917  * COAP_RESPONSE_CLASS(response->hdr->code) > 2
918  */
919  if (response->type == COAP_MESSAGE_CON ||
921  obs->non_cnt = 0;
922  } else {
923  obs->non_cnt++;
924  }
925 
926  tid = coap_send( obs->session, response );
927 
928  if (COAP_INVALID_TID == tid) {
930  "coap_check_notify: sending failed, resource stays "
931  "partially dirty\n");
932  obs->dirty = 1;
933  r->partiallydirty = 1;
934  context->observe_pending = 1;
935  }
936 
937  }
938  }
939  r->dirty = 0;
940 }
941 
942 int
944  return coap_resource_notify_observers(r, query);
945 }
946 
947 int
949  if (!r->observable)
950  return 0;
951  if (query) {
952  coap_subscription_t *obs;
953  int found = 0;
954  LL_FOREACH(r->subscribers, obs) {
955  if (obs->query
956  && obs->query->length==query->length
957  && memcmp(obs->query->s, query->s, query->length)==0 ) {
958  found = 1;
959  if (!r->dirty && !obs->dirty) {
960  obs->dirty = 1;
961  r->partiallydirty = 1;
962  }
963  }
964  }
965  if (!found)
966  return 0;
967  } else {
968  if ( !r->subscribers )
969  return 0;
970  r->dirty = 1;
971  }
972 
973  /* Increment value for next Observe use. Observe value must be < 2^24 */
974  r->observe = (r->observe + 1) & 0xFFFFFF;
975 
976  assert(r->context);
977  r->context->observe_pending = 1;
978 #ifdef COAP_EPOLL_SUPPORT
979  if (r->context->eptimerfd != -1) {
980  /* Need to immediately trigger any epoll_wait() */
981  struct itimerspec new_value;
982  int ret;
983 
984  memset(&new_value, 0, sizeof(new_value));
985  new_value.it_value.tv_nsec = 1; /* small that is not zero */
986  ret = timerfd_settime(r->context->eptimerfd, 0, &new_value, NULL);
987  if (ret == -1) {
989  "%s: timerfd_settime failed: %s (%d)\n",
990  "coap_resource_notify_observers",
991  coap_socket_strerror(), errno);
992  }
993  }
994 #endif /* COAP_EPOLL_SUPPORT */
995  return 1;
996 }
997 
998 void
1000 
1001  if (context->observe_pending) {
1002  context->observe_pending = 0;
1003  RESOURCES_ITER(context->resources, r) {
1005  }
1006  }
1007 }
1008 
1019 static void
1021  coap_resource_t *resource,
1022  coap_session_t *session,
1023  const coap_binary_t *token) {
1024  coap_subscription_t *obs, *otmp;
1025 
1026  LL_FOREACH_SAFE(resource->subscribers, obs, otmp) {
1027  if ( obs->session == session &&
1028  token->length == obs->token_length &&
1029  memcmp(token->s, obs->token, token->length) == 0) {
1030 
1031  /* count failed notifies and remove when
1032  * COAP_MAX_FAILED_NOTIFY is reached */
1033  if (obs->fail_cnt < COAP_OBS_MAX_FAIL)
1034  obs->fail_cnt++;
1035  else {
1036  LL_DELETE(resource->subscribers, obs);
1037  obs->fail_cnt = 0;
1038 
1039  if (LOG_DEBUG <= coap_get_log_level()) {
1040 #ifndef INET6_ADDRSTRLEN
1041 #define INET6_ADDRSTRLEN 40
1042 #endif
1043  unsigned char addr[INET6_ADDRSTRLEN+8];
1044 
1046  addr, INET6_ADDRSTRLEN+8))
1047  coap_log(LOG_DEBUG, "** removed observer %s\n", addr);
1048  }
1049  coap_cancel_all_messages(context, obs->session,
1050  obs->token, obs->token_length);
1051  coap_session_release( obs->session );
1052  if (obs->query)
1053  coap_delete_string(obs->query);
1054  COAP_FREE_TYPE(subscription, obs);
1055  }
1056  break; /* break loop if observer was found */
1057  }
1058  }
1059 }
1060 
1061 void
1063  coap_session_t *session,
1064  const coap_binary_t *token) {
1065 
1066  RESOURCES_ITER(context->resources, r) {
1067  coap_remove_failed_observers(context, r, session, token);
1068  }
1069 }
1070 #endif /* WITHOUT_NOTIFY */
Pulls together all the internal only header files.
const char * coap_socket_strerror(void)
Definition: coap_io.c:1459
size_t coap_session_max_pdu_size(const coap_session_t *session)
Get maximum acceptable PDU size.
Definition: coap_session.c:209
coap_session_t * coap_session_reference(coap_session_t *session)
Increment reference counter on a session.
Definition: coap_session.c:68
void coap_session_release(coap_session_t *session)
Decrement reference counter on a session.
Definition: coap_session.c:74
#define COAP_DEFAULT_NSTART
The number of simultaneous outstanding interactions that a client maintains to a given server.
Definition: coap_session.h:477
coap_resource_t * coap_resource_proxy_uri_init(coap_method_handler_t handler, size_t host_name_count, const char *host_name_list[])
Creates a new resource object for handling proxy URIs.
Definition: resource.c:356
void(* coap_method_handler_t)(coap_context_t *, struct coap_resource_t *, coap_session_t *, coap_pdu_t *, coap_binary_t *, coap_string_t *, coap_pdu_t *)
Definition of message handler function.
Definition: resource.h:41
#define COAP_ATTR_FLAGS_RELEASE_VALUE
Definition: resource.h:50
coap_print_status_t coap_print_link(const coap_resource_t *resource, unsigned char *buf, size_t *len, size_t *offset)
Writes a description of this resource in link-format to given text buffer.
Definition: resource.c:612
#define COAP_RESOURCE_FLAGS_NOTIFY_NON_ALWAYS
Notifications will always be sent non-confirmable.
Definition: resource.h:83
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
Definition: resource.c:578
#define COAP_ATTR_FLAGS_RELEASE_NAME
Definition: resource.h:49
void coap_delete_attr(coap_attr_t *attr)
Deletes an attribute.
Definition: resource.c:459
#define COAP_PRINT_STATUS_TRUNC
Definition: resource.h:368
#define COAP_RESOURCE_FLAGS_NOTIFY_CON
Notifications will be sent confirmable.
Definition: resource.h:73
void coap_register_handler(coap_resource_t *resource, coap_request_t method, coap_method_handler_t handler)
Registers the specified handler as message handler for the request type method.
Definition: resource.c:665
coap_resource_t * coap_resource_unknown_init(coap_method_handler_t put_handler)
Creates a new resource object for the unknown resource handler with support for PUT.
Definition: resource.c:335
coap_attr_t * coap_find_attr(coap_resource_t *resource, coap_str_const_t *name)
Returns resource's coap_attr_t object with given name if found, NULL otherwise.
Definition: resource.c:442
unsigned int coap_print_status_t
Status word to encode the result of conditional print or copy operations such as coap_print_link().
Definition: resource.h:363
coap_resource_t * coap_resource_init(coap_str_const_t *uri_path, int flags)
Creates a new resource object and initializes the link field to the string uri_path.
Definition: resource.c:301
void coap_add_resource(coap_context_t *context, coap_resource_t *resource)
Registers the given resource for context.
Definition: resource.c:524
coap_attr_t * coap_add_attr(coap_resource_t *resource, coap_str_const_t *name, coap_str_const_t *val, int flags)
Registers a new attribute with the given resource.
Definition: resource.c:405
#define COAP_PRINT_STATUS_ERROR
Definition: resource.h:367
#define COAP_PRINT_OUTPUT_LENGTH(v)
Definition: resource.h:366
int coap_delete_resource(coap_context_t *context, coap_resource_t *resource)
Deletes a resource identified by resource.
Definition: resource.c:553
#define COAP_RESOURCE_FLAGS_RELEASE_URI
The URI passed to coap_resource_init() is free'd by coap_delete_resource().
Definition: resource.h:60
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition: coap_debug.c:61
size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len)
Print the address into the defined buffer.
Definition: coap_debug.c:167
#define coap_log(level,...)
Logging function.
Definition: coap_debug.h:150
@ LOG_ERR
Error.
Definition: coap_debug.h:53
@ LOG_WARNING
Warning.
Definition: coap_debug.h:54
@ LOG_DEBUG
Debug.
Definition: coap_debug.h:57
int coap_resource_notify_observers(coap_resource_t *r, const coap_string_t *query)
Initiate the sending of an Observe packet for all observers of resource, optionally matching query if...
Definition: resource.c:948
int coap_delete_observer(coap_resource_t *resource, coap_session_t *session, const coap_binary_t *token)
Removes any subscription for observer from resource and releases the allocated storage.
Definition: resource.c:795
coap_subscription_t * coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_binary_t *token, coap_string_t *query, int has_block2, coap_block_t block2, uint8_t code)
Adds the specified peer as observer for resource.
Definition: resource.c:711
coap_subscription_t * coap_find_observer(coap_resource_t *resource, coap_session_t *session, const coap_binary_t *token)
Returns a subscription object for given peer.
Definition: resource.c:675
void coap_delete_observers(coap_context_t *context, coap_session_t *session)
Removes any subscription for session and releases the allocated storage.
Definition: resource.c:821
void coap_touch_observer(coap_context_t *context, coap_session_t *session, const coap_binary_t *token)
Flags that data is ready to be sent to observers.
Definition: resource.c:782
uint32_t coap_opt_length(const coap_opt_t *opt)
Returns the length of the given option.
Definition: option.c:209
const uint8_t * coap_opt_value(const coap_opt_t *opt)
Returns a pointer to the value of the given option.
Definition: option.c:246
void coap_delete_str_const(coap_str_const_t *s)
Deletes the given const string and releases any memory allocated.
Definition: str.c:51
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition: str.h:178
coap_str_const_t * coap_new_str_const(const uint8_t *data, size_t size)
Returns a new const string object with at least size+1 bytes storage allocated, and the provided data...
Definition: str.c:42
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition: str.c:38
#define COAP_OBS_MAX_NON
Number of notifications that may be sent non-confirmable before a confirmable message is sent to dete...
void coap_subscription_init(coap_subscription_t *s)
Definition: subscribe.c:13
#define COAP_OBS_MAX_FAIL
Number of confirmable notifications that may fail (i.e.
#define COAP_STATIC_INLINE
Definition: libcoap.h:38
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
COAP_STATIC_INLINE void * coap_malloc(size_t size)
Wrapper function to coap_malloc_type() for backwards compatibility.
Definition: mem.h:93
COAP_STATIC_INLINE void coap_free(void *object)
Wrapper function to coap_free_type() for backwards compatibility.
Definition: mem.h:100
@ COAP_RESOURCE
Definition: mem.h:39
@ COAP_RESOURCEATTR
Definition: mem.h:40
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
coap_tid_t coap_send(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition: net.c:1006
void coap_cancel_all_messages(coap_context_t *context, coap_session_t *session, const uint8_t *token, size_t token_length)
Cancels all outstanding messages for session session that have the specified token.
Definition: net.c:1872
COAP_STATIC_INLINE uint16_t coap_new_message_id(coap_session_t *session)
Returns a new message id and updates session->tx_mid accordingly.
Definition: net.h:400
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
Definition: option.h:25
void coap_delete_pdu(coap_pdu_t *pdu)
Dispose of an CoAP PDU and frees associated storage.
Definition: pdu.c:127
coap_pdu_t * coap_pdu_init(uint8_t type, uint8_t code, uint16_t tid, size_t size)
Creates a new CoAP PDU with at least enough storage space for the given size maximum message size.
Definition: pdu.c:79
int coap_add_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds token of length len to pdu.
Definition: pdu.c:191
coap_request_t
Definition: pdu.h:81
@ COAP_REQUEST_PUT
Definition: pdu.h:84
#define COAP_RESPONSE_CODE(N)
Definition: pdu.h:155
#define COAP_MESSAGE_NON
Definition: pdu.h:75
#define COAP_MESSAGE_CON
Definition: pdu.h:74
int coap_tid_t
coap_tid_t is used to store CoAP transaction id, i.e.
Definition: pdu.h:244
#define COAP_INVALID_TID
Indicates an invalid transaction id.
Definition: pdu.h:247
#define MATCH_URI
static const uint8_t coap_unknown_resource_uri[]
Definition: resource.c:331
static const uint8_t coap_proxy_resource_uri[]
Definition: resource.c:352
static void coap_free_resource(coap_resource_t *resource)
Definition: resource.c:484
#define PRINT_COND_WITH_OFFSET(Buf, Bufend, Offset, Char, Result)
Adds Char to Buf if Offset is zero and Buf is less than Bufend.
Definition: resource.c:85
static coap_str_const_t null_path_value
Definition: resource.c:297
int coap_resource_set_dirty(coap_resource_t *r, const coap_string_t *query)
Definition: resource.c:943
coap_resource_t * coap_get_resource_from_uri_path(coap_context_t *context, coap_str_const_t *uri_path)
Returns the resource identified by the unique string uri_path.
Definition: resource.c:603
void coap_check_notify(coap_context_t *context)
Checks for all known resources, if they are dirty and notifies subscribed observers.
Definition: resource.c:999
static int match(const coap_str_const_t *text, const coap_str_const_t *pattern, int match_prefix, int match_substring)
Definition: resource.c:105
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_binary_t *token)
Definition: resource.c:1062
#define MATCH_SUBSTRING
coap_print_status_t coap_print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen, size_t offset, coap_opt_t *query_filter)
Prints the names of all known resources to buf.
Definition: resource.c:169
coap_deleting_resource_t
Definition: resource.c:475
@ COAP_DELETING_RESOURCE
Definition: resource.c:476
@ COAP_NOT_DELETING_RESOURCE
Definition: resource.c:477
static void coap_remove_failed_observers(coap_context_t *context, coap_resource_t *resource, coap_session_t *session, const coap_binary_t *token)
Checks the failure counter for (peer, token) and removes peer from the list of observers for the give...
Definition: resource.c:1020
#define COAP_PRINT_STATUS_MAX
Definition: resource.c:61
#define COAP_MALLOC_TYPE(Type)
Definition: resource.c:56
static coap_subscription_t * coap_find_observer_query(coap_resource_t *resource, coap_session_t *session, const coap_string_t *query)
Definition: resource.c:693
static coap_str_const_t * null_path
Definition: resource.c:298
#define COAP_FREE_TYPE(Type, Object)
Definition: resource.c:58
static void coap_notify_observers(coap_context_t *context, coap_resource_t *r, coap_deleting_resource_t deleting)
Definition: resource.c:837
#define min(a, b)
Definition: resource.c:64
#define MATCH_PREFIX
#define COPY_COND_WITH_OFFSET(Buf, Bufend, Offset, Str, Length, Result)
Copies at most Length characters of Str to Buf.
Definition: resource.c:97
#define INET6_ADDRSTRLEN
#define RESOURCES_ADD(r, obj)
Definition: resource.h:422
#define RESOURCES_FIND(r, k, res)
Definition: resource.h:432
#define RESOURCES_DELETE(r, obj)
Definition: resource.h:425
#define RESOURCES_ITER(r, tmp)
Definition: resource.h:428
coap_address_t remote
remote address and port
Definition: coap_io.h:49
coap_str_const_t * value
Definition: resource.h:55
coap_str_const_t * name
Definition: resource.h:54
int flags
Definition: resource.h:56
CoAP binary data definition.
Definition: str.h:48
size_t length
length of binary data
Definition: str.h:49
uint8_t * s
binary data
Definition: str.h:50
Structure of Block options.
Definition: block.h:33
The CoAP stack's global state is stored in a coap_context_t object.
Definition: net.h:141
struct coap_resource_t * unknown_resource
can be used for handling unknown resources
Definition: net.h:145
int observe_pending
Observe response pending.
Definition: net.h:204
struct coap_resource_t * resources
hash table or list of known resources
Definition: net.h:143
struct coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
Definition: net.h:147
structure for CoAP PDUs token, if any, follows the fixed size header, then options until payload mark...
Definition: pdu.h:287
uint8_t type
message type
Definition: pdu.h:288
uint16_t tid
transaction id, if any, in regular host byte order
Definition: pdu.h:293
uint8_t code
request method (value 1–31) or response code (value 64-255)
Definition: pdu.h:289
unsigned int dirty
set to 1 if resource has changed
Definition: resource.h:86
unsigned int partiallydirty
set to 1 if some subscribers have not yet been notified of the last change
Definition: resource.h:87
coap_subscription_t * subscribers
list of observers for this resource
Definition: resource.h:106
coap_str_const_t ** proxy_name_list
Array valid names this host is known by (proxy support)
Definition: resource.h:135
coap_str_const_t * uri_path
Request URI Path for this resource.
Definition: resource.h:113
unsigned int observe
The next value for the Observe option.
Definition: resource.h:120
coap_context_t * context
Pointer back to the context that 'owns' this resource.
Definition: resource.h:125
coap_method_handler_t handler[7]
Used to store handlers for the seven coap methods GET, POST, PUT, DELETE, FETCH, PATCH and IPATCH.
Definition: resource.h:101
unsigned int is_proxy_uri
resource created for proxy URI handler
Definition: resource.h:92
unsigned int is_unknown
resource created for unknown handler
Definition: resource.h:91
coap_attr_t * link_attr
attributes to be included with the link format
Definition: resource.h:105
unsigned int observable
can be observed
Definition: resource.h:89
size_t proxy_name_count
Count of valid names this host is known by (proxy support)
Definition: resource.h:130
coap_addr_tuple_t addr_info
key: remote/local address info
Definition: coap_session.h:69
uint8_t con_active
Active CON request sent.
Definition: coap_session.h:76
CoAP string data definition with const data.
Definition: str.h:38
const uint8_t * s
read-only string data
Definition: str.h:40
size_t length
length of string
Definition: str.h:39
CoAP string data definition.
Definition: str.h:30
uint8_t * s
string data
Definition: str.h:32
size_t length
length of string
Definition: str.h:31
Subscriber information.
coap_block_t block2
request Block2 definition
unsigned char token[8]
token used for subscription
unsigned int has_block2
request had Block2 definition
unsigned int fail_cnt
up to 3 confirmable notifies can fail
unsigned int non_cnt
up to 15 non-confirmable notifies allowed
size_t token_length
actual length of token
struct coap_session_t * session
subscriber session
unsigned int dirty
set if the notification temporarily could not be sent (in that case, the resource's partially dirty f...
uint16_t tid
request type code (GET/FETCH)
struct coap_string_t * query
query string used for subscription, if any
#define HASH_DELETE(hh, head, delptr)
Definition: uthash.h:368
#define HASH_ITER(hh, head, el, tmp)
Definition: uthash.h:1031
unsigned char uint8_t
Definition: uthash.h:79
#define LL_DELETE(head, del)
Definition: utlist.h:385
#define LL_FOREACH(head, el)
Definition: utlist.h:413
#define LL_PREPEND(head, add)
Definition: utlist.h:314
#define LL_FOREACH_SAFE(head, el, tmp)
Definition: utlist.h:419