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