libcoap 4.3.5-develop-93694e6
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
15
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
67#ifndef WITHOUT_QUERY_FILTER
68static int
69match(const coap_str_const_t *text, const coap_str_const_t *pattern,
70 int match_prefix) {
71 const uint8_t *next_token = text->s;
72 size_t remaining_length = text->length;
73 assert(text);
74 assert(pattern);
75
76 if (text->length < pattern->length || !pattern->s)
77 return 0;
78
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 (token_length >= pattern->length &&
94 (match_prefix || pattern->length == token_length) &&
95 memcmp(token, pattern->s, pattern->length) == 0)
96 return 1;
97 }
98 return 0;
99}
100#endif /* WITHOUT_QUERY_FILTER */
101
103coap_print_wellknown(coap_context_t *context, unsigned char *buf,
104 size_t *buflen, size_t offset,
105 const coap_string_t *query_filter) {
106 coap_print_status_t result;
108 result = coap_print_wellknown_lkd(context, buf, buflen, offset, query_filter);
110 return result;
111}
112
113static coap_str_const_t coap_default_uri_wellknown = {
115 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
116};
117
119coap_print_wellknown_lkd(coap_context_t *context, unsigned char *buf,
120 size_t *buflen, size_t offset,
121 const coap_string_t *query_filterm) {
122 coap_print_status_t output_length = 0;
123 unsigned char *p = buf;
124 const uint8_t *bufend = buf + *buflen;
125 size_t left, written = 0;
126 coap_print_status_t result;
127 const size_t old_offset = offset;
128 int subsequent_resource = 0;
129#ifdef WITHOUT_QUERY_FILTER
130 (void)query_filterm;
131#endif /* WITHOUT_QUERY_FILTER */
132
134#ifndef WITHOUT_QUERY_FILTER
135 /* split query filter, if any */
136 if (query_filterm) {
137 unsigned char *next_query = (unsigned char *)memchr(query_filterm->s, '&', query_filterm->length);
138 size_t query_filterm_rem;
139 coap_string_t query_filter;
140
141 /* There could be multiple queries */
142 query_filter.s = query_filterm->s;
143 if (next_query) {
144 query_filter.length = next_query - query_filter.s;
145 next_query++;
146 query_filterm_rem = query_filterm->length - query_filter.length - 1;
147 } else {
148 query_filter.length = query_filterm->length;
149 query_filterm_rem = 0;
150 }
151
152 while (query_filter.length) {
153 coap_str_const_t resource_param = { 0, NULL }, query_pattern = { 0, NULL };
154 /*
155 * If query starts with href=, then MATCH_URI is set in flags.
156 * If query value contains a '*', then MATCH_PREFIX is set in flags to
157 * match up to the *.
158 */
159 int flags = 0; /* MATCH_PREFIX, MATCH_URI */
160#define MATCH_URI 0x01
161#define MATCH_PREFIX 0x02
162
163 resource_param.s = query_filter.s;
164 while (resource_param.length < query_filter.length &&
165 resource_param.s[resource_param.length] != '=')
166 resource_param.length++;
167
168 if (resource_param.length < query_filter.length) {
169 if (resource_param.length == 4 &&
170 memcmp(resource_param.s, "href", 4) == 0)
171 flags |= MATCH_URI;
172
173 /* rest is query-pattern (resource may have multiple values to match */
174 query_pattern.s =
175 query_filter.s + resource_param.length + 1;
176
177 assert((resource_param.length + 1) <= query_filter.length);
178 query_pattern.length =
179 query_filter.length - (resource_param.length + 1);
180
181 if (query_pattern.length &&
182 (query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) {
183 query_pattern.s++;
184 query_pattern.length--;
185 }
186
187 if (query_pattern.length &&
188 query_pattern.s[query_pattern.length-1] == '*') {
189 query_pattern.length--;
190 flags |= MATCH_PREFIX;
191 }
192 }
193
194 RESOURCES_ITER(context->resources, r) {
195
196 if (coap_string_equal(r->uri_path, &coap_default_uri_wellknown)) {
197 /* server app has defined a resource for .well-known/core - ignore */
198 continue;
199 }
200 if (r->flags & COAP_RESOURCE_HIDE_WELLKNOWN_CORE) {
201 continue;
202 }
203 if (resource_param.length) { /* there is a query filter */
204
205 if (flags & MATCH_URI) { /* match resource URI */
206 if (!match(r->uri_path, &query_pattern, (flags & MATCH_PREFIX) != 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 attribute has a quoted value, remove double quotes */
216 if (attr->value->length >= 2 && attr->value->s[0] == '"') {
217 unquoted_val.length -= 2;
218 unquoted_val.s += 1;
219 }
220 if (!match(&unquoted_val, &query_pattern, (flags & MATCH_PREFIX) != 0))
221 continue;
222 }
223 }
224
225 if (!subsequent_resource) { /* this is the first resource */
226 subsequent_resource = 1;
227 } else {
228 PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written);
229 }
230
231 left = bufend - p; /* calculate available space */
232 result = coap_print_link(r, p, &left, &offset);
233
234 if (result & COAP_PRINT_STATUS_ERROR) {
235 break;
236 }
237
238 /* coap_print_link() returns the number of characters that
239 * where actually written to p. Now advance to its end. */
240 p += COAP_PRINT_OUTPUT_LENGTH(result);
241 written += left;
242 }
243 query_filter.s = next_query;
244 if (next_query) {
245 next_query = (unsigned char *)memchr(next_query, '&', query_filterm_rem);
246 if (next_query) {
247 query_filter.length = next_query - query_filter.s;
248 next_query++;
249 query_filterm_rem = query_filterm_rem - query_filter.length - 1;
250 } else {
251 query_filter.length = query_filterm_rem;
252 query_filterm_rem = 0;
253 }
254 } else {
255 query_filter.length = query_filterm_rem;
256 query_filterm_rem = 0;
257 }
258 }
259 } else {
260#endif /* WITHOUT_QUERY_FILTER */
261 RESOURCES_ITER(context->resources, r) {
262
263 if (coap_string_equal(r->uri_path, &coap_default_uri_wellknown)) {
264 /* server app has defined a resource for .well-known/core - ignore */
265 continue;
266 }
267 if (r->flags & COAP_RESOURCE_HIDE_WELLKNOWN_CORE) {
268 continue;
269 }
270
271 if (!subsequent_resource) { /* this is the first resource */
272 subsequent_resource = 1;
273 } else {
274 PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written);
275 }
276
277 left = bufend - p; /* calculate available space */
278 result = coap_print_link(r, p, &left, &offset);
279
280 if (result & COAP_PRINT_STATUS_ERROR) {
281 break;
282 }
283
284 /* coap_print_link() returns the number of characters that
285 * where actually written to p. Now advance to its end. */
286 p += COAP_PRINT_OUTPUT_LENGTH(result);
287 written += left;
288 }
289#ifndef WITHOUT_QUERY_FILTER
290 }
291#endif /* WITHOUT_QUERY_FILTER */
292
293 *buflen = written;
294 output_length = (coap_print_status_t)(p - buf);
295
296 if (output_length > COAP_PRINT_STATUS_MAX) {
298 }
299
300 result = (coap_print_status_t)output_length;
301
302 if (result + old_offset - offset < *buflen) {
303 result |= COAP_PRINT_STATUS_TRUNC;
304 }
305 return result;
306}
307
308static coap_str_const_t null_path_value = {0, (const uint8_t *)""};
309static coap_str_const_t *null_path = &null_path_value;
310
312coap_resource_init(coap_str_const_t *uri_path, int flags) {
314
316 if (r) {
317 memset(r, 0, sizeof(coap_resource_t));
318#if COAP_THREAD_SAFE
319 coap_lock_init(&r->lock);
320#endif /* COAP_THREAD_SAFE */
321
322 if (!(flags & COAP_RESOURCE_FLAGS_RELEASE_URI)) {
323 /* Need to take a copy if caller is not providing a release request */
324 if (uri_path)
325 uri_path = coap_new_str_const(uri_path->s, uri_path->length);
326 else
327 uri_path = coap_new_str_const(null_path->s, null_path->length);
328 } else if (!uri_path) {
329 /* Do not expect this, but ... */
330 uri_path = coap_new_str_const(null_path->s, null_path->length);
331 }
332
333 if (uri_path)
334 r->uri_path = uri_path;
335
336 r->flags = flags;
337 r->observe = 2;
338 } else {
339 coap_log_debug("coap_resource_init: no memory left\n");
340 }
341
342 return r;
343}
344
345static const uint8_t coap_unknown_resource_uri[] =
346 "- Unknown -";
347
351
353 if (r) {
354 memset(r, 0, sizeof(coap_resource_t));
355#if COAP_THREAD_SAFE
356 coap_lock_init(&r->lock);
357#endif /* COAP_THREAD_SAFE */
358 r->is_unknown = 1;
359 /* Something unlikely to be used, but it shows up in the logs */
360 r->uri_path = coap_new_str_const(coap_unknown_resource_uri, sizeof(coap_unknown_resource_uri)-1);
361 r->flags = flags & ~COAP_RESOURCE_FLAGS_RELEASE_URI;
363 } else {
364 coap_log_debug("coap_resource_unknown_init2: no memory left\n");
365 }
366
367 return r;
368}
369
372 return coap_resource_unknown_init2(put_handler, 0);
373}
374
375static const uint8_t coap_proxy_resource_uri[] =
376 "- Proxy URI -";
377
380 size_t host_name_count,
381 const char *host_name_list[], int flags) {
383
385 if (r) {
386 size_t i;
387 memset(r, 0, sizeof(coap_resource_t));
388#if COAP_THREAD_SAFE
389 coap_lock_init(&r->lock);
390#endif /* COAP_THREAD_SAFE */
391 r->is_proxy_uri = 1;
392 /* Something unlikely to be used, but it shows up in the logs */
393 r->uri_path = coap_new_str_const(coap_proxy_resource_uri, sizeof(coap_proxy_resource_uri)-1);
394 /* Preset all the handlers */
395 for (i = 0; i < (sizeof(r->handler) / sizeof(r->handler[0])); i++) {
396 r->handler[i] = handler;
397 }
398 if (host_name_count) {
399 r->proxy_name_list = coap_malloc_type(COAP_STRING, host_name_count *
400 sizeof(coap_str_const_t *));
401 if (r->proxy_name_list) {
402 for (i = 0; i < host_name_count; i++) {
403 r->proxy_name_list[i] =
404 coap_new_str_const((const uint8_t *)host_name_list[i],
405 strlen(host_name_list[i]));
406 if (!r->proxy_name_list[i]) {
407 coap_log_err("coap_resource_proxy_uri_init: unable to add host name\n");
408 if (i == 0) {
409 coap_free_type(COAP_STRING, r->proxy_name_list);
410 r->proxy_name_list = NULL;
411 }
412 break;
413 }
414 }
415 r->proxy_name_count = i;
416 }
417 }
418 r->flags = flags & ~COAP_RESOURCE_FLAGS_RELEASE_URI;
419 } else {
420 coap_log_debug("coap_resource_proxy_uri_init2: no memory left\n");
421 }
422
423 return r;
424}
425
428 size_t host_name_count, const char *host_name_list[]) {
429 return coap_resource_proxy_uri_init2(handler, host_name_count,
430 host_name_list, 0);
431}
432
433static const uint8_t coap_rev_proxy_resource_uri[] =
434 "- Rev Proxy -";
435
439
441 if (r) {
442 memset(r, 0, sizeof(coap_resource_t));
443#if COAP_THREAD_SAFE
444 coap_lock_init(&r->lock);
445#endif /* COAP_THREAD_SAFE */
446 r->is_unknown = 1;
447 r->is_reverse_proxy = 1;
448 /* Something unlikely to be used, but it shows up in the logs */
449 r->uri_path = coap_new_str_const(coap_rev_proxy_resource_uri,
450 sizeof(coap_rev_proxy_resource_uri)-1);
451 r->flags = flags & ~COAP_RESOURCE_FLAGS_RELEASE_URI;
460 } else {
461 coap_log_debug("coap_resource_rev_proxy_init: no memory left\n");
462 }
463
464 return r;
465}
466
469 coap_str_const_t *name,
470 coap_str_const_t *val,
471 int flags) {
472 coap_attr_t *attr;
473
474 if (!resource || !name)
475 return NULL;
477
478 if (attr) {
479 if (!(flags & COAP_ATTR_FLAGS_RELEASE_NAME)) {
480 /* Need to take a copy if caller is not providing a release request */
481 name = coap_new_str_const(name->s, name->length);
482 }
483 attr->name = name;
484 if (val) {
485 if (!(flags & COAP_ATTR_FLAGS_RELEASE_VALUE)) {
486 /* Need to take a copy if caller is not providing a release request */
487 val = coap_new_str_const(val->s, val->length);
488 }
489 }
490 attr->value = val;
491
492 attr->flags = flags;
493
494 /* add attribute to resource list */
495 LL_PREPEND(resource->link_attr, attr);
496 } else {
497 coap_log_debug("coap_add_attr: no memory left\n");
498 }
499
500 return attr;
501}
502
505 coap_str_const_t *name) {
506 coap_attr_t *attr;
507
508 if (!resource || !name)
509 return NULL;
510
511 LL_FOREACH(resource->link_attr, attr) {
512 if (attr->name->length == name->length &&
513 memcmp(attr->name->s, name->s, name->length) == 0)
514 return attr;
515 }
516
517 return NULL;
518}
519
522 if (attr)
523 return attr->value;
524 return NULL;
525}
526
527void
528coap_delete_attr(coap_attr_t *attr) {
529 if (!attr)
530 return;
531 coap_delete_str_const(attr->name);
532 if (attr->value) {
533 coap_delete_str_const(attr->value);
534 }
535
537}
538
539static void coap_notify_observers(coap_context_t *context, coap_resource_t *r,
540 coap_deleting_resource_t deleting);
541
542static void
543coap_free_resource(coap_resource_t *resource, coap_deleting_resource_t deleting) {
544 coap_attr_t *attr, *tmp;
545 coap_subscription_t *obs, *otmp;
546 coap_context_t *context;
547
548 assert(resource);
549
550 context = resource->context;
551 if (context) {
552 if (!context->observe_no_clear) {
553 coap_resource_notify_observers_lkd(resource, deleting);
554 coap_notify_observers(context, resource, deleting);
555 }
556
557 if (context->resource_deleted_cb)
558 coap_lock_callback(context->resource_deleted_cb(context,
559 resource->uri_path,
560 context->observe_user_data));
561
562 if (context->release_userdata_cb && resource->user_data) {
563 coap_lock_callback(context->release_userdata_cb(resource->user_data));
564 }
565 }
566
567 /* delete registered attributes */
568 LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr);
569
570 /* Either the application provided or libcoap copied - need to delete it */
571 coap_delete_str_const(resource->uri_path);
572
573 /* free all elements from resource->subscribers */
574 LL_FOREACH_SAFE(resource->subscribers, obs, otmp) {
575 coap_delete_observer_internal(resource, obs->session, obs);
576 }
577 if (resource->proxy_name_count && resource->proxy_name_list) {
578 size_t i;
579
580 for (i = 0; i < resource->proxy_name_count; i++) {
581 coap_delete_str_const(resource->proxy_name_list[i]);
582 }
583 coap_free_type(COAP_STRING, resource->proxy_name_list);
584 }
585
586 coap_free_type(COAP_RESOURCE, resource);
587}
588
589COAP_API void
591 coap_lock_lock(return);
592 coap_add_resource_lkd(context, resource);
594}
595
596void
597coap_add_resource_lkd(coap_context_t *context, coap_resource_t *resource) {
599 if (resource->is_unknown) {
600 if (context->unknown_resource)
601 coap_free_resource(context->unknown_resource, COAP_DELETING_RESOURCE);
602 context->unknown_resource = resource;
603 } else if (resource->is_proxy_uri) {
604 if (context->proxy_uri_resource)
605 coap_free_resource(context->proxy_uri_resource, COAP_DELETING_RESOURCE);
606 context->proxy_uri_resource = resource;
607 } else {
608 coap_resource_t *r = coap_get_resource_from_uri_path_lkd(context,
609 resource->uri_path);
610
611 if (r) {
612 coap_log_warn("coap_add_resource: Duplicate uri_path '%*.*s', old resource deleted\n",
613 (int)resource->uri_path->length, (int)resource->uri_path->length,
614 resource->uri_path->s);
615 coap_delete_resource_lkd(r);
616 }
617 RESOURCES_ADD(context->resources, resource);
618#if COAP_WITH_OBSERVE_PERSIST
619 if (context->unknown_pdu && context->dyn_resource_save_file &&
620 context->dyn_resource_added_cb && resource->observable) {
621 coap_bin_const_t raw_packet;
622
623 raw_packet.s = context->unknown_pdu->token -
624 context->unknown_pdu->hdr_size;
625 raw_packet.length = context->unknown_pdu->used_size +
626 context->unknown_pdu->hdr_size;
627 coap_lock_callback(context->dyn_resource_added_cb(context->unknown_session,
628 resource->uri_path,
629 &raw_packet,
630 context->observe_user_data));
631 }
632#endif /* COAP_WITH_OBSERVE_PERSIST */
633 }
634 assert(resource->context == NULL);
635 resource->context = context;
636}
637
638COAP_API int
640 int ret;
641
642 (void)context;
643 if (!resource)
644 return 0;
645
646 coap_lock_lock(return 0);
647 ret = coap_delete_resource_lkd(resource);
649 return ret;
650}
651
652/*
653 * Input context is ignored, but param left there to keep API consistent
654 */
655int
656coap_delete_resource_lkd(coap_resource_t *resource) {
657 coap_context_t *context;
658 coap_deleting_resource_t deleting;
659
660 if (!resource)
661 return 0;
662
663 context = resource->context;
665
666 if (resource->ref) {
667 resource->ref--;
668 return 1;
669 }
670 if (context && context->context_going_away) {
671 deleting = COAP_DELETING_RESOURCE_ON_EXIT;
672 } else {
673 deleting = COAP_DELETING_RESOURCE;
674 }
675 if (resource->is_unknown) {
676 if (context && context->unknown_resource == resource) {
677 context->unknown_resource = NULL;
678 }
679 } else if (resource->is_proxy_uri) {
680 if (context && context->proxy_uri_resource == resource) {
681 context->proxy_uri_resource = NULL;
682 }
683 } else if (context) {
684 /* remove resource from list */
685 RESOURCES_DELETE(context->resources, resource);
686 }
687 if (resource->is_dynamic) {
688 if (context) {
689 assert(context->dynamic_cur);
690 context->dynamic_cur--;
691 }
692 }
693
694 /* and free its allocated memory */
695 coap_free_resource(resource, deleting);
696
697 return 1;
698}
699
700void
701coap_delete_all_resources(coap_context_t *context) {
703 coap_resource_t *tmp;
704
705 RESOURCE_ITER_SAFE(context->resources, r, tmp) {
706 coap_delete_resource_lkd(r);
707 }
708
709 context->resources = NULL;
710
711 if (context->unknown_resource) {
712 coap_delete_resource_lkd(context->unknown_resource);
713 context->unknown_resource = NULL;
714 }
715 if (context->proxy_uri_resource) {
716 coap_delete_resource_lkd(context->proxy_uri_resource);
717 context->proxy_uri_resource = NULL;
718 }
719}
720
723 coap_resource_t *result;
724
725 coap_lock_lock(return NULL);
726 result = coap_get_resource_from_uri_path_lkd(context, uri_path);
728
729 return result;
730}
731
733coap_get_resource_from_uri_path_lkd(coap_context_t *context,
734 coap_str_const_t *uri_path) {
735 coap_resource_t *result;
736
738
739 RESOURCES_FIND(context->resources, uri_path, result);
740
741 return result;
742}
743
745coap_print_link(const coap_resource_t *resource,
746 unsigned char *buf, size_t *len, size_t *offset) {
747 unsigned char *p = buf;
748 const uint8_t *bufend = buf + *len;
749 coap_attr_t *attr;
750 coap_print_status_t result = 0;
751 coap_print_status_t output_length = 0;
752 const size_t old_offset = *offset;
753
754 *len = 0;
755 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '<', *len);
756 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '/', *len);
757
758 COPY_COND_WITH_OFFSET(p, bufend, *offset,
759 resource->uri_path->s, resource->uri_path->length, *len);
760
761 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '>', *len);
762
763 LL_FOREACH(resource->link_attr, attr) {
764
765 PRINT_COND_WITH_OFFSET(p, bufend, *offset, ';', *len);
766
767 COPY_COND_WITH_OFFSET(p, bufend, *offset,
768 attr->name->s, attr->name->length, *len);
769
770 if (attr->value && attr->value->s) {
771 PRINT_COND_WITH_OFFSET(p, bufend, *offset, '=', *len);
772
773 COPY_COND_WITH_OFFSET(p, bufend, *offset,
774 attr->value->s, attr->value->length, *len);
775 }
776
777 }
778 if (resource->observable) {
779 COPY_COND_WITH_OFFSET(p, bufend, *offset, ";obs", 4, *len);
780 }
781
782#if COAP_OSCORE_SUPPORT
783 /* If oscore is enabled */
784 if (resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY)
785 COPY_COND_WITH_OFFSET(p, bufend, *offset, ";osc", 4, *len);
786#endif /* COAP_OSCORE_SUPPORT */
787
788 output_length = (coap_print_status_t)(p - buf);
789
790 if (output_length > COAP_PRINT_STATUS_MAX) {
792 }
793
794 result = (coap_print_status_t)output_length;
795
796 if (result + old_offset - *offset < *len) {
797 result |= COAP_PRINT_STATUS_TRUNC;
798 }
799
800 return result;
801}
802
803void
805 coap_request_t method,
806 coap_method_handler_t handler) {
807 coap_register_request_handler(resource, method, handler);
808}
809
810void
812 coap_request_t method,
813 coap_method_handler_t handler) {
814 assert(resource);
815 assert(method > 0 && (size_t)(method-1) <
816 sizeof(resource->handler)/sizeof(coap_method_handler_t));
817 resource->handler[method-1] = handler;
818}
819
821coap_find_observer(coap_resource_t *resource, coap_session_t *session,
822 const coap_bin_const_t *token) {
824
825 assert(resource);
826 assert(session);
827
828 LL_FOREACH(resource->subscribers, s) {
829 if (s->session == session &&
830 (!token || coap_binary_equal(token, &s->pdu->actual_token)))
831 return s;
832 }
833
834 return NULL;
835}
836
837static coap_subscription_t *
838coap_find_observer_cache_key(coap_resource_t *resource, coap_session_t *session,
839 const coap_cache_key_t *cache_key) {
841
842 assert(resource);
843 assert(session);
844
845 LL_FOREACH(resource->subscribers, s) {
846 if (s->session == session
847 && (memcmp(cache_key, s->cache_key, sizeof(coap_cache_key_t)) == 0))
848 return s;
849 }
850
851 return NULL;
852}
853
854/* https://rfc-editor.org/rfc/rfc7641#section-3.6 */
855static const uint16_t cache_ignore_options[] = { COAP_OPTION_ETAG,
857 };
859coap_add_observer(coap_resource_t *resource,
860 coap_session_t *session,
861 const coap_bin_const_t *token,
862 const coap_pdu_t *request) {
864 coap_cache_key_t *cache_key = NULL;
865 size_t len;
866 const uint8_t *data;
867
868 assert(session);
869
870 /* Check if there is already a subscription for this peer. */
871 s = coap_find_observer(resource, session, token);
872 if (!s) {
873 /*
874 * Cannot allow a duplicate to be created for the same query as application
875 * may not be cleaning up duplicates. If duplicate found, then original
876 * observer is deleted and a new one created with the new token
877 */
878 cache_key = coap_cache_derive_key_w_ignore(session, request,
880 cache_ignore_options,
881 sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0]));
882 if (cache_key) {
883 s = coap_find_observer_cache_key(resource, session, cache_key);
884 if (s) {
885 /* Delete old entry with old token */
886 coap_delete_observer(resource, session, &s->pdu->actual_token);
887 s = NULL;
888 }
889 }
890 }
891
892 /* Refresh the destination when an existing observation is renewed. */
893 if (s) {
894 coap_address_copy(&s->local_if, &session->addr_info.local);
895 return s;
896 }
897
898 /* Check if there is already maximum number of subscribers present */
899#if (COAP_RESOURCE_MAX_SUBSCRIBER > 0)
900 uint32_t subscriber_count = 0;
901 LL_COUNT(resource->subscribers, s, subscriber_count);
902 if (subscriber_count >= COAP_RESOURCE_MAX_SUBSCRIBER) {
903 return NULL; /* Signal error */
904 }
905#endif /* COAP_RESOURCE_MAX_SUBSCRIBER */
906
907 /* Create a new subscription */
909
910 if (!s) {
911 coap_delete_cache_key(cache_key);
912 return NULL;
913 }
914
915 coap_subscription_init(s);
916 s->pdu = coap_pdu_duplicate_lkd(request, session, token->length,
917 token->s, NULL, COAP_BOOL_FALSE);
918 if (s->pdu == NULL) {
919 coap_delete_cache_key(cache_key);
921 return NULL;
922 }
923 if (coap_get_data(request, &len, &data)) {
924 /* This could be a large bodied FETCH */
925 s->pdu->max_size = 0;
926 coap_add_data(s->pdu, len, data);
927 }
928 if (cache_key == NULL) {
929 cache_key = coap_cache_derive_key_w_ignore(session, request,
931 cache_ignore_options,
932 sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0]));
933 if (cache_key == NULL) {
934 coap_delete_pdu_lkd(s->pdu);
935 coap_delete_cache_key(cache_key);
937 return NULL;
938 }
939 }
940 s->cache_key = cache_key;
941 s->session = coap_session_reference_lkd(session);
942 coap_address_copy(&s->local_if, &session->addr_info.local);
943 session->ref_subscriptions++;
944
945 /* add subscriber to resource */
946 LL_PREPEND(resource->subscribers, s);
947
948 coap_log_debug("create new subscription %p key 0x%02x%02x%02x%02x\n",
949 (void *)s, s->cache_key->key[0], s->cache_key->key[1],
950 s->cache_key->key[2], s->cache_key->key[3]);
951
952 if (session->context->observe_added_cb && session->proto == COAP_PROTO_UDP &&
953 !coap_is_af_unix(&session->addr_info.local)) {
954 coap_bin_const_t raw_packet;
955 coap_bin_const_t *oscore_info = NULL;
956#if COAP_OSCORE_SUPPORT
957 oscore_association_t *association;
958
959 if (session->recipient_ctx && session->recipient_ctx->recipient_id) {
960 /*
961 * Need to track the association used for tracking this observe, done as
962 * a CBOR array. Read in coap_persist_observe_add().
963 *
964 * If an entry is null, then use nil, else a set of bytes
965 *
966 * Currently tracking 5 items
967 * recipient_id
968 * id_context
969 * aad (from oscore_association_t)
970 * partial_iv (from oscore_association_t)
971 * nonce (from oscore_association_t)
972 */
973 uint8_t info_buffer[60];
974 uint8_t *info_buf = info_buffer;
975 size_t info_len = sizeof(info_buffer);
976 size_t ret = 0;
977 coap_bin_const_t ctoken = { token->length, token->s };
978
979 ret += oscore_cbor_put_array(&info_buf, &info_len, 5);
980 ret += oscore_cbor_put_bytes(&info_buf,
981 &info_len,
982 session->recipient_ctx->recipient_id->s,
983 session->recipient_ctx->recipient_id->length);
984 if (session->recipient_ctx->osc_ctx &&
985 session->recipient_ctx->osc_ctx->id_context) {
986 ret += oscore_cbor_put_bytes(&info_buf,
987 &info_len,
988 session->recipient_ctx->osc_ctx->id_context->s,
989 session->recipient_ctx->osc_ctx->id_context->length);
990 } else {
991 ret += oscore_cbor_put_nil(&info_buf, &info_len);
992 }
993 association = oscore_find_association(session, &ctoken);
994 if (association) {
995 if (association->aad) {
996 ret += oscore_cbor_put_bytes(&info_buf,
997 &info_len,
998 association->aad->s,
999 association->aad->length);
1000 } else {
1001 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1002 }
1003 if (association->partial_iv) {
1004 ret += oscore_cbor_put_bytes(&info_buf,
1005 &info_len,
1006 association->partial_iv->s,
1007 association->partial_iv->length);
1008 } else {
1009 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1010 }
1011 if (association->nonce) {
1012 ret += oscore_cbor_put_bytes(&info_buf,
1013 &info_len,
1014 association->nonce->s,
1015 association->nonce->length);
1016 } else {
1017 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1018 }
1019 } else {
1020 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1021 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1022 }
1023 if (ret > sizeof(info_buffer)) {
1024 /* Should have been caught by assert() inoscborput_* functions */
1025 coap_log_warn("coap_add_observer overrun of info_buffer (%" PRIuS ")\n", ret);
1026 ret = sizeof(info_buffer);
1027 }
1028 oscore_info = coap_new_bin_const(info_buffer, ret);
1029 }
1030#endif /* COAP_OSCORE_SUPPORT */
1031
1032 /* s->pdu header is not currently encoded */
1033 memcpy(s->pdu->token - request->hdr_size,
1034 request->token - request->hdr_size, request->hdr_size);
1035 raw_packet.s = s->pdu->token - request->hdr_size;
1036 raw_packet.length = s->pdu->used_size + request->hdr_size;
1037 coap_lock_callback(session->context->observe_added_cb(session, s, session->proto,
1038 &session->endpoint->bind_addr,
1039 &session->addr_info,
1040 &raw_packet,
1041 oscore_info,
1042 session->context->observe_user_data));
1043#if COAP_OSCORE_SUPPORT
1044 coap_delete_bin_const(oscore_info);
1045#endif /* COAP_OSCORE_SUPPORT */
1046 }
1047 if (resource->context->track_observe_value_cb) {
1048 /* Track last used observe value (as app handler is called) */
1049 coap_lock_callback(resource->context->track_observe_value_cb(resource->context,resource->uri_path,
1050 resource->observe,
1051 resource->context->observe_user_data));
1052 }
1053
1054 return s;
1055}
1056
1057void
1058coap_touch_observer(coap_context_t *context, coap_session_t *session,
1059 const coap_bin_const_t *token) {
1061
1062 RESOURCES_ITER(context->resources, r) {
1063 s = coap_find_observer(r, session, token);
1064 if (s) {
1065 s->fail_cnt = 0;
1066 }
1067 }
1068}
1069
1070void
1071coap_delete_observer_internal(coap_resource_t *resource, coap_session_t *session,
1073 if (!s)
1074 return;
1075
1077 char outbuf[2 * 8 + 1] = "";
1078 unsigned int i;
1079 coap_string_t *uri_path;
1080 coap_string_t *uri_query;
1081
1082 for (i = 0; i < s->pdu->actual_token.length; i++) {
1083 size_t size = strlen(outbuf);
1084
1085 snprintf(&outbuf[size], sizeof(outbuf)-size, "%02x",
1086 s->pdu->actual_token.s[i]);
1087 }
1088 uri_path = coap_get_uri_path(s->pdu);
1089 uri_query = coap_get_query(s->pdu);
1090 coap_log_debug("removed subscription '/%*.*s%s%*.*s' (%p) with token '%s' key 0x%02x%02x%02x%02x\n",
1091 uri_path ? (int)uri_path->length : 0, uri_path ? (int)uri_path->length : 0,
1092 uri_path ? (char *)uri_path->s : "",
1093 uri_query ? "?" : "",
1094 uri_query ? (int)uri_query->length : 0, uri_query ? (int)uri_query->length : 0,
1095 uri_query ? (char *)uri_query->s : "",
1096 (void *)s, outbuf, s->cache_key->key[0], s->cache_key->key[1],
1097 s->cache_key->key[2], s-> cache_key->key[3]);
1098 coap_delete_string(uri_path);
1099 coap_delete_string(uri_query);
1100 }
1101 if (session->context->observe_deleted_cb)
1102 coap_lock_callback(session->context->observe_deleted_cb(session, s,
1103 session->context->observe_user_data));
1104
1105 if (resource->subscribers) {
1106 LL_DELETE(resource->subscribers, s);
1107 assert(session->ref_subscriptions > 0);
1108 session->ref_subscriptions--;
1109 coap_session_release_lkd(session);
1110 coap_delete_pdu_lkd(s->pdu);
1111 coap_delete_cache_key(s->cache_key);
1113 }
1114
1115 return;
1116}
1117
1118int
1119coap_delete_observer(coap_resource_t *resource, coap_session_t *session,
1120 const coap_bin_const_t *token) {
1122
1123 s = coap_find_observer(resource, session, token);
1124 if (s)
1125 coap_delete_observer_internal(resource, session, s);
1126
1127 return s != NULL;
1128}
1129
1130int
1131coap_delete_observer_request(coap_resource_t *resource, coap_session_t *session,
1132 const coap_bin_const_t *token, coap_pdu_t *request, int large_fetch) {
1134 int ret = 0;
1135
1136 s = coap_find_observer(resource, session, token);
1137 if (!s && large_fetch) {
1138 /*
1139 * It is possible that the client is using the wrong token.
1140 * An example being a large FETCH spanning multiple blocks.
1141 */
1142 coap_cache_key_t *cache_key;
1143
1144 cache_key = coap_cache_derive_key_w_ignore(session, request,
1146 cache_ignore_options,
1147 sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0]));
1148 if (cache_key) {
1149 s = coap_find_observer_cache_key(resource, session, cache_key);
1150 if (s) {
1151 /* Delete entry with setup token */
1152 ret = coap_delete_observer(resource, session, &s->pdu->actual_token);
1153 }
1154 coap_delete_cache_key(cache_key);
1155 }
1156 } else {
1157 coap_delete_observer_internal(resource, session, s);
1158 ret = 1;
1159 }
1160 return ret;
1161}
1162
1163void
1164coap_delete_observers(coap_context_t *context, coap_session_t *session) {
1165 RESOURCES_ITER(context->resources, resource) {
1166 coap_subscription_t *s, *tmp;
1167 LL_FOREACH_SAFE(resource->subscribers, s, tmp) {
1168 if (s->session == session) {
1169 if (context->observe_deleted_cb)
1170 coap_lock_callback(context->observe_deleted_cb(session, s, context->observe_user_data));
1171 assert(resource->subscribers);
1172 LL_DELETE(resource->subscribers, s);
1173 coap_session_release_lkd(session);
1174 coap_delete_pdu_lkd(s->pdu);
1175 coap_delete_cache_key(s->cache_key);
1177 }
1178 }
1179 }
1180}
1181
1182static void
1183coap_notify_observers(coap_context_t *context, coap_resource_t *r,
1184 coap_deleting_resource_t deleting) {
1186 coap_subscription_t *obs, *otmp;
1187 coap_pdu_t *response;
1188 uint8_t buf[4];
1189 coap_string_t *query;
1190 coap_block_b_t block;
1191 coap_tick_t now;
1192
1194
1195 if (r->observable && (r->dirty || r->partiallydirty)) {
1196 if (r->list_being_traversed)
1197 return;
1198 r->list_being_traversed = 1;
1199
1200 coap_resource_reference_lkd(r);
1201
1202 r->partiallydirty = 0;
1203
1204 LL_FOREACH_SAFE(r->subscribers, obs, otmp) {
1205 coap_session_t *obs_session;
1206 coap_pdu_t *obs_pdu;
1208
1209 if ((r->dirty == 0 && obs->dirty == 0) || obs->session->is_rate_limiting) {
1210 /*
1211 * running this resource due to partiallydirty, but this observation's
1212 * notification was already enqueued
1213 */
1214 context->observe_pending = 1;
1215 continue;
1216 }
1217
1218 /*
1219 * obs may get deleted in the callback, or by another running
1220 * thread when executing the callback or when sending a response.
1221 */
1222 obs_session = obs->session;
1223 obs_pdu = obs->pdu;
1224 coap_session_reference_lkd(obs_session);
1225 coap_pdu_reference_lkd(obs_pdu);
1226
1227 if (obs->session->con_active >= COAP_NSTART(obs->session) &&
1228 ((r->flags & COAP_RESOURCE_FLAGS_NOTIFY_CON) ||
1229 (obs->non_cnt >= COAP_OBS_MAX_NON))) {
1230 /* Waiting for the previous unsolicited response to finish */
1231 goto next_one_fail;
1232 }
1233 coap_ticks(&now);
1234 if (obs->session->lg_xmit && obs->session->lg_xmit->last_all_sent == 0 &&
1235 obs->session->lg_xmit->last_obs &&
1236 (obs->session->lg_xmit->last_obs + 2*COAP_TICKS_PER_SECOND) > now) {
1237 /* Waiting for the previous blocked unsolicited response to finish */
1238 goto next_one_fail;
1239 }
1240
1241 /* Other packets on this session may have changed the local address,
1242 * including multicast requests from the same peer and source port.
1243 * Restore it before the handler can register an async response. */
1244 coap_address_copy(&obs_session->addr_info.local, &obs->local_if);
1245
1246 obs->dirty = 0;
1247 /* initialize response */
1248 response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0,
1249 coap_session_max_pdu_size_lkd(obs->session));
1250 if (!response) {
1251 coap_log_debug("coap_check_notify: pdu init failed, resource stays "
1252 "partially dirty\n");
1253 goto next_one_fail_no_pending;
1254 }
1255
1256 if (!coap_add_token(response, obs->pdu->actual_token.length,
1257 obs->pdu->actual_token.s)) {
1258 coap_log_debug("coap_check_notify: cannot add token, resource stays "
1259 "partially dirty\n");
1260 coap_delete_pdu_lkd(response);
1261 goto next_one_fail_no_pending;
1262 }
1263
1264 obs->pdu->mid = response->mid = coap_new_message_id_lkd(obs->session);
1265 /* A lot of the reliable code assumes type is CON */
1266 if (COAP_PROTO_NOT_RELIABLE(obs->session->proto) &&
1267 (r->flags & COAP_RESOURCE_FLAGS_NOTIFY_CON) == 0 &&
1269 obs->non_cnt < COAP_OBS_MAX_NON)) {
1270 response->type = COAP_MESSAGE_NON;
1271 } else {
1272 response->type = COAP_MESSAGE_CON;
1273 }
1274 switch (deleting) {
1275 case COAP_NOT_DELETING_RESOURCE:
1276 /* fill with observer-specific data */
1278 coap_encode_var_safe(buf, sizeof(buf),
1279 r->observe),
1280 buf);
1281 if (coap_get_block_b(obs->session, obs->pdu, COAP_OPTION_BLOCK2,
1282 &block)) {
1283 /* Will get updated later (e.g. M bit) if appropriate */
1285 coap_encode_var_safe(buf, sizeof(buf),
1286 ((0 << 4) |
1287 (0 << 3) |
1288 block.aszx)),
1289 buf);
1290 }
1291#if COAP_Q_BLOCK_SUPPORT
1292 else if (coap_get_block_b(obs->session, obs->pdu, COAP_OPTION_Q_BLOCK2,
1293 &block)) {
1294 /* Will get updated later (e.g. M bit) if appropriate */
1296 coap_encode_var_safe(buf, sizeof(buf),
1297 ((0 << 4) |
1298 (0 << 3) |
1299 block.szx)),
1300 buf);
1301 }
1302#endif /* COAP_Q_BLOCK_SUPPORT */
1303
1304 h = r->handler[obs->pdu->code - 1];
1305 assert(h); /* we do not allow subscriptions if no
1306 * GET/FETCH handler is defined */
1307 query = coap_get_query(obs->pdu);
1308 coap_log_debug("Observe PDU presented to app.\n");
1309 coap_show_pdu(COAP_LOG_DEBUG, obs->pdu);
1310 coap_log_debug("call custom handler for resource '%*.*s' (4)\n",
1311 (int)r->uri_path->length, (int)r->uri_path->length,
1312 r->uri_path->s);
1313
1314 /* obs may get deleted during callback (potentially by another thread) */
1315 if (r->flags & COAP_RESOURCE_SAFE_REQUEST_HANDLER) {
1316 coap_lock_callback_release(h(r, obs->session, obs->pdu, query, response),
1317 /* context is being freed off */
1318 coap_delete_string(query);
1319 coap_delete_pdu_lkd(response);
1320 coap_session_release_lkd(obs_session);
1321 coap_pdu_release_lkd(obs_pdu);
1322 r->list_being_traversed = 0;
1323 coap_resource_release_lkd(r);
1324 return);
1325 } else {
1327 h(r, obs->session, obs->pdu, query, response),
1328 /* context is being freed off */
1329 coap_delete_string(query);
1330 coap_delete_pdu_lkd(response);
1331 coap_session_release_lkd(obs_session);
1332 coap_pdu_release_lkd(obs_pdu);
1333 r->list_being_traversed = 0;
1334 coap_resource_release_lkd(r);
1335 return);
1336 }
1337
1338 /* Check validity of response code */
1339 if (!coap_check_code_class(obs_session, response)) {
1340 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
1341 COAP_RESPONSE_CLASS(response->code),
1342 response->code & 0x1f);
1343 coap_delete_string(query);
1344 coap_delete_pdu_lkd(response);
1345 coap_session_release_lkd(obs_session);
1346 coap_pdu_release_lkd(obs_pdu);
1347 r->list_being_traversed = 0;
1348 coap_resource_release_lkd(r);
1349 return;
1350 }
1351
1352 /* Check if lg_xmit generated and update PDU code if so */
1353 coap_check_code_lg_xmit(obs_session, obs_pdu, response, r, query);
1354 coap_delete_string(query);
1355 if (COAP_RESPONSE_CLASS(response->code) != 2) {
1357 }
1358 if (COAP_RESPONSE_CLASS(response->code) > 2) {
1359 coap_delete_observer(r, obs_session, &obs_pdu->actual_token);
1360 obs = NULL;
1361 }
1362 break;
1363 case COAP_DELETING_RESOURCE_ON_EXIT:
1364 /* Don't worry if it does not get there */
1365 response->type = COAP_MESSAGE_NON;
1366 response->code = COAP_RESPONSE_CODE(503);
1368 coap_encode_var_safe(buf, sizeof(buf),
1369 30),
1370 buf);
1371 break;
1372 case COAP_DELETING_RESOURCE:
1373 default:
1374 /* Don't worry if it does not get there */
1375 response->type = COAP_MESSAGE_NON;
1376 response->code = COAP_RESPONSE_CODE(404);
1377 break;
1378 }
1379
1380 if (obs) {
1382 /*
1383 * obs may have been deleted in the callback, or by another running
1384 * thread when executing the callback.
1385 */
1386 LL_FOREACH(r->subscribers, s) {
1387 if (s == obs) {
1388 break;
1389 }
1390 }
1391 if (s == NULL)
1392 obs = NULL;
1393 }
1394 if (obs) {
1395 if (response->type == COAP_MESSAGE_CON ||
1397 obs->non_cnt = 0;
1398 } else {
1399 obs->non_cnt++;
1400 }
1401
1402#if COAP_Q_BLOCK_SUPPORT
1403 if (response->code == COAP_RESPONSE_CODE(205) &&
1404 coap_get_block_b(obs_session, response, COAP_OPTION_Q_BLOCK2,
1405 &block) &&
1406 block.m) {
1407 query = coap_get_query(obs_pdu);
1408 mid = coap_send_q_block2(obs_session, r, query, obs_pdu->code,
1409 block, response, 1);
1410 coap_delete_string(query);
1411 goto finish;
1412 }
1413#endif /* COAP_Q_BLOCK_SUPPORT */
1414 }
1415 mid = coap_send_internal(obs_session, response, NULL);
1416
1417#if COAP_Q_BLOCK_SUPPORT
1418finish:
1419#endif /* COAP_Q_BLOCK_SUPPORT */
1420 if (COAP_INVALID_MID == mid) {
1421 coap_log_debug("* %s: coap_check_notify: sending failed, resource stays "
1422 "partially dirty\n", coap_session_str(obs_session));
1423 if (obs) {
1425 /*
1426 * obs may have been deleted in coap_send_internal() or
1427 * coap_send_q_block2().
1428 */
1429 LL_FOREACH(r->subscribers, s) {
1430 if (s == obs) {
1431 break;
1432 }
1433 }
1434 if (s == NULL)
1435 obs = NULL;
1436 }
1437 if (obs)
1438 obs->dirty = 1;
1439 r->partiallydirty = 1;
1440 }
1441 goto cleanup;
1442
1443next_one_fail:
1444 context->observe_pending = 1;
1445next_one_fail_no_pending:
1446 r->partiallydirty = 1;
1447 if (obs)
1448 obs->dirty = 1;
1449cleanup:
1450 coap_session_release_lkd(obs_session);
1451 coap_pdu_release_lkd(obs_pdu);
1452 }
1453 r->list_being_traversed = 0;
1454 r->dirty = 0;
1455 coap_resource_release_lkd(r);
1456 /* r may be no more if elsewhere coap_free_resource() has been called */
1457 } else {
1458 r->dirty = 0;
1459 }
1460}
1461
1462COAP_API int
1464 int ret;
1465 (void)query;
1466
1467 coap_lock_lock(return 0);
1468 ret = coap_resource_notify_observers_lkd(r, COAP_NOT_DELETING_RESOURCE);
1470 return ret;
1471}
1472
1473COAP_API int
1475 const coap_string_t *query) {
1476 int ret;
1477
1478 (void)query;
1479 coap_lock_lock(return 0);
1480 ret = coap_resource_notify_observers_lkd(r, COAP_NOT_DELETING_RESOURCE);
1482 return ret;
1483}
1484
1485int
1486coap_resource_notify_observers_lkd(coap_resource_t *r,
1487 coap_deleting_resource_t deleting) {
1489 if (!r->observable)
1490 return 0;
1491 if (!r->subscribers)
1492 return 0;
1493 r->dirty = 1;
1494
1495 /* Increment value for next Observe use. Observe value must be < 2^24 */
1496 r->observe = (r->observe + 1) & 0xFFFFFF;
1497
1498 assert(r->context);
1499
1500 if (r->context->track_observe_value_cb) {
1501 /* Track last used observe value */
1502 if ((r->observe % r->context->observe_save_freq) == 0)
1503 coap_lock_callback(r->context->track_observe_value_cb(r->context, r->uri_path,
1504 r->observe,
1505 r->context->observe_user_data));
1506 }
1507
1508 coap_notify_observers(r->context, r, deleting);
1509 return 1;
1510}
1511
1512void
1513coap_resource_set_mode(coap_resource_t *resource, int mode) {
1514 resource->flags = (resource->flags &
1517}
1518
1519void
1520coap_resource_set_userdata(coap_resource_t *resource, void *data) {
1521 resource->user_data = data;
1522}
1523
1524void *
1526 return resource->user_data;
1527}
1528
1529void
1532 context->release_userdata_cb = callback;
1533}
1534
1535void
1537 if (resource->is_unknown || resource->is_proxy_uri) {
1538 /* We cannot observe these */
1539 coap_log_debug("coap_resource_set_get_observable: Not supported for Unknown or Proxy URIs\n");
1540 resource->observable = 0;
1541 } else {
1542 resource->observable = mode ? 1 : 0;
1543 }
1544}
1545
1548 if (resource)
1549 return resource->uri_path;
1550 return NULL;
1551}
1552
1553COAP_API void
1555 coap_lock_lock(return);
1556 coap_check_notify_lkd(context);
1558}
1559
1560void
1561coap_check_notify_lkd(coap_context_t *context) {
1562
1564 if (context->observe_pending) {
1565 context->observe_pending = 0;
1566 RESOURCES_ITER(context->resources, r) {
1567 coap_notify_observers(context, r, COAP_NOT_DELETING_RESOURCE);
1568 }
1569 }
1570}
1571
1572void
1574 uint32_t start_observe_no) {
1575 if (!resource)
1576 return;
1577
1578 resource->observe = start_observe_no & 0xffffff;
1579}
1580
1591static void
1592coap_remove_failed_observers(coap_context_t *context,
1593 coap_resource_t *resource,
1594 coap_session_t *session,
1595 const coap_bin_const_t *token) {
1596 coap_subscription_t *obs, *otmp;
1597
1598 LL_FOREACH_SAFE(resource->subscribers, obs, otmp) {
1599 if (obs->session == session &&
1600 coap_binary_equal(token, &obs->pdu->actual_token)) {
1601 /* count failed notifies and remove when
1602 * COAP_OBS_MAX_FAIL is reached */
1603 obs->fail_cnt++;
1604 if (obs->fail_cnt >= COAP_OBS_MAX_FAIL) {
1605 coap_cancel_all_messages(context, obs->session,
1606 &obs->pdu->actual_token);
1607 coap_delete_observer(resource, session, token);
1608 }
1609 break; /* break loop if observer was found */
1610 }
1611 }
1612}
1613
1614void
1615coap_handle_failed_notify(coap_context_t *context,
1616 coap_session_t *session,
1617 const coap_bin_const_t *token) {
1618
1619 RESOURCES_ITER(context->resources, r) {
1620 coap_remove_failed_observers(context, r, session, token);
1621 }
1622}
1623
1624void
1625coap_resource_reference_lkd(coap_resource_t *resource) {
1626 resource->ref++;
1627}
1628
1630coap_add_dynamic_resource(coap_session_t *session, coap_pdu_t *pdu) {
1631 coap_context_t *context = session->context;
1632 coap_resource_t *resource;
1633
1634 if ((context->dyn_create_handler != NULL) &&
1636 /* Above test must be the same as in coap_op_dyn_resource_load_disk() */
1637 if (context->dynamic_cur < context->dynamic_max || context->dynamic_max == 0) {
1638#if COAP_WITH_OBSERVE_PERSIST
1639 /* If we are maintaining Observe persist */
1640 context->unknown_pdu = pdu;
1641 context->unknown_session = session;
1642#endif /* COAP_WITH_OBSERVE_PERSIST */
1643 coap_lock_callback_ret(resource, context->dyn_create_handler(session, pdu));
1644#if COAP_WITH_OBSERVE_PERSIST
1645 /* If we are maintaining Observe persist */
1646 context->unknown_pdu = NULL;
1647 context->unknown_session = NULL;
1648#endif /* COAP_WITH_OBSERVE_PERSIST */
1649 if (resource) {
1650 context->dynamic_cur++;
1651 resource->is_dynamic = 1;
1652 }
1653 return resource;
1654 }
1655 }
1656 return NULL;
1657}
1658
1659#endif /* COAP_SERVER_SUPPORT */
int coap_is_af_unix(const coap_address_t *a)
Checks if given address a denotes a AF_UNIX address.
void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
struct coap_cache_key_t coap_cache_key_t
struct coap_attr_t coap_attr_t
struct coap_subscription_t coap_subscription_t
struct coap_resource_t coap_resource_t
#define PRIuS
Library specific build wrapper for coap_internal.h.
#define COAP_API
@ COAP_RESOURCE
Definition coap_mem.h:42
@ COAP_RESOURCEATTR
Definition coap_mem.h:43
@ COAP_SUBSCRIPTION
Definition coap_mem.h:53
@ COAP_STRING
Definition coap_mem.h:33
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().
#define NULL
Definition coap_option.h:30
@ COAP_OPTION_OBSERVE
Definition coap_option.h:75
@ COAP_OPTION_ETAG
Definition coap_option.h:73
@ COAP_OPTION_MAXAGE
Definition coap_option.h:83
@ COAP_OPTION_Q_BLOCK2
Definition coap_option.h:93
@ COAP_OPTION_BLOCK2
Definition coap_option.h:90
@ COAP_OPTION_OSCORE
Definition coap_option.h:78
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:71
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:41
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:149
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:164
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_RESOURCE_SAFE_REQUEST_HANDLER
Don't lock this resource when calling app call-back handler for requests as handler will not be manip...
#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:2099
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:1547
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:3367
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_specific_callback_release(lock, func, failed)
Dummy for no thread-safe code.
#define coap_lock_callback(func)
Dummy for no thread-safe code.
#define coap_lock_init(lock)
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, 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:812
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:1760
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:197
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:550
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, coap_bool_t expand_opt_abb)
Duplicate an existing PDU.
Definition coap_pdu.c:237
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:863
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:184
coap_request_t
CoAP PDU Request methods.
Definition coap_pdu.h:80
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:96
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:99
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:417
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:966
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:104
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:187
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition coap_pdu.h:55
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:935
@ COAP_BOOL_FALSE
Definition coap_pdu.h:295
@ COAP_REQUEST_PUT
Definition coap_pdu.h:83
@ COAP_REQUEST_DELETE
Definition coap_pdu.h:84
@ COAP_REQUEST_GET
Definition coap_pdu.h:81
@ COAP_REQUEST_FETCH
Definition coap_pdu.h:85
@ COAP_REQUEST_PATCH
Definition coap_pdu.h:86
@ COAP_REQUEST_IPATCH
Definition coap_pdu.h:87
@ COAP_REQUEST_POST
Definition coap_pdu.h:82
@ COAP_PROTO_UDP
Definition coap_pdu.h:236
@ COAP_REQUEST_CODE_PUT
Definition coap_pdu.h:253
@ COAP_REQUEST_CODE_POST
Definition coap_pdu.h:252
@ COAP_MESSAGE_NON
Definition coap_pdu.h:72
@ COAP_MESSAGE_CON
Definition coap_pdu.h:71
#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:130
void coap_delete_str_const(coap_str_const_t *s)
Deletes the given const string and releases any memory allocated.
Definition coap_str.c:65
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:119
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:222
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:208
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:55
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition coap_str.c:50
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition coap_uri.c:1182
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:1103
coap_address_t local
local address and port
Definition coap_io.h:59
CoAP binary data definition with const data.
Definition coap_str.h:65
size_t length
length of binary data
Definition coap_str.h:66
const uint8_t * s
read-only binary data
Definition coap_str.h:67
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.
uint32_t dynamic_cur
Current number of dynamic resources.
coap_resource_dynamic_create_t dyn_create_handler
Dynamic resource create handler.
uint32_t dynamic_max
Max number of dynamic resources or 0 is unlimited.
structure for CoAP PDUs
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
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
coap_pdu_type_t type
message type
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
coap_context_t * context
session's context
CoAP string data definition with const data.
Definition coap_str.h:47
const uint8_t * s
read-only string data
Definition coap_str.h:49
size_t length
length of string
Definition coap_str.h:48
CoAP string data definition.
Definition coap_str.h:39
uint8_t * s
string data
Definition coap_str.h:41
size_t length
length of string
Definition coap_str.h:40
coap_bin_const_t * partial_iv
coap_bin_const_t * aad
coap_bin_const_t * nonce