libcoap 4.3.5-develop-dfd5545
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 /* We are done if subscription was found. */
893 if (s) {
894 return s;
895 }
896
897 /* Check if there is already maximum number of subscribers present */
898#if (COAP_RESOURCE_MAX_SUBSCRIBER > 0)
899 uint32_t subscriber_count = 0;
900 LL_COUNT(resource->subscribers, s, subscriber_count);
901 if (subscriber_count >= COAP_RESOURCE_MAX_SUBSCRIBER) {
902 return NULL; /* Signal error */
903 }
904#endif /* COAP_RESOURCE_MAX_SUBSCRIBER */
905
906 /* Create a new subscription */
908
909 if (!s) {
910 coap_delete_cache_key(cache_key);
911 return NULL;
912 }
913
914 coap_subscription_init(s);
915 s->pdu = coap_pdu_duplicate_lkd(request, session, token->length,
916 token->s, NULL, COAP_BOOL_FALSE);
917 if (s->pdu == NULL) {
918 coap_delete_cache_key(cache_key);
920 return NULL;
921 }
922 if (coap_get_data(request, &len, &data)) {
923 /* This could be a large bodied FETCH */
924 s->pdu->max_size = 0;
925 coap_add_data(s->pdu, len, data);
926 }
927 if (cache_key == NULL) {
928 cache_key = coap_cache_derive_key_w_ignore(session, request,
930 cache_ignore_options,
931 sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0]));
932 if (cache_key == NULL) {
933 coap_delete_pdu_lkd(s->pdu);
934 coap_delete_cache_key(cache_key);
936 return NULL;
937 }
938 }
939 s->cache_key = cache_key;
940 s->session = coap_session_reference_lkd(session);
941 session->ref_subscriptions++;
942
943 /* add subscriber to resource */
944 LL_PREPEND(resource->subscribers, s);
945
946 coap_log_debug("create new subscription %p key 0x%02x%02x%02x%02x\n",
947 (void *)s, s->cache_key->key[0], s->cache_key->key[1],
948 s->cache_key->key[2], s->cache_key->key[3]);
949
950 if (session->context->observe_added_cb && session->proto == COAP_PROTO_UDP &&
951 !coap_is_af_unix(&session->addr_info.local)) {
952 coap_bin_const_t raw_packet;
953 coap_bin_const_t *oscore_info = NULL;
954#if COAP_OSCORE_SUPPORT
955 oscore_association_t *association;
956
957 if (session->recipient_ctx && session->recipient_ctx->recipient_id) {
958 /*
959 * Need to track the association used for tracking this observe, done as
960 * a CBOR array. Read in coap_persist_observe_add().
961 *
962 * If an entry is null, then use nil, else a set of bytes
963 *
964 * Currently tracking 5 items
965 * recipient_id
966 * id_context
967 * aad (from oscore_association_t)
968 * partial_iv (from oscore_association_t)
969 * nonce (from oscore_association_t)
970 */
971 uint8_t info_buffer[60];
972 uint8_t *info_buf = info_buffer;
973 size_t info_len = sizeof(info_buffer);
974 size_t ret = 0;
975 coap_bin_const_t ctoken = { token->length, token->s };
976
977 ret += oscore_cbor_put_array(&info_buf, &info_len, 5);
978 ret += oscore_cbor_put_bytes(&info_buf,
979 &info_len,
980 session->recipient_ctx->recipient_id->s,
981 session->recipient_ctx->recipient_id->length);
982 if (session->recipient_ctx->osc_ctx &&
983 session->recipient_ctx->osc_ctx->id_context) {
984 ret += oscore_cbor_put_bytes(&info_buf,
985 &info_len,
986 session->recipient_ctx->osc_ctx->id_context->s,
987 session->recipient_ctx->osc_ctx->id_context->length);
988 } else {
989 ret += oscore_cbor_put_nil(&info_buf, &info_len);
990 }
991 association = oscore_find_association(session, &ctoken);
992 if (association) {
993 if (association->aad) {
994 ret += oscore_cbor_put_bytes(&info_buf,
995 &info_len,
996 association->aad->s,
997 association->aad->length);
998 } else {
999 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1000 }
1001 if (association->partial_iv) {
1002 ret += oscore_cbor_put_bytes(&info_buf,
1003 &info_len,
1004 association->partial_iv->s,
1005 association->partial_iv->length);
1006 } else {
1007 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1008 }
1009 if (association->nonce) {
1010 ret += oscore_cbor_put_bytes(&info_buf,
1011 &info_len,
1012 association->nonce->s,
1013 association->nonce->length);
1014 } else {
1015 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1016 }
1017 } else {
1018 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1019 ret += oscore_cbor_put_nil(&info_buf, &info_len);
1020 }
1021 if (ret > sizeof(info_buffer)) {
1022 /* Should have been caught by assert() inoscborput_* functions */
1023 coap_log_warn("coap_add_observer overrun of info_buffer (%" PRIuS ")\n", ret);
1024 ret = sizeof(info_buffer);
1025 }
1026 oscore_info = coap_new_bin_const(info_buffer, ret);
1027 }
1028#endif /* COAP_OSCORE_SUPPORT */
1029
1030 /* s->pdu header is not currently encoded */
1031 memcpy(s->pdu->token - request->hdr_size,
1032 request->token - request->hdr_size, request->hdr_size);
1033 raw_packet.s = s->pdu->token - request->hdr_size;
1034 raw_packet.length = s->pdu->used_size + request->hdr_size;
1035 coap_lock_callback(session->context->observe_added_cb(session, s, session->proto,
1036 &session->endpoint->bind_addr,
1037 &session->addr_info,
1038 &raw_packet,
1039 oscore_info,
1040 session->context->observe_user_data));
1041#if COAP_OSCORE_SUPPORT
1042 coap_delete_bin_const(oscore_info);
1043#endif /* COAP_OSCORE_SUPPORT */
1044 }
1045 if (resource->context->track_observe_value_cb) {
1046 /* Track last used observe value (as app handler is called) */
1047 coap_lock_callback(resource->context->track_observe_value_cb(resource->context,resource->uri_path,
1048 resource->observe,
1049 resource->context->observe_user_data));
1050 }
1051
1052 return s;
1053}
1054
1055void
1056coap_touch_observer(coap_context_t *context, coap_session_t *session,
1057 const coap_bin_const_t *token) {
1059
1060 RESOURCES_ITER(context->resources, r) {
1061 s = coap_find_observer(r, session, token);
1062 if (s) {
1063 s->fail_cnt = 0;
1064 }
1065 }
1066}
1067
1068void
1069coap_delete_observer_internal(coap_resource_t *resource, coap_session_t *session,
1071 if (!s)
1072 return;
1073
1075 char outbuf[2 * 8 + 1] = "";
1076 unsigned int i;
1077 coap_string_t *uri_path;
1078 coap_string_t *uri_query;
1079
1080 for (i = 0; i < s->pdu->actual_token.length; i++) {
1081 size_t size = strlen(outbuf);
1082
1083 snprintf(&outbuf[size], sizeof(outbuf)-size, "%02x",
1084 s->pdu->actual_token.s[i]);
1085 }
1086 uri_path = coap_get_uri_path(s->pdu);
1087 uri_query = coap_get_query(s->pdu);
1088 coap_log_debug("removed subscription '/%*.*s%s%*.*s' (%p) with token '%s' key 0x%02x%02x%02x%02x\n",
1089 uri_path ? (int)uri_path->length : 0, uri_path ? (int)uri_path->length : 0,
1090 uri_path ? (char *)uri_path->s : "",
1091 uri_query ? "?" : "",
1092 uri_query ? (int)uri_query->length : 0, uri_query ? (int)uri_query->length : 0,
1093 uri_query ? (char *)uri_query->s : "",
1094 (void *)s, outbuf, s->cache_key->key[0], s->cache_key->key[1],
1095 s->cache_key->key[2], s-> cache_key->key[3]);
1096 coap_delete_string(uri_path);
1097 coap_delete_string(uri_query);
1098 }
1099 if (session->context->observe_deleted_cb)
1100 coap_lock_callback(session->context->observe_deleted_cb(session, s,
1101 session->context->observe_user_data));
1102
1103 if (resource->subscribers) {
1104 LL_DELETE(resource->subscribers, s);
1105 assert(session->ref_subscriptions > 0);
1106 session->ref_subscriptions--;
1107 coap_session_release_lkd(session);
1108 coap_delete_pdu_lkd(s->pdu);
1109 coap_delete_cache_key(s->cache_key);
1111 }
1112
1113 return;
1114}
1115
1116int
1117coap_delete_observer(coap_resource_t *resource, coap_session_t *session,
1118 const coap_bin_const_t *token) {
1120
1121 s = coap_find_observer(resource, session, token);
1122 if (s)
1123 coap_delete_observer_internal(resource, session, s);
1124
1125 return s != NULL;
1126}
1127
1128int
1129coap_delete_observer_request(coap_resource_t *resource, coap_session_t *session,
1130 const coap_bin_const_t *token, coap_pdu_t *request, int large_fetch) {
1132 int ret = 0;
1133
1134 s = coap_find_observer(resource, session, token);
1135 if (!s && large_fetch) {
1136 /*
1137 * It is possible that the client is using the wrong token.
1138 * An example being a large FETCH spanning multiple blocks.
1139 */
1140 coap_cache_key_t *cache_key;
1141
1142 cache_key = coap_cache_derive_key_w_ignore(session, request,
1144 cache_ignore_options,
1145 sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0]));
1146 if (cache_key) {
1147 s = coap_find_observer_cache_key(resource, session, cache_key);
1148 if (s) {
1149 /* Delete entry with setup token */
1150 ret = coap_delete_observer(resource, session, &s->pdu->actual_token);
1151 }
1152 coap_delete_cache_key(cache_key);
1153 }
1154 } else {
1155 coap_delete_observer_internal(resource, session, s);
1156 ret = 1;
1157 }
1158 return ret;
1159}
1160
1161void
1162coap_delete_observers(coap_context_t *context, coap_session_t *session) {
1163 RESOURCES_ITER(context->resources, resource) {
1164 coap_subscription_t *s, *tmp;
1165 LL_FOREACH_SAFE(resource->subscribers, s, tmp) {
1166 if (s->session == session) {
1167 if (context->observe_deleted_cb)
1168 coap_lock_callback(context->observe_deleted_cb(session, s, context->observe_user_data));
1169 assert(resource->subscribers);
1170 LL_DELETE(resource->subscribers, s);
1171 coap_session_release_lkd(session);
1172 coap_delete_pdu_lkd(s->pdu);
1173 coap_delete_cache_key(s->cache_key);
1175 }
1176 }
1177 }
1178}
1179
1180static void
1181coap_notify_observers(coap_context_t *context, coap_resource_t *r,
1182 coap_deleting_resource_t deleting) {
1184 coap_subscription_t *obs, *otmp;
1185 coap_pdu_t *response;
1186 uint8_t buf[4];
1187 coap_string_t *query;
1188 coap_block_b_t block;
1189 coap_tick_t now;
1190
1192
1193 if (r->observable && (r->dirty || r->partiallydirty)) {
1194 if (r->list_being_traversed)
1195 return;
1196 r->list_being_traversed = 1;
1197
1198 coap_resource_reference_lkd(r);
1199
1200 r->partiallydirty = 0;
1201
1202 LL_FOREACH_SAFE(r->subscribers, obs, otmp) {
1203 coap_session_t *obs_session;
1204 coap_pdu_t *obs_pdu;
1206
1207 if ((r->dirty == 0 && obs->dirty == 0) || obs->session->is_rate_limiting) {
1208 /*
1209 * running this resource due to partiallydirty, but this observation's
1210 * notification was already enqueued
1211 */
1212 context->observe_pending = 1;
1213 continue;
1214 }
1215
1216 /*
1217 * obs may get deleted in the callback, or by another running
1218 * thread when executing the callback or when sending a response.
1219 */
1220 obs_session = obs->session;
1221 obs_pdu = obs->pdu;
1222 coap_session_reference_lkd(obs_session);
1223 coap_pdu_reference_lkd(obs_pdu);
1224
1225 if (obs->session->con_active >= COAP_NSTART(obs->session) &&
1226 ((r->flags & COAP_RESOURCE_FLAGS_NOTIFY_CON) ||
1227 (obs->non_cnt >= COAP_OBS_MAX_NON))) {
1228 /* Waiting for the previous unsolicited response to finish */
1229 goto next_one_fail;
1230 }
1231 coap_ticks(&now);
1232 if (obs->session->lg_xmit && obs->session->lg_xmit->last_all_sent == 0 &&
1233 obs->session->lg_xmit->last_obs &&
1234 (obs->session->lg_xmit->last_obs + 2*COAP_TICKS_PER_SECOND) > now) {
1235 /* Waiting for the previous blocked unsolicited response to finish */
1236 goto next_one_fail;
1237 }
1238
1239 obs->dirty = 0;
1240 /* initialize response */
1241 response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0,
1242 coap_session_max_pdu_size_lkd(obs->session));
1243 if (!response) {
1244 coap_log_debug("coap_check_notify: pdu init failed, resource stays "
1245 "partially dirty\n");
1246 goto next_one_fail_no_pending;
1247 }
1248
1249 if (!coap_add_token(response, obs->pdu->actual_token.length,
1250 obs->pdu->actual_token.s)) {
1251 coap_log_debug("coap_check_notify: cannot add token, resource stays "
1252 "partially dirty\n");
1253 coap_delete_pdu_lkd(response);
1254 goto next_one_fail_no_pending;
1255 }
1256
1257 obs->pdu->mid = response->mid = coap_new_message_id_lkd(obs->session);
1258 /* A lot of the reliable code assumes type is CON */
1259 if (COAP_PROTO_NOT_RELIABLE(obs->session->proto) &&
1260 (r->flags & COAP_RESOURCE_FLAGS_NOTIFY_CON) == 0 &&
1262 obs->non_cnt < COAP_OBS_MAX_NON)) {
1263 response->type = COAP_MESSAGE_NON;
1264 } else {
1265 response->type = COAP_MESSAGE_CON;
1266 }
1267 switch (deleting) {
1268 case COAP_NOT_DELETING_RESOURCE:
1269 /* fill with observer-specific data */
1271 coap_encode_var_safe(buf, sizeof(buf),
1272 r->observe),
1273 buf);
1274 if (coap_get_block_b(obs->session, obs->pdu, COAP_OPTION_BLOCK2,
1275 &block)) {
1276 /* Will get updated later (e.g. M bit) if appropriate */
1278 coap_encode_var_safe(buf, sizeof(buf),
1279 ((0 << 4) |
1280 (0 << 3) |
1281 block.aszx)),
1282 buf);
1283 }
1284#if COAP_Q_BLOCK_SUPPORT
1285 else if (coap_get_block_b(obs->session, obs->pdu, COAP_OPTION_Q_BLOCK2,
1286 &block)) {
1287 /* Will get updated later (e.g. M bit) if appropriate */
1289 coap_encode_var_safe(buf, sizeof(buf),
1290 ((0 << 4) |
1291 (0 << 3) |
1292 block.szx)),
1293 buf);
1294 }
1295#endif /* COAP_Q_BLOCK_SUPPORT */
1296
1297 h = r->handler[obs->pdu->code - 1];
1298 assert(h); /* we do not allow subscriptions if no
1299 * GET/FETCH handler is defined */
1300 query = coap_get_query(obs->pdu);
1301 coap_log_debug("Observe PDU presented to app.\n");
1302 coap_show_pdu(COAP_LOG_DEBUG, obs->pdu);
1303 coap_log_debug("call custom handler for resource '%*.*s' (4)\n",
1304 (int)r->uri_path->length, (int)r->uri_path->length,
1305 r->uri_path->s);
1306
1307 /* obs may get deleted during callback (potentially by another thread) */
1308 if (r->flags & COAP_RESOURCE_SAFE_REQUEST_HANDLER) {
1309 coap_lock_callback_release(h(r, obs->session, obs->pdu, query, response),
1310 /* context is being freed off */
1311 coap_delete_string(query);
1312 coap_delete_pdu_lkd(response);
1313 coap_session_release_lkd(obs_session);
1314 coap_pdu_release_lkd(obs_pdu);
1315 r->list_being_traversed = 0;
1316 coap_resource_release_lkd(r);
1317 return);
1318 } else {
1320 h(r, obs->session, obs->pdu, query, response),
1321 /* context is being freed off */
1322 coap_delete_string(query);
1323 coap_delete_pdu_lkd(response);
1324 coap_session_release_lkd(obs_session);
1325 coap_pdu_release_lkd(obs_pdu);
1326 r->list_being_traversed = 0;
1327 coap_resource_release_lkd(r);
1328 return);
1329 }
1330
1331 /* Check validity of response code */
1332 if (!coap_check_code_class(obs_session, response)) {
1333 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
1334 COAP_RESPONSE_CLASS(response->code),
1335 response->code & 0x1f);
1336 coap_delete_string(query);
1337 coap_delete_pdu_lkd(response);
1338 coap_session_release_lkd(obs_session);
1339 coap_pdu_release_lkd(obs_pdu);
1340 r->list_being_traversed = 0;
1341 coap_resource_release_lkd(r);
1342 return;
1343 }
1344
1345 /* Check if lg_xmit generated and update PDU code if so */
1346 coap_check_code_lg_xmit(obs_session, obs_pdu, response, r, query);
1347 coap_delete_string(query);
1348 if (COAP_RESPONSE_CLASS(response->code) != 2) {
1350 }
1351 if (COAP_RESPONSE_CLASS(response->code) > 2) {
1352 coap_delete_observer(r, obs_session, &obs_pdu->actual_token);
1353 obs = NULL;
1354 }
1355 break;
1356 case COAP_DELETING_RESOURCE_ON_EXIT:
1357 /* Don't worry if it does not get there */
1358 response->type = COAP_MESSAGE_NON;
1359 response->code = COAP_RESPONSE_CODE(503);
1361 coap_encode_var_safe(buf, sizeof(buf),
1362 30),
1363 buf);
1364 break;
1365 case COAP_DELETING_RESOURCE:
1366 default:
1367 /* Don't worry if it does not get there */
1368 response->type = COAP_MESSAGE_NON;
1369 response->code = COAP_RESPONSE_CODE(404);
1370 break;
1371 }
1372
1373 if (obs) {
1375 /*
1376 * obs may have been deleted in the callback, or by another running
1377 * thread when executing the callback.
1378 */
1379 LL_FOREACH(r->subscribers, s) {
1380 if (s == obs) {
1381 break;
1382 }
1383 }
1384 if (s == NULL)
1385 obs = NULL;
1386 }
1387 if (obs) {
1388 if (response->type == COAP_MESSAGE_CON ||
1390 obs->non_cnt = 0;
1391 } else {
1392 obs->non_cnt++;
1393 }
1394
1395#if COAP_Q_BLOCK_SUPPORT
1396 if (response->code == COAP_RESPONSE_CODE(205) &&
1397 coap_get_block_b(obs_session, response, COAP_OPTION_Q_BLOCK2,
1398 &block) &&
1399 block.m) {
1400 query = coap_get_query(obs_pdu);
1401 mid = coap_send_q_block2(obs_session, r, query, obs_pdu->code,
1402 block, response, 1);
1403 coap_delete_string(query);
1404 goto finish;
1405 }
1406#endif /* COAP_Q_BLOCK_SUPPORT */
1407 }
1408 mid = coap_send_internal(obs_session, response, NULL);
1409
1410#if COAP_Q_BLOCK_SUPPORT
1411finish:
1412#endif /* COAP_Q_BLOCK_SUPPORT */
1413 if (COAP_INVALID_MID == mid) {
1414 coap_log_debug("* %s: coap_check_notify: sending failed, resource stays "
1415 "partially dirty\n", coap_session_str(obs_session));
1416 if (obs) {
1418 /*
1419 * obs may have been deleted in coap_send_internal() or
1420 * coap_send_q_block2().
1421 */
1422 LL_FOREACH(r->subscribers, s) {
1423 if (s == obs) {
1424 break;
1425 }
1426 }
1427 if (s == NULL)
1428 obs = NULL;
1429 }
1430 if (obs)
1431 obs->dirty = 1;
1432 r->partiallydirty = 1;
1433 }
1434 goto cleanup;
1435
1436next_one_fail:
1437 context->observe_pending = 1;
1438next_one_fail_no_pending:
1439 r->partiallydirty = 1;
1440 if (obs)
1441 obs->dirty = 1;
1442cleanup:
1443 coap_session_release_lkd(obs_session);
1444 coap_pdu_release_lkd(obs_pdu);
1445 }
1446 r->list_being_traversed = 0;
1447 r->dirty = 0;
1448 coap_resource_release_lkd(r);
1449 /* r may be no more if elsewhere coap_free_resource() has been called */
1450 } else {
1451 r->dirty = 0;
1452 }
1453}
1454
1455COAP_API int
1457 int ret;
1458 (void)query;
1459
1460 coap_lock_lock(return 0);
1461 ret = coap_resource_notify_observers_lkd(r, COAP_NOT_DELETING_RESOURCE);
1463 return ret;
1464}
1465
1466COAP_API int
1468 const coap_string_t *query) {
1469 int ret;
1470
1471 (void)query;
1472 coap_lock_lock(return 0);
1473 ret = coap_resource_notify_observers_lkd(r, COAP_NOT_DELETING_RESOURCE);
1475 return ret;
1476}
1477
1478int
1479coap_resource_notify_observers_lkd(coap_resource_t *r,
1480 coap_deleting_resource_t deleting) {
1482 if (!r->observable)
1483 return 0;
1484 if (!r->subscribers)
1485 return 0;
1486 r->dirty = 1;
1487
1488 /* Increment value for next Observe use. Observe value must be < 2^24 */
1489 r->observe = (r->observe + 1) & 0xFFFFFF;
1490
1491 assert(r->context);
1492
1493 if (r->context->track_observe_value_cb) {
1494 /* Track last used observe value */
1495 if ((r->observe % r->context->observe_save_freq) == 0)
1496 coap_lock_callback(r->context->track_observe_value_cb(r->context, r->uri_path,
1497 r->observe,
1498 r->context->observe_user_data));
1499 }
1500
1501 coap_notify_observers(r->context, r, deleting);
1502 return 1;
1503}
1504
1505void
1506coap_resource_set_mode(coap_resource_t *resource, int mode) {
1507 resource->flags = (resource->flags &
1510}
1511
1512void
1513coap_resource_set_userdata(coap_resource_t *resource, void *data) {
1514 resource->user_data = data;
1515}
1516
1517void *
1519 return resource->user_data;
1520}
1521
1522void
1525 context->release_userdata_cb = callback;
1526}
1527
1528void
1530 if (resource->is_unknown || resource->is_proxy_uri) {
1531 /* We cannot observe these */
1532 coap_log_debug("coap_resource_set_get_observable: Not supported for Unknown or Proxy URIs\n");
1533 resource->observable = 0;
1534 } else {
1535 resource->observable = mode ? 1 : 0;
1536 }
1537}
1538
1541 if (resource)
1542 return resource->uri_path;
1543 return NULL;
1544}
1545
1546COAP_API void
1548 coap_lock_lock(return);
1549 coap_check_notify_lkd(context);
1551}
1552
1553void
1554coap_check_notify_lkd(coap_context_t *context) {
1555
1557 if (context->observe_pending) {
1558 context->observe_pending = 0;
1559 RESOURCES_ITER(context->resources, r) {
1560 coap_notify_observers(context, r, COAP_NOT_DELETING_RESOURCE);
1561 }
1562 }
1563}
1564
1565void
1567 uint32_t start_observe_no) {
1568 if (!resource)
1569 return;
1570
1571 resource->observe = start_observe_no & 0xffffff;
1572}
1573
1584static void
1585coap_remove_failed_observers(coap_context_t *context,
1586 coap_resource_t *resource,
1587 coap_session_t *session,
1588 const coap_bin_const_t *token) {
1589 coap_subscription_t *obs, *otmp;
1590
1591 LL_FOREACH_SAFE(resource->subscribers, obs, otmp) {
1592 if (obs->session == session &&
1593 coap_binary_equal(token, &obs->pdu->actual_token)) {
1594 /* count failed notifies and remove when
1595 * COAP_OBS_MAX_FAIL is reached */
1596 obs->fail_cnt++;
1597 if (obs->fail_cnt >= COAP_OBS_MAX_FAIL) {
1598 coap_cancel_all_messages(context, obs->session,
1599 &obs->pdu->actual_token);
1600 coap_delete_observer(resource, session, token);
1601 }
1602 break; /* break loop if observer was found */
1603 }
1604 }
1605}
1606
1607void
1608coap_handle_failed_notify(coap_context_t *context,
1609 coap_session_t *session,
1610 const coap_bin_const_t *token) {
1611
1612 RESOURCES_ITER(context->resources, r) {
1613 coap_remove_failed_observers(context, r, session, token);
1614 }
1615}
1616
1617void
1618coap_resource_reference_lkd(coap_resource_t *resource) {
1619 resource->ref++;
1620}
1621
1623coap_add_dynamic_resource(coap_session_t *session, coap_pdu_t *pdu) {
1624 coap_context_t *context = session->context;
1625 coap_resource_t *resource;
1626
1627 if ((context->dyn_create_handler != NULL) &&
1629 /* Above test must be the same as in coap_op_dyn_resource_load_disk() */
1630 if (context->dynamic_cur < context->dynamic_max || context->dynamic_max == 0) {
1631#if COAP_WITH_OBSERVE_PERSIST
1632 /* If we are maintaining Observe persist */
1633 context->unknown_pdu = pdu;
1634 context->unknown_session = session;
1635#endif /* COAP_WITH_OBSERVE_PERSIST */
1636 coap_lock_callback_ret(resource, context->dyn_create_handler(session, pdu));
1637#if COAP_WITH_OBSERVE_PERSIST
1638 /* If we are maintaining Observe persist */
1639 context->unknown_pdu = NULL;
1640 context->unknown_session = NULL;
1641#endif /* COAP_WITH_OBSERVE_PERSIST */
1642 if (resource) {
1643 context->dynamic_cur++;
1644 resource->is_dynamic = 1;
1645 }
1646 return resource;
1647 }
1648 }
1649 return NULL;
1650}
1651
1652#endif /* COAP_SERVER_SUPPORT */
int coap_is_af_unix(const coap_address_t *a)
Checks if given address a denotes a AF_UNIX address.
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:70
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:2097
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:1545
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:3306
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:1741
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:546
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:851
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:413
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:947
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:916
@ 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