libcoap 4.3.5-develop-08ae1a7
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 coap_lock_callback(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
1347/*
1348 * Return: 0 Something failed
1349 * 1 Success
1350 */
1351int
1353#if COAP_CLIENT_SUPPORT
1354 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1355 int timeout_ms = 5000;
1356 coap_session_state_t current_state = session->state;
1357
1358 if (session->delay_recursive) {
1359 return 0;
1360 } else {
1361 session->delay_recursive = 1;
1362 }
1363 /*
1364 * Need to wait for first request to get out and response back before
1365 * continuing.. Response handler has to clear doing_first if not an error.
1366 */
1368 while (session->doing_first != 0) {
1369 int result = coap_io_process_lkd(session->context, 1000);
1370
1371 if (result < 0) {
1372 coap_reset_doing_first(session);
1373 session->delay_recursive = 0;
1374 coap_session_release_lkd(session);
1375 return 0;
1376 }
1377
1378 /* coap_io_process_lkd() may have updated session state */
1379 if (session->state == COAP_SESSION_STATE_CSM &&
1380 current_state != COAP_SESSION_STATE_CSM) {
1381 /* Update timeout and restart the clock for CSM timeout */
1382 current_state = COAP_SESSION_STATE_CSM;
1383 timeout_ms = session->context->csm_timeout_ms;
1384 result = 0;
1385 }
1386
1387 if (result < timeout_ms) {
1388 timeout_ms -= result;
1389 } else {
1390 if (session->doing_first == 1) {
1391 /* Timeout failure of some sort with first request */
1392 if (session->state == COAP_SESSION_STATE_CSM) {
1393 coap_log_debug("** %s: timeout waiting for CSM response\n",
1394 coap_session_str(session));
1395 session->csm_not_seen = 1;
1396 } else {
1397 coap_log_debug("** %s: timeout waiting for first response\n",
1398 coap_session_str(session));
1399 }
1400 coap_reset_doing_first(session);
1401 coap_session_connected(session);
1402 }
1403 }
1404 }
1405 session->delay_recursive = 0;
1406 coap_session_release_lkd(session);
1407 }
1408#else /* ! COAP_CLIENT_SUPPORT */
1409 (void)session;
1410#endif /* ! COAP_CLIENT_SUPPORT */
1411 return 1;
1412}
1413
1414/*
1415 * return 0 Invalid
1416 * 1 Valid
1417 */
1418int
1420
1421 /* Check validity of sending code */
1422 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1423 case 0: /* Empty or request */
1424 case 2: /* Success */
1425 case 3: /* Reserved for future use */
1426 case 4: /* Client error */
1427 case 5: /* Server error */
1428 break;
1429 case 7: /* Reliable signalling */
1430 if (COAP_PROTO_RELIABLE(session->proto))
1431 break;
1432 /* Not valid if UDP */
1433 /* Fall through */
1434 case 1: /* Invalid */
1435 case 6: /* Invalid */
1436 default:
1437 return 0;
1438 }
1439 return 1;
1440}
1441
1442#if COAP_CLIENT_SUPPORT
1443/*
1444 * If type is CON and protocol is not reliable, there is no need to set up
1445 * lg_crcv if it can be built up based on sent PDU if there is a
1446 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1447 * (Q-)Block1.
1448 */
1449static int
1450coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1451 coap_opt_iterator_t opt_iter;
1452
1453 if (!COAP_PDU_IS_REQUEST(pdu))
1454 return 0;
1455
1456 if (
1457#if COAP_OSCORE_SUPPORT
1458 session->oscore_encryption ||
1459#endif /* COAP_OSCORE_SUPPORT */
1460 pdu->type == COAP_MESSAGE_NON ||
1461 COAP_PROTO_RELIABLE(session->proto) ||
1462 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1463#if COAP_Q_BLOCK_SUPPORT
1464 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1465#endif /* COAP_Q_BLOCK_SUPPORT */
1466 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1467 return 1;
1468 }
1469 return 0;
1470}
1471#endif /* COAP_CLIENT_SUPPORT */
1472
1475 coap_mid_t mid;
1476
1478 mid = coap_send_lkd(session, pdu);
1480 return mid;
1481}
1482
1486#if COAP_CLIENT_SUPPORT
1487 coap_lg_crcv_t *lg_crcv = NULL;
1488 coap_opt_iterator_t opt_iter;
1489 coap_block_b_t block;
1490 int observe_action = -1;
1491 int have_block1 = 0;
1492 coap_opt_t *opt;
1493#endif /* COAP_CLIENT_SUPPORT */
1494
1495 assert(pdu);
1496
1498
1499 /* Check validity of sending code */
1500 if (!coap_check_code_class(session, pdu)) {
1501 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1503 pdu->code & 0x1f);
1504 goto error;
1505 }
1506 pdu->session = session;
1507#if COAP_CLIENT_SUPPORT
1508 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1509 !coap_netif_available(session) && !session->session_failed) {
1510 coap_log_debug("coap_send: Socket closed\n");
1511 goto error;
1512 }
1513
1514 if (session->doing_first) {
1515 LL_APPEND(session->doing_first_pdu, pdu);
1517 coap_log_debug("** %s: mid=0x%04x: queued\n",
1518 coap_session_str(session), pdu->mid);
1519 return pdu->mid;
1520 }
1521
1522 /* Indicate support for Extended Tokens if appropriate */
1523 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1525 session->type == COAP_SESSION_TYPE_CLIENT &&
1526 COAP_PDU_IS_REQUEST(pdu)) {
1527 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1528 /*
1529 * When the pass / fail response for Extended Token is received, this PDU
1530 * will get transmitted.
1531 */
1532 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1533 goto error;
1534 }
1535 }
1536 /*
1537 * For reliable protocols, this will get cleared after CSM exchanged
1538 * in coap_session_connected() where Token size support is indicated in the CSM.
1539 */
1540 session->doing_first = 1;
1542 LL_PREPEND(session->doing_first_pdu, pdu);
1543 if (session->proto != COAP_PROTO_UDP) {
1544 /* In case the next handshake / CSM is already in */
1546 }
1547 /*
1548 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1549 * will get called again.
1550 */
1552 coap_log_debug("** %s: mid=0x%04x: queued\n",
1553 coap_session_str(session), pdu->mid);
1554 return pdu->mid;
1555 }
1556#if COAP_Q_BLOCK_SUPPORT
1557 /* Indicate support for Q-Block if appropriate */
1558 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1559 session->type == COAP_SESSION_TYPE_CLIENT &&
1560 COAP_PDU_IS_REQUEST(pdu)) {
1561 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1562 goto error;
1563 }
1564 session->doing_first = 1;
1566 LL_PREPEND(session->doing_first_pdu, pdu);
1567 if (session->proto != COAP_PROTO_UDP) {
1568 /* In case the next handshake / CSM is already in */
1570 }
1571 /*
1572 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1573 * will get called again.
1574 */
1576 coap_log_debug("** %s: mid=0x%04x: queued\n",
1577 coap_session_str(session), pdu->mid);
1578 return pdu->mid;
1579 }
1580#endif /* COAP_Q_BLOCK_SUPPORT */
1581
1582 /*
1583 * Check validity of token length
1584 */
1585 if (COAP_PDU_IS_REQUEST(pdu) &&
1586 pdu->actual_token.length > session->max_token_size) {
1587 coap_log_warn("coap_send: PDU dropped as token too long (%" PRIuS " > %" PRIu32 ")\n",
1588 pdu->actual_token.length, session->max_token_size);
1589 goto error;
1590 }
1591
1592 /* A lot of the reliable code assumes type is CON */
1593 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1594 pdu->type = COAP_MESSAGE_CON;
1595
1596#if COAP_OSCORE_SUPPORT
1597 if (session->oscore_encryption) {
1598 if (session->recipient_ctx->initial_state == 1) {
1599 /*
1600 * Not sure if remote supports OSCORE, or is going to send us a
1601 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1602 * is OK. Continue sending current pdu to test things.
1603 */
1604 session->doing_first = 1;
1605 }
1606 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1608 goto error;
1609 }
1610 }
1611#endif /* COAP_OSCORE_SUPPORT */
1612
1613 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1614 return coap_send_internal(session, pdu, NULL);
1615 }
1616
1617 if (COAP_PDU_IS_REQUEST(pdu)) {
1618 uint8_t buf[4];
1619
1620 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1621
1622 if (opt) {
1623 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1624 coap_opt_length(opt));
1625 }
1626
1627 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1628 (block.m == 1 || block.bert == 1)) {
1629 have_block1 = 1;
1630 }
1631#if COAP_Q_BLOCK_SUPPORT
1632 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1633 (block.m == 1 || block.bert == 1)) {
1634 if (have_block1) {
1635 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1637 }
1638 have_block1 = 1;
1639 }
1640#endif /* COAP_Q_BLOCK_SUPPORT */
1641 if (observe_action != COAP_OBSERVE_CANCEL) {
1642 /* Warn about re-use of tokens */
1643 if (session->last_token &&
1644 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1646 char scratch[24];
1647 size_t size;
1648 size_t i;
1649
1650 scratch[0] = '\000';
1651 for (i = 0; i < pdu->actual_token.length; i++) {
1652 size = strlen(scratch);
1653 snprintf(&scratch[size], sizeof(scratch)-size,
1654 "%02x", pdu->actual_token.s[i]);
1655 }
1656 coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1657 scratch);
1658 }
1659 }
1662 pdu->actual_token.length);
1663 } else {
1664 /* observe_action == COAP_OBSERVE_CANCEL */
1665 coap_binary_t tmp;
1666 int ret;
1667
1668 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1669 /* Unfortunately need to change the ptr type to be r/w */
1670 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1671 tmp.length = pdu->actual_token.length;
1672 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1673 if (ret == 1) {
1674 /* Observe Cancel successfully sent */
1676 return ret;
1677 }
1678 /* Some mismatch somewhere - continue to send original packet */
1679 }
1680 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1681 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1685 coap_encode_var_safe(buf, sizeof(buf),
1686 ++session->tx_rtag),
1687 buf);
1688 } else {
1689 memset(&block, 0, sizeof(block));
1690 }
1691
1692#if COAP_Q_BLOCK_SUPPORT
1693 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1694#endif /* COAP_Q_BLOCK_SUPPORT */
1695 {
1696 /* Need to check if we need to reset Q-Block to Block */
1697 uint8_t buf[4];
1698
1699 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1702 coap_encode_var_safe(buf, sizeof(buf),
1703 (block.num << 4) | (0 << 3) | block.szx),
1704 buf);
1705 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1706 /* Need to update associated lg_xmit */
1707 coap_lg_xmit_t *lg_xmit;
1708
1709 LL_FOREACH(session->lg_xmit, lg_xmit) {
1710 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1711 lg_xmit->b.b1.app_token &&
1712 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1713 /* Update the skeletal PDU with the block1 option */
1716 coap_encode_var_safe(buf, sizeof(buf),
1717 (block.num << 4) | (0 << 3) | block.szx),
1718 buf);
1719 break;
1720 }
1721 }
1722 }
1723 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1726 coap_encode_var_safe(buf, sizeof(buf),
1727 (block.num << 4) | (block.m << 3) | block.szx),
1728 buf);
1729 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1730 /* Need to update associated lg_xmit */
1731 coap_lg_xmit_t *lg_xmit;
1732
1733 LL_FOREACH(session->lg_xmit, lg_xmit) {
1734 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1735 lg_xmit->b.b1.app_token &&
1736 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1737 /* Update the skeletal PDU with the block1 option */
1740 coap_encode_var_safe(buf, sizeof(buf),
1741 (block.num << 4) |
1742 (block.m << 3) |
1743 block.szx),
1744 buf);
1745 /* Update as this is a Request */
1746 lg_xmit->option = COAP_OPTION_BLOCK1;
1747 break;
1748 }
1749 }
1750 }
1751 }
1752
1753#if COAP_Q_BLOCK_SUPPORT
1754 if (COAP_PDU_IS_REQUEST(pdu) &&
1755 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1756 if (block.num == 0 && block.m == 0) {
1757 uint8_t buf[4];
1758
1759 /* M needs to be set as asking for all the blocks */
1761 coap_encode_var_safe(buf, sizeof(buf),
1762 (0 << 4) | (1 << 3) | block.szx),
1763 buf);
1764 }
1765 }
1766#endif /* COAP_Q_BLOCK_SUPPORT */
1767
1768 /*
1769 * If type is CON and protocol is not reliable, there is no need to set up
1770 * lg_crcv here as it can be built up based on sent PDU if there is a
1771 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1772 * (Q-)Block1.
1773 */
1774 if (coap_check_send_need_lg_crcv(session, pdu)) {
1775 coap_lg_xmit_t *lg_xmit = NULL;
1776
1777 if (!session->lg_xmit && have_block1) {
1778 coap_log_debug("PDU presented by app\n");
1780 }
1781 /* See if this token is already in use for large body responses */
1782 LL_FOREACH(session->lg_crcv, lg_crcv) {
1783 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1784 /* Need to terminate and clean up previous response setup */
1785 LL_DELETE(session->lg_crcv, lg_crcv);
1786 coap_block_delete_lg_crcv(session, lg_crcv);
1787 break;
1788 }
1789 }
1790
1791 if (have_block1 && session->lg_xmit) {
1792 LL_FOREACH(session->lg_xmit, lg_xmit) {
1793 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1794 lg_xmit->b.b1.app_token &&
1795 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1796 break;
1797 }
1798 }
1799 }
1800 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1801 if (lg_crcv == NULL) {
1802 goto error;
1803 }
1804 if (lg_xmit) {
1805 /* Need to update the token as set up in the session->lg_xmit */
1806 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1807 }
1808 }
1809 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1810 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1811
1812#if COAP_Q_BLOCK_SUPPORT
1813 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1814 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1815 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1816 } else
1817#endif /* COAP_Q_BLOCK_SUPPORT */
1818 mid = coap_send_internal(session, pdu, NULL);
1819#else /* !COAP_CLIENT_SUPPORT */
1820 mid = coap_send_internal(session, pdu, NULL);
1821#endif /* !COAP_CLIENT_SUPPORT */
1822#if COAP_CLIENT_SUPPORT
1823 if (lg_crcv) {
1824 if (mid != COAP_INVALID_MID) {
1825 LL_PREPEND(session->lg_crcv, lg_crcv);
1826 } else {
1827 coap_block_delete_lg_crcv(session, lg_crcv);
1828 }
1829 }
1830#endif /* COAP_CLIENT_SUPPORT */
1831 return mid;
1832
1833error:
1835 return COAP_INVALID_MID;
1836}
1837
1838#if COAP_SERVER_SUPPORT
1839static int
1840coap_pdu_cksum(const coap_pdu_t *pdu, coap_digest_t *digest_buffer) {
1841 coap_digest_ctx_t *digest_ctx = coap_digest_setup();
1842
1843 if (!digest_ctx || !pdu) {
1844 goto fail;
1845 }
1846 if (pdu->used_size && pdu->token) {
1847 if (!coap_digest_update(digest_ctx, pdu->token, pdu->used_size)) {
1848 goto fail;
1849 }
1850 }
1851 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->type, sizeof(pdu->type))) {
1852 goto fail;
1853 }
1854 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->code, sizeof(pdu->code))) {
1855 goto fail;
1856 }
1857 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->mid, sizeof(pdu->mid))) {
1858 goto fail;
1859 }
1860 if (!coap_digest_final(digest_ctx, digest_buffer))
1861 return 0;
1862
1863 return 1;
1864
1865fail:
1866 coap_digest_free(digest_ctx);
1867 return 0;
1868}
1869#endif /* COAP_SERVER_SUPPORT */
1870
1873 uint8_t r;
1874 ssize_t bytes_written;
1875 coap_opt_iterator_t opt_iter;
1876
1877#if ! COAP_SERVER_SUPPORT
1878 (void)request_pdu;
1879#endif /* COAP_SERVER_SUPPORT */
1880 pdu->session = session;
1881#if COAP_CLIENT_SUPPORT
1882 if (session->session_failed) {
1883 coap_session_reconnect(session);
1884 if (session->session_failed)
1885 goto error;
1886 }
1887#endif /* COAP_CLIENT_SUPPORT */
1888#if COAP_PROXY_SUPPORT
1889 if (session->server_list) {
1890 /* Local session wanting to use proxy logic */
1891 return coap_proxy_local_write(session, pdu);
1892 }
1893#endif /* COAP_PROXY_SUPPORT */
1894 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1895 /*
1896 * Need to prepend our IP identifier to the data as per
1897 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1898 */
1899 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1900 coap_opt_t *opt;
1901 size_t hop_limit;
1902
1903 addr_str[sizeof(addr_str)-1] = '\000';
1904 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1905 sizeof(addr_str) - 1)) {
1906 char *cp;
1907 size_t len;
1908
1909 if (addr_str[0] == '[') {
1910 cp = strchr(addr_str, ']');
1911 if (cp)
1912 *cp = '\000';
1913 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1914 /* IPv4 embedded into IPv6 */
1915 cp = &addr_str[8];
1916 } else {
1917 cp = &addr_str[1];
1918 }
1919 } else {
1920 cp = strchr(addr_str, ':');
1921 if (cp)
1922 *cp = '\000';
1923 cp = addr_str;
1924 }
1925 len = strlen(cp);
1926
1927 /* See if Hop Limit option is being used in return path */
1928 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1929 if (opt) {
1930 uint8_t buf[4];
1931
1932 hop_limit =
1934 if (hop_limit == 1) {
1935 coap_log_warn("Proxy loop detected '%s'\n",
1936 (char *)pdu->data);
1939 } else if (hop_limit < 1 || hop_limit > 255) {
1940 /* Something is bad - need to drop this pdu (TODO or delete option) */
1941 coap_log_warn("Proxy return has bad hop limit count '%" PRIuS "'\n",
1942 hop_limit);
1945 }
1946 hop_limit--;
1948 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1949 buf);
1950 }
1951
1952 /* Need to check that we are not seeing this proxy in the return loop */
1953 if (pdu->data && opt == NULL) {
1954 char *a_match;
1955 size_t data_len;
1956
1957 if (pdu->used_size + 1 > pdu->max_size) {
1958 /* No space */
1961 }
1962 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1963 /* Internal error */
1966 }
1967 data_len = pdu->used_size - (pdu->data - pdu->token);
1968 pdu->data[data_len] = '\000';
1969 a_match = strstr((char *)pdu->data, cp);
1970 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1971 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1972 a_match[len] == ' ')) {
1973 coap_log_warn("Proxy loop detected '%s'\n",
1974 (char *)pdu->data);
1977 }
1978 }
1979 if (pdu->used_size + len + 1 <= pdu->max_size) {
1980 size_t old_size = pdu->used_size;
1981 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1982 if (pdu->data == NULL) {
1983 /*
1984 * Set Hop Limit to max for return path. If this libcoap is in
1985 * a proxy loop path, it will always decrement hop limit in code
1986 * above and hence timeout / drop the response as appropriate
1987 */
1988 hop_limit = 255;
1990 (uint8_t *)&hop_limit);
1991 coap_add_data(pdu, len, (uint8_t *)cp);
1992 } else {
1993 /* prepend with space separator, leaving hop limit "as is" */
1994 memmove(pdu->data + len + 1, pdu->data,
1995 old_size - (pdu->data - pdu->token));
1996 memcpy(pdu->data, cp, len);
1997 pdu->data[len] = ' ';
1998 pdu->used_size += len + 1;
1999 }
2000 }
2001 }
2002 }
2003 }
2004
2005 if (session->echo) {
2006 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
2007 session->echo->s))
2008 goto error;
2009 coap_delete_bin_const(session->echo);
2010 session->echo = NULL;
2011 }
2012#if COAP_OSCORE_SUPPORT
2013 if (session->oscore_encryption) {
2014 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
2016 goto error;
2017 }
2018#endif /* COAP_OSCORE_SUPPORT */
2019
2020 if (!coap_pdu_encode_header(pdu, session->proto)) {
2021 goto error;
2022 }
2023
2024#if !COAP_DISABLE_TCP
2025 if (COAP_PROTO_RELIABLE(session->proto) &&
2027 if (!session->csm_block_supported) {
2028 /*
2029 * Need to check that this instance is not sending any block options as
2030 * the remote end via CSM has not informed us that there is support
2031 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2032 * This includes potential BERT blocks.
2033 */
2034 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2035 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2036 }
2037 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2038 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2039 }
2040 } else if (!session->csm_bert_rem_support) {
2041 coap_opt_t *opt;
2042
2043 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2044 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2045 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2046 }
2047 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2048 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2049 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2050 }
2051 }
2052 }
2053#endif /* !COAP_DISABLE_TCP */
2054
2055#if COAP_OSCORE_SUPPORT
2056 if (session->oscore_encryption &&
2057 pdu->type != COAP_MESSAGE_RST &&
2058 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2059 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2060 /* Refactor PDU as appropriate RFC8613 */
2061 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2062
2063 if (osc_pdu == NULL) {
2064 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2067 goto error;
2068 }
2069 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2071 pdu = osc_pdu;
2072 } else
2073#endif /* COAP_OSCORE_SUPPORT */
2074 bytes_written = coap_send_pdu(session, pdu, NULL);
2075
2076#if COAP_SERVER_SUPPORT
2077 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
2078 session->cached_pdu != pdu &&
2079 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2080 COAP_PDU_IS_REQUEST(request_pdu) &&
2081 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2083 session->cached_pdu = pdu;
2085 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
2086 }
2087#endif /* COAP_SERVER_SUPPORT */
2088
2089 if (bytes_written == COAP_PDU_DELAYED) {
2090 /* do not free pdu as it is stored with session for later use */
2091 return pdu->mid;
2092 }
2093 if (bytes_written < 0) {
2095 goto error;
2096 }
2097
2098#if !COAP_DISABLE_TCP
2099 if (COAP_PROTO_RELIABLE(session->proto) &&
2100 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2101 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2102 session->partial_write = (size_t)bytes_written;
2103 /* do not free pdu as it is stored with session for later use */
2104 return pdu->mid;
2105 } else {
2106 goto error;
2107 }
2108 }
2109#endif /* !COAP_DISABLE_TCP */
2110
2111 if (pdu->type != COAP_MESSAGE_CON
2112 || COAP_PROTO_RELIABLE(session->proto)) {
2113 coap_mid_t id = pdu->mid;
2115 return id;
2116 }
2117
2118 coap_queue_t *node = coap_new_node();
2119 if (!node) {
2120 coap_log_debug("coap_wait_ack: insufficient memory\n");
2121 goto error;
2122 }
2123
2124 node->id = pdu->mid;
2125 node->pdu = pdu;
2126 coap_prng_lkd(&r, sizeof(r));
2127 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2128 node->timeout = coap_calc_timeout(session, r);
2129 return coap_wait_ack(session->context, session, node);
2130error:
2132 return COAP_INVALID_MID;
2133}
2134
2135static int send_recv_terminate = 0;
2136
2137void
2141
2142COAP_API int
2144 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2145 int ret;
2146
2147 coap_lock_lock(return 0);
2148 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2150 return ret;
2151}
2152
2153/*
2154 * Return 0 or +ve Time in function in ms after successful transfer
2155 * -1 Invalid timeout parameter
2156 * -2 Failed to transmit PDU
2157 * -3 Nack or Event handler invoked, cancelling request
2158 * -4 coap_io_process returned error (fail to re-lock or select())
2159 * -5 Response not received in the given time
2160 * -6 Terminated by user
2161 * -7 Client mode code not enabled
2162 */
2163int
2165 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2166#if COAP_CLIENT_SUPPORT
2168 uint32_t rem_timeout = timeout_ms;
2169 uint32_t block_mode = session->block_mode;
2170 int ret = 0;
2171 coap_tick_t now;
2172 coap_tick_t start;
2173 coap_tick_t ticks_so_far;
2174 uint32_t time_so_far_ms;
2175
2176 coap_ticks(&start);
2177 assert(request_pdu);
2178
2180
2181 session->resp_pdu = NULL;
2182 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2183 request_pdu->actual_token.length);
2184
2185 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2186 ret = -1;
2187 goto fail;
2188 }
2189 if (session->state == COAP_SESSION_STATE_NONE) {
2190 ret = -3;
2191 goto fail;
2192 }
2193
2195 if (coap_is_mcast(&session->addr_info.remote))
2196 block_mode = session->block_mode;
2197
2198 session->doing_send_recv = 1;
2199 /* So the user needs to delete the PDU */
2200 coap_pdu_reference_lkd(request_pdu);
2201 mid = coap_send_lkd(session, request_pdu);
2202 if (mid == COAP_INVALID_MID) {
2203 if (!session->doing_send_recv)
2204 ret = -3;
2205 else
2206 ret = -2;
2207 goto fail;
2208 }
2209
2210 /* Wait for the response to come in */
2211 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2212 if (send_recv_terminate) {
2213 ret = -6;
2214 goto fail;
2215 }
2216 ret = coap_io_process_lkd(session->context, rem_timeout);
2217 if (ret < 0) {
2218 ret = -4;
2219 goto fail;
2220 }
2221 /* timeout_ms is for timeout between specific request and response */
2222 coap_ticks(&now);
2223 ticks_so_far = now - session->last_rx_tx;
2224 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2225 if (time_so_far_ms >= timeout_ms) {
2226 rem_timeout = 0;
2227 } else {
2228 rem_timeout = timeout_ms - time_so_far_ms;
2229 }
2230 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2231 /* To pick up on (D)TLS setup issues */
2232 coap_ticks(&now);
2233 ticks_so_far = now - start;
2234 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2235 if (time_so_far_ms >= timeout_ms) {
2236 rem_timeout = 0;
2237 } else {
2238 rem_timeout = timeout_ms - time_so_far_ms;
2239 }
2240 }
2241 }
2242
2243 if (rem_timeout) {
2244 coap_ticks(&now);
2245 ticks_so_far = now - start;
2246 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2247 ret = time_so_far_ms;
2248 /* Give PDU to user who will be calling coap_delete_pdu() */
2249 *response_pdu = session->resp_pdu;
2250 session->resp_pdu = NULL;
2251 if (*response_pdu == NULL) {
2252 ret = -3;
2253 }
2254 } else {
2255 /* If there is a resp_pdu, it will get cleared below */
2256 ret = -5;
2257 }
2258
2259fail:
2260 session->block_mode = block_mode;
2261 session->doing_send_recv = 0;
2262 /* delete referenced copy */
2263 coap_delete_pdu_lkd(session->resp_pdu);
2264 session->resp_pdu = NULL;
2266 session->req_token = NULL;
2267 return ret;
2268
2269#else /* !COAP_CLIENT_SUPPORT */
2270
2271 (void)session;
2272 (void)timeout_ms;
2273 (void)request_pdu;
2274 coap_log_warn("coap_send_recv: Client mode not supported\n");
2275 *response_pdu = NULL;
2276 return -7;
2277
2278#endif /* ! COAP_CLIENT_SUPPORT */
2279}
2280
2283 if (!context || !node || !node->session)
2284 return COAP_INVALID_MID;
2285
2286#if COAP_CLIENT_SUPPORT
2287 if (node->session->session_failed) {
2288 /* Force failure */
2289 node->retransmit_cnt = (unsigned char)node->session->max_retransmit;
2290 }
2291#endif /* COAP_CLIENT_SUPPORT */
2292
2293 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2294 if (node->retransmit_cnt < node->session->max_retransmit) {
2295 ssize_t bytes_written;
2296 coap_tick_t now;
2297 coap_tick_t next_delay;
2298 coap_address_t remote;
2299
2300 node->retransmit_cnt++;
2302
2303 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2304 if (context->ping_timeout &&
2305 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2306 uint8_t byte;
2307
2308 coap_prng_lkd(&byte, sizeof(byte));
2309 /* Don't exceed the ping timeout value */
2310 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2311 }
2312
2313 coap_ticks(&now);
2314 if (context->sendqueue == NULL) {
2315 node->t = next_delay;
2316 context->sendqueue_basetime = now;
2317 } else {
2318 /* make node->t relative to context->sendqueue_basetime */
2319 node->t = (now - context->sendqueue_basetime) + next_delay;
2320 }
2321 coap_insert_node(&context->sendqueue, node);
2322 coap_address_copy(&remote, &node->session->addr_info.remote);
2324
2325 if (node->is_mcast) {
2326 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2327 coap_session_str(node->session), node->id);
2328 } else {
2329 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2330 coap_session_str(node->session), node->id,
2331 node->retransmit_cnt,
2332 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2333 }
2334
2335 if (node->session->con_active)
2336 node->session->con_active--;
2337 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2338
2339 if (bytes_written == COAP_PDU_DELAYED) {
2340 /* PDU was not retransmitted immediately because a new handshake is
2341 in progress. node was moved to the send queue of the session. */
2342 return node->id;
2343 }
2344
2345 coap_address_copy(&node->session->addr_info.remote, &remote);
2346 if (node->is_mcast) {
2349 return COAP_INVALID_MID;
2350 }
2351
2352 if (bytes_written < 0)
2353 return (int)bytes_written;
2354
2355 return node->id;
2356 }
2357
2358#if COAP_CLIENT_SUPPORT
2359 if (node->session->session_failed) {
2360 coap_log_info("** %s: mid=0x%04x: deleted due to reconnection issue\n",
2361 coap_session_str(node->session), node->id);
2362 } else {
2363#endif /* COAP_CLIENT_SUPPORT */
2364 /* no more retransmissions, remove node from system */
2365 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2366 coap_session_str(node->session), node->id, node->retransmit_cnt);
2367#if COAP_CLIENT_SUPPORT
2368 }
2369#endif /* COAP_CLIENT_SUPPORT */
2370
2371#if COAP_SERVER_SUPPORT
2372 /* Check if subscriptions exist that should be canceled after
2373 COAP_OBS_MAX_FAIL */
2374 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2375 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2376 if (context->ping_timeout) {
2379 return COAP_INVALID_MID;
2380 } else {
2381 if (node->session->ref_subscriptions)
2382 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2383#if COAP_PROXY_SUPPORT
2384 /* Need to check is there is a proxy subscription active and delete it */
2385 if (node->session->ref_proxy_subs)
2386 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2387 0, COAP_PROXY_SUBS_TOKEN);
2388#endif /* COAP_PROXY_SUPPORT */
2389 }
2390 }
2391#endif /* COAP_SERVER_SUPPORT */
2392 if (node->session->con_active) {
2393 node->session->con_active--;
2395 /*
2396 * As there may be another CON in a different queue entry on the same
2397 * session that needs to be immediately released,
2398 * coap_session_connected() is called.
2399 * However, there is the possibility coap_wait_ack() may be called for
2400 * this node (queue) and re-added to context->sendqueue.
2401 * coap_delete_node_lkd(node) called shortly will handle this and
2402 * remove it.
2403 */
2405 }
2406 }
2407
2408 if (node->pdu->type == COAP_MESSAGE_CON) {
2410 }
2411#if COAP_CLIENT_SUPPORT
2412 node->session->doing_send_recv = 0;
2413#endif /* COAP_CLIENT_SUPPORT */
2414 /* And finally delete the node */
2416 return COAP_INVALID_MID;
2417}
2418
2419static int
2421 uint8_t *data;
2422 size_t data_len;
2423 int result = -1;
2424
2425 coap_packet_get_memmapped(packet, &data, &data_len);
2426 if (session->proto == COAP_PROTO_DTLS) {
2427#if COAP_SERVER_SUPPORT
2428 if (session->type == COAP_SESSION_TYPE_HELLO)
2429 result = coap_dtls_hello(session, data, data_len);
2430 else
2431#endif /* COAP_SERVER_SUPPORT */
2432 if (session->tls)
2433 result = coap_dtls_receive(session, data, data_len);
2434 } else if (session->proto == COAP_PROTO_UDP) {
2435 result = coap_handle_dgram(ctx, session, data, data_len);
2436 }
2437 return result;
2438}
2439
2440#if COAP_CLIENT_SUPPORT
2441void
2443#if COAP_DISABLE_TCP
2444 (void)now;
2445
2447#else /* !COAP_DISABLE_TCP */
2448 if (coap_netif_strm_connect2(session)) {
2449 session->last_rx_tx = now;
2451 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2452 } else {
2455 }
2456#endif /* !COAP_DISABLE_TCP */
2457}
2458#endif /* COAP_CLIENT_SUPPORT */
2459
2460static void
2462 (void)ctx;
2463 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2464
2465 while (session->delayqueue) {
2466 ssize_t bytes_written;
2467 coap_queue_t *q = session->delayqueue;
2468
2469 coap_address_copy(&session->addr_info.remote, &q->remote);
2470 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2471 coap_session_str(session), (int)q->pdu->mid);
2472 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2473 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2474 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2475 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2476 if (bytes_written > 0)
2477 session->last_rx_tx = now;
2478 if (bytes_written <= 0 ||
2479 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2480 if (bytes_written > 0)
2481 session->partial_write += (size_t)bytes_written;
2482 break;
2483 }
2484 session->delayqueue = q->next;
2485 session->partial_write = 0;
2487 }
2488}
2489
2490void
2492#if COAP_CONSTRAINED_STACK
2493 /* payload and packet can be protected by global_lock if needed */
2494 static unsigned char payload[COAP_RXBUFFER_SIZE];
2495 static coap_packet_t s_packet;
2496#else /* ! COAP_CONSTRAINED_STACK */
2497 unsigned char payload[COAP_RXBUFFER_SIZE];
2498 coap_packet_t s_packet;
2499#endif /* ! COAP_CONSTRAINED_STACK */
2500 coap_packet_t *packet = &s_packet;
2501
2503
2504 packet->length = sizeof(payload);
2505 packet->payload = payload;
2506
2507 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2508 ssize_t bytes_read;
2509 coap_address_t remote;
2510
2511 coap_address_copy(&remote, &session->addr_info.remote);
2512 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2513 bytes_read = coap_netif_dgrm_read(session, packet);
2514
2515 if (bytes_read < 0) {
2516 if (bytes_read == -2) {
2517 coap_address_copy(&session->addr_info.remote, &remote);
2518 /* Reset the session back to startup defaults */
2520 }
2521 } else if (bytes_read > 0) {
2522 session->last_rx_tx = now;
2523#if COAP_CLIENT_SUPPORT
2524 if (session->session_failed) {
2525 session->session_failed = 0;
2527 }
2528#endif /* COAP_CLIENT_SUPPORT */
2529 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2530 coap_handle_dgram_for_proto(ctx, session, packet);
2531 } else {
2532 coap_address_copy(&session->addr_info.remote, &remote);
2533 }
2534#if !COAP_DISABLE_TCP
2535 } else if (session->proto == COAP_PROTO_WS ||
2536 session->proto == COAP_PROTO_WSS) {
2537 ssize_t bytes_read = 0;
2538
2539 /* WebSocket layer passes us the whole packet */
2540 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2541 packet->payload,
2542 packet->length);
2543 if (bytes_read < 0) {
2545 } else if (bytes_read > 2) {
2546 coap_pdu_t *pdu;
2547
2548 session->last_rx_tx = now;
2549 /* Need max space incase PDU is updated with updated token etc. */
2550 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2551 if (!pdu) {
2552 return;
2553 }
2554
2555 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2557 coap_log_warn("discard malformed PDU\n");
2559 return;
2560 }
2561
2562 coap_dispatch(ctx, session, pdu);
2564 return;
2565 }
2566 } else {
2567 ssize_t bytes_read = 0;
2568 const uint8_t *p;
2569 int retry;
2570
2571 do {
2572 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2573 packet->payload,
2574 packet->length);
2575 if (bytes_read > 0) {
2576 session->last_rx_tx = now;
2577 }
2578 p = packet->payload;
2579 retry = bytes_read == (ssize_t)packet->length;
2580 while (bytes_read > 0) {
2581 if (session->partial_pdu) {
2582 size_t len = session->partial_pdu->used_size
2583 + session->partial_pdu->hdr_size
2584 - session->partial_read;
2585 size_t n = min(len, (size_t)bytes_read);
2586 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2587 + session->partial_read, p, n);
2588 p += n;
2589 bytes_read -= n;
2590 if (n == len) {
2591 coap_opt_filter_t error_opts;
2592 coap_pdu_t *pdu = session->partial_pdu;
2593
2594 session->partial_pdu = NULL;
2595 session->partial_read = 0;
2596
2597 coap_option_filter_clear(&error_opts);
2598 if (coap_pdu_parse_header(pdu, session->proto)
2599 && coap_pdu_parse_opt(pdu, &error_opts)) {
2600 coap_dispatch(ctx, session, pdu);
2601 } else if (error_opts.mask) {
2602 coap_pdu_t *response =
2604 COAP_RESPONSE_CODE(402), &error_opts);
2605 if (!response) {
2606 coap_log_warn("coap_read_session: cannot create error response\n");
2607 } else {
2608 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2609 coap_log_warn("coap_read_session: error sending response\n");
2610 }
2611 }
2613 } else {
2614 session->partial_read += n;
2615 }
2616 } else if (session->partial_read > 0) {
2617 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2618 session->read_header);
2619 size_t tkl = session->read_header[0] & 0x0f;
2620 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2621 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2622 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2623 size_t n = min(len, (size_t)bytes_read);
2624 memcpy(session->read_header + session->partial_read, p, n);
2625 p += n;
2626 bytes_read -= n;
2627 if (n == len) {
2628 /* Header now all in */
2629 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2630 hdr_size + tok_ext_bytes);
2631 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2632 coap_log_warn("** %s: incoming PDU length too large (%" PRIuS " > %lu)\n",
2633 coap_session_str(session),
2634 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2635 bytes_read = -1;
2636 break;
2637 }
2638 /* Need max space incase PDU is updated with updated token etc. */
2639 session->partial_pdu = coap_pdu_init(0, 0, 0,
2641 if (session->partial_pdu == NULL) {
2642 bytes_read = -1;
2643 break;
2644 }
2645 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2646 bytes_read = -1;
2647 break;
2648 }
2649 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2650 session->partial_pdu->used_size = size;
2651 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2652 session->partial_read = hdr_size + tok_ext_bytes;
2653 if (size == 0) {
2654 coap_pdu_t *pdu = session->partial_pdu;
2655
2656 session->partial_pdu = NULL;
2657 session->partial_read = 0;
2658 if (coap_pdu_parse_header(pdu, session->proto)) {
2659 coap_dispatch(ctx, session, pdu);
2660 }
2662 }
2663 } else {
2664 /* More of the header to go */
2665 session->partial_read += n;
2666 }
2667 } else {
2668 /* Get in first byte of the header */
2669 session->read_header[0] = *p++;
2670 bytes_read -= 1;
2671 if (!coap_pdu_parse_header_size(session->proto,
2672 session->read_header)) {
2673 bytes_read = -1;
2674 break;
2675 }
2676 session->partial_read = 1;
2677 }
2678 }
2679 } while (bytes_read == 0 && retry);
2680 if (bytes_read < 0)
2682#endif /* !COAP_DISABLE_TCP */
2683 }
2684}
2685
2686#if COAP_SERVER_SUPPORT
2687static int
2688coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2689 ssize_t bytes_read = -1;
2690 int result = -1; /* the value to be returned */
2691#if COAP_CONSTRAINED_STACK
2692 /* payload and e_packet can be protected by global_lock if needed */
2693 static unsigned char payload[COAP_RXBUFFER_SIZE];
2694 static coap_packet_t e_packet;
2695#else /* ! COAP_CONSTRAINED_STACK */
2696 unsigned char payload[COAP_RXBUFFER_SIZE];
2697 coap_packet_t e_packet;
2698#endif /* ! COAP_CONSTRAINED_STACK */
2699 coap_packet_t *packet = &e_packet;
2700
2701 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2702 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2703
2704 /* Need to do this as there may be holes in addr_info */
2705 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2706 packet->length = sizeof(payload);
2707 packet->payload = payload;
2709 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2710
2711 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2712 if (bytes_read < 0) {
2713 if (errno != EAGAIN) {
2714 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2715 }
2716 } else if (bytes_read > 0) {
2717 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2718 if (session) {
2720 coap_log_debug("* %s: netif: recv %4" PRIdS " bytes\n",
2721 coap_session_str(session), bytes_read);
2722 result = coap_handle_dgram_for_proto(ctx, session, packet);
2723 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2724 coap_session_new_dtls_session(session, now);
2725 coap_session_release_lkd(session);
2726 }
2727 }
2728 return result;
2729}
2730
2731static int
2732coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2733 (void)ctx;
2734 (void)endpoint;
2735 (void)now;
2736 return 0;
2737}
2738
2739#if !COAP_DISABLE_TCP
2740static int
2741coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2742 coap_tick_t now, void *extra) {
2743 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2744 if (session)
2745 session->last_rx_tx = now;
2746 return session != NULL;
2747}
2748#endif /* !COAP_DISABLE_TCP */
2749#endif /* COAP_SERVER_SUPPORT */
2750
2751COAP_API void
2753 coap_lock_lock(return);
2754 coap_io_do_io_lkd(ctx, now);
2756}
2757
2758void
2760#ifdef COAP_EPOLL_SUPPORT
2761 (void)ctx;
2762 (void)now;
2763 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2764#else /* ! COAP_EPOLL_SUPPORT */
2765 coap_session_t *s, *rtmp;
2766
2768#if COAP_SERVER_SUPPORT
2769 coap_endpoint_t *ep, *tmp;
2770 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2771 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2772 coap_read_endpoint(ctx, ep, now);
2773 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2774 coap_write_endpoint(ctx, ep, now);
2775#if !COAP_DISABLE_TCP
2776 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2777 coap_accept_endpoint(ctx, ep, now, NULL);
2778#endif /* !COAP_DISABLE_TCP */
2779 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2780 /* Make sure the session object is not deleted in one of the callbacks */
2782#if COAP_CLIENT_SUPPORT
2783 if (s->client_initiated && (s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2784 coap_connect_session(s, now);
2785 }
2786#endif /* COAP_CLIENT_SUPPORT */
2787 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2788 coap_read_session(ctx, s, now);
2789 }
2790 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2791 coap_write_session(ctx, s, now);
2792 }
2794 }
2795 }
2796#endif /* COAP_SERVER_SUPPORT */
2797
2798#if COAP_CLIENT_SUPPORT
2799 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2800 /* Make sure the session object is not deleted in one of the callbacks */
2802 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2803 coap_connect_session(s, now);
2804 }
2805 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2806 coap_read_session(ctx, s, now);
2807 }
2808 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2809 coap_write_session(ctx, s, now);
2810 }
2812 }
2813#endif /* COAP_CLIENT_SUPPORT */
2814#endif /* ! COAP_EPOLL_SUPPORT */
2815}
2816
2817COAP_API void
2818coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2819 coap_lock_lock(return);
2820 coap_io_do_epoll_lkd(ctx, events, nevents);
2822}
2823
2824/*
2825 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2826 * directly saves having to iterate through the endpoints / sessions.
2827 */
2828void
2829coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2830#ifndef COAP_EPOLL_SUPPORT
2831 (void)ctx;
2832 (void)events;
2833 (void)nevents;
2834 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2835#else /* COAP_EPOLL_SUPPORT */
2836 coap_tick_t now;
2837 size_t j;
2838
2840 coap_ticks(&now);
2841 for (j = 0; j < nevents; j++) {
2842 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2843
2844 /* Ignore 'timer trigger' ptr which is NULL */
2845 if (sock) {
2846#if COAP_SERVER_SUPPORT
2847 if (sock->endpoint) {
2848 coap_endpoint_t *endpoint = sock->endpoint;
2849 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2850 (events[j].events & EPOLLIN)) {
2851 sock->flags |= COAP_SOCKET_CAN_READ;
2852 coap_read_endpoint(endpoint->context, endpoint, now);
2853 }
2854
2855 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2856 (events[j].events & EPOLLOUT)) {
2857 /*
2858 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2859 * be true causing epoll_wait to return early
2860 */
2861 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2863 coap_write_endpoint(endpoint->context, endpoint, now);
2864 }
2865
2866#if !COAP_DISABLE_TCP
2867 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2868 (events[j].events & EPOLLIN)) {
2870 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2871 }
2872#endif /* !COAP_DISABLE_TCP */
2873
2874 } else
2875#endif /* COAP_SERVER_SUPPORT */
2876 if (sock->session) {
2877 coap_session_t *session = sock->session;
2878
2879 /* Make sure the session object is not deleted
2880 in one of the callbacks */
2882#if COAP_CLIENT_SUPPORT
2883 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2884 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2886 coap_connect_session(session, now);
2887 if (coap_netif_available(session) &&
2888 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2889 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2890 }
2891 }
2892#endif /* COAP_CLIENT_SUPPORT */
2893
2894 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2895 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2896 sock->flags |= COAP_SOCKET_CAN_READ;
2897 coap_read_session(session->context, session, now);
2898 }
2899
2900 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2901 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2902 /*
2903 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2904 * be true causing epoll_wait to return early
2905 */
2906 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2908 coap_write_session(session->context, session, now);
2909 }
2910 /* Now dereference session so it can go away if needed */
2911 coap_session_release_lkd(session);
2912 }
2913 } else if (ctx->eptimerfd != -1) {
2914 /*
2915 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2916 * it so that it does not set EPOLLIN in the next epoll_wait().
2917 */
2918 uint64_t count;
2919
2920 /* Check the result from read() to suppress the warning on
2921 * systems that declare read() with warn_unused_result. */
2922 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2923 /* do nothing */;
2924 }
2925 }
2926 }
2927 /* And update eptimerfd as to when to next trigger */
2928 coap_ticks(&now);
2929 coap_io_prepare_epoll_lkd(ctx, now);
2930#endif /* COAP_EPOLL_SUPPORT */
2931}
2932
2933int
2935 uint8_t *msg, size_t msg_len) {
2936
2937 coap_pdu_t *pdu = NULL;
2938 coap_opt_filter_t error_opts;
2939
2940 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2941 if (msg_len < 4) {
2942 /* Minimum size of CoAP header - ignore runt */
2943 return -1;
2944 }
2945 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2946 /*
2947 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2948 * this MUST be silently ignored.
2949 */
2950 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2951 return -1;
2952 }
2953
2954 /* Need max space incase PDU is updated with updated token etc. */
2955 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2956 if (!pdu)
2957 goto error;
2958
2959 coap_option_filter_clear(&error_opts);
2960 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
2962 coap_log_warn("discard malformed PDU\n");
2963 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
2964 coap_pdu_t *response =
2966 COAP_RESPONSE_CODE(402), &error_opts);
2967 if (!response) {
2968 coap_log_warn("coap_handle_dgram: cannot create error response\n");
2969 } else {
2970 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2971 coap_log_warn("coap_handle_dgram: error sending response\n");
2972 }
2974 return -1;
2975 } else {
2976 goto error;
2977 }
2978 }
2979
2980 coap_dispatch(ctx, session, pdu);
2982 return 0;
2983
2984error:
2985 /*
2986 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2987 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2988 */
2989 coap_send_rst_lkd(session, pdu);
2991 return -1;
2992}
2993
2994int
2996 coap_queue_t **node) {
2997 coap_queue_t *p, *q;
2998
2999 if (!queue || !*queue) {
3000 *node = NULL;
3001 return 0;
3002 }
3003
3004 /* replace queue head if PDU's time is less than head's time */
3005
3006 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
3007 *node = *queue;
3008 *queue = (*queue)->next;
3009 if (*queue) { /* adjust relative time of new queue head */
3010 (*queue)->t += (*node)->t;
3011 }
3012 (*node)->next = NULL;
3013 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
3014 coap_session_str(session), id);
3015 return 1;
3016 }
3017
3018 /* search message id in queue to remove (only first occurence will be removed) */
3019 q = *queue;
3020 do {
3021 p = q;
3022 q = q->next;
3023 } while (q && (session != q->session || id != q->id));
3024
3025 if (q) { /* found message id */
3026 p->next = q->next;
3027 if (p->next) { /* must update relative time of p->next */
3028 p->next->t += q->t;
3029 }
3030 q->next = NULL;
3031 *node = q;
3032 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
3033 coap_session_str(session), id);
3034 return 1;
3035 }
3036
3037 *node = NULL;
3038 return 0;
3039
3040}
3041
3042static int
3044 coap_bin_const_t *token, coap_queue_t **node) {
3045 coap_queue_t *p, *q;
3046
3047 if (!queue || !*queue)
3048 return 0;
3049
3050 /* replace queue head if PDU's time is less than head's time */
3051
3052 if (session == (*queue)->session &&
3053 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
3054 *node = *queue;
3055 *queue = (*queue)->next;
3056 if (*queue) { /* adjust relative time of new queue head */
3057 (*queue)->t += (*node)->t;
3058 }
3059 (*node)->next = NULL;
3060 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3061 coap_session_str(session), (*node)->id);
3062 if ((*node)->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 /* search token in queue to remove (only first occurence will be removed) */
3072 q = *queue;
3073 do {
3074 p = q;
3075 q = q->next;
3076 } while (q && (session != q->session ||
3077 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3078
3079 if (q) { /* found token */
3080 p->next = q->next;
3081 if (p->next) { /* must update relative time of p->next */
3082 p->next->t += q->t;
3083 }
3084 q->next = NULL;
3085 *node = q;
3086 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3087 coap_session_str(session), (*node)->id);
3088 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3089 session->con_active--;
3090 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3091 /* Flush out any entries on session->delayqueue */
3092 coap_session_connected(session);
3093 }
3094 return 1;
3095 }
3096
3097 return 0;
3098
3099}
3100
3101void
3103 coap_nack_reason_t reason) {
3104 coap_queue_t *p, *q;
3105
3106 while (context->sendqueue && context->sendqueue->session == session) {
3107 q = context->sendqueue;
3108 context->sendqueue = q->next;
3109 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3110 coap_session_str(session), q->id);
3111 if (q->pdu->type == COAP_MESSAGE_CON) {
3112 coap_handle_nack(session, q->pdu, reason, q->id);
3113 }
3115 }
3116
3117 if (!context->sendqueue)
3118 return;
3119
3120 p = context->sendqueue;
3121 q = p->next;
3122
3123 while (q) {
3124 if (q->session == session) {
3125 p->next = q->next;
3126 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3127 coap_session_str(session), q->id);
3128 if (q->pdu->type == COAP_MESSAGE_CON) {
3129 coap_handle_nack(session, q->pdu, reason, q->id);
3130 }
3132 q = p->next;
3133 } else {
3134 p = q;
3135 q = q->next;
3136 }
3137 }
3138}
3139
3140void
3142 coap_bin_const_t *token) {
3143 /* cancel all messages in sendqueue that belong to session
3144 * and use the specified token */
3145 coap_queue_t **p, *q;
3146
3147 if (!context->sendqueue)
3148 return;
3149
3150 p = &context->sendqueue;
3151 q = *p;
3152
3153 while (q) {
3154 if (q->session == session &&
3155 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3156 *p = q->next;
3157 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3158 coap_session_str(session), q->id);
3159 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3160 session->con_active--;
3161 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3162 /* Flush out any entries on session->delayqueue */
3163 coap_session_connected(session);
3164 }
3166 } else {
3167 p = &(q->next);
3168 }
3169 q = *p;
3170 }
3171}
3172
3173coap_pdu_t *
3175 coap_opt_filter_t *opts) {
3176 coap_opt_iterator_t opt_iter;
3177 coap_pdu_t *response;
3178 unsigned char type;
3179
3180#if COAP_ERROR_PHRASE_LENGTH > 0
3181 const char *phrase;
3182 if (code != COAP_RESPONSE_CODE(508)) {
3183 phrase = coap_response_phrase(code);
3184 } else {
3185 phrase = NULL;
3186 }
3187#endif
3188
3189 assert(request);
3190
3191 /* cannot send ACK if original request was not confirmable */
3192 type = request->type == COAP_MESSAGE_CON ?
3194
3195 /* Now create the response and fill with options and payload data. */
3196 response = coap_pdu_init(type, code, request->mid,
3197 request->session ?
3198 coap_session_max_pdu_size_lkd(request->session) : 512);
3199 if (response) {
3200 /* copy token */
3201 if (!coap_add_token(response, request->actual_token.length,
3202 request->actual_token.s)) {
3203 coap_log_debug("cannot add token to error response\n");
3204 coap_delete_pdu_lkd(response);
3205 return NULL;
3206 }
3207 if (response->code == COAP_RESPONSE_CODE(402)) {
3208 char buf[128];
3209 int first = 1;
3210
3211#if COAP_ERROR_PHRASE_LENGTH > 0
3212 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3213#else
3214 buf[0] = '\000';
3215#endif
3216 /* copy all options into diagnostic message */
3217 coap_option_iterator_init(request, &opt_iter, opts);
3218 while (coap_option_next(&opt_iter)) {
3219 size_t len = strlen(buf);
3220
3221 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",", opt_iter.number);
3222 first = 0;
3223 }
3224 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3225 } else if (opts && opts->mask) {
3226 coap_opt_t *option;
3227
3228 /* copy all options */
3229 coap_option_iterator_init(request, &opt_iter, opts);
3230 while ((option = coap_option_next(&opt_iter))) {
3231 coap_add_option_internal(response, opt_iter.number,
3232 coap_opt_length(option),
3233 coap_opt_value(option));
3234 }
3235#if COAP_ERROR_PHRASE_LENGTH > 0
3236 if (phrase)
3237 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3238 } else {
3239 /* note that diagnostic messages do not need a Content-Format option. */
3240 if (phrase)
3241 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3242#endif
3243 }
3244 }
3245
3246 return response;
3247}
3248
3249#if COAP_SERVER_SUPPORT
3250#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3251
3252static void
3253free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3254 coap_delete_string(app_ptr);
3255}
3256
3257/*
3258 * Caution: As this handler is in libcoap space, it is called with
3259 * context locked.
3260 */
3261static void
3262hnd_get_wellknown_lkd(coap_resource_t *resource,
3263 coap_session_t *session,
3264 const coap_pdu_t *request,
3265 const coap_string_t *query,
3266 coap_pdu_t *response) {
3267 size_t len = 0;
3268 coap_string_t *data_string = NULL;
3269 coap_print_status_t result = 0;
3270 size_t wkc_len = 0;
3271 uint8_t buf[4];
3272
3273 /*
3274 * Quick hack to determine the size of the resource descriptions for
3275 * .well-known/core.
3276 */
3277 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3278 if (result & COAP_PRINT_STATUS_ERROR) {
3279 coap_log_warn("cannot determine length of /.well-known/core\n");
3280 goto error;
3281 }
3282
3283 if (wkc_len > 0) {
3284 data_string = coap_new_string(wkc_len);
3285 if (!data_string)
3286 goto error;
3287
3288 len = wkc_len;
3289 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3290 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3291 coap_log_debug("coap_print_wellknown failed\n");
3292 goto error;
3293 }
3294 assert(len <= (size_t)wkc_len);
3295 data_string->length = len;
3296
3297 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3299 coap_encode_var_safe(buf, sizeof(buf),
3301 goto error;
3302 }
3303 if (response->used_size + len + 1 > response->max_size) {
3304 /*
3305 * Data does not fit into a packet and no libcoap block support
3306 * +1 for end of options marker
3307 */
3308 coap_log_debug(".well-known/core: truncating data length to %" PRIuS " from %" PRIuS "\n",
3309 len, response->max_size - response->used_size - 1);
3310 len = response->max_size - response->used_size - 1;
3311 }
3312 if (!coap_add_data(response, len, data_string->s)) {
3313 goto error;
3314 }
3315 free_wellknown_response(session, data_string);
3316 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3317 response, query,
3319 -1, 0, data_string->length,
3320 data_string->s,
3321 free_wellknown_response,
3322 data_string)) {
3323 goto error_released;
3324 }
3325 } else {
3327 coap_encode_var_safe(buf, sizeof(buf),
3329 goto error;
3330 }
3331 }
3332 response->code = COAP_RESPONSE_CODE(205);
3333 return;
3334
3335error:
3336 free_wellknown_response(session, data_string);
3337error_released:
3338 if (response->code == 0) {
3339 /* set error code 5.03 and remove all options and data from response */
3340 response->code = COAP_RESPONSE_CODE(503);
3341 response->used_size = response->e_token_length;
3342 response->data = NULL;
3343 }
3344}
3345#endif /* COAP_SERVER_SUPPORT */
3346
3357static int
3359 int num_cancelled = 0; /* the number of observers cancelled */
3360
3361#ifndef COAP_SERVER_SUPPORT
3362 (void)sent;
3363#endif /* ! COAP_SERVER_SUPPORT */
3364 (void)context;
3365
3366#if COAP_SERVER_SUPPORT
3367 /* remove observer for this resource, if any
3368 * Use token from sent and try to find a matching resource. Uh!
3369 */
3370 RESOURCES_ITER(context->resources, r) {
3371 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3372 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3373 }
3374#endif /* COAP_SERVER_SUPPORT */
3375
3376 return num_cancelled;
3377}
3378
3379#if COAP_SERVER_SUPPORT
3384enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3385
3386/*
3387 * Checks for No-Response option in given @p request and
3388 * returns @c RESPONSE_DROP if @p response should be suppressed
3389 * according to RFC 7967.
3390 *
3391 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3392 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3393 * on retrying.
3394 *
3395 * Checks if the response code is 0.00 and if either the session is reliable or
3396 * non-confirmable, @c RESPONSE_DROP is also returned.
3397 *
3398 * Multicast response checking is also carried out.
3399 *
3400 * NOTE: It is the responsibility of the application to determine whether
3401 * a delayed separate response should be sent as the original requesting packet
3402 * containing the No-Response option has long since gone.
3403 *
3404 * The value of the No-Response option is encoded as
3405 * follows:
3406 *
3407 * @verbatim
3408 * +-------+-----------------------+-----------------------------------+
3409 * | Value | Binary Representation | Description |
3410 * +-------+-----------------------+-----------------------------------+
3411 * | 0 | <empty> | Interested in all responses. |
3412 * +-------+-----------------------+-----------------------------------+
3413 * | 2 | 00000010 | Not interested in 2.xx responses. |
3414 * +-------+-----------------------+-----------------------------------+
3415 * | 8 | 00001000 | Not interested in 4.xx responses. |
3416 * +-------+-----------------------+-----------------------------------+
3417 * | 16 | 00010000 | Not interested in 5.xx responses. |
3418 * +-------+-----------------------+-----------------------------------+
3419 * @endverbatim
3420 *
3421 * @param request The CoAP request to check for the No-Response option.
3422 * This parameter must not be NULL.
3423 * @param response The response that is potentially suppressed.
3424 * This parameter must not be NULL.
3425 * @param session The session this request/response are associated with.
3426 * This parameter must not be NULL.
3427 * @return RESPONSE_DEFAULT when no special treatment is requested,
3428 * RESPONSE_DROP when the response must be discarded, or
3429 * RESPONSE_SEND when the response must be sent.
3430 */
3431static enum respond_t
3432no_response(coap_pdu_t *request, coap_pdu_t *response,
3433 coap_session_t *session, coap_resource_t *resource) {
3434 coap_opt_t *nores;
3435 coap_opt_iterator_t opt_iter;
3436 unsigned int val = 0;
3437
3438 assert(request);
3439 assert(response);
3440
3441 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3442 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3443
3444 if (nores) {
3446
3447 /* The response should be dropped when the bit corresponding to
3448 * the response class is set (cf. table in function
3449 * documentation). When a No-Response option is present and the
3450 * bit is not set, the sender explicitly indicates interest in
3451 * this response. */
3452 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3453 /* Should be dropping the response */
3454 if (response->type == COAP_MESSAGE_ACK &&
3455 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3456 /* Still need to ACK the request */
3457 response->code = 0;
3458 /* Remove token/data from piggybacked acknowledgment PDU */
3459 response->actual_token.length = 0;
3460 response->e_token_length = 0;
3461 response->used_size = 0;
3462 response->data = NULL;
3463 return RESPONSE_SEND;
3464 } else {
3465 return RESPONSE_DROP;
3466 }
3467 } else {
3468 /* True for mcast as well RFC7967 2.1 */
3469 return RESPONSE_SEND;
3470 }
3471 } else if (resource && session->context->mcast_per_resource &&
3472 coap_is_mcast(&session->addr_info.local)) {
3473 /* Handle any mcast suppression specifics if no NoResponse option */
3474 if ((resource->flags &
3476 COAP_RESPONSE_CLASS(response->code) == 2) {
3477 return RESPONSE_DROP;
3478 } else if ((resource->flags &
3480 response->code == COAP_RESPONSE_CODE(205)) {
3481 if (response->data == NULL)
3482 return RESPONSE_DROP;
3483 } else if ((resource->flags &
3485 COAP_RESPONSE_CLASS(response->code) == 4) {
3486 return RESPONSE_DROP;
3487 } else if ((resource->flags &
3489 COAP_RESPONSE_CLASS(response->code) == 5) {
3490 return RESPONSE_DROP;
3491 }
3492 }
3493 } else if (COAP_PDU_IS_EMPTY(response) &&
3494 (response->type == COAP_MESSAGE_NON ||
3495 COAP_PROTO_RELIABLE(session->proto))) {
3496 /* response is 0.00, and this is reliable or non-confirmable */
3497 return RESPONSE_DROP;
3498 }
3499
3500 /*
3501 * Do not send error responses for requests that were received via
3502 * IP multicast. RFC7252 8.1
3503 */
3504
3505 if (coap_is_mcast(&session->addr_info.local)) {
3506 if (request->type == COAP_MESSAGE_NON &&
3507 response->type == COAP_MESSAGE_RST)
3508 return RESPONSE_DROP;
3509
3510 if ((!resource || session->context->mcast_per_resource == 0) &&
3511 COAP_RESPONSE_CLASS(response->code) > 2)
3512 return RESPONSE_DROP;
3513 }
3514
3515 /* Default behavior applies when we are not dealing with a response
3516 * (class == 0) or the request did not contain a No-Response option.
3517 */
3518 return RESPONSE_DEFAULT;
3519}
3520
3521static coap_str_const_t coap_default_uri_wellknown = {
3523 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3524};
3525
3526/* Initialized in coap_startup() */
3527static coap_resource_t resource_uri_wellknown;
3528
3529static void
3530handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3531 coap_pdu_t *orig_pdu) {
3532 coap_method_handler_t h = NULL;
3533 coap_pdu_t *response = NULL;
3534 coap_opt_filter_t opt_filter;
3535 coap_resource_t *resource = NULL;
3536 /* The respond field indicates whether a response must be treated
3537 * specially due to a No-Response option that declares disinterest
3538 * or interest in a specific response class. DEFAULT indicates that
3539 * No-Response has not been specified. */
3540 enum respond_t respond = RESPONSE_DEFAULT;
3541 coap_opt_iterator_t opt_iter;
3542 coap_opt_t *opt;
3543 int is_proxy_uri = 0;
3544 int is_proxy_scheme = 0;
3545 int skip_hop_limit_check = 0;
3546 int resp = 0;
3547 int send_early_empty_ack = 0;
3548 coap_string_t *query = NULL;
3549 coap_opt_t *observe = NULL;
3550 coap_string_t *uri_path = NULL;
3551 int observe_action = COAP_OBSERVE_CANCEL;
3552 coap_block_b_t block;
3553 int added_block = 0;
3554 coap_lg_srcv_t *free_lg_srcv = NULL;
3555#if COAP_Q_BLOCK_SUPPORT
3556 int lg_xmit_ctrl = 0;
3557#endif /* COAP_Q_BLOCK_SUPPORT */
3558#if COAP_ASYNC_SUPPORT
3559 coap_async_t *async;
3560#endif /* COAP_ASYNC_SUPPORT */
3561
3562 if (coap_is_mcast(&session->addr_info.local)) {
3563 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3564 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3565 return;
3566 }
3567 }
3568#if COAP_ASYNC_SUPPORT
3569 async = coap_find_async_lkd(session, pdu->actual_token);
3570 if (async) {
3571 coap_tick_t now;
3572
3573 coap_ticks(&now);
3574 if (async->delay == 0 || async->delay > now) {
3575 /* re-transmit missing ACK (only if CON) */
3576 coap_log_info("Retransmit async response\n");
3577 coap_send_ack_lkd(session, pdu);
3578 /* and do not pass on to the upper layers */
3579 return;
3580 }
3581 }
3582#endif /* COAP_ASYNC_SUPPORT */
3583
3584 coap_option_filter_clear(&opt_filter);
3585 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3586 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3587 if (opt) {
3588 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3589 if (!opt) {
3590 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3591 resp = 402;
3592 goto fail_response;
3593 }
3594 is_proxy_scheme = 1;
3595 }
3596
3597 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3598 if (opt)
3599 is_proxy_uri = 1;
3600 }
3601
3602 if (is_proxy_scheme || is_proxy_uri) {
3603 coap_uri_t uri;
3604
3605 if (!context->proxy_uri_resource) {
3606 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3607 coap_log_debug("Proxy-%s support not configured\n",
3608 is_proxy_scheme ? "Scheme" : "Uri");
3609 resp = 505;
3610 goto fail_response;
3611 }
3612 if (((size_t)pdu->code - 1 <
3613 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3614 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3615 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3616 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3617 is_proxy_scheme ? "Scheme" : "Uri",
3618 pdu->code/100, pdu->code%100);
3619 resp = 505;
3620 goto fail_response;
3621 }
3622
3623 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3624 if (is_proxy_uri) {
3626 coap_opt_length(opt), &uri) < 0) {
3627 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3628 coap_log_debug("Proxy-URI not decodable\n");
3629 resp = 505;
3630 goto fail_response;
3631 }
3632 } else {
3633 memset(&uri, 0, sizeof(uri));
3634 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3635 if (opt) {
3636 uri.host.length = coap_opt_length(opt);
3637 uri.host.s = coap_opt_value(opt);
3638 } else
3639 uri.host.length = 0;
3640 }
3641
3642 resource = context->proxy_uri_resource;
3643 if (uri.host.length && resource->proxy_name_count &&
3644 resource->proxy_name_list) {
3645 size_t i;
3646
3647 if (resource->proxy_name_count == 1 &&
3648 resource->proxy_name_list[0]->length == 0) {
3649 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3650 i = 0;
3651 } else {
3652 for (i = 0; i < resource->proxy_name_count; i++) {
3653 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3654 break;
3655 }
3656 }
3657 }
3658 if (i != resource->proxy_name_count) {
3659 /* This server is hosting the proxy connection endpoint */
3660 if (pdu->crit_opt) {
3661 /* Cannot handle critical option */
3662 pdu->crit_opt = 0;
3663 resp = 402;
3664 resource = NULL;
3665 goto fail_response;
3666 }
3667 is_proxy_uri = 0;
3668 is_proxy_scheme = 0;
3669 skip_hop_limit_check = 1;
3670 }
3671 }
3672 resource = NULL;
3673 }
3674 assert(resource == NULL);
3675
3676 if (!skip_hop_limit_check) {
3677 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3678 if (opt) {
3679 size_t hop_limit;
3680 uint8_t buf[4];
3681
3682 hop_limit =
3684 if (hop_limit == 1) {
3685 /* coap_send_internal() will fill in the IP address for us */
3686 resp = 508;
3687 goto fail_response;
3688 } else if (hop_limit < 1 || hop_limit > 255) {
3689 /* Need to return a 4.00 RFC8768 Section 3 */
3690 coap_log_info("Invalid Hop Limit\n");
3691 resp = 400;
3692 goto fail_response;
3693 }
3694 hop_limit--;
3696 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3697 buf);
3698 }
3699 }
3700
3701 uri_path = coap_get_uri_path(pdu);
3702 if (!uri_path)
3703 return;
3704
3705 if (!is_proxy_uri && !is_proxy_scheme) {
3706 /* try to find the resource from the request URI */
3707 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3708 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3709 }
3710
3711 if ((resource == NULL) || (resource->is_unknown == 1) ||
3712 (resource->is_proxy_uri == 1)) {
3713 /* The resource was not found or there is an unexpected match against the
3714 * resource defined for handling unknown or proxy URIs.
3715 */
3716 if (resource != NULL)
3717 /* Close down unexpected match */
3718 resource = NULL;
3719 /*
3720 * Check if the request URI happens to be the well-known URI, or if the
3721 * unknown resource handler is defined, a PUT or optionally other methods,
3722 * if configured, for the unknown handler.
3723 *
3724 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3725 * proxy URI handler.
3726 *
3727 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3728 * set, call the unknown URI handler with any unknown URI (including
3729 * .well-known/core) if the appropriate method is defined.
3730 *
3731 * else if well-known URI generate a default response.
3732 *
3733 * else if unknown URI handler defined, call the unknown
3734 * URI handler (to allow for potential generation of resource
3735 * [RFC7272 5.8.3]) if the appropriate method is defined.
3736 *
3737 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3738 *
3739 * else return 4.04.
3740 */
3741
3742 if (is_proxy_uri || is_proxy_scheme) {
3743 resource = context->proxy_uri_resource;
3744 } else if (context->unknown_resource != NULL &&
3746 ((size_t)pdu->code - 1 <
3747 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3748 (context->unknown_resource->handler[pdu->code - 1])) {
3749 resource = context->unknown_resource;
3750 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3751 /* request for .well-known/core */
3752 resource = &resource_uri_wellknown;
3753 } else if ((context->unknown_resource != NULL) &&
3754 ((size_t)pdu->code - 1 <
3755 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3756 (context->unknown_resource->handler[pdu->code - 1])) {
3757 /*
3758 * The unknown_resource can be used to handle undefined resources
3759 * for a PUT request and can support any other registered handler
3760 * defined for it
3761 * Example set up code:-
3762 * r = coap_resource_unknown_init(hnd_put_unknown);
3763 * coap_register_request_handler(r, COAP_REQUEST_POST,
3764 * hnd_post_unknown);
3765 * coap_register_request_handler(r, COAP_REQUEST_GET,
3766 * hnd_get_unknown);
3767 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3768 * hnd_delete_unknown);
3769 * coap_add_resource(ctx, r);
3770 *
3771 * Note: It is not possible to observe the unknown_resource, a separate
3772 * resource must be created (by PUT or POST) which has a GET
3773 * handler to be observed
3774 */
3775 resource = context->unknown_resource;
3776 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3777 /*
3778 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3779 */
3780 coap_log_debug("request for unknown resource '%*.*s',"
3781 " return 2.02\n",
3782 (int)uri_path->length,
3783 (int)uri_path->length,
3784 uri_path->s);
3785 resp = 202;
3786 goto fail_response;
3787 } else if ((context->dyn_create_handler != NULL) &&
3789 /* Above test must be the same as in coap_op_dyn_resource_load_disk() */
3790 if (context->dynamic_cur < context->dynamic_max || context->dynamic_max == 0) {
3791#if COAP_WITH_OBSERVE_PERSIST
3792 /* If we are maintaining Observe persist */
3793 context->unknown_pdu = pdu;
3794 context->unknown_session = session;
3795#endif /* COAP_WITH_OBSERVE_PERSIST */
3796 coap_lock_callback_ret(resource, context->dyn_create_handler(session, pdu));
3797#if COAP_WITH_OBSERVE_PERSIST
3798 /* If we are maintaining Observe persist */
3799 context->unknown_pdu = NULL;
3800 context->unknown_session = NULL;
3801#endif /* COAP_WITH_OBSERVE_PERSIST */
3802 }
3803 if (!resource) {
3804 resp = 406;
3805 goto fail_response;
3806 }
3807 context->dynamic_cur++;
3808 resource->is_dynamic = 1;
3809 } else { /* request for any another resource, return 4.04 */
3810
3811 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3812 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3813 resp = 404;
3814 goto fail_response;
3815 }
3816
3817 }
3818
3820
3821#if COAP_OSCORE_SUPPORT
3822 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3823 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3824 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3825 resp = 401;
3826 goto fail_response;
3827 }
3828#endif /* COAP_OSCORE_SUPPORT */
3829 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3830 /* Check for existing resource and If-Non-Match */
3831 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3832 if (opt) {
3833 resp = 412;
3834 goto fail_response;
3835 }
3836 }
3837
3838 /* the resource was found, check if there is a registered handler */
3839 if ((size_t)pdu->code - 1 <
3840 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3841 h = resource->handler[pdu->code - 1];
3842
3843 if (h == NULL) {
3844 resp = 405;
3845 goto fail_response;
3846 }
3847 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3848 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3849 if (opt == NULL) {
3850 /* RFC 8132 2.3.1 */
3851 resp = 415;
3852 goto fail_response;
3853 }
3854 }
3855 if (context->mcast_per_resource &&
3856 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3857 coap_is_mcast(&session->addr_info.local)) {
3858 resp = 405;
3859 goto fail_response;
3860 }
3861
3862 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3864 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3865 if (!response) {
3866 coap_log_err("could not create response PDU\n");
3867 resp = 500;
3868 goto fail_response;
3869 }
3870 response->session = session;
3871#if COAP_ASYNC_SUPPORT
3872 /* If handling a separate response, need CON, not ACK response */
3873 if (async && pdu->type == COAP_MESSAGE_CON)
3874 response->type = COAP_MESSAGE_CON;
3875#endif /* COAP_ASYNC_SUPPORT */
3876 /* A lot of the reliable code assumes type is CON */
3877 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3878 response->type = COAP_MESSAGE_CON;
3879
3880 if (!coap_add_token(response, pdu->actual_token.length,
3881 pdu->actual_token.s)) {
3882 resp = 500;
3883 goto fail_response;
3884 }
3885
3886 query = coap_get_query(pdu);
3887
3888 /* check for Observe option RFC7641 and RFC8132 */
3889 if (resource->observable &&
3890 (pdu->code == COAP_REQUEST_CODE_GET ||
3891 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3892 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3893 }
3894
3895 /*
3896 * See if blocks need to be aggregated or next requests sent off
3897 * before invoking application request handler
3898 */
3899 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3900 uint32_t block_mode = session->block_mode;
3901
3902 if (observe ||
3905 if (coap_handle_request_put_block(context, session, pdu, response,
3906 resource, uri_path, observe,
3907 &added_block, &free_lg_srcv)) {
3908 session->block_mode = block_mode;
3909 goto skip_handler;
3910 }
3911 session->block_mode = block_mode;
3912
3913 if (coap_handle_request_send_block(session, pdu, response, resource,
3914 query)) {
3915#if COAP_Q_BLOCK_SUPPORT
3916 lg_xmit_ctrl = 1;
3917#endif /* COAP_Q_BLOCK_SUPPORT */
3918 goto skip_handler;
3919 }
3920 }
3921
3922 if (observe) {
3923 observe_action =
3925 coap_opt_length(observe));
3926
3927 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3928 coap_subscription_t *subscription;
3929
3930 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3931 if (block.num != 0) {
3932 response->code = COAP_RESPONSE_CODE(400);
3933 goto skip_handler;
3934 }
3935#if COAP_Q_BLOCK_SUPPORT
3936 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3937 &block)) {
3938 if (block.num != 0) {
3939 response->code = COAP_RESPONSE_CODE(400);
3940 goto skip_handler;
3941 }
3942#endif /* COAP_Q_BLOCK_SUPPORT */
3943 }
3944 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3945 pdu);
3946 if (subscription) {
3947 uint8_t buf[4];
3948
3949 coap_touch_observer(context, session, &pdu->actual_token);
3951 coap_encode_var_safe(buf, sizeof(buf),
3952 resource->observe),
3953 buf);
3954 }
3955 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3956 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3957 } else {
3958 coap_log_info("observe: unexpected action %d\n", observe_action);
3959 }
3960 }
3961
3962 if ((resource == context->proxy_uri_resource ||
3963 (resource == context->unknown_resource &&
3964 context->unknown_resource->is_reverse_proxy)) &&
3965 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3966 pdu->type == COAP_MESSAGE_CON &&
3967 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
3968 /* Make the proxy response separate and fix response later */
3969 send_early_empty_ack = 1;
3970 }
3971 if (send_early_empty_ack) {
3972 coap_send_ack_lkd(session, pdu);
3973 if (pdu->mid == session->last_con_mid) {
3974 /* request has already been processed - do not process it again */
3975 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3976 pdu->mid);
3977 goto drop_it_no_debug;
3978 }
3979 session->last_con_mid = pdu->mid;
3980 }
3981#if COAP_WITH_OBSERVE_PERSIST
3982 /* If we are maintaining Observe persist */
3983 if (resource == context->unknown_resource) {
3984 context->unknown_pdu = pdu;
3985 context->unknown_session = session;
3986 } else
3987 context->unknown_pdu = NULL;
3988#endif /* COAP_WITH_OBSERVE_PERSIST */
3989
3990 /*
3991 * Call the request handler with everything set up
3992 */
3993 if (resource == &resource_uri_wellknown) {
3994 /* Leave context locked */
3995 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3996 (int)resource->uri_path->length, (int)resource->uri_path->length,
3997 resource->uri_path->s);
3998 h(resource, session, pdu, query, response);
3999 } else {
4000 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
4001 (int)resource->uri_path->length, (int)resource->uri_path->length,
4002 resource->uri_path->s);
4003 coap_lock_callback_release(h(resource, session, pdu, query, response),
4004 /* context is being freed off */
4005 goto finish);
4006 }
4007
4008 /* Check validity of response code */
4009 if (!coap_check_code_class(session, response)) {
4010 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
4011 COAP_RESPONSE_CLASS(response->code),
4012 response->code & 0x1f);
4013 goto drop_it_no_debug;
4014 }
4015
4016 /* Check if lg_xmit generated and update PDU code if so */
4017 coap_check_code_lg_xmit(session, pdu, response, resource, query);
4018
4019 if (free_lg_srcv) {
4020 /* Check to see if the server is doing a 4.01 + Echo response */
4021 if (response->code == COAP_RESPONSE_CODE(401) &&
4022 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
4023 /* Need to keep lg_srcv around for client's response */
4024 } else {
4025 coap_lg_srcv_t *lg_srcv;
4026 /*
4027 * Need to check free_lg_srcv still exists in case of error or timing window
4028 */
4029 LL_FOREACH(session->lg_srcv, lg_srcv) {
4030 if (lg_srcv == free_lg_srcv) {
4031 LL_DELETE(session->lg_srcv, free_lg_srcv);
4032 coap_block_delete_lg_srcv(session, free_lg_srcv);
4033 break;
4034 }
4035 }
4036 }
4037 }
4038 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
4039 /* Just in case, as there are more to go */
4040 response->code = COAP_RESPONSE_CODE(231);
4041 }
4042
4043skip_handler:
4044 if (send_early_empty_ack &&
4045 response->type == COAP_MESSAGE_ACK) {
4046 /* Response is now separate - convert to CON as needed */
4047 response->type = COAP_MESSAGE_CON;
4048 /* Check for empty ACK - need to drop as already sent */
4049 if (response->code == 0) {
4050 goto drop_it_no_debug;
4051 }
4052 }
4053 respond = no_response(pdu, response, session, resource);
4054 if (respond != RESPONSE_DROP) {
4055#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
4056 coap_mid_t mid = pdu->mid;
4057#endif
4058 if (COAP_RESPONSE_CLASS(response->code) != 2) {
4059 if (observe) {
4061 }
4062 }
4063 if (COAP_RESPONSE_CLASS(response->code) > 2) {
4064 if (observe)
4065 coap_delete_observer(resource, session, &pdu->actual_token);
4066 if (response->code != COAP_RESPONSE_CODE(413))
4068 }
4069
4070 /* If original request contained a token, and the registered
4071 * application handler made no changes to the response, then
4072 * this is an empty ACK with a token, which is a malformed
4073 * PDU */
4074 if ((response->type == COAP_MESSAGE_ACK)
4075 && (response->code == 0)) {
4076 /* Remove token from otherwise-empty acknowledgment PDU */
4077 response->actual_token.length = 0;
4078 response->e_token_length = 0;
4079 response->used_size = 0;
4080 response->data = NULL;
4081 }
4082
4083 if (!coap_is_mcast(&session->addr_info.local) ||
4084 (context->mcast_per_resource &&
4085 resource &&
4087 /* No delays to response */
4088#if COAP_Q_BLOCK_SUPPORT
4089 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4090 !lg_xmit_ctrl && COAP_RESPONSE_CLASS(response->code) == 2 &&
4091 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4092 block.m) {
4093 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4094 response,
4095 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4096 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4097 response = NULL;
4098 if (query)
4099 coap_delete_string(query);
4100 goto finish;
4101 }
4102#endif /* COAP_Q_BLOCK_SUPPORT */
4103 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4104 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4105 if (query)
4106 coap_delete_string(query);
4107 goto finish;
4108 }
4109 } else {
4110 /* Need to delay mcast response */
4111 coap_queue_t *node = coap_new_node();
4112 uint8_t r;
4113 coap_tick_t delay;
4114
4115 if (!node) {
4116 coap_log_debug("mcast delay: insufficient memory\n");
4117 goto drop_it_no_debug;
4118 }
4119 if (!coap_pdu_encode_header(response, session->proto)) {
4121 goto drop_it_no_debug;
4122 }
4123
4124 node->id = response->mid;
4125 node->pdu = response;
4126 node->is_mcast = 1;
4127 coap_prng_lkd(&r, sizeof(r));
4128 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4129 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4130 coap_session_str(session),
4131 response->mid,
4132 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4133 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4134 1000 / COAP_TICKS_PER_SECOND));
4135 node->timeout = (unsigned int)delay;
4136 /* Use this to delay transmission */
4137 coap_wait_ack(session->context, session, node);
4138 }
4139 } else {
4140 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4141 coap_session_str(session),
4142 response->mid);
4143 coap_show_pdu(COAP_LOG_DEBUG, response);
4144drop_it_no_debug:
4145 coap_delete_pdu_lkd(response);
4146 }
4147 if (query)
4148 coap_delete_string(query);
4149#if COAP_Q_BLOCK_SUPPORT
4150 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4151 if (COAP_PROTO_RELIABLE(session->proto)) {
4152 if (block.m) {
4153 /* All of the sequence not in yet */
4154 goto finish;
4155 }
4156 } else if (pdu->type == COAP_MESSAGE_NON) {
4157 /* More to go and not at a payload break */
4158 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4159 goto finish;
4160 }
4161 }
4162 }
4163#endif /* COAP_Q_BLOCK_SUPPORT */
4164
4165finish:
4166 if (resource)
4167 coap_resource_release_lkd(resource);
4168 coap_delete_string(uri_path);
4169 return;
4170
4171fail_response:
4172 coap_delete_pdu_lkd(response);
4173 response =
4175 &opt_filter);
4176 if (response)
4177 goto skip_handler;
4178 if (resource)
4179 coap_resource_release_lkd(resource);
4180 coap_delete_string(uri_path);
4181}
4182#endif /* COAP_SERVER_SUPPORT */
4183
4184#if COAP_CLIENT_SUPPORT
4185/* Call application-specific response handler when available. */
4186void
4188 coap_pdu_t *sent, coap_pdu_t *rcvd,
4189 void *body_data) {
4190 coap_context_t *context = session->context;
4191 coap_response_t ret;
4192
4193#if COAP_PROXY_SUPPORT
4194 if (context->proxy_response_cb) {
4195 coap_proxy_list_t *proxy_entry;
4196 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4197 rcvd,
4198 &proxy_entry);
4199
4200 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4201 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4202 proxy_entry);
4203 return;
4204 }
4205 }
4206#endif /* COAP_PROXY_SUPPORT */
4207 if (session->doing_send_recv && session->req_token &&
4208 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4209 /* processing coap_send_recv() call */
4210 session->resp_pdu = rcvd;
4212 /* Will get freed off when PDU is freed off */
4213 rcvd->data_free = body_data;
4214 coap_send_ack_lkd(session, rcvd);
4216 return;
4217 } else if (context->response_cb) {
4219 context->response_cb(session,
4220 sent,
4221 rcvd,
4222 rcvd->mid),
4223 /* context is being freed off */
4224 return);
4225 } else {
4226 ret = COAP_RESPONSE_OK;
4227 }
4228 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4229 coap_send_rst_lkd(session, rcvd);
4231 } else {
4232 coap_send_ack_lkd(session, rcvd);
4234 }
4235 coap_free_type(COAP_STRING, body_data);
4236}
4237
4238static void
4239handle_response(coap_context_t *context, coap_session_t *session,
4240 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4241
4242 /* Set in case there is a later call to coap_update_token() */
4243 rcvd->session = session;
4244
4245 /* Check for message duplication */
4246 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4247 if (rcvd->type == COAP_MESSAGE_CON) {
4248 if (rcvd->mid == session->last_con_mid) {
4249 /* Duplicate response: send ACK/RST, but don't process */
4250 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4251 coap_send_ack_lkd(session, rcvd);
4252 else
4253 coap_send_rst_lkd(session, rcvd);
4254 return;
4255 }
4256 session->last_con_mid = rcvd->mid;
4257 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4258 if (rcvd->mid == session->last_ack_mid) {
4259 /* Duplicate response */
4260 return;
4261 }
4262 session->last_ack_mid = rcvd->mid;
4263 }
4264 }
4265 /* Check to see if checking out extended token support */
4266 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4267 session->last_token) {
4268 coap_lg_crcv_t *lg_crcv;
4269
4270 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4271 rcvd->actual_token.length != session->max_token_size ||
4272 rcvd->code == COAP_RESPONSE_CODE(400) ||
4273 rcvd->code == COAP_RESPONSE_CODE(503)) {
4274 coap_log_debug("Extended Token requested size support not available\n");
4276 } else {
4277 coap_log_debug("Extended Token support available\n");
4278 }
4280 /* Need to remove lg_crcv set up for this test */
4281 lg_crcv = coap_find_lg_crcv(session, rcvd);
4282 if (lg_crcv) {
4283 LL_DELETE(session->lg_crcv, lg_crcv);
4284 coap_block_delete_lg_crcv(session, lg_crcv);
4285 }
4286 coap_send_ack_lkd(session, rcvd);
4287 coap_reset_doing_first(session);
4288 return;
4289 }
4290#if COAP_Q_BLOCK_SUPPORT
4291 /* Check to see if checking out Q-Block support */
4292 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
4293 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4294 coap_log_debug("Q-Block support not available\n");
4295 set_block_mode_drop_q(session->block_mode);
4296 } else {
4297 coap_block_b_t qblock;
4298
4299 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4300 coap_log_debug("Q-Block support available\n");
4301 set_block_mode_has_q(session->block_mode);
4302 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4303 /* Flush out any entries on session->delayqueue */
4304 coap_session_connected(session);
4305 } else {
4306 coap_log_debug("Q-Block support not available\n");
4307 set_block_mode_drop_q(session->block_mode);
4308 }
4309 }
4310 coap_send_ack_lkd(session, rcvd);
4311 coap_reset_doing_first(session);
4312 return;
4313 }
4314#endif /* COAP_Q_BLOCK_SUPPORT */
4315
4316 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4317 /* See if need to send next block to server */
4318 if (coap_handle_response_send_block(session, sent, rcvd)) {
4319 /* Next block transmitted, no need to inform app */
4320 coap_send_ack_lkd(session, rcvd);
4321 return;
4322 }
4323
4324 /* Need to see if needing to request next block */
4325 if (coap_handle_response_get_block(context, session, sent, rcvd,
4326 COAP_RECURSE_OK)) {
4327 /* Next block transmitted, ack sent no need to inform app */
4328 return;
4329 }
4330 }
4331 coap_reset_doing_first(session);
4332
4333 /* Call application-specific response handler when available. */
4334 coap_call_response_handler(session, sent, rcvd, NULL);
4335}
4336#endif /* COAP_CLIENT_SUPPORT */
4337
4338#if !COAP_DISABLE_TCP
4339static void
4341 coap_pdu_t *pdu) {
4342 coap_opt_iterator_t opt_iter;
4343 coap_opt_t *option;
4344 int set_mtu = 0;
4345
4346 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4347
4348 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4349 if (session->csm_not_seen) {
4350 coap_tick_t now;
4351
4352 coap_ticks(&now);
4353 /* CSM timeout before CSM seen */
4354 coap_log_warn("***%s: CSM received after CSM timeout\n",
4355 coap_session_str(session));
4356 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4357 coap_session_str(session),
4358 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4359 }
4360 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4362 }
4363 while ((option = coap_option_next(&opt_iter))) {
4365 unsigned max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4366
4367 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4368 max_recv = COAP_DEFAULT_MAX_PDU_RX_SIZE;
4369 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4370 coap_session_str(session), max_recv);
4371 }
4372 coap_session_set_mtu(session, max_recv);
4373 set_mtu = 1;
4374 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4375 session->csm_block_supported = 1;
4376 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4377 session->max_token_size =
4379 coap_opt_length(option));
4382 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4385 }
4386 }
4387 if (set_mtu) {
4388 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4389 session->csm_bert_rem_support = 1;
4390 else
4391 session->csm_bert_rem_support = 0;
4392 }
4393 if (session->state == COAP_SESSION_STATE_CSM)
4394 coap_session_connected(session);
4395 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4397 if (context->ping_cb) {
4398 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4399 }
4400 if (pong) {
4402 coap_send_internal(session, pong, NULL);
4403 }
4404 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4405 session->last_pong = session->last_rx_tx;
4406 if (context->pong_cb) {
4407 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4408 }
4409 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4410 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4412 }
4413}
4414#endif /* !COAP_DISABLE_TCP */
4415
4416static int
4418 if (COAP_PDU_IS_REQUEST(pdu) &&
4419 pdu->actual_token.length >
4420 (session->type == COAP_SESSION_TYPE_CLIENT ?
4421 session->max_token_size : session->context->max_token_size)) {
4422 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4423 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4424 coap_opt_filter_t opt_filter;
4425 coap_pdu_t *response;
4426
4427 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4428 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4429 &opt_filter);
4430 if (!response) {
4431 coap_log_warn("coap_dispatch: cannot create error response\n");
4432 } else {
4433 /*
4434 * Note - have to leave in oversize token as per
4435 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4436 */
4437 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4438 coap_log_warn("coap_dispatch: error sending response\n");
4439 }
4440 } else {
4441 /* Indicate no extended token support */
4442 coap_send_rst_lkd(session, pdu);
4443 }
4444 return 0;
4445 }
4446 return 1;
4447}
4448
4449void
4451 coap_pdu_t *pdu) {
4452 coap_queue_t *sent = NULL;
4453 coap_pdu_t *response;
4454 coap_pdu_t *orig_pdu = NULL;
4455 coap_opt_filter_t opt_filter;
4456 int is_ping_rst;
4457 int packet_is_bad = 0;
4458#if COAP_OSCORE_SUPPORT
4459 coap_opt_iterator_t opt_iter;
4460 coap_pdu_t *dec_pdu = NULL;
4461#endif /* COAP_OSCORE_SUPPORT */
4462 int is_ext_token_rst = 0;
4463 int oscore_invalid = 0;
4464
4465 pdu->session = session;
4467
4468 /* Check validity of received code */
4469 if (!coap_check_code_class(session, pdu)) {
4470 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4472 pdu->code & 0x1f);
4473 packet_is_bad = 1;
4474 if (pdu->type == COAP_MESSAGE_CON) {
4476 }
4477 /* find message id in sendqueue to stop retransmission */
4478 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4479 goto cleanup;
4480 }
4481
4482 coap_option_filter_clear(&opt_filter);
4483
4484#if COAP_SERVER_SUPPORT
4485 /* See if this a repeat request */
4486 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4488 coap_digest_t digest;
4489
4490 coap_pdu_cksum(pdu, &digest);
4491 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4492#if COAP_OSCORE_SUPPORT
4493 uint8_t oscore_encryption = session->oscore_encryption;
4494
4495 session->oscore_encryption = 0;
4496#endif /* COAP_OSCORE_SUPPORT */
4497 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4498 cached_pdu must not be removed */
4500 coap_log_debug("Retransmit response to duplicate request\n");
4501 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4502#if COAP_OSCORE_SUPPORT
4503 session->oscore_encryption = oscore_encryption;
4504#endif /* COAP_OSCORE_SUPPORT */
4505 return;
4506 }
4507#if COAP_OSCORE_SUPPORT
4508 session->oscore_encryption = oscore_encryption;
4509#endif /* COAP_OSCORE_SUPPORT */
4510 }
4511 }
4512#endif /* COAP_SERVER_SUPPORT */
4513 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4514 if (!check_token_size(session, pdu)) {
4515 goto cleanup;
4516 }
4517 }
4518#if COAP_OSCORE_SUPPORT
4519 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4520 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4521 if (pdu->type == COAP_MESSAGE_NON) {
4522 coap_send_rst_lkd(session, pdu);
4523 goto cleanup;
4524 } else if (pdu->type == COAP_MESSAGE_CON) {
4525 if (COAP_PDU_IS_REQUEST(pdu)) {
4526 response =
4527 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4528
4529 if (!response) {
4530 coap_log_warn("coap_dispatch: cannot create error response\n");
4531 } else {
4532 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4533 coap_log_warn("coap_dispatch: error sending response\n");
4534 }
4535 } else {
4536 coap_send_rst_lkd(session, pdu);
4537 }
4538 }
4539 goto cleanup;
4540 }
4541
4542 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4543 int decrypt = 1;
4544#if COAP_SERVER_SUPPORT
4545 coap_opt_t *opt;
4546 coap_resource_t *resource;
4547 coap_uri_t uri;
4548#endif /* COAP_SERVER_SUPPORT */
4549
4550 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4551 decrypt = 0;
4552
4553#if COAP_SERVER_SUPPORT
4554 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4555 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4556 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4557 != NULL) {
4558 /* Need to check whether this is a direct or proxy session */
4559 memset(&uri, 0, sizeof(uri));
4560 uri.host.length = coap_opt_length(opt);
4561 uri.host.s = coap_opt_value(opt);
4562 resource = context->proxy_uri_resource;
4563 if (uri.host.length && resource && resource->proxy_name_count &&
4564 resource->proxy_name_list) {
4565 size_t i;
4566 for (i = 0; i < resource->proxy_name_count; i++) {
4567 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4568 break;
4569 }
4570 }
4571 if (i == resource->proxy_name_count) {
4572 /* This server is not hosting the proxy connection endpoint */
4573 decrypt = 0;
4574 }
4575 }
4576 }
4577#endif /* COAP_SERVER_SUPPORT */
4578 if (decrypt) {
4579 /* find message id in sendqueue to stop retransmission and get sent */
4580 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4581 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4582 orig_pdu = pdu;
4583 coap_pdu_reference_lkd(orig_pdu);
4584 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4585 if (session->recipient_ctx == NULL ||
4586 session->recipient_ctx->initial_state == 0) {
4587 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4588 }
4590 coap_delete_pdu_lkd(orig_pdu);
4591 return;
4592 } else {
4593 session->oscore_encryption = 1;
4594 pdu = dec_pdu;
4595 }
4596 coap_log_debug("Decrypted PDU\n");
4598 }
4599 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4600 session->oscore_encryption &&
4601 pdu->type != COAP_MESSAGE_RST) {
4602 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4603 /* Violates RFC 8613 2 */
4604 coap_log_err("received an invalid response to the OSCORE request\n");
4605 oscore_invalid = 1;
4606 }
4607 }
4608#endif /* COAP_OSCORE_SUPPORT */
4609
4610 switch (pdu->type) {
4611 case COAP_MESSAGE_ACK:
4612 /* find message id in sendqueue to stop retransmission */
4613 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4614
4615 if (sent && session->con_active) {
4616 session->con_active--;
4617 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4618 /* Flush out any entries on session->delayqueue */
4619 coap_session_connected(session);
4620 }
4621 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4622 packet_is_bad = 1;
4623 goto cleanup;
4624 }
4625
4626#if COAP_SERVER_SUPPORT
4627 /* if sent code was >= 64 the message might have been a
4628 * notification. Then, we must flag the observer to be alive
4629 * by setting obs->fail_cnt = 0. */
4630 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4631 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4632 }
4633#endif /* COAP_SERVER_SUPPORT */
4634
4635#if COAP_Q_BLOCK_SUPPORT
4636 if (session->lg_xmit && sent && sent->pdu && sent->pdu->type == COAP_MESSAGE_CON &&
4637 !(session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK)) {
4638 int doing_q_block = 0;
4639 coap_lg_xmit_t *lg_xmit = NULL;
4640
4641 LL_FOREACH(session->lg_xmit, lg_xmit) {
4642 if ((lg_xmit->option == COAP_OPTION_Q_BLOCK1 || lg_xmit->option == COAP_OPTION_Q_BLOCK2) &&
4643 lg_xmit->last_all_sent == 0 && lg_xmit->sent_pdu->type != COAP_MESSAGE_NON) {
4644 doing_q_block = 1;
4645 break;
4646 }
4647 }
4648 if (doing_q_block && lg_xmit) {
4649 coap_block_b_t block;
4650
4651 memset(&block, 0, sizeof(block));
4652 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
4653 block.num = lg_xmit->last_block + lg_xmit->b.b1.count;
4654 } else {
4655 block.num = lg_xmit->last_block;
4656 }
4657 block.m = 1;
4658 block.szx = block.aszx = lg_xmit->blk_size;
4659 block.defined = 1;
4660 block.bert = 0;
4661 block.chunk_size = 1024;
4662
4663 coap_send_q_blocks(session, lg_xmit, block,
4664 lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
4665 }
4666 }
4667#endif /* COAP_Q_BLOCK_SUPPORT */
4668 if (pdu->code == 0) {
4669#if COAP_CLIENT_SUPPORT
4670 /*
4671 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4672 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4673 * response if the response was piggy-backed. Here, a separate response
4674 * detected and so the lg_crcv needs to be set up before the sent PDU
4675 * information is lost.
4676 *
4677 * lg_crcv was not set up if not a CoAP request.
4678 *
4679 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4680 * options.
4681 */
4682 if (sent &&
4683 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4684 COAP_PDU_IS_REQUEST(sent->pdu)) {
4685 /*
4686 * lg_crcv was not set up in coap_send(). It could have been set up
4687 * the first separate response.
4688 * See if there already is a lg_crcv set up.
4689 */
4690 coap_lg_crcv_t *lg_crcv;
4691 uint64_t token_match =
4693 sent->pdu->actual_token.length));
4694
4695 LL_FOREACH(session->lg_crcv, lg_crcv) {
4696 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4697 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4698 break;
4699 }
4700 }
4701 if (!lg_crcv) {
4702 /*
4703 * Need to set up a lg_crcv as it was not set up in coap_send()
4704 * to save time, but server has not sent back a piggy-back response.
4705 */
4706 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4707 if (lg_crcv) {
4708 LL_PREPEND(session->lg_crcv, lg_crcv);
4709 }
4710 }
4711 }
4712#endif /* COAP_CLIENT_SUPPORT */
4713 /* an empty ACK needs no further handling */
4714 goto cleanup;
4715 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4716 /* This is not legitimate - Request using ACK - ignore */
4717 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4719 pdu->code & 0x1f);
4720 packet_is_bad = 1;
4721 goto cleanup;
4722 }
4723
4724 break;
4725
4726 case COAP_MESSAGE_RST:
4727 /* We have sent something the receiver disliked, so we remove
4728 * not only the message id but also the subscriptions we might
4729 * have. */
4730 is_ping_rst = 0;
4731 if (pdu->mid == session->last_ping_mid &&
4732 session->last_ping > 0)
4733 is_ping_rst = 1;
4734
4735#if COAP_CLIENT_SUPPORT
4736#if COAP_Q_BLOCK_SUPPORT
4737 /* Check to see if checking out Q-Block support */
4738 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4739 session->remote_test_mid == pdu->mid) {
4740 coap_log_debug("Q-Block support not available\n");
4741 set_block_mode_drop_q(session->block_mode);
4742 coap_reset_doing_first(session);
4743 }
4744#endif /* COAP_Q_BLOCK_SUPPORT */
4745
4746 /* Check to see if checking out extended token support */
4747 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4748 session->remote_test_mid == pdu->mid) {
4749 coap_log_debug("Extended Token support not available\n");
4752 coap_reset_doing_first(session);
4753 is_ext_token_rst = 1;
4754 }
4755#endif /* COAP_CLIENT_SUPPORT */
4756
4757 if (!is_ping_rst && !is_ext_token_rst)
4758 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4759
4760 if (session->con_active) {
4761 session->con_active--;
4762 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4763 /* Flush out any entries on session->delayqueue */
4764 coap_session_connected(session);
4765 }
4766
4767 /* find message id in sendqueue to stop retransmission */
4768 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4769
4770 if (sent) {
4771 if (!is_ping_rst)
4772 coap_cancel(context, sent);
4773
4774 if (!is_ping_rst && !is_ext_token_rst) {
4775 if (sent->pdu->type==COAP_MESSAGE_CON) {
4776 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4777 }
4778 } else if (is_ping_rst) {
4779 if (context->pong_cb) {
4780 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4781 }
4782 session->last_pong = session->last_rx_tx;
4784 }
4785 } else {
4786#if COAP_SERVER_SUPPORT
4787 /* Need to check is there is a subscription active and delete it */
4788 RESOURCES_ITER(context->resources, r) {
4789 coap_subscription_t *obs, *tmp;
4790 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4791 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4792 /* Need to do this now as session may get de-referenced */
4794 coap_delete_observer(r, session, &obs->pdu->actual_token);
4795 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4796 coap_session_release_lkd(session);
4797 goto cleanup;
4798 }
4799 }
4800 }
4801#endif /* COAP_SERVER_SUPPORT */
4802 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4803 }
4804#if COAP_PROXY_SUPPORT
4805 if (!is_ping_rst) {
4806 /* Need to check is there is a proxy subscription active and delete it */
4807 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
4808 }
4809#endif /* COAP_PROXY_SUPPORT */
4810 goto cleanup;
4811
4812 case COAP_MESSAGE_NON:
4813 /* check for oscore issue or unknown critical options */
4814 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4815 packet_is_bad = 1;
4816 coap_send_rst_lkd(session, pdu);
4817 goto cleanup;
4818 }
4819 break;
4820
4821 case COAP_MESSAGE_CON:
4822 /* In a lossy context, the ACK of a separate response may have
4823 * been lost, so we need to stop retransmitting requests with the
4824 * same token. Matching on token potentially containing ext length bytes.
4825 */
4826 /* find message token in sendqueue to stop retransmission */
4827 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4828
4829 /* check for oscore issue or unknown critical options in non-signaling messages */
4830 if (oscore_invalid ||
4831 (!COAP_PDU_IS_SIGNALING(pdu) && coap_option_check_critical(session, pdu, &opt_filter) == 0)) {
4832 packet_is_bad = 1;
4833 if (COAP_PDU_IS_REQUEST(pdu)) {
4834 response =
4835 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4836
4837 if (!response) {
4838 coap_log_warn("coap_dispatch: cannot create error response\n");
4839 } else {
4840 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4841 coap_log_warn("coap_dispatch: error sending response\n");
4842 }
4843 } else {
4844 coap_send_rst_lkd(session, pdu);
4845 }
4846 goto cleanup;
4847 }
4848 break;
4849 default:
4850 break;
4851 }
4852
4853 /* Pass message to upper layer if a specific handler was
4854 * registered for a request that should be handled locally. */
4855#if !COAP_DISABLE_TCP
4856 if (COAP_PDU_IS_SIGNALING(pdu))
4857 handle_signaling(context, session, pdu);
4858 else
4859#endif /* !COAP_DISABLE_TCP */
4860#if COAP_SERVER_SUPPORT
4861 if (COAP_PDU_IS_REQUEST(pdu))
4862 handle_request(context, session, pdu, orig_pdu);
4863 else
4864#endif /* COAP_SERVER_SUPPORT */
4865#if COAP_CLIENT_SUPPORT
4866 if (COAP_PDU_IS_RESPONSE(pdu))
4867 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4868 else
4869#endif /* COAP_CLIENT_SUPPORT */
4870 {
4871 if (COAP_PDU_IS_EMPTY(pdu)) {
4872 if (context->ping_cb) {
4873 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4874 }
4875 } else {
4876 packet_is_bad = 1;
4877 }
4878 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4880 pdu->code & 0x1f);
4881
4882 if (!coap_is_mcast(&session->addr_info.local)) {
4883 if (COAP_PDU_IS_EMPTY(pdu)) {
4884 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4885 coap_tick_t now;
4886 coap_ticks(&now);
4887 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4889 session->last_tx_rst = now;
4890 }
4891 }
4892 } else {
4893 if (pdu->type == COAP_MESSAGE_CON)
4895 }
4896 }
4897 }
4898
4899cleanup:
4900 if (packet_is_bad) {
4901 if (sent) {
4902 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
4903 } else {
4905 }
4906 }
4907 coap_delete_pdu_lkd(orig_pdu);
4909#if COAP_OSCORE_SUPPORT
4910 coap_delete_pdu_lkd(dec_pdu);
4911#endif /* COAP_OSCORE_SUPPORT */
4912}
4913
4914#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4915static const char *
4917 switch (event) {
4919 return "COAP_EVENT_DTLS_CLOSED";
4921 return "COAP_EVENT_DTLS_CONNECTED";
4923 return "COAP_EVENT_DTLS_RENEGOTIATE";
4925 return "COAP_EVENT_DTLS_ERROR";
4927 return "COAP_EVENT_TCP_CONNECTED";
4929 return "COAP_EVENT_TCP_CLOSED";
4931 return "COAP_EVENT_TCP_FAILED";
4933 return "COAP_EVENT_SESSION_CONNECTED";
4935 return "COAP_EVENT_SESSION_CLOSED";
4937 return "COAP_EVENT_SESSION_FAILED";
4939 return "COAP_EVENT_PARTIAL_BLOCK";
4941 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4943 return "COAP_EVENT_SERVER_SESSION_NEW";
4945 return "COAP_EVENT_SERVER_SESSION_DEL";
4947 return "COAP_EVENT_SERVER_SESSION_CONNECTED";
4949 return "COAP_EVENT_BAD_PACKET";
4951 return "COAP_EVENT_MSG_RETRANSMITTED";
4953 return "COAP_EVENT_FIRST_PDU_FAIL";
4955 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4957 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4959 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4961 return "COAP_EVENT_OSCORE_NO_SECURITY";
4963 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4965 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4967 return "COAP_EVENT_WS_PACKET_SIZE";
4969 return "COAP_EVENT_WS_CONNECTED";
4971 return "COAP_EVENT_WS_CLOSED";
4973 return "COAP_EVENT_KEEPALIVE_FAILURE";
4975 return "COAP_EVENT_RECONNECT_FAILED";
4977 return "COAP_EVENT_RECONNECT_SUCCESS";
4979 return "COAP_EVENT_RECONNECT_NO_MORE";
4981 return "COAP_EVENT_RECONNECT_STARTED";
4982 default:
4983 return "???";
4984 }
4985}
4986#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4987
4988COAP_API int
4990 coap_session_t *session) {
4991 int ret;
4992
4993 coap_lock_lock(return 0);
4994 ret = coap_handle_event_lkd(context, event, session);
4996 return ret;
4997}
4998
4999int
5001 coap_session_t *session) {
5002 int ret = 0;
5003
5004 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
5005
5006 if (context->event_cb) {
5007 coap_lock_callback_ret(ret, context->event_cb(session, event));
5008#if COAP_PROXY_SUPPORT
5009 if (event == COAP_EVENT_SERVER_SESSION_DEL)
5010 coap_proxy_remove_association(session, 0);
5011#endif /* COAP_PROXY_SUPPORT */
5012#if COAP_CLIENT_SUPPORT
5013 switch (event) {
5028 /* Those that are deemed fatal to end sending a request */
5029 session->doing_send_recv = 0;
5030 break;
5032 /* Session will now be available as well - for call-home */
5033 if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
5035 session);
5036 }
5037 break;
5043 break;
5045 /* Session will now be available as well - for call-home if not (D)TLS */
5046 if (session->type == COAP_SESSION_TYPE_SERVER &&
5047 (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
5049 session);
5050 }
5051 break;
5055 break;
5057 /* Session will now be available as well - for call-home if not (D)TLS */
5058 if (session->proto == COAP_PROTO_UDP) {
5060 session);
5061 }
5062 break;
5070 default:
5071 break;
5072 }
5073#endif /* COAP_CLIENT_SUPPORT */
5074 }
5075 return ret;
5076}
5077
5078COAP_API int
5080 int ret;
5081
5082 coap_lock_lock(return 0);
5083 ret = coap_can_exit_lkd(context);
5085 return ret;
5086}
5087
5088int
5090 coap_session_t *s, *rtmp;
5091 if (!context)
5092 return 1;
5094 if (context->sendqueue)
5095 return 0;
5096#if COAP_SERVER_SUPPORT
5097 coap_endpoint_t *ep;
5098
5099 LL_FOREACH(context->endpoint, ep) {
5100 SESSIONS_ITER(ep->sessions, s, rtmp) {
5101 if (s->delayqueue)
5102 return 0;
5103 if (s->lg_xmit)
5104 return 0;
5105 }
5106 }
5107#endif /* COAP_SERVER_SUPPORT */
5108#if COAP_CLIENT_SUPPORT
5109 SESSIONS_ITER(context->sessions, s, rtmp) {
5110 if (s->delayqueue)
5111 return 0;
5112 if (s->lg_xmit)
5113 return 0;
5114 }
5115#endif /* COAP_CLIENT_SUPPORT */
5116 return 1;
5117}
5118#if COAP_SERVER_SUPPORT
5119#if COAP_ASYNC_SUPPORT
5120/*
5121 * Return 1 if there is a future expire time, else 0.
5122 * Update tim_rem with remaining value if return is 1.
5123 */
5124int
5125coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5127 coap_async_t *async, *tmp;
5128 int ret = 0;
5129
5130 if (context->async_state_traversing)
5131 return 0;
5132 context->async_state_traversing = 1;
5133 LL_FOREACH_SAFE(context->async_state, async, tmp) {
5134 if (async->delay != 0) {
5135 if (async->delay <= now) {
5136 /* Send off the request to the application */
5137 coap_log_debug("Async PDU presented to app.\n");
5138 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5139 handle_request(context, async->session, async->pdu, NULL);
5140
5141 /* Remove this async entry as it has now fired */
5142 coap_free_async_lkd(async->session, async);
5143 } else {
5144 next_due = async->delay - now;
5145 ret = 1;
5146 }
5147 }
5148 }
5149 if (tim_rem)
5150 *tim_rem = next_due;
5151 context->async_state_traversing = 0;
5152 return ret;
5153}
5154#endif /* COAP_ASYNC_SUPPORT */
5155#endif /* COAP_SERVER_SUPPORT */
5156
5158uint8_t coap_unique_id[8] = { 0 };
5159
5160#if COAP_THREAD_SAFE
5161/*
5162 * Global lock for multi-thread support
5163 */
5164coap_lock_t global_lock;
5165/*
5166 * low level protection mutex
5167 */
5168coap_mutex_t m_show_pdu;
5169coap_mutex_t m_log_impl;
5170coap_mutex_t m_io_threads;
5171#endif /* COAP_THREAD_SAFE */
5172
5173void
5175 coap_tick_t now;
5176#ifndef WITH_CONTIKI
5177 uint64_t us;
5178#endif /* !WITH_CONTIKI */
5179
5180 if (coap_started)
5181 return;
5182 coap_started = 1;
5183
5184#if COAP_THREAD_SAFE
5186 coap_mutex_init(&m_show_pdu);
5187 coap_mutex_init(&m_log_impl);
5188 coap_mutex_init(&m_io_threads);
5189#endif /* COAP_THREAD_SAFE */
5190
5191#if defined(HAVE_WINSOCK2_H)
5192 WORD wVersionRequested = MAKEWORD(2, 2);
5193 WSADATA wsaData;
5194 WSAStartup(wVersionRequested, &wsaData);
5195#endif
5197 coap_ticks(&now);
5198#ifndef WITH_CONTIKI
5199 us = coap_ticks_to_rt_us(now);
5200 /* Be accurate to the nearest (approx) us */
5201 coap_prng_init_lkd((unsigned int)us);
5202#else /* WITH_CONTIKI */
5203 coap_start_io_process();
5204#endif /* WITH_CONTIKI */
5207#ifdef WITH_LWIP
5208 coap_io_lwip_init();
5209#endif /* WITH_LWIP */
5210#if COAP_SERVER_SUPPORT
5211 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5212 (const uint8_t *)".well-known/core"
5213 };
5214 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5215 resource_uri_wellknown.ref = 1;
5216 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5217 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5218 resource_uri_wellknown.uri_path = &well_known;
5219#endif /* COAP_SERVER_SUPPORT */
5222}
5223
5224void
5226 if (!coap_started)
5227 return;
5228 coap_started = 0;
5229#if defined(HAVE_WINSOCK2_H)
5230 WSACleanup();
5231#elif defined(WITH_CONTIKI)
5232 coap_stop_io_process();
5233#endif
5234#ifdef WITH_LWIP
5235 coap_io_lwip_cleanup();
5236#endif /* WITH_LWIP */
5238
5239#if COAP_THREAD_SAFE
5240 coap_mutex_destroy(&m_show_pdu);
5241 coap_mutex_destroy(&m_log_impl);
5242 coap_mutex_destroy(&m_io_threads);
5243#endif /* COAP_THREAD_SAFE */
5244
5246}
5247
5248void
5250 coap_response_handler_t handler) {
5251#if COAP_CLIENT_SUPPORT
5252 context->response_cb = handler;
5253#else /* ! COAP_CLIENT_SUPPORT */
5254 (void)context;
5255 (void)handler;
5256#endif /* ! COAP_CLIENT_SUPPORT */
5257}
5258
5259void
5262#if COAP_PROXY_SUPPORT
5263 context->proxy_response_cb = handler;
5264#else /* ! COAP_PROXY_SUPPORT */
5265 (void)context;
5266 (void)handler;
5267#endif /* ! COAP_PROXY_SUPPORT */
5268}
5269
5270void
5272 coap_nack_handler_t handler) {
5273 context->nack_cb = handler;
5274}
5275
5276void
5278 coap_ping_handler_t handler) {
5279 context->ping_cb = handler;
5280}
5281
5282void
5284 coap_pong_handler_t handler) {
5285 context->pong_cb = handler;
5286}
5287
5288void
5290 coap_resource_dynamic_create_t dyn_create_handler,
5291 uint32_t dynamic_max) {
5292 context->dyn_create_handler = dyn_create_handler;
5293 context->dynamic_max = dynamic_max;
5294 return;
5295}
5296
5297COAP_API void
5299 coap_lock_lock(return);
5300 coap_register_option_lkd(ctx, type);
5302}
5303
5304void
5307}
5308
5309#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5310#if COAP_SERVER_SUPPORT
5311COAP_API int
5312coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5313 const char *ifname) {
5314 int ret;
5315
5316 coap_lock_lock(return -1);
5317 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
5319 return ret;
5320}
5321
5322int
5323coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
5324 const char *ifname) {
5325#if COAP_IPV4_SUPPORT
5326 struct ip_mreq mreq4;
5327#endif /* COAP_IPV4_SUPPORT */
5328#if COAP_IPV6_SUPPORT
5329 struct ipv6_mreq mreq6;
5330#endif /* COAP_IPV6_SUPPORT */
5331 struct addrinfo *resmulti = NULL, hints, *ainfo;
5332 int result = -1;
5333 coap_endpoint_t *endpoint;
5334 int mgroup_setup = 0;
5335
5336 /* Need to have at least one endpoint! */
5337 assert(ctx->endpoint);
5338 if (!ctx->endpoint)
5339 return -1;
5340
5341 /* Default is let the kernel choose */
5342#if COAP_IPV6_SUPPORT
5343 mreq6.ipv6mr_interface = 0;
5344#endif /* COAP_IPV6_SUPPORT */
5345#if COAP_IPV4_SUPPORT
5346 mreq4.imr_interface.s_addr = INADDR_ANY;
5347#endif /* COAP_IPV4_SUPPORT */
5348
5349 memset(&hints, 0, sizeof(hints));
5350 hints.ai_socktype = SOCK_DGRAM;
5351
5352 /* resolve the multicast group address */
5353 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5354
5355 if (result != 0) {
5356 coap_log_err("coap_join_mcast_group_intf: %s: "
5357 "Cannot resolve multicast address: %s\n",
5358 group_name, gai_strerror(result));
5359 goto finish;
5360 }
5361
5362 /* Need to do a windows equivalent at some point */
5363#ifndef _WIN32
5364 if (ifname) {
5365 /* interface specified - check if we have correct IPv4/IPv6 information */
5366 int done_ip4 = 0;
5367 int done_ip6 = 0;
5368#if defined(ESPIDF_VERSION)
5369 struct netif *netif;
5370#else /* !ESPIDF_VERSION */
5371#if COAP_IPV4_SUPPORT
5372 int ip4fd;
5373#endif /* COAP_IPV4_SUPPORT */
5374 struct ifreq ifr;
5375#endif /* !ESPIDF_VERSION */
5376
5377 /* See which mcast address family types are being asked for */
5378 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5379 ainfo = ainfo->ai_next) {
5380 switch (ainfo->ai_family) {
5381#if COAP_IPV6_SUPPORT
5382 case AF_INET6:
5383 if (done_ip6)
5384 break;
5385 done_ip6 = 1;
5386#if defined(ESPIDF_VERSION)
5387 netif = netif_find(ifname);
5388 if (netif)
5389 mreq6.ipv6mr_interface = netif_get_index(netif);
5390 else
5391 coap_log_err("coap_join_mcast_group_intf: %s: "
5392 "Cannot get IPv4 address: %s\n",
5393 ifname, coap_socket_strerror());
5394#else /* !ESPIDF_VERSION */
5395 memset(&ifr, 0, sizeof(ifr));
5396 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5397 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5398
5399#ifdef HAVE_IF_NAMETOINDEX
5400 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5401 if (mreq6.ipv6mr_interface == 0) {
5402 coap_log_warn("coap_join_mcast_group_intf: "
5403 "cannot get interface index for '%s'\n",
5404 ifname);
5405 }
5406#elif defined(__QNXNTO__)
5407#else /* !HAVE_IF_NAMETOINDEX */
5408 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5409 if (result != 0) {
5410 coap_log_warn("coap_join_mcast_group_intf: "
5411 "cannot get interface index for '%s': %s\n",
5412 ifname, coap_socket_strerror());
5413 } else {
5414 /* Capture the IPv6 if_index for later */
5415 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5416 }
5417#endif /* !HAVE_IF_NAMETOINDEX */
5418#endif /* !ESPIDF_VERSION */
5419#endif /* COAP_IPV6_SUPPORT */
5420 break;
5421#if COAP_IPV4_SUPPORT
5422 case AF_INET:
5423 if (done_ip4)
5424 break;
5425 done_ip4 = 1;
5426#if defined(ESPIDF_VERSION)
5427 netif = netif_find(ifname);
5428 if (netif)
5429 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5430 else
5431 coap_log_err("coap_join_mcast_group_intf: %s: "
5432 "Cannot get IPv4 address: %s\n",
5433 ifname, coap_socket_strerror());
5434#else /* !ESPIDF_VERSION */
5435 /*
5436 * Need an AF_INET socket to do this unfortunately to stop
5437 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5438 */
5439 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5440 if (ip4fd == -1) {
5441 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5442 ifname, coap_socket_strerror());
5443 continue;
5444 }
5445 memset(&ifr, 0, sizeof(ifr));
5446 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5447 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5448 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5449 if (result != 0) {
5450 coap_log_err("coap_join_mcast_group_intf: %s: "
5451 "Cannot get IPv4 address: %s\n",
5452 ifname, coap_socket_strerror());
5453 } else {
5454 /* Capture the IPv4 address for later */
5455 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5456 }
5457 close(ip4fd);
5458#endif /* !ESPIDF_VERSION */
5459 break;
5460#endif /* COAP_IPV4_SUPPORT */
5461 default:
5462 break;
5463 }
5464 }
5465 }
5466#else /* _WIN32 */
5467 /*
5468 * On Windows this function ignores the ifname variable so we unset this
5469 * variable on this platform in any case in order to enable the interface
5470 * selection from the bind address below.
5471 */
5472 ifname = 0;
5473#endif /* _WIN32 */
5474
5475 /* Add in mcast address(es) to appropriate interface */
5476 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5477 LL_FOREACH(ctx->endpoint, endpoint) {
5478 /* Only UDP currently supported */
5479 if (endpoint->proto == COAP_PROTO_UDP) {
5480 coap_address_t gaddr;
5481
5482 coap_address_init(&gaddr);
5483#if COAP_IPV6_SUPPORT
5484 if (ainfo->ai_family == AF_INET6) {
5485 if (!ifname) {
5486 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5487 /*
5488 * Do it on the ifindex that the server is listening on
5489 * (sin6_scope_id could still be 0)
5490 */
5491 mreq6.ipv6mr_interface =
5492 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5493 } else {
5494 mreq6.ipv6mr_interface = 0;
5495 }
5496 }
5497 gaddr.addr.sin6.sin6_family = AF_INET6;
5498 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5499 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5500 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5501 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5502 (char *)&mreq6, sizeof(mreq6));
5503 }
5504#endif /* COAP_IPV6_SUPPORT */
5505#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5506 else
5507#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5508#if COAP_IPV4_SUPPORT
5509 if (ainfo->ai_family == AF_INET) {
5510 if (!ifname) {
5511 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5512 /*
5513 * Do it on the interface that the server is listening on
5514 * (sin_addr could still be INADDR_ANY)
5515 */
5516 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5517 } else {
5518 mreq4.imr_interface.s_addr = INADDR_ANY;
5519 }
5520 }
5521 gaddr.addr.sin.sin_family = AF_INET;
5522 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5523 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5524 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5525 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5526 (char *)&mreq4, sizeof(mreq4));
5527 }
5528#endif /* COAP_IPV4_SUPPORT */
5529 else {
5530 continue;
5531 }
5532
5533 if (result == COAP_SOCKET_ERROR) {
5534 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5535 group_name, coap_socket_strerror());
5536 } else {
5537 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5538
5539 addr_str[sizeof(addr_str)-1] = '\000';
5540 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5541 sizeof(addr_str) - 1)) {
5542 if (ifname)
5543 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5544 ifname);
5545 else
5546 coap_log_debug("added mcast group %s\n", addr_str);
5547 }
5548 mgroup_setup = 1;
5549 }
5550 }
5551 }
5552 }
5553 if (!mgroup_setup) {
5554 result = -1;
5555 }
5556
5557finish:
5558 freeaddrinfo(resmulti);
5559
5560 return result;
5561}
5562
5563void
5565 context->mcast_per_resource = 1;
5566}
5567
5568#endif /* ! COAP_SERVER_SUPPORT */
5569
5570#if COAP_CLIENT_SUPPORT
5571int
5572coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5573 if (session && coap_is_mcast(&session->addr_info.remote)) {
5574 switch (session->addr_info.remote.addr.sa.sa_family) {
5575#if COAP_IPV4_SUPPORT
5576 case AF_INET:
5577 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5578 (const char *)&hops, sizeof(hops)) < 0) {
5579 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5580 hops, coap_socket_strerror());
5581 return 0;
5582 }
5583 return 1;
5584#endif /* COAP_IPV4_SUPPORT */
5585#if COAP_IPV6_SUPPORT
5586 case AF_INET6:
5587 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5588 (const char *)&hops, sizeof(hops)) < 0) {
5589 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5590 hops, coap_socket_strerror());
5591 return 0;
5592 }
5593 return 1;
5594#endif /* COAP_IPV6_SUPPORT */
5595 default:
5596 break;
5597 }
5598 }
5599 return 0;
5600}
5601#endif /* COAP_CLIENT_SUPPORT */
5602
5603#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
5604COAP_API int
5606 const char *group_name COAP_UNUSED,
5607 const char *ifname COAP_UNUSED) {
5608 return -1;
5609}
5610
5611int
5613 size_t hops COAP_UNUSED) {
5614 return 0;
5615}
5616
5617void
5619}
5620#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 PRIuS
#define PRIdS
#define PRIu32
const char * coap_socket_strerror(void)
Definition coap_io.c:935
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:2135
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:3043
#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:5225
#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:4916
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:3358
int coap_started
Definition coap_net.c:5157
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2420
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2461
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:4340
#define min(a, b)
Definition coap_net.c:76
void coap_startup(void)
Definition coap_net.c:5174
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4417
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:5158
#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:2829
void coap_reset_doing_first(coap_session_t *session)
Reset doing the first packet state when testing for optional functionality.
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:2759
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:2164
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:1484
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:2818
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:2752
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:233
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:5000
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:5305
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:2995
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:1352
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:4450
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:1872
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:5089
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2282
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:1419
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:3102
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:2934
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:3141
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:2143
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:1474
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:2138
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:5249
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:3174
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:5289
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:5277
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:5079
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:5298
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:5283
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:4989
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:5271
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:70
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:80
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:130
@ 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:149
@ COAP_EVENT_OSCORE_INTERNAL_ERROR
Triggered when there is an OSCORE internal error i.e malloc failed.
Definition coap_event.h:128
@ 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:137
@ 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:122
@ COAP_EVENT_RECONNECT_STARTED
Triggered when a session starts to reconnect.
Definition coap_event.h:155
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:139
@ COAP_EVENT_RECONNECT_NO_MORE
Triggered when a session failed, and retry reconnect attempts failed.
Definition coap_event.h:153
@ COAP_EVENT_SESSION_CLOSED
Triggered when TCP layer closes following exchange of CSM information.
Definition coap_event.h:67
@ COAP_EVENT_FIRST_PDU_FAIL
Triggered when the initial app PDU cannot be transmitted.
Definition coap_event.h:114
@ 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:126
@ 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:124
@ COAP_EVENT_RECONNECT_SUCCESS
Triggered when a session failed, and a reconnect is successful.
Definition coap_event.h:151
@ 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:135
@ 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:120
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:144
@ 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:1661
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:639
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:499
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:1358
#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:1084
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:1000
#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:593
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:733
#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:1523
#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:1499
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:1031
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:307
#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:789
#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:960
#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:366
#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:1489
#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:854
@ 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:5260
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:2491
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:1020
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:969
#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_app_data_free_callback_t app_cb
call-back to release app_data
coap_pong_handler_t pong_cb
Called when a ping response is received.
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_nack_handler_t nack_cb
Called when a response issue has occurred.
coap_response_handler_t response_cb
Called when a response is received.
coap_resource_dynamic_create_t dyn_create_handler
Dynamc resource create handler.
coap_session_t * sessions
client sessions
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_event_handler_t event_cb
Callback function that is used to signal events to the application.
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
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_ping_handler_t ping_cb
Called when a CoAP ping is received.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
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.
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_tick_t doing_first_timeout
If doing_first, when to timeout.
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_pdu_t * doing_first_pdu
If doing fist, PDU to retry sending.
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