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