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