libcoap 4.3.5-develop-433f483
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_final(digest_ctx, digest_buffer))
1833 return 0;
1834
1835 return 1;
1836
1837fail:
1838 coap_digest_free(digest_ctx);
1839 return 0;
1840}
1841#endif /* COAP_SERVER_SUPPORT */
1842
1845 uint8_t r;
1846 ssize_t bytes_written;
1847 coap_opt_iterator_t opt_iter;
1848
1849#if ! COAP_SERVER_SUPPORT
1850 (void)request_pdu;
1851#endif /* COAP_SERVER_SUPPORT */
1852 pdu->session = session;
1853#if COAP_CLIENT_SUPPORT
1854 if (session->session_failed) {
1855 coap_session_reconnect(session);
1856 if (session->session_failed)
1857 goto error;
1858 }
1859#endif /* COAP_CLIENT_SUPPORT */
1860#if COAP_PROXY_SUPPORT
1861 if (session->server_list) {
1862 /* Local session wanting to use proxy logic */
1863 return coap_proxy_local_write(session, pdu);
1864 }
1865#endif /* COAP_PROXY_SUPPORT */
1866 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1867 /*
1868 * Need to prepend our IP identifier to the data as per
1869 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1870 */
1871 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1872 coap_opt_t *opt;
1873 size_t hop_limit;
1874
1875 addr_str[sizeof(addr_str)-1] = '\000';
1876 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1877 sizeof(addr_str) - 1)) {
1878 char *cp;
1879 size_t len;
1880
1881 if (addr_str[0] == '[') {
1882 cp = strchr(addr_str, ']');
1883 if (cp)
1884 *cp = '\000';
1885 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1886 /* IPv4 embedded into IPv6 */
1887 cp = &addr_str[8];
1888 } else {
1889 cp = &addr_str[1];
1890 }
1891 } else {
1892 cp = strchr(addr_str, ':');
1893 if (cp)
1894 *cp = '\000';
1895 cp = addr_str;
1896 }
1897 len = strlen(cp);
1898
1899 /* See if Hop Limit option is being used in return path */
1900 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1901 if (opt) {
1902 uint8_t buf[4];
1903
1904 hop_limit =
1906 if (hop_limit == 1) {
1907 coap_log_warn("Proxy loop detected '%s'\n",
1908 (char *)pdu->data);
1911 } else if (hop_limit < 1 || hop_limit > 255) {
1912 /* Something is bad - need to drop this pdu (TODO or delete option) */
1913 coap_log_warn("Proxy return has bad hop limit count '%zu'\n",
1914 hop_limit);
1917 }
1918 hop_limit--;
1920 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1921 buf);
1922 }
1923
1924 /* Need to check that we are not seeing this proxy in the return loop */
1925 if (pdu->data && opt == NULL) {
1926 char *a_match;
1927 size_t data_len;
1928
1929 if (pdu->used_size + 1 > pdu->max_size) {
1930 /* No space */
1932 }
1933 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1934 /* Internal error */
1936 }
1937 data_len = pdu->used_size - (pdu->data - pdu->token);
1938 pdu->data[data_len] = '\000';
1939 a_match = strstr((char *)pdu->data, cp);
1940 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1941 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1942 a_match[len] == ' ')) {
1943 coap_log_warn("Proxy loop detected '%s'\n",
1944 (char *)pdu->data);
1947 }
1948 }
1949 if (pdu->used_size + len + 1 <= pdu->max_size) {
1950 size_t old_size = pdu->used_size;
1951 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1952 if (pdu->data == NULL) {
1953 /*
1954 * Set Hop Limit to max for return path. If this libcoap is in
1955 * a proxy loop path, it will always decrement hop limit in code
1956 * above and hence timeout / drop the response as appropriate
1957 */
1958 hop_limit = 255;
1960 (uint8_t *)&hop_limit);
1961 coap_add_data(pdu, len, (uint8_t *)cp);
1962 } else {
1963 /* prepend with space separator, leaving hop limit "as is" */
1964 memmove(pdu->data + len + 1, pdu->data,
1965 old_size - (pdu->data - pdu->token));
1966 memcpy(pdu->data, cp, len);
1967 pdu->data[len] = ' ';
1968 pdu->used_size += len + 1;
1969 }
1970 }
1971 }
1972 }
1973 }
1974
1975 if (session->echo) {
1976 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1977 session->echo->s))
1978 goto error;
1979 coap_delete_bin_const(session->echo);
1980 session->echo = NULL;
1981 }
1982#if COAP_OSCORE_SUPPORT
1983 if (session->oscore_encryption) {
1984 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1986 goto error;
1987 }
1988#endif /* COAP_OSCORE_SUPPORT */
1989
1990 if (!coap_pdu_encode_header(pdu, session->proto)) {
1991 goto error;
1992 }
1993
1994#if !COAP_DISABLE_TCP
1995 if (COAP_PROTO_RELIABLE(session->proto) &&
1997 if (!session->csm_block_supported) {
1998 /*
1999 * Need to check that this instance is not sending any block options as
2000 * the remote end via CSM has not informed us that there is support
2001 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2002 * This includes potential BERT blocks.
2003 */
2004 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2005 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2006 }
2007 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2008 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2009 }
2010 } else if (!session->csm_bert_rem_support) {
2011 coap_opt_t *opt;
2012
2013 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2014 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2015 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2016 }
2017 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2018 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2019 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2020 }
2021 }
2022 }
2023#endif /* !COAP_DISABLE_TCP */
2024
2025#if COAP_OSCORE_SUPPORT
2026 if (session->oscore_encryption &&
2027 pdu->type != COAP_MESSAGE_RST &&
2028 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2029 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2030 /* Refactor PDU as appropriate RFC8613 */
2031 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2032
2033 if (osc_pdu == NULL) {
2034 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2037 goto error;
2038 }
2039 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2041 pdu = osc_pdu;
2042 } else
2043#endif /* COAP_OSCORE_SUPPORT */
2044 bytes_written = coap_send_pdu(session, pdu, NULL);
2045
2046#if COAP_SERVER_SUPPORT
2047 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
2048 session->cached_pdu != pdu &&
2049 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2050 COAP_PDU_IS_REQUEST(request_pdu) &&
2051 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2053 session->cached_pdu = pdu;
2055 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
2056 }
2057#endif /* COAP_SERVER_SUPPORT */
2058
2059 if (bytes_written == COAP_PDU_DELAYED) {
2060 /* do not free pdu as it is stored with session for later use */
2061 return pdu->mid;
2062 }
2063 if (bytes_written < 0) {
2065 goto error;
2066 }
2067
2068#if !COAP_DISABLE_TCP
2069 if (COAP_PROTO_RELIABLE(session->proto) &&
2070 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2071 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2072 session->partial_write = (size_t)bytes_written;
2073 /* do not free pdu as it is stored with session for later use */
2074 return pdu->mid;
2075 } else {
2076 goto error;
2077 }
2078 }
2079#endif /* !COAP_DISABLE_TCP */
2080
2081 if (pdu->type != COAP_MESSAGE_CON
2082 || COAP_PROTO_RELIABLE(session->proto)) {
2083 coap_mid_t id = pdu->mid;
2085 return id;
2086 }
2087
2088 coap_queue_t *node = coap_new_node();
2089 if (!node) {
2090 coap_log_debug("coap_wait_ack: insufficient memory\n");
2091 goto error;
2092 }
2093
2094 node->id = pdu->mid;
2095 node->pdu = pdu;
2096 coap_prng_lkd(&r, sizeof(r));
2097 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2098 node->timeout = coap_calc_timeout(session, r);
2099 return coap_wait_ack(session->context, session, node);
2100error:
2102 return COAP_INVALID_MID;
2103}
2104
2105static int send_recv_terminate = 0;
2106
2107void
2111
2112COAP_API int
2114 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2115 int ret;
2116
2117 coap_lock_lock(return 0);
2118 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2120 return ret;
2121}
2122
2123/*
2124 * Return 0 or +ve Time in function in ms after successful transfer
2125 * -1 Invalid timeout parameter
2126 * -2 Failed to transmit PDU
2127 * -3 Nack or Event handler invoked, cancelling request
2128 * -4 coap_io_process returned error (fail to re-lock or select())
2129 * -5 Response not received in the given time
2130 * -6 Terminated by user
2131 * -7 Client mode code not enabled
2132 */
2133int
2135 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2136#if COAP_CLIENT_SUPPORT
2138 uint32_t rem_timeout = timeout_ms;
2139 uint32_t block_mode = session->block_mode;
2140 int ret = 0;
2141 coap_tick_t now;
2142 coap_tick_t start;
2143 coap_tick_t ticks_so_far;
2144 uint32_t time_so_far_ms;
2145
2146 coap_ticks(&start);
2147 assert(request_pdu);
2148
2150
2151 session->resp_pdu = NULL;
2152 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2153 request_pdu->actual_token.length);
2154
2155 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2156 ret = -1;
2157 goto fail;
2158 }
2159 if (session->state == COAP_SESSION_STATE_NONE) {
2160 ret = -3;
2161 goto fail;
2162 }
2163
2165 if (coap_is_mcast(&session->addr_info.remote))
2166 block_mode = session->block_mode;
2167
2168 session->doing_send_recv = 1;
2169 /* So the user needs to delete the PDU */
2170 coap_pdu_reference_lkd(request_pdu);
2171 mid = coap_send_lkd(session, request_pdu);
2172 if (mid == COAP_INVALID_MID) {
2173 if (!session->doing_send_recv)
2174 ret = -3;
2175 else
2176 ret = -2;
2177 goto fail;
2178 }
2179
2180 /* Wait for the response to come in */
2181 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2182 if (send_recv_terminate) {
2183 ret = -6;
2184 goto fail;
2185 }
2186 ret = coap_io_process_lkd(session->context, rem_timeout);
2187 if (ret < 0) {
2188 ret = -4;
2189 goto fail;
2190 }
2191 /* timeout_ms is for timeout between specific request and response */
2192 coap_ticks(&now);
2193 ticks_so_far = now - session->last_rx_tx;
2194 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2195 if (time_so_far_ms >= timeout_ms) {
2196 rem_timeout = 0;
2197 } else {
2198 rem_timeout = timeout_ms - time_so_far_ms;
2199 }
2200 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2201 /* To pick up on (D)TLS setup issues */
2202 coap_ticks(&now);
2203 ticks_so_far = now - start;
2204 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2205 if (time_so_far_ms >= timeout_ms) {
2206 rem_timeout = 0;
2207 } else {
2208 rem_timeout = timeout_ms - time_so_far_ms;
2209 }
2210 }
2211 }
2212
2213 if (rem_timeout) {
2214 coap_ticks(&now);
2215 ticks_so_far = now - start;
2216 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2217 ret = time_so_far_ms;
2218 /* Give PDU to user who will be calling coap_delete_pdu() */
2219 *response_pdu = session->resp_pdu;
2220 session->resp_pdu = NULL;
2221 if (*response_pdu == NULL) {
2222 ret = -3;
2223 }
2224 } else {
2225 /* If there is a resp_pdu, it will get cleared below */
2226 ret = -5;
2227 }
2228
2229fail:
2230 session->block_mode = block_mode;
2231 session->doing_send_recv = 0;
2232 /* delete referenced copy */
2233 coap_delete_pdu_lkd(session->resp_pdu);
2234 session->resp_pdu = NULL;
2236 session->req_token = NULL;
2237 return ret;
2238
2239#else /* !COAP_CLIENT_SUPPORT */
2240
2241 (void)session;
2242 (void)timeout_ms;
2243 (void)request_pdu;
2244 coap_log_warn("coap_send_recv: Client mode not supported\n");
2245 *response_pdu = NULL;
2246 return -7;
2247
2248#endif /* ! COAP_CLIENT_SUPPORT */
2249}
2250
2253 if (!context || !node || !node->session)
2254 return COAP_INVALID_MID;
2255
2256 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2257 if (node->retransmit_cnt < node->session->max_retransmit) {
2258 ssize_t bytes_written;
2259 coap_tick_t now;
2260 coap_tick_t next_delay;
2261 coap_address_t remote;
2262
2263 node->retransmit_cnt++;
2265
2266 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2267 if (context->ping_timeout &&
2268 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2269 uint8_t byte;
2270
2271 coap_prng_lkd(&byte, sizeof(byte));
2272 /* Don't exceed the ping timeout value */
2273 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2274 }
2275
2276 coap_ticks(&now);
2277 if (context->sendqueue == NULL) {
2278 node->t = next_delay;
2279 context->sendqueue_basetime = now;
2280 } else {
2281 /* make node->t relative to context->sendqueue_basetime */
2282 node->t = (now - context->sendqueue_basetime) + next_delay;
2283 }
2284 coap_insert_node(&context->sendqueue, node);
2285 coap_address_copy(&remote, &node->session->addr_info.remote);
2287
2288 if (node->is_mcast) {
2289 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2290 coap_session_str(node->session), node->id);
2291 } else {
2292 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2293 coap_session_str(node->session), node->id,
2294 node->retransmit_cnt,
2295 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2296 }
2297
2298 if (node->session->con_active)
2299 node->session->con_active--;
2300 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2301
2302 if (bytes_written == COAP_PDU_DELAYED) {
2303 /* PDU was not retransmitted immediately because a new handshake is
2304 in progress. node was moved to the send queue of the session. */
2305 return node->id;
2306 }
2307
2308 coap_address_copy(&node->session->addr_info.remote, &remote);
2309 if (node->is_mcast) {
2312 return COAP_INVALID_MID;
2313 }
2314
2315 if (bytes_written < 0)
2316 return (int)bytes_written;
2317
2318 return node->id;
2319 }
2320
2321 /* no more retransmissions, remove node from system */
2322 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2323 coap_session_str(node->session), node->id, node->retransmit_cnt);
2324
2325#if COAP_SERVER_SUPPORT
2326 /* Check if subscriptions exist that should be canceled after
2327 COAP_OBS_MAX_FAIL */
2328 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2329 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2330 if (context->ping_timeout) {
2333 return COAP_INVALID_MID;
2334 } else {
2335 if (node->session->ref_subscriptions)
2336 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2337#if COAP_PROXY_SUPPORT
2338 /* Need to check is there is a proxy subscription active and delete it */
2339 if (node->session->ref_proxy_subs)
2340 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2341 0, COAP_PROXY_SUBS_TOKEN);
2342#endif /* COAP_PROXY_SUPPORT */
2343 }
2344 }
2345#endif /* COAP_SERVER_SUPPORT */
2346 if (node->session->con_active) {
2347 node->session->con_active--;
2349 /*
2350 * As there may be another CON in a different queue entry on the same
2351 * session that needs to be immediately released,
2352 * coap_session_connected() is called.
2353 * However, there is the possibility coap_wait_ack() may be called for
2354 * this node (queue) and re-added to context->sendqueue.
2355 * coap_delete_node_lkd(node) called shortly will handle this and
2356 * remove it.
2357 */
2359 }
2360 }
2361
2362 if (node->pdu->type == COAP_MESSAGE_CON) {
2364 }
2365#if COAP_CLIENT_SUPPORT
2366 node->session->doing_send_recv = 0;
2367#endif /* COAP_CLIENT_SUPPORT */
2368 /* And finally delete the node */
2370 return COAP_INVALID_MID;
2371}
2372
2373static int
2375 uint8_t *data;
2376 size_t data_len;
2377 int result = -1;
2378
2379 coap_packet_get_memmapped(packet, &data, &data_len);
2380 if (session->proto == COAP_PROTO_DTLS) {
2381#if COAP_SERVER_SUPPORT
2382 if (session->type == COAP_SESSION_TYPE_HELLO)
2383 result = coap_dtls_hello(session, data, data_len);
2384 else
2385#endif /* COAP_SERVER_SUPPORT */
2386 if (session->tls)
2387 result = coap_dtls_receive(session, data, data_len);
2388 } else if (session->proto == COAP_PROTO_UDP) {
2389 result = coap_handle_dgram(ctx, session, data, data_len);
2390 }
2391 return result;
2392}
2393
2394#if COAP_CLIENT_SUPPORT
2395void
2397#if COAP_DISABLE_TCP
2398 (void)now;
2399
2401#else /* !COAP_DISABLE_TCP */
2402 if (coap_netif_strm_connect2(session)) {
2403 session->last_rx_tx = now;
2405 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2406 } else {
2409 }
2410#endif /* !COAP_DISABLE_TCP */
2411}
2412#endif /* COAP_CLIENT_SUPPORT */
2413
2414static void
2416 (void)ctx;
2417 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2418
2419 while (session->delayqueue) {
2420 ssize_t bytes_written;
2421 coap_queue_t *q = session->delayqueue;
2422
2423 coap_address_copy(&session->addr_info.remote, &q->remote);
2424 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2425 coap_session_str(session), (int)q->pdu->mid);
2426 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2427 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2428 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2429 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2430 if (bytes_written > 0)
2431 session->last_rx_tx = now;
2432 if (bytes_written <= 0 ||
2433 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2434 if (bytes_written > 0)
2435 session->partial_write += (size_t)bytes_written;
2436 break;
2437 }
2438 session->delayqueue = q->next;
2439 session->partial_write = 0;
2441 }
2442}
2443
2444void
2446#if COAP_CONSTRAINED_STACK
2447 /* payload and packet can be protected by global_lock if needed */
2448 static unsigned char payload[COAP_RXBUFFER_SIZE];
2449 static coap_packet_t s_packet;
2450#else /* ! COAP_CONSTRAINED_STACK */
2451 unsigned char payload[COAP_RXBUFFER_SIZE];
2452 coap_packet_t s_packet;
2453#endif /* ! COAP_CONSTRAINED_STACK */
2454 coap_packet_t *packet = &s_packet;
2455
2457
2458 packet->length = sizeof(payload);
2459 packet->payload = payload;
2460
2461 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2462 ssize_t bytes_read;
2463 coap_address_t remote;
2464
2465 coap_address_copy(&remote, &session->addr_info.remote);
2466 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2467 bytes_read = coap_netif_dgrm_read(session, packet);
2468
2469 if (bytes_read < 0) {
2470 if (bytes_read == -2) {
2471 coap_address_copy(&session->addr_info.remote, &remote);
2472 /* Reset the session back to startup defaults */
2474 }
2475 } else if (bytes_read > 0) {
2476 session->last_rx_tx = now;
2477#if COAP_CLIENT_SUPPORT
2478 if (session->session_failed)
2479 session->session_failed = 0;
2480#endif /* COAP_CLIENT_SUPPORT */
2481 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2482 coap_handle_dgram_for_proto(ctx, session, packet);
2483 } else {
2484 coap_address_copy(&session->addr_info.remote, &remote);
2485 }
2486#if !COAP_DISABLE_TCP
2487 } else if (session->proto == COAP_PROTO_WS ||
2488 session->proto == COAP_PROTO_WSS) {
2489 ssize_t bytes_read = 0;
2490
2491 /* WebSocket layer passes us the whole packet */
2492 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2493 packet->payload,
2494 packet->length);
2495 if (bytes_read < 0) {
2497 } else if (bytes_read > 2) {
2498 coap_pdu_t *pdu;
2499
2500 session->last_rx_tx = now;
2501 /* Need max space incase PDU is updated with updated token etc. */
2502 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2503 if (!pdu) {
2504 return;
2505 }
2506
2507 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2509 coap_log_warn("discard malformed PDU\n");
2511 return;
2512 }
2513
2514 coap_dispatch(ctx, session, pdu);
2516 return;
2517 }
2518 } else {
2519 ssize_t bytes_read = 0;
2520 const uint8_t *p;
2521 int retry;
2522
2523 do {
2524 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2525 packet->payload,
2526 packet->length);
2527 if (bytes_read > 0) {
2528 session->last_rx_tx = now;
2529 }
2530 p = packet->payload;
2531 retry = bytes_read == (ssize_t)packet->length;
2532 while (bytes_read > 0) {
2533 if (session->partial_pdu) {
2534 size_t len = session->partial_pdu->used_size
2535 + session->partial_pdu->hdr_size
2536 - session->partial_read;
2537 size_t n = min(len, (size_t)bytes_read);
2538 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2539 + session->partial_read, p, n);
2540 p += n;
2541 bytes_read -= n;
2542 if (n == len) {
2543 coap_opt_filter_t error_opts;
2544 coap_pdu_t *pdu = session->partial_pdu;
2545
2546 session->partial_pdu = NULL;
2547 session->partial_read = 0;
2548
2549 coap_option_filter_clear(&error_opts);
2550 if (coap_pdu_parse_header(pdu, session->proto)
2551 && coap_pdu_parse_opt(pdu, &error_opts)) {
2552 coap_dispatch(ctx, session, pdu);
2553 } else if (error_opts.mask) {
2554 coap_pdu_t *response =
2556 COAP_RESPONSE_CODE(402), &error_opts);
2557 if (!response) {
2558 coap_log_warn("coap_read_session: cannot create error response\n");
2559 } else {
2560 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2561 coap_log_warn("coap_read_session: error sending response\n");
2562 }
2563 }
2565 } else {
2566 session->partial_read += n;
2567 }
2568 } else if (session->partial_read > 0) {
2569 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2570 session->read_header);
2571 size_t tkl = session->read_header[0] & 0x0f;
2572 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2573 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2574 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2575 size_t n = min(len, (size_t)bytes_read);
2576 memcpy(session->read_header + session->partial_read, p, n);
2577 p += n;
2578 bytes_read -= n;
2579 if (n == len) {
2580 /* Header now all in */
2581 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2582 hdr_size + tok_ext_bytes);
2583 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2584 coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
2585 coap_session_str(session),
2586 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2587 bytes_read = -1;
2588 break;
2589 }
2590 /* Need max space incase PDU is updated with updated token etc. */
2591 session->partial_pdu = coap_pdu_init(0, 0, 0,
2593 if (session->partial_pdu == NULL) {
2594 bytes_read = -1;
2595 break;
2596 }
2597 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2598 bytes_read = -1;
2599 break;
2600 }
2601 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2602 session->partial_pdu->used_size = size;
2603 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2604 session->partial_read = hdr_size + tok_ext_bytes;
2605 if (size == 0) {
2606 coap_pdu_t *pdu = session->partial_pdu;
2607
2608 session->partial_pdu = NULL;
2609 session->partial_read = 0;
2610 if (coap_pdu_parse_header(pdu, session->proto)) {
2611 coap_dispatch(ctx, session, pdu);
2612 }
2614 }
2615 } else {
2616 /* More of the header to go */
2617 session->partial_read += n;
2618 }
2619 } else {
2620 /* Get in first byte of the header */
2621 session->read_header[0] = *p++;
2622 bytes_read -= 1;
2623 if (!coap_pdu_parse_header_size(session->proto,
2624 session->read_header)) {
2625 bytes_read = -1;
2626 break;
2627 }
2628 session->partial_read = 1;
2629 }
2630 }
2631 } while (bytes_read == 0 && retry);
2632 if (bytes_read < 0)
2634#endif /* !COAP_DISABLE_TCP */
2635 }
2636}
2637
2638#if COAP_SERVER_SUPPORT
2639static int
2640coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2641 ssize_t bytes_read = -1;
2642 int result = -1; /* the value to be returned */
2643#if COAP_CONSTRAINED_STACK
2644 /* payload and e_packet can be protected by global_lock if needed */
2645 static unsigned char payload[COAP_RXBUFFER_SIZE];
2646 static coap_packet_t e_packet;
2647#else /* ! COAP_CONSTRAINED_STACK */
2648 unsigned char payload[COAP_RXBUFFER_SIZE];
2649 coap_packet_t e_packet;
2650#endif /* ! COAP_CONSTRAINED_STACK */
2651 coap_packet_t *packet = &e_packet;
2652
2653 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2654 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2655
2656 /* Need to do this as there may be holes in addr_info */
2657 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2658 packet->length = sizeof(payload);
2659 packet->payload = payload;
2661 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2662
2663 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2664 if (bytes_read < 0) {
2665 if (errno != EAGAIN) {
2666 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2667 }
2668 } else if (bytes_read > 0) {
2669 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2670 if (session) {
2672 coap_log_debug("* %s: netif: recv %4zd bytes\n",
2673 coap_session_str(session), bytes_read);
2674 result = coap_handle_dgram_for_proto(ctx, session, packet);
2675 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2676 coap_session_new_dtls_session(session, now);
2677 coap_session_release_lkd(session);
2678 }
2679 }
2680 return result;
2681}
2682
2683static int
2684coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2685 (void)ctx;
2686 (void)endpoint;
2687 (void)now;
2688 return 0;
2689}
2690
2691#if !COAP_DISABLE_TCP
2692static int
2693coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2694 coap_tick_t now, void *extra) {
2695 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2696 if (session)
2697 session->last_rx_tx = now;
2698 return session != NULL;
2699}
2700#endif /* !COAP_DISABLE_TCP */
2701#endif /* COAP_SERVER_SUPPORT */
2702
2703COAP_API void
2705 coap_lock_lock(return);
2706 coap_io_do_io_lkd(ctx, now);
2708}
2709
2710void
2712#ifdef COAP_EPOLL_SUPPORT
2713 (void)ctx;
2714 (void)now;
2715 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2716#else /* ! COAP_EPOLL_SUPPORT */
2717 coap_session_t *s, *rtmp;
2718
2720#if COAP_SERVER_SUPPORT
2721 coap_endpoint_t *ep, *tmp;
2722 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2723 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2724 coap_read_endpoint(ctx, ep, now);
2725 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2726 coap_write_endpoint(ctx, ep, now);
2727#if !COAP_DISABLE_TCP
2728 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2729 coap_accept_endpoint(ctx, ep, now, NULL);
2730#endif /* !COAP_DISABLE_TCP */
2731 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2732 /* Make sure the session object is not deleted in one of the callbacks */
2734 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2735 coap_read_session(ctx, s, now);
2736 }
2737 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2738 coap_write_session(ctx, s, now);
2739 }
2741 }
2742 }
2743#endif /* COAP_SERVER_SUPPORT */
2744
2745#if COAP_CLIENT_SUPPORT
2746 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2747 /* Make sure the session object is not deleted in one of the callbacks */
2749 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2750 coap_connect_session(s, now);
2751 }
2752 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2753 coap_read_session(ctx, s, now);
2754 }
2755 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2756 coap_write_session(ctx, s, now);
2757 }
2759 }
2760#endif /* COAP_CLIENT_SUPPORT */
2761#endif /* ! COAP_EPOLL_SUPPORT */
2762}
2763
2764COAP_API void
2765coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2766 coap_lock_lock(return);
2767 coap_io_do_epoll_lkd(ctx, events, nevents);
2769}
2770
2771/*
2772 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2773 * directly saves having to iterate through the endpoints / sessions.
2774 */
2775void
2776coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2777#ifndef COAP_EPOLL_SUPPORT
2778 (void)ctx;
2779 (void)events;
2780 (void)nevents;
2781 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2782#else /* COAP_EPOLL_SUPPORT */
2783 coap_tick_t now;
2784 size_t j;
2785
2787 coap_ticks(&now);
2788 for (j = 0; j < nevents; j++) {
2789 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2790
2791 /* Ignore 'timer trigger' ptr which is NULL */
2792 if (sock) {
2793#if COAP_SERVER_SUPPORT
2794 if (sock->endpoint) {
2795 coap_endpoint_t *endpoint = sock->endpoint;
2796 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2797 (events[j].events & EPOLLIN)) {
2798 sock->flags |= COAP_SOCKET_CAN_READ;
2799 coap_read_endpoint(endpoint->context, endpoint, now);
2800 }
2801
2802 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2803 (events[j].events & EPOLLOUT)) {
2804 /*
2805 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2806 * be true causing epoll_wait to return early
2807 */
2808 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2810 coap_write_endpoint(endpoint->context, endpoint, now);
2811 }
2812
2813#if !COAP_DISABLE_TCP
2814 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2815 (events[j].events & EPOLLIN)) {
2817 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2818 }
2819#endif /* !COAP_DISABLE_TCP */
2820
2821 } else
2822#endif /* COAP_SERVER_SUPPORT */
2823 if (sock->session) {
2824 coap_session_t *session = sock->session;
2825
2826 /* Make sure the session object is not deleted
2827 in one of the callbacks */
2829#if COAP_CLIENT_SUPPORT
2830 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2831 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2833 coap_connect_session(session, now);
2834 if (coap_netif_available(session) &&
2835 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2836 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2837 }
2838 }
2839#endif /* COAP_CLIENT_SUPPORT */
2840
2841 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2842 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2843 sock->flags |= COAP_SOCKET_CAN_READ;
2844 coap_read_session(session->context, session, now);
2845 }
2846
2847 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2848 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2849 /*
2850 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2851 * be true causing epoll_wait to return early
2852 */
2853 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2855 coap_write_session(session->context, session, now);
2856 }
2857 /* Now dereference session so it can go away if needed */
2858 coap_session_release_lkd(session);
2859 }
2860 } else if (ctx->eptimerfd != -1) {
2861 /*
2862 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2863 * it so that it does not set EPOLLIN in the next epoll_wait().
2864 */
2865 uint64_t count;
2866
2867 /* Check the result from read() to suppress the warning on
2868 * systems that declare read() with warn_unused_result. */
2869 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2870 /* do nothing */;
2871 }
2872 }
2873 }
2874 /* And update eptimerfd as to when to next trigger */
2875 coap_ticks(&now);
2876 coap_io_prepare_epoll_lkd(ctx, now);
2877#endif /* COAP_EPOLL_SUPPORT */
2878}
2879
2880int
2882 uint8_t *msg, size_t msg_len) {
2883
2884 coap_pdu_t *pdu = NULL;
2885 coap_opt_filter_t error_opts;
2886
2887 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2888 if (msg_len < 4) {
2889 /* Minimum size of CoAP header - ignore runt */
2890 return -1;
2891 }
2892 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2893 /*
2894 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2895 * this MUST be silently ignored.
2896 */
2897 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2898 return -1;
2899 }
2900
2901 /* Need max space incase PDU is updated with updated token etc. */
2902 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2903 if (!pdu)
2904 goto error;
2905
2906 coap_option_filter_clear(&error_opts);
2907 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
2909 coap_log_warn("discard malformed PDU\n");
2910 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
2911 coap_pdu_t *response =
2913 COAP_RESPONSE_CODE(402), &error_opts);
2914 if (!response) {
2915 coap_log_warn("coap_handle_dgram: cannot create error response\n");
2916 } else {
2917 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2918 coap_log_warn("coap_handle_dgram: error sending response\n");
2919 }
2921 return -1;
2922 } else {
2923 goto error;
2924 }
2925 }
2926
2927 coap_dispatch(ctx, session, pdu);
2929 return 0;
2930
2931error:
2932 /*
2933 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2934 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2935 */
2936 coap_send_rst_lkd(session, pdu);
2938 return -1;
2939}
2940
2941int
2943 coap_queue_t **node) {
2944 coap_queue_t *p, *q;
2945
2946 if (!queue || !*queue)
2947 return 0;
2948
2949 /* replace queue head if PDU's time is less than head's time */
2950
2951 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2952 *node = *queue;
2953 *queue = (*queue)->next;
2954 if (*queue) { /* adjust relative time of new queue head */
2955 (*queue)->t += (*node)->t;
2956 }
2957 (*node)->next = NULL;
2958 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2959 coap_session_str(session), id);
2960 return 1;
2961 }
2962
2963 /* search message id in queue to remove (only first occurence will be removed) */
2964 q = *queue;
2965 do {
2966 p = q;
2967 q = q->next;
2968 } while (q && (session != q->session || id != q->id));
2969
2970 if (q) { /* found message id */
2971 p->next = q->next;
2972 if (p->next) { /* must update relative time of p->next */
2973 p->next->t += q->t;
2974 }
2975 q->next = NULL;
2976 *node = q;
2977 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
2978 coap_session_str(session), id);
2979 return 1;
2980 }
2981
2982 return 0;
2983
2984}
2985
2986static int
2988 coap_bin_const_t *token, coap_queue_t **node) {
2989 coap_queue_t *p, *q;
2990
2991 if (!queue || !*queue)
2992 return 0;
2993
2994 /* replace queue head if PDU's time is less than head's time */
2995
2996 if (session == (*queue)->session &&
2997 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
2998 *node = *queue;
2999 *queue = (*queue)->next;
3000 if (*queue) { /* adjust relative time of new queue head */
3001 (*queue)->t += (*node)->t;
3002 }
3003 (*node)->next = NULL;
3004 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3005 coap_session_str(session), (*node)->id);
3006 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3007 session->con_active--;
3008 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3009 /* Flush out any entries on session->delayqueue */
3010 coap_session_connected(session);
3011 }
3012 return 1;
3013 }
3014
3015 /* search token in queue to remove (only first occurence will be removed) */
3016 q = *queue;
3017 do {
3018 p = q;
3019 q = q->next;
3020 } while (q && (session != q->session ||
3021 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3022
3023 if (q) { /* found token */
3024 p->next = q->next;
3025 if (p->next) { /* must update relative time of p->next */
3026 p->next->t += q->t;
3027 }
3028 q->next = NULL;
3029 *node = q;
3030 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3031 coap_session_str(session), (*node)->id);
3032 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3033 session->con_active--;
3034 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3035 /* Flush out any entries on session->delayqueue */
3036 coap_session_connected(session);
3037 }
3038 return 1;
3039 }
3040
3041 return 0;
3042
3043}
3044
3045void
3047 coap_nack_reason_t reason) {
3048 coap_queue_t *p, *q;
3049
3050 while (context->sendqueue && context->sendqueue->session == session) {
3051 q = context->sendqueue;
3052 context->sendqueue = q->next;
3053 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3054 coap_session_str(session), q->id);
3055 if (q->pdu->type == COAP_MESSAGE_CON) {
3056 coap_handle_nack(session, q->pdu, reason, q->id);
3057 }
3059 }
3060
3061 if (!context->sendqueue)
3062 return;
3063
3064 p = context->sendqueue;
3065 q = p->next;
3066
3067 while (q) {
3068 if (q->session == session) {
3069 p->next = q->next;
3070 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3071 coap_session_str(session), q->id);
3072 if (q->pdu->type == COAP_MESSAGE_CON) {
3073 coap_handle_nack(session, q->pdu, reason, q->id);
3074 }
3076 q = p->next;
3077 } else {
3078 p = q;
3079 q = q->next;
3080 }
3081 }
3082}
3083
3084void
3086 coap_bin_const_t *token) {
3087 /* cancel all messages in sendqueue that belong to session
3088 * and use the specified token */
3089 coap_queue_t **p, *q;
3090
3091 if (!context->sendqueue)
3092 return;
3093
3094 p = &context->sendqueue;
3095 q = *p;
3096
3097 while (q) {
3098 if (q->session == session &&
3099 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3100 *p = q->next;
3101 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3102 coap_session_str(session), q->id);
3103 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3104 session->con_active--;
3105 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3106 /* Flush out any entries on session->delayqueue */
3107 coap_session_connected(session);
3108 }
3110 } else {
3111 p = &(q->next);
3112 }
3113 q = *p;
3114 }
3115}
3116
3117coap_pdu_t *
3119 coap_opt_filter_t *opts) {
3120 coap_opt_iterator_t opt_iter;
3121 coap_pdu_t *response;
3122 unsigned char type;
3123
3124#if COAP_ERROR_PHRASE_LENGTH > 0
3125 const char *phrase;
3126 if (code != COAP_RESPONSE_CODE(508)) {
3127 phrase = coap_response_phrase(code);
3128 } else {
3129 phrase = NULL;
3130 }
3131#endif
3132
3133 assert(request);
3134
3135 /* cannot send ACK if original request was not confirmable */
3136 type = request->type == COAP_MESSAGE_CON ?
3138
3139 /* Now create the response and fill with options and payload data. */
3140 response = coap_pdu_init(type, code, request->mid,
3141 request->session ?
3142 coap_session_max_pdu_size_lkd(request->session) : 512);
3143 if (response) {
3144 /* copy token */
3145 if (!coap_add_token(response, request->actual_token.length,
3146 request->actual_token.s)) {
3147 coap_log_debug("cannot add token to error response\n");
3148 coap_delete_pdu_lkd(response);
3149 return NULL;
3150 }
3151 if (response->code == COAP_RESPONSE_CODE(402)) {
3152 char buf[128];
3153 int first = 1;
3154
3155#if COAP_ERROR_PHRASE_LENGTH > 0
3156 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3157#else
3158 buf[0] = '\000';
3159#endif
3160 /* copy all options into diagnostic message */
3161 coap_option_iterator_init(request, &opt_iter, opts);
3162 while (coap_option_next(&opt_iter)) {
3163 size_t len = strlen(buf);
3164
3165 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",", opt_iter.number);
3166 first = 0;
3167 }
3168 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3169 } else if (opts && opts->mask) {
3170 coap_opt_t *option;
3171
3172 /* copy all options */
3173 coap_option_iterator_init(request, &opt_iter, opts);
3174 while ((option = coap_option_next(&opt_iter))) {
3175 coap_add_option_internal(response, opt_iter.number,
3176 coap_opt_length(option),
3177 coap_opt_value(option));
3178 }
3179#if COAP_ERROR_PHRASE_LENGTH > 0
3180 if (phrase)
3181 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3182 } else {
3183 /* note that diagnostic messages do not need a Content-Format option. */
3184 if (phrase)
3185 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3186#endif
3187 }
3188 }
3189
3190 return response;
3191}
3192
3193#if COAP_SERVER_SUPPORT
3194#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3195
3196static void
3197free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3198 coap_delete_string(app_ptr);
3199}
3200
3201/*
3202 * Caution: As this handler is in libcoap space, it is called with
3203 * context locked.
3204 */
3205static void
3206hnd_get_wellknown_lkd(coap_resource_t *resource,
3207 coap_session_t *session,
3208 const coap_pdu_t *request,
3209 const coap_string_t *query,
3210 coap_pdu_t *response) {
3211 size_t len = 0;
3212 coap_string_t *data_string = NULL;
3213 coap_print_status_t result = 0;
3214 size_t wkc_len = 0;
3215 uint8_t buf[4];
3216
3217 /*
3218 * Quick hack to determine the size of the resource descriptions for
3219 * .well-known/core.
3220 */
3221 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3222 if (result & COAP_PRINT_STATUS_ERROR) {
3223 coap_log_warn("cannot determine length of /.well-known/core\n");
3224 goto error;
3225 }
3226
3227 if (wkc_len > 0) {
3228 data_string = coap_new_string(wkc_len);
3229 if (!data_string)
3230 goto error;
3231
3232 len = wkc_len;
3233 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3234 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3235 coap_log_debug("coap_print_wellknown failed\n");
3236 goto error;
3237 }
3238 assert(len <= (size_t)wkc_len);
3239 data_string->length = len;
3240
3241 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3243 coap_encode_var_safe(buf, sizeof(buf),
3245 goto error;
3246 }
3247 if (response->used_size + len + 1 > response->max_size) {
3248 /*
3249 * Data does not fit into a packet and no libcoap block support
3250 * +1 for end of options marker
3251 */
3252 coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
3253 len, response->max_size - response->used_size - 1);
3254 len = response->max_size - response->used_size - 1;
3255 }
3256 if (!coap_add_data(response, len, data_string->s)) {
3257 goto error;
3258 }
3259 free_wellknown_response(session, data_string);
3260 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3261 response, query,
3263 -1, 0, data_string->length,
3264 data_string->s,
3265 free_wellknown_response,
3266 data_string)) {
3267 goto error_released;
3268 }
3269 } else {
3271 coap_encode_var_safe(buf, sizeof(buf),
3273 goto error;
3274 }
3275 }
3276 response->code = COAP_RESPONSE_CODE(205);
3277 return;
3278
3279error:
3280 free_wellknown_response(session, data_string);
3281error_released:
3282 if (response->code == 0) {
3283 /* set error code 5.03 and remove all options and data from response */
3284 response->code = COAP_RESPONSE_CODE(503);
3285 response->used_size = response->e_token_length;
3286 response->data = NULL;
3287 }
3288}
3289#endif /* COAP_SERVER_SUPPORT */
3290
3301static int
3303 int num_cancelled = 0; /* the number of observers cancelled */
3304
3305#ifndef COAP_SERVER_SUPPORT
3306 (void)sent;
3307#endif /* ! COAP_SERVER_SUPPORT */
3308 (void)context;
3309
3310#if COAP_SERVER_SUPPORT
3311 /* remove observer for this resource, if any
3312 * Use token from sent and try to find a matching resource. Uh!
3313 */
3314 RESOURCES_ITER(context->resources, r) {
3315 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3316 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3317 }
3318#endif /* COAP_SERVER_SUPPORT */
3319
3320 return num_cancelled;
3321}
3322
3323#if COAP_SERVER_SUPPORT
3328enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3329
3330/*
3331 * Checks for No-Response option in given @p request and
3332 * returns @c RESPONSE_DROP if @p response should be suppressed
3333 * according to RFC 7967.
3334 *
3335 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3336 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3337 * on retrying.
3338 *
3339 * Checks if the response code is 0.00 and if either the session is reliable or
3340 * non-confirmable, @c RESPONSE_DROP is also returned.
3341 *
3342 * Multicast response checking is also carried out.
3343 *
3344 * NOTE: It is the responsibility of the application to determine whether
3345 * a delayed separate response should be sent as the original requesting packet
3346 * containing the No-Response option has long since gone.
3347 *
3348 * The value of the No-Response option is encoded as
3349 * follows:
3350 *
3351 * @verbatim
3352 * +-------+-----------------------+-----------------------------------+
3353 * | Value | Binary Representation | Description |
3354 * +-------+-----------------------+-----------------------------------+
3355 * | 0 | <empty> | Interested in all responses. |
3356 * +-------+-----------------------+-----------------------------------+
3357 * | 2 | 00000010 | Not interested in 2.xx responses. |
3358 * +-------+-----------------------+-----------------------------------+
3359 * | 8 | 00001000 | Not interested in 4.xx responses. |
3360 * +-------+-----------------------+-----------------------------------+
3361 * | 16 | 00010000 | Not interested in 5.xx responses. |
3362 * +-------+-----------------------+-----------------------------------+
3363 * @endverbatim
3364 *
3365 * @param request The CoAP request to check for the No-Response option.
3366 * This parameter must not be NULL.
3367 * @param response The response that is potentially suppressed.
3368 * This parameter must not be NULL.
3369 * @param session The session this request/response are associated with.
3370 * This parameter must not be NULL.
3371 * @return RESPONSE_DEFAULT when no special treatment is requested,
3372 * RESPONSE_DROP when the response must be discarded, or
3373 * RESPONSE_SEND when the response must be sent.
3374 */
3375static enum respond_t
3376no_response(coap_pdu_t *request, coap_pdu_t *response,
3377 coap_session_t *session, coap_resource_t *resource) {
3378 coap_opt_t *nores;
3379 coap_opt_iterator_t opt_iter;
3380 unsigned int val = 0;
3381
3382 assert(request);
3383 assert(response);
3384
3385 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3386 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3387
3388 if (nores) {
3390
3391 /* The response should be dropped when the bit corresponding to
3392 * the response class is set (cf. table in function
3393 * documentation). When a No-Response option is present and the
3394 * bit is not set, the sender explicitly indicates interest in
3395 * this response. */
3396 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3397 /* Should be dropping the response */
3398 if (response->type == COAP_MESSAGE_ACK &&
3399 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3400 /* Still need to ACK the request */
3401 response->code = 0;
3402 /* Remove token/data from piggybacked acknowledgment PDU */
3403 response->actual_token.length = 0;
3404 response->e_token_length = 0;
3405 response->used_size = 0;
3406 response->data = NULL;
3407 return RESPONSE_SEND;
3408 } else {
3409 return RESPONSE_DROP;
3410 }
3411 } else {
3412 /* True for mcast as well RFC7967 2.1 */
3413 return RESPONSE_SEND;
3414 }
3415 } else if (resource && session->context->mcast_per_resource &&
3416 coap_is_mcast(&session->addr_info.local)) {
3417 /* Handle any mcast suppression specifics if no NoResponse option */
3418 if ((resource->flags &
3420 COAP_RESPONSE_CLASS(response->code) == 2) {
3421 return RESPONSE_DROP;
3422 } else if ((resource->flags &
3424 response->code == COAP_RESPONSE_CODE(205)) {
3425 if (response->data == NULL)
3426 return RESPONSE_DROP;
3427 } else if ((resource->flags &
3429 COAP_RESPONSE_CLASS(response->code) == 4) {
3430 return RESPONSE_DROP;
3431 } else if ((resource->flags &
3433 COAP_RESPONSE_CLASS(response->code) == 5) {
3434 return RESPONSE_DROP;
3435 }
3436 }
3437 } else if (COAP_PDU_IS_EMPTY(response) &&
3438 (response->type == COAP_MESSAGE_NON ||
3439 COAP_PROTO_RELIABLE(session->proto))) {
3440 /* response is 0.00, and this is reliable or non-confirmable */
3441 return RESPONSE_DROP;
3442 }
3443
3444 /*
3445 * Do not send error responses for requests that were received via
3446 * IP multicast. RFC7252 8.1
3447 */
3448
3449 if (coap_is_mcast(&session->addr_info.local)) {
3450 if (request->type == COAP_MESSAGE_NON &&
3451 response->type == COAP_MESSAGE_RST)
3452 return RESPONSE_DROP;
3453
3454 if ((!resource || session->context->mcast_per_resource == 0) &&
3455 COAP_RESPONSE_CLASS(response->code) > 2)
3456 return RESPONSE_DROP;
3457 }
3458
3459 /* Default behavior applies when we are not dealing with a response
3460 * (class == 0) or the request did not contain a No-Response option.
3461 */
3462 return RESPONSE_DEFAULT;
3463}
3464
3465static coap_str_const_t coap_default_uri_wellknown = {
3467 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3468};
3469
3470/* Initialized in coap_startup() */
3471static coap_resource_t resource_uri_wellknown;
3472
3473static void
3474handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3475 coap_pdu_t *orig_pdu) {
3476 coap_method_handler_t h = NULL;
3477 coap_pdu_t *response = NULL;
3478 coap_opt_filter_t opt_filter;
3479 coap_resource_t *resource = NULL;
3480 /* The respond field indicates whether a response must be treated
3481 * specially due to a No-Response option that declares disinterest
3482 * or interest in a specific response class. DEFAULT indicates that
3483 * No-Response has not been specified. */
3484 enum respond_t respond = RESPONSE_DEFAULT;
3485 coap_opt_iterator_t opt_iter;
3486 coap_opt_t *opt;
3487 int is_proxy_uri = 0;
3488 int is_proxy_scheme = 0;
3489 int skip_hop_limit_check = 0;
3490 int resp = 0;
3491 int send_early_empty_ack = 0;
3492 coap_string_t *query = NULL;
3493 coap_opt_t *observe = NULL;
3494 coap_string_t *uri_path = NULL;
3495 int observe_action = COAP_OBSERVE_CANCEL;
3496 coap_block_b_t block;
3497 int added_block = 0;
3498 coap_lg_srcv_t *free_lg_srcv = NULL;
3499#if COAP_Q_BLOCK_SUPPORT
3500 int lg_xmit_ctrl = 0;
3501#endif /* COAP_Q_BLOCK_SUPPORT */
3502#if COAP_ASYNC_SUPPORT
3503 coap_async_t *async;
3504#endif /* COAP_ASYNC_SUPPORT */
3505
3506 if (coap_is_mcast(&session->addr_info.local)) {
3507 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3508 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3509 return;
3510 }
3511 }
3512#if COAP_ASYNC_SUPPORT
3513 async = coap_find_async_lkd(session, pdu->actual_token);
3514 if (async) {
3515 coap_tick_t now;
3516
3517 coap_ticks(&now);
3518 if (async->delay == 0 || async->delay > now) {
3519 /* re-transmit missing ACK (only if CON) */
3520 coap_log_info("Retransmit async response\n");
3521 coap_send_ack_lkd(session, pdu);
3522 /* and do not pass on to the upper layers */
3523 return;
3524 }
3525 }
3526#endif /* COAP_ASYNC_SUPPORT */
3527
3528 coap_option_filter_clear(&opt_filter);
3529 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3530 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3531 if (opt) {
3532 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3533 if (!opt) {
3534 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3535 resp = 402;
3536 goto fail_response;
3537 }
3538 is_proxy_scheme = 1;
3539 }
3540
3541 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3542 if (opt)
3543 is_proxy_uri = 1;
3544 }
3545
3546 if (is_proxy_scheme || is_proxy_uri) {
3547 coap_uri_t uri;
3548
3549 if (!context->proxy_uri_resource) {
3550 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3551 coap_log_debug("Proxy-%s support not configured\n",
3552 is_proxy_scheme ? "Scheme" : "Uri");
3553 resp = 505;
3554 goto fail_response;
3555 }
3556 if (((size_t)pdu->code - 1 <
3557 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3558 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3559 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3560 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3561 is_proxy_scheme ? "Scheme" : "Uri",
3562 pdu->code/100, pdu->code%100);
3563 resp = 505;
3564 goto fail_response;
3565 }
3566
3567 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3568 if (is_proxy_uri) {
3570 coap_opt_length(opt), &uri) < 0) {
3571 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3572 coap_log_debug("Proxy-URI not decodable\n");
3573 resp = 505;
3574 goto fail_response;
3575 }
3576 } else {
3577 memset(&uri, 0, sizeof(uri));
3578 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3579 if (opt) {
3580 uri.host.length = coap_opt_length(opt);
3581 uri.host.s = coap_opt_value(opt);
3582 } else
3583 uri.host.length = 0;
3584 }
3585
3586 resource = context->proxy_uri_resource;
3587 if (uri.host.length && resource->proxy_name_count &&
3588 resource->proxy_name_list) {
3589 size_t i;
3590
3591 if (resource->proxy_name_count == 1 &&
3592 resource->proxy_name_list[0]->length == 0) {
3593 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3594 i = 0;
3595 } else {
3596 for (i = 0; i < resource->proxy_name_count; i++) {
3597 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3598 break;
3599 }
3600 }
3601 }
3602 if (i != resource->proxy_name_count) {
3603 /* This server is hosting the proxy connection endpoint */
3604 if (pdu->crit_opt) {
3605 /* Cannot handle critical option */
3606 pdu->crit_opt = 0;
3607 resp = 402;
3608 resource = NULL;
3609 goto fail_response;
3610 }
3611 is_proxy_uri = 0;
3612 is_proxy_scheme = 0;
3613 skip_hop_limit_check = 1;
3614 }
3615 }
3616 resource = NULL;
3617 }
3618 assert(resource == NULL);
3619
3620 if (!skip_hop_limit_check) {
3621 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3622 if (opt) {
3623 size_t hop_limit;
3624 uint8_t buf[4];
3625
3626 hop_limit =
3628 if (hop_limit == 1) {
3629 /* coap_send_internal() will fill in the IP address for us */
3630 resp = 508;
3631 goto fail_response;
3632 } else if (hop_limit < 1 || hop_limit > 255) {
3633 /* Need to return a 4.00 RFC8768 Section 3 */
3634 coap_log_info("Invalid Hop Limit\n");
3635 resp = 400;
3636 goto fail_response;
3637 }
3638 hop_limit--;
3640 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3641 buf);
3642 }
3643 }
3644
3645 uri_path = coap_get_uri_path(pdu);
3646 if (!uri_path)
3647 return;
3648
3649 if (!is_proxy_uri && !is_proxy_scheme) {
3650 /* try to find the resource from the request URI */
3651 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3652 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3653 }
3654
3655 if ((resource == NULL) || (resource->is_unknown == 1) ||
3656 (resource->is_proxy_uri == 1)) {
3657 /* The resource was not found or there is an unexpected match against the
3658 * resource defined for handling unknown or proxy URIs.
3659 */
3660 if (resource != NULL)
3661 /* Close down unexpected match */
3662 resource = NULL;
3663 /*
3664 * Check if the request URI happens to be the well-known URI, or if the
3665 * unknown resource handler is defined, a PUT or optionally other methods,
3666 * if configured, for the unknown handler.
3667 *
3668 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3669 * proxy URI handler.
3670 *
3671 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3672 * set, call the unknown URI handler with any unknown URI (including
3673 * .well-known/core) if the appropriate method is defined.
3674 *
3675 * else if well-known URI generate a default response.
3676 *
3677 * else if unknown URI handler defined, call the unknown
3678 * URI handler (to allow for potential generation of resource
3679 * [RFC7272 5.8.3]) if the appropriate method is defined.
3680 *
3681 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3682 *
3683 * else return 4.04.
3684 */
3685
3686 if (is_proxy_uri || is_proxy_scheme) {
3687 resource = context->proxy_uri_resource;
3688 } else if (context->unknown_resource != NULL &&
3690 ((size_t)pdu->code - 1 <
3691 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3692 (context->unknown_resource->handler[pdu->code - 1])) {
3693 resource = context->unknown_resource;
3694 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3695 /* request for .well-known/core */
3696 resource = &resource_uri_wellknown;
3697 } else if ((context->unknown_resource != NULL) &&
3698 ((size_t)pdu->code - 1 <
3699 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3700 (context->unknown_resource->handler[pdu->code - 1])) {
3701 /*
3702 * The unknown_resource can be used to handle undefined resources
3703 * for a PUT request and can support any other registered handler
3704 * defined for it
3705 * Example set up code:-
3706 * r = coap_resource_unknown_init(hnd_put_unknown);
3707 * coap_register_request_handler(r, COAP_REQUEST_POST,
3708 * hnd_post_unknown);
3709 * coap_register_request_handler(r, COAP_REQUEST_GET,
3710 * hnd_get_unknown);
3711 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3712 * hnd_delete_unknown);
3713 * coap_add_resource(ctx, r);
3714 *
3715 * Note: It is not possible to observe the unknown_resource, a separate
3716 * resource must be created (by PUT or POST) which has a GET
3717 * handler to be observed
3718 */
3719 resource = context->unknown_resource;
3720 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3721 /*
3722 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3723 */
3724 coap_log_debug("request for unknown resource '%*.*s',"
3725 " return 2.02\n",
3726 (int)uri_path->length,
3727 (int)uri_path->length,
3728 uri_path->s);
3729 resp = 202;
3730 goto fail_response;
3731 } else if ((context->dyn_create_handler != NULL) &&
3733 /* Above test must be the same as in coap_op_dyn_resource_load_disk() */
3734 if (context->dynamic_cur < context->dynamic_max || context->dynamic_max == 0) {
3735#if COAP_WITH_OBSERVE_PERSIST
3736 /* If we are maintaining Observe persist */
3737 context->unknown_pdu = pdu;
3738 context->unknown_session = session;
3739#endif /* COAP_WITH_OBSERVE_PERSIST */
3740 coap_lock_callback_ret(resource, context->dyn_create_handler(session, pdu));
3741#if COAP_WITH_OBSERVE_PERSIST
3742 /* If we are maintaining Observe persist */
3743 context->unknown_pdu = NULL;
3744 context->unknown_session = NULL;
3745#endif /* COAP_WITH_OBSERVE_PERSIST */
3746 }
3747 if (!resource) {
3748 resp = 406;
3749 goto fail_response;
3750 }
3751 context->dynamic_cur++;
3752 resource->is_dynamic = 1;
3753 } else { /* request for any another resource, return 4.04 */
3754
3755 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3756 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3757 resp = 404;
3758 goto fail_response;
3759 }
3760
3761 }
3762
3764
3765#if COAP_OSCORE_SUPPORT
3766 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3767 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3768 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3769 resp = 401;
3770 goto fail_response;
3771 }
3772#endif /* COAP_OSCORE_SUPPORT */
3773 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3774 /* Check for existing resource and If-Non-Match */
3775 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3776 if (opt) {
3777 resp = 412;
3778 goto fail_response;
3779 }
3780 }
3781
3782 /* the resource was found, check if there is a registered handler */
3783 if ((size_t)pdu->code - 1 <
3784 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3785 h = resource->handler[pdu->code - 1];
3786
3787 if (h == NULL) {
3788 resp = 405;
3789 goto fail_response;
3790 }
3791 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3792 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3793 if (opt == NULL) {
3794 /* RFC 8132 2.3.1 */
3795 resp = 415;
3796 goto fail_response;
3797 }
3798 }
3799 if (context->mcast_per_resource &&
3800 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3801 coap_is_mcast(&session->addr_info.local)) {
3802 resp = 405;
3803 goto fail_response;
3804 }
3805
3806 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3808 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3809 if (!response) {
3810 coap_log_err("could not create response PDU\n");
3811 resp = 500;
3812 goto fail_response;
3813 }
3814 response->session = session;
3815#if COAP_ASYNC_SUPPORT
3816 /* If handling a separate response, need CON, not ACK response */
3817 if (async && pdu->type == COAP_MESSAGE_CON)
3818 response->type = COAP_MESSAGE_CON;
3819#endif /* COAP_ASYNC_SUPPORT */
3820 /* A lot of the reliable code assumes type is CON */
3821 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3822 response->type = COAP_MESSAGE_CON;
3823
3824 if (!coap_add_token(response, pdu->actual_token.length,
3825 pdu->actual_token.s)) {
3826 resp = 500;
3827 goto fail_response;
3828 }
3829
3830 query = coap_get_query(pdu);
3831
3832 /* check for Observe option RFC7641 and RFC8132 */
3833 if (resource->observable &&
3834 (pdu->code == COAP_REQUEST_CODE_GET ||
3835 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3836 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3837 }
3838
3839 /*
3840 * See if blocks need to be aggregated or next requests sent off
3841 * before invoking application request handler
3842 */
3843 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3844 uint32_t block_mode = session->block_mode;
3845
3846 if (observe ||
3849 if (coap_handle_request_put_block(context, session, pdu, response,
3850 resource, uri_path, observe,
3851 &added_block, &free_lg_srcv)) {
3852 session->block_mode = block_mode;
3853 goto skip_handler;
3854 }
3855 session->block_mode = block_mode;
3856
3857 if (coap_handle_request_send_block(session, pdu, response, resource,
3858 query)) {
3859#if COAP_Q_BLOCK_SUPPORT
3860 lg_xmit_ctrl = 1;
3861#endif /* COAP_Q_BLOCK_SUPPORT */
3862 goto skip_handler;
3863 }
3864 }
3865
3866 if (observe) {
3867 observe_action =
3869 coap_opt_length(observe));
3870
3871 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3872 coap_subscription_t *subscription;
3873
3874 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3875 if (block.num != 0) {
3876 response->code = COAP_RESPONSE_CODE(400);
3877 goto skip_handler;
3878 }
3879#if COAP_Q_BLOCK_SUPPORT
3880 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3881 &block)) {
3882 if (block.num != 0) {
3883 response->code = COAP_RESPONSE_CODE(400);
3884 goto skip_handler;
3885 }
3886#endif /* COAP_Q_BLOCK_SUPPORT */
3887 }
3888 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3889 pdu);
3890 if (subscription) {
3891 uint8_t buf[4];
3892
3893 coap_touch_observer(context, session, &pdu->actual_token);
3895 coap_encode_var_safe(buf, sizeof(buf),
3896 resource->observe),
3897 buf);
3898 }
3899 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3900 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3901 } else {
3902 coap_log_info("observe: unexpected action %d\n", observe_action);
3903 }
3904 }
3905
3906 if ((resource == context->proxy_uri_resource ||
3907 (resource == context->unknown_resource &&
3908 context->unknown_resource->is_reverse_proxy)) &&
3909 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3910 pdu->type == COAP_MESSAGE_CON &&
3911 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
3912 /* Make the proxy response separate and fix response later */
3913 send_early_empty_ack = 1;
3914 }
3915 if (send_early_empty_ack) {
3916 coap_send_ack_lkd(session, pdu);
3917 if (pdu->mid == session->last_con_mid) {
3918 /* request has already been processed - do not process it again */
3919 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3920 pdu->mid);
3921 goto drop_it_no_debug;
3922 }
3923 session->last_con_mid = pdu->mid;
3924 }
3925#if COAP_WITH_OBSERVE_PERSIST
3926 /* If we are maintaining Observe persist */
3927 if (resource == context->unknown_resource) {
3928 context->unknown_pdu = pdu;
3929 context->unknown_session = session;
3930 } else
3931 context->unknown_pdu = NULL;
3932#endif /* COAP_WITH_OBSERVE_PERSIST */
3933
3934 /*
3935 * Call the request handler with everything set up
3936 */
3937 if (resource == &resource_uri_wellknown) {
3938 /* Leave context locked */
3939 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3940 (int)resource->uri_path->length, (int)resource->uri_path->length,
3941 resource->uri_path->s);
3942 h(resource, session, pdu, query, response);
3943 } else {
3944 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3945 (int)resource->uri_path->length, (int)resource->uri_path->length,
3946 resource->uri_path->s);
3947 coap_lock_callback_release(h(resource, session, pdu, query, response),
3948 /* context is being freed off */
3949 goto finish);
3950 }
3951
3952 /* Check validity of response code */
3953 if (!coap_check_code_class(session, response)) {
3954 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
3955 COAP_RESPONSE_CLASS(response->code),
3956 response->code & 0x1f);
3957 goto drop_it_no_debug;
3958 }
3959
3960 /* Check if lg_xmit generated and update PDU code if so */
3961 coap_check_code_lg_xmit(session, pdu, response, resource, query);
3962
3963 if (free_lg_srcv) {
3964 /* Check to see if the server is doing a 4.01 + Echo response */
3965 if (response->code == COAP_RESPONSE_CODE(401) &&
3966 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3967 /* Need to keep lg_srcv around for client's response */
3968 } else {
3969 LL_DELETE(session->lg_srcv, free_lg_srcv);
3970 coap_block_delete_lg_srcv(session, free_lg_srcv);
3971 }
3972 }
3973 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
3974 /* Just in case, as there are more to go */
3975 response->code = COAP_RESPONSE_CODE(231);
3976 }
3977
3978skip_handler:
3979 if (send_early_empty_ack &&
3980 response->type == COAP_MESSAGE_ACK) {
3981 /* Response is now separate - convert to CON as needed */
3982 response->type = COAP_MESSAGE_CON;
3983 /* Check for empty ACK - need to drop as already sent */
3984 if (response->code == 0) {
3985 goto drop_it_no_debug;
3986 }
3987 }
3988 respond = no_response(pdu, response, session, resource);
3989 if (respond != RESPONSE_DROP) {
3990#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
3991 coap_mid_t mid = pdu->mid;
3992#endif
3993 if (COAP_RESPONSE_CLASS(response->code) != 2) {
3994 if (observe) {
3996 }
3997 }
3998 if (COAP_RESPONSE_CLASS(response->code) > 2) {
3999 if (observe)
4000 coap_delete_observer(resource, session, &pdu->actual_token);
4001 if (response->code != COAP_RESPONSE_CODE(413))
4003 }
4004
4005 /* If original request contained a token, and the registered
4006 * application handler made no changes to the response, then
4007 * this is an empty ACK with a token, which is a malformed
4008 * PDU */
4009 if ((response->type == COAP_MESSAGE_ACK)
4010 && (response->code == 0)) {
4011 /* Remove token from otherwise-empty acknowledgment PDU */
4012 response->actual_token.length = 0;
4013 response->e_token_length = 0;
4014 response->used_size = 0;
4015 response->data = NULL;
4016 }
4017
4018 if (!coap_is_mcast(&session->addr_info.local) ||
4019 (context->mcast_per_resource &&
4020 resource &&
4022 /* No delays to response */
4023#if COAP_Q_BLOCK_SUPPORT
4024 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4025 !lg_xmit_ctrl && response->code == COAP_RESPONSE_CODE(205) &&
4026 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4027 block.m) {
4028 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4029 response,
4030 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4031 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4032 response = NULL;
4033 if (query)
4034 coap_delete_string(query);
4035 goto finish;
4036 }
4037#endif /* COAP_Q_BLOCK_SUPPORT */
4038 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4039 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4040 if (query)
4041 coap_delete_string(query);
4042 goto finish;
4043 }
4044 } else {
4045 /* Need to delay mcast response */
4046 coap_queue_t *node = coap_new_node();
4047 uint8_t r;
4048 coap_tick_t delay;
4049
4050 if (!node) {
4051 coap_log_debug("mcast delay: insufficient memory\n");
4052 goto drop_it_no_debug;
4053 }
4054 if (!coap_pdu_encode_header(response, session->proto)) {
4056 goto drop_it_no_debug;
4057 }
4058
4059 node->id = response->mid;
4060 node->pdu = response;
4061 node->is_mcast = 1;
4062 coap_prng_lkd(&r, sizeof(r));
4063 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4064 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4065 coap_session_str(session),
4066 response->mid,
4067 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4068 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4069 1000 / COAP_TICKS_PER_SECOND));
4070 node->timeout = (unsigned int)delay;
4071 /* Use this to delay transmission */
4072 coap_wait_ack(session->context, session, node);
4073 }
4074 } else {
4075 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4076 coap_session_str(session),
4077 response->mid);
4078 coap_show_pdu(COAP_LOG_DEBUG, response);
4079drop_it_no_debug:
4080 coap_delete_pdu_lkd(response);
4081 }
4082 if (query)
4083 coap_delete_string(query);
4084#if COAP_Q_BLOCK_SUPPORT
4085 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4086 if (COAP_PROTO_RELIABLE(session->proto)) {
4087 if (block.m) {
4088 /* All of the sequence not in yet */
4089 goto finish;
4090 }
4091 } else if (pdu->type == COAP_MESSAGE_NON) {
4092 /* More to go and not at a payload break */
4093 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4094 goto finish;
4095 }
4096 }
4097 }
4098#endif /* COAP_Q_BLOCK_SUPPORT */
4099
4100finish:
4101 if (resource)
4102 coap_resource_release_lkd(resource);
4103 coap_delete_string(uri_path);
4104 return;
4105
4106fail_response:
4107 coap_delete_pdu_lkd(response);
4108 response =
4110 &opt_filter);
4111 if (response)
4112 goto skip_handler;
4113 if (resource)
4114 coap_resource_release_lkd(resource);
4115 coap_delete_string(uri_path);
4116}
4117#endif /* COAP_SERVER_SUPPORT */
4118
4119#if COAP_CLIENT_SUPPORT
4120/* Call application-specific response handler when available. */
4121void
4123 coap_pdu_t *sent, coap_pdu_t *rcvd,
4124 void *body_data) {
4125 coap_context_t *context = session->context;
4126 coap_response_t ret;
4127
4128#if COAP_PROXY_SUPPORT
4129 if (context->proxy_response_handler) {
4130 coap_proxy_list_t *proxy_entry;
4131 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4132 rcvd,
4133 &proxy_entry);
4134
4135 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4136 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4137 proxy_entry);
4138 return;
4139 }
4140 }
4141#endif /* COAP_PROXY_SUPPORT */
4142 if (session->doing_send_recv && session->req_token &&
4143 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4144 /* processing coap_send_recv() call */
4145 session->resp_pdu = rcvd;
4147 /* Will get freed off when PDU is freed off */
4148 rcvd->data_free = body_data;
4149 coap_send_ack_lkd(session, rcvd);
4151 return;
4152 } else if (context->response_handler) {
4154 context->response_handler(session,
4155 sent,
4156 rcvd,
4157 rcvd->mid),
4158 /* context is being freed off */
4159 return);
4160 } else {
4161 ret = COAP_RESPONSE_OK;
4162 }
4163 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4164 coap_send_rst_lkd(session, rcvd);
4166 } else {
4167 coap_send_ack_lkd(session, rcvd);
4169 }
4170 coap_free_type(COAP_STRING, body_data);
4171}
4172
4173static void
4174handle_response(coap_context_t *context, coap_session_t *session,
4175 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4176
4177 /* Set in case there is a later call to coap_update_token() */
4178 rcvd->session = session;
4179
4180 /* Check for message duplication */
4181 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4182 if (rcvd->type == COAP_MESSAGE_CON) {
4183 if (rcvd->mid == session->last_con_mid) {
4184 /* Duplicate response: send ACK/RST, but don't process */
4185 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4186 coap_send_ack_lkd(session, rcvd);
4187 else
4188 coap_send_rst_lkd(session, rcvd);
4189 return;
4190 }
4191 session->last_con_mid = rcvd->mid;
4192 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4193 if (rcvd->mid == session->last_ack_mid) {
4194 /* Duplicate response */
4195 return;
4196 }
4197 session->last_ack_mid = rcvd->mid;
4198 }
4199 }
4200 /* Check to see if checking out extended token support */
4201 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4202 session->last_token) {
4203 coap_lg_crcv_t *lg_crcv;
4204
4205 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4206 rcvd->actual_token.length != session->max_token_size ||
4207 rcvd->code == COAP_RESPONSE_CODE(400) ||
4208 rcvd->code == COAP_RESPONSE_CODE(503)) {
4209 coap_log_debug("Extended Token requested size support not available\n");
4211 } else {
4212 coap_log_debug("Extended Token support available\n");
4213 }
4215 /* Need to remove lg_crcv set up for this test */
4216 lg_crcv = coap_find_lg_crcv(session, rcvd);
4217 if (lg_crcv) {
4218 LL_DELETE(session->lg_crcv, lg_crcv);
4219 coap_block_delete_lg_crcv(session, lg_crcv);
4220 }
4221 coap_send_ack_lkd(session, rcvd);
4222 session->doing_first = 0;
4223 return;
4224 }
4225#if COAP_Q_BLOCK_SUPPORT
4226 /* Check to see if checking out Q-Block support */
4227 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4228 session->remote_test_mid == rcvd->mid) {
4229 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4230 coap_log_debug("Q-Block support not available\n");
4231 set_block_mode_drop_q(session->block_mode);
4232 } else {
4233 coap_block_b_t qblock;
4234
4235 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4236 coap_log_debug("Q-Block support available\n");
4237 set_block_mode_has_q(session->block_mode);
4238 } else {
4239 coap_log_debug("Q-Block support not available\n");
4240 set_block_mode_drop_q(session->block_mode);
4241 }
4242 }
4243 session->doing_first = 0;
4244 return;
4245 }
4246#endif /* COAP_Q_BLOCK_SUPPORT */
4247
4248 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4249 /* See if need to send next block to server */
4250 if (coap_handle_response_send_block(session, sent, rcvd)) {
4251 /* Next block transmitted, no need to inform app */
4252 coap_send_ack_lkd(session, rcvd);
4253 return;
4254 }
4255
4256 /* Need to see if needing to request next block */
4257 if (coap_handle_response_get_block(context, session, sent, rcvd,
4258 COAP_RECURSE_OK)) {
4259 /* Next block transmitted, ack sent no need to inform app */
4260 return;
4261 }
4262 }
4263 if (session->doing_first)
4264 session->doing_first = 0;
4265
4266 /* Call application-specific response handler when available. */
4267 coap_call_response_handler(session, sent, rcvd, NULL);
4268}
4269#endif /* COAP_CLIENT_SUPPORT */
4270
4271#if !COAP_DISABLE_TCP
4272static void
4274 coap_pdu_t *pdu) {
4275 coap_opt_iterator_t opt_iter;
4276 coap_opt_t *option;
4277 int set_mtu = 0;
4278
4279 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4280
4281 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4282 if (session->csm_not_seen) {
4283 coap_tick_t now;
4284
4285 coap_ticks(&now);
4286 /* CSM timeout before CSM seen */
4287 coap_log_warn("***%s: CSM received after CSM timeout\n",
4288 coap_session_str(session));
4289 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4290 coap_session_str(session),
4291 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4292 }
4293 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4295 }
4296 while ((option = coap_option_next(&opt_iter))) {
4298 unsigned max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4299
4300 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4301 max_recv = COAP_DEFAULT_MAX_PDU_RX_SIZE;
4302 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4303 coap_session_str(session), max_recv);
4304 }
4305 coap_session_set_mtu(session, max_recv);
4306 set_mtu = 1;
4307 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4308 session->csm_block_supported = 1;
4309 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4310 session->max_token_size =
4312 coap_opt_length(option));
4315 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4318 }
4319 }
4320 if (set_mtu) {
4321 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4322 session->csm_bert_rem_support = 1;
4323 else
4324 session->csm_bert_rem_support = 0;
4325 }
4326 if (session->state == COAP_SESSION_STATE_CSM)
4327 coap_session_connected(session);
4328 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4330 if (context->ping_handler) {
4331 coap_lock_callback(context->ping_handler(session, pdu, pdu->mid));
4332 }
4333 if (pong) {
4335 coap_send_internal(session, pong, NULL);
4336 }
4337 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4338 session->last_pong = session->last_rx_tx;
4339 if (context->pong_handler) {
4340 coap_lock_callback(context->pong_handler(session, pdu, pdu->mid));
4341 }
4342 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4343 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4345 }
4346}
4347#endif /* !COAP_DISABLE_TCP */
4348
4349static int
4351 if (COAP_PDU_IS_REQUEST(pdu) &&
4352 pdu->actual_token.length >
4353 (session->type == COAP_SESSION_TYPE_CLIENT ?
4354 session->max_token_size : session->context->max_token_size)) {
4355 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4356 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4357 coap_opt_filter_t opt_filter;
4358 coap_pdu_t *response;
4359
4360 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4361 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4362 &opt_filter);
4363 if (!response) {
4364 coap_log_warn("coap_dispatch: cannot create error response\n");
4365 } else {
4366 /*
4367 * Note - have to leave in oversize token as per
4368 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4369 */
4370 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4371 coap_log_warn("coap_dispatch: error sending response\n");
4372 }
4373 } else {
4374 /* Indicate no extended token support */
4375 coap_send_rst_lkd(session, pdu);
4376 }
4377 return 0;
4378 }
4379 return 1;
4380}
4381
4382void
4384 coap_pdu_t *pdu) {
4385 coap_queue_t *sent = NULL;
4386 coap_pdu_t *response;
4387 coap_pdu_t *orig_pdu = NULL;
4388 coap_opt_filter_t opt_filter;
4389 int is_ping_rst;
4390 int packet_is_bad = 0;
4391#if COAP_OSCORE_SUPPORT
4392 coap_opt_iterator_t opt_iter;
4393 coap_pdu_t *dec_pdu = NULL;
4394#endif /* COAP_OSCORE_SUPPORT */
4395 int is_ext_token_rst;
4396 int oscore_invalid = 0;
4397
4398 pdu->session = session;
4400
4401 /* Check validity of received code */
4402 if (!coap_check_code_class(session, pdu)) {
4403 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4405 pdu->code & 0x1f);
4406 packet_is_bad = 1;
4407 if (pdu->type == COAP_MESSAGE_CON) {
4409 }
4410 /* find message id in sendqueue to stop retransmission */
4411 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4412 goto cleanup;
4413 }
4414
4415 coap_option_filter_clear(&opt_filter);
4416
4417#if COAP_SERVER_SUPPORT
4418 /* See if this a repeat request */
4419 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4421 coap_digest_t digest;
4422
4423 coap_pdu_cksum(pdu, &digest);
4424 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4425#if COAP_OSCORE_SUPPORT
4426 uint8_t oscore_encryption = session->oscore_encryption;
4427
4428 session->oscore_encryption = 0;
4429#endif /* COAP_OSCORE_SUPPORT */
4430 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4431 cached_pdu must not be removed */
4433 coap_log_debug("Retransmit response to duplicate request\n");
4434 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4435#if COAP_OSCORE_SUPPORT
4436 session->oscore_encryption = oscore_encryption;
4437#endif /* COAP_OSCORE_SUPPORT */
4438 return;
4439 }
4440#if COAP_OSCORE_SUPPORT
4441 session->oscore_encryption = oscore_encryption;
4442#endif /* COAP_OSCORE_SUPPORT */
4443 }
4444 }
4445#endif /* COAP_SERVER_SUPPORT */
4446 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4447 if (!check_token_size(session, pdu)) {
4448 goto cleanup;
4449 }
4450 }
4451#if COAP_OSCORE_SUPPORT
4452 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4453 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4454 if (pdu->type == COAP_MESSAGE_NON) {
4455 coap_send_rst_lkd(session, pdu);
4456 goto cleanup;
4457 } else if (pdu->type == COAP_MESSAGE_CON) {
4458 if (COAP_PDU_IS_REQUEST(pdu)) {
4459 response =
4460 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4461
4462 if (!response) {
4463 coap_log_warn("coap_dispatch: cannot create error response\n");
4464 } else {
4465 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4466 coap_log_warn("coap_dispatch: error sending response\n");
4467 }
4468 } else {
4469 coap_send_rst_lkd(session, pdu);
4470 }
4471 }
4472 goto cleanup;
4473 }
4474
4475 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4476 int decrypt = 1;
4477#if COAP_SERVER_SUPPORT
4478 coap_opt_t *opt;
4479 coap_resource_t *resource;
4480 coap_uri_t uri;
4481#endif /* COAP_SERVER_SUPPORT */
4482
4483 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4484 decrypt = 0;
4485
4486#if COAP_SERVER_SUPPORT
4487 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4488 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4489 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4490 != NULL) {
4491 /* Need to check whether this is a direct or proxy session */
4492 memset(&uri, 0, sizeof(uri));
4493 uri.host.length = coap_opt_length(opt);
4494 uri.host.s = coap_opt_value(opt);
4495 resource = context->proxy_uri_resource;
4496 if (uri.host.length && resource && resource->proxy_name_count &&
4497 resource->proxy_name_list) {
4498 size_t i;
4499 for (i = 0; i < resource->proxy_name_count; i++) {
4500 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4501 break;
4502 }
4503 }
4504 if (i == resource->proxy_name_count) {
4505 /* This server is not hosting the proxy connection endpoint */
4506 decrypt = 0;
4507 }
4508 }
4509 }
4510#endif /* COAP_SERVER_SUPPORT */
4511 if (decrypt) {
4512 /* find message id in sendqueue to stop retransmission and get sent */
4513 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4514 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4515 orig_pdu = pdu;
4516 coap_pdu_reference_lkd(orig_pdu);
4517 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4518 if (session->recipient_ctx == NULL ||
4519 session->recipient_ctx->initial_state == 0) {
4520 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4521 }
4523 coap_delete_pdu_lkd(orig_pdu);
4524 return;
4525 } else {
4526 session->oscore_encryption = 1;
4527 pdu = dec_pdu;
4528 }
4529 coap_log_debug("Decrypted PDU\n");
4531 }
4532 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4533 session->oscore_encryption &&
4534 pdu->type != COAP_MESSAGE_RST) {
4535 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4536 /* Violates RFC 8613 2 */
4537 coap_log_err("received an invalid response to the OSCORE request\n");
4538 oscore_invalid = 1;
4539 }
4540 }
4541#endif /* COAP_OSCORE_SUPPORT */
4542
4543 switch (pdu->type) {
4544 case COAP_MESSAGE_ACK:
4545 /* find message id in sendqueue to stop retransmission */
4546 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4547
4548 if (sent && session->con_active) {
4549 session->con_active--;
4550 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4551 /* Flush out any entries on session->delayqueue */
4552 coap_session_connected(session);
4553 }
4554 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4555 packet_is_bad = 1;
4556 goto cleanup;
4557 }
4558
4559#if COAP_SERVER_SUPPORT
4560 /* if sent code was >= 64 the message might have been a
4561 * notification. Then, we must flag the observer to be alive
4562 * by setting obs->fail_cnt = 0. */
4563 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4564 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4565 }
4566#endif /* COAP_SERVER_SUPPORT */
4567
4568 if (pdu->code == 0) {
4569#if COAP_Q_BLOCK_SUPPORT
4570 if (sent) {
4571 coap_block_b_t block;
4572
4573 if (sent->pdu->type == COAP_MESSAGE_CON &&
4574 COAP_PROTO_NOT_RELIABLE(session->proto) &&
4575 coap_get_block_b(session, sent->pdu,
4576 COAP_PDU_IS_REQUEST(sent->pdu) ?
4578 &block)) {
4579 if (block.m) {
4580#if COAP_CLIENT_SUPPORT
4581 if (COAP_PDU_IS_REQUEST(sent->pdu))
4582 coap_send_q_block1(session, block, sent->pdu,
4583 COAP_SEND_SKIP_PDU);
4584#endif /* COAP_CLIENT_SUPPORT */
4585 if (COAP_PDU_IS_RESPONSE(sent->pdu))
4586 coap_send_q_blocks(session, sent->pdu->lg_xmit, block,
4587 sent->pdu, COAP_SEND_SKIP_PDU);
4588 }
4589 }
4590 }
4591#endif /* COAP_Q_BLOCK_SUPPORT */
4592#if COAP_CLIENT_SUPPORT
4593 /*
4594 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4595 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4596 * response if the response was piggy-backed. Here, a separate response
4597 * detected and so the lg_crcv needs to be set up before the sent PDU
4598 * information is lost.
4599 *
4600 * lg_crcv was not set up if not a CoAP request.
4601 *
4602 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4603 * options.
4604 */
4605 if (sent &&
4606 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4607 COAP_PDU_IS_REQUEST(sent->pdu)) {
4608 /*
4609 * lg_crcv was not set up in coap_send(). It could have been set up
4610 * the first separate response.
4611 * See if there already is a lg_crcv set up.
4612 */
4613 coap_lg_crcv_t *lg_crcv;
4614 uint64_t token_match =
4616 sent->pdu->actual_token.length));
4617
4618 LL_FOREACH(session->lg_crcv, lg_crcv) {
4619 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4620 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4621 break;
4622 }
4623 }
4624 if (!lg_crcv) {
4625 /*
4626 * Need to set up a lg_crcv as it was not set up in coap_send()
4627 * to save time, but server has not sent back a piggy-back response.
4628 */
4629 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4630 if (lg_crcv) {
4631 LL_PREPEND(session->lg_crcv, lg_crcv);
4632 }
4633 }
4634 }
4635#endif /* COAP_CLIENT_SUPPORT */
4636 /* an empty ACK needs no further handling */
4637 goto cleanup;
4638 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4639 /* This is not legitimate - Request using ACK - ignore */
4640 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4642 pdu->code & 0x1f);
4643 packet_is_bad = 1;
4644 goto cleanup;
4645 }
4646
4647 break;
4648
4649 case COAP_MESSAGE_RST:
4650 /* We have sent something the receiver disliked, so we remove
4651 * not only the message id but also the subscriptions we might
4652 * have. */
4653 is_ping_rst = 0;
4654 if (pdu->mid == session->last_ping_mid &&
4655 session->last_ping > 0)
4656 is_ping_rst = 1;
4657
4658#if COAP_Q_BLOCK_SUPPORT
4659 /* Check to see if checking out Q-Block support */
4660 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4661 session->remote_test_mid == pdu->mid) {
4662 coap_log_debug("Q-Block support not available\n");
4663 set_block_mode_drop_q(session->block_mode);
4664 }
4665#endif /* COAP_Q_BLOCK_SUPPORT */
4666
4667 /* Check to see if checking out extended token support */
4668 is_ext_token_rst = 0;
4669 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4670 session->remote_test_mid == pdu->mid) {
4671 coap_log_debug("Extended Token support not available\n");
4674 session->doing_first = 0;
4675 is_ext_token_rst = 1;
4676 }
4677
4678 if (!is_ping_rst && !is_ext_token_rst)
4679 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4680
4681 if (session->con_active) {
4682 session->con_active--;
4683 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4684 /* Flush out any entries on session->delayqueue */
4685 coap_session_connected(session);
4686 }
4687
4688 /* find message id in sendqueue to stop retransmission */
4689 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4690
4691 if (sent) {
4692 if (!is_ping_rst)
4693 coap_cancel(context, sent);
4694
4695 if (!is_ping_rst && !is_ext_token_rst) {
4696 if (sent->pdu->type==COAP_MESSAGE_CON) {
4697 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4698 }
4699 } else if (is_ping_rst) {
4700 if (context->pong_handler) {
4701 coap_lock_callback(context->pong_handler(session, pdu, pdu->mid));
4702 }
4703 session->last_pong = session->last_rx_tx;
4705 }
4706 } else {
4707#if COAP_SERVER_SUPPORT
4708 /* Need to check is there is a subscription active and delete it */
4709 RESOURCES_ITER(context->resources, r) {
4710 coap_subscription_t *obs, *tmp;
4711 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4712 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4713 /* Need to do this now as session may get de-referenced */
4715 coap_delete_observer(r, session, &obs->pdu->actual_token);
4716 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4717 coap_session_release_lkd(session);
4718 goto cleanup;
4719 }
4720 }
4721 }
4722#endif /* COAP_SERVER_SUPPORT */
4723 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4724 }
4725#if COAP_PROXY_SUPPORT
4726 if (!is_ping_rst) {
4727 /* Need to check is there is a proxy subscription active and delete it */
4728 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
4729 }
4730#endif /* COAP_PROXY_SUPPORT */
4731 goto cleanup;
4732
4733 case COAP_MESSAGE_NON:
4734 /* check for oscore issue or unknown critical options */
4735 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4736 packet_is_bad = 1;
4737 coap_send_rst_lkd(session, pdu);
4738 goto cleanup;
4739 }
4740 break;
4741
4742 case COAP_MESSAGE_CON:
4743 /* In a lossy context, the ACK of a separate response may have
4744 * been lost, so we need to stop retransmitting requests with the
4745 * same token. Matching on token potentially containing ext length bytes.
4746 */
4747 /* find message token in sendqueue to stop retransmission */
4748 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4749
4750 /* check for oscore issue or unknown critical options in non-signaling messages */
4751 if (oscore_invalid ||
4752 (!COAP_PDU_IS_SIGNALING(pdu) && coap_option_check_critical(session, pdu, &opt_filter) == 0)) {
4753 packet_is_bad = 1;
4754 if (COAP_PDU_IS_REQUEST(pdu)) {
4755 response =
4756 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4757
4758 if (!response) {
4759 coap_log_warn("coap_dispatch: cannot create error response\n");
4760 } else {
4761 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4762 coap_log_warn("coap_dispatch: error sending response\n");
4763 }
4764 } else {
4765 coap_send_rst_lkd(session, pdu);
4766 }
4767 goto cleanup;
4768 }
4769 break;
4770 default:
4771 break;
4772 }
4773
4774 /* Pass message to upper layer if a specific handler was
4775 * registered for a request that should be handled locally. */
4776#if !COAP_DISABLE_TCP
4777 if (COAP_PDU_IS_SIGNALING(pdu))
4778 handle_signaling(context, session, pdu);
4779 else
4780#endif /* !COAP_DISABLE_TCP */
4781#if COAP_SERVER_SUPPORT
4782 if (COAP_PDU_IS_REQUEST(pdu))
4783 handle_request(context, session, pdu, orig_pdu);
4784 else
4785#endif /* COAP_SERVER_SUPPORT */
4786#if COAP_CLIENT_SUPPORT
4787 if (COAP_PDU_IS_RESPONSE(pdu))
4788 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4789 else
4790#endif /* COAP_CLIENT_SUPPORT */
4791 {
4792 if (COAP_PDU_IS_EMPTY(pdu)) {
4793 if (context->ping_handler) {
4794 coap_lock_callback(context->ping_handler(session, pdu, pdu->mid));
4795 }
4796 } else {
4797 packet_is_bad = 1;
4798 }
4799 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4801 pdu->code & 0x1f);
4802
4803 if (!coap_is_mcast(&session->addr_info.local)) {
4804 if (COAP_PDU_IS_EMPTY(pdu)) {
4805 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4806 coap_tick_t now;
4807 coap_ticks(&now);
4808 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4810 session->last_tx_rst = now;
4811 }
4812 }
4813 } else {
4814 if (pdu->type == COAP_MESSAGE_CON)
4816 }
4817 }
4818 }
4819
4820cleanup:
4821 if (packet_is_bad) {
4822 if (sent) {
4823 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
4824 } else {
4826 }
4827 }
4828 coap_delete_pdu_lkd(orig_pdu);
4830#if COAP_OSCORE_SUPPORT
4831 coap_delete_pdu_lkd(dec_pdu);
4832#endif /* COAP_OSCORE_SUPPORT */
4833}
4834
4835#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4836static const char *
4838 switch (event) {
4840 return "COAP_EVENT_DTLS_CLOSED";
4842 return "COAP_EVENT_DTLS_CONNECTED";
4844 return "COAP_EVENT_DTLS_RENEGOTIATE";
4846 return "COAP_EVENT_DTLS_ERROR";
4848 return "COAP_EVENT_TCP_CONNECTED";
4850 return "COAP_EVENT_TCP_CLOSED";
4852 return "COAP_EVENT_TCP_FAILED";
4854 return "COAP_EVENT_SESSION_CONNECTED";
4856 return "COAP_EVENT_SESSION_CLOSED";
4858 return "COAP_EVENT_SESSION_FAILED";
4860 return "COAP_EVENT_PARTIAL_BLOCK";
4862 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4864 return "COAP_EVENT_SERVER_SESSION_NEW";
4866 return "COAP_EVENT_SERVER_SESSION_DEL";
4868 return "COAP_EVENT_SERVER_SESSION_CONNECTED";
4870 return "COAP_EVENT_BAD_PACKET";
4872 return "COAP_EVENT_MSG_RETRANSMITTED";
4874 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4876 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4878 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4880 return "COAP_EVENT_OSCORE_NO_SECURITY";
4882 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4884 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4886 return "COAP_EVENT_WS_PACKET_SIZE";
4888 return "COAP_EVENT_WS_CONNECTED";
4890 return "COAP_EVENT_WS_CLOSED";
4892 return "COAP_EVENT_KEEPALIVE_FAILURE";
4893 default:
4894 return "???";
4895 }
4896}
4897#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4898
4899COAP_API int
4901 coap_session_t *session) {
4902 int ret;
4903
4904 coap_lock_lock(return 0);
4905 ret = coap_handle_event_lkd(context, event, session);
4907 return ret;
4908}
4909
4910int
4912 coap_session_t *session) {
4913 int ret = 0;
4914
4915 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
4916
4917 if (context->handle_event) {
4918 coap_lock_callback_ret(ret, context->handle_event(session, event));
4919#if COAP_PROXY_SUPPORT
4920 if (event == COAP_EVENT_SERVER_SESSION_DEL)
4921 coap_proxy_remove_association(session, 0);
4922#endif /* COAP_PROXY_SUPPORT */
4923#if COAP_CLIENT_SUPPORT
4924 switch (event) {
4937 /* Those that are deemed fatal to end sending a request */
4938 session->doing_send_recv = 0;
4939 break;
4941 /* Session will now be available as well - for call-home */
4942 if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
4944 session);
4945 }
4946 break;
4951 break;
4953 /* Session will now be available as well - for call-home if not (D)TLS */
4954 if (session->type == COAP_SESSION_TYPE_SERVER &&
4955 (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
4957 session);
4958 }
4959 break;
4963 break;
4965 /* Session will now be available as well - for call-home if not (D)TLS */
4966 if (session->proto == COAP_PROTO_UDP) {
4968 session);
4969 }
4970 break;
4976 default:
4977 break;
4978 }
4979#endif /* COAP_CLIENT_SUPPORT */
4980 }
4981 return ret;
4982}
4983
4984COAP_API int
4986 int ret;
4987
4988 coap_lock_lock(return 0);
4989 ret = coap_can_exit_lkd(context);
4991 return ret;
4992}
4993
4994int
4996 coap_session_t *s, *rtmp;
4997 if (!context)
4998 return 1;
5000 if (context->sendqueue)
5001 return 0;
5002#if COAP_SERVER_SUPPORT
5003 coap_endpoint_t *ep;
5004
5005 LL_FOREACH(context->endpoint, ep) {
5006 SESSIONS_ITER(ep->sessions, s, rtmp) {
5007 if (s->delayqueue)
5008 return 0;
5009 if (s->lg_xmit)
5010 return 0;
5011 }
5012 }
5013#endif /* COAP_SERVER_SUPPORT */
5014#if COAP_CLIENT_SUPPORT
5015 SESSIONS_ITER(context->sessions, s, rtmp) {
5016 if (s->delayqueue)
5017 return 0;
5018 if (s->lg_xmit)
5019 return 0;
5020 }
5021#endif /* COAP_CLIENT_SUPPORT */
5022 return 1;
5023}
5024#if COAP_SERVER_SUPPORT
5025#if COAP_ASYNC_SUPPORT
5026/*
5027 * Return 1 if there is a future expire time, else 0.
5028 * Update tim_rem with remaining value if return is 1.
5029 */
5030int
5031coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5033 coap_async_t *async, *tmp;
5034 int ret = 0;
5035
5036 if (context->async_state_traversing)
5037 return 0;
5038 context->async_state_traversing = 1;
5039 LL_FOREACH_SAFE(context->async_state, async, tmp) {
5040 if (async->delay != 0) {
5041 if (async->delay <= now) {
5042 /* Send off the request to the application */
5043 coap_log_debug("Async PDU presented to app.\n");
5044 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5045 handle_request(context, async->session, async->pdu, NULL);
5046
5047 /* Remove this async entry as it has now fired */
5048 coap_free_async_lkd(async->session, async);
5049 } else {
5050 next_due = async->delay - now;
5051 ret = 1;
5052 }
5053 }
5054 }
5055 if (tim_rem)
5056 *tim_rem = next_due;
5057 context->async_state_traversing = 0;
5058 return ret;
5059}
5060#endif /* COAP_ASYNC_SUPPORT */
5061#endif /* COAP_SERVER_SUPPORT */
5062
5064
5065#if COAP_THREAD_SAFE
5066/*
5067 * Global lock for multi-thread support
5068 */
5069coap_lock_t global_lock;
5070/*
5071 * low level protection mutex
5072 */
5073coap_mutex_t m_show_pdu;
5074coap_mutex_t m_log_impl;
5075coap_mutex_t m_io_threads;
5076#endif /* COAP_THREAD_SAFE */
5077
5078void
5080 coap_tick_t now;
5081#ifndef WITH_CONTIKI
5082 uint64_t us;
5083#endif /* !WITH_CONTIKI */
5084
5085 if (coap_started)
5086 return;
5087 coap_started = 1;
5088
5089#if COAP_THREAD_SAFE
5091 coap_mutex_init(&m_show_pdu);
5092 coap_mutex_init(&m_log_impl);
5093 coap_mutex_init(&m_io_threads);
5094#endif /* COAP_THREAD_SAFE */
5095
5096#if defined(HAVE_WINSOCK2_H)
5097 WORD wVersionRequested = MAKEWORD(2, 2);
5098 WSADATA wsaData;
5099 WSAStartup(wVersionRequested, &wsaData);
5100#endif
5102 coap_ticks(&now);
5103#ifndef WITH_CONTIKI
5104 us = coap_ticks_to_rt_us(now);
5105 /* Be accurate to the nearest (approx) us */
5106 coap_prng_init_lkd((unsigned int)us);
5107#else /* WITH_CONTIKI */
5108 coap_start_io_process();
5109#endif /* WITH_CONTIKI */
5112#ifdef WITH_LWIP
5113 coap_io_lwip_init();
5114#endif /* WITH_LWIP */
5115#if COAP_SERVER_SUPPORT
5116 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5117 (const uint8_t *)".well-known/core"
5118 };
5119 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5120 resource_uri_wellknown.ref = 1;
5121 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5122 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5123 resource_uri_wellknown.uri_path = &well_known;
5124#endif /* COAP_SERVER_SUPPORT */
5126}
5127
5128void
5130 if (!coap_started)
5131 return;
5132 coap_started = 0;
5133#if defined(HAVE_WINSOCK2_H)
5134 WSACleanup();
5135#elif defined(WITH_CONTIKI)
5136 coap_stop_io_process();
5137#endif
5138#ifdef WITH_LWIP
5139 coap_io_lwip_cleanup();
5140#endif /* WITH_LWIP */
5142
5143#if COAP_THREAD_SAFE
5144 coap_mutex_destroy(&m_show_pdu);
5145 coap_mutex_destroy(&m_log_impl);
5146 coap_mutex_destroy(&m_io_threads);
5147#endif /* COAP_THREAD_SAFE */
5148
5150}
5151
5152void
5154 coap_response_handler_t handler) {
5155#if COAP_CLIENT_SUPPORT
5156 context->response_handler = handler;
5157#else /* ! COAP_CLIENT_SUPPORT */
5158 (void)context;
5159 (void)handler;
5160#endif /* ! COAP_CLIENT_SUPPORT */
5161}
5162
5163void
5166#if COAP_PROXY_SUPPORT
5167 context->proxy_response_handler = handler;
5168#else /* ! COAP_PROXY_SUPPORT */
5169 (void)context;
5170 (void)handler;
5171#endif /* ! COAP_PROXY_SUPPORT */
5172}
5173
5174void
5176 coap_nack_handler_t handler) {
5177 context->nack_handler = handler;
5178}
5179
5180void
5182 coap_ping_handler_t handler) {
5183 context->ping_handler = handler;
5184}
5185
5186void
5188 coap_pong_handler_t handler) {
5189 context->pong_handler = handler;
5190}
5191
5192void
5194 coap_resource_dynamic_create_t dyn_create_handler,
5195 uint32_t dynamic_max) {
5196 context->dyn_create_handler = dyn_create_handler;
5197 context->dynamic_max = dynamic_max;
5198 return;
5199}
5200
5201COAP_API void
5203 coap_lock_lock(return);
5204 coap_register_option_lkd(ctx, type);
5206}
5207
5208void
5211}
5212
5213#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5214#if COAP_SERVER_SUPPORT
5215COAP_API int
5216coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5217 const char *ifname) {
5218 int ret;
5219
5220 coap_lock_lock(return -1);
5221 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
5223 return ret;
5224}
5225
5226int
5227coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
5228 const char *ifname) {
5229#if COAP_IPV4_SUPPORT
5230 struct ip_mreq mreq4;
5231#endif /* COAP_IPV4_SUPPORT */
5232#if COAP_IPV6_SUPPORT
5233 struct ipv6_mreq mreq6;
5234#endif /* COAP_IPV6_SUPPORT */
5235 struct addrinfo *resmulti = NULL, hints, *ainfo;
5236 int result = -1;
5237 coap_endpoint_t *endpoint;
5238 int mgroup_setup = 0;
5239
5240 /* Need to have at least one endpoint! */
5241 assert(ctx->endpoint);
5242 if (!ctx->endpoint)
5243 return -1;
5244
5245 /* Default is let the kernel choose */
5246#if COAP_IPV6_SUPPORT
5247 mreq6.ipv6mr_interface = 0;
5248#endif /* COAP_IPV6_SUPPORT */
5249#if COAP_IPV4_SUPPORT
5250 mreq4.imr_interface.s_addr = INADDR_ANY;
5251#endif /* COAP_IPV4_SUPPORT */
5252
5253 memset(&hints, 0, sizeof(hints));
5254 hints.ai_socktype = SOCK_DGRAM;
5255
5256 /* resolve the multicast group address */
5257 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5258
5259 if (result != 0) {
5260 coap_log_err("coap_join_mcast_group_intf: %s: "
5261 "Cannot resolve multicast address: %s\n",
5262 group_name, gai_strerror(result));
5263 goto finish;
5264 }
5265
5266 /* Need to do a windows equivalent at some point */
5267#ifndef _WIN32
5268 if (ifname) {
5269 /* interface specified - check if we have correct IPv4/IPv6 information */
5270 int done_ip4 = 0;
5271 int done_ip6 = 0;
5272#if defined(ESPIDF_VERSION)
5273 struct netif *netif;
5274#else /* !ESPIDF_VERSION */
5275#if COAP_IPV4_SUPPORT
5276 int ip4fd;
5277#endif /* COAP_IPV4_SUPPORT */
5278 struct ifreq ifr;
5279#endif /* !ESPIDF_VERSION */
5280
5281 /* See which mcast address family types are being asked for */
5282 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5283 ainfo = ainfo->ai_next) {
5284 switch (ainfo->ai_family) {
5285#if COAP_IPV6_SUPPORT
5286 case AF_INET6:
5287 if (done_ip6)
5288 break;
5289 done_ip6 = 1;
5290#if defined(ESPIDF_VERSION)
5291 netif = netif_find(ifname);
5292 if (netif)
5293 mreq6.ipv6mr_interface = netif_get_index(netif);
5294 else
5295 coap_log_err("coap_join_mcast_group_intf: %s: "
5296 "Cannot get IPv4 address: %s\n",
5297 ifname, coap_socket_strerror());
5298#else /* !ESPIDF_VERSION */
5299 memset(&ifr, 0, sizeof(ifr));
5300 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5301 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5302
5303#ifdef HAVE_IF_NAMETOINDEX
5304 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5305 if (mreq6.ipv6mr_interface == 0) {
5306 coap_log_warn("coap_join_mcast_group_intf: "
5307 "cannot get interface index for '%s'\n",
5308 ifname);
5309 }
5310#elif defined(__QNXNTO__)
5311#else /* !HAVE_IF_NAMETOINDEX */
5312 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5313 if (result != 0) {
5314 coap_log_warn("coap_join_mcast_group_intf: "
5315 "cannot get interface index for '%s': %s\n",
5316 ifname, coap_socket_strerror());
5317 } else {
5318 /* Capture the IPv6 if_index for later */
5319 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5320 }
5321#endif /* !HAVE_IF_NAMETOINDEX */
5322#endif /* !ESPIDF_VERSION */
5323#endif /* COAP_IPV6_SUPPORT */
5324 break;
5325#if COAP_IPV4_SUPPORT
5326 case AF_INET:
5327 if (done_ip4)
5328 break;
5329 done_ip4 = 1;
5330#if defined(ESPIDF_VERSION)
5331 netif = netif_find(ifname);
5332 if (netif)
5333 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5334 else
5335 coap_log_err("coap_join_mcast_group_intf: %s: "
5336 "Cannot get IPv4 address: %s\n",
5337 ifname, coap_socket_strerror());
5338#else /* !ESPIDF_VERSION */
5339 /*
5340 * Need an AF_INET socket to do this unfortunately to stop
5341 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5342 */
5343 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5344 if (ip4fd == -1) {
5345 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5346 ifname, coap_socket_strerror());
5347 continue;
5348 }
5349 memset(&ifr, 0, sizeof(ifr));
5350 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5351 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5352 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5353 if (result != 0) {
5354 coap_log_err("coap_join_mcast_group_intf: %s: "
5355 "Cannot get IPv4 address: %s\n",
5356 ifname, coap_socket_strerror());
5357 } else {
5358 /* Capture the IPv4 address for later */
5359 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5360 }
5361 close(ip4fd);
5362#endif /* !ESPIDF_VERSION */
5363 break;
5364#endif /* COAP_IPV4_SUPPORT */
5365 default:
5366 break;
5367 }
5368 }
5369 }
5370#else /* _WIN32 */
5371 /*
5372 * On Windows this function ignores the ifname variable so we unset this
5373 * variable on this platform in any case in order to enable the interface
5374 * selection from the bind address below.
5375 */
5376 ifname = 0;
5377#endif /* _WIN32 */
5378
5379 /* Add in mcast address(es) to appropriate interface */
5380 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5381 LL_FOREACH(ctx->endpoint, endpoint) {
5382 /* Only UDP currently supported */
5383 if (endpoint->proto == COAP_PROTO_UDP) {
5384 coap_address_t gaddr;
5385
5386 coap_address_init(&gaddr);
5387#if COAP_IPV6_SUPPORT
5388 if (ainfo->ai_family == AF_INET6) {
5389 if (!ifname) {
5390 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5391 /*
5392 * Do it on the ifindex that the server is listening on
5393 * (sin6_scope_id could still be 0)
5394 */
5395 mreq6.ipv6mr_interface =
5396 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5397 } else {
5398 mreq6.ipv6mr_interface = 0;
5399 }
5400 }
5401 gaddr.addr.sin6.sin6_family = AF_INET6;
5402 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5403 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5404 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5405 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5406 (char *)&mreq6, sizeof(mreq6));
5407 }
5408#endif /* COAP_IPV6_SUPPORT */
5409#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5410 else
5411#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5412#if COAP_IPV4_SUPPORT
5413 if (ainfo->ai_family == AF_INET) {
5414 if (!ifname) {
5415 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5416 /*
5417 * Do it on the interface that the server is listening on
5418 * (sin_addr could still be INADDR_ANY)
5419 */
5420 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5421 } else {
5422 mreq4.imr_interface.s_addr = INADDR_ANY;
5423 }
5424 }
5425 gaddr.addr.sin.sin_family = AF_INET;
5426 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5427 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5428 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5429 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5430 (char *)&mreq4, sizeof(mreq4));
5431 }
5432#endif /* COAP_IPV4_SUPPORT */
5433 else {
5434 continue;
5435 }
5436
5437 if (result == COAP_SOCKET_ERROR) {
5438 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5439 group_name, coap_socket_strerror());
5440 } else {
5441 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5442
5443 addr_str[sizeof(addr_str)-1] = '\000';
5444 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5445 sizeof(addr_str) - 1)) {
5446 if (ifname)
5447 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5448 ifname);
5449 else
5450 coap_log_debug("added mcast group %s\n", addr_str);
5451 }
5452 mgroup_setup = 1;
5453 }
5454 }
5455 }
5456 }
5457 if (!mgroup_setup) {
5458 result = -1;
5459 }
5460
5461finish:
5462 freeaddrinfo(resmulti);
5463
5464 return result;
5465}
5466
5467void
5469 context->mcast_per_resource = 1;
5470}
5471
5472#endif /* ! COAP_SERVER_SUPPORT */
5473
5474#if COAP_CLIENT_SUPPORT
5475int
5476coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5477 if (session && coap_is_mcast(&session->addr_info.remote)) {
5478 switch (session->addr_info.remote.addr.sa.sa_family) {
5479#if COAP_IPV4_SUPPORT
5480 case AF_INET:
5481 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5482 (const char *)&hops, sizeof(hops)) < 0) {
5483 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5484 hops, coap_socket_strerror());
5485 return 0;
5486 }
5487 return 1;
5488#endif /* COAP_IPV4_SUPPORT */
5489#if COAP_IPV6_SUPPORT
5490 case AF_INET6:
5491 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5492 (const char *)&hops, sizeof(hops)) < 0) {
5493 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5494 hops, coap_socket_strerror());
5495 return 0;
5496 }
5497 return 1;
5498#endif /* COAP_IPV6_SUPPORT */
5499 default:
5500 break;
5501 }
5502 }
5503 return 0;
5504}
5505#endif /* COAP_CLIENT_SUPPORT */
5506
5507#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
5508COAP_API int
5510 const char *group_name COAP_UNUSED,
5511 const char *ifname COAP_UNUSED) {
5512 return -1;
5513}
5514
5515int
5517 size_t hops COAP_UNUSED) {
5518 return 0;
5519}
5520
5521void
5523}
5524#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:2359
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:1052
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:528
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:29
#define COAP_SOCKET_ERROR
Definition coap_io.h:49
coap_nack_reason_t
Definition coap_io.h:62
@ COAP_NACK_NOT_DELIVERABLE
Definition coap_io.h:64
@ COAP_NACK_TOO_MANY_RETRIES
Definition coap_io.h:63
@ COAP_NACK_ICMP_ISSUE
Definition coap_io.h:67
@ COAP_NACK_RST
Definition coap_io.h:65
@ COAP_NACK_BAD_RESPONSE
Definition coap_io.h:68
#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:43
@ COAP_CONTEXT
Definition coap_mem.h:44
@ COAP_STRING
Definition coap_mem.h:39
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
CoAP 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:2105
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:2987
#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:5129
#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:4837
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:3302
int coap_started
Definition coap_net.c:5063
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2374
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2415
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:4273
#define min(a, b)
Definition coap_net.c:76
void coap_startup(void)
Definition coap_net.c:5079
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4350
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:20
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:26
#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:2776
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:2711
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:2134
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1837
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:1296
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:761
#define COAP_IO_WAIT
Definition coap_net.h:760
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:2765
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:2704
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:90
#define COAP_BLOCK_TRY_Q_BLOCK
Definition coap_block.h:63
#define COAP_BLOCK_SINGLE_BODY
Definition coap_block.h:62
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:65
#define COAP_BLOCK_CACHE_RESPONSE
Definition coap_block.h:69
#define COAP_BLOCK_USE_LIBCOAP
Definition coap_block.h:61
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:155
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:143
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:158
#define COAP_MAX_DELAY_TICKS
Definition coap_time.h:221
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:4911
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:5209
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:2942
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:4383
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:1844
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:4995
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2252
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:3046
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:2881
void coap_cancel_all_messages(coap_context_t *context, coap_session_t *session, coap_bin_const_t *token)
Cancels all outstanding messages for session session that have the specified token.
Definition coap_net.c:3085
void coap_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:105
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:2113
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:69
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:2108
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:117
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:5153
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:3118
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:5193
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:53
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:94
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:82
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:5181
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:4985
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:5202
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:5187
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:4900
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:5175
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:54
@ COAP_RESPONSE_OK
Response is fine.
Definition coap_net.h:55
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:307
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:46
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:34
@ COAP_EVENT_OSCORE_DECODE_ERROR
Triggered when there is an OSCORE decode of OSCORE option failure.
Definition coap_event.h:124
@ COAP_EVENT_SESSION_CONNECTED
Triggered when TCP layer completes exchange of CSM information.
Definition coap_event.h:61
@ COAP_EVENT_OSCORE_INTERNAL_ERROR
Triggered when there is an OSCORE internal error i.e malloc failed.
Definition coap_event.h:122
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition coap_event.h:39
@ COAP_EVENT_TCP_FAILED
Triggered when TCP layer fails for some reason.
Definition coap_event.h:55
@ COAP_EVENT_WS_CONNECTED
Triggered when the WebSockets layer is up.
Definition coap_event.h:131
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:41
@ COAP_EVENT_SESSION_FAILED
Triggered when TCP layer fails following exchange of CSM information.
Definition coap_event.h:65
@ COAP_EVENT_PARTIAL_BLOCK
Triggered when not all of a large body has been received.
Definition coap_event.h:71
@ COAP_EVENT_XMIT_BLOCK_FAIL
Triggered when not all of a large body has been transmitted.
Definition coap_event.h:73
@ 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:85
@ COAP_EVENT_OSCORE_NOT_ENABLED
Triggered when trying to use OSCORE to decrypt, but it is not enabled.
Definition coap_event.h:116
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:133
@ COAP_EVENT_SESSION_CLOSED
Triggered when TCP layer closes following exchange of CSM information.
Definition coap_event.h:63
@ 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:94
@ COAP_EVENT_OSCORE_NO_SECURITY
Triggered when there is no OSCORE security definition found.
Definition coap_event.h:120
@ COAP_EVENT_DTLS_RENEGOTIATE
Triggered when (D)TLS session renegotiated.
Definition coap_event.h:43
@ COAP_EVENT_BAD_PACKET
Triggered when badly formatted packet received.
Definition coap_event.h:106
@ 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:100
@ COAP_EVENT_MSG_RETRANSMITTED
Triggered when a message is retransmitted.
Definition coap_event.h:108
@ COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD
Triggered when there is no OSCORE encrypted payload provided.
Definition coap_event.h:118
@ COAP_EVENT_TCP_CLOSED
Triggered when TCP layer is closed.
Definition coap_event.h:53
@ COAP_EVENT_WS_PACKET_SIZE
Triggered when there is an oversize WebSockets packet.
Definition coap_event.h:129
@ COAP_EVENT_TCP_CONNECTED
Triggered when TCP layer connects.
Definition coap_event.h:51
@ COAP_EVENT_OSCORE_DECRYPTION_FAILURE
Triggered when there is an OSCORE decryption failure.
Definition coap_event.h:114
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:138
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:45
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:120
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:84
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:81
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:108
#define coap_log_warn(...)
Definition coap_debug.h:102
#define coap_log_err(...)
Definition coap_debug.h:96
@ COAP_LOG_DEBUG
Definition coap_debug.h:58
@ COAP_LOG_WARN
Definition coap_debug.h:55
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:133
#define COAP_OPTION_NORESPONSE
Definition coap_pdu.h:146
#define COAP_OPTION_URI_HOST
Definition coap_pdu.h:120
#define COAP_OPTION_IF_MATCH
Definition coap_pdu.h:119
#define COAP_OPTION_BLOCK2
Definition coap_pdu.h:138
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:128
#define COAP_OPTION_BLOCK1
Definition coap_pdu.h:139
#define COAP_OPTION_Q_BLOCK1
Definition coap_pdu.h:135
#define COAP_OPTION_PROXY_SCHEME
Definition coap_pdu.h:143
#define COAP_OPTION_URI_QUERY
Definition coap_pdu.h:132
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:264
#define COAP_TOKEN_DEFAULT_MAX
Definition coap_pdu.h:56
#define COAP_OPTION_IF_NONE_MATCH
Definition coap_pdu.h:122
#define COAP_TOKEN_EXT_MAX
Definition coap_pdu.h:60
#define COAP_OPTION_URI_PATH
Definition coap_pdu.h:127
#define COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH
Definition coap_pdu.h:200
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:161
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:164
coap_pdu_code_t
Set of codes available for a PDU.
Definition coap_pdu.h:327
#define COAP_OPTION_OSCORE
Definition coap_pdu.h:126
coap_pdu_type_t
CoAP PDU message type definitions.
Definition coap_pdu.h:68
#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
Definition coap_pdu.h:199
int coap_add_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds token of length len to pdu.
Definition coap_pdu.c:360
#define COAP_OPTION_Q_BLOCK2
Definition coap_pdu.h:141
#define COAP_SIGNALING_OPTION_CUSTODY
Definition coap_pdu.h:203
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:147
#define COAP_OPTION_URI_PORT
Definition coap_pdu.h:124
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:134
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:267
#define COAP_OPTION_PROXY_URI
Definition coap_pdu.h:142
#define COAP_OPTION_OBSERVE
Definition coap_pdu.h:123
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition coap_pdu.h:53
#define COAP_BERT_BASE
Definition coap_pdu.h:44
#define COAP_OPTION_ECHO
Definition coap_pdu.h:145
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition coap_pdu.h:215
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition coap_pdu.h:198
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:79
@ COAP_PROTO_WS
Definition coap_pdu.h:319
@ COAP_PROTO_DTLS
Definition coap_pdu.h:316
@ COAP_PROTO_UDP
Definition coap_pdu.h:315
@ COAP_PROTO_TLS
Definition coap_pdu.h:318
@ COAP_PROTO_WSS
Definition coap_pdu.h:320
@ COAP_PROTO_TCP
Definition coap_pdu.h:317
@ COAP_SIGNALING_CODE_ABORT
Definition coap_pdu.h:370
@ COAP_REQUEST_CODE_PUT
Definition coap_pdu.h:332
@ COAP_REQUEST_CODE_POST
Definition coap_pdu.h:331
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:366
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:367
@ COAP_REQUEST_CODE_DELETE
Definition coap_pdu.h:333
@ COAP_SIGNALING_CODE_PONG
Definition coap_pdu.h:368
@ COAP_EMPTY_CODE
Definition coap_pdu.h:328
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:330
@ COAP_SIGNALING_CODE_RELEASE
Definition coap_pdu.h:369
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:334
@ COAP_MESSAGE_NON
Definition coap_pdu.h:70
@ COAP_MESSAGE_ACK
Definition coap_pdu.h:71
@ COAP_MESSAGE_CON
Definition coap_pdu.h:69
@ COAP_MESSAGE_RST
Definition coap_pdu.h:72
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:5164
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:85
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:2445
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:211
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:197
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:990
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:281
coap_string_t * coap_get_query(const coap_pdu_t *request)
Extract query string from request PDU according to escape rules in 6.5.8.
Definition coap_uri.c:939
#define COAP_UNUSED
Definition libcoap.h:72
#define COAP_STATIC_INLINE
Definition libcoap.h:55
coap_address_t remote
remote address and port
Definition coap_io.h:56
coap_address_t local
local address and port
Definition coap_io.h:57
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:64
size_t length
length of binary data
Definition coap_str.h:65
const uint8_t * s
read-only binary data
Definition coap_str.h:66
CoAP binary data definition.
Definition coap_str.h:56
size_t length
length of binary data
Definition coap_str.h:57
uint8_t * s
binary data
Definition coap_str.h:58
Structure of Block options with BERT support.
Definition coap_block.h:51
unsigned int num
block number
Definition coap_block.h:52
unsigned int bert
Operating as BERT.
Definition coap_block.h:57
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:55
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:53
unsigned int szx
block size (0-6)
Definition coap_block.h:54
The CoAP stack's global state is stored in a coap_context_t object.
coap_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:381
coap_bin_const_t identity
Definition coap_dtls.h:380
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:443
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:312
uint8_t version
Definition coap_dtls.h:313
coap_bin_const_t hint
Definition coap_dtls.h:451
coap_bin_const_t key
Definition coap_dtls.h:452
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:501
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:533
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:46
const uint8_t * s
read-only string data
Definition coap_str.h:48
size_t length
length of string
Definition coap_str.h:47
CoAP string data definition.
Definition coap_str.h:38
uint8_t * s
string data
Definition coap_str.h:40
size_t length
length of string
Definition coap_str.h:39
Number of notifications that may be sent non-confirmable before a confirmable message is sent to dete...
struct coap_session_t * session
subscriber session
coap_pdu_t * pdu
cache_key to identify requester
Representation of parsed URI.
Definition coap_uri.h:68
coap_str_const_t host
The host part of the URI.
Definition coap_uri.h:69