libcoap 4.3.5-develop-18bb1ff
Loading...
Searching...
No Matches
coap_net.c
Go to the documentation of this file.
1/* coap_net.c -- CoAP context inteface
2 *
3 * Copyright (C) 2010--2025 Olaf Bergmann <bergmann@tzi.org> and others
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
18
19#include <ctype.h>
20#include <stdio.h>
21#ifdef HAVE_LIMITS_H
22#include <limits.h>
23#endif
24
25#ifndef __ZEPHYR__
26#ifdef HAVE_UNISTD_H
27#include <unistd.h>
28#else
29#ifdef HAVE_SYS_UNISTD_H
30#include <sys/unistd.h>
31#endif
32#endif
33#ifdef HAVE_SYS_TYPES_H
34#include <sys/types.h>
35#endif
36#ifdef HAVE_SYS_SOCKET_H
37#include <sys/socket.h>
38#endif
39#ifdef HAVE_SYS_IOCTL_H
40#include <sys/ioctl.h>
41#endif
42#ifdef HAVE_NETINET_IN_H
43#include <netinet/in.h>
44#endif
45#ifdef HAVE_ARPA_INET_H
46#include <arpa/inet.h>
47#endif
48#ifdef HAVE_NET_IF_H
49#include <net/if.h>
50#endif
51#ifdef COAP_EPOLL_SUPPORT
52#include <sys/epoll.h>
53#include <sys/timerfd.h>
54#endif /* COAP_EPOLL_SUPPORT */
55#ifdef HAVE_WS2TCPIP_H
56#include <ws2tcpip.h>
57#endif
58
59#ifdef HAVE_NETDB_H
60#include <netdb.h>
61#endif
62#endif /* !__ZEPHYR__ */
63
64#ifdef WITH_LWIP
65#include <lwip/pbuf.h>
66#include <lwip/udp.h>
67#include <lwip/timeouts.h>
68#include <lwip/tcpip.h>
69#endif
70
71#ifndef INET6_ADDRSTRLEN
72#define INET6_ADDRSTRLEN 40
73#endif
74
75#ifndef min
76#define min(a,b) ((a) < (b) ? (a) : (b))
77#endif
78
83#define FRAC_BITS 6
84
89#define MAX_BITS 8
90
91#if FRAC_BITS > 8
92#error FRAC_BITS must be less or equal 8
93#endif
94
96#define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
97 ((1 << (frac)) * fval.fractional_part + 500)/1000))
98
100#define ACK_RANDOM_FACTOR \
101 Q(FRAC_BITS, session->ack_random_factor)
102
104#define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
105
110
115
116unsigned int
118 unsigned int result = 0;
119 coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
120
121 if (ctx->sendqueue) {
122 /* delta < 0 means that the new time stamp is before the old. */
123 if (delta <= 0) {
124 ctx->sendqueue->t -= delta;
125 } else {
126 /* This case is more complex: The time must be advanced forward,
127 * thus possibly leading to timed out elements at the queue's
128 * start. For every element that has timed out, its relative
129 * time is set to zero and the result counter is increased. */
130
131 coap_queue_t *q = ctx->sendqueue;
132 coap_tick_t t = 0;
133 while (q && (t + q->t < (coap_tick_t)delta)) {
134 t += q->t;
135 q->t = 0;
136 result++;
137 q = q->next;
138 }
139
140 /* finally adjust the first element that has not expired */
141 if (q) {
142 q->t = (coap_tick_t)delta - t;
143 }
144 }
145 }
146
147 /* adjust basetime */
148 ctx->sendqueue_basetime += delta;
149
150 return result;
151}
152
153int
155 coap_queue_t *p, *q;
156 if (!queue || !node)
157 return 0;
158
159 /* set queue head if empty */
160 if (!*queue) {
161 *queue = node;
162 return 1;
163 }
164
165 /* replace queue head if PDU's time is less than head's time */
166 q = *queue;
167 if (node->t < q->t) {
168 node->next = q;
169 *queue = node;
170 q->t -= node->t; /* make q->t relative to node->t */
171 return 1;
172 }
173
174 /* search for right place to insert */
175 do {
176 node->t -= q->t; /* make node-> relative to q->t */
177 p = q;
178 q = q->next;
179 } while (q && q->t <= node->t);
180
181 /* insert new item */
182 if (q) {
183 q->t -= node->t; /* make q->t relative to node->t */
184 }
185 node->next = q;
186 p->next = node;
187 return 1;
188}
189
190COAP_API int
192 int ret;
193#if COAP_THREAD_SAFE
194 coap_context_t *context;
195#endif /* COAP_THREAD_SAFE */
196
197 if (!node)
198 return 0;
199 if (!node->session)
200 return coap_delete_node_lkd(node);
201
202#if COAP_THREAD_SAFE
203 /* Keep copy as node will be going away */
204 context = node->session->context;
205 (void)context;
206#endif /* COAP_THREAD_SAFE */
207 coap_lock_lock(return 0);
208 ret = coap_delete_node_lkd(node);
210 return ret;
211}
212
213int
215 if (!node)
216 return 0;
217
219 if (node->session) {
220 /*
221 * Need to remove out of context->sendqueue as added in by coap_wait_ack()
222 */
223 if (node->session->context->sendqueue) {
224 LL_DELETE(node->session->context->sendqueue, node);
225 }
227 }
228 coap_free_node(node);
229
230 return 1;
231}
232
233void
235 if (!queue)
236 return;
237
238 coap_delete_all(queue->next);
240}
241
244 coap_queue_t *node;
245 node = coap_malloc_node();
246
247 if (!node) {
248 coap_log_warn("coap_new_node: malloc failed\n");
249 return NULL;
250 }
251
252 memset(node, 0, sizeof(*node));
253 return node;
254}
255
258 if (!context || !context->sendqueue)
259 return NULL;
260
261 return context->sendqueue;
262}
263
266 coap_queue_t *next;
267
268 if (!context || !context->sendqueue)
269 return NULL;
270
271 next = context->sendqueue;
272 context->sendqueue = context->sendqueue->next;
273 if (context->sendqueue) {
274 context->sendqueue->t += next->t;
275 }
276 next->next = NULL;
277 return next;
278}
279
280#if COAP_CLIENT_SUPPORT
281const coap_bin_const_t *
283
284 if (session->psk_key) {
285 return session->psk_key;
286 }
287 if (session->cpsk_setup_data.psk_info.key.length)
288 return &session->cpsk_setup_data.psk_info.key;
289
290 /* Not defined in coap_new_client_session_psk2() */
291 return NULL;
292}
293
294const coap_bin_const_t *
296
297 if (session->psk_identity) {
298 return session->psk_identity;
299 }
301 return &session->cpsk_setup_data.psk_info.identity;
302
303 /* Not defined in coap_new_client_session_psk2() */
304 return NULL;
305}
306#endif /* COAP_CLIENT_SUPPORT */
307
308#if COAP_SERVER_SUPPORT
309const coap_bin_const_t *
311
312 if (session->psk_key)
313 return session->psk_key;
314
316 return &session->context->spsk_setup_data.psk_info.key;
317
318 /* Not defined in coap_context_set_psk2() */
319 return NULL;
320}
321
322const coap_bin_const_t *
324
325 if (session->psk_hint)
326 return session->psk_hint;
327
329 return &session->context->spsk_setup_data.psk_info.hint;
330
331 /* Not defined in coap_context_set_psk2() */
332 return NULL;
333}
334
335COAP_API int
337 const char *hint,
338 const uint8_t *key,
339 size_t key_len) {
340 int ret;
341
342 coap_lock_lock(return 0);
343 ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
345 return ret;
346}
347
348int
350 const char *hint,
351 const uint8_t *key,
352 size_t key_len) {
353 coap_dtls_spsk_t setup_data;
354
356 memset(&setup_data, 0, sizeof(setup_data));
357 if (hint) {
358 setup_data.psk_info.hint.s = (const uint8_t *)hint;
359 setup_data.psk_info.hint.length = strlen(hint);
360 }
361
362 if (key && key_len > 0) {
363 setup_data.psk_info.key.s = key;
364 setup_data.psk_info.key.length = key_len;
365 }
366
367 return coap_context_set_psk2_lkd(ctx, &setup_data);
368}
369
370COAP_API int
372 int ret;
373
374 coap_lock_lock(return 0);
375 ret = coap_context_set_psk2_lkd(ctx, setup_data);
377 return ret;
378}
379
380int
382 if (!setup_data)
383 return 0;
384
386 ctx->spsk_setup_data = *setup_data;
387
389 return coap_dtls_context_set_spsk(ctx, setup_data);
390 }
391 return 0;
392}
393
394COAP_API int
396 const coap_dtls_pki_t *setup_data) {
397 int ret;
398
399 coap_lock_lock(return 0);
400 ret = coap_context_set_pki_lkd(ctx, setup_data);
402 return ret;
403}
404
405int
407 const coap_dtls_pki_t *setup_data) {
409 if (!setup_data)
410 return 0;
411 if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
412 coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
413 return 0;
414 }
416 return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
417 }
418 return 0;
419}
420#endif /* ! COAP_SERVER_SUPPORT */
421
422COAP_API int
424 const char *ca_file,
425 const char *ca_dir) {
426 int ret;
427
428 coap_lock_lock(return 0);
429 ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
431 return ret;
432}
433
434int
436 const char *ca_file,
437 const char *ca_dir) {
439 return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
440 }
441 return 0;
442}
443
444COAP_API int
446 int ret;
447
448 coap_lock_lock(return 0);
451 return ret;
452}
453
454int
461
462
463void
464coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
465 context->ping_timeout = seconds;
466}
467
468int
470#if COAP_CLIENT_SUPPORT
471 return coap_dtls_set_cid_tuple_change(context, every);
472#else /* ! COAP_CLIENT_SUPPORT */
473 (void)context;
474 (void)every;
475 return 0;
476#endif /* ! COAP_CLIENT_SUPPORT */
477}
478
479void
481 size_t max_token_size) {
482 assert(max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
483 max_token_size <= COAP_TOKEN_EXT_MAX);
484 context->max_token_size = (uint32_t)max_token_size;
485}
486
487void
489 unsigned int max_idle_sessions) {
490 context->max_idle_sessions = max_idle_sessions;
491}
492
493unsigned int
495 return context->max_idle_sessions;
496}
497
498void
500 unsigned int max_handshake_sessions) {
501 context->max_handshake_sessions = max_handshake_sessions;
502}
503
504unsigned int
508
509static unsigned int s_csm_timeout = 30;
510
511void
513 unsigned int csm_timeout) {
514 s_csm_timeout = csm_timeout;
515 coap_context_set_csm_timeout_ms(context, csm_timeout * 1000);
516}
517
518unsigned int
520 (void)context;
521 return s_csm_timeout;
522}
523
524void
526 unsigned int csm_timeout_ms) {
527 if (csm_timeout_ms < 10)
528 csm_timeout_ms = 10;
529 if (csm_timeout_ms > 10000)
530 csm_timeout_ms = 10000;
531 context->csm_timeout_ms = csm_timeout_ms;
532}
533
534unsigned int
536 return context->csm_timeout_ms;
537}
538
539void
541 uint32_t csm_max_message_size) {
542 assert(csm_max_message_size >= 64);
543 if (csm_max_message_size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
544 csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
545 coap_log_debug("Restricting CSM Max-Message-Size size to %" PRIu32 "\n",
546 csm_max_message_size);
547 }
548
549 context->csm_max_message_size = csm_max_message_size;
550}
551
552uint32_t
556
557void
559 unsigned int session_timeout) {
560 context->session_timeout = session_timeout;
561}
562
563void
565 unsigned int reconnect_time) {
566 coap_context_set_session_reconnect_time2(context, reconnect_time, 0);
567}
568
569void
571 unsigned int reconnect_time,
572 uint8_t retry_count) {
573#if COAP_CLIENT_SUPPORT
574 context->reconnect_time = reconnect_time;
575 context->retry_count = retry_count;
576#else /* ! COAP_CLIENT_SUPPORT */
577 (void)context;
578 (void)reconnect_time;
579 (void)retry_count;
580#endif /* ! COAP_CLIENT_SUPPORT */
581}
582
583unsigned int
585 return context->session_timeout;
586}
587
588void
590#if COAP_SERVER_SUPPORT
591 context->shutdown_no_send_observe = 1;
592#else /* ! COAP_SERVER_SUPPORT */
593 (void)context;
594#endif /* ! COAP_SERVER_SUPPORT */
595}
596
597int
599#if COAP_EPOLL_SUPPORT
600 return context->epfd;
601#else /* ! COAP_EPOLL_SUPPORT */
602 (void)context;
603 return -1;
604#endif /* ! COAP_EPOLL_SUPPORT */
605}
606
607int
609#if COAP_EPOLL_SUPPORT
610 return 1;
611#else /* ! COAP_EPOLL_SUPPORT */
612 return 0;
613#endif /* ! COAP_EPOLL_SUPPORT */
614}
615
616int
618#if COAP_THREAD_SAFE
619 return 1;
620#else /* ! COAP_THREAD_SAFE */
621 return 0;
622#endif /* ! COAP_THREAD_SAFE */
623}
624
625int
627#if COAP_IPV4_SUPPORT
628 return 1;
629#else /* ! COAP_IPV4_SUPPORT */
630 return 0;
631#endif /* ! COAP_IPV4_SUPPORT */
632}
633
634int
636#if COAP_IPV6_SUPPORT
637 return 1;
638#else /* ! COAP_IPV6_SUPPORT */
639 return 0;
640#endif /* ! COAP_IPV6_SUPPORT */
641}
642
643int
645#if COAP_CLIENT_SUPPORT
646 return 1;
647#else /* ! COAP_CLIENT_SUPPORT */
648 return 0;
649#endif /* ! COAP_CLIENT_SUPPORT */
650}
651
652int
654#if COAP_SERVER_SUPPORT
655 return 1;
656#else /* ! COAP_SERVER_SUPPORT */
657 return 0;
658#endif /* ! COAP_SERVER_SUPPORT */
659}
660
661int
663#if COAP_AF_UNIX_SUPPORT
664 return 1;
665#else /* ! COAP_AF_UNIX_SUPPORT */
666 return 0;
667#endif /* ! COAP_AF_UNIX_SUPPORT */
668}
669
670COAP_API void
671coap_context_set_app_data(coap_context_t *context, void *app_data) {
672 assert(context);
673 coap_lock_lock(return);
674 coap_context_set_app_data2_lkd(context, app_data, NULL);
676}
677
678void *
680 assert(context);
681 return context->app_data;
682}
683
684COAP_API void *
687 void *old_data;
688
689 coap_lock_lock(return NULL);
690 old_data = coap_context_set_app_data2_lkd(context, app_data, callback);
692 return old_data;
693}
694
695void *
698 void *old_data = context->app_data;
699
700 context->app_data = app_data;
701 context->app_cb = app_data ? callback : NULL;
702 return old_data;
703}
704
706coap_new_context(const coap_address_t *listen_addr) {
708
709#if ! COAP_SERVER_SUPPORT
710 (void)listen_addr;
711#endif /* COAP_SERVER_SUPPORT */
712
713 if (!coap_started) {
714 coap_startup();
715 coap_log_warn("coap_startup() should be called before any other "
716 "coap_*() functions are called\n");
717 }
718
720 if (!c) {
721 coap_log_emerg("coap_init: malloc: failed\n");
722 return NULL;
723 }
724 memset(c, 0, sizeof(coap_context_t));
725
727#ifdef COAP_EPOLL_SUPPORT
728 c->epfd = epoll_create1(0);
729 if (c->epfd == -1) {
730 coap_log_err("coap_new_context: Unable to epoll_create: %s (%d)\n",
732 errno);
733 goto onerror;
734 }
735 if (c->epfd != -1) {
736 c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
737 if (c->eptimerfd == -1) {
738 coap_log_err("coap_new_context: Unable to timerfd_create: %s (%d)\n",
740 errno);
741 goto onerror;
742 } else {
743 int ret;
744 struct epoll_event event;
745
746 /* Needed if running 32bit as ptr is only 32bit */
747 memset(&event, 0, sizeof(event));
748 event.events = EPOLLIN;
749 /* We special case this event by setting to NULL */
750 event.data.ptr = NULL;
751
752 ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
753 if (ret == -1) {
754 coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
755 "coap_new_context",
756 coap_socket_strerror(), errno);
757 goto onerror;
758 }
759 }
760 }
761#endif /* COAP_EPOLL_SUPPORT */
762
765 if (!c->dtls_context) {
766 coap_log_emerg("coap_init: no DTLS context available\n");
768 return NULL;
769 }
770 }
771
772 /* set default CSM values */
773 c->csm_timeout_ms = 1000;
774 c->csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
775
776#if COAP_SERVER_SUPPORT
777 if (listen_addr) {
778 coap_endpoint_t *endpoint = coap_new_endpoint_lkd(c, listen_addr, COAP_PROTO_UDP);
779 if (endpoint == NULL) {
780 goto onerror;
781 }
782 }
783#endif /* COAP_SERVER_SUPPORT */
784
785 c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
786
788 return c;
789
790#if defined(COAP_EPOLL_SUPPORT) || COAP_SERVER_SUPPORT
791onerror:
793 return NULL;
794#endif /* COAP_EPOLL_SUPPORT || COAP_SERVER_SUPPORT */
795}
796
797COAP_API void
798coap_set_app_data(coap_context_t *context, void *app_data) {
799 assert(context);
800 coap_lock_lock(return);
801 coap_context_set_app_data2_lkd(context, app_data, NULL);
803}
804
805void *
807 assert(ctx);
808 return ctx->app_data;
809}
810
811COAP_API void
813 if (!context)
814 return;
815 coap_lock_lock(return);
816 coap_free_context_lkd(context);
818}
819
820void
822 if (!context)
823 return;
824
826#if COAP_SERVER_SUPPORT
827 /* Removing a resource may cause a NON unsolicited observe to be sent */
828 if (context->shutdown_no_send_observe)
829 context->observe_no_clear = 1;
831#endif /* COAP_SERVER_SUPPORT */
832#if COAP_CLIENT_SUPPORT
833 /* Stop any attempts at reconnection */
834 context->reconnect_time = 0;
835#endif /* COAP_CLIENT_SUPPORT */
836
837 coap_delete_all(context->sendqueue);
838 context->sendqueue = NULL;
839
840#ifdef WITH_LWIP
841 if (context->timer_configured) {
842 LOCK_TCPIP_CORE();
843 sys_untimeout(coap_io_process_timeout, (void *)context);
844 UNLOCK_TCPIP_CORE();
845 context->timer_configured = 0;
846 }
847#endif /* WITH_LWIP */
848
849#if COAP_ASYNC_SUPPORT
850 coap_delete_all_async(context);
851#endif /* COAP_ASYNC_SUPPORT */
852
853#if COAP_OSCORE_SUPPORT
854 coap_delete_all_oscore(context);
855#endif /* COAP_OSCORE_SUPPORT */
856
857#if COAP_SERVER_SUPPORT
858 coap_cache_entry_t *cp, *ctmp;
859 coap_endpoint_t *ep, *tmp;
860
861 HASH_ITER(hh, context->cache, cp, ctmp) {
862 coap_delete_cache_entry(context, cp);
863 }
864 if (context->cache_ignore_count) {
866 }
867
868 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
870 }
871#endif /* COAP_SERVER_SUPPORT */
872
873#if COAP_CLIENT_SUPPORT
874 coap_session_t *sp, *rtmp;
875
876 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
878 }
879#endif /* COAP_CLIENT_SUPPORT */
880
881 if (context->dtls_context)
883#ifdef COAP_EPOLL_SUPPORT
884 if (context->eptimerfd != -1) {
885 int ret;
886 struct epoll_event event;
887
888 /* Kernels prior to 2.6.9 expect non NULL event parameter */
889 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
890 if (ret == -1) {
891 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
892 "coap_free_context",
893 coap_socket_strerror(), errno);
894 }
895 close(context->eptimerfd);
896 context->eptimerfd = -1;
897 }
898 if (context->epfd != -1) {
899 close(context->epfd);
900 context->epfd = -1;
901 }
902#endif /* COAP_EPOLL_SUPPORT */
903#if COAP_SERVER_SUPPORT
904#if COAP_WITH_OBSERVE_PERSIST
905 coap_persist_cleanup(context);
906#endif /* COAP_WITH_OBSERVE_PERSIST */
907#endif /* COAP_SERVER_SUPPORT */
908#if COAP_PROXY_SUPPORT
909 coap_proxy_cleanup(context);
910#endif /* COAP_PROXY_SUPPORT */
911
912 if (context->app_cb) {
913 context->app_cb(context->app_data);
914 }
917}
918
919int
921 coap_pdu_t *pdu,
922 coap_opt_filter_t *unknown) {
923 coap_context_t *ctx = session->context;
924 coap_opt_iterator_t opt_iter;
925 int ok = 1;
926 coap_option_num_t last_number = -1;
927
929
930 while (coap_option_next(&opt_iter)) {
931 /* Check for explicitely reserved option RFC 5272 12.2 Table 7 */
932 /* Need to check reserved options */
933 switch (opt_iter.number) {
934 case 0:
935 case 128:
936 case 132:
937 case 136:
938 case 140:
939 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
940 coap_log_debug("unknown reserved option %d\n", opt_iter.number);
941 ok = 0;
942
943 /* When opt_iter.number cannot be set in unknown, all of the appropriate
944 * slots have been used up and no more options can be tracked.
945 * Safe to break out of this loop as ok is already set. */
946 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
947 goto overflow;
948 }
949 }
950 break;
951 default:
952 break;
953 }
954 if (opt_iter.number & 0x01) {
955 /* first check the known built-in critical options */
956 switch (opt_iter.number) {
957#if COAP_Q_BLOCK_SUPPORT
960 if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
961 coap_log_debug("disabled support for critical option %u\n",
962 opt_iter.number);
963 ok = 0;
964 /* When opt_iter.number cannot be set in unknown, all of the appropriate
965 * slots have been used up and no more options can be tracked.
966 * Safe to break out of this loop as ok is already set. */
967 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
968 goto overflow;
969 }
970 }
971 break;
972#endif /* COAP_Q_BLOCK_SUPPORT */
984 break;
986 /* Valid critical if doing OSCORE */
987#if COAP_OSCORE_SUPPORT
988 if (ctx->p_osc_ctx)
989 break;
990#endif /* COAP_OSCORE_SUPPORT */
991 /* Fall Through */
992 default:
993 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
994#if COAP_SERVER_SUPPORT
995 if ((opt_iter.number & 0x02) == 0) {
996 coap_opt_iterator_t t_iter;
997
998 /* Safe to forward - check if proxy pdu */
999 if (session->proxy_session)
1000 break;
1001 if (COAP_PDU_IS_REQUEST(pdu) && ctx->proxy_uri_resource &&
1002 (coap_check_option(pdu, COAP_OPTION_PROXY_URI, &t_iter) ||
1004 pdu->crit_opt = 1;
1005 break;
1006 }
1007 if (COAP_PDU_IS_REQUEST(pdu) && ctx->unknown_resource &&
1009 pdu->crit_opt = 1;
1010 break;
1011 }
1012 }
1013#endif /* COAP_SERVER_SUPPORT */
1014 coap_log_debug("unknown critical option %d\n", opt_iter.number);
1015 ok = 0;
1016
1017 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1018 * slots have been used up and no more options can be tracked.
1019 * Safe to break out of this loop as ok is already set. */
1020 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1021 goto overflow;
1022 }
1023 }
1024 }
1025 }
1026 if (last_number == opt_iter.number) {
1027 /* Check for duplicated option RFC 5272 5.4.5 */
1028 if (!coap_option_check_repeatable(opt_iter.number)) {
1029 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1030 ok = 0;
1031 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1032 goto overflow;
1033 }
1034 }
1035 }
1036 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
1037 COAP_PDU_IS_REQUEST(pdu)) {
1038 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
1039 coap_block_b_t block;
1040
1041 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
1042 if (block.m) {
1043 size_t used_size = pdu->used_size;
1044 unsigned char buf[4];
1045
1046 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
1047 block.m = 0;
1048 coap_update_option(pdu, opt_iter.number,
1049 coap_encode_var_safe(buf, sizeof(buf),
1050 ((block.num << 4) |
1051 (block.m << 3) |
1052 block.aszx)),
1053 buf);
1054 if (used_size != pdu->used_size) {
1055 /* Unfortunately need to restart the scan */
1056 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1057 last_number = -1;
1058 continue;
1059 }
1060 }
1061 }
1062 }
1063 last_number = opt_iter.number;
1064 }
1065overflow:
1066 return ok;
1067}
1068
1070coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
1071 coap_mid_t mid;
1072
1074 mid = coap_send_rst_lkd(session, request);
1076 return mid;
1077}
1078
1081 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
1082}
1083
1085coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
1086 coap_mid_t mid;
1087
1089 mid = coap_send_ack_lkd(session, request);
1091 return mid;
1092}
1093
1096 coap_pdu_t *response;
1098
1100 if (request && request->type == COAP_MESSAGE_CON &&
1101 COAP_PROTO_NOT_RELIABLE(session->proto)) {
1102 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
1103 if (response)
1104 result = coap_send_internal(session, response, NULL);
1105 }
1106 return result;
1107}
1108
1109ssize_t
1111 ssize_t bytes_written = -1;
1112 assert(pdu->hdr_size > 0);
1113
1114 /* Caller handles partial writes */
1115 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1116 pdu->token - pdu->hdr_size,
1117 pdu->used_size + pdu->hdr_size);
1119 return bytes_written;
1120}
1121
1122static ssize_t
1124 ssize_t bytes_written;
1125
1126 if (session->state == COAP_SESSION_STATE_NONE) {
1127#if ! COAP_CLIENT_SUPPORT
1128 return -1;
1129#else /* COAP_CLIENT_SUPPORT */
1130 if (session->type != COAP_SESSION_TYPE_CLIENT)
1131 return -1;
1132#endif /* COAP_CLIENT_SUPPORT */
1133 }
1134
1135 if (pdu->type == COAP_MESSAGE_CON &&
1136 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1137 coap_is_mcast(&session->addr_info.remote)) {
1138 /* Violates RFC72522 8.1 */
1139 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1140 return -1;
1141 }
1142
1143 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1144 (pdu->type == COAP_MESSAGE_CON &&
1145 session->con_active >= COAP_NSTART(session))) {
1146 return coap_session_delay_pdu(session, pdu, node);
1147 }
1148
1149 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1150 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1151 return coap_session_delay_pdu(session, pdu, node);
1152
1153 bytes_written = coap_session_send_pdu(session, pdu);
1154 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1156 session->con_active++;
1157
1158 return bytes_written;
1159}
1160
1163 const coap_pdu_t *request,
1164 coap_pdu_code_t code,
1165 coap_opt_filter_t *opts) {
1166 coap_mid_t mid;
1167
1169 mid = coap_send_error_lkd(session, request, code, opts);
1171 return mid;
1172}
1173
1176 const coap_pdu_t *request,
1177 coap_pdu_code_t code,
1178 coap_opt_filter_t *opts) {
1179 coap_pdu_t *response;
1181
1182 assert(request);
1183 assert(session);
1184
1185 response = coap_new_error_response(request, code, opts);
1186 if (response)
1187 result = coap_send_internal(session, response, NULL);
1188
1189 return result;
1190}
1191
1194 coap_pdu_type_t type) {
1195 coap_mid_t mid;
1196
1198 mid = coap_send_message_type_lkd(session, request, type);
1200 return mid;
1201}
1202
1205 coap_pdu_type_t type) {
1206 coap_pdu_t *response;
1208
1210 if (request && COAP_PROTO_NOT_RELIABLE(session->proto)) {
1211 response = coap_pdu_init(type, 0, request->mid, 0);
1212 if (response)
1213 result = coap_send_internal(session, response, NULL);
1214 }
1215 return result;
1216}
1217
1231unsigned int
1232coap_calc_timeout(coap_session_t *session, unsigned char r) {
1233 unsigned int result;
1234
1235 /* The integer 1.0 as a Qx.FRAC_BITS */
1236#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1237
1238 /* rounds val up and right shifts by frac positions */
1239#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1240
1241 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1242 * make the result a rounded Qx.FRAC_BITS */
1243 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1244
1245 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1246 * make the result a rounded Qx.FRAC_BITS */
1247 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1248
1249 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1250 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1251 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1252
1253#undef FP1
1254#undef SHR_FP
1255}
1256
1259 coap_queue_t *node) {
1260 coap_tick_t now;
1261
1262 node->session = coap_session_reference_lkd(session);
1263
1264 /* Set timer for pdu retransmission. If this is the first element in
1265 * the retransmission queue, the base time is set to the current
1266 * time and the retransmission time is node->timeout. If there is
1267 * already an entry in the sendqueue, we must check if this node is
1268 * to be retransmitted earlier. Therefore, node->timeout is first
1269 * normalized to the base time and then inserted into the queue with
1270 * an adjusted relative time.
1271 */
1272 coap_ticks(&now);
1273 if (context->sendqueue == NULL) {
1274 node->t = node->timeout << node->retransmit_cnt;
1275 context->sendqueue_basetime = now;
1276 } else {
1277 /* make node->t relative to context->sendqueue_basetime */
1278 node->t = (now - context->sendqueue_basetime) +
1279 (node->timeout << node->retransmit_cnt);
1280 }
1281 coap_address_copy(&node->remote, &session->addr_info.remote);
1282
1283 coap_insert_node(&context->sendqueue, node);
1284
1285 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1286 coap_session_str(node->session), node->id,
1287 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1289
1290 coap_update_io_timer(context, node->t);
1291
1292 return node->id;
1293}
1294
1295#if COAP_CLIENT_SUPPORT
1296/*
1297 * Sent out a test PDU for Extended Token
1298 */
1299static coap_mid_t
1300coap_send_test_extended_token(coap_session_t *session) {
1301 coap_pdu_t *pdu;
1303 size_t i;
1304 coap_binary_t *token;
1305 coap_lg_crcv_t *lg_crcv;
1306
1307 coap_log_debug("Testing for Extended Token support\n");
1308 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1310 coap_new_message_id_lkd(session),
1312 if (!pdu)
1313 return COAP_INVALID_MID;
1314
1315 token = coap_new_binary(session->max_token_size);
1316 if (token == NULL) {
1318 return COAP_INVALID_MID;
1319 }
1320 for (i = 0; i < session->max_token_size; i++) {
1321 token->s[i] = (uint8_t)(i + 1);
1322 }
1323 coap_add_token(pdu, session->max_token_size, token->s);
1324 coap_delete_binary(token);
1325
1328 pdu->actual_token.length);
1329
1331
1332 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1333
1334 /* Need to track incase OSCORE / Echo etc. comes back after non-piggy-backed ACK */
1335 lg_crcv = coap_block_new_lg_crcv(session, pdu, NULL);
1336 if (lg_crcv) {
1337 LL_PREPEND(session->lg_crcv, lg_crcv);
1338 }
1339 mid = coap_send_internal(session, pdu, NULL);
1340 if (mid == COAP_INVALID_MID)
1341 return COAP_INVALID_MID;
1342 session->remote_test_mid = mid;
1343 return mid;
1344}
1345#endif /* COAP_CLIENT_SUPPORT */
1346
1347int
1349#if COAP_CLIENT_SUPPORT
1350 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1351 int timeout_ms = 5000;
1352 coap_session_state_t current_state = session->state;
1353
1354 if (session->delay_recursive) {
1355 return 0;
1356 } else {
1357 session->delay_recursive = 1;
1358 }
1359 /*
1360 * Need to wait for first request to get out and response back before
1361 * continuing.. Response handler has to clear doing_first if not an error.
1362 */
1364 while (session->doing_first != 0) {
1365 int result = coap_io_process_lkd(session->context, 1000);
1366
1367 if (result < 0) {
1368 session->doing_first = 0;
1369 session->delay_recursive = 0;
1370 coap_session_release_lkd(session);
1371 return 0;
1372 }
1373
1374 /* coap_io_process_lkd() may have updated session state */
1375 if (session->state == COAP_SESSION_STATE_CSM &&
1376 current_state != COAP_SESSION_STATE_CSM) {
1377 /* Update timeout and restart the clock for CSM timeout */
1378 current_state = COAP_SESSION_STATE_CSM;
1379 timeout_ms = session->context->csm_timeout_ms;
1380 result = 0;
1381 }
1382
1383 if (result < timeout_ms) {
1384 timeout_ms -= result;
1385 } else {
1386 if (session->doing_first == 1) {
1387 /* Timeout failure of some sort with first request */
1388 session->doing_first = 0;
1389 if (session->state == COAP_SESSION_STATE_CSM) {
1390 coap_log_debug("** %s: timeout waiting for CSM response\n",
1391 coap_session_str(session));
1392 session->csm_not_seen = 1;
1393 coap_session_connected(session);
1394 } else {
1395 coap_log_debug("** %s: timeout waiting for first response\n",
1396 coap_session_str(session));
1397 }
1398 }
1399 }
1400 }
1401 session->delay_recursive = 0;
1402 coap_session_release_lkd(session);
1403 }
1404#else /* ! COAP_CLIENT_SUPPORT */
1405 (void)session;
1406#endif /* ! COAP_CLIENT_SUPPORT */
1407 return 1;
1408}
1409
1410/*
1411 * return 0 Invalid
1412 * 1 Valid
1413 */
1414int
1416
1417 /* Check validity of sending code */
1418 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1419 case 0: /* Empty or request */
1420 case 2: /* Success */
1421 case 3: /* Reserved for future use */
1422 case 4: /* Client error */
1423 case 5: /* Server error */
1424 break;
1425 case 7: /* Reliable signalling */
1426 if (COAP_PROTO_RELIABLE(session->proto))
1427 break;
1428 /* Not valid if UDP */
1429 /* Fall through */
1430 case 1: /* Invalid */
1431 case 6: /* Invalid */
1432 default:
1433 return 0;
1434 }
1435 return 1;
1436}
1437
1438#if COAP_CLIENT_SUPPORT
1439/*
1440 * If type is CON and protocol is not reliable, there is no need to set up
1441 * lg_crcv if it can be built up based on sent PDU if there is a
1442 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1443 * (Q-)Block1.
1444 */
1445static int
1446coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1447 coap_opt_iterator_t opt_iter;
1448
1449 if (!COAP_PDU_IS_REQUEST(pdu))
1450 return 0;
1451
1452 if (
1453#if COAP_OSCORE_SUPPORT
1454 session->oscore_encryption ||
1455#endif /* COAP_OSCORE_SUPPORT */
1456 pdu->type == COAP_MESSAGE_NON ||
1457 COAP_PROTO_RELIABLE(session->proto) ||
1458 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1459#if COAP_Q_BLOCK_SUPPORT
1460 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1461#endif /* COAP_Q_BLOCK_SUPPORT */
1462 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1463 return 1;
1464 }
1465 return 0;
1466}
1467#endif /* COAP_CLIENT_SUPPORT */
1468
1471 coap_mid_t mid;
1472
1474 mid = coap_send_lkd(session, pdu);
1476 return mid;
1477}
1478
1482#if COAP_CLIENT_SUPPORT
1483 coap_lg_crcv_t *lg_crcv = NULL;
1484 coap_opt_iterator_t opt_iter;
1485 coap_block_b_t block;
1486 int observe_action = -1;
1487 int have_block1 = 0;
1488 coap_opt_t *opt;
1489#endif /* COAP_CLIENT_SUPPORT */
1490
1491 assert(pdu);
1492
1494
1495 /* Check validity of sending code */
1496 if (!coap_check_code_class(session, pdu)) {
1497 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1499 pdu->code & 0x1f);
1500 goto error;
1501 }
1502 pdu->session = session;
1503#if COAP_CLIENT_SUPPORT
1504 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1505 !coap_netif_available(session) && !session->session_failed) {
1506 coap_log_debug("coap_send: Socket closed\n");
1507 goto error;
1508 }
1509 /*
1510 * If this is not the first client request and are waiting for a response
1511 * to the first client request, then drop sending out this next request
1512 * until all is properly established.
1513 */
1514 if (!coap_client_delay_first(session)) {
1515 goto error;
1516 }
1517
1518 /* Indicate support for Extended Tokens if appropriate */
1519 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1521 session->type == COAP_SESSION_TYPE_CLIENT &&
1522 COAP_PDU_IS_REQUEST(pdu)) {
1523 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1524 /*
1525 * When the pass / fail response for Extended Token is received, this PDU
1526 * will get transmitted.
1527 */
1528 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1529 goto error;
1530 }
1531 }
1532 /*
1533 * For reliable protocols, this will get cleared after CSM exchanged
1534 * in coap_session_connected()
1535 */
1536 session->doing_first = 1;
1537 if (!coap_client_delay_first(session)) {
1538 goto error;
1539 }
1540 }
1541
1542 /*
1543 * Check validity of token length
1544 */
1545 if (COAP_PDU_IS_REQUEST(pdu) &&
1546 pdu->actual_token.length > session->max_token_size) {
1547 coap_log_warn("coap_send: PDU dropped as token too long (%zu > %" PRIu32 ")\n",
1548 pdu->actual_token.length, session->max_token_size);
1549 goto error;
1550 }
1551
1552 /* A lot of the reliable code assumes type is CON */
1553 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1554 pdu->type = COAP_MESSAGE_CON;
1555
1556#if COAP_OSCORE_SUPPORT
1557 if (session->oscore_encryption) {
1558 if (session->recipient_ctx->initial_state == 1) {
1559 /*
1560 * Not sure if remote supports OSCORE, or is going to send us a
1561 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1562 * is OK. Continue sending current pdu to test things.
1563 */
1564 session->doing_first = 1;
1565 }
1566 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1568 goto error;
1569 }
1570 }
1571#endif /* COAP_OSCORE_SUPPORT */
1572
1573 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1574 return coap_send_internal(session, pdu, NULL);
1575 }
1576
1577 if (COAP_PDU_IS_REQUEST(pdu)) {
1578 uint8_t buf[4];
1579
1580 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1581
1582 if (opt) {
1583 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1584 coap_opt_length(opt));
1585 }
1586
1587 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1588 (block.m == 1 || block.bert == 1)) {
1589 have_block1 = 1;
1590 }
1591#if COAP_Q_BLOCK_SUPPORT
1592 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1593 (block.m == 1 || block.bert == 1)) {
1594 if (have_block1) {
1595 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1597 }
1598 have_block1 = 1;
1599 }
1600#endif /* COAP_Q_BLOCK_SUPPORT */
1601 if (observe_action != COAP_OBSERVE_CANCEL) {
1602 /* Warn about re-use of tokens */
1603 if (session->last_token &&
1604 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1606 char scratch[24];
1607 size_t size;
1608 size_t i;
1609
1610 scratch[0] = '\000';
1611 for (i = 0; i < pdu->actual_token.length; i++) {
1612 size = strlen(scratch);
1613 snprintf(&scratch[size], sizeof(scratch)-size,
1614 "%02x", pdu->actual_token.s[i]);
1615 }
1616 coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1617 scratch);
1618 }
1619 }
1622 pdu->actual_token.length);
1623 } else {
1624 /* observe_action == COAP_OBSERVE_CANCEL */
1625 coap_binary_t tmp;
1626 int ret;
1627
1628 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1629 /* Unfortunately need to change the ptr type to be r/w */
1630 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1631 tmp.length = pdu->actual_token.length;
1632 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1633 if (ret == 1) {
1634 /* Observe Cancel successfully sent */
1636 return ret;
1637 }
1638 /* Some mismatch somewhere - continue to send original packet */
1639 }
1640 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1641 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1645 coap_encode_var_safe(buf, sizeof(buf),
1646 ++session->tx_rtag),
1647 buf);
1648 } else {
1649 memset(&block, 0, sizeof(block));
1650 }
1651
1652#if COAP_Q_BLOCK_SUPPORT
1653 /* Indicate support for Q-Block if appropriate */
1654 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1655 session->type == COAP_SESSION_TYPE_CLIENT &&
1656 COAP_PDU_IS_REQUEST(pdu)) {
1657 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1658 goto error;
1659 }
1660 session->doing_first = 1;
1661 if (!coap_client_delay_first(session)) {
1662 /* Q-Block test Session has failed for some reason */
1663 set_block_mode_drop_q(session->block_mode);
1664 goto error;
1665 }
1666 }
1667#endif /* COAP_Q_BLOCK_SUPPORT */
1668
1669#if COAP_Q_BLOCK_SUPPORT
1670 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1671#endif /* COAP_Q_BLOCK_SUPPORT */
1672 {
1673 /* Need to check if we need to reset Q-Block to Block */
1674 uint8_t buf[4];
1675
1676 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1679 coap_encode_var_safe(buf, sizeof(buf),
1680 (block.num << 4) | (0 << 3) | block.szx),
1681 buf);
1682 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1683 /* Need to update associated lg_xmit */
1684 coap_lg_xmit_t *lg_xmit;
1685
1686 LL_FOREACH(session->lg_xmit, lg_xmit) {
1687 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1688 lg_xmit->b.b1.app_token &&
1689 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1690 /* Update the skeletal PDU with the block1 option */
1693 coap_encode_var_safe(buf, sizeof(buf),
1694 (block.num << 4) | (0 << 3) | block.szx),
1695 buf);
1696 break;
1697 }
1698 }
1699 }
1700 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1703 coap_encode_var_safe(buf, sizeof(buf),
1704 (block.num << 4) | (block.m << 3) | block.szx),
1705 buf);
1706 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1707 /* Need to update associated lg_xmit */
1708 coap_lg_xmit_t *lg_xmit;
1709
1710 LL_FOREACH(session->lg_xmit, lg_xmit) {
1711 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1712 lg_xmit->b.b1.app_token &&
1713 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1714 /* Update the skeletal PDU with the block1 option */
1717 coap_encode_var_safe(buf, sizeof(buf),
1718 (block.num << 4) |
1719 (block.m << 3) |
1720 block.szx),
1721 buf);
1722 /* Update as this is a Request */
1723 lg_xmit->option = COAP_OPTION_BLOCK1;
1724 break;
1725 }
1726 }
1727 }
1728 }
1729
1730#if COAP_Q_BLOCK_SUPPORT
1731 if (COAP_PDU_IS_REQUEST(pdu) &&
1732 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1733 if (block.num == 0 && block.m == 0) {
1734 uint8_t buf[4];
1735
1736 /* M needs to be set as asking for all the blocks */
1738 coap_encode_var_safe(buf, sizeof(buf),
1739 (0 << 4) | (1 << 3) | block.szx),
1740 buf);
1741 }
1742 }
1743#endif /* COAP_Q_BLOCK_SUPPORT */
1744
1745 /*
1746 * If type is CON and protocol is not reliable, there is no need to set up
1747 * lg_crcv here as it can be built up based on sent PDU if there is a
1748 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1749 * (Q-)Block1.
1750 */
1751 if (coap_check_send_need_lg_crcv(session, pdu)) {
1752 coap_lg_xmit_t *lg_xmit = NULL;
1753
1754 if (!session->lg_xmit && have_block1) {
1755 coap_log_debug("PDU presented by app\n");
1757 }
1758 /* See if this token is already in use for large body responses */
1759 LL_FOREACH(session->lg_crcv, lg_crcv) {
1760 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1761 /* Need to terminate and clean up previous response setup */
1762 LL_DELETE(session->lg_crcv, lg_crcv);
1763 coap_block_delete_lg_crcv(session, lg_crcv);
1764 break;
1765 }
1766 }
1767
1768 if (have_block1 && session->lg_xmit) {
1769 LL_FOREACH(session->lg_xmit, lg_xmit) {
1770 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1771 lg_xmit->b.b1.app_token &&
1772 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1773 break;
1774 }
1775 }
1776 }
1777 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1778 if (lg_crcv == NULL) {
1779 goto error;
1780 }
1781 if (lg_xmit) {
1782 /* Need to update the token as set up in the session->lg_xmit */
1783 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1784 }
1785 }
1786 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1787 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1788
1789#if COAP_Q_BLOCK_SUPPORT
1790 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1791 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1792 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1793 } else
1794#endif /* COAP_Q_BLOCK_SUPPORT */
1795 mid = coap_send_internal(session, pdu, NULL);
1796#else /* !COAP_CLIENT_SUPPORT */
1797 mid = coap_send_internal(session, pdu, NULL);
1798#endif /* !COAP_CLIENT_SUPPORT */
1799#if COAP_CLIENT_SUPPORT
1800 if (lg_crcv) {
1801 if (mid != COAP_INVALID_MID) {
1802 LL_PREPEND(session->lg_crcv, lg_crcv);
1803 } else {
1804 coap_block_delete_lg_crcv(session, lg_crcv);
1805 }
1806 }
1807#endif /* COAP_CLIENT_SUPPORT */
1808 return mid;
1809
1810error:
1812 return COAP_INVALID_MID;
1813}
1814
1815#if COAP_SERVER_SUPPORT
1816static int
1817coap_pdu_cksum(const coap_pdu_t *pdu, coap_digest_t *digest_buffer) {
1818 coap_digest_ctx_t *digest_ctx = coap_digest_setup();
1819
1820 if (!digest_ctx || !pdu) {
1821 goto fail;
1822 }
1823 if (pdu->used_size && pdu->token) {
1824 if (!coap_digest_update(digest_ctx, pdu->token, pdu->used_size)) {
1825 goto fail;
1826 }
1827 }
1828 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->type, sizeof(pdu->type))) {
1829 goto fail;
1830 }
1831 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->code, sizeof(pdu->code))) {
1832 goto fail;
1833 }
1834 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->mid, sizeof(pdu->mid))) {
1835 goto fail;
1836 }
1837 if (!coap_digest_final(digest_ctx, digest_buffer))
1838 return 0;
1839
1840 return 1;
1841
1842fail:
1843 coap_digest_free(digest_ctx);
1844 return 0;
1845}
1846#endif /* COAP_SERVER_SUPPORT */
1847
1850 uint8_t r;
1851 ssize_t bytes_written;
1852 coap_opt_iterator_t opt_iter;
1853
1854#if ! COAP_SERVER_SUPPORT
1855 (void)request_pdu;
1856#endif /* COAP_SERVER_SUPPORT */
1857 pdu->session = session;
1858#if COAP_CLIENT_SUPPORT
1859 if (session->session_failed) {
1860 coap_session_reconnect(session);
1861 if (session->session_failed)
1862 goto error;
1863 }
1864#endif /* COAP_CLIENT_SUPPORT */
1865#if COAP_PROXY_SUPPORT
1866 if (session->server_list) {
1867 /* Local session wanting to use proxy logic */
1868 return coap_proxy_local_write(session, pdu);
1869 }
1870#endif /* COAP_PROXY_SUPPORT */
1871 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1872 /*
1873 * Need to prepend our IP identifier to the data as per
1874 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1875 */
1876 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1877 coap_opt_t *opt;
1878 size_t hop_limit;
1879
1880 addr_str[sizeof(addr_str)-1] = '\000';
1881 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1882 sizeof(addr_str) - 1)) {
1883 char *cp;
1884 size_t len;
1885
1886 if (addr_str[0] == '[') {
1887 cp = strchr(addr_str, ']');
1888 if (cp)
1889 *cp = '\000';
1890 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1891 /* IPv4 embedded into IPv6 */
1892 cp = &addr_str[8];
1893 } else {
1894 cp = &addr_str[1];
1895 }
1896 } else {
1897 cp = strchr(addr_str, ':');
1898 if (cp)
1899 *cp = '\000';
1900 cp = addr_str;
1901 }
1902 len = strlen(cp);
1903
1904 /* See if Hop Limit option is being used in return path */
1905 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1906 if (opt) {
1907 uint8_t buf[4];
1908
1909 hop_limit =
1911 if (hop_limit == 1) {
1912 coap_log_warn("Proxy loop detected '%s'\n",
1913 (char *)pdu->data);
1916 } else if (hop_limit < 1 || hop_limit > 255) {
1917 /* Something is bad - need to drop this pdu (TODO or delete option) */
1918 coap_log_warn("Proxy return has bad hop limit count '%zu'\n",
1919 hop_limit);
1922 }
1923 hop_limit--;
1925 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1926 buf);
1927 }
1928
1929 /* Need to check that we are not seeing this proxy in the return loop */
1930 if (pdu->data && opt == NULL) {
1931 char *a_match;
1932 size_t data_len;
1933
1934 if (pdu->used_size + 1 > pdu->max_size) {
1935 /* No space */
1938 }
1939 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1940 /* Internal error */
1943 }
1944 data_len = pdu->used_size - (pdu->data - pdu->token);
1945 pdu->data[data_len] = '\000';
1946 a_match = strstr((char *)pdu->data, cp);
1947 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1948 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1949 a_match[len] == ' ')) {
1950 coap_log_warn("Proxy loop detected '%s'\n",
1951 (char *)pdu->data);
1954 }
1955 }
1956 if (pdu->used_size + len + 1 <= pdu->max_size) {
1957 size_t old_size = pdu->used_size;
1958 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1959 if (pdu->data == NULL) {
1960 /*
1961 * Set Hop Limit to max for return path. If this libcoap is in
1962 * a proxy loop path, it will always decrement hop limit in code
1963 * above and hence timeout / drop the response as appropriate
1964 */
1965 hop_limit = 255;
1967 (uint8_t *)&hop_limit);
1968 coap_add_data(pdu, len, (uint8_t *)cp);
1969 } else {
1970 /* prepend with space separator, leaving hop limit "as is" */
1971 memmove(pdu->data + len + 1, pdu->data,
1972 old_size - (pdu->data - pdu->token));
1973 memcpy(pdu->data, cp, len);
1974 pdu->data[len] = ' ';
1975 pdu->used_size += len + 1;
1976 }
1977 }
1978 }
1979 }
1980 }
1981
1982 if (session->echo) {
1983 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1984 session->echo->s))
1985 goto error;
1986 coap_delete_bin_const(session->echo);
1987 session->echo = NULL;
1988 }
1989#if COAP_OSCORE_SUPPORT
1990 if (session->oscore_encryption) {
1991 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1993 goto error;
1994 }
1995#endif /* COAP_OSCORE_SUPPORT */
1996
1997 if (!coap_pdu_encode_header(pdu, session->proto)) {
1998 goto error;
1999 }
2000
2001#if !COAP_DISABLE_TCP
2002 if (COAP_PROTO_RELIABLE(session->proto) &&
2004 if (!session->csm_block_supported) {
2005 /*
2006 * Need to check that this instance is not sending any block options as
2007 * the remote end via CSM has not informed us that there is support
2008 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2009 * This includes potential BERT blocks.
2010 */
2011 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2012 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2013 }
2014 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2015 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2016 }
2017 } else if (!session->csm_bert_rem_support) {
2018 coap_opt_t *opt;
2019
2020 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2021 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2022 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2023 }
2024 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2025 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2026 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2027 }
2028 }
2029 }
2030#endif /* !COAP_DISABLE_TCP */
2031
2032#if COAP_OSCORE_SUPPORT
2033 if (session->oscore_encryption &&
2034 pdu->type != COAP_MESSAGE_RST &&
2035 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2036 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2037 /* Refactor PDU as appropriate RFC8613 */
2038 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2039
2040 if (osc_pdu == NULL) {
2041 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2044 goto error;
2045 }
2046 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2048 pdu = osc_pdu;
2049 } else
2050#endif /* COAP_OSCORE_SUPPORT */
2051 bytes_written = coap_send_pdu(session, pdu, NULL);
2052
2053#if COAP_SERVER_SUPPORT
2054 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
2055 session->cached_pdu != pdu &&
2056 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2057 COAP_PDU_IS_REQUEST(request_pdu) &&
2058 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2060 session->cached_pdu = pdu;
2062 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
2063 }
2064#endif /* COAP_SERVER_SUPPORT */
2065
2066 if (bytes_written == COAP_PDU_DELAYED) {
2067 /* do not free pdu as it is stored with session for later use */
2068 return pdu->mid;
2069 }
2070 if (bytes_written < 0) {
2072 goto error;
2073 }
2074
2075#if !COAP_DISABLE_TCP
2076 if (COAP_PROTO_RELIABLE(session->proto) &&
2077 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2078 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2079 session->partial_write = (size_t)bytes_written;
2080 /* do not free pdu as it is stored with session for later use */
2081 return pdu->mid;
2082 } else {
2083 goto error;
2084 }
2085 }
2086#endif /* !COAP_DISABLE_TCP */
2087
2088 if (pdu->type != COAP_MESSAGE_CON
2089 || COAP_PROTO_RELIABLE(session->proto)) {
2090 coap_mid_t id = pdu->mid;
2092 return id;
2093 }
2094
2095 coap_queue_t *node = coap_new_node();
2096 if (!node) {
2097 coap_log_debug("coap_wait_ack: insufficient memory\n");
2098 goto error;
2099 }
2100
2101 node->id = pdu->mid;
2102 node->pdu = pdu;
2103 coap_prng_lkd(&r, sizeof(r));
2104 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2105 node->timeout = coap_calc_timeout(session, r);
2106 return coap_wait_ack(session->context, session, node);
2107error:
2109 return COAP_INVALID_MID;
2110}
2111
2112static int send_recv_terminate = 0;
2113
2114void
2118
2119COAP_API int
2121 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2122 int ret;
2123
2124 coap_lock_lock(return 0);
2125 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2127 return ret;
2128}
2129
2130/*
2131 * Return 0 or +ve Time in function in ms after successful transfer
2132 * -1 Invalid timeout parameter
2133 * -2 Failed to transmit PDU
2134 * -3 Nack or Event handler invoked, cancelling request
2135 * -4 coap_io_process returned error (fail to re-lock or select())
2136 * -5 Response not received in the given time
2137 * -6 Terminated by user
2138 * -7 Client mode code not enabled
2139 */
2140int
2142 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2143#if COAP_CLIENT_SUPPORT
2145 uint32_t rem_timeout = timeout_ms;
2146 uint32_t block_mode = session->block_mode;
2147 int ret = 0;
2148 coap_tick_t now;
2149 coap_tick_t start;
2150 coap_tick_t ticks_so_far;
2151 uint32_t time_so_far_ms;
2152
2153 coap_ticks(&start);
2154 assert(request_pdu);
2155
2157
2158 session->resp_pdu = NULL;
2159 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2160 request_pdu->actual_token.length);
2161
2162 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2163 ret = -1;
2164 goto fail;
2165 }
2166 if (session->state == COAP_SESSION_STATE_NONE) {
2167 ret = -3;
2168 goto fail;
2169 }
2170
2172 if (coap_is_mcast(&session->addr_info.remote))
2173 block_mode = session->block_mode;
2174
2175 session->doing_send_recv = 1;
2176 /* So the user needs to delete the PDU */
2177 coap_pdu_reference_lkd(request_pdu);
2178 mid = coap_send_lkd(session, request_pdu);
2179 if (mid == COAP_INVALID_MID) {
2180 if (!session->doing_send_recv)
2181 ret = -3;
2182 else
2183 ret = -2;
2184 goto fail;
2185 }
2186
2187 /* Wait for the response to come in */
2188 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2189 if (send_recv_terminate) {
2190 ret = -6;
2191 goto fail;
2192 }
2193 ret = coap_io_process_lkd(session->context, rem_timeout);
2194 if (ret < 0) {
2195 ret = -4;
2196 goto fail;
2197 }
2198 /* timeout_ms is for timeout between specific request and response */
2199 coap_ticks(&now);
2200 ticks_so_far = now - session->last_rx_tx;
2201 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2202 if (time_so_far_ms >= timeout_ms) {
2203 rem_timeout = 0;
2204 } else {
2205 rem_timeout = timeout_ms - time_so_far_ms;
2206 }
2207 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2208 /* To pick up on (D)TLS setup issues */
2209 coap_ticks(&now);
2210 ticks_so_far = now - start;
2211 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2212 if (time_so_far_ms >= timeout_ms) {
2213 rem_timeout = 0;
2214 } else {
2215 rem_timeout = timeout_ms - time_so_far_ms;
2216 }
2217 }
2218 }
2219
2220 if (rem_timeout) {
2221 coap_ticks(&now);
2222 ticks_so_far = now - start;
2223 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2224 ret = time_so_far_ms;
2225 /* Give PDU to user who will be calling coap_delete_pdu() */
2226 *response_pdu = session->resp_pdu;
2227 session->resp_pdu = NULL;
2228 if (*response_pdu == NULL) {
2229 ret = -3;
2230 }
2231 } else {
2232 /* If there is a resp_pdu, it will get cleared below */
2233 ret = -5;
2234 }
2235
2236fail:
2237 session->block_mode = block_mode;
2238 session->doing_send_recv = 0;
2239 /* delete referenced copy */
2240 coap_delete_pdu_lkd(session->resp_pdu);
2241 session->resp_pdu = NULL;
2243 session->req_token = NULL;
2244 return ret;
2245
2246#else /* !COAP_CLIENT_SUPPORT */
2247
2248 (void)session;
2249 (void)timeout_ms;
2250 (void)request_pdu;
2251 coap_log_warn("coap_send_recv: Client mode not supported\n");
2252 *response_pdu = NULL;
2253 return -7;
2254
2255#endif /* ! COAP_CLIENT_SUPPORT */
2256}
2257
2260 if (!context || !node || !node->session)
2261 return COAP_INVALID_MID;
2262
2263#if COAP_CLIENT_SUPPORT
2264 if (node->session->session_failed) {
2265 /* Force failure */
2266 node->retransmit_cnt = (unsigned char)node->session->max_retransmit;
2267 }
2268#endif /* COAP_CLIENT_SUPPORT */
2269
2270 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2271 if (node->retransmit_cnt < node->session->max_retransmit) {
2272 ssize_t bytes_written;
2273 coap_tick_t now;
2274 coap_tick_t next_delay;
2275 coap_address_t remote;
2276
2277 node->retransmit_cnt++;
2279
2280 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2281 if (context->ping_timeout &&
2282 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2283 uint8_t byte;
2284
2285 coap_prng_lkd(&byte, sizeof(byte));
2286 /* Don't exceed the ping timeout value */
2287 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2288 }
2289
2290 coap_ticks(&now);
2291 if (context->sendqueue == NULL) {
2292 node->t = next_delay;
2293 context->sendqueue_basetime = now;
2294 } else {
2295 /* make node->t relative to context->sendqueue_basetime */
2296 node->t = (now - context->sendqueue_basetime) + next_delay;
2297 }
2298 coap_insert_node(&context->sendqueue, node);
2299 coap_address_copy(&remote, &node->session->addr_info.remote);
2301
2302 if (node->is_mcast) {
2303 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2304 coap_session_str(node->session), node->id);
2305 } else {
2306 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2307 coap_session_str(node->session), node->id,
2308 node->retransmit_cnt,
2309 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2310 }
2311
2312 if (node->session->con_active)
2313 node->session->con_active--;
2314 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2315
2316 if (bytes_written == COAP_PDU_DELAYED) {
2317 /* PDU was not retransmitted immediately because a new handshake is
2318 in progress. node was moved to the send queue of the session. */
2319 return node->id;
2320 }
2321
2322 coap_address_copy(&node->session->addr_info.remote, &remote);
2323 if (node->is_mcast) {
2326 return COAP_INVALID_MID;
2327 }
2328
2329 if (bytes_written < 0)
2330 return (int)bytes_written;
2331
2332 return node->id;
2333 }
2334
2335#if COAP_CLIENT_SUPPORT
2336 if (node->session->session_failed) {
2337 coap_log_info("** %s: mid=0x%04x: deleted due to reconnection issue\n",
2338 coap_session_str(node->session), node->id);
2339 } else {
2340#endif /* COAP_CLIENT_SUPPORT */
2341 /* no more retransmissions, remove node from system */
2342 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2343 coap_session_str(node->session), node->id, node->retransmit_cnt);
2344#if COAP_CLIENT_SUPPORT
2345 }
2346#endif /* COAP_CLIENT_SUPPORT */
2347
2348#if COAP_SERVER_SUPPORT
2349 /* Check if subscriptions exist that should be canceled after
2350 COAP_OBS_MAX_FAIL */
2351 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2352 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2353 if (context->ping_timeout) {
2356 return COAP_INVALID_MID;
2357 } else {
2358 if (node->session->ref_subscriptions)
2359 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2360#if COAP_PROXY_SUPPORT
2361 /* Need to check is there is a proxy subscription active and delete it */
2362 if (node->session->ref_proxy_subs)
2363 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2364 0, COAP_PROXY_SUBS_TOKEN);
2365#endif /* COAP_PROXY_SUPPORT */
2366 }
2367 }
2368#endif /* COAP_SERVER_SUPPORT */
2369 if (node->session->con_active) {
2370 node->session->con_active--;
2372 /*
2373 * As there may be another CON in a different queue entry on the same
2374 * session that needs to be immediately released,
2375 * coap_session_connected() is called.
2376 * However, there is the possibility coap_wait_ack() may be called for
2377 * this node (queue) and re-added to context->sendqueue.
2378 * coap_delete_node_lkd(node) called shortly will handle this and
2379 * remove it.
2380 */
2382 }
2383 }
2384
2385 if (node->pdu->type == COAP_MESSAGE_CON) {
2387 }
2388#if COAP_CLIENT_SUPPORT
2389 node->session->doing_send_recv = 0;
2390#endif /* COAP_CLIENT_SUPPORT */
2391 /* And finally delete the node */
2393 return COAP_INVALID_MID;
2394}
2395
2396static int
2398 uint8_t *data;
2399 size_t data_len;
2400 int result = -1;
2401
2402 coap_packet_get_memmapped(packet, &data, &data_len);
2403 if (session->proto == COAP_PROTO_DTLS) {
2404#if COAP_SERVER_SUPPORT
2405 if (session->type == COAP_SESSION_TYPE_HELLO)
2406 result = coap_dtls_hello(session, data, data_len);
2407 else
2408#endif /* COAP_SERVER_SUPPORT */
2409 if (session->tls)
2410 result = coap_dtls_receive(session, data, data_len);
2411 } else if (session->proto == COAP_PROTO_UDP) {
2412 result = coap_handle_dgram(ctx, session, data, data_len);
2413 }
2414 return result;
2415}
2416
2417#if COAP_CLIENT_SUPPORT
2418void
2420#if COAP_DISABLE_TCP
2421 (void)now;
2422
2424#else /* !COAP_DISABLE_TCP */
2425 if (coap_netif_strm_connect2(session)) {
2426 session->last_rx_tx = now;
2428 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2429 } else {
2432 }
2433#endif /* !COAP_DISABLE_TCP */
2434}
2435#endif /* COAP_CLIENT_SUPPORT */
2436
2437static void
2439 (void)ctx;
2440 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2441
2442 while (session->delayqueue) {
2443 ssize_t bytes_written;
2444 coap_queue_t *q = session->delayqueue;
2445
2446 coap_address_copy(&session->addr_info.remote, &q->remote);
2447 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2448 coap_session_str(session), (int)q->pdu->mid);
2449 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2450 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2451 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2452 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2453 if (bytes_written > 0)
2454 session->last_rx_tx = now;
2455 if (bytes_written <= 0 ||
2456 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2457 if (bytes_written > 0)
2458 session->partial_write += (size_t)bytes_written;
2459 break;
2460 }
2461 session->delayqueue = q->next;
2462 session->partial_write = 0;
2464 }
2465}
2466
2467void
2469#if COAP_CONSTRAINED_STACK
2470 /* payload and packet can be protected by global_lock if needed */
2471 static unsigned char payload[COAP_RXBUFFER_SIZE];
2472 static coap_packet_t s_packet;
2473#else /* ! COAP_CONSTRAINED_STACK */
2474 unsigned char payload[COAP_RXBUFFER_SIZE];
2475 coap_packet_t s_packet;
2476#endif /* ! COAP_CONSTRAINED_STACK */
2477 coap_packet_t *packet = &s_packet;
2478
2480
2481 packet->length = sizeof(payload);
2482 packet->payload = payload;
2483
2484 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2485 ssize_t bytes_read;
2486 coap_address_t remote;
2487
2488 coap_address_copy(&remote, &session->addr_info.remote);
2489 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2490 bytes_read = coap_netif_dgrm_read(session, packet);
2491
2492 if (bytes_read < 0) {
2493 if (bytes_read == -2) {
2494 coap_address_copy(&session->addr_info.remote, &remote);
2495 /* Reset the session back to startup defaults */
2497 }
2498 } else if (bytes_read > 0) {
2499 session->last_rx_tx = now;
2500#if COAP_CLIENT_SUPPORT
2501 if (session->session_failed) {
2502 session->session_failed = 0;
2504 }
2505#endif /* COAP_CLIENT_SUPPORT */
2506 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2507 coap_handle_dgram_for_proto(ctx, session, packet);
2508 } else {
2509 coap_address_copy(&session->addr_info.remote, &remote);
2510 }
2511#if !COAP_DISABLE_TCP
2512 } else if (session->proto == COAP_PROTO_WS ||
2513 session->proto == COAP_PROTO_WSS) {
2514 ssize_t bytes_read = 0;
2515
2516 /* WebSocket layer passes us the whole packet */
2517 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2518 packet->payload,
2519 packet->length);
2520 if (bytes_read < 0) {
2522 } else if (bytes_read > 2) {
2523 coap_pdu_t *pdu;
2524
2525 session->last_rx_tx = now;
2526 /* Need max space incase PDU is updated with updated token etc. */
2527 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2528 if (!pdu) {
2529 return;
2530 }
2531
2532 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2534 coap_log_warn("discard malformed PDU\n");
2536 return;
2537 }
2538
2539 coap_dispatch(ctx, session, pdu);
2541 return;
2542 }
2543 } else {
2544 ssize_t bytes_read = 0;
2545 const uint8_t *p;
2546 int retry;
2547
2548 do {
2549 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2550 packet->payload,
2551 packet->length);
2552 if (bytes_read > 0) {
2553 session->last_rx_tx = now;
2554 }
2555 p = packet->payload;
2556 retry = bytes_read == (ssize_t)packet->length;
2557 while (bytes_read > 0) {
2558 if (session->partial_pdu) {
2559 size_t len = session->partial_pdu->used_size
2560 + session->partial_pdu->hdr_size
2561 - session->partial_read;
2562 size_t n = min(len, (size_t)bytes_read);
2563 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2564 + session->partial_read, p, n);
2565 p += n;
2566 bytes_read -= n;
2567 if (n == len) {
2568 coap_opt_filter_t error_opts;
2569 coap_pdu_t *pdu = session->partial_pdu;
2570
2571 session->partial_pdu = NULL;
2572 session->partial_read = 0;
2573
2574 coap_option_filter_clear(&error_opts);
2575 if (coap_pdu_parse_header(pdu, session->proto)
2576 && coap_pdu_parse_opt(pdu, &error_opts)) {
2577 coap_dispatch(ctx, session, pdu);
2578 } else if (error_opts.mask) {
2579 coap_pdu_t *response =
2581 COAP_RESPONSE_CODE(402), &error_opts);
2582 if (!response) {
2583 coap_log_warn("coap_read_session: cannot create error response\n");
2584 } else {
2585 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2586 coap_log_warn("coap_read_session: error sending response\n");
2587 }
2588 }
2590 } else {
2591 session->partial_read += n;
2592 }
2593 } else if (session->partial_read > 0) {
2594 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2595 session->read_header);
2596 size_t tkl = session->read_header[0] & 0x0f;
2597 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2598 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2599 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2600 size_t n = min(len, (size_t)bytes_read);
2601 memcpy(session->read_header + session->partial_read, p, n);
2602 p += n;
2603 bytes_read -= n;
2604 if (n == len) {
2605 /* Header now all in */
2606 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2607 hdr_size + tok_ext_bytes);
2608 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2609 coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
2610 coap_session_str(session),
2611 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2612 bytes_read = -1;
2613 break;
2614 }
2615 /* Need max space incase PDU is updated with updated token etc. */
2616 session->partial_pdu = coap_pdu_init(0, 0, 0,
2618 if (session->partial_pdu == NULL) {
2619 bytes_read = -1;
2620 break;
2621 }
2622 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2623 bytes_read = -1;
2624 break;
2625 }
2626 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2627 session->partial_pdu->used_size = size;
2628 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2629 session->partial_read = hdr_size + tok_ext_bytes;
2630 if (size == 0) {
2631 coap_pdu_t *pdu = session->partial_pdu;
2632
2633 session->partial_pdu = NULL;
2634 session->partial_read = 0;
2635 if (coap_pdu_parse_header(pdu, session->proto)) {
2636 coap_dispatch(ctx, session, pdu);
2637 }
2639 }
2640 } else {
2641 /* More of the header to go */
2642 session->partial_read += n;
2643 }
2644 } else {
2645 /* Get in first byte of the header */
2646 session->read_header[0] = *p++;
2647 bytes_read -= 1;
2648 if (!coap_pdu_parse_header_size(session->proto,
2649 session->read_header)) {
2650 bytes_read = -1;
2651 break;
2652 }
2653 session->partial_read = 1;
2654 }
2655 }
2656 } while (bytes_read == 0 && retry);
2657 if (bytes_read < 0)
2659#endif /* !COAP_DISABLE_TCP */
2660 }
2661}
2662
2663#if COAP_SERVER_SUPPORT
2664static int
2665coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2666 ssize_t bytes_read = -1;
2667 int result = -1; /* the value to be returned */
2668#if COAP_CONSTRAINED_STACK
2669 /* payload and e_packet can be protected by global_lock if needed */
2670 static unsigned char payload[COAP_RXBUFFER_SIZE];
2671 static coap_packet_t e_packet;
2672#else /* ! COAP_CONSTRAINED_STACK */
2673 unsigned char payload[COAP_RXBUFFER_SIZE];
2674 coap_packet_t e_packet;
2675#endif /* ! COAP_CONSTRAINED_STACK */
2676 coap_packet_t *packet = &e_packet;
2677
2678 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2679 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2680
2681 /* Need to do this as there may be holes in addr_info */
2682 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2683 packet->length = sizeof(payload);
2684 packet->payload = payload;
2686 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2687
2688 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2689 if (bytes_read < 0) {
2690 if (errno != EAGAIN) {
2691 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2692 }
2693 } else if (bytes_read > 0) {
2694 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2695 if (session) {
2697 coap_log_debug("* %s: netif: recv %4zd bytes\n",
2698 coap_session_str(session), bytes_read);
2699 result = coap_handle_dgram_for_proto(ctx, session, packet);
2700 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2701 coap_session_new_dtls_session(session, now);
2702 coap_session_release_lkd(session);
2703 }
2704 }
2705 return result;
2706}
2707
2708static int
2709coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2710 (void)ctx;
2711 (void)endpoint;
2712 (void)now;
2713 return 0;
2714}
2715
2716#if !COAP_DISABLE_TCP
2717static int
2718coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2719 coap_tick_t now, void *extra) {
2720 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2721 if (session)
2722 session->last_rx_tx = now;
2723 return session != NULL;
2724}
2725#endif /* !COAP_DISABLE_TCP */
2726#endif /* COAP_SERVER_SUPPORT */
2727
2728COAP_API void
2730 coap_lock_lock(return);
2731 coap_io_do_io_lkd(ctx, now);
2733}
2734
2735void
2737#ifdef COAP_EPOLL_SUPPORT
2738 (void)ctx;
2739 (void)now;
2740 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2741#else /* ! COAP_EPOLL_SUPPORT */
2742 coap_session_t *s, *rtmp;
2743
2745#if COAP_SERVER_SUPPORT
2746 coap_endpoint_t *ep, *tmp;
2747 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2748 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2749 coap_read_endpoint(ctx, ep, now);
2750 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2751 coap_write_endpoint(ctx, ep, now);
2752#if !COAP_DISABLE_TCP
2753 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2754 coap_accept_endpoint(ctx, ep, now, NULL);
2755#endif /* !COAP_DISABLE_TCP */
2756 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2757 /* Make sure the session object is not deleted in one of the callbacks */
2759#if COAP_CLIENT_SUPPORT
2760 if (s->client_initiated && (s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2761 coap_connect_session(s, now);
2762 }
2763#endif /* COAP_CLIENT_SUPPORT */
2764 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2765 coap_read_session(ctx, s, now);
2766 }
2767 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2768 coap_write_session(ctx, s, now);
2769 }
2771 }
2772 }
2773#endif /* COAP_SERVER_SUPPORT */
2774
2775#if COAP_CLIENT_SUPPORT
2776 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2777 /* Make sure the session object is not deleted in one of the callbacks */
2779 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2780 coap_connect_session(s, now);
2781 }
2782 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2783 coap_read_session(ctx, s, now);
2784 }
2785 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2786 coap_write_session(ctx, s, now);
2787 }
2789 }
2790#endif /* COAP_CLIENT_SUPPORT */
2791#endif /* ! COAP_EPOLL_SUPPORT */
2792}
2793
2794COAP_API void
2795coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2796 coap_lock_lock(return);
2797 coap_io_do_epoll_lkd(ctx, events, nevents);
2799}
2800
2801/*
2802 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2803 * directly saves having to iterate through the endpoints / sessions.
2804 */
2805void
2806coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2807#ifndef COAP_EPOLL_SUPPORT
2808 (void)ctx;
2809 (void)events;
2810 (void)nevents;
2811 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2812#else /* COAP_EPOLL_SUPPORT */
2813 coap_tick_t now;
2814 size_t j;
2815
2817 coap_ticks(&now);
2818 for (j = 0; j < nevents; j++) {
2819 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2820
2821 /* Ignore 'timer trigger' ptr which is NULL */
2822 if (sock) {
2823#if COAP_SERVER_SUPPORT
2824 if (sock->endpoint) {
2825 coap_endpoint_t *endpoint = sock->endpoint;
2826 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2827 (events[j].events & EPOLLIN)) {
2828 sock->flags |= COAP_SOCKET_CAN_READ;
2829 coap_read_endpoint(endpoint->context, endpoint, now);
2830 }
2831
2832 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2833 (events[j].events & EPOLLOUT)) {
2834 /*
2835 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2836 * be true causing epoll_wait to return early
2837 */
2838 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2840 coap_write_endpoint(endpoint->context, endpoint, now);
2841 }
2842
2843#if !COAP_DISABLE_TCP
2844 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2845 (events[j].events & EPOLLIN)) {
2847 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2848 }
2849#endif /* !COAP_DISABLE_TCP */
2850
2851 } else
2852#endif /* COAP_SERVER_SUPPORT */
2853 if (sock->session) {
2854 coap_session_t *session = sock->session;
2855
2856 /* Make sure the session object is not deleted
2857 in one of the callbacks */
2859#if COAP_CLIENT_SUPPORT
2860 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2861 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2863 coap_connect_session(session, now);
2864 if (coap_netif_available(session) &&
2865 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2866 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2867 }
2868 }
2869#endif /* COAP_CLIENT_SUPPORT */
2870
2871 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2872 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2873 sock->flags |= COAP_SOCKET_CAN_READ;
2874 coap_read_session(session->context, session, now);
2875 }
2876
2877 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2878 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2879 /*
2880 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2881 * be true causing epoll_wait to return early
2882 */
2883 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2885 coap_write_session(session->context, session, now);
2886 }
2887 /* Now dereference session so it can go away if needed */
2888 coap_session_release_lkd(session);
2889 }
2890 } else if (ctx->eptimerfd != -1) {
2891 /*
2892 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2893 * it so that it does not set EPOLLIN in the next epoll_wait().
2894 */
2895 uint64_t count;
2896
2897 /* Check the result from read() to suppress the warning on
2898 * systems that declare read() with warn_unused_result. */
2899 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2900 /* do nothing */;
2901 }
2902 }
2903 }
2904 /* And update eptimerfd as to when to next trigger */
2905 coap_ticks(&now);
2906 coap_io_prepare_epoll_lkd(ctx, now);
2907#endif /* COAP_EPOLL_SUPPORT */
2908}
2909
2910int
2912 uint8_t *msg, size_t msg_len) {
2913
2914 coap_pdu_t *pdu = NULL;
2915 coap_opt_filter_t error_opts;
2916
2917 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2918 if (msg_len < 4) {
2919 /* Minimum size of CoAP header - ignore runt */
2920 return -1;
2921 }
2922 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2923 /*
2924 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2925 * this MUST be silently ignored.
2926 */
2927 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2928 return -1;
2929 }
2930
2931 /* Need max space incase PDU is updated with updated token etc. */
2932 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2933 if (!pdu)
2934 goto error;
2935
2936 coap_option_filter_clear(&error_opts);
2937 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
2939 coap_log_warn("discard malformed PDU\n");
2940 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
2941 coap_pdu_t *response =
2943 COAP_RESPONSE_CODE(402), &error_opts);
2944 if (!response) {
2945 coap_log_warn("coap_handle_dgram: cannot create error response\n");
2946 } else {
2947 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2948 coap_log_warn("coap_handle_dgram: error sending response\n");
2949 }
2951 return -1;
2952 } else {
2953 goto error;
2954 }
2955 }
2956
2957 coap_dispatch(ctx, session, pdu);
2959 return 0;
2960
2961error:
2962 /*
2963 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2964 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2965 */
2966 coap_send_rst_lkd(session, pdu);
2968 return -1;
2969}
2970
2971int
2973 coap_queue_t **node) {
2974 coap_queue_t *p, *q;
2975
2976 if (!queue || !*queue)
2977 return 0;
2978
2979 /* replace queue head if PDU's time is less than head's time */
2980
2981 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2982 *node = *queue;
2983 *queue = (*queue)->next;
2984 if (*queue) { /* adjust relative time of new queue head */
2985 (*queue)->t += (*node)->t;
2986 }
2987 (*node)->next = NULL;
2988 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2989 coap_session_str(session), id);
2990 return 1;
2991 }
2992
2993 /* search message id in queue to remove (only first occurence will be removed) */
2994 q = *queue;
2995 do {
2996 p = q;
2997 q = q->next;
2998 } while (q && (session != q->session || id != q->id));
2999
3000 if (q) { /* found message id */
3001 p->next = q->next;
3002 if (p->next) { /* must update relative time of p->next */
3003 p->next->t += q->t;
3004 }
3005 q->next = NULL;
3006 *node = q;
3007 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
3008 coap_session_str(session), id);
3009 return 1;
3010 }
3011
3012 return 0;
3013
3014}
3015
3016static int
3018 coap_bin_const_t *token, coap_queue_t **node) {
3019 coap_queue_t *p, *q;
3020
3021 if (!queue || !*queue)
3022 return 0;
3023
3024 /* replace queue head if PDU's time is less than head's time */
3025
3026 if (session == (*queue)->session &&
3027 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
3028 *node = *queue;
3029 *queue = (*queue)->next;
3030 if (*queue) { /* adjust relative time of new queue head */
3031 (*queue)->t += (*node)->t;
3032 }
3033 (*node)->next = NULL;
3034 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3035 coap_session_str(session), (*node)->id);
3036 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3037 session->con_active--;
3038 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3039 /* Flush out any entries on session->delayqueue */
3040 coap_session_connected(session);
3041 }
3042 return 1;
3043 }
3044
3045 /* search token in queue to remove (only first occurence will be removed) */
3046 q = *queue;
3047 do {
3048 p = q;
3049 q = q->next;
3050 } while (q && (session != q->session ||
3051 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3052
3053 if (q) { /* found token */
3054 p->next = q->next;
3055 if (p->next) { /* must update relative time of p->next */
3056 p->next->t += q->t;
3057 }
3058 q->next = NULL;
3059 *node = q;
3060 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3061 coap_session_str(session), (*node)->id);
3062 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3063 session->con_active--;
3064 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3065 /* Flush out any entries on session->delayqueue */
3066 coap_session_connected(session);
3067 }
3068 return 1;
3069 }
3070
3071 return 0;
3072
3073}
3074
3075void
3077 coap_nack_reason_t reason) {
3078 coap_queue_t *p, *q;
3079
3080 while (context->sendqueue && context->sendqueue->session == session) {
3081 q = context->sendqueue;
3082 context->sendqueue = q->next;
3083 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3084 coap_session_str(session), q->id);
3085 if (q->pdu->type == COAP_MESSAGE_CON) {
3086 coap_handle_nack(session, q->pdu, reason, q->id);
3087 }
3089 }
3090
3091 if (!context->sendqueue)
3092 return;
3093
3094 p = context->sendqueue;
3095 q = p->next;
3096
3097 while (q) {
3098 if (q->session == session) {
3099 p->next = q->next;
3100 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3101 coap_session_str(session), q->id);
3102 if (q->pdu->type == COAP_MESSAGE_CON) {
3103 coap_handle_nack(session, q->pdu, reason, q->id);
3104 }
3106 q = p->next;
3107 } else {
3108 p = q;
3109 q = q->next;
3110 }
3111 }
3112}
3113
3114void
3116 coap_bin_const_t *token) {
3117 /* cancel all messages in sendqueue that belong to session
3118 * and use the specified token */
3119 coap_queue_t **p, *q;
3120
3121 if (!context->sendqueue)
3122 return;
3123
3124 p = &context->sendqueue;
3125 q = *p;
3126
3127 while (q) {
3128 if (q->session == session &&
3129 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3130 *p = q->next;
3131 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3132 coap_session_str(session), q->id);
3133 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3134 session->con_active--;
3135 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3136 /* Flush out any entries on session->delayqueue */
3137 coap_session_connected(session);
3138 }
3140 } else {
3141 p = &(q->next);
3142 }
3143 q = *p;
3144 }
3145}
3146
3147coap_pdu_t *
3149 coap_opt_filter_t *opts) {
3150 coap_opt_iterator_t opt_iter;
3151 coap_pdu_t *response;
3152 unsigned char type;
3153
3154#if COAP_ERROR_PHRASE_LENGTH > 0
3155 const char *phrase;
3156 if (code != COAP_RESPONSE_CODE(508)) {
3157 phrase = coap_response_phrase(code);
3158 } else {
3159 phrase = NULL;
3160 }
3161#endif
3162
3163 assert(request);
3164
3165 /* cannot send ACK if original request was not confirmable */
3166 type = request->type == COAP_MESSAGE_CON ?
3168
3169 /* Now create the response and fill with options and payload data. */
3170 response = coap_pdu_init(type, code, request->mid,
3171 request->session ?
3172 coap_session_max_pdu_size_lkd(request->session) : 512);
3173 if (response) {
3174 /* copy token */
3175 if (!coap_add_token(response, request->actual_token.length,
3176 request->actual_token.s)) {
3177 coap_log_debug("cannot add token to error response\n");
3178 coap_delete_pdu_lkd(response);
3179 return NULL;
3180 }
3181 if (response->code == COAP_RESPONSE_CODE(402)) {
3182 char buf[128];
3183 int first = 1;
3184
3185#if COAP_ERROR_PHRASE_LENGTH > 0
3186 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3187#else
3188 buf[0] = '\000';
3189#endif
3190 /* copy all options into diagnostic message */
3191 coap_option_iterator_init(request, &opt_iter, opts);
3192 while (coap_option_next(&opt_iter)) {
3193 size_t len = strlen(buf);
3194
3195 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",", opt_iter.number);
3196 first = 0;
3197 }
3198 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3199 } else if (opts && opts->mask) {
3200 coap_opt_t *option;
3201
3202 /* copy all options */
3203 coap_option_iterator_init(request, &opt_iter, opts);
3204 while ((option = coap_option_next(&opt_iter))) {
3205 coap_add_option_internal(response, opt_iter.number,
3206 coap_opt_length(option),
3207 coap_opt_value(option));
3208 }
3209#if COAP_ERROR_PHRASE_LENGTH > 0
3210 if (phrase)
3211 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3212 } else {
3213 /* note that diagnostic messages do not need a Content-Format option. */
3214 if (phrase)
3215 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3216#endif
3217 }
3218 }
3219
3220 return response;
3221}
3222
3223#if COAP_SERVER_SUPPORT
3224#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3225
3226static void
3227free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3228 coap_delete_string(app_ptr);
3229}
3230
3231/*
3232 * Caution: As this handler is in libcoap space, it is called with
3233 * context locked.
3234 */
3235static void
3236hnd_get_wellknown_lkd(coap_resource_t *resource,
3237 coap_session_t *session,
3238 const coap_pdu_t *request,
3239 const coap_string_t *query,
3240 coap_pdu_t *response) {
3241 size_t len = 0;
3242 coap_string_t *data_string = NULL;
3243 coap_print_status_t result = 0;
3244 size_t wkc_len = 0;
3245 uint8_t buf[4];
3246
3247 /*
3248 * Quick hack to determine the size of the resource descriptions for
3249 * .well-known/core.
3250 */
3251 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3252 if (result & COAP_PRINT_STATUS_ERROR) {
3253 coap_log_warn("cannot determine length of /.well-known/core\n");
3254 goto error;
3255 }
3256
3257 if (wkc_len > 0) {
3258 data_string = coap_new_string(wkc_len);
3259 if (!data_string)
3260 goto error;
3261
3262 len = wkc_len;
3263 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3264 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3265 coap_log_debug("coap_print_wellknown failed\n");
3266 goto error;
3267 }
3268 assert(len <= (size_t)wkc_len);
3269 data_string->length = len;
3270
3271 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3273 coap_encode_var_safe(buf, sizeof(buf),
3275 goto error;
3276 }
3277 if (response->used_size + len + 1 > response->max_size) {
3278 /*
3279 * Data does not fit into a packet and no libcoap block support
3280 * +1 for end of options marker
3281 */
3282 coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
3283 len, response->max_size - response->used_size - 1);
3284 len = response->max_size - response->used_size - 1;
3285 }
3286 if (!coap_add_data(response, len, data_string->s)) {
3287 goto error;
3288 }
3289 free_wellknown_response(session, data_string);
3290 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3291 response, query,
3293 -1, 0, data_string->length,
3294 data_string->s,
3295 free_wellknown_response,
3296 data_string)) {
3297 goto error_released;
3298 }
3299 } else {
3301 coap_encode_var_safe(buf, sizeof(buf),
3303 goto error;
3304 }
3305 }
3306 response->code = COAP_RESPONSE_CODE(205);
3307 return;
3308
3309error:
3310 free_wellknown_response(session, data_string);
3311error_released:
3312 if (response->code == 0) {
3313 /* set error code 5.03 and remove all options and data from response */
3314 response->code = COAP_RESPONSE_CODE(503);
3315 response->used_size = response->e_token_length;
3316 response->data = NULL;
3317 }
3318}
3319#endif /* COAP_SERVER_SUPPORT */
3320
3331static int
3333 int num_cancelled = 0; /* the number of observers cancelled */
3334
3335#ifndef COAP_SERVER_SUPPORT
3336 (void)sent;
3337#endif /* ! COAP_SERVER_SUPPORT */
3338 (void)context;
3339
3340#if COAP_SERVER_SUPPORT
3341 /* remove observer for this resource, if any
3342 * Use token from sent and try to find a matching resource. Uh!
3343 */
3344 RESOURCES_ITER(context->resources, r) {
3345 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3346 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3347 }
3348#endif /* COAP_SERVER_SUPPORT */
3349
3350 return num_cancelled;
3351}
3352
3353#if COAP_SERVER_SUPPORT
3358enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3359
3360/*
3361 * Checks for No-Response option in given @p request and
3362 * returns @c RESPONSE_DROP if @p response should be suppressed
3363 * according to RFC 7967.
3364 *
3365 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3366 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3367 * on retrying.
3368 *
3369 * Checks if the response code is 0.00 and if either the session is reliable or
3370 * non-confirmable, @c RESPONSE_DROP is also returned.
3371 *
3372 * Multicast response checking is also carried out.
3373 *
3374 * NOTE: It is the responsibility of the application to determine whether
3375 * a delayed separate response should be sent as the original requesting packet
3376 * containing the No-Response option has long since gone.
3377 *
3378 * The value of the No-Response option is encoded as
3379 * follows:
3380 *
3381 * @verbatim
3382 * +-------+-----------------------+-----------------------------------+
3383 * | Value | Binary Representation | Description |
3384 * +-------+-----------------------+-----------------------------------+
3385 * | 0 | <empty> | Interested in all responses. |
3386 * +-------+-----------------------+-----------------------------------+
3387 * | 2 | 00000010 | Not interested in 2.xx responses. |
3388 * +-------+-----------------------+-----------------------------------+
3389 * | 8 | 00001000 | Not interested in 4.xx responses. |
3390 * +-------+-----------------------+-----------------------------------+
3391 * | 16 | 00010000 | Not interested in 5.xx responses. |
3392 * +-------+-----------------------+-----------------------------------+
3393 * @endverbatim
3394 *
3395 * @param request The CoAP request to check for the No-Response option.
3396 * This parameter must not be NULL.
3397 * @param response The response that is potentially suppressed.
3398 * This parameter must not be NULL.
3399 * @param session The session this request/response are associated with.
3400 * This parameter must not be NULL.
3401 * @return RESPONSE_DEFAULT when no special treatment is requested,
3402 * RESPONSE_DROP when the response must be discarded, or
3403 * RESPONSE_SEND when the response must be sent.
3404 */
3405static enum respond_t
3406no_response(coap_pdu_t *request, coap_pdu_t *response,
3407 coap_session_t *session, coap_resource_t *resource) {
3408 coap_opt_t *nores;
3409 coap_opt_iterator_t opt_iter;
3410 unsigned int val = 0;
3411
3412 assert(request);
3413 assert(response);
3414
3415 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3416 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3417
3418 if (nores) {
3420
3421 /* The response should be dropped when the bit corresponding to
3422 * the response class is set (cf. table in function
3423 * documentation). When a No-Response option is present and the
3424 * bit is not set, the sender explicitly indicates interest in
3425 * this response. */
3426 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3427 /* Should be dropping the response */
3428 if (response->type == COAP_MESSAGE_ACK &&
3429 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3430 /* Still need to ACK the request */
3431 response->code = 0;
3432 /* Remove token/data from piggybacked acknowledgment PDU */
3433 response->actual_token.length = 0;
3434 response->e_token_length = 0;
3435 response->used_size = 0;
3436 response->data = NULL;
3437 return RESPONSE_SEND;
3438 } else {
3439 return RESPONSE_DROP;
3440 }
3441 } else {
3442 /* True for mcast as well RFC7967 2.1 */
3443 return RESPONSE_SEND;
3444 }
3445 } else if (resource && session->context->mcast_per_resource &&
3446 coap_is_mcast(&session->addr_info.local)) {
3447 /* Handle any mcast suppression specifics if no NoResponse option */
3448 if ((resource->flags &
3450 COAP_RESPONSE_CLASS(response->code) == 2) {
3451 return RESPONSE_DROP;
3452 } else if ((resource->flags &
3454 response->code == COAP_RESPONSE_CODE(205)) {
3455 if (response->data == NULL)
3456 return RESPONSE_DROP;
3457 } else if ((resource->flags &
3459 COAP_RESPONSE_CLASS(response->code) == 4) {
3460 return RESPONSE_DROP;
3461 } else if ((resource->flags &
3463 COAP_RESPONSE_CLASS(response->code) == 5) {
3464 return RESPONSE_DROP;
3465 }
3466 }
3467 } else if (COAP_PDU_IS_EMPTY(response) &&
3468 (response->type == COAP_MESSAGE_NON ||
3469 COAP_PROTO_RELIABLE(session->proto))) {
3470 /* response is 0.00, and this is reliable or non-confirmable */
3471 return RESPONSE_DROP;
3472 }
3473
3474 /*
3475 * Do not send error responses for requests that were received via
3476 * IP multicast. RFC7252 8.1
3477 */
3478
3479 if (coap_is_mcast(&session->addr_info.local)) {
3480 if (request->type == COAP_MESSAGE_NON &&
3481 response->type == COAP_MESSAGE_RST)
3482 return RESPONSE_DROP;
3483
3484 if ((!resource || session->context->mcast_per_resource == 0) &&
3485 COAP_RESPONSE_CLASS(response->code) > 2)
3486 return RESPONSE_DROP;
3487 }
3488
3489 /* Default behavior applies when we are not dealing with a response
3490 * (class == 0) or the request did not contain a No-Response option.
3491 */
3492 return RESPONSE_DEFAULT;
3493}
3494
3495static coap_str_const_t coap_default_uri_wellknown = {
3497 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3498};
3499
3500/* Initialized in coap_startup() */
3501static coap_resource_t resource_uri_wellknown;
3502
3503static void
3504handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3505 coap_pdu_t *orig_pdu) {
3506 coap_method_handler_t h = NULL;
3507 coap_pdu_t *response = NULL;
3508 coap_opt_filter_t opt_filter;
3509 coap_resource_t *resource = NULL;
3510 /* The respond field indicates whether a response must be treated
3511 * specially due to a No-Response option that declares disinterest
3512 * or interest in a specific response class. DEFAULT indicates that
3513 * No-Response has not been specified. */
3514 enum respond_t respond = RESPONSE_DEFAULT;
3515 coap_opt_iterator_t opt_iter;
3516 coap_opt_t *opt;
3517 int is_proxy_uri = 0;
3518 int is_proxy_scheme = 0;
3519 int skip_hop_limit_check = 0;
3520 int resp = 0;
3521 int send_early_empty_ack = 0;
3522 coap_string_t *query = NULL;
3523 coap_opt_t *observe = NULL;
3524 coap_string_t *uri_path = NULL;
3525 int observe_action = COAP_OBSERVE_CANCEL;
3526 coap_block_b_t block;
3527 int added_block = 0;
3528 coap_lg_srcv_t *free_lg_srcv = NULL;
3529#if COAP_Q_BLOCK_SUPPORT
3530 int lg_xmit_ctrl = 0;
3531#endif /* COAP_Q_BLOCK_SUPPORT */
3532#if COAP_ASYNC_SUPPORT
3533 coap_async_t *async;
3534#endif /* COAP_ASYNC_SUPPORT */
3535
3536 if (coap_is_mcast(&session->addr_info.local)) {
3537 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3538 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3539 return;
3540 }
3541 }
3542#if COAP_ASYNC_SUPPORT
3543 async = coap_find_async_lkd(session, pdu->actual_token);
3544 if (async) {
3545 coap_tick_t now;
3546
3547 coap_ticks(&now);
3548 if (async->delay == 0 || async->delay > now) {
3549 /* re-transmit missing ACK (only if CON) */
3550 coap_log_info("Retransmit async response\n");
3551 coap_send_ack_lkd(session, pdu);
3552 /* and do not pass on to the upper layers */
3553 return;
3554 }
3555 }
3556#endif /* COAP_ASYNC_SUPPORT */
3557
3558 coap_option_filter_clear(&opt_filter);
3559 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3560 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3561 if (opt) {
3562 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3563 if (!opt) {
3564 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3565 resp = 402;
3566 goto fail_response;
3567 }
3568 is_proxy_scheme = 1;
3569 }
3570
3571 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3572 if (opt)
3573 is_proxy_uri = 1;
3574 }
3575
3576 if (is_proxy_scheme || is_proxy_uri) {
3577 coap_uri_t uri;
3578
3579 if (!context->proxy_uri_resource) {
3580 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3581 coap_log_debug("Proxy-%s support not configured\n",
3582 is_proxy_scheme ? "Scheme" : "Uri");
3583 resp = 505;
3584 goto fail_response;
3585 }
3586 if (((size_t)pdu->code - 1 <
3587 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3588 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3589 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3590 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3591 is_proxy_scheme ? "Scheme" : "Uri",
3592 pdu->code/100, pdu->code%100);
3593 resp = 505;
3594 goto fail_response;
3595 }
3596
3597 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3598 if (is_proxy_uri) {
3600 coap_opt_length(opt), &uri) < 0) {
3601 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3602 coap_log_debug("Proxy-URI not decodable\n");
3603 resp = 505;
3604 goto fail_response;
3605 }
3606 } else {
3607 memset(&uri, 0, sizeof(uri));
3608 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3609 if (opt) {
3610 uri.host.length = coap_opt_length(opt);
3611 uri.host.s = coap_opt_value(opt);
3612 } else
3613 uri.host.length = 0;
3614 }
3615
3616 resource = context->proxy_uri_resource;
3617 if (uri.host.length && resource->proxy_name_count &&
3618 resource->proxy_name_list) {
3619 size_t i;
3620
3621 if (resource->proxy_name_count == 1 &&
3622 resource->proxy_name_list[0]->length == 0) {
3623 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3624 i = 0;
3625 } else {
3626 for (i = 0; i < resource->proxy_name_count; i++) {
3627 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3628 break;
3629 }
3630 }
3631 }
3632 if (i != resource->proxy_name_count) {
3633 /* This server is hosting the proxy connection endpoint */
3634 if (pdu->crit_opt) {
3635 /* Cannot handle critical option */
3636 pdu->crit_opt = 0;
3637 resp = 402;
3638 resource = NULL;
3639 goto fail_response;
3640 }
3641 is_proxy_uri = 0;
3642 is_proxy_scheme = 0;
3643 skip_hop_limit_check = 1;
3644 }
3645 }
3646 resource = NULL;
3647 }
3648 assert(resource == NULL);
3649
3650 if (!skip_hop_limit_check) {
3651 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3652 if (opt) {
3653 size_t hop_limit;
3654 uint8_t buf[4];
3655
3656 hop_limit =
3658 if (hop_limit == 1) {
3659 /* coap_send_internal() will fill in the IP address for us */
3660 resp = 508;
3661 goto fail_response;
3662 } else if (hop_limit < 1 || hop_limit > 255) {
3663 /* Need to return a 4.00 RFC8768 Section 3 */
3664 coap_log_info("Invalid Hop Limit\n");
3665 resp = 400;
3666 goto fail_response;
3667 }
3668 hop_limit--;
3670 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3671 buf);
3672 }
3673 }
3674
3675 uri_path = coap_get_uri_path(pdu);
3676 if (!uri_path)
3677 return;
3678
3679 if (!is_proxy_uri && !is_proxy_scheme) {
3680 /* try to find the resource from the request URI */
3681 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3682 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3683 }
3684
3685 if ((resource == NULL) || (resource->is_unknown == 1) ||
3686 (resource->is_proxy_uri == 1)) {
3687 /* The resource was not found or there is an unexpected match against the
3688 * resource defined for handling unknown or proxy URIs.
3689 */
3690 if (resource != NULL)
3691 /* Close down unexpected match */
3692 resource = NULL;
3693 /*
3694 * Check if the request URI happens to be the well-known URI, or if the
3695 * unknown resource handler is defined, a PUT or optionally other methods,
3696 * if configured, for the unknown handler.
3697 *
3698 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3699 * proxy URI handler.
3700 *
3701 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3702 * set, call the unknown URI handler with any unknown URI (including
3703 * .well-known/core) if the appropriate method is defined.
3704 *
3705 * else if well-known URI generate a default response.
3706 *
3707 * else if unknown URI handler defined, call the unknown
3708 * URI handler (to allow for potential generation of resource
3709 * [RFC7272 5.8.3]) if the appropriate method is defined.
3710 *
3711 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3712 *
3713 * else return 4.04.
3714 */
3715
3716 if (is_proxy_uri || is_proxy_scheme) {
3717 resource = context->proxy_uri_resource;
3718 } else if (context->unknown_resource != NULL &&
3720 ((size_t)pdu->code - 1 <
3721 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3722 (context->unknown_resource->handler[pdu->code - 1])) {
3723 resource = context->unknown_resource;
3724 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3725 /* request for .well-known/core */
3726 resource = &resource_uri_wellknown;
3727 } else if ((context->unknown_resource != NULL) &&
3728 ((size_t)pdu->code - 1 <
3729 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3730 (context->unknown_resource->handler[pdu->code - 1])) {
3731 /*
3732 * The unknown_resource can be used to handle undefined resources
3733 * for a PUT request and can support any other registered handler
3734 * defined for it
3735 * Example set up code:-
3736 * r = coap_resource_unknown_init(hnd_put_unknown);
3737 * coap_register_request_handler(r, COAP_REQUEST_POST,
3738 * hnd_post_unknown);
3739 * coap_register_request_handler(r, COAP_REQUEST_GET,
3740 * hnd_get_unknown);
3741 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3742 * hnd_delete_unknown);
3743 * coap_add_resource(ctx, r);
3744 *
3745 * Note: It is not possible to observe the unknown_resource, a separate
3746 * resource must be created (by PUT or POST) which has a GET
3747 * handler to be observed
3748 */
3749 resource = context->unknown_resource;
3750 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3751 /*
3752 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3753 */
3754 coap_log_debug("request for unknown resource '%*.*s',"
3755 " return 2.02\n",
3756 (int)uri_path->length,
3757 (int)uri_path->length,
3758 uri_path->s);
3759 resp = 202;
3760 goto fail_response;
3761 } else if ((context->dyn_create_handler != NULL) &&
3763 /* Above test must be the same as in coap_op_dyn_resource_load_disk() */
3764 if (context->dynamic_cur < context->dynamic_max || context->dynamic_max == 0) {
3765#if COAP_WITH_OBSERVE_PERSIST
3766 /* If we are maintaining Observe persist */
3767 context->unknown_pdu = pdu;
3768 context->unknown_session = session;
3769#endif /* COAP_WITH_OBSERVE_PERSIST */
3770 coap_lock_callback_ret(resource, context->dyn_create_handler(session, pdu));
3771#if COAP_WITH_OBSERVE_PERSIST
3772 /* If we are maintaining Observe persist */
3773 context->unknown_pdu = NULL;
3774 context->unknown_session = NULL;
3775#endif /* COAP_WITH_OBSERVE_PERSIST */
3776 }
3777 if (!resource) {
3778 resp = 406;
3779 goto fail_response;
3780 }
3781 context->dynamic_cur++;
3782 resource->is_dynamic = 1;
3783 } else { /* request for any another resource, return 4.04 */
3784
3785 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3786 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3787 resp = 404;
3788 goto fail_response;
3789 }
3790
3791 }
3792
3794
3795#if COAP_OSCORE_SUPPORT
3796 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3797 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3798 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3799 resp = 401;
3800 goto fail_response;
3801 }
3802#endif /* COAP_OSCORE_SUPPORT */
3803 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3804 /* Check for existing resource and If-Non-Match */
3805 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3806 if (opt) {
3807 resp = 412;
3808 goto fail_response;
3809 }
3810 }
3811
3812 /* the resource was found, check if there is a registered handler */
3813 if ((size_t)pdu->code - 1 <
3814 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3815 h = resource->handler[pdu->code - 1];
3816
3817 if (h == NULL) {
3818 resp = 405;
3819 goto fail_response;
3820 }
3821 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3822 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3823 if (opt == NULL) {
3824 /* RFC 8132 2.3.1 */
3825 resp = 415;
3826 goto fail_response;
3827 }
3828 }
3829 if (context->mcast_per_resource &&
3830 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3831 coap_is_mcast(&session->addr_info.local)) {
3832 resp = 405;
3833 goto fail_response;
3834 }
3835
3836 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3838 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3839 if (!response) {
3840 coap_log_err("could not create response PDU\n");
3841 resp = 500;
3842 goto fail_response;
3843 }
3844 response->session = session;
3845#if COAP_ASYNC_SUPPORT
3846 /* If handling a separate response, need CON, not ACK response */
3847 if (async && pdu->type == COAP_MESSAGE_CON)
3848 response->type = COAP_MESSAGE_CON;
3849#endif /* COAP_ASYNC_SUPPORT */
3850 /* A lot of the reliable code assumes type is CON */
3851 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3852 response->type = COAP_MESSAGE_CON;
3853
3854 if (!coap_add_token(response, pdu->actual_token.length,
3855 pdu->actual_token.s)) {
3856 resp = 500;
3857 goto fail_response;
3858 }
3859
3860 query = coap_get_query(pdu);
3861
3862 /* check for Observe option RFC7641 and RFC8132 */
3863 if (resource->observable &&
3864 (pdu->code == COAP_REQUEST_CODE_GET ||
3865 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3866 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3867 }
3868
3869 /*
3870 * See if blocks need to be aggregated or next requests sent off
3871 * before invoking application request handler
3872 */
3873 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3874 uint32_t block_mode = session->block_mode;
3875
3876 if (observe ||
3879 if (coap_handle_request_put_block(context, session, pdu, response,
3880 resource, uri_path, observe,
3881 &added_block, &free_lg_srcv)) {
3882 session->block_mode = block_mode;
3883 goto skip_handler;
3884 }
3885 session->block_mode = block_mode;
3886
3887 if (coap_handle_request_send_block(session, pdu, response, resource,
3888 query)) {
3889#if COAP_Q_BLOCK_SUPPORT
3890 lg_xmit_ctrl = 1;
3891#endif /* COAP_Q_BLOCK_SUPPORT */
3892 goto skip_handler;
3893 }
3894 }
3895
3896 if (observe) {
3897 observe_action =
3899 coap_opt_length(observe));
3900
3901 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3902 coap_subscription_t *subscription;
3903
3904 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3905 if (block.num != 0) {
3906 response->code = COAP_RESPONSE_CODE(400);
3907 goto skip_handler;
3908 }
3909#if COAP_Q_BLOCK_SUPPORT
3910 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3911 &block)) {
3912 if (block.num != 0) {
3913 response->code = COAP_RESPONSE_CODE(400);
3914 goto skip_handler;
3915 }
3916#endif /* COAP_Q_BLOCK_SUPPORT */
3917 }
3918 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3919 pdu);
3920 if (subscription) {
3921 uint8_t buf[4];
3922
3923 coap_touch_observer(context, session, &pdu->actual_token);
3925 coap_encode_var_safe(buf, sizeof(buf),
3926 resource->observe),
3927 buf);
3928 }
3929 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3930 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3931 } else {
3932 coap_log_info("observe: unexpected action %d\n", observe_action);
3933 }
3934 }
3935
3936 if ((resource == context->proxy_uri_resource ||
3937 (resource == context->unknown_resource &&
3938 context->unknown_resource->is_reverse_proxy)) &&
3939 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3940 pdu->type == COAP_MESSAGE_CON &&
3941 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
3942 /* Make the proxy response separate and fix response later */
3943 send_early_empty_ack = 1;
3944 }
3945 if (send_early_empty_ack) {
3946 coap_send_ack_lkd(session, pdu);
3947 if (pdu->mid == session->last_con_mid) {
3948 /* request has already been processed - do not process it again */
3949 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3950 pdu->mid);
3951 goto drop_it_no_debug;
3952 }
3953 session->last_con_mid = pdu->mid;
3954 }
3955#if COAP_WITH_OBSERVE_PERSIST
3956 /* If we are maintaining Observe persist */
3957 if (resource == context->unknown_resource) {
3958 context->unknown_pdu = pdu;
3959 context->unknown_session = session;
3960 } else
3961 context->unknown_pdu = NULL;
3962#endif /* COAP_WITH_OBSERVE_PERSIST */
3963
3964 /*
3965 * Call the request handler with everything set up
3966 */
3967 if (resource == &resource_uri_wellknown) {
3968 /* Leave context locked */
3969 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3970 (int)resource->uri_path->length, (int)resource->uri_path->length,
3971 resource->uri_path->s);
3972 h(resource, session, pdu, query, response);
3973 } else {
3974 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3975 (int)resource->uri_path->length, (int)resource->uri_path->length,
3976 resource->uri_path->s);
3977 coap_lock_callback_release(h(resource, session, pdu, query, response),
3978 /* context is being freed off */
3979 goto finish);
3980 }
3981
3982 /* Check validity of response code */
3983 if (!coap_check_code_class(session, response)) {
3984 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
3985 COAP_RESPONSE_CLASS(response->code),
3986 response->code & 0x1f);
3987 goto drop_it_no_debug;
3988 }
3989
3990 /* Check if lg_xmit generated and update PDU code if so */
3991 coap_check_code_lg_xmit(session, pdu, response, resource, query);
3992
3993 if (free_lg_srcv) {
3994 /* Check to see if the server is doing a 4.01 + Echo response */
3995 if (response->code == COAP_RESPONSE_CODE(401) &&
3996 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3997 /* Need to keep lg_srcv around for client's response */
3998 } else {
3999 LL_DELETE(session->lg_srcv, free_lg_srcv);
4000 coap_block_delete_lg_srcv(session, free_lg_srcv);
4001 }
4002 }
4003 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
4004 /* Just in case, as there are more to go */
4005 response->code = COAP_RESPONSE_CODE(231);
4006 }
4007
4008skip_handler:
4009 if (send_early_empty_ack &&
4010 response->type == COAP_MESSAGE_ACK) {
4011 /* Response is now separate - convert to CON as needed */
4012 response->type = COAP_MESSAGE_CON;
4013 /* Check for empty ACK - need to drop as already sent */
4014 if (response->code == 0) {
4015 goto drop_it_no_debug;
4016 }
4017 }
4018 respond = no_response(pdu, response, session, resource);
4019 if (respond != RESPONSE_DROP) {
4020#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
4021 coap_mid_t mid = pdu->mid;
4022#endif
4023 if (COAP_RESPONSE_CLASS(response->code) != 2) {
4024 if (observe) {
4026 }
4027 }
4028 if (COAP_RESPONSE_CLASS(response->code) > 2) {
4029 if (observe)
4030 coap_delete_observer(resource, session, &pdu->actual_token);
4031 if (response->code != COAP_RESPONSE_CODE(413))
4033 }
4034
4035 /* If original request contained a token, and the registered
4036 * application handler made no changes to the response, then
4037 * this is an empty ACK with a token, which is a malformed
4038 * PDU */
4039 if ((response->type == COAP_MESSAGE_ACK)
4040 && (response->code == 0)) {
4041 /* Remove token from otherwise-empty acknowledgment PDU */
4042 response->actual_token.length = 0;
4043 response->e_token_length = 0;
4044 response->used_size = 0;
4045 response->data = NULL;
4046 }
4047
4048 if (!coap_is_mcast(&session->addr_info.local) ||
4049 (context->mcast_per_resource &&
4050 resource &&
4052 /* No delays to response */
4053#if COAP_Q_BLOCK_SUPPORT
4054 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4055 !lg_xmit_ctrl && COAP_RESPONSE_CLASS(response->code) == 2 &&
4056 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4057 block.m) {
4058 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4059 response,
4060 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4061 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4062 response = NULL;
4063 if (query)
4064 coap_delete_string(query);
4065 goto finish;
4066 }
4067#endif /* COAP_Q_BLOCK_SUPPORT */
4068 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4069 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4070 if (query)
4071 coap_delete_string(query);
4072 goto finish;
4073 }
4074 } else {
4075 /* Need to delay mcast response */
4076 coap_queue_t *node = coap_new_node();
4077 uint8_t r;
4078 coap_tick_t delay;
4079
4080 if (!node) {
4081 coap_log_debug("mcast delay: insufficient memory\n");
4082 goto drop_it_no_debug;
4083 }
4084 if (!coap_pdu_encode_header(response, session->proto)) {
4086 goto drop_it_no_debug;
4087 }
4088
4089 node->id = response->mid;
4090 node->pdu = response;
4091 node->is_mcast = 1;
4092 coap_prng_lkd(&r, sizeof(r));
4093 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4094 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4095 coap_session_str(session),
4096 response->mid,
4097 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4098 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4099 1000 / COAP_TICKS_PER_SECOND));
4100 node->timeout = (unsigned int)delay;
4101 /* Use this to delay transmission */
4102 coap_wait_ack(session->context, session, node);
4103 }
4104 } else {
4105 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4106 coap_session_str(session),
4107 response->mid);
4108 coap_show_pdu(COAP_LOG_DEBUG, response);
4109drop_it_no_debug:
4110 coap_delete_pdu_lkd(response);
4111 }
4112 if (query)
4113 coap_delete_string(query);
4114#if COAP_Q_BLOCK_SUPPORT
4115 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4116 if (COAP_PROTO_RELIABLE(session->proto)) {
4117 if (block.m) {
4118 /* All of the sequence not in yet */
4119 goto finish;
4120 }
4121 } else if (pdu->type == COAP_MESSAGE_NON) {
4122 /* More to go and not at a payload break */
4123 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4124 goto finish;
4125 }
4126 }
4127 }
4128#endif /* COAP_Q_BLOCK_SUPPORT */
4129
4130finish:
4131 if (resource)
4132 coap_resource_release_lkd(resource);
4133 coap_delete_string(uri_path);
4134 return;
4135
4136fail_response:
4137 coap_delete_pdu_lkd(response);
4138 response =
4140 &opt_filter);
4141 if (response)
4142 goto skip_handler;
4143 if (resource)
4144 coap_resource_release_lkd(resource);
4145 coap_delete_string(uri_path);
4146}
4147#endif /* COAP_SERVER_SUPPORT */
4148
4149#if COAP_CLIENT_SUPPORT
4150/* Call application-specific response handler when available. */
4151void
4153 coap_pdu_t *sent, coap_pdu_t *rcvd,
4154 void *body_data) {
4155 coap_context_t *context = session->context;
4156 coap_response_t ret;
4157
4158#if COAP_PROXY_SUPPORT
4159 if (context->proxy_response_handler) {
4160 coap_proxy_list_t *proxy_entry;
4161 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4162 rcvd,
4163 &proxy_entry);
4164
4165 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4166 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4167 proxy_entry);
4168 return;
4169 }
4170 }
4171#endif /* COAP_PROXY_SUPPORT */
4172 if (session->doing_send_recv && session->req_token &&
4173 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4174 /* processing coap_send_recv() call */
4175 session->resp_pdu = rcvd;
4177 /* Will get freed off when PDU is freed off */
4178 rcvd->data_free = body_data;
4179 coap_send_ack_lkd(session, rcvd);
4181 return;
4182 } else if (context->response_handler) {
4184 context->response_handler(session,
4185 sent,
4186 rcvd,
4187 rcvd->mid),
4188 /* context is being freed off */
4189 return);
4190 } else {
4191 ret = COAP_RESPONSE_OK;
4192 }
4193 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4194 coap_send_rst_lkd(session, rcvd);
4196 } else {
4197 coap_send_ack_lkd(session, rcvd);
4199 }
4200 coap_free_type(COAP_STRING, body_data);
4201}
4202
4203static void
4204handle_response(coap_context_t *context, coap_session_t *session,
4205 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4206
4207 /* Set in case there is a later call to coap_update_token() */
4208 rcvd->session = session;
4209
4210 /* Check for message duplication */
4211 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4212 if (rcvd->type == COAP_MESSAGE_CON) {
4213 if (rcvd->mid == session->last_con_mid) {
4214 /* Duplicate response: send ACK/RST, but don't process */
4215 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4216 coap_send_ack_lkd(session, rcvd);
4217 else
4218 coap_send_rst_lkd(session, rcvd);
4219 return;
4220 }
4221 session->last_con_mid = rcvd->mid;
4222 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4223 if (rcvd->mid == session->last_ack_mid) {
4224 /* Duplicate response */
4225 return;
4226 }
4227 session->last_ack_mid = rcvd->mid;
4228 }
4229 }
4230 /* Check to see if checking out extended token support */
4231 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4232 session->last_token) {
4233 coap_lg_crcv_t *lg_crcv;
4234
4235 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4236 rcvd->actual_token.length != session->max_token_size ||
4237 rcvd->code == COAP_RESPONSE_CODE(400) ||
4238 rcvd->code == COAP_RESPONSE_CODE(503)) {
4239 coap_log_debug("Extended Token requested size support not available\n");
4241 } else {
4242 coap_log_debug("Extended Token support available\n");
4243 }
4245 /* Need to remove lg_crcv set up for this test */
4246 lg_crcv = coap_find_lg_crcv(session, rcvd);
4247 if (lg_crcv) {
4248 LL_DELETE(session->lg_crcv, lg_crcv);
4249 coap_block_delete_lg_crcv(session, lg_crcv);
4250 }
4251 coap_send_ack_lkd(session, rcvd);
4252 session->doing_first = 0;
4253 return;
4254 }
4255#if COAP_Q_BLOCK_SUPPORT
4256 /* Check to see if checking out Q-Block support */
4257 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
4258 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4259 coap_log_debug("Q-Block support not available\n");
4260 set_block_mode_drop_q(session->block_mode);
4261 } else {
4262 coap_block_b_t qblock;
4263
4264 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4265 coap_log_debug("Q-Block support available\n");
4266 set_block_mode_has_q(session->block_mode);
4267 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4268 /* Flush out any entries on session->delayqueue */
4269 coap_session_connected(session);
4270 } else {
4271 coap_log_debug("Q-Block support not available\n");
4272 set_block_mode_drop_q(session->block_mode);
4273 }
4274 }
4275 session->doing_first = 0;
4276 if (rcvd->type == COAP_MESSAGE_CON)
4277 coap_send_ack_lkd(session, rcvd);
4278 return;
4279 }
4280#endif /* COAP_Q_BLOCK_SUPPORT */
4281
4282 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4283 /* See if need to send next block to server */
4284 if (coap_handle_response_send_block(session, sent, rcvd)) {
4285 /* Next block transmitted, no need to inform app */
4286 coap_send_ack_lkd(session, rcvd);
4287 return;
4288 }
4289
4290 /* Need to see if needing to request next block */
4291 if (coap_handle_response_get_block(context, session, sent, rcvd,
4292 COAP_RECURSE_OK)) {
4293 /* Next block transmitted, ack sent no need to inform app */
4294 return;
4295 }
4296 }
4297 if (session->doing_first)
4298 session->doing_first = 0;
4299
4300 /* Call application-specific response handler when available. */
4301 coap_call_response_handler(session, sent, rcvd, NULL);
4302}
4303#endif /* COAP_CLIENT_SUPPORT */
4304
4305#if !COAP_DISABLE_TCP
4306static void
4308 coap_pdu_t *pdu) {
4309 coap_opt_iterator_t opt_iter;
4310 coap_opt_t *option;
4311 int set_mtu = 0;
4312
4313 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4314
4315 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4316 if (session->csm_not_seen) {
4317 coap_tick_t now;
4318
4319 coap_ticks(&now);
4320 /* CSM timeout before CSM seen */
4321 coap_log_warn("***%s: CSM received after CSM timeout\n",
4322 coap_session_str(session));
4323 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4324 coap_session_str(session),
4325 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4326 }
4327 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4329 }
4330 while ((option = coap_option_next(&opt_iter))) {
4332 unsigned max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4333
4334 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4335 max_recv = COAP_DEFAULT_MAX_PDU_RX_SIZE;
4336 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4337 coap_session_str(session), max_recv);
4338 }
4339 coap_session_set_mtu(session, max_recv);
4340 set_mtu = 1;
4341 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4342 session->csm_block_supported = 1;
4343 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4344 session->max_token_size =
4346 coap_opt_length(option));
4349 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4352 }
4353 }
4354 if (set_mtu) {
4355 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4356 session->csm_bert_rem_support = 1;
4357 else
4358 session->csm_bert_rem_support = 0;
4359 }
4360 if (session->state == COAP_SESSION_STATE_CSM)
4361 coap_session_connected(session);
4362 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4364 if (context->ping_handler) {
4365 coap_lock_callback(context->ping_handler(session, pdu, pdu->mid));
4366 }
4367 if (pong) {
4369 coap_send_internal(session, pong, NULL);
4370 }
4371 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4372 session->last_pong = session->last_rx_tx;
4373 if (context->pong_handler) {
4374 coap_lock_callback(context->pong_handler(session, pdu, pdu->mid));
4375 }
4376 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4377 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4379 }
4380}
4381#endif /* !COAP_DISABLE_TCP */
4382
4383static int
4385 if (COAP_PDU_IS_REQUEST(pdu) &&
4386 pdu->actual_token.length >
4387 (session->type == COAP_SESSION_TYPE_CLIENT ?
4388 session->max_token_size : session->context->max_token_size)) {
4389 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4390 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4391 coap_opt_filter_t opt_filter;
4392 coap_pdu_t *response;
4393
4394 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4395 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4396 &opt_filter);
4397 if (!response) {
4398 coap_log_warn("coap_dispatch: cannot create error response\n");
4399 } else {
4400 /*
4401 * Note - have to leave in oversize token as per
4402 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4403 */
4404 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4405 coap_log_warn("coap_dispatch: error sending response\n");
4406 }
4407 } else {
4408 /* Indicate no extended token support */
4409 coap_send_rst_lkd(session, pdu);
4410 }
4411 return 0;
4412 }
4413 return 1;
4414}
4415
4416void
4418 coap_pdu_t *pdu) {
4419 coap_queue_t *sent = NULL;
4420 coap_pdu_t *response;
4421 coap_pdu_t *orig_pdu = NULL;
4422 coap_opt_filter_t opt_filter;
4423 int is_ping_rst;
4424 int packet_is_bad = 0;
4425#if COAP_OSCORE_SUPPORT
4426 coap_opt_iterator_t opt_iter;
4427 coap_pdu_t *dec_pdu = NULL;
4428#endif /* COAP_OSCORE_SUPPORT */
4429 int is_ext_token_rst;
4430 int oscore_invalid = 0;
4431
4432 pdu->session = session;
4434
4435 /* Check validity of received code */
4436 if (!coap_check_code_class(session, pdu)) {
4437 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4439 pdu->code & 0x1f);
4440 packet_is_bad = 1;
4441 if (pdu->type == COAP_MESSAGE_CON) {
4443 }
4444 /* find message id in sendqueue to stop retransmission */
4445 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4446 goto cleanup;
4447 }
4448
4449 coap_option_filter_clear(&opt_filter);
4450
4451#if COAP_SERVER_SUPPORT
4452 /* See if this a repeat request */
4453 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4455 coap_digest_t digest;
4456
4457 coap_pdu_cksum(pdu, &digest);
4458 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4459#if COAP_OSCORE_SUPPORT
4460 uint8_t oscore_encryption = session->oscore_encryption;
4461
4462 session->oscore_encryption = 0;
4463#endif /* COAP_OSCORE_SUPPORT */
4464 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4465 cached_pdu must not be removed */
4467 coap_log_debug("Retransmit response to duplicate request\n");
4468 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4469#if COAP_OSCORE_SUPPORT
4470 session->oscore_encryption = oscore_encryption;
4471#endif /* COAP_OSCORE_SUPPORT */
4472 return;
4473 }
4474#if COAP_OSCORE_SUPPORT
4475 session->oscore_encryption = oscore_encryption;
4476#endif /* COAP_OSCORE_SUPPORT */
4477 }
4478 }
4479#endif /* COAP_SERVER_SUPPORT */
4480 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4481 if (!check_token_size(session, pdu)) {
4482 goto cleanup;
4483 }
4484 }
4485#if COAP_OSCORE_SUPPORT
4486 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4487 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4488 if (pdu->type == COAP_MESSAGE_NON) {
4489 coap_send_rst_lkd(session, pdu);
4490 goto cleanup;
4491 } else if (pdu->type == COAP_MESSAGE_CON) {
4492 if (COAP_PDU_IS_REQUEST(pdu)) {
4493 response =
4494 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4495
4496 if (!response) {
4497 coap_log_warn("coap_dispatch: cannot create error response\n");
4498 } else {
4499 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4500 coap_log_warn("coap_dispatch: error sending response\n");
4501 }
4502 } else {
4503 coap_send_rst_lkd(session, pdu);
4504 }
4505 }
4506 goto cleanup;
4507 }
4508
4509 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4510 int decrypt = 1;
4511#if COAP_SERVER_SUPPORT
4512 coap_opt_t *opt;
4513 coap_resource_t *resource;
4514 coap_uri_t uri;
4515#endif /* COAP_SERVER_SUPPORT */
4516
4517 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4518 decrypt = 0;
4519
4520#if COAP_SERVER_SUPPORT
4521 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4522 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4523 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4524 != NULL) {
4525 /* Need to check whether this is a direct or proxy session */
4526 memset(&uri, 0, sizeof(uri));
4527 uri.host.length = coap_opt_length(opt);
4528 uri.host.s = coap_opt_value(opt);
4529 resource = context->proxy_uri_resource;
4530 if (uri.host.length && resource && resource->proxy_name_count &&
4531 resource->proxy_name_list) {
4532 size_t i;
4533 for (i = 0; i < resource->proxy_name_count; i++) {
4534 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4535 break;
4536 }
4537 }
4538 if (i == resource->proxy_name_count) {
4539 /* This server is not hosting the proxy connection endpoint */
4540 decrypt = 0;
4541 }
4542 }
4543 }
4544#endif /* COAP_SERVER_SUPPORT */
4545 if (decrypt) {
4546 /* find message id in sendqueue to stop retransmission and get sent */
4547 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4548 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4549 orig_pdu = pdu;
4550 coap_pdu_reference_lkd(orig_pdu);
4551 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4552 if (session->recipient_ctx == NULL ||
4553 session->recipient_ctx->initial_state == 0) {
4554 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4555 }
4557 coap_delete_pdu_lkd(orig_pdu);
4558 return;
4559 } else {
4560 session->oscore_encryption = 1;
4561 pdu = dec_pdu;
4562 }
4563 coap_log_debug("Decrypted PDU\n");
4565 }
4566 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4567 session->oscore_encryption &&
4568 pdu->type != COAP_MESSAGE_RST) {
4569 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4570 /* Violates RFC 8613 2 */
4571 coap_log_err("received an invalid response to the OSCORE request\n");
4572 oscore_invalid = 1;
4573 }
4574 }
4575#endif /* COAP_OSCORE_SUPPORT */
4576
4577 switch (pdu->type) {
4578 case COAP_MESSAGE_ACK:
4579 /* find message id in sendqueue to stop retransmission */
4580 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4581
4582 if (sent && session->con_active) {
4583 session->con_active--;
4584 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4585 /* Flush out any entries on session->delayqueue */
4586 coap_session_connected(session);
4587 }
4588 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4589 packet_is_bad = 1;
4590 goto cleanup;
4591 }
4592
4593#if COAP_SERVER_SUPPORT
4594 /* if sent code was >= 64 the message might have been a
4595 * notification. Then, we must flag the observer to be alive
4596 * by setting obs->fail_cnt = 0. */
4597 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4598 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4599 }
4600#endif /* COAP_SERVER_SUPPORT */
4601
4602#if COAP_Q_BLOCK_SUPPORT
4603 if (session->lg_xmit && sent && sent->pdu && sent->pdu->type == COAP_MESSAGE_CON &&
4604 !(session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK)) {
4605 int doing_q_block = 0;
4606 coap_lg_xmit_t *lg_xmit = NULL;
4607
4608 LL_FOREACH(session->lg_xmit, lg_xmit) {
4609 if ((lg_xmit->option == COAP_OPTION_Q_BLOCK1 || lg_xmit->option == COAP_OPTION_Q_BLOCK2) &&
4610 lg_xmit->last_all_sent == 0 && lg_xmit->sent_pdu->type != COAP_MESSAGE_NON) {
4611 doing_q_block = 1;
4612 break;
4613 }
4614 }
4615 if (doing_q_block && lg_xmit) {
4616 coap_block_b_t block;
4617
4618 memset(&block, 0, sizeof(block));
4619 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
4620 block.num = lg_xmit->last_block + lg_xmit->b.b1.count;
4621 } else {
4622 block.num = lg_xmit->last_block;
4623 }
4624 block.m = 1;
4625 block.szx = block.aszx = lg_xmit->blk_size;
4626 block.defined = 1;
4627 block.bert = 0;
4628 block.chunk_size = 1024;
4629
4630 coap_send_q_blocks(session, lg_xmit, block,
4631 lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
4632 }
4633 }
4634#endif /* COAP_Q_BLOCK_SUPPORT */
4635 if (pdu->code == 0) {
4636#if COAP_CLIENT_SUPPORT
4637 /*
4638 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4639 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4640 * response if the response was piggy-backed. Here, a separate response
4641 * detected and so the lg_crcv needs to be set up before the sent PDU
4642 * information is lost.
4643 *
4644 * lg_crcv was not set up if not a CoAP request.
4645 *
4646 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4647 * options.
4648 */
4649 if (sent &&
4650 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4651 COAP_PDU_IS_REQUEST(sent->pdu)) {
4652 /*
4653 * lg_crcv was not set up in coap_send(). It could have been set up
4654 * the first separate response.
4655 * See if there already is a lg_crcv set up.
4656 */
4657 coap_lg_crcv_t *lg_crcv;
4658 uint64_t token_match =
4660 sent->pdu->actual_token.length));
4661
4662 LL_FOREACH(session->lg_crcv, lg_crcv) {
4663 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4664 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4665 break;
4666 }
4667 }
4668 if (!lg_crcv) {
4669 /*
4670 * Need to set up a lg_crcv as it was not set up in coap_send()
4671 * to save time, but server has not sent back a piggy-back response.
4672 */
4673 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4674 if (lg_crcv) {
4675 LL_PREPEND(session->lg_crcv, lg_crcv);
4676 }
4677 }
4678 }
4679#endif /* COAP_CLIENT_SUPPORT */
4680 /* an empty ACK needs no further handling */
4681 goto cleanup;
4682 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4683 /* This is not legitimate - Request using ACK - ignore */
4684 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4686 pdu->code & 0x1f);
4687 packet_is_bad = 1;
4688 goto cleanup;
4689 }
4690
4691 break;
4692
4693 case COAP_MESSAGE_RST:
4694 /* We have sent something the receiver disliked, so we remove
4695 * not only the message id but also the subscriptions we might
4696 * have. */
4697 is_ping_rst = 0;
4698 if (pdu->mid == session->last_ping_mid &&
4699 session->last_ping > 0)
4700 is_ping_rst = 1;
4701
4702#if COAP_Q_BLOCK_SUPPORT
4703 /* Check to see if checking out Q-Block support */
4704 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4705 session->remote_test_mid == pdu->mid) {
4706 coap_log_debug("Q-Block support not available\n");
4707 set_block_mode_drop_q(session->block_mode);
4708 }
4709#endif /* COAP_Q_BLOCK_SUPPORT */
4710
4711 /* Check to see if checking out extended token support */
4712 is_ext_token_rst = 0;
4713 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4714 session->remote_test_mid == pdu->mid) {
4715 coap_log_debug("Extended Token support not available\n");
4718 session->doing_first = 0;
4719 is_ext_token_rst = 1;
4720 }
4721
4722 if (!is_ping_rst && !is_ext_token_rst)
4723 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4724
4725 if (session->con_active) {
4726 session->con_active--;
4727 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4728 /* Flush out any entries on session->delayqueue */
4729 coap_session_connected(session);
4730 }
4731
4732 /* find message id in sendqueue to stop retransmission */
4733 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4734
4735 if (sent) {
4736 if (!is_ping_rst)
4737 coap_cancel(context, sent);
4738
4739 if (!is_ping_rst && !is_ext_token_rst) {
4740 if (sent->pdu->type==COAP_MESSAGE_CON) {
4741 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4742 }
4743 } else if (is_ping_rst) {
4744 if (context->pong_handler) {
4745 coap_lock_callback(context->pong_handler(session, pdu, pdu->mid));
4746 }
4747 session->last_pong = session->last_rx_tx;
4749 }
4750 } else {
4751#if COAP_SERVER_SUPPORT
4752 /* Need to check is there is a subscription active and delete it */
4753 RESOURCES_ITER(context->resources, r) {
4754 coap_subscription_t *obs, *tmp;
4755 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4756 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4757 /* Need to do this now as session may get de-referenced */
4759 coap_delete_observer(r, session, &obs->pdu->actual_token);
4760 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4761 coap_session_release_lkd(session);
4762 goto cleanup;
4763 }
4764 }
4765 }
4766#endif /* COAP_SERVER_SUPPORT */
4767 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4768 }
4769#if COAP_PROXY_SUPPORT
4770 if (!is_ping_rst) {
4771 /* Need to check is there is a proxy subscription active and delete it */
4772 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
4773 }
4774#endif /* COAP_PROXY_SUPPORT */
4775 goto cleanup;
4776
4777 case COAP_MESSAGE_NON:
4778 /* check for oscore issue or unknown critical options */
4779 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4780 packet_is_bad = 1;
4781 coap_send_rst_lkd(session, pdu);
4782 goto cleanup;
4783 }
4784 break;
4785
4786 case COAP_MESSAGE_CON:
4787 /* In a lossy context, the ACK of a separate response may have
4788 * been lost, so we need to stop retransmitting requests with the
4789 * same token. Matching on token potentially containing ext length bytes.
4790 */
4791 /* find message token in sendqueue to stop retransmission */
4792 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4793
4794 /* check for oscore issue or unknown critical options in non-signaling messages */
4795 if (oscore_invalid ||
4796 (!COAP_PDU_IS_SIGNALING(pdu) && coap_option_check_critical(session, pdu, &opt_filter) == 0)) {
4797 packet_is_bad = 1;
4798 if (COAP_PDU_IS_REQUEST(pdu)) {
4799 response =
4800 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4801
4802 if (!response) {
4803 coap_log_warn("coap_dispatch: cannot create error response\n");
4804 } else {
4805 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4806 coap_log_warn("coap_dispatch: error sending response\n");
4807 }
4808 } else {
4809 coap_send_rst_lkd(session, pdu);
4810 }
4811 goto cleanup;
4812 }
4813 break;
4814 default:
4815 break;
4816 }
4817
4818 /* Pass message to upper layer if a specific handler was
4819 * registered for a request that should be handled locally. */
4820#if !COAP_DISABLE_TCP
4821 if (COAP_PDU_IS_SIGNALING(pdu))
4822 handle_signaling(context, session, pdu);
4823 else
4824#endif /* !COAP_DISABLE_TCP */
4825#if COAP_SERVER_SUPPORT
4826 if (COAP_PDU_IS_REQUEST(pdu))
4827 handle_request(context, session, pdu, orig_pdu);
4828 else
4829#endif /* COAP_SERVER_SUPPORT */
4830#if COAP_CLIENT_SUPPORT
4831 if (COAP_PDU_IS_RESPONSE(pdu))
4832 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4833 else
4834#endif /* COAP_CLIENT_SUPPORT */
4835 {
4836 if (COAP_PDU_IS_EMPTY(pdu)) {
4837 if (context->ping_handler) {
4838 coap_lock_callback(context->ping_handler(session, pdu, pdu->mid));
4839 }
4840 } else {
4841 packet_is_bad = 1;
4842 }
4843 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4845 pdu->code & 0x1f);
4846
4847 if (!coap_is_mcast(&session->addr_info.local)) {
4848 if (COAP_PDU_IS_EMPTY(pdu)) {
4849 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4850 coap_tick_t now;
4851 coap_ticks(&now);
4852 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4854 session->last_tx_rst = now;
4855 }
4856 }
4857 } else {
4858 if (pdu->type == COAP_MESSAGE_CON)
4860 }
4861 }
4862 }
4863
4864cleanup:
4865 if (packet_is_bad) {
4866 if (sent) {
4867 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
4868 } else {
4870 }
4871 }
4872 coap_delete_pdu_lkd(orig_pdu);
4874#if COAP_OSCORE_SUPPORT
4875 coap_delete_pdu_lkd(dec_pdu);
4876#endif /* COAP_OSCORE_SUPPORT */
4877}
4878
4879#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4880static const char *
4882 switch (event) {
4884 return "COAP_EVENT_DTLS_CLOSED";
4886 return "COAP_EVENT_DTLS_CONNECTED";
4888 return "COAP_EVENT_DTLS_RENEGOTIATE";
4890 return "COAP_EVENT_DTLS_ERROR";
4892 return "COAP_EVENT_TCP_CONNECTED";
4894 return "COAP_EVENT_TCP_CLOSED";
4896 return "COAP_EVENT_TCP_FAILED";
4898 return "COAP_EVENT_SESSION_CONNECTED";
4900 return "COAP_EVENT_SESSION_CLOSED";
4902 return "COAP_EVENT_SESSION_FAILED";
4904 return "COAP_EVENT_PARTIAL_BLOCK";
4906 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4908 return "COAP_EVENT_SERVER_SESSION_NEW";
4910 return "COAP_EVENT_SERVER_SESSION_DEL";
4912 return "COAP_EVENT_SERVER_SESSION_CONNECTED";
4914 return "COAP_EVENT_BAD_PACKET";
4916 return "COAP_EVENT_MSG_RETRANSMITTED";
4918 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4920 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4922 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4924 return "COAP_EVENT_OSCORE_NO_SECURITY";
4926 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4928 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4930 return "COAP_EVENT_WS_PACKET_SIZE";
4932 return "COAP_EVENT_WS_CONNECTED";
4934 return "COAP_EVENT_WS_CLOSED";
4936 return "COAP_EVENT_KEEPALIVE_FAILURE";
4938 return "COAP_EVENT_RECONNECT_FAILED";
4940 return "COAP_EVENT_RECONNECT_SUCCESS";
4942 return "COAP_EVENT_RECONNECT_NO_MORE";
4944 return "COAP_EVENT_RECONNECT_STARTED";
4945 default:
4946 return "???";
4947 }
4948}
4949#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4950
4951COAP_API int
4953 coap_session_t *session) {
4954 int ret;
4955
4956 coap_lock_lock(return 0);
4957 ret = coap_handle_event_lkd(context, event, session);
4959 return ret;
4960}
4961
4962int
4964 coap_session_t *session) {
4965 int ret = 0;
4966
4967 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
4968
4969 if (context->handle_event) {
4970 coap_lock_callback_ret(ret, context->handle_event(session, event));
4971#if COAP_PROXY_SUPPORT
4972 if (event == COAP_EVENT_SERVER_SESSION_DEL)
4973 coap_proxy_remove_association(session, 0);
4974#endif /* COAP_PROXY_SUPPORT */
4975#if COAP_CLIENT_SUPPORT
4976 switch (event) {
4990 /* Those that are deemed fatal to end sending a request */
4991 session->doing_send_recv = 0;
4992 break;
4994 /* Session will now be available as well - for call-home */
4995 if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
4997 session);
4998 }
4999 break;
5005 break;
5007 /* Session will now be available as well - for call-home if not (D)TLS */
5008 if (session->type == COAP_SESSION_TYPE_SERVER &&
5009 (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
5011 session);
5012 }
5013 break;
5017 break;
5019 /* Session will now be available as well - for call-home if not (D)TLS */
5020 if (session->proto == COAP_PROTO_UDP) {
5022 session);
5023 }
5024 break;
5032 default:
5033 break;
5034 }
5035#endif /* COAP_CLIENT_SUPPORT */
5036 }
5037 return ret;
5038}
5039
5040COAP_API int
5042 int ret;
5043
5044 coap_lock_lock(return 0);
5045 ret = coap_can_exit_lkd(context);
5047 return ret;
5048}
5049
5050int
5052 coap_session_t *s, *rtmp;
5053 if (!context)
5054 return 1;
5056 if (context->sendqueue)
5057 return 0;
5058#if COAP_SERVER_SUPPORT
5059 coap_endpoint_t *ep;
5060
5061 LL_FOREACH(context->endpoint, ep) {
5062 SESSIONS_ITER(ep->sessions, s, rtmp) {
5063 if (s->delayqueue)
5064 return 0;
5065 if (s->lg_xmit)
5066 return 0;
5067 }
5068 }
5069#endif /* COAP_SERVER_SUPPORT */
5070#if COAP_CLIENT_SUPPORT
5071 SESSIONS_ITER(context->sessions, s, rtmp) {
5072 if (s->delayqueue)
5073 return 0;
5074 if (s->lg_xmit)
5075 return 0;
5076 }
5077#endif /* COAP_CLIENT_SUPPORT */
5078 return 1;
5079}
5080#if COAP_SERVER_SUPPORT
5081#if COAP_ASYNC_SUPPORT
5082/*
5083 * Return 1 if there is a future expire time, else 0.
5084 * Update tim_rem with remaining value if return is 1.
5085 */
5086int
5087coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5089 coap_async_t *async, *tmp;
5090 int ret = 0;
5091
5092 if (context->async_state_traversing)
5093 return 0;
5094 context->async_state_traversing = 1;
5095 LL_FOREACH_SAFE(context->async_state, async, tmp) {
5096 if (async->delay != 0) {
5097 if (async->delay <= now) {
5098 /* Send off the request to the application */
5099 coap_log_debug("Async PDU presented to app.\n");
5100 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5101 handle_request(context, async->session, async->pdu, NULL);
5102
5103 /* Remove this async entry as it has now fired */
5104 coap_free_async_lkd(async->session, async);
5105 } else {
5106 next_due = async->delay - now;
5107 ret = 1;
5108 }
5109 }
5110 }
5111 if (tim_rem)
5112 *tim_rem = next_due;
5113 context->async_state_traversing = 0;
5114 return ret;
5115}
5116#endif /* COAP_ASYNC_SUPPORT */
5117#endif /* COAP_SERVER_SUPPORT */
5118
5120uint8_t coap_unique_id[8] = { 0 };
5121
5122#if COAP_THREAD_SAFE
5123/*
5124 * Global lock for multi-thread support
5125 */
5126coap_lock_t global_lock;
5127/*
5128 * low level protection mutex
5129 */
5130coap_mutex_t m_show_pdu;
5131coap_mutex_t m_log_impl;
5132coap_mutex_t m_io_threads;
5133#endif /* COAP_THREAD_SAFE */
5134
5135void
5137 coap_tick_t now;
5138#ifndef WITH_CONTIKI
5139 uint64_t us;
5140#endif /* !WITH_CONTIKI */
5141
5142 if (coap_started)
5143 return;
5144 coap_started = 1;
5145
5146#if COAP_THREAD_SAFE
5148 coap_mutex_init(&m_show_pdu);
5149 coap_mutex_init(&m_log_impl);
5150 coap_mutex_init(&m_io_threads);
5151#endif /* COAP_THREAD_SAFE */
5152
5153#if defined(HAVE_WINSOCK2_H)
5154 WORD wVersionRequested = MAKEWORD(2, 2);
5155 WSADATA wsaData;
5156 WSAStartup(wVersionRequested, &wsaData);
5157#endif
5159 coap_ticks(&now);
5160#ifndef WITH_CONTIKI
5161 us = coap_ticks_to_rt_us(now);
5162 /* Be accurate to the nearest (approx) us */
5163 coap_prng_init_lkd((unsigned int)us);
5164#else /* WITH_CONTIKI */
5165 coap_start_io_process();
5166#endif /* WITH_CONTIKI */
5169#ifdef WITH_LWIP
5170 coap_io_lwip_init();
5171#endif /* WITH_LWIP */
5172#if COAP_SERVER_SUPPORT
5173 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5174 (const uint8_t *)".well-known/core"
5175 };
5176 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5177 resource_uri_wellknown.ref = 1;
5178 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5179 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5180 resource_uri_wellknown.uri_path = &well_known;
5181#endif /* COAP_SERVER_SUPPORT */
5184}
5185
5186void
5188 if (!coap_started)
5189 return;
5190 coap_started = 0;
5191#if defined(HAVE_WINSOCK2_H)
5192 WSACleanup();
5193#elif defined(WITH_CONTIKI)
5194 coap_stop_io_process();
5195#endif
5196#ifdef WITH_LWIP
5197 coap_io_lwip_cleanup();
5198#endif /* WITH_LWIP */
5200
5201#if COAP_THREAD_SAFE
5202 coap_mutex_destroy(&m_show_pdu);
5203 coap_mutex_destroy(&m_log_impl);
5204 coap_mutex_destroy(&m_io_threads);
5205#endif /* COAP_THREAD_SAFE */
5206
5208}
5209
5210void
5212 coap_response_handler_t handler) {
5213#if COAP_CLIENT_SUPPORT
5214 context->response_handler = handler;
5215#else /* ! COAP_CLIENT_SUPPORT */
5216 (void)context;
5217 (void)handler;
5218#endif /* ! COAP_CLIENT_SUPPORT */
5219}
5220
5221void
5224#if COAP_PROXY_SUPPORT
5225 context->proxy_response_handler = handler;
5226#else /* ! COAP_PROXY_SUPPORT */
5227 (void)context;
5228 (void)handler;
5229#endif /* ! COAP_PROXY_SUPPORT */
5230}
5231
5232void
5234 coap_nack_handler_t handler) {
5235 context->nack_handler = handler;
5236}
5237
5238void
5240 coap_ping_handler_t handler) {
5241 context->ping_handler = handler;
5242}
5243
5244void
5246 coap_pong_handler_t handler) {
5247 context->pong_handler = handler;
5248}
5249
5250void
5252 coap_resource_dynamic_create_t dyn_create_handler,
5253 uint32_t dynamic_max) {
5254 context->dyn_create_handler = dyn_create_handler;
5255 context->dynamic_max = dynamic_max;
5256 return;
5257}
5258
5259COAP_API void
5261 coap_lock_lock(return);
5262 coap_register_option_lkd(ctx, type);
5264}
5265
5266void
5269}
5270
5271#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5272#if COAP_SERVER_SUPPORT
5273COAP_API int
5274coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5275 const char *ifname) {
5276 int ret;
5277
5278 coap_lock_lock(return -1);
5279 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
5281 return ret;
5282}
5283
5284int
5285coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
5286 const char *ifname) {
5287#if COAP_IPV4_SUPPORT
5288 struct ip_mreq mreq4;
5289#endif /* COAP_IPV4_SUPPORT */
5290#if COAP_IPV6_SUPPORT
5291 struct ipv6_mreq mreq6;
5292#endif /* COAP_IPV6_SUPPORT */
5293 struct addrinfo *resmulti = NULL, hints, *ainfo;
5294 int result = -1;
5295 coap_endpoint_t *endpoint;
5296 int mgroup_setup = 0;
5297
5298 /* Need to have at least one endpoint! */
5299 assert(ctx->endpoint);
5300 if (!ctx->endpoint)
5301 return -1;
5302
5303 /* Default is let the kernel choose */
5304#if COAP_IPV6_SUPPORT
5305 mreq6.ipv6mr_interface = 0;
5306#endif /* COAP_IPV6_SUPPORT */
5307#if COAP_IPV4_SUPPORT
5308 mreq4.imr_interface.s_addr = INADDR_ANY;
5309#endif /* COAP_IPV4_SUPPORT */
5310
5311 memset(&hints, 0, sizeof(hints));
5312 hints.ai_socktype = SOCK_DGRAM;
5313
5314 /* resolve the multicast group address */
5315 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5316
5317 if (result != 0) {
5318 coap_log_err("coap_join_mcast_group_intf: %s: "
5319 "Cannot resolve multicast address: %s\n",
5320 group_name, gai_strerror(result));
5321 goto finish;
5322 }
5323
5324 /* Need to do a windows equivalent at some point */
5325#ifndef _WIN32
5326 if (ifname) {
5327 /* interface specified - check if we have correct IPv4/IPv6 information */
5328 int done_ip4 = 0;
5329 int done_ip6 = 0;
5330#if defined(ESPIDF_VERSION)
5331 struct netif *netif;
5332#else /* !ESPIDF_VERSION */
5333#if COAP_IPV4_SUPPORT
5334 int ip4fd;
5335#endif /* COAP_IPV4_SUPPORT */
5336 struct ifreq ifr;
5337#endif /* !ESPIDF_VERSION */
5338
5339 /* See which mcast address family types are being asked for */
5340 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5341 ainfo = ainfo->ai_next) {
5342 switch (ainfo->ai_family) {
5343#if COAP_IPV6_SUPPORT
5344 case AF_INET6:
5345 if (done_ip6)
5346 break;
5347 done_ip6 = 1;
5348#if defined(ESPIDF_VERSION)
5349 netif = netif_find(ifname);
5350 if (netif)
5351 mreq6.ipv6mr_interface = netif_get_index(netif);
5352 else
5353 coap_log_err("coap_join_mcast_group_intf: %s: "
5354 "Cannot get IPv4 address: %s\n",
5355 ifname, coap_socket_strerror());
5356#else /* !ESPIDF_VERSION */
5357 memset(&ifr, 0, sizeof(ifr));
5358 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5359 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5360
5361#ifdef HAVE_IF_NAMETOINDEX
5362 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5363 if (mreq6.ipv6mr_interface == 0) {
5364 coap_log_warn("coap_join_mcast_group_intf: "
5365 "cannot get interface index for '%s'\n",
5366 ifname);
5367 }
5368#elif defined(__QNXNTO__)
5369#else /* !HAVE_IF_NAMETOINDEX */
5370 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5371 if (result != 0) {
5372 coap_log_warn("coap_join_mcast_group_intf: "
5373 "cannot get interface index for '%s': %s\n",
5374 ifname, coap_socket_strerror());
5375 } else {
5376 /* Capture the IPv6 if_index for later */
5377 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5378 }
5379#endif /* !HAVE_IF_NAMETOINDEX */
5380#endif /* !ESPIDF_VERSION */
5381#endif /* COAP_IPV6_SUPPORT */
5382 break;
5383#if COAP_IPV4_SUPPORT
5384 case AF_INET:
5385 if (done_ip4)
5386 break;
5387 done_ip4 = 1;
5388#if defined(ESPIDF_VERSION)
5389 netif = netif_find(ifname);
5390 if (netif)
5391 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5392 else
5393 coap_log_err("coap_join_mcast_group_intf: %s: "
5394 "Cannot get IPv4 address: %s\n",
5395 ifname, coap_socket_strerror());
5396#else /* !ESPIDF_VERSION */
5397 /*
5398 * Need an AF_INET socket to do this unfortunately to stop
5399 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5400 */
5401 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5402 if (ip4fd == -1) {
5403 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5404 ifname, coap_socket_strerror());
5405 continue;
5406 }
5407 memset(&ifr, 0, sizeof(ifr));
5408 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5409 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5410 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5411 if (result != 0) {
5412 coap_log_err("coap_join_mcast_group_intf: %s: "
5413 "Cannot get IPv4 address: %s\n",
5414 ifname, coap_socket_strerror());
5415 } else {
5416 /* Capture the IPv4 address for later */
5417 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5418 }
5419 close(ip4fd);
5420#endif /* !ESPIDF_VERSION */
5421 break;
5422#endif /* COAP_IPV4_SUPPORT */
5423 default:
5424 break;
5425 }
5426 }
5427 }
5428#else /* _WIN32 */
5429 /*
5430 * On Windows this function ignores the ifname variable so we unset this
5431 * variable on this platform in any case in order to enable the interface
5432 * selection from the bind address below.
5433 */
5434 ifname = 0;
5435#endif /* _WIN32 */
5436
5437 /* Add in mcast address(es) to appropriate interface */
5438 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5439 LL_FOREACH(ctx->endpoint, endpoint) {
5440 /* Only UDP currently supported */
5441 if (endpoint->proto == COAP_PROTO_UDP) {
5442 coap_address_t gaddr;
5443
5444 coap_address_init(&gaddr);
5445#if COAP_IPV6_SUPPORT
5446 if (ainfo->ai_family == AF_INET6) {
5447 if (!ifname) {
5448 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5449 /*
5450 * Do it on the ifindex that the server is listening on
5451 * (sin6_scope_id could still be 0)
5452 */
5453 mreq6.ipv6mr_interface =
5454 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5455 } else {
5456 mreq6.ipv6mr_interface = 0;
5457 }
5458 }
5459 gaddr.addr.sin6.sin6_family = AF_INET6;
5460 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5461 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5462 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5463 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5464 (char *)&mreq6, sizeof(mreq6));
5465 }
5466#endif /* COAP_IPV6_SUPPORT */
5467#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5468 else
5469#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5470#if COAP_IPV4_SUPPORT
5471 if (ainfo->ai_family == AF_INET) {
5472 if (!ifname) {
5473 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5474 /*
5475 * Do it on the interface that the server is listening on
5476 * (sin_addr could still be INADDR_ANY)
5477 */
5478 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5479 } else {
5480 mreq4.imr_interface.s_addr = INADDR_ANY;
5481 }
5482 }
5483 gaddr.addr.sin.sin_family = AF_INET;
5484 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5485 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5486 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5487 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5488 (char *)&mreq4, sizeof(mreq4));
5489 }
5490#endif /* COAP_IPV4_SUPPORT */
5491 else {
5492 continue;
5493 }
5494
5495 if (result == COAP_SOCKET_ERROR) {
5496 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5497 group_name, coap_socket_strerror());
5498 } else {
5499 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5500
5501 addr_str[sizeof(addr_str)-1] = '\000';
5502 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5503 sizeof(addr_str) - 1)) {
5504 if (ifname)
5505 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5506 ifname);
5507 else
5508 coap_log_debug("added mcast group %s\n", addr_str);
5509 }
5510 mgroup_setup = 1;
5511 }
5512 }
5513 }
5514 }
5515 if (!mgroup_setup) {
5516 result = -1;
5517 }
5518
5519finish:
5520 freeaddrinfo(resmulti);
5521
5522 return result;
5523}
5524
5525void
5527 context->mcast_per_resource = 1;
5528}
5529
5530#endif /* ! COAP_SERVER_SUPPORT */
5531
5532#if COAP_CLIENT_SUPPORT
5533int
5534coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5535 if (session && coap_is_mcast(&session->addr_info.remote)) {
5536 switch (session->addr_info.remote.addr.sa.sa_family) {
5537#if COAP_IPV4_SUPPORT
5538 case AF_INET:
5539 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5540 (const char *)&hops, sizeof(hops)) < 0) {
5541 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5542 hops, coap_socket_strerror());
5543 return 0;
5544 }
5545 return 1;
5546#endif /* COAP_IPV4_SUPPORT */
5547#if COAP_IPV6_SUPPORT
5548 case AF_INET6:
5549 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5550 (const char *)&hops, sizeof(hops)) < 0) {
5551 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5552 hops, coap_socket_strerror());
5553 return 0;
5554 }
5555 return 1;
5556#endif /* COAP_IPV6_SUPPORT */
5557 default:
5558 break;
5559 }
5560 }
5561 return 0;
5562}
5563#endif /* COAP_CLIENT_SUPPORT */
5564
5565#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
5566COAP_API int
5568 const char *group_name COAP_UNUSED,
5569 const char *ifname COAP_UNUSED) {
5570 return -1;
5571}
5572
5573int
5575 size_t hops COAP_UNUSED) {
5576 return 0;
5577}
5578
5579void
5581}
5582#endif /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
int coap_is_mcast(const coap_address_t *a)
Checks if given address a denotes a multicast address.
void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
void coap_debug_reset(void)
Reset all the defined logging parameters.
struct coap_proxy_list_t coap_proxy_list_t
Proxy information.
struct coap_async_t coap_async_t
Async Entry information.
#define PRIu32
const char * coap_socket_strerror(void)
Definition coap_io.c:847
void coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length)
Given a packet, set msg and msg_len to an address and length of the packet's data in memory.
Definition coap_io.c:203
void coap_update_io_timer(coap_context_t *context, coap_tick_t delay)
Update when to continue with I/O processing, unless packets come in in the meantime.
Definition coap_io.c:70
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:33
#define COAP_SOCKET_ERROR
Definition coap_io.h:53
coap_nack_reason_t
Definition coap_io.h:66
@ COAP_NACK_NOT_DELIVERABLE
Definition coap_io.h:68
@ COAP_NACK_TOO_MANY_RETRIES
Definition coap_io.h:67
@ COAP_NACK_ICMP_ISSUE
Definition coap_io.h:71
@ COAP_NACK_RST
Definition coap_io.h:69
@ COAP_NACK_BAD_RESPONSE
Definition coap_io.h:72
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
#define COAP_SOCKET_WANT_ACCEPT
non blocking server socket is waiting for accept
#define COAP_SOCKET_NOT_EMPTY
the socket is not empty
#define COAP_SOCKET_CAN_WRITE
non blocking socket can now write without blocking
#define COAP_SOCKET_BOUND
the socket is bound
#define COAP_SOCKET_WANT_READ
non blocking socket is waiting for reading
#define COAP_SOCKET_CAN_ACCEPT
non blocking server socket can now accept without blocking
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
#define COAP_SOCKET_CAN_CONNECT
non blocking client socket can now connect without blocking
void coap_epoll_ctl_mod(coap_socket_t *sock, uint32_t events, const char *func)
Epoll specific function to modify the state of events that epoll is tracking on the appropriate file ...
#define COAP_SOCKET_WANT_CONNECT
non blocking client socket is waiting for connect
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
#define COAP_SOCKET_CONNECTED
the socket is connected
@ COAP_LAYER_SESSION
Library specific build wrapper for coap_internal.h.
#define COAP_API
void coap_dump_memory_type_counts(coap_log_t level)
Dumps the current usage of malloc'd memory types.
Definition coap_mem.c:747
void coap_memory_init(void)
Initializes libcoap's memory management.
@ COAP_NODE
Definition coap_mem.h:38
@ COAP_CONTEXT
Definition coap_mem.h:39
@ COAP_STRING
Definition coap_mem.h:34
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
CoAP mutex mechanism wrapper.
#define coap_mutex_init(a)
int coap_mutex_t
#define coap_mutex_destroy(a)
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition coap_net.c:83
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition coap_net.c:1123
static int send_recv_terminate
Definition coap_net.c:2112
static int coap_remove_from_queue_token(coap_queue_t **queue, coap_session_t *session, coap_bin_const_t *token, coap_queue_t **node)
Definition coap_net.c:3017
#define MAX_BITS
The maximum number of bits for fixed point integers that are used for retransmission time calculation...
Definition coap_net.c:89
void coap_cleanup(void)
Definition coap_net.c:5187
#define ACK_TIMEOUT
creates a Qx.FRAC_BITS from session's 'ack_timeout'
Definition coap_net.c:104
static const char * coap_event_name(coap_event_t event)
Definition coap_net.c:4881
static int coap_cancel(coap_context_t *context, const coap_queue_t *sent)
This function cancels outstanding messages for the session and token specified in sent.
Definition coap_net.c:3332
int coap_started
Definition coap_net.c:5119
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2397
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2438
COAP_STATIC_INLINE void coap_free_node(coap_queue_t *node)
Definition coap_net.c:112
#define SHR_FP(val, frac)
static void handle_signaling(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition coap_net.c:4307
#define min(a, b)
Definition coap_net.c:76
void coap_startup(void)
Definition coap_net.c:5136
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4384
static unsigned int s_csm_timeout
Definition coap_net.c:509
COAP_STATIC_INLINE coap_queue_t * coap_malloc_node(void)
Definition coap_net.c:107
uint8_t coap_unique_id[8]
Definition coap_net.c:5120
#define FP1
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition coap_net.c:100
#define INET6_ADDRSTRLEN
Definition coap_net.c:72
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c:108
int coap_dtls_receive(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:243
int coap_dtls_context_load_pki_trust_store(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:124
int coap_dtls_context_set_pki_root_cas(coap_context_t *ctx COAP_UNUSED, const char *ca_file COAP_UNUSED, const char *ca_path COAP_UNUSED)
Definition coap_notls.c:116
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:186
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:181
uint16_t coap_option_num_t
Definition coap_option.h:24
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
Definition coap_option.h:30
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define SESSIONS_ITER(e, el, rtmp)
void coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition coap_net.c:2806
coap_mid_t coap_send_rst_lkd(coap_session_t *session, const coap_pdu_t *request)
Sends an RST message with code 0 for the specified request to dst.
Definition coap_net.c:1080
coap_mid_t coap_send_message_type_lkd(coap_session_t *session, const coap_pdu_t *request, coap_pdu_type_t type)
Helper function to create and send a message with type (usually ACK or RST).
Definition coap_net.c:1204
coap_mid_t coap_send_error_lkd(coap_session_t *session, const coap_pdu_t *request, coap_pdu_code_t code, coap_opt_filter_t *opts)
Sends an error response with code code for request request to dst.
Definition coap_net.c:1175
void coap_io_do_io_lkd(coap_context_t *ctx, coap_tick_t now)
Processes any outstanding read, write, accept or connect I/O as indicated in the coap_socket_t struct...
Definition coap_net.c:2736
int coap_send_recv_lkd(coap_session_t *session, coap_pdu_t *request_pdu, coap_pdu_t **response_pdu, uint32_t timeout_ms)
Definition coap_net.c:2141
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
void coap_call_response_handler(coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd, void *body_free)
unsigned int coap_io_prepare_epoll_lkd(coap_context_t *ctx, coap_tick_t now)
Any now timed out delayed packet is transmitted, along with any packets associated with requested obs...
Definition coap_io.c:219
coap_mid_t coap_send_lkd(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1480
coap_mid_t coap_send_ack_lkd(coap_session_t *session, const coap_pdu_t *request)
Sends an ACK message with code 0 for the specified request to dst.
Definition coap_net.c:1095
#define COAP_IO_NO_WAIT
Definition coap_net.h:826
#define COAP_IO_WAIT
Definition coap_net.h:825
COAP_API void coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition coap_net.c:2795
COAP_API void coap_io_do_io(coap_context_t *ctx, coap_tick_t now)
Processes any outstanding read, write, accept or connect I/O as indicated in the coap_socket_t struct...
Definition coap_net.c:2729
int coap_add_data_large_response_lkd(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_string_t *query, uint16_t media_type, int maxage, uint64_t etag, size_t length, const uint8_t *data, coap_release_large_data_t release_func, void *app_ptr)
Associates given data with the response pdu that is passed as fourth parameter.
void coap_block_delete_lg_srcv(coap_session_t *session, coap_lg_srcv_t *lg_srcv)
void coap_block_delete_lg_crcv(coap_session_t *session, coap_lg_crcv_t *lg_crcv)
int coap_handle_response_get_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd, coap_recurse_t recursive)
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_handle_response_send_block(coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd)
coap_lg_crcv_t * coap_find_lg_crcv(coap_session_t *session, coap_pdu_t *pdu)
Find the current lg_crcv for the session that matches the pdu.
int coap_handle_request_put_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *uri_path, coap_opt_t *observe, int *added_block, coap_lg_srcv_t **free_lg_srcv)
#define STATE_TOKEN_BASE(t)
coap_lg_crcv_t * coap_block_new_lg_crcv(coap_session_t *session, coap_pdu_t *pdu, coap_lg_xmit_t *lg_xmit)
int coap_handle_request_send_block(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *query)
@ COAP_RECURSE_OK
#define COAP_OPT_BLOCK_SZX(opt)
Returns the value of the SZX-field of a Block option opt.
Definition coap_block.h:95
#define COAP_BLOCK_TRY_Q_BLOCK
Definition coap_block.h:67
#define COAP_BLOCK_SINGLE_BODY
Definition coap_block.h:66
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
#define COAP_BLOCK_NO_PREEMPTIVE_RTAG
Definition coap_block.h:69
#define COAP_BLOCK_CACHE_RESPONSE
Definition coap_block.h:73
#define COAP_BLOCK_USE_LIBCOAP
Definition coap_block.h:65
void coap_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
int coap_digest_final(coap_digest_ctx_t *digest_ctx, coap_digest_t *digest_buffer)
Finalize the coap_digest information into the provided digest_buffer.
int coap_digest_update(coap_digest_ctx_t *digest_ctx, const uint8_t *data, size_t data_len)
Update the coap_digest information with the next chunk of data.
void coap_digest_ctx_t
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
void coap_delete_cache_entry(coap_context_t *context, coap_cache_entry_t *cache_entry)
Remove a cache-entry from the hash list and free off all the appropriate contents apart from app_data...
int64_t coap_tick_diff_t
This data type is used to represent the difference between two clock_tick_t values.
Definition coap_time.h:163
void coap_clock_init(void)
Initializes the internal clock.
Definition coap_time.c:68
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:151
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:166
#define COAP_MAX_DELAY_TICKS
Definition coap_time.h:230
uint64_t coap_ticks_to_rt_us(coap_tick_t t)
Helper function that converts coap ticks to POSIX wallclock time in us.
Definition coap_time.c:128
void coap_prng_init_lkd(unsigned int seed)
Seeds the default random number generation function with the given seed.
Definition coap_prng.c:178
int coap_prng_lkd(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition coap_prng.c:190
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.
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.
#define RESOURCES_ITER(r, tmp)
#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_RESOURCE_FLAGS_HAS_MCAST_SUPPORT
This resource has support for multicast requests.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_4_XX
Disable libcoap library suppressing 4.xx multicast responses (overridden by RFC7969 No-Response optio...
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS
Disable libcoap library from adding in delays to multicast requests before releasing the response bac...
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.
#define COAP_RESOURCE_FLAGS_OSCORE_ONLY
Define this resource as an OSCORE enabled access only.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_5_XX
Disable libcoap library suppressing 5.xx multicast responses (overridden by RFC7969 No-Response optio...
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
#define COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY
Force all large traffic to this resource to be presented as a single body to the request handler.
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_05
Enable libcoap library suppression of 205 multicast responses that are empty (overridden by RFC7969 N...
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_XX
Enable libcoap library suppressing 2.xx multicast responses (overridden by RFC7969 No-Response option...
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4963
uint16_t coap_new_message_id_lkd(coap_session_t *session)
Returns a new message id and updates session->tx_mid accordingly.
unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now)
Set sendqueue_basetime in the given context object ctx to now.
Definition coap_net.c:117
int coap_delete_node_lkd(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:214
void coap_delete_all(coap_queue_t *queue)
Removes all items from given queue and frees the allocated storage.
Definition coap_net.c:234
int coap_context_set_psk2_lkd(coap_context_t *context, coap_dtls_spsk_t *setup_data)
Set the context's default PSK hint and/or key for a server.
void coap_register_option_lkd(coap_context_t *ctx, uint16_t type)
Registers the option number number with the given context object context.
Definition coap_net.c:5267
int coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id, coap_queue_t **node)
This function removes the element with given id from the list given list.
Definition coap_net.c:2972
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition coap_net.c:257
COAP_API int coap_delete_node(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:191
int coap_client_delay_first(coap_session_t *session)
Delay the sending of the first client request until some other negotiation has completed.
Definition coap_net.c:1348
int coap_context_set_psk_lkd(coap_context_t *context, const char *hint, const uint8_t *key, size_t key_len)
Set the context's default PSK hint and/or key for a server.
coap_queue_t * coap_pop_next(coap_context_t *context)
Returns the next pdu to send and removes it from the sendqeue.
Definition coap_net.c:265
void coap_dispatch(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Dispatches the PDUs from the receive queue in given context.
Definition coap_net.c:4417
int coap_insert_node(coap_queue_t **queue, coap_queue_t *node)
Adds node to given queue, ordered by variable t in node.
Definition coap_net.c:154
unsigned int coap_calc_timeout(coap_session_t *session, unsigned char r)
Calculates the initial timeout based on the session CoAP transmission parameters 'ack_timeout',...
Definition coap_net.c:1232
int coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *groupname, const char *ifname)
Function interface for joining a multicast group for listening for the currently defined endpoints th...
void coap_free_context_lkd(coap_context_t *context)
CoAP stack context must be released with coap_free_context_lkd().
Definition coap_net.c:821
int coap_context_load_pki_trust_store_lkd(coap_context_t *ctx)
Load the context's default trusted CAs for a client or server.
Definition coap_net.c:455
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:1849
void * coap_context_set_app_data2_lkd(coap_context_t *context, void *app_data, coap_app_data_free_callback_t callback)
Stores data with the given context, returning the previously stored value or NULL.
Definition coap_net.c:696
int coap_can_exit_lkd(coap_context_t *context)
Returns 1 if there are no messages to send or to dispatch in the context's queues.
Definition coap_net.c:5051
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2259
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:1415
int coap_context_set_pki_root_cas_lkd(coap_context_t *ctx, const char *ca_file, const char *ca_dir)
Set the context's default Root CA information for a client or server.
Definition coap_net.c:435
int coap_option_check_critical(coap_session_t *session, coap_pdu_t *pdu, coap_opt_filter_t *unknown)
Verifies that pdu contains no unknown critical options, duplicate options or the options defined as R...
Definition coap_net.c:920
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1258
coap_queue_t * coap_new_node(void)
Creates a new node suitable for adding to the CoAP sendqueue.
Definition coap_net.c:243
void coap_cancel_session_messages(coap_context_t *context, coap_session_t *session, coap_nack_reason_t reason)
Cancels all outstanding messages for session session.
Definition coap_net.c:3076
int coap_context_set_pki_lkd(coap_context_t *context, const coap_dtls_pki_t *setup_data)
Set the context's default PKI information for a server.
int coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *msg, size_t msg_len)
Parses and interprets a CoAP datagram with context ctx.
Definition coap_net.c:2911
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:3115
void coap_context_set_session_timeout(coap_context_t *context, unsigned int session_timeout)
Set the session timeout value.
Definition coap_net.c:558
unsigned int coap_context_get_max_handshake_sessions(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:505
COAP_API int coap_join_mcast_group_intf(coap_context_t *ctx, const char *groupname, const char *ifname)
Function interface for joining a multicast group for listening for the currently defined endpoints th...
void(* coap_pong_handler_t)(coap_session_t *session, const coap_pdu_t *received, const coap_mid_t mid)
Received Pong handler that is used as callback in coap_context_t.
Definition coap_net.h:106
unsigned int coap_context_get_max_idle_sessions(const coap_context_t *context)
Get the maximum idle sessions count.
Definition coap_net.c:494
COAP_API int coap_send_recv(coap_session_t *session, coap_pdu_t *request_pdu, coap_pdu_t **response_pdu, uint32_t timeout_ms)
Definition coap_net.c:2120
coap_context_t * coap_new_context(const coap_address_t *listen_addr)
Creates a new coap_context_t object that will hold the CoAP stack status.
Definition coap_net.c:706
COAP_API coap_mid_t coap_send(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1470
COAP_API int coap_context_set_pki(coap_context_t *context, const coap_dtls_pki_t *setup_data)
Set the context's default PKI information for a server.
void coap_mcast_per_resource(coap_context_t *context)
Function interface to enable processing mcast requests on a per resource basis.
coap_response_t(* coap_response_handler_t)(coap_session_t *session, const coap_pdu_t *sent, const coap_pdu_t *received, const coap_mid_t mid)
Response handler that is used as callback in coap_context_t.
Definition coap_net.h:70
COAP_API coap_mid_t coap_send_error(coap_session_t *session, const coap_pdu_t *request, coap_pdu_code_t code, coap_opt_filter_t *opts)
Sends an error response with code code for request request to dst.
Definition coap_net.c:1162
void coap_context_set_csm_max_message_size(coap_context_t *context, uint32_t csm_max_message_size)
Set the CSM max session size value.
Definition coap_net.c:540
void coap_context_set_csm_timeout(coap_context_t *context, unsigned int csm_timeout)
Set the CSM timeout value.
Definition coap_net.c:512
void coap_send_recv_terminate(void)
Terminate any active coap_send_recv() sessions.
Definition coap_net.c:2115
coap_resource_t *(* coap_resource_dynamic_create_t)(coap_session_t *session, const coap_pdu_t *request)
Definition of resource dynamic creation handler function.
Definition coap_net.h:118
void coap_register_response_handler(coap_context_t *context, coap_response_handler_t handler)
Registers a new message handler that is called whenever a response is received.
Definition coap_net.c:5211
COAP_API void * coap_context_set_app_data2(coap_context_t *context, void *app_data, coap_app_data_free_callback_t callback)
Stores data with the given context, returning the previously stored value or NULL.
Definition coap_net.c:685
coap_pdu_t * coap_new_error_response(const coap_pdu_t *request, coap_pdu_code_t code, coap_opt_filter_t *opts)
Creates a new ACK PDU with specified error code.
Definition coap_net.c:3148
void coap_context_set_max_handshake_sessions(coap_context_t *context, unsigned int max_handshake_sessions)
Set the maximum number of sessions in (D)TLS handshake value.
Definition coap_net.c:499
int coap_context_get_coap_fd(const coap_context_t *context)
Get the libcoap internal file descriptor for using in an application's select() or returned as an eve...
Definition coap_net.c:598
void coap_register_dynamic_resource_handler(coap_context_t *context, coap_resource_dynamic_create_t dyn_create_handler, uint32_t dynamic_max)
Sets up a handler for calling when an unknown resource is requested.
Definition coap_net.c:5251
COAP_API void coap_set_app_data(coap_context_t *context, void *app_data)
Definition coap_net.c:798
int coap_mcast_set_hops(coap_session_t *session, size_t hops)
Function interface for defining the hop count (ttl) for sending multicast traffic.
coap_response_t
Definition coap_net.h:54
void(* coap_ping_handler_t)(coap_session_t *session, const coap_pdu_t *received, const coap_mid_t mid)
Received Ping handler that is used as callback in coap_context_t.
Definition coap_net.h:95
void coap_ticks(coap_tick_t *t)
Returns the current value of an internal tick counter.
Definition coap_time.c:90
COAP_API void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition coap_net.c:812
void(* coap_nack_handler_t)(coap_session_t *session, const coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
Negative Acknowedge handler that is used as callback in coap_context_t.
Definition coap_net.h:83
void coap_context_set_shutdown_no_observe(coap_context_t *context)
Definition coap_net.c:589
void * coap_context_get_app_data(const coap_context_t *context)
Returns any application-specific data that has been stored with context using the function coap_conte...
Definition coap_net.c:679
COAP_API int coap_context_set_pki_root_cas(coap_context_t *ctx, const char *ca_file, const char *ca_dir)
Set the context's default Root CA information for a client or server.
Definition coap_net.c:423
COAP_API void coap_context_set_app_data(coap_context_t *context, void *app_data)
Stores data with the given context.
Definition coap_net.c:671
uint32_t coap_context_get_csm_max_message_size(const coap_context_t *context)
Get the CSM max session size value.
Definition coap_net.c:553
unsigned int coap_context_get_session_timeout(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:584
COAP_API int coap_context_set_psk(coap_context_t *context, const char *hint, const uint8_t *key, size_t key_len)
Set the context's default PSK hint and/or key for a server.
COAP_API coap_mid_t coap_send_ack(coap_session_t *session, const coap_pdu_t *request)
Sends an ACK message with code 0 for the specified request to dst.
Definition coap_net.c:1085
unsigned int coap_context_get_csm_timeout_ms(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:535
void coap_register_ping_handler(coap_context_t *context, coap_ping_handler_t handler)
Registers a new message handler that is called whenever a CoAP Ping message is received.
Definition coap_net.c:5239
COAP_API int coap_context_set_psk2(coap_context_t *context, coap_dtls_spsk_t *setup_data)
Set the context's default PSK hint and/or key for a server.
void * coap_get_app_data(const coap_context_t *ctx)
Definition coap_net.c:806
int coap_context_set_cid_tuple_change(coap_context_t *context, uint8_t every)
Set the Connection ID client tuple frequency change for testing CIDs.
Definition coap_net.c:469
void coap_context_set_max_idle_sessions(coap_context_t *context, unsigned int max_idle_sessions)
Set the maximum idle sessions count.
Definition coap_net.c:488
COAP_API coap_mid_t coap_send_message_type(coap_session_t *session, const coap_pdu_t *request, coap_pdu_type_t type)
Helper function to create and send a message with type (usually ACK or RST).
Definition coap_net.c:1193
COAP_API coap_mid_t coap_send_rst(coap_session_t *session, const coap_pdu_t *request)
Sends an RST message with code 0 for the specified request to dst.
Definition coap_net.c:1070
void coap_context_set_session_reconnect_time2(coap_context_t *context, unsigned int reconnect_time, uint8_t retry_count)
Set the session reconnect delay time after a working client session has failed.
Definition coap_net.c:570
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds)
Set the context keepalive timer for sessions.
Definition coap_net.c:464
COAP_API int coap_can_exit(coap_context_t *context)
Returns 1 if there are no messages to send or to dispatch in the context's queues.
Definition coap_net.c:5041
COAP_API void coap_register_option(coap_context_t *ctx, uint16_t type)
Registers the option number number with the given context object context.
Definition coap_net.c:5260
unsigned int coap_context_get_csm_timeout(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:519
COAP_API int coap_context_load_pki_trust_store(coap_context_t *ctx)
Load the hosts's default trusted CAs for a client or server.
Definition coap_net.c:445
void coap_context_set_session_reconnect_time(coap_context_t *context, unsigned int reconnect_time)
Set the session reconnect delay time after a working client session has failed.
Definition coap_net.c:564
void coap_register_pong_handler(coap_context_t *context, coap_pong_handler_t handler)
Registers a new message handler that is called whenever a CoAP Pong message is received.
Definition coap_net.c:5245
void coap_context_set_max_token_size(coap_context_t *context, size_t max_token_size)
Set the maximum token size (RFC8974).
Definition coap_net.c:480
COAP_API int coap_handle_event(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4952
void coap_register_nack_handler(coap_context_t *context, coap_nack_handler_t handler)
Registers a new message handler that is called whenever a confirmable message (request or response) i...
Definition coap_net.c:5233
void coap_context_set_csm_timeout_ms(coap_context_t *context, unsigned int csm_timeout_ms)
Set the CSM timeout value.
Definition coap_net.c:525
@ COAP_RESPONSE_FAIL
Response not liked - send CoAP RST packet.
Definition coap_net.h:55
@ COAP_RESPONSE_OK
Response is fine.
Definition coap_net.h:56
const coap_bin_const_t * coap_get_session_client_psk_identity(const coap_session_t *coap_session)
Get the current client's PSK identity.
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition coap_notls.c:154
coap_session_t * coap_session_new_dtls_session(coap_session_t *session, coap_tick_t now)
Create a new DTLS session for the session.
int coap_dtls_hello(coap_session_t *coap_session, const uint8_t *data, size_t data_len)
Handling client HELLO messages from a new candiate peer.
int coap_dtls_set_cid_tuple_change(coap_context_t *context, uint8_t every)
Set the Connection ID client tuple frequency change for testing CIDs.
int coap_dtls_context_set_spsk(coap_context_t *coap_context, coap_dtls_spsk_t *setup_data)
Set the DTLS context's default server PSK information.
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:166
const coap_bin_const_t * coap_get_session_client_psk_key(const coap_session_t *coap_session)
Get the current client's PSK key.
const coap_bin_const_t * coap_get_session_server_psk_key(const coap_session_t *coap_session)
Get the current server's PSK key.
const coap_bin_const_t * coap_get_session_server_psk_hint(const coap_session_t *coap_session)
Get the current server's PSK identity hint.
#define COAP_DTLS_PKI_SETUP_VERSION
Latest PKI setup version.
Definition coap_dtls.h:311
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:50
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
unsigned int coap_decode_var_bytes(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:38
uint64_t coap_decode_var_bytes8(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:67
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:77
coap_event_t
Scalar type to represent different events, e.g.
Definition coap_event.h:38
@ COAP_EVENT_OSCORE_DECODE_ERROR
Triggered when there is an OSCORE decode of OSCORE option failure.
Definition coap_event.h:128
@ COAP_EVENT_SESSION_CONNECTED
Triggered when TCP layer completes exchange of CSM information.
Definition coap_event.h:65
@ COAP_EVENT_RECONNECT_FAILED
Triggered when a session failed, and a reconnect is going to be attempted.
Definition coap_event.h:147
@ COAP_EVENT_OSCORE_INTERNAL_ERROR
Triggered when there is an OSCORE internal error i.e malloc failed.
Definition coap_event.h:126
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition coap_event.h:43
@ COAP_EVENT_TCP_FAILED
Triggered when TCP layer fails for some reason.
Definition coap_event.h:59
@ COAP_EVENT_WS_CONNECTED
Triggered when the WebSockets layer is up.
Definition coap_event.h:135
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:45
@ COAP_EVENT_SESSION_FAILED
Triggered when TCP layer fails following exchange of CSM information.
Definition coap_event.h:69
@ COAP_EVENT_PARTIAL_BLOCK
Triggered when not all of a large body has been received.
Definition coap_event.h:75
@ COAP_EVENT_XMIT_BLOCK_FAIL
Triggered when not all of a large body has been transmitted.
Definition coap_event.h:77
@ COAP_EVENT_SERVER_SESSION_NEW
Called in the CoAP IO loop if a new server-side session is created due to an incoming connection.
Definition coap_event.h:89
@ COAP_EVENT_OSCORE_NOT_ENABLED
Triggered when trying to use OSCORE to decrypt, but it is not enabled.
Definition coap_event.h:120
@ COAP_EVENT_RECONNECT_STARTED
Triggered when a session starts to reconnect.
Definition coap_event.h:153
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:137
@ COAP_EVENT_RECONNECT_NO_MORE
Triggered when a session failed, and retry reconnect attempts failed.
Definition coap_event.h:151
@ COAP_EVENT_SESSION_CLOSED
Triggered when TCP layer closes following exchange of CSM information.
Definition coap_event.h:67
@ COAP_EVENT_SERVER_SESSION_DEL
Called in the CoAP IO loop if a server session is deleted (e.g., due to inactivity or because the max...
Definition coap_event.h:98
@ COAP_EVENT_OSCORE_NO_SECURITY
Triggered when there is no OSCORE security definition found.
Definition coap_event.h:124
@ COAP_EVENT_DTLS_RENEGOTIATE
Triggered when (D)TLS session renegotiated.
Definition coap_event.h:47
@ COAP_EVENT_BAD_PACKET
Triggered when badly formatted packet received.
Definition coap_event.h:110
@ COAP_EVENT_SERVER_SESSION_CONNECTED
Called in the CoAP IO loop once a server session is active and (D)TLS (if any) is established.
Definition coap_event.h:104
@ COAP_EVENT_MSG_RETRANSMITTED
Triggered when a message is retransmitted.
Definition coap_event.h:112
@ COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD
Triggered when there is no OSCORE encrypted payload provided.
Definition coap_event.h:122
@ COAP_EVENT_RECONNECT_SUCCESS
Triggered when a session failed, and a reconnect is successful.
Definition coap_event.h:149
@ COAP_EVENT_TCP_CLOSED
Triggered when TCP layer is closed.
Definition coap_event.h:57
@ COAP_EVENT_WS_PACKET_SIZE
Triggered when there is an oversize WebSockets packet.
Definition coap_event.h:133
@ COAP_EVENT_TCP_CONNECTED
Triggered when TCP layer connects.
Definition coap_event.h:55
@ COAP_EVENT_OSCORE_DECRYPTION_FAILURE
Triggered when there is an OSCORE decryption failure.
Definition coap_event.h:118
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:142
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:49
coap_mutex_t coap_lock_t
#define coap_lock_callback(func)
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, func)
Dummy for no thread-safe code.
#define coap_lock_callback_ret_release(r, func, failed)
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_lock_init()
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
#define coap_log_alert(...)
Definition coap_debug.h:90
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition coap_debug.c:793
#define coap_log_emerg(...)
Definition coap_debug.h:87
size_t coap_print_addr(const coap_address_t *addr, unsigned char *buf, size_t len)
Print the address into the defined buffer.
Definition coap_debug.c:241
const char * coap_endpoint_str(const coap_endpoint_t *endpoint)
Get endpoint description.
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:114
#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
@ COAP_LOG_WARN
Definition coap_debug.h:61
int coap_netif_strm_connect2(coap_session_t *session)
Layer function interface for Netif stream connect (tcp).
ssize_t coap_netif_dgrm_read(coap_session_t *session, coap_packet_t *packet)
Function interface for layer data datagram receiving for sessions.
Definition coap_netif.c:72
ssize_t coap_netif_dgrm_read_ep(coap_endpoint_t *endpoint, coap_packet_t *packet)
Function interface for layer data datagram receiving for endpoints.
int coap_netif_available(coap_session_t *session)
Function interface to check whether netif for session is still available.
Definition coap_netif.c:25
#define COAP_OBSERVE_CANCEL
The value COAP_OBSERVE_CANCEL in a GET/FETCH request option COAP_OPTION_OBSERVE indicates that the ob...
#define COAP_OBSERVE_ESTABLISH
The value COAP_OBSERVE_ESTABLISH in a GET/FETCH request option COAP_OPTION_OBSERVE indicates a new ob...
coap_opt_t * coap_option_next(coap_opt_iterator_t *oi)
Updates the iterator oi to point to the next option.
uint32_t coap_opt_length(const coap_opt_t *opt)
Returns the length of the given option.
coap_opt_iterator_t * coap_option_iterator_init(const coap_pdu_t *pdu, coap_opt_iterator_t *oi, const coap_opt_filter_t *filter)
Initializes the given option iterator oi to point to the beginning of the pdu's option list.
#define COAP_OPT_ALL
Pre-defined filter that includes all options.
void coap_option_filter_clear(coap_opt_filter_t *filter)
Clears filter filter.
coap_opt_t * coap_check_option(const coap_pdu_t *pdu, coap_option_num_t number, coap_opt_iterator_t *oi)
Retrieves the first option of number number from pdu.
const uint8_t * coap_opt_value(const coap_opt_t *opt)
Returns a pointer to the value of the given option.
int coap_option_filter_get(coap_opt_filter_t *filter, coap_option_num_t option)
Checks if number is contained in filter.
int coap_option_filter_set(coap_opt_filter_t *filter, coap_option_num_t option)
Sets the corresponding entry for number in filter.
coap_pdu_t * coap_oscore_new_pdu_encrypted_lkd(coap_session_t *session, coap_pdu_t *pdu, coap_bin_const_t *kid_context, oscore_partial_iv_t send_partial_iv)
Encrypts the specified pdu when OSCORE encryption is required on session.
struct coap_pdu_t * coap_oscore_decrypt_pdu(coap_session_t *session, coap_pdu_t *pdu)
Decrypts the OSCORE-encrypted parts of pdu when OSCORE is used.
int coap_rebuild_pdu_for_proxy(coap_pdu_t *pdu)
Convert PDU to use Proxy-Scheme option if Proxy-Uri option is present.
void coap_delete_all_oscore(coap_context_t *context)
Cleanup all allocated OSCORE information.
#define COAP_PDU_IS_RESPONSE(pdu)
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
#define COAP_TOKEN_EXT_2B_TKL
size_t coap_insert_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Inserts option of given number in the pdu with the appropriate data.
Definition coap_pdu.c:633
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
int coap_pdu_parse_opt(coap_pdu_t *pdu, coap_opt_filter_t *error_opts)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition coap_pdu.c:1352
#define COAP_DROPPED_RESPONSE
Indicates that a response is suppressed.
int coap_pdu_parse_header(coap_pdu_t *pdu, coap_proto_t proto)
Decode the protocol specific header for the specified PDU.
Definition coap_pdu.c:1078
size_t coap_pdu_parse_header_size(coap_proto_t proto, const uint8_t *data)
Interprets data to determine the number of bytes in the header.
Definition coap_pdu.c:994
#define COAP_PDU_DELAYED
#define COAP_PDU_IS_EMPTY(pdu)
#define COAP_PDU_IS_SIGNALING(pdu)
int coap_option_check_repeatable(coap_option_num_t number)
Check whether the option is allowed to be repeated or not.
Definition coap_pdu.c:587
size_t coap_update_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Updates existing first option of given number in the pdu with the new data.
Definition coap_pdu.c:727
#define COAP_TOKEN_EXT_1B_TKL
size_t coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto)
Compose the protocol specific header for the specified PDU.
Definition coap_pdu.c:1517
#define COAP_DEFAULT_VERSION
int coap_pdu_parse2(coap_proto_t proto, const uint8_t *data, size_t length, coap_pdu_t *pdu, coap_opt_filter_t *error_opts)
Parses data into the CoAP PDU structure given in result.
Definition coap_pdu.c:1493
size_t coap_pdu_parse_size(coap_proto_t proto, const uint8_t *data, size_t length)
Parses data to extract the message size.
Definition coap_pdu.c:1025
int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size)
Dynamically grows the size of pdu to new_size.
Definition coap_pdu.c:301
#define COAP_PDU_IS_REQUEST(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_HOP_LIMIT
Definition coap_pdu.h:137
#define COAP_OPTION_NORESPONSE
Definition coap_pdu.h:150
#define COAP_OPTION_URI_HOST
Definition coap_pdu.h:124
#define COAP_OPTION_IF_MATCH
Definition coap_pdu.h:123
#define COAP_OPTION_BLOCK2
Definition coap_pdu.h:142
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition coap_pdu.c:954
#define COAP_OPTION_CONTENT_FORMAT
Definition coap_pdu.h:132
#define COAP_OPTION_BLOCK1
Definition coap_pdu.h:143
#define COAP_OPTION_Q_BLOCK1
Definition coap_pdu.h:139
#define COAP_OPTION_PROXY_SCHEME
Definition coap_pdu.h:147
#define COAP_OPTION_URI_QUERY
Definition coap_pdu.h:136
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:268
#define COAP_TOKEN_DEFAULT_MAX
Definition coap_pdu.h:60
#define COAP_OPTION_IF_NONE_MATCH
Definition coap_pdu.h:126
#define COAP_TOKEN_EXT_MAX
Definition coap_pdu.h:64
#define COAP_OPTION_URI_PATH
Definition coap_pdu.h:131
#define COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH
Definition coap_pdu.h:204
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:165
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:168
coap_pdu_code_t
Set of codes available for a PDU.
Definition coap_pdu.h:332
#define COAP_OPTION_OSCORE
Definition coap_pdu.h:130
coap_pdu_type_t
CoAP PDU message type definitions.
Definition coap_pdu.h:72
#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
Definition coap_pdu.h:203
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:145
#define COAP_SIGNALING_OPTION_CUSTODY
Definition coap_pdu.h:207
int coap_pdu_parse(coap_proto_t proto, const uint8_t *data, size_t length, coap_pdu_t *pdu)
Parses data into the CoAP PDU structure given in result.
Definition coap_pdu.c:1483
#define COAP_OPTION_RTAG
Definition coap_pdu.h:151
#define COAP_OPTION_URI_PORT
Definition coap_pdu.h:128
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_OPTION_ACCEPT
Definition coap_pdu.h:138
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:271
#define COAP_OPTION_PROXY_URI
Definition coap_pdu.h:146
#define COAP_OPTION_OBSERVE
Definition coap_pdu.h:127
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition coap_pdu.h:57
#define COAP_BERT_BASE
Definition coap_pdu.h:48
#define COAP_OPTION_ECHO
Definition coap_pdu.h:149
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition coap_pdu.h:219
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition coap_pdu.h:202
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_GET
Definition coap_pdu.h:83
@ COAP_PROTO_WS
Definition coap_pdu.h:324
@ COAP_PROTO_DTLS
Definition coap_pdu.h:321
@ COAP_PROTO_UDP
Definition coap_pdu.h:320
@ COAP_PROTO_TLS
Definition coap_pdu.h:323
@ COAP_PROTO_WSS
Definition coap_pdu.h:325
@ COAP_PROTO_TCP
Definition coap_pdu.h:322
@ COAP_SIGNALING_CODE_ABORT
Definition coap_pdu.h:375
@ COAP_REQUEST_CODE_PUT
Definition coap_pdu.h:337
@ COAP_REQUEST_CODE_POST
Definition coap_pdu.h:336
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:371
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:372
@ COAP_REQUEST_CODE_DELETE
Definition coap_pdu.h:338
@ COAP_SIGNALING_CODE_PONG
Definition coap_pdu.h:373
@ COAP_EMPTY_CODE
Definition coap_pdu.h:333
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:335
@ COAP_SIGNALING_CODE_RELEASE
Definition coap_pdu.h:374
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:339
@ COAP_MESSAGE_NON
Definition coap_pdu.h:74
@ COAP_MESSAGE_ACK
Definition coap_pdu.h:75
@ COAP_MESSAGE_CON
Definition coap_pdu.h:73
@ COAP_MESSAGE_RST
Definition coap_pdu.h:76
void coap_register_proxy_response_handler(coap_context_t *context, coap_proxy_response_handler_t handler)
Registers a new message handler that is called whenever a response is received by the proxy logic.
Definition coap_net.c:5222
coap_pdu_t *(* coap_proxy_response_handler_t)(coap_session_t *session, const coap_pdu_t *sent, coap_pdu_t *received, coap_cache_key_t *cache_key)
Proxy response handler that is used as callback held in coap_context_t.
Definition coap_proxy.h:126
void coap_connect_session(coap_session_t *session, coap_tick_t now)
ssize_t coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
#define COAP_DEFAULT_LEISURE_TICKS(s)
The DEFAULT_LEISURE definition for the session (s).
void coap_handle_nack(coap_session_t *session, coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
size_t coap_session_max_pdu_rcv_size(const coap_session_t *session)
Get maximum acceptable receive PDU size.
coap_session_t * coap_endpoint_get_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Lookup the server session for the packet received on an endpoint, or create a new one.
void coap_free_endpoint_lkd(coap_endpoint_t *endpoint)
Release an endpoint and all the structures associated with it.
void coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2468
int coap_session_reconnect(coap_session_t *session)
Close the current session (if not already closed) and reconnect to server (client session only).
void coap_session_server_keepalive_failed(coap_session_t *session)
Clear down a session following a keepalive failure.
#define COAP_NSTART(s)
#define COAP_MAX_PAYLOADS(s)
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
ssize_t coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu)
Send a pdu according to the session's protocol.
Definition coap_net.c:1110
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.
void coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
coap_endpoint_t * coap_new_endpoint_lkd(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto)
Create a new endpoint for communicating with peers.
coap_session_t * coap_new_server_session(coap_context_t *ctx, coap_endpoint_t *ep, void *extra)
Creates a new server session for the specified endpoint.
@ COAP_EXT_T_NOT_CHECKED
Not checked.
@ COAP_EXT_T_CHECKING
Token size check request sent.
@ COAP_EXT_T_CHECKED
Token size valid.
void coap_session_set_mtu(coap_session_t *session, unsigned mtu)
Set the session MTU.
coap_session_state_t
coap_session_state_t values
#define COAP_PROTO_NOT_RELIABLE(p)
#define COAP_PROTO_RELIABLE(p)
void(* coap_app_data_free_callback_t)(void *data)
Callback to free off the app data when the entry is being deleted / freed off.
@ COAP_SESSION_TYPE_HELLO
server-side ephemeral session for responding to a client hello
@ COAP_SESSION_TYPE_SERVER
server-side
@ COAP_SESSION_TYPE_CLIENT
client-side
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_ESTABLISHED
@ COAP_SESSION_STATE_NONE
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
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:77
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
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:105
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:214
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:200
coap_string_t * coap_new_string(size_t size)
Returns a new string object with at least size+1 bytes storage allocated.
Definition coap_str.c:21
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition coap_str.c:46
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.
void coap_persist_cleanup(coap_context_t *context)
Close down persist tracking, releasing any memory used.
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.
int coap_cancel_observe_lkd(coap_session_t *session, coap_binary_t *token, coap_pdu_type_t message_type)
Cancel an observe that is being tracked by the client large receive logic.
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Handles a failed observe notify.
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.
int coap_epoll_is_supported(void)
Determine whether epoll is supported or not.
Definition coap_net.c:608
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition coap_notls.c:41
int coap_af_unix_is_supported(void)
Check whether socket type AF_UNIX is available.
Definition coap_net.c:662
int coap_ipv6_is_supported(void)
Check whether IPv6 is available.
Definition coap_net.c:635
int coap_threadsafe_is_supported(void)
Determine whether libcoap is threadsafe or not.
Definition coap_net.c:617
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition coap_notls.c:36
int coap_server_is_supported(void)
Check whether Server code is available.
Definition coap_net.c:653
int coap_client_is_supported(void)
Check whether Client code is available.
Definition coap_net.c:644
int coap_ipv4_is_supported(void)
Check whether IPv4 is available.
Definition coap_net.c:626
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition coap_uri.c:1008
int coap_split_proxy_uri(const uint8_t *str_var, size_t len, coap_uri_t *uri)
Parses a given string into URI components.
Definition coap_uri.c:299
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:957
#define COAP_UNUSED
Definition libcoap.h:74
#define COAP_STATIC_INLINE
Definition libcoap.h:57
coap_address_t remote
remote address and port
Definition coap_io.h:60
coap_address_t local
local address and port
Definition coap_io.h:61
Multi-purpose address abstraction.
struct sockaddr_in sin
struct sockaddr_in6 sin6
struct sockaddr sa
union coap_address_t::@0 addr
CoAP binary data definition with const data.
Definition coap_str.h:67
size_t length
length of binary data
Definition coap_str.h:68
const uint8_t * s
read-only binary data
Definition coap_str.h:69
CoAP binary data definition.
Definition coap_str.h:59
size_t length
length of binary data
Definition coap_str.h:60
uint8_t * s
binary data
Definition coap_str.h:61
Structure of Block options with BERT support.
Definition coap_block.h:55
unsigned int num
block number
Definition coap_block.h:56
uint32_t chunk_size
‍1024 if BERT
Definition coap_block.h:62
unsigned int bert
Operating as BERT.
Definition coap_block.h:61
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:59
unsigned int defined
Set if block found.
Definition coap_block.h:60
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:57
unsigned int szx
block size (0-6)
Definition coap_block.h:58
The CoAP stack's global state is stored in a coap_context_t object.
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
coap_pong_handler_t pong_handler
Called when a ping response is received.
coap_app_data_free_callback_t app_cb
call-back to release app_data
unsigned int reconnect_time
Time to wait before reconnecting a failed client session.
uint8_t shutdown_no_send_observe
Do not send out unsolicited observe when coap_free_context() is called.
coap_resource_dynamic_create_t dyn_create_handler
Dynamc resource create handler.
coap_session_t * sessions
client sessions
coap_nack_handler_t nack_handler
Called when a response issue has occurred.
void * app_data
application-specific data
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
uint8_t retry_count
Number of times to retry reconnecting a.
coap_resource_t * resources
hash table or list of known resources
uint16_t * cache_ignore_options
CoAP options to ignore when creating a cache-key.
coap_opt_filter_t known_options
coap_ping_handler_t ping_handler
Called when a CoAP ping is received.
uint32_t csm_max_message_size
Value for CSM Max-Message-Size.
size_t cache_ignore_count
The number of CoAP options to ignore when creating a cache-key.
unsigned int max_handshake_sessions
Maximum number of simultaneous negotating sessions per endpoint.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
coap_response_handler_t response_handler
Called when a response is received.
coap_cache_entry_t * cache
CoAP cache-entry cache.
uint8_t mcast_per_resource
Mcast controlled on a per resource basis.
coap_endpoint_t * endpoint
the endpoints used for listening
uint32_t csm_timeout_ms
Timeout for waiting for a CSM from the remote side.
coap_event_handler_t handle_event
Callback function that is used to signal events to the application.
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
uint8_t observe_no_clear
Observe 4.04 not to be sent on deleting resource.
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
coap_resource_t * unknown_resource
can be used for handling unknown resources
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
coap_bin_const_t key
Definition coap_dtls.h:385
coap_bin_const_t identity
Definition coap_dtls.h:384
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:447
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:316
uint8_t version
Definition coap_dtls.h:317
coap_bin_const_t hint
Definition coap_dtls.h:455
coap_bin_const_t key
Definition coap_dtls.h:456
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:505
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:537
Abstraction of virtual endpoint that can be attached to coap_context_t.
coap_context_t * context
endpoint's context
coap_session_t * sessions
hash table or list of active sessions
coap_address_t bind_addr
local interface address
coap_socket_t sock
socket object for the interface, if any
coap_proto_t proto
protocol used on this interface
uint64_t state_token
state token
uint32_t count
the number of packets sent for payload
coap_binary_t * app_token
original PDU token
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
Structure to hold large body (many blocks) client receive information.
uint64_t state_token
state token
coap_binary_t * app_token
app requesting PDU token
Structure to hold large body (many blocks) server receive information.
Structure to hold large body (many blocks) transmission information.
coap_tick_t last_all_sent
Last time all data sent or 0.
uint8_t blk_size
large block transmission size
union coap_lg_xmit_t::@1 b
int last_block
last acknowledged block number Block1 last transmitted Q-Block2
coap_pdu_t * sent_pdu
The sent pdu with all the data.
coap_l_block1_t b1
uint16_t option
large block transmisson CoAP option
Iterator to run through PDU options.
coap_option_num_t number
decoded option number
size_t length
length of payload
coap_addr_tuple_t addr_info
local and remote addresses
unsigned char * payload
payload
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.
uint8_t * data
first byte of payload, if any
coap_mid_t mid
message id, if any, in regular host byte order
uint32_t e_token_length
length of Token space (includes leading extended bytes
size_t used_size
used bytes of storage for token, options and payload
uint8_t crit_opt
Set if unknown critical option for proxy.
coap_binary_t * data_free
Data to be freed off by coap_delete_pdu()
size_t alloc_size
allocated storage for token, options and payload
coap_session_t * session
Session responsible for PDU or NULL.
coap_pdu_type_t type
message type
Queue entry.
coap_address_t remote
For re-transmission - where the node is going.
coap_session_t * session
the CoAP session
coap_pdu_t * pdu
the CoAP PDU to send
unsigned int timeout
the randomized timeout value
uint8_t is_mcast
Set if this is a queued mcast response.
struct coap_queue_t * next
coap_mid_t id
CoAP message id.
coap_tick_t t
when to send PDU for the next time
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Abstraction of resource that can be attached to coap_context_t.
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_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
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
volatile uint8_t max_token_checked
Check for max token size coap_ext_token_check_t.
uint8_t csm_not_seen
Set if timeout waiting for CSM.
unsigned ref_subscriptions
reference count of current subscriptions
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
uint8_t doing_first
Set if doing client's first request.
uint8_t delay_recursive
Set if in coap_client_delay_first()
coap_socket_t sock
socket object for the session, if any
coap_pdu_t * partial_pdu
incomplete incoming pdu
uint32_t max_token_size
Largest token size supported RFC8974.
coap_bin_const_t * psk_identity
If client, this field contains the current identity for server; When this field is NULL,...
coap_session_state_t state
current state of relationship with peer
uint8_t csm_bert_rem_support
CSM TCP BERT blocks supported (remote)
uint8_t client_initiated
Session initially started as a client.
coap_digest_t cached_pdu_cksum
Checksum of last CON request PDU.
coap_mid_t remote_test_mid
mid used for checking remote support
uint8_t read_header[8]
storage space for header of incoming message header
unsigned ref_proxy_subs
reference count of current proxy subscriptions
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
unsigned ref
reference count from queues
coap_response_t last_con_handler_res
The result of calling the response handler of the last CON.
coap_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
coap_bin_const_t * last_token
uint8_t doing_send_recv
Set if coap_send_recv() active.
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
size_t partial_read
if > 0 indicates number of bytes already read for an incoming message
void * tls
security parameters
uint16_t max_retransmit
maximum re-transmit count (default 4)
uint8_t csm_block_supported
CSM TCP blocks supported.
uint8_t proxy_session
Set if this is an ongoing proxy session.
uint8_t con_active
Active CON request sent.
coap_queue_t * delayqueue
list of delayed messages waiting to be sent
uint32_t tx_rtag
Next Request-Tag number to use.
coap_mid_t last_ping_mid
the last keepalive message id that was used in this session
coap_lg_srcv_t * lg_srcv
Server list of expected large receives.
coap_bin_const_t * req_token
Token in request pdu of coap_send_recv()
coap_pdu_t * resp_pdu
PDU returned in coap_send_recv() call.
coap_lg_crcv_t * lg_crcv
Client list of expected large receives.
coap_mid_t last_con_mid
The last CON mid that has been been processed.
coap_session_type_t type
client or server side socket
coap_mid_t last_ack_mid
The last ACK mid that has been been processed.
coap_context_t * context
session's context
uint8_t session_failed
Set if session failed and can try re-connect.
size_t partial_write
if > 0 indicates number of bytes already written from the pdu at the head of sendqueue
coap_pdu_t * cached_pdu
Cached copy of last ACK response PDU.
coap_bin_const_t * echo
last token used to make a request
coap_layer_func_t lfunc[COAP_LAYER_LAST]
Layer functions to use.
coap_session_t * session
Used to determine session owner.
coap_endpoint_t * endpoint
Used by the epoll logic for a listening endpoint.
coap_address_t mcast_addr
remote address and port (multicast track)
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values
CoAP string data definition with const data.
Definition coap_str.h:49
const uint8_t * s
read-only string data
Definition coap_str.h:51
size_t length
length of string
Definition coap_str.h:50
CoAP string data definition.
Definition coap_str.h:41
uint8_t * s
string data
Definition coap_str.h:43
size_t length
length of string
Definition coap_str.h:42
Number of notifications that may be sent non-confirmable before a confirmable message is sent to dete...
struct coap_session_t * session
subscriber session
coap_pdu_t * pdu
cache_key to identify requester
Representation of parsed URI.
Definition coap_uri.h:72
coap_str_const_t host
The host part of the URI.
Definition coap_uri.h:73