libcoap 4.3.5-develop-2ddf01b
Loading...
Searching...
No Matches
coap_resource.c
Go to the documentation of this file.
1/* coap_resource.c -- generic resource handling
2 *
3 * Copyright (C) 2010--2026 Olaf Bergmann <bergmann@tzi.org>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 *
7 * This file is part of the CoAP library libcoap. Please see
8 * README for terms of use.
9 */
10
17
18#if COAP_SERVER_SUPPORT
19#include <stdio.h>
20
21#ifdef COAP_EPOLL_SUPPORT
22#include <sys/epoll.h>
23#include <sys/timerfd.h>
24#endif /* COAP_EPOLL_SUPPORT */
25
26#ifndef min
27#define min(a,b) ((a) < (b) ? (a) : (b))
28#endif
29
30/* Helper functions for conditional output of character sequences into
31 * a given buffer. The first Offset characters are skipped.
32 */
33
38#define PRINT_WITH_OFFSET(Buf,Offset,Char) \
39 if ((Offset) == 0) { \
40 (*(Buf)++) = (Char); \
41 } else { \
42 (Offset)--; \
43 } \
44
48#define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) { \
49 if ((Buf) < (Bufend)) { \
50 PRINT_WITH_OFFSET(Buf,Offset,Char); \
51 } \
52 (Result)++; \
53 }
54
60#define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) { \
61 size_t i; \
62 for (i = 0; i < (Length); i++) { \
63 PRINT_COND_WITH_OFFSET((Buf), (Bufend), (Offset), (Str)[i], (Result)); \
64 } \
65 }
66
67static int
68match(const coap_str_const_t *text, const coap_str_const_t *pattern,
69 int match_prefix, int match_substring) {
70 assert(text);
71 assert(pattern);
72
73 if (text->length < pattern->length || !pattern->s)
74 return 0;
75
76 if (match_substring) {
77 const uint8_t *next_token = text->s;
78 size_t remaining_length = text->length;
79 while (remaining_length) {
80 size_t token_length;
81 const uint8_t *token = next_token;
82 next_token = (unsigned char *)memchr(token, ' ', remaining_length);
83
84 if (next_token) {
85 token_length = next_token - token;
86 remaining_length -= (token_length + 1);
87 next_token++;
88 } else {
89 token_length = remaining_length;
90 remaining_length = 0;
91 }
92
93 if ((match_prefix || pattern->length == token_length) &&
94 memcmp(token, pattern->s, pattern->length) == 0)
95 return 1;
96 }
97 return 0;
98 }
99
100 return (match_prefix || pattern->length == text->length) &&
101 memcmp(text->s, pattern->s, pattern->length) == 0;
102}
103
105coap_print_wellknown(coap_context_t *context, unsigned char *buf,
106 size_t *buflen, size_t offset,
107 const coap_string_t *query_filter) {
108 coap_print_status_t result;
110 result = coap_print_wellknown_lkd(context, buf, buflen, offset, query_filter);
112 return result;
113}
114
115static coap_str_const_t coap_default_uri_wellknown = {
117 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
118};
119
121coap_print_wellknown_lkd(coap_context_t *context, unsigned char *buf,
122 size_t *buflen, size_t offset,
123 const coap_string_t *query_filter) {
124 coap_print_status_t output_length = 0;
125 unsigned char *p = buf;
126 const uint8_t *bufend = buf + *buflen;
127 size_t left, written = 0;
128 coap_print_status_t result;
129 const size_t old_offset = offset;
130 int subsequent_resource = 0;
131#ifdef WITHOUT_QUERY_FILTER
132 (void)query_filter;
133#else
134 coap_str_const_t resource_param = { 0, NULL }, query_pattern = { 0, NULL };
135 int flags = 0; /* MATCH_SUBSTRING, MATCH_PREFIX, MATCH_URI */
136#define MATCH_URI 0x01
137#define MATCH_PREFIX 0x02
138#define MATCH_SUBSTRING 0x04
139 static const coap_str_const_t _rt_attributes[] = {
140 {2, (const uint8_t *)"rt"},
141 {2, (const uint8_t *)"if"},
142 {3, (const uint8_t *)"rel"},
143 {0, NULL}
144 };
145#endif /* WITHOUT_QUERY_FILTER */
146
148#ifndef WITHOUT_QUERY_FILTER
149 /* split query filter, if any */
150 if (query_filter) {
151 resource_param.s = query_filter->s;
152 while (resource_param.length < query_filter->length &&
153 resource_param.s[resource_param.length] != '=')
154 resource_param.length++;
155
156 if (resource_param.length < query_filter->length) {
157 const coap_str_const_t *rt_attributes;
158 if (resource_param.length == 4 &&
159 memcmp(resource_param.s, "href", 4) == 0)
160 flags |= MATCH_URI;
161
162 for (rt_attributes = _rt_attributes; rt_attributes->s; rt_attributes++) {
163 if (resource_param.length == rt_attributes->length &&
164 memcmp(resource_param.s, rt_attributes->s, rt_attributes->length) == 0) {
165 flags |= MATCH_SUBSTRING;
166 break;
167 }
168 }
169
170 /* rest is query-pattern */
171 query_pattern.s =
172 query_filter->s + resource_param.length + 1;
173
174 assert((resource_param.length + 1) <= query_filter->length);
175 query_pattern.length =
176 query_filter->length - (resource_param.length + 1);
177
178 if ((query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) {
179 query_pattern.s++;
180 query_pattern.length--;
181 }
182
183 if (query_pattern.length &&
184 query_pattern.s[query_pattern.length-1] == '*') {
185 query_pattern.length--;
186 flags |= MATCH_PREFIX;
187 }
188 }
189 }
190#endif /* WITHOUT_QUERY_FILTER */
191
192 RESOURCES_ITER(context->resources, r) {
193
194 if (coap_string_equal(r->uri_path, &coap_default_uri_wellknown)) {
195 /* server app has defined a resource for .well-known/core - ignore */
196 continue;
197 }
198 if (r->flags & COAP_RESOURCE_HIDE_WELLKNOWN_CORE) {
199 continue;
200 }
201#ifndef WITHOUT_QUERY_FILTER
202 if (resource_param.length) { /* there is a query filter */
203
204 if (flags & MATCH_URI) { /* match resource URI */
205 if (!match(r->uri_path, &query_pattern, (flags & MATCH_PREFIX) != 0,
206 (flags & MATCH_SUBSTRING) != 0))
207 continue;
208 } else { /* match attribute */
209 coap_attr_t *attr;
210 coap_str_const_t unquoted_val;
211 attr = coap_find_attr(r, &resource_param);
212 if (!attr || !attr->value)
213 continue;
214 unquoted_val = *attr->value;
215 if (attr->value->s[0] == '"') { /* if attribute has a quoted value, remove double quotes */
216 unquoted_val.length -= 2;
217 unquoted_val.s += 1;
218 }
219 if (!(match(&unquoted_val, &query_pattern,
220 (flags & MATCH_PREFIX) != 0,
221 (flags & MATCH_SUBSTRING) != 0)))
222 continue;
223 }
224 }
225#endif /* WITHOUT_QUERY_FILTER */
226
227 if (!subsequent_resource) { /* this is the first resource */
228 subsequent_resource = 1;
229 } else {
230 PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written);
231 }
232
233 left = bufend - p; /* calculate available space */
234 result = coap_print_link(r, p, &left, &offset);
235
236 if (result & COAP_PRINT_STATUS_ERROR) {
237 break;
238 }
239
240 /* coap_print_link() returns the number of characters that
241 * where actually written to p. Now advance to its end. */
242 p += COAP_PRINT_OUTPUT_LENGTH(result);
243 written += left;
244 }
245
246 *buflen = written;
247 output_length = (coap_print_status_t)(p - buf);
248
249 if (output_length > COAP_PRINT_STATUS_MAX) {
251 }
252
253 result = (coap_print_status_t)output_length;
254
255 if (result + old_offset - offset < *buflen) {
256 result |= COAP_PRINT_STATUS_TRUNC;
257 }
258 return result;
259}
260
261static coap_str_const_t null_path_value = {0, (const uint8_t *)""};
262static coap_str_const_t *null_path = &null_path_value;
263
265coap_resource_init(coap_str_const_t *uri_path, int flags) {
267
269 if (r) {
270 memset(r, 0, sizeof(coap_resource_t));
271 r->ref = 1;
272
273 if (!(flags & COAP_RESOURCE_FLAGS_RELEASE_URI)) {
274 /* Need to take a copy if caller is not providing a release request */
275 if (uri_path)
276 uri_path = coap_new_str_const(uri_path->s, uri_path->length);
277 else
278 uri_path = coap_new_str_const(null_path->s, null_path->length);
279 } else if (!uri_path) {
280 /* Do not expect this, but ... */
281 uri_path = coap_new_str_const(null_path->s, null_path->length);
282 }
283
284 if (uri_path)
285 r->uri_path = uri_path;
286
287 r->flags = flags;
288 r->observe = 2;
289 } else {
290 coap_log_debug("coap_resource_init: no memory left\n");
291 }
292
293 return r;
294}
295
296static const uint8_t coap_unknown_resource_uri[] =
297 "- Unknown -";
298
302
304 if (r) {
305 memset(r, 0, sizeof(coap_resource_t));
306 r->ref = 1;
307 r->is_unknown = 1;
308 /* Something unlikely to be used, but it shows up in the logs */
309 r->uri_path = coap_new_str_const(coap_unknown_resource_uri, sizeof(coap_unknown_resource_uri)-1);
310 r->flags = flags & ~COAP_RESOURCE_FLAGS_RELEASE_URI;
312 } else {
313 coap_log_debug("coap_resource_unknown_init2: no memory left\n");
314 }
315
316 return r;
317}
318
321 return coap_resource_unknown_init2(put_handler, 0);
322}
323
324static const uint8_t coap_proxy_resource_uri[] =
325 "- Proxy URI -";
326
329 size_t host_name_count,
330 const char *host_name_list[], int flags) {
332
334 if (r) {
335 size_t i;
336 memset(r, 0, sizeof(coap_resource_t));
337 r->ref = 1;
338 r->is_proxy_uri = 1;
339 /* Something unlikely to be used, but it shows up in the logs */
340 r->uri_path = coap_new_str_const(coap_proxy_resource_uri, sizeof(coap_proxy_resource_uri)-1);
341 /* Preset all the handlers */
342 for (i = 0; i < (sizeof(r->handler) / sizeof(r->handler[0])); i++) {
343 r->handler[i] = handler;
344 }
345 if (host_name_count) {
346 r->proxy_name_list = coap_malloc_type(COAP_STRING, host_name_count *
347 sizeof(coap_str_const_t *));
348 if (r->proxy_name_list) {
349 for (i = 0; i < host_name_count; i++) {
350 r->proxy_name_list[i] =
351 coap_new_str_const((const uint8_t *)host_name_list[i],
352 strlen(host_name_list[i]));
353 if (!r->proxy_name_list[i]) {
354 coap_log_err("coap_resource_proxy_uri_init: unable to add host name\n");
355 if (i == 0) {
357 r->proxy_name_list = NULL;
358 }
359 break;
360 }
361 }
362 r->proxy_name_count = i;
363 }
364 }
365 r->flags = flags & ~COAP_RESOURCE_FLAGS_RELEASE_URI;
366 } else {
367 coap_log_debug("coap_resource_proxy_uri_init2: no memory left\n");
368 }
369
370 return r;
371}
372
375 size_t host_name_count, const char *host_name_list[]) {
376 return coap_resource_proxy_uri_init2(handler, host_name_count,
377 host_name_list, 0);
378}
379
380static const uint8_t coap_rev_proxy_resource_uri[] =
381 "- Rev Proxy -";
382
386
388 if (r) {
389 memset(r, 0, sizeof(coap_resource_t));
390 r->ref = 1;
391 r->is_unknown = 1;
392 r->is_reverse_proxy = 1;
393 /* Something unlikely to be used, but it shows up in the logs */
394 r->uri_path = coap_new_str_const(coap_rev_proxy_resource_uri,
395 sizeof(coap_rev_proxy_resource_uri)-1);
396 r->flags = flags & ~COAP_RESOURCE_FLAGS_RELEASE_URI;
405 } else {
406 coap_log_debug("coap_resource_rev_proxy_init: no memory left\n");
407 }
408
409 return r;
410}
411
414 coap_str_const_t *name,
415 coap_str_const_t *val,
416 int flags) {
417 coap_attr_t *attr;
418
419 if (!resource || !name)
420 return NULL;
422
423 if (attr) {
424 if (!(flags & COAP_ATTR_FLAGS_RELEASE_NAME)) {
425 /* Need to take a copy if caller is not providing a release request */
426 name = coap_new_str_const(name->s, name->length);
427 }
428 attr->name = name;
429 if (val) {
430 if (!(flags & COAP_ATTR_FLAGS_RELEASE_VALUE)) {
431 /* Need to take a copy if caller is not providing a release request */
432 val = coap_new_str_const(val->s, val->length);
433 }
434 }
435 attr->value = val;
436
437 attr->flags = flags;
438
439 /* add attribute to resource list */
440 LL_PREPEND(resource->link_attr, attr);
441 } else {
442 coap_log_debug("coap_add_attr: no memory left\n");
443 }
444
445 return attr;
446}
447
450 coap_str_const_t *name) {
451 coap_attr_t *attr;
452
453 if (!resource || !name)
454 return NULL;
455
456 LL_FOREACH(resource->link_attr, attr) {
457 if (attr->name->length == name->length &&
458 memcmp(attr->name->s, name->s, name->length) == 0)
459 return attr;
460 }
461
462 return NULL;
463}
464
467 if (attr)
468 return attr->value;
469 return NULL;
470}
471
472void
474 if (!attr)
475 return;
477 if (attr->value) {
479 }
480
482}
483
484typedef enum coap_deleting_resource_t {
485 COAP_DELETING_RESOURCE,
486 COAP_NOT_DELETING_RESOURCE,
487 COAP_DELETING_RESOURCE_ON_EXIT
488} coap_deleting_resource_t;
489
490static void coap_notify_observers(coap_context_t *context, coap_resource_t *r,
491 coap_deleting_resource_t deleting);
492
493static void
494coap_free_resource(coap_resource_t *resource, coap_deleting_resource_t deleting) {
495 coap_attr_t *attr, *tmp;
496 coap_subscription_t *obs, *otmp;
497
498 assert(resource);
499
500 if (!resource->context->observe_no_clear) {
502 coap_notify_observers(resource->context, resource, deleting);
503 }
504
505 if (resource->context->resource_deleted_cb)
507 resource->uri_path,
508 resource->context->observe_user_data));
509
510 if (resource->context->release_userdata_cb && resource->user_data) {
512 }
513
514 /* delete registered attributes */
515 LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr);
516
517 /* Either the application provided or libcoap copied - need to delete it */
519
520 /* free all elements from resource->subscribers */
521 LL_FOREACH_SAFE(resource->subscribers, obs, otmp) {
522 coap_delete_observer_internal(resource, obs->session, obs);
523 }
525}
526
527void
529
530#ifndef __COVERITY__
531 assert(resource->ref);
532 resource->ref--;
533 if (resource->ref)
534 return;
535
536 if (resource->proxy_name_count && resource->proxy_name_list) {
537 size_t i;
538
539 for (i = 0; i < resource->proxy_name_count; i++) {
541 }
543 }
544
545 coap_free_type(COAP_RESOURCE, resource);
546#else /* __COVERITY__ */
547 /* Coverity scan is fooled by the reference counter leading to
548 * false positives for USE_AFTER_FREE. */
549 --resource->ref;
550 __coverity_negative_sink__(resource->ref);
551 /* Indicate that resources are released properly. */
552 __coverity_free__(resource);
553#endif /* __COVERITY__ */
554}
555
556COAP_API void
558 coap_lock_lock(return);
559 coap_add_resource_lkd(context, resource);
561}
562
563void
566 if (resource->is_unknown) {
567 if (context->unknown_resource)
568 coap_free_resource(context->unknown_resource, COAP_DELETING_RESOURCE);
569 context->unknown_resource = resource;
570 } else if (resource->is_proxy_uri) {
571 if (context->proxy_uri_resource)
572 coap_free_resource(context->proxy_uri_resource, COAP_DELETING_RESOURCE);
573 context->proxy_uri_resource = resource;
574 } else {
576 resource->uri_path);
577
578 if (r) {
579 coap_log_warn("coap_add_resource: Duplicate uri_path '%*.*s', old resource deleted\n",
580 (int)resource->uri_path->length, (int)resource->uri_path->length,
581 resource->uri_path->s);
582 coap_delete_resource_lkd(context, r);
583 }
584 RESOURCES_ADD(context->resources, resource);
585#if COAP_WITH_OBSERVE_PERSIST
586 if (context->unknown_pdu && context->dyn_resource_save_file &&
587 context->dyn_resource_added_cb && resource->observable) {
588 coap_bin_const_t raw_packet;
589
590 raw_packet.s = context->unknown_pdu->token -
591 context->unknown_pdu->hdr_size;
592 raw_packet.length = context->unknown_pdu->used_size +
593 context->unknown_pdu->hdr_size;
594 coap_lock_callback(context->dyn_resource_added_cb(context->unknown_session,
595 resource->uri_path,
596 &raw_packet,
597 context->observe_user_data));
598 }
599#endif /* COAP_WITH_OBSERVE_PERSIST */
600 }
601 assert(resource->context == NULL);
602 resource->context = context;
603}
604
605COAP_API int
607 int ret;
608
609 if (!resource)
610 return 0;
611
612 context = resource->context;
613 coap_lock_lock(return 0);
614 ret = coap_delete_resource_lkd(context, resource);
616 return ret;
617}
618
619/*
620 * Input context is ignored, but param left there to keep API consistent
621 */
622int
624 (void)context;
625
626 if (!resource)
627 return 0;
628
630
631 if (resource->is_unknown) {
632 if (context && context->unknown_resource == resource) {
633 context->unknown_resource = NULL;
634 }
635 } else if (resource->is_proxy_uri) {
636 if (context && context->proxy_uri_resource == resource) {
637 context->proxy_uri_resource = NULL;
638 }
639 } else if (context) {
640 /* remove resource from list */
641 RESOURCES_DELETE(context->resources, resource);
642 }
643 if (resource->is_dynamic) {
644 if (context) {
645 assert(context->dynamic_cur);
646 context->dynamic_cur--;
647 }
648 }
649
650 /* and free its allocated memory */
651 coap_free_resource(resource, COAP_DELETING_RESOURCE);
652
653 return 1;
654}
655
656void
658 coap_resource_t *res;
659 coap_resource_t *rtmp;
660
661 /* Cannot call RESOURCES_ITER because coap_free_resource() releases
662 * the allocated storage. */
663
664 HASH_ITER(hh, context->resources, res, rtmp) {
665 HASH_DELETE(hh, context->resources, res);
666 coap_free_resource(res, COAP_DELETING_RESOURCE_ON_EXIT);
667 }
668
669 context->resources = NULL;
670
671 if (context->unknown_resource) {
672 coap_free_resource(context->unknown_resource, COAP_DELETING_RESOURCE_ON_EXIT);
673 context->unknown_resource = NULL;
674 }
675 if (context->proxy_uri_resource) {
676 coap_free_resource(context->proxy_uri_resource, COAP_DELETING_RESOURCE_ON_EXIT);
677 context->proxy_uri_resource = NULL;
678 }
679}
680
683 coap_resource_t *result;
684
685 coap_lock_lock(return NULL);
686 result = coap_get_resource_from_uri_path_lkd(context, uri_path);
688
689 return result;
690}
691
694 coap_str_const_t *uri_path) {
695 coap_resource_t *result;
696
698
699 RESOURCES_FIND(context->resources, uri_path, result);
700
701 return result;
702}
703
705coap_print_link(const coap_resource_t *resource,
706 unsigned char *buf, size_t *len, size_t *offset) {
707 unsigned char *p = buf;
708 const uint8_t *bufend = buf + *len;
709 coap_attr_t *attr;
710 coap_print_status_t result = 0;
711 coap_print_status_t output_length = 0;
712 const size_t old_offset = *offset;
713
714 *len = 0;
715 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '<', *len);
716 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '/', *len);
717
718 COPY_COND_WITH_OFFSET(p, bufend, *offset,
719 resource->uri_path->s, resource->uri_path->length, *len);
720
721 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '>', *len);
722
723 LL_FOREACH(resource->link_attr, attr) {
724
725 PRINT_COND_WITH_OFFSET(p, bufend, *offset, ';', *len);
726
727 COPY_COND_WITH_OFFSET(p, bufend, *offset,
728 attr->name->s, attr->name->length, *len);
729
730 if (attr->value && attr->value->s) {
731 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '=', *len);
732
733 COPY_COND_WITH_OFFSET(p, bufend, *offset,
734 attr->value->s, attr->value->length, *len);
735 }
736
737 }
738 if (resource->observable) {
739 COPY_COND_WITH_OFFSET(p, bufend, *offset, ";obs", 4, *len);
740 }
741
742#if COAP_OSCORE_SUPPORT
743 /* If oscore is enabled */
745 COPY_COND_WITH_OFFSET(p, bufend, *offset, ";osc", 4, *len);
746#endif /* COAP_OSCORE_SUPPORT */
747
748 output_length = (coap_print_status_t)(p - buf);
749
750 if (output_length > COAP_PRINT_STATUS_MAX) {
752 }
753
754 result = (coap_print_status_t)output_length;
755
756 if (result + old_offset - *offset < *len) {
757 result |= COAP_PRINT_STATUS_TRUNC;
758 }
759
760 return result;
761}
762
763void
765 coap_request_t method,
766 coap_method_handler_t handler) {
767 coap_register_request_handler(resource, method, handler);
768}
769
770void
772 coap_request_t method,
773 coap_method_handler_t handler) {
774 assert(resource);
775 assert(method > 0 && (size_t)(method-1) <
776 sizeof(resource->handler)/sizeof(coap_method_handler_t));
777 resource->handler[method-1] = handler;
778}
779
782 const coap_bin_const_t *token) {
784
785 assert(resource);
786 assert(session);
787
788 LL_FOREACH(resource->subscribers, s) {
789 if (s->session == session &&
790 (!token || coap_binary_equal(token, &s->pdu->actual_token)))
791 return s;
792 }
793
794 return NULL;
795}
796
797static coap_subscription_t *
798coap_find_observer_cache_key(coap_resource_t *resource, coap_session_t *session,
799 const coap_cache_key_t *cache_key) {
801
802 assert(resource);
803 assert(session);
804
805 LL_FOREACH(resource->subscribers, s) {
806 if (s->session == session
807 && (memcmp(cache_key, s->cache_key, sizeof(coap_cache_key_t)) == 0))
808 return s;
809 }
810
811 return NULL;
812}
813
814/* https://rfc-editor.org/rfc/rfc7641#section-3.6 */
815static const uint16_t cache_ignore_options[] = { COAP_OPTION_ETAG,
817 };
820 coap_session_t *session,
821 const coap_bin_const_t *token,
822 const coap_pdu_t *request) {
824 coap_cache_key_t *cache_key = NULL;
825 size_t len;
826 const uint8_t *data;
827
828 assert(session);
829
830 /* Check if there is already a subscription for this peer. */
831 s = coap_find_observer(resource, session, token);
832 if (!s) {
833 /*
834 * Cannot allow a duplicate to be created for the same query as application
835 * may not be cleaning up duplicates. If duplicate found, then original
836 * observer is deleted and a new one created with the new token
837 */
838 cache_key = coap_cache_derive_key_w_ignore(session, request,
840 cache_ignore_options,
841 sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0]));
842 if (cache_key) {
843 s = coap_find_observer_cache_key(resource, session, cache_key);
844 if (s) {
845 /* Delete old entry with old token */
846 coap_delete_observer(resource, session, &s->pdu->actual_token);
847 s = NULL;
848 }
849 }
850 }
851
852 /* We are done if subscription was found. */
853 if (s) {
854 return s;
855 }
856
857 /* Check if there is already maximum number of subscribers present */
858#if (COAP_RESOURCE_MAX_SUBSCRIBER > 0)
859 uint32_t subscriber_count = 0;
860 LL_COUNT(resource->subscribers, s, subscriber_count);
861 if (subscriber_count >= COAP_RESOURCE_MAX_SUBSCRIBER) {
862 return NULL; /* Signal error */
863 }
864#endif /* COAP_RESOURCE_MAX_SUBSCRIBER */
865
866 /* Create a new subscription */
868
869 if (!s) {
870 coap_delete_cache_key(cache_key);
871 return NULL;
872 }
873
875 s->pdu = coap_pdu_duplicate_lkd(request, session, token->length,
876 token->s, NULL);
877 if (s->pdu == NULL) {
878 coap_delete_cache_key(cache_key);
880 return NULL;
881 }
882 if (coap_get_data(request, &len, &data)) {
883 /* This could be a large bodied FETCH */
884 s->pdu->max_size = 0;
885 coap_add_data(s->pdu, len, data);
886 }
887 if (cache_key == NULL) {
888 cache_key = coap_cache_derive_key_w_ignore(session, request,
890 cache_ignore_options,
891 sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0]));
892 if (cache_key == NULL) {
894 coap_delete_cache_key(cache_key);
896 return NULL;
897 }
898 }
899 s->cache_key = cache_key;
901 session->ref_subscriptions++;
902
903 /* add subscriber to resource */
904 LL_PREPEND(resource->subscribers, s);
905
906 coap_log_debug("create new subscription %p key 0x%02x%02x%02x%02x\n",
907 (void *)s, s->cache_key->key[0], s->cache_key->key[1],
908 s->cache_key->key[2], s->cache_key->key[3]);
909
910 if (session->context->observe_added_cb && session->proto == COAP_PROTO_UDP &&
911 !coap_is_af_unix(&session->addr_info.local)) {
912 coap_bin_const_t raw_packet;
913 coap_bin_const_t *oscore_info = NULL;
914#if COAP_OSCORE_SUPPORT
915 oscore_association_t *association;
916
917 if (session->recipient_ctx && session->recipient_ctx->recipient_id) {
918 /*
919 * Need to track the association used for tracking this observe, done as
920 * a CBOR array. Read in coap_persist_observe_add().
921 *
922 * If an entry is null, then use nil, else a set of bytes
923 *
924 * Currently tracking 5 items
925 * recipient_id
926 * id_context
927 * aad (from oscore_association_t)
928 * partial_iv (from oscore_association_t)
929 * nonce (from oscore_association_t)
930 */
931 uint8_t info_buffer[60];
932 uint8_t *info_buf = info_buffer;
933 size_t info_len = sizeof(info_buffer);
934 size_t ret = 0;
935 coap_bin_const_t ctoken = { token->length, token->s };
936
937 ret += oscore_cbor_put_array(&info_buf, &info_len, 5);
938 ret += oscore_cbor_put_bytes(&info_buf,
939 &info_len,
940 session->recipient_ctx->recipient_id->s,
941 session->recipient_ctx->recipient_id->length);
942 if (session->recipient_ctx->osc_ctx &&
943 session->recipient_ctx->osc_ctx->id_context) {
944 ret += oscore_cbor_put_bytes(&info_buf,
945 &info_len,
946 session->recipient_ctx->osc_ctx->id_context->s,
947 session->recipient_ctx->osc_ctx->id_context->length);
948 } else {
949 ret += oscore_cbor_put_nil(&info_buf, &info_len);
950 }
951 association = oscore_find_association(session, &ctoken);
952 if (association) {
953 if (association->aad) {
954 ret += oscore_cbor_put_bytes(&info_buf,
955 &info_len,
956 association->aad->s,
957 association->aad->length);
958 } else {
959 ret += oscore_cbor_put_nil(&info_buf, &info_len);
960 }
961 if (association->partial_iv) {
962 ret += oscore_cbor_put_bytes(&info_buf,
963 &info_len,
964 association->partial_iv->s,
965 association->partial_iv->length);
966 } else {
967 ret += oscore_cbor_put_nil(&info_buf, &info_len);
968 }
969 if (association->nonce) {
970 ret += oscore_cbor_put_bytes(&info_buf,
971 &info_len,
972 association->nonce->s,
973 association->nonce->length);
974 } else {
975 ret += oscore_cbor_put_nil(&info_buf, &info_len);
976 }
977 } else {
978 ret += oscore_cbor_put_nil(&info_buf, &info_len);
979 ret += oscore_cbor_put_nil(&info_buf, &info_len);
980 }
981 if (ret > sizeof(info_buffer)) {
982 /* Should have been caught by assert() inoscborput_* functions */
983 coap_log_warn("coap_add_observer overrun of info_buffer (%" PRIuS ")\n", ret);
984 ret = sizeof(info_buffer);
985 }
986 oscore_info = coap_new_bin_const(info_buffer, ret);
987 }
988#endif /* COAP_OSCORE_SUPPORT */
989
990 /* s->pdu header is not currently encoded */
991 memcpy(s->pdu->token - request->hdr_size,
992 request->token - request->hdr_size, request->hdr_size);
993 raw_packet.s = s->pdu->token - request->hdr_size;
994 raw_packet.length = s->pdu->used_size + request->hdr_size;
995 coap_lock_callback(session->context->observe_added_cb(session, s, session->proto,
996 &session->endpoint->bind_addr,
997 &session->addr_info,
998 &raw_packet,
999 oscore_info,
1000 session->context->observe_user_data));
1001#if COAP_OSCORE_SUPPORT
1002 coap_delete_bin_const(oscore_info);
1003#endif /* COAP_OSCORE_SUPPORT */
1004 }
1005 if (resource->context->track_observe_value_cb) {
1006 /* Track last used observe value (as app handler is called) */
1007 coap_lock_callback(resource->context->track_observe_value_cb(resource->context,resource->uri_path,
1008 resource->observe,
1009 resource->context->observe_user_data));
1010 }
1011
1012 return s;
1013}
1014
1015void
1017 const coap_bin_const_t *token) {
1019
1020 RESOURCES_ITER(context->resources, r) {
1021 s = coap_find_observer(r, session, token);
1022 if (s) {
1023 s->fail_cnt = 0;
1024 }
1025 }
1026}
1027
1028void
1031 if (!s)
1032 return;
1033
1035 char outbuf[2 * 8 + 1] = "";
1036 unsigned int i;
1037 coap_string_t *uri_path;
1038 coap_string_t *uri_query;
1039
1040 for (i = 0; i < s->pdu->actual_token.length; i++) {
1041 size_t size = strlen(outbuf);
1042
1043 snprintf(&outbuf[size], sizeof(outbuf)-size, "%02x",
1044 s->pdu->actual_token.s[i]);
1045 }
1046 uri_path = coap_get_uri_path(s->pdu);
1047 uri_query = coap_get_query(s->pdu);
1048 coap_log_debug("removed subscription '/%*.*s%s%*.*s' (%p) with token '%s' key 0x%02x%02x%02x%02x\n",
1049 uri_path ? (int)uri_path->length : 0, uri_path ? (int)uri_path->length : 0,
1050 uri_path ? (char *)uri_path->s : "",
1051 uri_query ? "?" : "",
1052 uri_query ? (int)uri_query->length : 0, uri_query ? (int)uri_query->length : 0,
1053 uri_query ? (char *)uri_query->s : "",
1054 (void *)s, outbuf, s->cache_key->key[0], s->cache_key->key[1],
1055 s->cache_key->key[2], s-> cache_key->key[3]);
1056 coap_delete_string(uri_path);
1057 coap_delete_string(uri_query);
1058 }
1059 if (session->context->observe_deleted_cb)
1060 coap_lock_callback(session->context->observe_deleted_cb(session, s,
1061 session->context->observe_user_data));
1062
1063 if (resource->subscribers) {
1064 LL_DELETE(resource->subscribers, s);
1065 assert(session->ref_subscriptions > 0);
1066 session->ref_subscriptions--;
1067 coap_session_release_lkd(session);
1071 }
1072
1073 return;
1074}
1075
1076int
1078 const coap_bin_const_t *token) {
1080
1081 s = coap_find_observer(resource, session, token);
1082 if (s)
1083 coap_delete_observer_internal(resource, session, s);
1084
1085 return s != NULL;
1086}
1087
1088int
1090 const coap_bin_const_t *token, coap_pdu_t *request) {
1092 int ret = 0;
1093
1094 s = coap_find_observer(resource, session, token);
1095 if (!s) {
1096 /*
1097 * It is possible that the client is using the wrong token.
1098 * An example being a large FETCH spanning multiple blocks.
1099 */
1100 coap_cache_key_t *cache_key;
1101
1102 cache_key = coap_cache_derive_key_w_ignore(session, request,
1104 cache_ignore_options,
1105 sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0]));
1106 if (cache_key) {
1107 s = coap_find_observer_cache_key(resource, session, cache_key);
1108 if (s) {
1109 /* Delete entry with setup token */
1110 ret = coap_delete_observer(resource, session, &s->pdu->actual_token);
1111 }
1112 coap_delete_cache_key(cache_key);
1113 }
1114 } else {
1115 coap_delete_observer_internal(resource, session, s);
1116 ret = 1;
1117 }
1118 return ret;
1119}
1120
1121void
1123 RESOURCES_ITER(context->resources, resource) {
1124 coap_subscription_t *s, *tmp;
1125 LL_FOREACH_SAFE(resource->subscribers, s, tmp) {
1126 if (s->session == session) {
1127 if (context->observe_deleted_cb)
1128 coap_lock_callback(context->observe_deleted_cb(session, s, context->observe_user_data));
1129 assert(resource->subscribers);
1130 LL_DELETE(resource->subscribers, s);
1131 coap_session_release_lkd(session);
1135 }
1136 }
1137 }
1138}
1139
1140static void
1141coap_notify_observers(coap_context_t *context, coap_resource_t *r,
1142 coap_deleting_resource_t deleting) {
1144 coap_subscription_t *obs, *otmp;
1145 coap_pdu_t *response;
1146 uint8_t buf[4];
1147 coap_string_t *query;
1148 coap_block_b_t block;
1149 coap_tick_t now;
1150
1152
1153 if (r->observable && (r->dirty || r->partiallydirty)) {
1154 if (r->list_being_traversed)
1155 return;
1156 r->list_being_traversed = 1;
1157
1159
1160 r->partiallydirty = 0;
1161
1162 LL_FOREACH_SAFE(r->subscribers, obs, otmp) {
1163 coap_session_t *obs_session;
1164 coap_pdu_t *obs_pdu;
1166
1167 if (r->dirty == 0 && obs->dirty == 0) {
1168 /*
1169 * running this resource due to partiallydirty, but this observation's
1170 * notification was already enqueued
1171 */
1172 context->observe_pending = 1;
1173 continue;
1174 }
1175
1176 /*
1177 * obs may get deleted in the callback, or by another running
1178 * thread when executing the callback or when sending a response.
1179 */
1180 obs_session = obs->session;
1181 obs_pdu = obs->pdu;
1182 coap_session_reference_lkd(obs_session);
1183 coap_pdu_reference_lkd(obs_pdu);
1184
1185 if (obs->session->con_active >= COAP_NSTART(obs->session) &&
1187 (obs->non_cnt >= COAP_OBS_MAX_NON))) {
1188 /* Waiting for the previous unsolicited response to finish */
1189 goto next_one_fail;
1190 }
1191 coap_ticks(&now);
1192 if (obs->session->lg_xmit && obs->session->lg_xmit->last_all_sent == 0 &&
1193 obs->session->lg_xmit->last_obs &&
1194 (obs->session->lg_xmit->last_obs + 2*COAP_TICKS_PER_SECOND) > now) {
1195 /* Waiting for the previous blocked unsolicited response to finish */
1196 goto next_one_fail;
1197 }
1198
1199 obs->dirty = 0;
1200 /* initialize response */
1201 response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0,
1203 if (!response) {
1204 coap_log_debug("coap_check_notify: pdu init failed, resource stays "
1205 "partially dirty\n");
1206 goto next_one_fail_no_pending;
1207 }
1208
1209 if (!coap_add_token(response, obs->pdu->actual_token.length,
1210 obs->pdu->actual_token.s)) {
1211 coap_log_debug("coap_check_notify: cannot add token, resource stays "
1212 "partially dirty\n");
1213 coap_delete_pdu_lkd(response);
1214 goto next_one_fail_no_pending;
1215 }
1216
1217 obs->pdu->mid = response->mid = coap_new_message_id_lkd(obs->session);
1218 /* A lot of the reliable code assumes type is CON */
1222 obs->non_cnt < COAP_OBS_MAX_NON)) {
1223 response->type = COAP_MESSAGE_NON;
1224 } else {
1225 response->type = COAP_MESSAGE_CON;
1226 }
1227 switch (deleting) {
1228 case COAP_NOT_DELETING_RESOURCE:
1229 /* fill with observer-specific data */
1231 coap_encode_var_safe(buf, sizeof(buf),
1232 r->observe),
1233 buf);
1235 &block)) {
1236 /* Will get updated later (e.g. M bit) if appropriate */
1238 coap_encode_var_safe(buf, sizeof(buf),
1239 ((0 << 4) |
1240 (0 << 3) |
1241 block.aszx)),
1242 buf);
1243 }
1244#if COAP_Q_BLOCK_SUPPORT
1245 else if (coap_get_block_b(obs->session, obs->pdu, COAP_OPTION_Q_BLOCK2,
1246 &block)) {
1247 /* Will get updated later (e.g. M bit) if appropriate */
1249 coap_encode_var_safe(buf, sizeof(buf),
1250 ((0 << 4) |
1251 (0 << 3) |
1252 block.szx)),
1253 buf);
1254 }
1255#endif /* COAP_Q_BLOCK_SUPPORT */
1256
1257 h = r->handler[obs->pdu->code - 1];
1258 assert(h); /* we do not allow subscriptions if no
1259 * GET/FETCH handler is defined */
1260 query = coap_get_query(obs->pdu);
1261 coap_log_debug("Observe PDU presented to app.\n");
1263 coap_log_debug("call custom handler for resource '%*.*s' (4)\n",
1264 (int)r->uri_path->length, (int)r->uri_path->length,
1265 r->uri_path->s);
1266
1267 /* obs may get deleted during callback (potentially by another thread) */
1268 coap_lock_callback_release(h(r, obs->session, obs->pdu, query, response),
1269 /* context is being freed off */
1270 coap_delete_string(query);
1271 coap_delete_pdu_lkd(response);
1272 coap_session_release_lkd(obs_session);
1273 coap_pdu_release_lkd(obs_pdu);
1274 r->list_being_traversed = 0;
1276 return);
1277
1278 /* Check validity of response code */
1279 if (!coap_check_code_class(obs_session, response)) {
1280 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
1281 COAP_RESPONSE_CLASS(response->code),
1282 response->code & 0x1f);
1283 coap_delete_string(query);
1284 coap_delete_pdu_lkd(response);
1285 coap_session_release_lkd(obs_session);
1286 coap_pdu_release_lkd(obs_pdu);
1287 r->list_being_traversed = 0;
1289 return;
1290 }
1291
1292 /* Check if lg_xmit generated and update PDU code if so */
1293 coap_check_code_lg_xmit(obs_session, obs_pdu, response, r, query);
1294 coap_delete_string(query);
1295 if (COAP_RESPONSE_CLASS(response->code) != 2) {
1297 }
1298 if (COAP_RESPONSE_CLASS(response->code) > 2) {
1299 coap_delete_observer(r, obs_session, &obs_pdu->actual_token);
1300 obs = NULL;
1301 }
1302 break;
1303 case COAP_DELETING_RESOURCE_ON_EXIT:
1304 /* Don't worry if it does not get there */
1305 response->type = COAP_MESSAGE_NON;
1306 response->code = COAP_RESPONSE_CODE(503);
1308 coap_encode_var_safe(buf, sizeof(buf),
1309 30),
1310 buf);
1311 break;
1312 case COAP_DELETING_RESOURCE:
1313 default:
1314 /* Don't worry if it does not get there */
1315 response->type = COAP_MESSAGE_NON;
1316 response->code = COAP_RESPONSE_CODE(404);
1317 break;
1318 }
1319
1320 if (obs) {
1322 /*
1323 * obs may have been deleted in the callback, or by another running
1324 * thread when executing the callback.
1325 */
1326 LL_FOREACH(r->subscribers, s) {
1327 if (s == obs) {
1328 break;
1329 }
1330 }
1331 if (s == NULL)
1332 obs = NULL;
1333 }
1334 if (obs) {
1335 if (response->type == COAP_MESSAGE_CON ||
1337 obs->non_cnt = 0;
1338 } else {
1339 obs->non_cnt++;
1340 }
1341
1342#if COAP_Q_BLOCK_SUPPORT
1343 if (response->code == COAP_RESPONSE_CODE(205) &&
1344 coap_get_block_b(obs_session, response, COAP_OPTION_Q_BLOCK2,
1345 &block) &&
1346 block.m) {
1347 query = coap_get_query(obs_pdu);
1348 mid = coap_send_q_block2(obs_session, r, query, obs_pdu->code,
1349 block, response, 1);
1350 coap_delete_string(query);
1351 goto finish;
1352 }
1353#endif /* COAP_Q_BLOCK_SUPPORT */
1354 }
1355 mid = coap_send_internal(obs_session, response, NULL);
1356
1357#if COAP_Q_BLOCK_SUPPORT
1358finish:
1359#endif /* COAP_Q_BLOCK_SUPPORT */
1360 if (COAP_INVALID_MID == mid && obs) {
1361 coap_log_debug("* %s: coap_check_notify: sending failed, resource stays "
1362 "partially dirty\n", coap_session_str(obs_session));
1363 obs->dirty = 1;
1364 r->partiallydirty = 1;
1365 }
1366 goto cleanup;
1367
1368next_one_fail:
1369 context->observe_pending = 1;
1370next_one_fail_no_pending:
1371 r->partiallydirty = 1;
1372 if (obs)
1373 obs->dirty = 1;
1374cleanup:
1375 coap_session_release_lkd(obs_session);
1376 coap_pdu_release_lkd(obs_pdu);
1377 }
1378 r->list_being_traversed = 0;
1379 r->dirty = 0;
1381 /* r may be no more if elsewhere coap_free_resource() has been called */
1382 } else {
1383 r->dirty = 0;
1384 }
1385}
1386
1387COAP_API int
1389 int ret;
1390
1391 coap_lock_lock(return 0);
1392 ret = coap_resource_notify_observers_lkd(r, query);
1394 return ret;
1395}
1396
1397COAP_API int
1399 const coap_string_t *query) {
1400 int ret;
1401
1402 coap_lock_lock(return 0);
1403 ret = coap_resource_notify_observers_lkd(r, query);
1405 return ret;
1406}
1407
1408int
1410 const coap_string_t *query COAP_UNUSED) {
1412 if (!r->observable)
1413 return 0;
1414 if (!r->subscribers)
1415 return 0;
1416 r->dirty = 1;
1417
1418 /* Increment value for next Observe use. Observe value must be < 2^24 */
1419 r->observe = (r->observe + 1) & 0xFFFFFF;
1420
1421 assert(r->context);
1422
1424 /* Track last used observe value */
1425 if ((r->observe % r->context->observe_save_freq) == 0)
1427 r->observe,
1429 }
1430
1431 r->context->observe_pending = 1;
1433 return 1;
1434}
1435
1436void
1437coap_resource_set_mode(coap_resource_t *resource, int mode) {
1438 resource->flags = (resource->flags &
1441}
1442
1443void
1444coap_resource_set_userdata(coap_resource_t *resource, void *data) {
1445 resource->user_data = data;
1446}
1447
1448void *
1450 return resource->user_data;
1451}
1452
1453void
1456 context->release_userdata_cb = callback;
1457}
1458
1459void
1461 if (resource->is_unknown || resource->is_proxy_uri) {
1462 /* We cannot observe these */
1463 coap_log_debug("coap_resource_set_get_observable: Not supported for Unknown or Proxy URIs\n");
1464 resource->observable = 0;
1465 } else {
1466 resource->observable = mode ? 1 : 0;
1467 }
1468}
1469
1472 if (resource)
1473 return resource->uri_path;
1474 return NULL;
1475}
1476
1477COAP_API void
1479 coap_lock_lock(return);
1480 coap_check_notify_lkd(context);
1482}
1483
1484void
1486
1488 if (context->observe_pending) {
1489 context->observe_pending = 0;
1490 RESOURCES_ITER(context->resources, r) {
1491 coap_notify_observers(context, r, COAP_NOT_DELETING_RESOURCE);
1492 }
1493 }
1494}
1495
1496void
1498 uint32_t start_observe_no) {
1499 if (!resource)
1500 return;
1501
1502 resource->observe = start_observe_no & 0xffffff;
1503}
1504
1515static void
1516coap_remove_failed_observers(coap_context_t *context,
1517 coap_resource_t *resource,
1518 coap_session_t *session,
1519 const coap_bin_const_t *token) {
1520 coap_subscription_t *obs, *otmp;
1521
1522 LL_FOREACH_SAFE(resource->subscribers, obs, otmp) {
1523 if (obs->session == session &&
1524 coap_binary_equal(token, &obs->pdu->actual_token)) {
1525 /* count failed notifies and remove when
1526 * COAP_OBS_MAX_FAIL is reached */
1527 obs->fail_cnt++;
1528 if (obs->fail_cnt >= COAP_OBS_MAX_FAIL) {
1529 coap_cancel_all_messages(context, obs->session,
1530 &obs->pdu->actual_token);
1531 coap_delete_observer(resource, session, token);
1532 }
1533 break; /* break loop if observer was found */
1534 }
1535 }
1536}
1537
1538void
1540 coap_session_t *session,
1541 const coap_bin_const_t *token) {
1542
1543 RESOURCES_ITER(context->resources, r) {
1544 coap_remove_failed_observers(context, r, session, token);
1545 }
1546}
1547
1548void
1550 resource->ref++;
1551}
1552#endif /* ! COAP_SERVER_SUPPORT */
int coap_is_af_unix(const coap_address_t *a)
Checks if given address a denotes a AF_UNIX address.
#define PRIuS
Library specific build wrapper for coap_internal.h.
#define COAP_API
@ COAP_RESOURCE
Definition coap_mem.h:43
@ COAP_RESOURCEATTR
Definition coap_mem.h:44
@ COAP_SUBSCRIPTION
Definition coap_mem.h:54
@ COAP_STRING
Definition coap_mem.h:34
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.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
COAP_DEPRECATED COAP_API int coap_resource_set_dirty(coap_resource_t *r, const coap_string_t *query)
void coap_check_code_lg_xmit(const coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_resource_t *resource, const coap_string_t *query)
The function checks that the code in a newly formed lg_xmit created by coap_add_data_large_response_l...
int coap_get_block_b(const coap_session_t *session, const coap_pdu_t *pdu, coap_option_num_t number, coap_block_b_t *block)
Initializes block from pdu.
Definition coap_block.c:62
void coap_delete_cache_key(coap_cache_key_t *cache_key)
Delete the cache-key.
coap_cache_key_t * coap_cache_derive_key_w_ignore(const coap_session_t *session, const coap_pdu_t *pdu, coap_cache_session_based_t session_based, const uint16_t *ignore_options, size_t ignore_count)
Calculates a cache-key for the given CoAP PDU.
@ COAP_CACHE_IS_SESSION_BASED
Definition coap_cache.h:43
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:151
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:166
#define RESOURCES_ADD(r, obj)
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
void coap_resource_release_lkd(coap_resource_t *resource)
Decrement reference counter on a resource.
coap_print_status_t coap_print_wellknown_lkd(coap_context_t *context, unsigned char *buf, size_t *buflen, size_t offset, const coap_string_t *query_filter)
Prints the names of all known resources for context to buf.
void coap_delete_attr(coap_attr_t *attr)
Deletes an attribute.
coap_resource_t * coap_get_resource_from_uri_path_lkd(coap_context_t *context, coap_str_const_t *uri_path)
Returns the resource identified by the unique string uri_path.
void coap_resource_reference_lkd(coap_resource_t *resource)
Increment reference counter on a resource.
void coap_add_resource_lkd(coap_context_t *context, coap_resource_t *resource)
Registers the given resource for context.
#define RESOURCES_FIND(r, k, res)
int coap_delete_resource_lkd(coap_context_t *context, coap_resource_t *resource)
Deletes a resource identified by resource.
#define RESOURCES_DELETE(r, obj)
#define RESOURCES_ITER(r, tmp)
COAP_API 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.
#define COAP_RESOURCE_FLAGS_NOTIFY_NON
Observe Notifications will be sent non-confirmable by default.
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.
coap_attr_t * coap_add_attr(coap_resource_t *resource, coap_str_const_t *name, coap_str_const_t *value, int flags)
Registers a new attribute with the given resource.
#define COAP_ATTR_FLAGS_RELEASE_VALUE
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.
coap_resource_t * coap_resource_proxy_uri_init2(coap_method_handler_t handler, size_t host_name_count, const char *host_name_list[], int flags)
Creates a new resource object for handling proxy URIs with configurable control over multicast reques...
#define COAP_RESOURCE_FLAGS_NOTIFY_NON_ALWAYS
Observe Notifications will always be sent non-confirmable.
#define COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
Define this when invoking coap_resource_unknown_init2() if .well-known/core is to be passed to the un...
#define COAP_ATTR_FLAGS_RELEASE_NAME
void coap_resource_set_mode(coap_resource_t *resource, int mode)
Sets the notification message type of resource resource to given mode.
#define COAP_PRINT_STATUS_TRUNC
void(* coap_method_handler_t)(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
Definition of message handler function.
void coap_resource_release_userdata_handler(coap_context_t *context, coap_resource_release_userdata_handler_t callback)
Defines the context wide callback to use to when the resource is deleted to release the data held in ...
#define COAP_RESOURCE_FLAGS_OSCORE_ONLY
Define this resource as an OSCORE enabled access only.
COAP_API coap_print_status_t coap_print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen, size_t offset, const coap_string_t *query_filter)
Prints the names of all known resources for context to buf.
#define COAP_RESOURCE_FLAGS_NOTIFY_CON
Observe Notifications will be sent confirmable.
coap_resource_t * coap_resource_reverse_proxy_init(coap_method_handler_t handler, int flags)
Creates a new resource object for the reverse-proxy resource handler with control over multicast requ...
COAP_API int coap_delete_resource(coap_context_t *context, coap_resource_t *resource)
Deletes a resource identified by resource.
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.
#define COAP_PRINT_STATUS_MAX
void(* coap_resource_release_userdata_handler_t)(void *user_data)
Definition of release resource user_data callback function.
void coap_register_request_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.
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.
void coap_resource_set_userdata(coap_resource_t *resource, void *data)
Sets the user_data.
uint32_t coap_print_status_t
Status word to encode the result of conditional print or copy operations such as coap_print_link().
#define COAP_PRINT_STATUS_ERROR
coap_str_const_t * coap_resource_get_uri_path(coap_resource_t *resource)
Get the uri_path from a resource.
coap_resource_t * coap_resource_unknown_init2(coap_method_handler_t put_handler, int flags)
Creates a new resource object for the unknown resource handler with support for PUT and configurable ...
coap_str_const_t * coap_attr_get_value(coap_attr_t *attribute)
Returns attribute's value.
#define COAP_PRINT_OUTPUT_LENGTH(v)
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.
void * coap_resource_get_userdata(coap_resource_t *resource)
Gets the user_data.
COAP_API void coap_add_resource(coap_context_t *context, coap_resource_t *resource)
Registers the given resource for context.
#define COAP_RESOURCE_FLAGS_RELEASE_URI
The URI passed to coap_resource_init() is free'd by coap_delete_resource().
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.
#define COAP_RESOURCE_HIDE_WELLKNOWN_CORE
Hide this resource from .well-known/core.
uint16_t coap_new_message_id_lkd(coap_session_t *session)
Returns a new message id and updates session->tx_mid accordingly.
coap_mid_t coap_send_internal(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *request_pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1872
int coap_check_code_class(coap_session_t *session, coap_pdu_t *pdu)
Check whether the pdu contains a valid code class.
Definition coap_net.c:1419
void coap_cancel_all_messages(coap_context_t *context, coap_session_t *session, coap_bin_const_t *token)
Cancels all outstanding messages for session session that have the specified token.
Definition coap_net.c:3141
void coap_ticks(coap_tick_t *t)
Returns the current value of an internal tick counter.
Definition coap_time.c:90
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:47
#define coap_lock_callback(func)
Dummy for no thread-safe code.
#define coap_lock_unlock()
Dummy for no thread-safe code.
#define coap_lock_check_locked()
Dummy for no thread-safe code.
#define coap_lock_callback_release(func, failed)
Dummy for no thread-safe code.
#define coap_lock_lock(failed)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:126
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition coap_debug.c:103
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition coap_debug.c:793
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_warn(...)
Definition coap_debug.h:108
#define coap_log_err(...)
Definition coap_debug.h:102
@ COAP_LOG_DEBUG
Definition coap_debug.h:64
void coap_persist_set_observe_num(coap_resource_t *resource, uint32_t observe_num)
Sets the current observe number value.
void coap_resource_set_get_observable(coap_resource_t *resource, int mode)
Set whether a resource is observable.
COAP_API void coap_check_notify(coap_context_t *context)
Checks all known resources to see if they are dirty and then notifies subscribed observers.
COAP_API int coap_resource_notify_observers(coap_resource_t *resource, const coap_string_t *query)
Initiate the sending of an Observe packet for all observers of resource, optionally matching query if...
size_t oscore_cbor_put_nil(uint8_t **buffer, size_t *buf_size)
size_t oscore_cbor_put_bytes(uint8_t **buffer, size_t *buf_size, const uint8_t *bytes, size_t bytes_len)
size_t oscore_cbor_put_array(uint8_t **buffer, size_t *buf_size, size_t elements)
oscore_association_t * oscore_find_association(coap_session_t *session, coap_bin_const_t *token)
coap_pdu_t * coap_pdu_reference_lkd(coap_pdu_t *pdu)
Increment reference counter on a pdu to stop it prematurely getting freed off when coap_delete_pdu() ...
Definition coap_pdu.c:1661
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:194
int coap_remove_option(coap_pdu_t *pdu, coap_option_num_t number)
Removes (first) option of given number from the pdu.
Definition coap_pdu.c:499
coap_pdu_t * coap_pdu_duplicate_lkd(const coap_pdu_t *old_pdu, coap_session_t *session, size_t token_length, const uint8_t *token, coap_opt_filter_t *drop_options)
Duplicate an existing PDU.
Definition coap_pdu.c:234
COAP_STATIC_INLINE void coap_pdu_release_lkd(coap_pdu_t *pdu)
size_t coap_add_option_internal(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Adds option of given number to pdu that is passed as first parameter.
Definition coap_pdu.c:789
#define COAP_OPTION_BLOCK2
Definition coap_pdu.h:142
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:268
coap_request_t
CoAP PDU Request methods.
Definition coap_pdu.h:82
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:165
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:168
#define COAP_OPTION_OSCORE
Definition coap_pdu.h:130
int coap_add_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds token of length len to pdu.
Definition coap_pdu.c:366
#define COAP_OPTION_Q_BLOCK2
Definition coap_pdu.h:145
int coap_get_data(const coap_pdu_t *pdu, size_t *len, const uint8_t **data)
Retrieves the length and data pointer of specified PDU.
Definition coap_pdu.c:885
coap_pdu_t * coap_pdu_init(coap_pdu_type_t type, coap_pdu_code_t code, coap_mid_t mid, size_t size)
Creates a new CoAP PDU with at least enough storage space for the given size maximum message size.
Definition coap_pdu.c:102
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:271
#define COAP_OPTION_MAXAGE
Definition coap_pdu.h:135
#define COAP_OPTION_ETAG
Definition coap_pdu.h:125
#define COAP_OPTION_OBSERVE
Definition coap_pdu.h:127
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition coap_pdu.h:57
int coap_add_data(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds given data to the pdu that is passed as first parameter.
Definition coap_pdu.c:854
@ COAP_REQUEST_PUT
Definition coap_pdu.h:85
@ COAP_REQUEST_DELETE
Definition coap_pdu.h:86
@ COAP_REQUEST_GET
Definition coap_pdu.h:83
@ COAP_REQUEST_FETCH
Definition coap_pdu.h:87
@ COAP_REQUEST_PATCH
Definition coap_pdu.h:88
@ COAP_REQUEST_IPATCH
Definition coap_pdu.h:89
@ COAP_REQUEST_POST
Definition coap_pdu.h:84
@ COAP_PROTO_UDP
Definition coap_pdu.h:320
@ COAP_MESSAGE_NON
Definition coap_pdu.h:74
@ COAP_MESSAGE_CON
Definition coap_pdu.h:73
#define COAP_NSTART(s)
size_t coap_session_max_pdu_size_lkd(const coap_session_t *session)
Get maximum acceptable PDU size.
void coap_session_release_lkd(coap_session_t *session)
Decrement reference counter on a session.
coap_session_t * coap_session_reference_lkd(coap_session_t *session)
Increment reference counter on a session.
#define COAP_PROTO_NOT_RELIABLE(p)
void coap_delete_bin_const(coap_bin_const_t *s)
Deletes the given const binary data and releases any memory allocated.
Definition coap_str.c:120
void coap_delete_str_const(coap_str_const_t *s)
Deletes the given const string and releases any memory allocated.
Definition coap_str.c:61
coap_bin_const_t * coap_new_bin_const(const uint8_t *data, size_t size)
Take the specified byte array (text) and create a coap_bin_const_t * Returns a new const binary objec...
Definition coap_str.c:110
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:214
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:200
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 coap_str.c:51
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition coap_str.c:46
void coap_delete_observer_internal(coap_resource_t *resource, coap_session_t *session, coap_subscription_t *subscription)
Removes specific subscription for session for resource and releases the allocated storage.
void coap_check_notify_lkd(coap_context_t *context)
Checks all known resources to see if they are dirty and then notifies subscribed observers.
int coap_delete_observer_request(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, coap_pdu_t *request)
Removes any subscription for session observer from resource and releases the allocated storage.
int coap_delete_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token)
Removes any subscription for session observer from resource and releases the allocated storage.
coap_subscription_t * coap_find_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token)
Returns a subscription object for given peer.
void coap_delete_observers(coap_context_t *context, coap_session_t *session)
Removes any subscription for session and releases the allocated storage.
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Handles a failed observe notify.
int coap_resource_notify_observers_lkd(coap_resource_t *resource, const coap_string_t *query)
Initiate the sending of an Observe packet for all observers of resource, optionally matching query if...
void coap_subscription_init(coap_subscription_t *)
coap_subscription_t * coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, const coap_pdu_t *pdu)
Adds the specified peer as observer for resource.
void coap_touch_observer(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Flags that data is ready to be sent to observers.
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition coap_uri.c:1020
coap_string_t * coap_get_query(const coap_pdu_t *request)
Extract query string from request PDU according to escape rules in 6.5.8.
Definition coap_uri.c:969
#define COAP_UNUSED
Definition libcoap.h:74
coap_address_t local
local address and port
Definition coap_io.h:61
Limits the number of subscribers for each resource that this server support.
coap_str_const_t * value
Value of the attribute (can be NULL)
coap_str_const_t * name
Name of the attribute.
CoAP binary data definition with const data.
Definition coap_str.h:67
size_t length
length of binary data
Definition coap_str.h:68
const uint8_t * s
read-only binary data
Definition coap_str.h:69
Structure of Block options with BERT support.
Definition coap_block.h:55
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:59
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:57
unsigned int szx
block size (0-6)
Definition coap_block.h:58
The CoAP stack's global state is stored in a coap_context_t object.
coap_resource_deleted_t resource_deleted_cb
Invoked when resource is deleted.
coap_observe_deleted_t observe_deleted_cb
Called when there is a observe subscription de-register request.
coap_observe_added_t observe_added_cb
Called when there is a new observe subscription request.
coap_resource_release_userdata_handler_t release_userdata_cb
function to release user_data when resource is deleted
coap_resource_t * resources
hash table or list of known resources
void * observe_user_data
App provided data for use in observe_added or observe_deleted.
coap_track_observe_value_t track_observe_value_cb
Callback to save observe value when updated.
uint8_t observe_pending
Observe response pending.
uint32_t observe_save_freq
How frequently to update observe value.
uint8_t observe_no_clear
Observe 4.04 not to be sent on deleting resource.
coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
coap_dyn_resource_added_t dyn_resource_added_cb
Callback to save dynamic resource when created.
coap_resource_t * unknown_resource
can be used for handling unknown resources
coap_address_t bind_addr
local interface address
coap_tick_t last_all_sent
Last time all data sent or 0.
coap_tick_t last_obs
Last time used (Observe tracking) or 0.
structure for CoAP PDUs
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
coap_pdu_code_t code
request method (value 1–31) or response code (value 64-255)
uint8_t hdr_size
actual size used for protocol-specific header (0 until header is encoded)
coap_bin_const_t actual_token
Actual token in pdu.
coap_mid_t mid
message id, if any, in regular host byte order
size_t used_size
used bytes of storage for token, options and payload
coap_pdu_type_t type
message type
Abstraction of resource that can be attached to coap_context_t.
unsigned int dirty
set to 1 if resource has changed
unsigned int partiallydirty
set to 1 if some subscribers have not yet been notified of the last change
unsigned int list_being_traversed
resource subscriber list being traversed
coap_subscription_t * subscribers
list of observers for this resource
void * user_data
This pointer is under user control.
coap_str_const_t ** proxy_name_list
Array valid names this host is known by (proxy support)
coap_str_const_t * uri_path
Request URI Path for this resource.
unsigned int observe
The next value for the Observe option.
coap_context_t * context
Pointer back to the context that 'owns' this resource.
coap_method_handler_t handler[7]
Used to store handlers for the seven coap methods GET, POST, PUT, DELETE, FETCH, PATCH and IPATCH.
uint32_t ref
Resource reference count.
unsigned int is_proxy_uri
resource created for proxy URI handler
unsigned int is_dynamic
create unknown resource dynamically
unsigned int is_unknown
resource created for unknown handler
coap_attr_t * link_attr
attributes to be included with the link format
unsigned int is_reverse_proxy
resource created for reverse proxy URI handler
unsigned int observable
can be observed
size_t proxy_name_count
Count of valid names this host is known by (proxy support)
int flags
zero or more COAP_RESOURCE_FLAGS_* or'd together
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
unsigned ref_subscriptions
reference count of current subscriptions
coap_endpoint_t * endpoint
session's endpoint
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
uint8_t con_active
Active CON request sent.
coap_context_t * context
session's context
CoAP string data definition with const data.
Definition coap_str.h:49
const uint8_t * s
read-only string data
Definition coap_str.h:51
size_t length
length of string
Definition coap_str.h:50
CoAP string data definition.
Definition coap_str.h:41
uint8_t * s
string data
Definition coap_str.h:43
size_t length
length of string
Definition coap_str.h:42
Number of notifications that may be sent non-confirmable before a confirmable message is sent to dete...
uint8_t dirty
set if the notification temporarily could not be sent (in that case, the resource's partially dirty f...
uint8_t non_cnt
up to 255 non-confirmable notifies allowed
coap_cache_key_t * cache_key
struct coap_session_t * session
subscriber session
uint8_t fail_cnt
up to 255 confirmable notifies can fail
coap_pdu_t * pdu
cache_key to identify requester
coap_bin_const_t * partial_iv
coap_bin_const_t * aad
coap_bin_const_t * nonce