libcoap 4.3.5-develop-4fa3dfa
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 %u\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
863 HASH_ITER(hh, context->cache, cp, ctmp) {
864 coap_delete_cache_entry(context, cp);
865 }
866 if (context->cache_ignore_count) {
868 }
869
870 coap_endpoint_t *ep, *tmp;
871
872 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
874 }
875#endif /* COAP_SERVER_SUPPORT */
876
877#if COAP_CLIENT_SUPPORT
878 coap_session_t *sp, *rtmp;
879
880 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
882 }
883#endif /* COAP_CLIENT_SUPPORT */
884
885 if (context->dtls_context)
887#ifdef COAP_EPOLL_SUPPORT
888 if (context->eptimerfd != -1) {
889 int ret;
890 struct epoll_event event;
891
892 /* Kernels prior to 2.6.9 expect non NULL event parameter */
893 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
894 if (ret == -1) {
895 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
896 "coap_free_context",
897 coap_socket_strerror(), errno);
898 }
899 close(context->eptimerfd);
900 context->eptimerfd = -1;
901 }
902 if (context->epfd != -1) {
903 close(context->epfd);
904 context->epfd = -1;
905 }
906#endif /* COAP_EPOLL_SUPPORT */
907#if COAP_SERVER_SUPPORT
908#if COAP_WITH_OBSERVE_PERSIST
909 coap_persist_cleanup(context);
910#endif /* COAP_WITH_OBSERVE_PERSIST */
911#endif /* COAP_SERVER_SUPPORT */
912#if COAP_PROXY_SUPPORT
913 coap_proxy_cleanup(context);
914#endif /* COAP_PROXY_SUPPORT */
915
916 if (context->app_cb) {
917 context->app_cb(context->app_data);
918 }
921}
922
923int
925 coap_pdu_t *pdu,
926 coap_opt_filter_t *unknown) {
927 coap_context_t *ctx = session->context;
928 coap_opt_iterator_t opt_iter;
929 int ok = 1;
930 coap_option_num_t last_number = -1;
931
933
934 while (coap_option_next(&opt_iter)) {
935 /* Check for explicitely reserved option RFC 5272 12.2 Table 7 */
936 /* Need to check reserved options */
937 switch (opt_iter.number) {
938 case 0:
939 case 128:
940 case 132:
941 case 136:
942 case 140:
943 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
944 coap_log_debug("unknown reserved option %d\n", opt_iter.number);
945 ok = 0;
946
947 /* When opt_iter.number cannot be set in unknown, all of the appropriate
948 * slots have been used up and no more options can be tracked.
949 * Safe to break out of this loop as ok is already set. */
950 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
951 goto overflow;
952 }
953 }
954 break;
955 default:
956 break;
957 }
958 if (opt_iter.number & 0x01) {
959 /* first check the known built-in critical options */
960 switch (opt_iter.number) {
961#if COAP_Q_BLOCK_SUPPORT
964 if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
965 coap_log_debug("disabled support for critical option %u\n",
966 opt_iter.number);
967 ok = 0;
968 /* When opt_iter.number cannot be set in unknown, all of the appropriate
969 * slots have been used up and no more options can be tracked.
970 * Safe to break out of this loop as ok is already set. */
971 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
972 goto overflow;
973 }
974 }
975 break;
976#endif /* COAP_Q_BLOCK_SUPPORT */
988 break;
990 /* Valid critical if doing OSCORE */
991#if COAP_OSCORE_SUPPORT
992 if (ctx->p_osc_ctx)
993 break;
994#endif /* COAP_OSCORE_SUPPORT */
995 /* Fall Through */
996 default:
997 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
998#if COAP_SERVER_SUPPORT
999 if ((opt_iter.number & 0x02) == 0) {
1000 coap_opt_iterator_t t_iter;
1001
1002 /* Safe to forward - check if proxy pdu */
1003 if (session->proxy_session)
1004 break;
1005 if (COAP_PDU_IS_REQUEST(pdu) && ctx->proxy_uri_resource &&
1006 (coap_check_option(pdu, COAP_OPTION_PROXY_URI, &t_iter) ||
1008 pdu->crit_opt = 1;
1009 break;
1010 }
1011 }
1012#endif /* COAP_SERVER_SUPPORT */
1013 coap_log_debug("unknown critical option %d\n", opt_iter.number);
1014 ok = 0;
1015
1016 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1017 * slots have been used up and no more options can be tracked.
1018 * Safe to break out of this loop as ok is already set. */
1019 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1020 goto overflow;
1021 }
1022 }
1023 }
1024 }
1025 if (last_number == opt_iter.number) {
1026 /* Check for duplicated option RFC 5272 5.4.5 */
1027 if (!coap_option_check_repeatable(opt_iter.number)) {
1028 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1029 ok = 0;
1030 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1031 goto overflow;
1032 }
1033 }
1034 }
1035 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
1036 COAP_PDU_IS_REQUEST(pdu)) {
1037 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
1038 coap_block_b_t block;
1039
1040 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
1041 if (block.m) {
1042 size_t used_size = pdu->used_size;
1043 unsigned char buf[4];
1044
1045 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
1046 block.m = 0;
1047 coap_update_option(pdu, opt_iter.number,
1048 coap_encode_var_safe(buf, sizeof(buf),
1049 ((block.num << 4) |
1050 (block.m << 3) |
1051 block.aszx)),
1052 buf);
1053 if (used_size != pdu->used_size) {
1054 /* Unfortunately need to restart the scan */
1055 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1056 last_number = -1;
1057 continue;
1058 }
1059 }
1060 }
1061 }
1062 last_number = opt_iter.number;
1063 }
1064overflow:
1065 return ok;
1066}
1067
1069coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
1070 coap_mid_t mid;
1071
1073 mid = coap_send_rst_lkd(session, request);
1075 return mid;
1076}
1077
1080 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
1081}
1082
1084coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
1085 coap_mid_t mid;
1086
1088 mid = coap_send_ack_lkd(session, request);
1090 return mid;
1091}
1092
1095 coap_pdu_t *response;
1097
1099 if (request && request->type == COAP_MESSAGE_CON &&
1100 COAP_PROTO_NOT_RELIABLE(session->proto)) {
1101 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
1102 if (response)
1103 result = coap_send_internal(session, response, NULL);
1104 }
1105 return result;
1106}
1107
1108ssize_t
1110 ssize_t bytes_written = -1;
1111 assert(pdu->hdr_size > 0);
1112
1113 /* Caller handles partial writes */
1114 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1115 pdu->token - pdu->hdr_size,
1116 pdu->used_size + pdu->hdr_size);
1118 return bytes_written;
1119}
1120
1121static ssize_t
1123 ssize_t bytes_written;
1124
1125 if (session->state == COAP_SESSION_STATE_NONE) {
1126#if ! COAP_CLIENT_SUPPORT
1127 return -1;
1128#else /* COAP_CLIENT_SUPPORT */
1129 if (session->type != COAP_SESSION_TYPE_CLIENT)
1130 return -1;
1131#endif /* COAP_CLIENT_SUPPORT */
1132 }
1133
1134 if (pdu->type == COAP_MESSAGE_CON &&
1135 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1136 coap_is_mcast(&session->addr_info.remote)) {
1137 /* Violates RFC72522 8.1 */
1138 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1139 return -1;
1140 }
1141
1142 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1143 (pdu->type == COAP_MESSAGE_CON &&
1144 session->con_active >= COAP_NSTART(session))) {
1145 return coap_session_delay_pdu(session, pdu, node);
1146 }
1147
1148 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1149 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1150 return coap_session_delay_pdu(session, pdu, node);
1151
1152 bytes_written = coap_session_send_pdu(session, pdu);
1153 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1155 session->con_active++;
1156
1157 return bytes_written;
1158}
1159
1162 const coap_pdu_t *request,
1163 coap_pdu_code_t code,
1164 coap_opt_filter_t *opts) {
1165 coap_mid_t mid;
1166
1168 mid = coap_send_error_lkd(session, request, code, opts);
1170 return mid;
1171}
1172
1175 const coap_pdu_t *request,
1176 coap_pdu_code_t code,
1177 coap_opt_filter_t *opts) {
1178 coap_pdu_t *response;
1180
1181 assert(request);
1182 assert(session);
1183
1184 response = coap_new_error_response(request, code, opts);
1185 if (response)
1186 result = coap_send_internal(session, response, NULL);
1187
1188 return result;
1189}
1190
1193 coap_pdu_type_t type) {
1194 coap_mid_t mid;
1195
1197 mid = coap_send_message_type_lkd(session, request, type);
1199 return mid;
1200}
1201
1204 coap_pdu_type_t type) {
1205 coap_pdu_t *response;
1207
1209 if (request && COAP_PROTO_NOT_RELIABLE(session->proto)) {
1210 response = coap_pdu_init(type, 0, request->mid, 0);
1211 if (response)
1212 result = coap_send_internal(session, response, NULL);
1213 }
1214 return result;
1215}
1216
1230unsigned int
1231coap_calc_timeout(coap_session_t *session, unsigned char r) {
1232 unsigned int result;
1233
1234 /* The integer 1.0 as a Qx.FRAC_BITS */
1235#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1236
1237 /* rounds val up and right shifts by frac positions */
1238#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1239
1240 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1241 * make the result a rounded Qx.FRAC_BITS */
1242 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1243
1244 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1245 * make the result a rounded Qx.FRAC_BITS */
1246 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1247
1248 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1249 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1250 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1251
1252#undef FP1
1253#undef SHR_FP
1254}
1255
1258 coap_queue_t *node) {
1259 coap_tick_t now;
1260
1261 node->session = coap_session_reference_lkd(session);
1262
1263 /* Set timer for pdu retransmission. If this is the first element in
1264 * the retransmission queue, the base time is set to the current
1265 * time and the retransmission time is node->timeout. If there is
1266 * already an entry in the sendqueue, we must check if this node is
1267 * to be retransmitted earlier. Therefore, node->timeout is first
1268 * normalized to the base time and then inserted into the queue with
1269 * an adjusted relative time.
1270 */
1271 coap_ticks(&now);
1272 if (context->sendqueue == NULL) {
1273 node->t = node->timeout << node->retransmit_cnt;
1274 context->sendqueue_basetime = now;
1275 } else {
1276 /* make node->t relative to context->sendqueue_basetime */
1277 node->t = (now - context->sendqueue_basetime) +
1278 (node->timeout << node->retransmit_cnt);
1279 }
1280 coap_address_copy(&node->remote, &session->addr_info.remote);
1281
1282 coap_insert_node(&context->sendqueue, node);
1283
1284 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1285 coap_session_str(node->session), node->id,
1286 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1288
1289 coap_update_io_timer(context, node->t);
1290
1291 return node->id;
1292}
1293
1294#if COAP_CLIENT_SUPPORT
1295/*
1296 * Sent out a test PDU for Extended Token
1297 */
1298static coap_mid_t
1299coap_send_test_extended_token(coap_session_t *session) {
1300 coap_pdu_t *pdu;
1302 size_t i;
1303 coap_binary_t *token;
1304 coap_lg_crcv_t *lg_crcv;
1305
1306 coap_log_debug("Testing for Extended Token support\n");
1307 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1309 coap_new_message_id_lkd(session),
1311 if (!pdu)
1312 return COAP_INVALID_MID;
1313
1314 token = coap_new_binary(session->max_token_size);
1315 if (token == NULL) {
1317 return COAP_INVALID_MID;
1318 }
1319 for (i = 0; i < session->max_token_size; i++) {
1320 token->s[i] = (uint8_t)(i + 1);
1321 }
1322 coap_add_token(pdu, session->max_token_size, token->s);
1323 coap_delete_binary(token);
1324
1327 pdu->actual_token.length);
1328
1330
1331 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1332
1333 /* Need to track incase OSCORE / Echo etc. comes back after non-piggy-backed ACK */
1334 lg_crcv = coap_block_new_lg_crcv(session, pdu, NULL);
1335 if (lg_crcv) {
1336 LL_PREPEND(session->lg_crcv, lg_crcv);
1337 }
1338 mid = coap_send_internal(session, pdu, NULL);
1339 if (mid == COAP_INVALID_MID)
1340 return COAP_INVALID_MID;
1341 session->remote_test_mid = mid;
1342 return mid;
1343}
1344#endif /* COAP_CLIENT_SUPPORT */
1345
1346int
1348#if COAP_CLIENT_SUPPORT
1349 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1350 int timeout_ms = 5000;
1351 coap_session_state_t current_state = session->state;
1352
1353 if (session->delay_recursive) {
1354 return 0;
1355 } else {
1356 session->delay_recursive = 1;
1357 }
1358 /*
1359 * Need to wait for first request to get out and response back before
1360 * continuing.. Response handler has to clear doing_first if not an error.
1361 */
1363 while (session->doing_first != 0) {
1364 int result = coap_io_process_lkd(session->context, 1000);
1365
1366 if (result < 0) {
1367 session->doing_first = 0;
1368 session->delay_recursive = 0;
1369 coap_session_release_lkd(session);
1370 return 0;
1371 }
1372
1373 /* coap_io_process_lkd() may have updated session state */
1374 if (session->state == COAP_SESSION_STATE_CSM &&
1375 current_state != COAP_SESSION_STATE_CSM) {
1376 /* Update timeout and restart the clock for CSM timeout */
1377 current_state = COAP_SESSION_STATE_CSM;
1378 timeout_ms = session->context->csm_timeout_ms;
1379 result = 0;
1380 }
1381
1382 if (result < timeout_ms) {
1383 timeout_ms -= result;
1384 } else {
1385 if (session->doing_first == 1) {
1386 /* Timeout failure of some sort with first request */
1387 session->doing_first = 0;
1388 if (session->state == COAP_SESSION_STATE_CSM) {
1389 coap_log_debug("** %s: timeout waiting for CSM response\n",
1390 coap_session_str(session));
1391 session->csm_not_seen = 1;
1392 coap_session_connected(session);
1393 } else {
1394 coap_log_debug("** %s: timeout waiting for first response\n",
1395 coap_session_str(session));
1396 }
1397 }
1398 }
1399 }
1400 session->delay_recursive = 0;
1401 coap_session_release_lkd(session);
1402 }
1403#else /* ! COAP_CLIENT_SUPPORT */
1404 (void)session;
1405#endif /* ! COAP_CLIENT_SUPPORT */
1406 return 1;
1407}
1408
1409/*
1410 * return 0 Invalid
1411 * 1 Valid
1412 */
1413int
1415
1416 /* Check validity of sending code */
1417 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1418 case 0: /* Empty or request */
1419 case 2: /* Success */
1420 case 3: /* Reserved for future use */
1421 case 4: /* Client error */
1422 case 5: /* Server error */
1423 break;
1424 case 7: /* Reliable signalling */
1425 if (COAP_PROTO_RELIABLE(session->proto))
1426 break;
1427 /* Not valid if UDP */
1428 /* Fall through */
1429 case 1: /* Invalid */
1430 case 6: /* Invalid */
1431 default:
1432 return 0;
1433 }
1434 return 1;
1435}
1436
1437#if COAP_CLIENT_SUPPORT
1438/*
1439 * If type is CON and protocol is not reliable, there is no need to set up
1440 * lg_crcv if it can be built up based on sent PDU if there is a
1441 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1442 * (Q-)Block1.
1443 */
1444static int
1445coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1446 coap_opt_iterator_t opt_iter;
1447
1448 if (!COAP_PDU_IS_REQUEST(pdu))
1449 return 0;
1450
1451 if (
1452#if COAP_OSCORE_SUPPORT
1453 session->oscore_encryption ||
1454#endif /* COAP_OSCORE_SUPPORT */
1455 pdu->type == COAP_MESSAGE_NON ||
1456 COAP_PROTO_RELIABLE(session->proto) ||
1457 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1458#if COAP_Q_BLOCK_SUPPORT
1459 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1460#endif /* COAP_Q_BLOCK_SUPPORT */
1461 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1462 return 1;
1463 }
1464 return 0;
1465}
1466#endif /* COAP_CLIENT_SUPPORT */
1467
1470 coap_mid_t mid;
1471
1473 mid = coap_send_lkd(session, pdu);
1475 return mid;
1476}
1477
1481#if COAP_CLIENT_SUPPORT
1482 coap_lg_crcv_t *lg_crcv = NULL;
1483 coap_opt_iterator_t opt_iter;
1484 coap_block_b_t block;
1485 int observe_action = -1;
1486 int have_block1 = 0;
1487 coap_opt_t *opt;
1488#endif /* COAP_CLIENT_SUPPORT */
1489
1490 assert(pdu);
1491
1493
1494 /* Check validity of sending code */
1495 if (!coap_check_code_class(session, pdu)) {
1496 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1498 pdu->code & 0x1f);
1499 goto error;
1500 }
1501 pdu->session = session;
1502#if COAP_CLIENT_SUPPORT
1503 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1504 !coap_netif_available(session) && !session->session_failed) {
1505 coap_log_debug("coap_send: Socket closed\n");
1506 goto error;
1507 }
1508 /*
1509 * If this is not the first client request and are waiting for a response
1510 * to the first client request, then drop sending out this next request
1511 * until all is properly established.
1512 */
1513 if (!coap_client_delay_first(session)) {
1514 goto error;
1515 }
1516
1517 /* Indicate support for Extended Tokens if appropriate */
1518 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1520 session->type == COAP_SESSION_TYPE_CLIENT &&
1521 COAP_PDU_IS_REQUEST(pdu)) {
1522 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1523 /*
1524 * When the pass / fail response for Extended Token is received, this PDU
1525 * will get transmitted.
1526 */
1527 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1528 goto error;
1529 }
1530 }
1531 /*
1532 * For reliable protocols, this will get cleared after CSM exchanged
1533 * in coap_session_connected()
1534 */
1535 session->doing_first = 1;
1536 if (!coap_client_delay_first(session)) {
1537 goto error;
1538 }
1539 }
1540
1541 /*
1542 * Check validity of token length
1543 */
1544 if (COAP_PDU_IS_REQUEST(pdu) &&
1545 pdu->actual_token.length > session->max_token_size) {
1546 coap_log_warn("coap_send: PDU dropped as token too long (%zu > %" PRIu32 ")\n",
1547 pdu->actual_token.length, session->max_token_size);
1548 goto error;
1549 }
1550
1551 /* A lot of the reliable code assumes type is CON */
1552 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1553 pdu->type = COAP_MESSAGE_CON;
1554
1555#if COAP_OSCORE_SUPPORT
1556 if (session->oscore_encryption) {
1557 if (session->recipient_ctx->initial_state == 1) {
1558 /*
1559 * Not sure if remote supports OSCORE, or is going to send us a
1560 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1561 * is OK. Continue sending current pdu to test things.
1562 */
1563 session->doing_first = 1;
1564 }
1565 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1567 goto error;
1568 }
1569 }
1570#endif /* COAP_OSCORE_SUPPORT */
1571
1572 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1573 return coap_send_internal(session, pdu, NULL);
1574 }
1575
1576 if (COAP_PDU_IS_REQUEST(pdu)) {
1577 uint8_t buf[4];
1578
1579 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1580
1581 if (opt) {
1582 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1583 coap_opt_length(opt));
1584 }
1585
1586 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1587 (block.m == 1 || block.bert == 1)) {
1588 have_block1 = 1;
1589 }
1590#if COAP_Q_BLOCK_SUPPORT
1591 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1592 (block.m == 1 || block.bert == 1)) {
1593 if (have_block1) {
1594 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1596 }
1597 have_block1 = 1;
1598 }
1599#endif /* COAP_Q_BLOCK_SUPPORT */
1600 if (observe_action != COAP_OBSERVE_CANCEL) {
1601 /* Warn about re-use of tokens */
1602 if (session->last_token &&
1603 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1605 char scratch[24];
1606 size_t size;
1607 size_t i;
1608
1609 scratch[0] = '\000';
1610 for (i = 0; i < pdu->actual_token.length; i++) {
1611 size = strlen(scratch);
1612 snprintf(&scratch[size], sizeof(scratch)-size,
1613 "%02x", pdu->actual_token.s[i]);
1614 }
1615 coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1616 scratch);
1617 }
1618 }
1621 pdu->actual_token.length);
1622 } else {
1623 /* observe_action == COAP_OBSERVE_CANCEL */
1624 coap_binary_t tmp;
1625 int ret;
1626
1627 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1628 /* Unfortunately need to change the ptr type to be r/w */
1629 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1630 tmp.length = pdu->actual_token.length;
1631 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1632 if (ret == 1) {
1633 /* Observe Cancel successfully sent */
1635 return ret;
1636 }
1637 /* Some mismatch somewhere - continue to send original packet */
1638 }
1639 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1640 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1644 coap_encode_var_safe(buf, sizeof(buf),
1645 ++session->tx_rtag),
1646 buf);
1647 } else {
1648 memset(&block, 0, sizeof(block));
1649 }
1650
1651#if COAP_Q_BLOCK_SUPPORT
1652 /* Indicate support for Q-Block if appropriate */
1653 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1654 session->type == COAP_SESSION_TYPE_CLIENT &&
1655 COAP_PDU_IS_REQUEST(pdu)) {
1656 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1657 goto error;
1658 }
1659 session->doing_first = 1;
1660 if (!coap_client_delay_first(session)) {
1661 /* Q-Block test Session has failed for some reason */
1662 set_block_mode_drop_q(session->block_mode);
1663 goto error;
1664 }
1665 }
1666#endif /* COAP_Q_BLOCK_SUPPORT */
1667
1668#if COAP_Q_BLOCK_SUPPORT
1669 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1670#endif /* COAP_Q_BLOCK_SUPPORT */
1671 {
1672 /* Need to check if we need to reset Q-Block to Block */
1673 uint8_t buf[4];
1674
1675 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1678 coap_encode_var_safe(buf, sizeof(buf),
1679 (block.num << 4) | (0 << 3) | block.szx),
1680 buf);
1681 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1682 /* Need to update associated lg_xmit */
1683 coap_lg_xmit_t *lg_xmit;
1684
1685 LL_FOREACH(session->lg_xmit, lg_xmit) {
1686 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1687 lg_xmit->b.b1.app_token &&
1688 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1689 /* Update the skeletal PDU with the block1 option */
1692 coap_encode_var_safe(buf, sizeof(buf),
1693 (block.num << 4) | (0 << 3) | block.szx),
1694 buf);
1695 break;
1696 }
1697 }
1698 }
1699 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1702 coap_encode_var_safe(buf, sizeof(buf),
1703 (block.num << 4) | (block.m << 3) | block.szx),
1704 buf);
1705 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1706 /* Need to update associated lg_xmit */
1707 coap_lg_xmit_t *lg_xmit;
1708
1709 LL_FOREACH(session->lg_xmit, lg_xmit) {
1710 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1711 lg_xmit->b.b1.app_token &&
1712 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1713 /* Update the skeletal PDU with the block1 option */
1716 coap_encode_var_safe(buf, sizeof(buf),
1717 (block.num << 4) |
1718 (block.m << 3) |
1719 block.szx),
1720 buf);
1721 /* Update as this is a Request */
1722 lg_xmit->option = COAP_OPTION_BLOCK1;
1723 break;
1724 }
1725 }
1726 }
1727 }
1728
1729#if COAP_Q_BLOCK_SUPPORT
1730 if (COAP_PDU_IS_REQUEST(pdu) &&
1731 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1732 if (block.num == 0 && block.m == 0) {
1733 uint8_t buf[4];
1734
1735 /* M needs to be set as asking for all the blocks */
1737 coap_encode_var_safe(buf, sizeof(buf),
1738 (0 << 4) | (1 << 3) | block.szx),
1739 buf);
1740 }
1741 }
1742#endif /* COAP_Q_BLOCK_SUPPORT */
1743
1744 /*
1745 * If type is CON and protocol is not reliable, there is no need to set up
1746 * lg_crcv here as it can be built up based on sent PDU if there is a
1747 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1748 * (Q-)Block1.
1749 */
1750 if (coap_check_send_need_lg_crcv(session, pdu)) {
1751 coap_lg_xmit_t *lg_xmit = NULL;
1752
1753 if (!session->lg_xmit && have_block1) {
1754 coap_log_debug("PDU presented by app\n");
1756 }
1757 /* See if this token is already in use for large body responses */
1758 LL_FOREACH(session->lg_crcv, lg_crcv) {
1759 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1760 /* Need to terminate and clean up previous response setup */
1761 LL_DELETE(session->lg_crcv, lg_crcv);
1762 coap_block_delete_lg_crcv(session, lg_crcv);
1763 break;
1764 }
1765 }
1766
1767 if (have_block1 && session->lg_xmit) {
1768 LL_FOREACH(session->lg_xmit, lg_xmit) {
1769 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1770 lg_xmit->b.b1.app_token &&
1771 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1772 break;
1773 }
1774 }
1775 }
1776 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1777 if (lg_crcv == NULL) {
1778 goto error;
1779 }
1780 if (lg_xmit) {
1781 /* Need to update the token as set up in the session->lg_xmit */
1782 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1783 }
1784 }
1785 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1786 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1787
1788#if COAP_Q_BLOCK_SUPPORT
1789 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1790 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1791 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1792 } else
1793#endif /* COAP_Q_BLOCK_SUPPORT */
1794 mid = coap_send_internal(session, pdu, NULL);
1795#else /* !COAP_CLIENT_SUPPORT */
1796 mid = coap_send_internal(session, pdu, NULL);
1797#endif /* !COAP_CLIENT_SUPPORT */
1798#if COAP_CLIENT_SUPPORT
1799 if (lg_crcv) {
1800 if (mid != COAP_INVALID_MID) {
1801 LL_PREPEND(session->lg_crcv, lg_crcv);
1802 } else {
1803 coap_block_delete_lg_crcv(session, lg_crcv);
1804 }
1805 }
1806#endif /* COAP_CLIENT_SUPPORT */
1807 return mid;
1808
1809error:
1811 return COAP_INVALID_MID;
1812}
1813
1814#if COAP_SERVER_SUPPORT
1815static int
1816coap_pdu_cksum(const coap_pdu_t *pdu, coap_digest_t *digest_buffer) {
1817 coap_digest_ctx_t *digest_ctx = coap_digest_setup();
1818
1819 if (!digest_ctx || !pdu) {
1820 goto fail;
1821 }
1822 if (pdu->used_size && pdu->token) {
1823 if (!coap_digest_update(digest_ctx, pdu->token, pdu->used_size)) {
1824 goto fail;
1825 }
1826 }
1827 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->type, sizeof(pdu->type))) {
1828 goto fail;
1829 }
1830 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->code, sizeof(pdu->code))) {
1831 goto fail;
1832 }
1833 if (!coap_digest_final(digest_ctx, digest_buffer))
1834 return 0;
1835
1836 return 1;
1837
1838fail:
1839 coap_digest_free(digest_ctx);
1840 return 0;
1841}
1842#endif /* COAP_SERVER_SUPPORT */
1843
1846 uint8_t r;
1847 ssize_t bytes_written;
1848 coap_opt_iterator_t opt_iter;
1849
1850#if ! COAP_SERVER_SUPPORT
1851 (void)request_pdu;
1852#endif /* COAP_SERVER_SUPPORT */
1853 pdu->session = session;
1854#if COAP_CLIENT_SUPPORT
1855 if (session->session_failed) {
1856 coap_session_reconnect(session);
1857 if (session->session_failed)
1858 goto error;
1859 }
1860#endif /* COAP_CLIENT_SUPPORT */
1861#if COAP_PROXY_SUPPORT
1862 if (session->server_list) {
1863 /* Local session wanting to use proxy logic */
1864 return coap_proxy_local_write(session, pdu);
1865 }
1866#endif /* COAP_PROXY_SUPPORT */
1867 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1868 /*
1869 * Need to prepend our IP identifier to the data as per
1870 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1871 */
1872 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1873 coap_opt_t *opt;
1874 size_t hop_limit;
1875
1876 addr_str[sizeof(addr_str)-1] = '\000';
1877 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1878 sizeof(addr_str) - 1)) {
1879 char *cp;
1880 size_t len;
1881
1882 if (addr_str[0] == '[') {
1883 cp = strchr(addr_str, ']');
1884 if (cp)
1885 *cp = '\000';
1886 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1887 /* IPv4 embedded into IPv6 */
1888 cp = &addr_str[8];
1889 } else {
1890 cp = &addr_str[1];
1891 }
1892 } else {
1893 cp = strchr(addr_str, ':');
1894 if (cp)
1895 *cp = '\000';
1896 cp = addr_str;
1897 }
1898 len = strlen(cp);
1899
1900 /* See if Hop Limit option is being used in return path */
1901 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1902 if (opt) {
1903 uint8_t buf[4];
1904
1905 hop_limit =
1907 if (hop_limit == 1) {
1908 coap_log_warn("Proxy loop detected '%s'\n",
1909 (char *)pdu->data);
1912 } else if (hop_limit < 1 || hop_limit > 255) {
1913 /* Something is bad - need to drop this pdu (TODO or delete option) */
1914 coap_log_warn("Proxy return has bad hop limit count '%zu'\n",
1915 hop_limit);
1918 }
1919 hop_limit--;
1921 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1922 buf);
1923 }
1924
1925 /* Need to check that we are not seeing this proxy in the return loop */
1926 if (pdu->data && opt == NULL) {
1927 char *a_match;
1928 size_t data_len;
1929
1930 if (pdu->used_size + 1 > pdu->max_size) {
1931 /* No space */
1933 }
1934 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1935 /* Internal error */
1937 }
1938 data_len = pdu->used_size - (pdu->data - pdu->token);
1939 pdu->data[data_len] = '\000';
1940 a_match = strstr((char *)pdu->data, cp);
1941 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1942 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1943 a_match[len] == ' ')) {
1944 coap_log_warn("Proxy loop detected '%s'\n",
1945 (char *)pdu->data);
1948 }
1949 }
1950 if (pdu->used_size + len + 1 <= pdu->max_size) {
1951 size_t old_size = pdu->used_size;
1952 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1953 if (pdu->data == NULL) {
1954 /*
1955 * Set Hop Limit to max for return path. If this libcoap is in
1956 * a proxy loop path, it will always decrement hop limit in code
1957 * above and hence timeout / drop the response as appropriate
1958 */
1959 hop_limit = 255;
1961 (uint8_t *)&hop_limit);
1962 coap_add_data(pdu, len, (uint8_t *)cp);
1963 } else {
1964 /* prepend with space separator, leaving hop limit "as is" */
1965 memmove(pdu->data + len + 1, pdu->data,
1966 old_size - (pdu->data - pdu->token));
1967 memcpy(pdu->data, cp, len);
1968 pdu->data[len] = ' ';
1969 pdu->used_size += len + 1;
1970 }
1971 }
1972 }
1973 }
1974 }
1975
1976 if (session->echo) {
1977 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1978 session->echo->s))
1979 goto error;
1980 coap_delete_bin_const(session->echo);
1981 session->echo = NULL;
1982 }
1983#if COAP_OSCORE_SUPPORT
1984 if (session->oscore_encryption) {
1985 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1987 goto error;
1988 }
1989#endif /* COAP_OSCORE_SUPPORT */
1990
1991 if (!coap_pdu_encode_header(pdu, session->proto)) {
1992 goto error;
1993 }
1994
1995#if !COAP_DISABLE_TCP
1996 if (COAP_PROTO_RELIABLE(session->proto) &&
1998 if (!session->csm_block_supported) {
1999 /*
2000 * Need to check that this instance is not sending any block options as
2001 * the remote end via CSM has not informed us that there is support
2002 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2003 * This includes potential BERT blocks.
2004 */
2005 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2006 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2007 }
2008 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2009 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2010 }
2011 } else if (!session->csm_bert_rem_support) {
2012 coap_opt_t *opt;
2013
2014 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2015 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2016 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2017 }
2018 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2019 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2020 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2021 }
2022 }
2023 }
2024#endif /* !COAP_DISABLE_TCP */
2025
2026#if COAP_OSCORE_SUPPORT
2027 if (session->oscore_encryption &&
2028 pdu->type != COAP_MESSAGE_RST &&
2029 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2030 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2031 /* Refactor PDU as appropriate RFC8613 */
2032 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2033
2034 if (osc_pdu == NULL) {
2035 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2038 goto error;
2039 }
2040 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2042 pdu = osc_pdu;
2043 } else
2044#endif /* COAP_OSCORE_SUPPORT */
2045 bytes_written = coap_send_pdu(session, pdu, NULL);
2046
2047#if COAP_SERVER_SUPPORT
2048 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
2049 session->cached_pdu != pdu &&
2050 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2051 COAP_PDU_IS_REQUEST(request_pdu) &&
2052 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2054 session->cached_pdu = pdu;
2056 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
2057 }
2058#endif /* COAP_SERVER_SUPPORT */
2059
2060 if (bytes_written == COAP_PDU_DELAYED) {
2061 /* do not free pdu as it is stored with session for later use */
2062 return pdu->mid;
2063 }
2064 if (bytes_written < 0) {
2066 goto error;
2067 }
2068
2069#if !COAP_DISABLE_TCP
2070 if (COAP_PROTO_RELIABLE(session->proto) &&
2071 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2072 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2073 session->partial_write = (size_t)bytes_written;
2074 /* do not free pdu as it is stored with session for later use */
2075 return pdu->mid;
2076 } else {
2077 goto error;
2078 }
2079 }
2080#endif /* !COAP_DISABLE_TCP */
2081
2082 if (pdu->type != COAP_MESSAGE_CON
2083 || COAP_PROTO_RELIABLE(session->proto)) {
2084 coap_mid_t id = pdu->mid;
2086 return id;
2087 }
2088
2089 coap_queue_t *node = coap_new_node();
2090 if (!node) {
2091 coap_log_debug("coap_wait_ack: insufficient memory\n");
2092 goto error;
2093 }
2094
2095 node->id = pdu->mid;
2096 node->pdu = pdu;
2097 coap_prng_lkd(&r, sizeof(r));
2098 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2099 node->timeout = coap_calc_timeout(session, r);
2100 return coap_wait_ack(session->context, session, node);
2101error:
2103 return COAP_INVALID_MID;
2104}
2105
2106static int send_recv_terminate = 0;
2107
2108void
2112
2113COAP_API int
2115 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2116 int ret;
2117
2118 coap_lock_lock(return 0);
2119 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2121 return ret;
2122}
2123
2124/*
2125 * Return 0 or +ve Time in function in ms after successful transfer
2126 * -1 Invalid timeout parameter
2127 * -2 Failed to transmit PDU
2128 * -3 Nack or Event handler invoked, cancelling request
2129 * -4 coap_io_process returned error (fail to re-lock or select())
2130 * -5 Response not received in the given time
2131 * -6 Terminated by user
2132 * -7 Client mode code not enabled
2133 */
2134int
2136 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2137#if COAP_CLIENT_SUPPORT
2139 uint32_t rem_timeout = timeout_ms;
2140 uint32_t block_mode = session->block_mode;
2141 int ret = 0;
2142 coap_tick_t now;
2143 coap_tick_t start;
2144 coap_tick_t ticks_so_far;
2145 uint32_t time_so_far_ms;
2146
2147 coap_ticks(&start);
2148 assert(request_pdu);
2149
2151
2152 session->resp_pdu = NULL;
2153 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2154 request_pdu->actual_token.length);
2155
2156 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2157 ret = -1;
2158 goto fail;
2159 }
2160 if (session->state == COAP_SESSION_STATE_NONE) {
2161 ret = -3;
2162 goto fail;
2163 }
2164
2166 if (coap_is_mcast(&session->addr_info.remote))
2167 block_mode = session->block_mode;
2168
2169 session->doing_send_recv = 1;
2170 /* So the user needs to delete the PDU */
2171 coap_pdu_reference_lkd(request_pdu);
2172 mid = coap_send_lkd(session, request_pdu);
2173 if (mid == COAP_INVALID_MID) {
2174 if (!session->doing_send_recv)
2175 ret = -3;
2176 else
2177 ret = -2;
2178 goto fail;
2179 }
2180
2181 /* Wait for the response to come in */
2182 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2183 if (send_recv_terminate) {
2184 ret = -6;
2185 goto fail;
2186 }
2187 ret = coap_io_process_lkd(session->context, rem_timeout);
2188 if (ret < 0) {
2189 ret = -4;
2190 goto fail;
2191 }
2192 /* timeout_ms is for timeout between specific request and response */
2193 coap_ticks(&now);
2194 ticks_so_far = now - session->last_rx_tx;
2195 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2196 if (time_so_far_ms >= timeout_ms) {
2197 rem_timeout = 0;
2198 } else {
2199 rem_timeout = timeout_ms - time_so_far_ms;
2200 }
2201 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2202 /* To pick up on (D)TLS setup issues */
2203 coap_ticks(&now);
2204 ticks_so_far = now - start;
2205 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2206 if (time_so_far_ms >= timeout_ms) {
2207 rem_timeout = 0;
2208 } else {
2209 rem_timeout = timeout_ms - time_so_far_ms;
2210 }
2211 }
2212 }
2213
2214 if (rem_timeout) {
2215 coap_ticks(&now);
2216 ticks_so_far = now - start;
2217 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2218 ret = time_so_far_ms;
2219 /* Give PDU to user who will be calling coap_delete_pdu() */
2220 *response_pdu = session->resp_pdu;
2221 session->resp_pdu = NULL;
2222 if (*response_pdu == NULL) {
2223 ret = -3;
2224 }
2225 } else {
2226 /* If there is a resp_pdu, it will get cleared below */
2227 ret = -5;
2228 }
2229
2230fail:
2231 session->block_mode = block_mode;
2232 session->doing_send_recv = 0;
2233 /* delete referenced copy */
2234 coap_delete_pdu_lkd(session->resp_pdu);
2235 session->resp_pdu = NULL;
2237 session->req_token = NULL;
2238 return ret;
2239
2240#else /* !COAP_CLIENT_SUPPORT */
2241
2242 (void)session;
2243 (void)timeout_ms;
2244 (void)request_pdu;
2245 coap_log_warn("coap_send_recv: Client mode not supported\n");
2246 *response_pdu = NULL;
2247 return -7;
2248
2249#endif /* ! COAP_CLIENT_SUPPORT */
2250}
2251
2254 if (!context || !node || !node->session)
2255 return COAP_INVALID_MID;
2256
2257 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2258 if (node->retransmit_cnt < node->session->max_retransmit) {
2259 ssize_t bytes_written;
2260 coap_tick_t now;
2261 coap_tick_t next_delay;
2262 coap_address_t remote;
2263
2264 node->retransmit_cnt++;
2266
2267 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2268 if (context->ping_timeout &&
2269 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2270 uint8_t byte;
2271
2272 coap_prng_lkd(&byte, sizeof(byte));
2273 /* Don't exceed the ping timeout value */
2274 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2275 }
2276
2277 coap_ticks(&now);
2278 if (context->sendqueue == NULL) {
2279 node->t = next_delay;
2280 context->sendqueue_basetime = now;
2281 } else {
2282 /* make node->t relative to context->sendqueue_basetime */
2283 node->t = (now - context->sendqueue_basetime) + next_delay;
2284 }
2285 coap_insert_node(&context->sendqueue, node);
2286 coap_address_copy(&remote, &node->session->addr_info.remote);
2288
2289 if (node->is_mcast) {
2290 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2291 coap_session_str(node->session), node->id);
2292 } else {
2293 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2294 coap_session_str(node->session), node->id,
2295 node->retransmit_cnt,
2296 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2297 }
2298
2299 if (node->session->con_active)
2300 node->session->con_active--;
2301 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2302
2303 if (bytes_written == COAP_PDU_DELAYED) {
2304 /* PDU was not retransmitted immediately because a new handshake is
2305 in progress. node was moved to the send queue of the session. */
2306 return node->id;
2307 }
2308
2309 coap_address_copy(&node->session->addr_info.remote, &remote);
2310 if (node->is_mcast) {
2313 return COAP_INVALID_MID;
2314 }
2315
2316 if (bytes_written < 0)
2317 return (int)bytes_written;
2318
2319 return node->id;
2320 }
2321
2322 /* no more retransmissions, remove node from system */
2323 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2324 coap_session_str(node->session), node->id, node->retransmit_cnt);
2325
2326#if COAP_SERVER_SUPPORT
2327 /* Check if subscriptions exist that should be canceled after
2328 COAP_OBS_MAX_FAIL */
2329 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2330 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2331 if (context->ping_timeout) {
2334 return COAP_INVALID_MID;
2335 } else {
2336 if (node->session->ref_subscriptions)
2337 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2338#if COAP_PROXY_SUPPORT
2339 /* Need to check is there is a proxy subscription active and delete it */
2340 if (node->session->ref_proxy_subs)
2341 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2342 0, COAP_PROXY_SUBS_TOKEN);
2343#endif /* COAP_PROXY_SUPPORT */
2344 }
2345 }
2346#endif /* COAP_SERVER_SUPPORT */
2347 if (node->session->con_active) {
2348 node->session->con_active--;
2350 /*
2351 * As there may be another CON in a different queue entry on the same
2352 * session that needs to be immediately released,
2353 * coap_session_connected() is called.
2354 * However, there is the possibility coap_wait_ack() may be called for
2355 * this node (queue) and re-added to context->sendqueue.
2356 * coap_delete_node_lkd(node) called shortly will handle this and
2357 * remove it.
2358 */
2360 }
2361 }
2362
2363 if (node->pdu->type == COAP_MESSAGE_CON) {
2365 }
2366#if COAP_CLIENT_SUPPORT
2367 node->session->doing_send_recv = 0;
2368#endif /* COAP_CLIENT_SUPPORT */
2369 /* And finally delete the node */
2371 return COAP_INVALID_MID;
2372}
2373
2374static int
2376 uint8_t *data;
2377 size_t data_len;
2378 int result = -1;
2379
2380 coap_packet_get_memmapped(packet, &data, &data_len);
2381 if (session->proto == COAP_PROTO_DTLS) {
2382#if COAP_SERVER_SUPPORT
2383 if (session->type == COAP_SESSION_TYPE_HELLO)
2384 result = coap_dtls_hello(session, data, data_len);
2385 else
2386#endif /* COAP_SERVER_SUPPORT */
2387 if (session->tls)
2388 result = coap_dtls_receive(session, data, data_len);
2389 } else if (session->proto == COAP_PROTO_UDP) {
2390 result = coap_handle_dgram(ctx, session, data, data_len);
2391 }
2392 return result;
2393}
2394
2395#if COAP_CLIENT_SUPPORT
2396void
2398#if COAP_DISABLE_TCP
2399 (void)now;
2400
2402#else /* !COAP_DISABLE_TCP */
2403 if (coap_netif_strm_connect2(session)) {
2404 session->last_rx_tx = now;
2406 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2407 } else {
2410 }
2411#endif /* !COAP_DISABLE_TCP */
2412}
2413#endif /* COAP_CLIENT_SUPPORT */
2414
2415static void
2417 (void)ctx;
2418 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2419
2420 while (session->delayqueue) {
2421 ssize_t bytes_written;
2422 coap_queue_t *q = session->delayqueue;
2423
2424 coap_address_copy(&session->addr_info.remote, &q->remote);
2425 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2426 coap_session_str(session), (int)q->pdu->mid);
2427 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2428 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2429 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2430 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2431 if (bytes_written > 0)
2432 session->last_rx_tx = now;
2433 if (bytes_written <= 0 ||
2434 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2435 if (bytes_written > 0)
2436 session->partial_write += (size_t)bytes_written;
2437 break;
2438 }
2439 session->delayqueue = q->next;
2440 session->partial_write = 0;
2442 }
2443}
2444
2445void
2447#if COAP_CONSTRAINED_STACK
2448 /* payload and packet can be protected by global_lock if needed */
2449 static unsigned char payload[COAP_RXBUFFER_SIZE];
2450 static coap_packet_t s_packet;
2451#else /* ! COAP_CONSTRAINED_STACK */
2452 unsigned char payload[COAP_RXBUFFER_SIZE];
2453 coap_packet_t s_packet;
2454#endif /* ! COAP_CONSTRAINED_STACK */
2455 coap_packet_t *packet = &s_packet;
2456
2458
2459 packet->length = sizeof(payload);
2460 packet->payload = payload;
2461
2462 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2463 ssize_t bytes_read;
2464 coap_address_t remote;
2465
2466 coap_address_copy(&remote, &session->addr_info.remote);
2467 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2468 bytes_read = coap_netif_dgrm_read(session, packet);
2469
2470 if (bytes_read < 0) {
2471 if (bytes_read == -2) {
2472 coap_address_copy(&session->addr_info.remote, &remote);
2473 /* Reset the session back to startup defaults */
2475 }
2476 } else if (bytes_read > 0) {
2477 session->last_rx_tx = now;
2478#if COAP_CLIENT_SUPPORT
2479 if (session->session_failed)
2480 session->session_failed = 0;
2481#endif /* COAP_CLIENT_SUPPORT */
2482 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2483 coap_handle_dgram_for_proto(ctx, session, packet);
2484 } else {
2485 coap_address_copy(&session->addr_info.remote, &remote);
2486 }
2487#if !COAP_DISABLE_TCP
2488 } else if (session->proto == COAP_PROTO_WS ||
2489 session->proto == COAP_PROTO_WSS) {
2490 ssize_t bytes_read = 0;
2491
2492 /* WebSocket layer passes us the whole packet */
2493 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2494 packet->payload,
2495 packet->length);
2496 if (bytes_read < 0) {
2498 } else if (bytes_read > 2) {
2499 coap_pdu_t *pdu;
2500
2501 session->last_rx_tx = now;
2502 /* Need max space incase PDU is updated with updated token etc. */
2503 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2504 if (!pdu) {
2505 return;
2506 }
2507
2508 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2510 coap_log_warn("discard malformed PDU\n");
2512 return;
2513 }
2514
2515 coap_dispatch(ctx, session, pdu);
2517 return;
2518 }
2519 } else {
2520 ssize_t bytes_read = 0;
2521 const uint8_t *p;
2522 int retry;
2523
2524 do {
2525 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2526 packet->payload,
2527 packet->length);
2528 if (bytes_read > 0) {
2529 session->last_rx_tx = now;
2530 }
2531 p = packet->payload;
2532 retry = bytes_read == (ssize_t)packet->length;
2533 while (bytes_read > 0) {
2534 if (session->partial_pdu) {
2535 size_t len = session->partial_pdu->used_size
2536 + session->partial_pdu->hdr_size
2537 - session->partial_read;
2538 size_t n = min(len, (size_t)bytes_read);
2539 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2540 + session->partial_read, p, n);
2541 p += n;
2542 bytes_read -= n;
2543 if (n == len) {
2544 coap_opt_filter_t error_opts;
2545 coap_pdu_t *pdu = session->partial_pdu;
2546
2547 session->partial_pdu = NULL;
2548 session->partial_read = 0;
2549
2550 coap_option_filter_clear(&error_opts);
2551 if (coap_pdu_parse_header(pdu, session->proto)
2552 && coap_pdu_parse_opt(pdu, &error_opts)) {
2553 coap_dispatch(ctx, session, pdu);
2554 } else if (error_opts.mask) {
2555 coap_pdu_t *response =
2557 COAP_RESPONSE_CODE(402), &error_opts);
2558 if (!response) {
2559 coap_log_warn("coap_read_session: cannot create error response\n");
2560 } else {
2561 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2562 coap_log_warn("coap_read_session: error sending response\n");
2563 }
2564 }
2566 } else {
2567 session->partial_read += n;
2568 }
2569 } else if (session->partial_read > 0) {
2570 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2571 session->read_header);
2572 size_t tkl = session->read_header[0] & 0x0f;
2573 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2574 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2575 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2576 size_t n = min(len, (size_t)bytes_read);
2577 memcpy(session->read_header + session->partial_read, p, n);
2578 p += n;
2579 bytes_read -= n;
2580 if (n == len) {
2581 /* Header now all in */
2582 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2583 hdr_size + tok_ext_bytes);
2584 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2585 coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
2586 coap_session_str(session),
2587 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2588 bytes_read = -1;
2589 break;
2590 }
2591 /* Need max space incase PDU is updated with updated token etc. */
2592 session->partial_pdu = coap_pdu_init(0, 0, 0,
2594 if (session->partial_pdu == NULL) {
2595 bytes_read = -1;
2596 break;
2597 }
2598 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2599 bytes_read = -1;
2600 break;
2601 }
2602 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2603 session->partial_pdu->used_size = size;
2604 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2605 session->partial_read = hdr_size + tok_ext_bytes;
2606 if (size == 0) {
2607 coap_pdu_t *pdu = session->partial_pdu;
2608
2609 session->partial_pdu = NULL;
2610 session->partial_read = 0;
2611 if (coap_pdu_parse_header(pdu, session->proto)) {
2612 coap_dispatch(ctx, session, pdu);
2613 }
2615 }
2616 } else {
2617 /* More of the header to go */
2618 session->partial_read += n;
2619 }
2620 } else {
2621 /* Get in first byte of the header */
2622 session->read_header[0] = *p++;
2623 bytes_read -= 1;
2624 if (!coap_pdu_parse_header_size(session->proto,
2625 session->read_header)) {
2626 bytes_read = -1;
2627 break;
2628 }
2629 session->partial_read = 1;
2630 }
2631 }
2632 } while (bytes_read == 0 && retry);
2633 if (bytes_read < 0)
2635#endif /* !COAP_DISABLE_TCP */
2636 }
2637}
2638
2639#if COAP_SERVER_SUPPORT
2640static int
2641coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2642 ssize_t bytes_read = -1;
2643 int result = -1; /* the value to be returned */
2644#if COAP_CONSTRAINED_STACK
2645 /* payload and e_packet can be protected by global_lock if needed */
2646 static unsigned char payload[COAP_RXBUFFER_SIZE];
2647 static coap_packet_t e_packet;
2648#else /* ! COAP_CONSTRAINED_STACK */
2649 unsigned char payload[COAP_RXBUFFER_SIZE];
2650 coap_packet_t e_packet;
2651#endif /* ! COAP_CONSTRAINED_STACK */
2652 coap_packet_t *packet = &e_packet;
2653
2654 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2655 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2656
2657 /* Need to do this as there may be holes in addr_info */
2658 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2659 packet->length = sizeof(payload);
2660 packet->payload = payload;
2662 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2663
2664 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2665 if (bytes_read < 0) {
2666 if (errno != EAGAIN) {
2667 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2668 }
2669 } else if (bytes_read > 0) {
2670 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2671 if (session) {
2673 coap_log_debug("* %s: netif: recv %4zd bytes\n",
2674 coap_session_str(session), bytes_read);
2675 result = coap_handle_dgram_for_proto(ctx, session, packet);
2676 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2677 coap_session_new_dtls_session(session, now);
2678 coap_session_release_lkd(session);
2679 }
2680 }
2681 return result;
2682}
2683
2684static int
2685coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2686 (void)ctx;
2687 (void)endpoint;
2688 (void)now;
2689 return 0;
2690}
2691
2692#if !COAP_DISABLE_TCP
2693static int
2694coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2695 coap_tick_t now, void *extra) {
2696 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2697 if (session)
2698 session->last_rx_tx = now;
2699 return session != NULL;
2700}
2701#endif /* !COAP_DISABLE_TCP */
2702#endif /* COAP_SERVER_SUPPORT */
2703
2704COAP_API void
2706 coap_lock_lock(return);
2707 coap_io_do_io_lkd(ctx, now);
2709}
2710
2711void
2713#ifdef COAP_EPOLL_SUPPORT
2714 (void)ctx;
2715 (void)now;
2716 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2717#else /* ! COAP_EPOLL_SUPPORT */
2718 coap_session_t *s, *rtmp;
2719
2721#if COAP_SERVER_SUPPORT
2722 coap_endpoint_t *ep, *tmp;
2723 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2724 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2725 coap_read_endpoint(ctx, ep, now);
2726 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2727 coap_write_endpoint(ctx, ep, now);
2728#if !COAP_DISABLE_TCP
2729 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2730 coap_accept_endpoint(ctx, ep, now, NULL);
2731#endif /* !COAP_DISABLE_TCP */
2732 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2733 /* Make sure the session object is not deleted in one of the callbacks */
2735 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2736 coap_read_session(ctx, s, now);
2737 }
2738 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2739 coap_write_session(ctx, s, now);
2740 }
2742 }
2743 }
2744#endif /* COAP_SERVER_SUPPORT */
2745
2746#if COAP_CLIENT_SUPPORT
2747 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2748 /* Make sure the session object is not deleted in one of the callbacks */
2750 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2751 coap_connect_session(s, now);
2752 }
2753 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2754 coap_read_session(ctx, s, now);
2755 }
2756 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2757 coap_write_session(ctx, s, now);
2758 }
2760 }
2761#endif /* COAP_CLIENT_SUPPORT */
2762#endif /* ! COAP_EPOLL_SUPPORT */
2763}
2764
2765COAP_API void
2766coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2767 coap_lock_lock(return);
2768 coap_io_do_epoll_lkd(ctx, events, nevents);
2770}
2771
2772/*
2773 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2774 * directly saves having to iterate through the endpoints / sessions.
2775 */
2776void
2777coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2778#ifndef COAP_EPOLL_SUPPORT
2779 (void)ctx;
2780 (void)events;
2781 (void)nevents;
2782 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2783#else /* COAP_EPOLL_SUPPORT */
2784 coap_tick_t now;
2785 size_t j;
2786
2788 coap_ticks(&now);
2789 for (j = 0; j < nevents; j++) {
2790 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2791
2792 /* Ignore 'timer trigger' ptr which is NULL */
2793 if (sock) {
2794#if COAP_SERVER_SUPPORT
2795 if (sock->endpoint) {
2796 coap_endpoint_t *endpoint = sock->endpoint;
2797 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2798 (events[j].events & EPOLLIN)) {
2799 sock->flags |= COAP_SOCKET_CAN_READ;
2800 coap_read_endpoint(endpoint->context, endpoint, now);
2801 }
2802
2803 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2804 (events[j].events & EPOLLOUT)) {
2805 /*
2806 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2807 * be true causing epoll_wait to return early
2808 */
2809 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2811 coap_write_endpoint(endpoint->context, endpoint, now);
2812 }
2813
2814#if !COAP_DISABLE_TCP
2815 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2816 (events[j].events & EPOLLIN)) {
2818 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2819 }
2820#endif /* !COAP_DISABLE_TCP */
2821
2822 } else
2823#endif /* COAP_SERVER_SUPPORT */
2824 if (sock->session) {
2825 coap_session_t *session = sock->session;
2826
2827 /* Make sure the session object is not deleted
2828 in one of the callbacks */
2830#if COAP_CLIENT_SUPPORT
2831 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2832 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2834 coap_connect_session(session, now);
2835 if (coap_netif_available(session) &&
2836 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2837 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2838 }
2839 }
2840#endif /* COAP_CLIENT_SUPPORT */
2841
2842 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2843 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2844 sock->flags |= COAP_SOCKET_CAN_READ;
2845 coap_read_session(session->context, session, now);
2846 }
2847
2848 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2849 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2850 /*
2851 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2852 * be true causing epoll_wait to return early
2853 */
2854 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2856 coap_write_session(session->context, session, now);
2857 }
2858 /* Now dereference session so it can go away if needed */
2859 coap_session_release_lkd(session);
2860 }
2861 } else if (ctx->eptimerfd != -1) {
2862 /*
2863 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2864 * it so that it does not set EPOLLIN in the next epoll_wait().
2865 */
2866 uint64_t count;
2867
2868 /* Check the result from read() to suppress the warning on
2869 * systems that declare read() with warn_unused_result. */
2870 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2871 /* do nothing */;
2872 }
2873 }
2874 }
2875 /* And update eptimerfd as to when to next trigger */
2876 coap_ticks(&now);
2877 coap_io_prepare_epoll_lkd(ctx, now);
2878#endif /* COAP_EPOLL_SUPPORT */
2879}
2880
2881int
2883 uint8_t *msg, size_t msg_len) {
2884
2885 coap_pdu_t *pdu = NULL;
2886 coap_opt_filter_t error_opts;
2887
2888 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2889 if (msg_len < 4) {
2890 /* Minimum size of CoAP header - ignore runt */
2891 return -1;
2892 }
2893 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2894 /*
2895 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2896 * this MUST be silently ignored.
2897 */
2898 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2899 return -1;
2900 }
2901
2902 /* Need max space incase PDU is updated with updated token etc. */
2903 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2904 if (!pdu)
2905 goto error;
2906
2907 coap_option_filter_clear(&error_opts);
2908 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
2910 coap_log_warn("discard malformed PDU\n");
2911 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
2912 coap_pdu_t *response =
2914 COAP_RESPONSE_CODE(402), &error_opts);
2915 if (!response) {
2916 coap_log_warn("coap_handle_dgram: cannot create error response\n");
2917 } else {
2918 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2919 coap_log_warn("coap_handle_dgram: error sending response\n");
2920 }
2922 return -1;
2923 } else {
2924 goto error;
2925 }
2926 }
2927
2928 coap_dispatch(ctx, session, pdu);
2930 return 0;
2931
2932error:
2933 /*
2934 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2935 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2936 */
2937 coap_send_rst_lkd(session, pdu);
2939 return -1;
2940}
2941
2942int
2944 coap_queue_t **node) {
2945 coap_queue_t *p, *q;
2946
2947 if (!queue || !*queue)
2948 return 0;
2949
2950 /* replace queue head if PDU's time is less than head's time */
2951
2952 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2953 *node = *queue;
2954 *queue = (*queue)->next;
2955 if (*queue) { /* adjust relative time of new queue head */
2956 (*queue)->t += (*node)->t;
2957 }
2958 (*node)->next = NULL;
2959 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2960 coap_session_str(session), id);
2961 return 1;
2962 }
2963
2964 /* search message id in queue to remove (only first occurence will be removed) */
2965 q = *queue;
2966 do {
2967 p = q;
2968 q = q->next;
2969 } while (q && (session != q->session || id != q->id));
2970
2971 if (q) { /* found message id */
2972 p->next = q->next;
2973 if (p->next) { /* must update relative time of p->next */
2974 p->next->t += q->t;
2975 }
2976 q->next = NULL;
2977 *node = q;
2978 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
2979 coap_session_str(session), id);
2980 return 1;
2981 }
2982
2983 return 0;
2984
2985}
2986
2987static int
2989 coap_bin_const_t *token, coap_queue_t **node) {
2990 coap_queue_t *p, *q;
2991
2992 if (!queue || !*queue)
2993 return 0;
2994
2995 /* replace queue head if PDU's time is less than head's time */
2996
2997 if (session == (*queue)->session &&
2998 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
2999 *node = *queue;
3000 *queue = (*queue)->next;
3001 if (*queue) { /* adjust relative time of new queue head */
3002 (*queue)->t += (*node)->t;
3003 }
3004 (*node)->next = NULL;
3005 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3006 coap_session_str(session), (*node)->id);
3007 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3008 session->con_active--;
3009 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3010 /* Flush out any entries on session->delayqueue */
3011 coap_session_connected(session);
3012 }
3013 return 1;
3014 }
3015
3016 /* search token in queue to remove (only first occurence will be removed) */
3017 q = *queue;
3018 do {
3019 p = q;
3020 q = q->next;
3021 } while (q && (session != q->session ||
3022 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3023
3024 if (q) { /* found token */
3025 p->next = q->next;
3026 if (p->next) { /* must update relative time of p->next */
3027 p->next->t += q->t;
3028 }
3029 q->next = NULL;
3030 *node = q;
3031 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3032 coap_session_str(session), (*node)->id);
3033 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3034 session->con_active--;
3035 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3036 /* Flush out any entries on session->delayqueue */
3037 coap_session_connected(session);
3038 }
3039 return 1;
3040 }
3041
3042 return 0;
3043
3044}
3045
3046void
3048 coap_nack_reason_t reason) {
3049 coap_queue_t *p, *q;
3050
3051 while (context->sendqueue && context->sendqueue->session == session) {
3052 q = context->sendqueue;
3053 context->sendqueue = q->next;
3054 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3055 coap_session_str(session), q->id);
3056 if (q->pdu->type == COAP_MESSAGE_CON) {
3057 coap_handle_nack(session, q->pdu, reason, q->id);
3058 }
3060 }
3061
3062 if (!context->sendqueue)
3063 return;
3064
3065 p = context->sendqueue;
3066 q = p->next;
3067
3068 while (q) {
3069 if (q->session == session) {
3070 p->next = q->next;
3071 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3072 coap_session_str(session), q->id);
3073 if (q->pdu->type == COAP_MESSAGE_CON) {
3074 coap_handle_nack(session, q->pdu, reason, q->id);
3075 }
3077 q = p->next;
3078 } else {
3079 p = q;
3080 q = q->next;
3081 }
3082 }
3083}
3084
3085void
3087 coap_bin_const_t *token) {
3088 /* cancel all messages in sendqueue that belong to session
3089 * and use the specified token */
3090 coap_queue_t **p, *q;
3091
3092 if (!context->sendqueue)
3093 return;
3094
3095 p = &context->sendqueue;
3096 q = *p;
3097
3098 while (q) {
3099 if (q->session == session &&
3100 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3101 *p = q->next;
3102 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3103 coap_session_str(session), q->id);
3104 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3105 session->con_active--;
3106 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3107 /* Flush out any entries on session->delayqueue */
3108 coap_session_connected(session);
3109 }
3111 } else {
3112 p = &(q->next);
3113 }
3114 q = *p;
3115 }
3116}
3117
3118coap_pdu_t *
3120 coap_opt_filter_t *opts) {
3121 coap_opt_iterator_t opt_iter;
3122 coap_pdu_t *response;
3123 unsigned char type;
3124
3125#if COAP_ERROR_PHRASE_LENGTH > 0
3126 const char *phrase;
3127 if (code != COAP_RESPONSE_CODE(508)) {
3128 phrase = coap_response_phrase(code);
3129 } else {
3130 phrase = NULL;
3131 }
3132#endif
3133
3134 assert(request);
3135
3136 /* cannot send ACK if original request was not confirmable */
3137 type = request->type == COAP_MESSAGE_CON ?
3139
3140 /* Now create the response and fill with options and payload data. */
3141 response = coap_pdu_init(type, code, request->mid,
3142 request->session ?
3143 coap_session_max_pdu_size_lkd(request->session) : 512);
3144 if (response) {
3145 /* copy token */
3146 if (!coap_add_token(response, request->actual_token.length,
3147 request->actual_token.s)) {
3148 coap_log_debug("cannot add token to error response\n");
3149 coap_delete_pdu_lkd(response);
3150 return NULL;
3151 }
3152 if (response->code == COAP_RESPONSE_CODE(402)) {
3153 char buf[128];
3154 int first = 1;
3155
3156#if COAP_ERROR_PHRASE_LENGTH > 0
3157 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3158#else
3159 buf[0] = '\000';
3160#endif
3161 /* copy all options into diagnostic message */
3162 coap_option_iterator_init(request, &opt_iter, opts);
3163 while (coap_option_next(&opt_iter)) {
3164 size_t len = strlen(buf);
3165
3166 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",", opt_iter.number);
3167 first = 0;
3168 }
3169 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3170 } else if (opts && opts->mask) {
3171 coap_opt_t *option;
3172
3173 /* copy all options */
3174 coap_option_iterator_init(request, &opt_iter, opts);
3175 while ((option = coap_option_next(&opt_iter))) {
3176 coap_add_option_internal(response, opt_iter.number,
3177 coap_opt_length(option),
3178 coap_opt_value(option));
3179 }
3180#if COAP_ERROR_PHRASE_LENGTH > 0
3181 if (phrase)
3182 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3183 } else {
3184 /* note that diagnostic messages do not need a Content-Format option. */
3185 if (phrase)
3186 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3187#endif
3188 }
3189 }
3190
3191 return response;
3192}
3193
3194#if COAP_SERVER_SUPPORT
3195#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3196
3197static void
3198free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3199 coap_delete_string(app_ptr);
3200}
3201
3202/*
3203 * Caution: As this handler is in libcoap space, it is called with
3204 * context locked.
3205 */
3206static void
3207hnd_get_wellknown_lkd(coap_resource_t *resource,
3208 coap_session_t *session,
3209 const coap_pdu_t *request,
3210 const coap_string_t *query,
3211 coap_pdu_t *response) {
3212 size_t len = 0;
3213 coap_string_t *data_string = NULL;
3214 coap_print_status_t result = 0;
3215 size_t wkc_len = 0;
3216 uint8_t buf[4];
3217
3218 /*
3219 * Quick hack to determine the size of the resource descriptions for
3220 * .well-known/core.
3221 */
3222 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3223 if (result & COAP_PRINT_STATUS_ERROR) {
3224 coap_log_warn("cannot determine length of /.well-known/core\n");
3225 goto error;
3226 }
3227
3228 if (wkc_len > 0) {
3229 data_string = coap_new_string(wkc_len);
3230 if (!data_string)
3231 goto error;
3232
3233 len = wkc_len;
3234 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3235 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3236 coap_log_debug("coap_print_wellknown failed\n");
3237 goto error;
3238 }
3239 assert(len <= (size_t)wkc_len);
3240 data_string->length = len;
3241
3242 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3244 coap_encode_var_safe(buf, sizeof(buf),
3246 goto error;
3247 }
3248 if (response->used_size + len + 1 > response->max_size) {
3249 /*
3250 * Data does not fit into a packet and no libcoap block support
3251 * +1 for end of options marker
3252 */
3253 coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
3254 len, response->max_size - response->used_size - 1);
3255 len = response->max_size - response->used_size - 1;
3256 }
3257 if (!coap_add_data(response, len, data_string->s)) {
3258 goto error;
3259 }
3260 free_wellknown_response(session, data_string);
3261 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3262 response, query,
3264 -1, 0, data_string->length,
3265 data_string->s,
3266 free_wellknown_response,
3267 data_string)) {
3268 goto error_released;
3269 }
3270 } else {
3272 coap_encode_var_safe(buf, sizeof(buf),
3274 goto error;
3275 }
3276 }
3277 response->code = COAP_RESPONSE_CODE(205);
3278 return;
3279
3280error:
3281 free_wellknown_response(session, data_string);
3282error_released:
3283 if (response->code == 0) {
3284 /* set error code 5.03 and remove all options and data from response */
3285 response->code = COAP_RESPONSE_CODE(503);
3286 response->used_size = response->e_token_length;
3287 response->data = NULL;
3288 }
3289}
3290#endif /* COAP_SERVER_SUPPORT */
3291
3302static int
3304 int num_cancelled = 0; /* the number of observers cancelled */
3305
3306#ifndef COAP_SERVER_SUPPORT
3307 (void)sent;
3308#endif /* ! COAP_SERVER_SUPPORT */
3309 (void)context;
3310
3311#if COAP_SERVER_SUPPORT
3312 /* remove observer for this resource, if any
3313 * Use token from sent and try to find a matching resource. Uh!
3314 */
3315 RESOURCES_ITER(context->resources, r) {
3316 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3317 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3318 }
3319#endif /* COAP_SERVER_SUPPORT */
3320
3321 return num_cancelled;
3322}
3323
3324#if COAP_SERVER_SUPPORT
3329enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3330
3331/*
3332 * Checks for No-Response option in given @p request and
3333 * returns @c RESPONSE_DROP if @p response should be suppressed
3334 * according to RFC 7967.
3335 *
3336 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3337 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3338 * on retrying.
3339 *
3340 * Checks if the response code is 0.00 and if either the session is reliable or
3341 * non-confirmable, @c RESPONSE_DROP is also returned.
3342 *
3343 * Multicast response checking is also carried out.
3344 *
3345 * NOTE: It is the responsibility of the application to determine whether
3346 * a delayed separate response should be sent as the original requesting packet
3347 * containing the No-Response option has long since gone.
3348 *
3349 * The value of the No-Response option is encoded as
3350 * follows:
3351 *
3352 * @verbatim
3353 * +-------+-----------------------+-----------------------------------+
3354 * | Value | Binary Representation | Description |
3355 * +-------+-----------------------+-----------------------------------+
3356 * | 0 | <empty> | Interested in all responses. |
3357 * +-------+-----------------------+-----------------------------------+
3358 * | 2 | 00000010 | Not interested in 2.xx responses. |
3359 * +-------+-----------------------+-----------------------------------+
3360 * | 8 | 00001000 | Not interested in 4.xx responses. |
3361 * +-------+-----------------------+-----------------------------------+
3362 * | 16 | 00010000 | Not interested in 5.xx responses. |
3363 * +-------+-----------------------+-----------------------------------+
3364 * @endverbatim
3365 *
3366 * @param request The CoAP request to check for the No-Response option.
3367 * This parameter must not be NULL.
3368 * @param response The response that is potentially suppressed.
3369 * This parameter must not be NULL.
3370 * @param session The session this request/response are associated with.
3371 * This parameter must not be NULL.
3372 * @return RESPONSE_DEFAULT when no special treatment is requested,
3373 * RESPONSE_DROP when the response must be discarded, or
3374 * RESPONSE_SEND when the response must be sent.
3375 */
3376static enum respond_t
3377no_response(coap_pdu_t *request, coap_pdu_t *response,
3378 coap_session_t *session, coap_resource_t *resource) {
3379 coap_opt_t *nores;
3380 coap_opt_iterator_t opt_iter;
3381 unsigned int val = 0;
3382
3383 assert(request);
3384 assert(response);
3385
3386 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3387 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3388
3389 if (nores) {
3391
3392 /* The response should be dropped when the bit corresponding to
3393 * the response class is set (cf. table in function
3394 * documentation). When a No-Response option is present and the
3395 * bit is not set, the sender explicitly indicates interest in
3396 * this response. */
3397 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3398 /* Should be dropping the response */
3399 if (response->type == COAP_MESSAGE_ACK &&
3400 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3401 /* Still need to ACK the request */
3402 response->code = 0;
3403 /* Remove token/data from piggybacked acknowledgment PDU */
3404 response->actual_token.length = 0;
3405 response->e_token_length = 0;
3406 response->used_size = 0;
3407 response->data = NULL;
3408 return RESPONSE_SEND;
3409 } else {
3410 return RESPONSE_DROP;
3411 }
3412 } else {
3413 /* True for mcast as well RFC7967 2.1 */
3414 return RESPONSE_SEND;
3415 }
3416 } else if (resource && session->context->mcast_per_resource &&
3417 coap_is_mcast(&session->addr_info.local)) {
3418 /* Handle any mcast suppression specifics if no NoResponse option */
3419 if ((resource->flags &
3421 COAP_RESPONSE_CLASS(response->code) == 2) {
3422 return RESPONSE_DROP;
3423 } else if ((resource->flags &
3425 response->code == COAP_RESPONSE_CODE(205)) {
3426 if (response->data == NULL)
3427 return RESPONSE_DROP;
3428 } else if ((resource->flags &
3430 COAP_RESPONSE_CLASS(response->code) == 4) {
3431 return RESPONSE_DROP;
3432 } else if ((resource->flags &
3434 COAP_RESPONSE_CLASS(response->code) == 5) {
3435 return RESPONSE_DROP;
3436 }
3437 }
3438 } else if (COAP_PDU_IS_EMPTY(response) &&
3439 (response->type == COAP_MESSAGE_NON ||
3440 COAP_PROTO_RELIABLE(session->proto))) {
3441 /* response is 0.00, and this is reliable or non-confirmable */
3442 return RESPONSE_DROP;
3443 }
3444
3445 /*
3446 * Do not send error responses for requests that were received via
3447 * IP multicast. RFC7252 8.1
3448 */
3449
3450 if (coap_is_mcast(&session->addr_info.local)) {
3451 if (request->type == COAP_MESSAGE_NON &&
3452 response->type == COAP_MESSAGE_RST)
3453 return RESPONSE_DROP;
3454
3455 if ((!resource || session->context->mcast_per_resource == 0) &&
3456 COAP_RESPONSE_CLASS(response->code) > 2)
3457 return RESPONSE_DROP;
3458 }
3459
3460 /* Default behavior applies when we are not dealing with a response
3461 * (class == 0) or the request did not contain a No-Response option.
3462 */
3463 return RESPONSE_DEFAULT;
3464}
3465
3466static coap_str_const_t coap_default_uri_wellknown = {
3468 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3469};
3470
3471/* Initialized in coap_startup() */
3472static coap_resource_t resource_uri_wellknown;
3473
3474static void
3475handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3476 coap_pdu_t *orig_pdu) {
3477 coap_method_handler_t h = NULL;
3478 coap_pdu_t *response = NULL;
3479 coap_opt_filter_t opt_filter;
3480 coap_resource_t *resource = NULL;
3481 /* The respond field indicates whether a response must be treated
3482 * specially due to a No-Response option that declares disinterest
3483 * or interest in a specific response class. DEFAULT indicates that
3484 * No-Response has not been specified. */
3485 enum respond_t respond = RESPONSE_DEFAULT;
3486 coap_opt_iterator_t opt_iter;
3487 coap_opt_t *opt;
3488 int is_proxy_uri = 0;
3489 int is_proxy_scheme = 0;
3490 int skip_hop_limit_check = 0;
3491 int resp = 0;
3492 int send_early_empty_ack = 0;
3493 coap_string_t *query = NULL;
3494 coap_opt_t *observe = NULL;
3495 coap_string_t *uri_path = NULL;
3496 int observe_action = COAP_OBSERVE_CANCEL;
3497 coap_block_b_t block;
3498 int added_block = 0;
3499 coap_lg_srcv_t *free_lg_srcv = NULL;
3500#if COAP_Q_BLOCK_SUPPORT
3501 int lg_xmit_ctrl = 0;
3502#endif /* COAP_Q_BLOCK_SUPPORT */
3503#if COAP_ASYNC_SUPPORT
3504 coap_async_t *async;
3505#endif /* COAP_ASYNC_SUPPORT */
3506
3507 if (coap_is_mcast(&session->addr_info.local)) {
3508 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3509 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3510 return;
3511 }
3512 }
3513#if COAP_ASYNC_SUPPORT
3514 async = coap_find_async_lkd(session, pdu->actual_token);
3515 if (async) {
3516 coap_tick_t now;
3517
3518 coap_ticks(&now);
3519 if (async->delay == 0 || async->delay > now) {
3520 /* re-transmit missing ACK (only if CON) */
3521 coap_log_info("Retransmit async response\n");
3522 coap_send_ack_lkd(session, pdu);
3523 /* and do not pass on to the upper layers */
3524 return;
3525 }
3526 }
3527#endif /* COAP_ASYNC_SUPPORT */
3528
3529 coap_option_filter_clear(&opt_filter);
3530 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3531 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3532 if (opt) {
3533 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3534 if (!opt) {
3535 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3536 resp = 402;
3537 goto fail_response;
3538 }
3539 is_proxy_scheme = 1;
3540 }
3541
3542 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3543 if (opt)
3544 is_proxy_uri = 1;
3545 }
3546
3547 if (is_proxy_scheme || is_proxy_uri) {
3548 coap_uri_t uri;
3549
3550 if (!context->proxy_uri_resource) {
3551 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3552 coap_log_debug("Proxy-%s support not configured\n",
3553 is_proxy_scheme ? "Scheme" : "Uri");
3554 resp = 505;
3555 goto fail_response;
3556 }
3557 if (((size_t)pdu->code - 1 <
3558 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3559 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3560 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3561 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3562 is_proxy_scheme ? "Scheme" : "Uri",
3563 pdu->code/100, pdu->code%100);
3564 resp = 505;
3565 goto fail_response;
3566 }
3567
3568 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3569 if (is_proxy_uri) {
3571 coap_opt_length(opt), &uri) < 0) {
3572 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3573 coap_log_debug("Proxy-URI not decodable\n");
3574 resp = 505;
3575 goto fail_response;
3576 }
3577 } else {
3578 memset(&uri, 0, sizeof(uri));
3579 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3580 if (opt) {
3581 uri.host.length = coap_opt_length(opt);
3582 uri.host.s = coap_opt_value(opt);
3583 } else
3584 uri.host.length = 0;
3585 }
3586
3587 resource = context->proxy_uri_resource;
3588 if (uri.host.length && resource->proxy_name_count &&
3589 resource->proxy_name_list) {
3590 size_t i;
3591
3592 if (resource->proxy_name_count == 1 &&
3593 resource->proxy_name_list[0]->length == 0) {
3594 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3595 i = 0;
3596 } else {
3597 for (i = 0; i < resource->proxy_name_count; i++) {
3598 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3599 break;
3600 }
3601 }
3602 }
3603 if (i != resource->proxy_name_count) {
3604 /* This server is hosting the proxy connection endpoint */
3605 if (pdu->crit_opt) {
3606 /* Cannot handle critical option */
3607 pdu->crit_opt = 0;
3608 resp = 402;
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
3619 if (!skip_hop_limit_check) {
3620 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3621 if (opt) {
3622 size_t hop_limit;
3623 uint8_t buf[4];
3624
3625 hop_limit =
3627 if (hop_limit == 1) {
3628 /* coap_send_internal() will fill in the IP address for us */
3629 resp = 508;
3630 goto fail_response;
3631 } else if (hop_limit < 1 || hop_limit > 255) {
3632 /* Need to return a 4.00 RFC8768 Section 3 */
3633 coap_log_info("Invalid Hop Limit\n");
3634 resp = 400;
3635 goto fail_response;
3636 }
3637 hop_limit--;
3639 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3640 buf);
3641 }
3642 }
3643
3644 uri_path = coap_get_uri_path(pdu);
3645 if (!uri_path)
3646 return;
3647
3648 if (!is_proxy_uri && !is_proxy_scheme) {
3649 /* try to find the resource from the request URI */
3650 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3651 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3652 }
3653
3654 if ((resource == NULL) || (resource->is_unknown == 1) ||
3655 (resource->is_proxy_uri == 1)) {
3656 /* The resource was not found or there is an unexpected match against the
3657 * resource defined for handling unknown or proxy URIs.
3658 */
3659 if (resource != NULL)
3660 /* Close down unexpected match */
3661 resource = NULL;
3662 /*
3663 * Check if the request URI happens to be the well-known URI, or if the
3664 * unknown resource handler is defined, a PUT or optionally other methods,
3665 * if configured, for the unknown handler.
3666 *
3667 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3668 * proxy URI handler.
3669 *
3670 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3671 * set, call the unknown URI handler with any unknown URI (including
3672 * .well-known/core) if the appropriate method is defined.
3673 *
3674 * else if well-known URI generate a default response.
3675 *
3676 * else if unknown URI handler defined, call the unknown
3677 * URI handler (to allow for potential generation of resource
3678 * [RFC7272 5.8.3]) if the appropriate method is defined.
3679 *
3680 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3681 *
3682 * else return 4.04.
3683 */
3684
3685 if (is_proxy_uri || is_proxy_scheme) {
3686 resource = context->proxy_uri_resource;
3687 } else if (context->unknown_resource != NULL &&
3689 ((size_t)pdu->code - 1 <
3690 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3691 (context->unknown_resource->handler[pdu->code - 1])) {
3692 resource = context->unknown_resource;
3693 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3694 /* request for .well-known/core */
3695 resource = &resource_uri_wellknown;
3696 } else if ((context->unknown_resource != NULL) &&
3697 ((size_t)pdu->code - 1 <
3698 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3699 (context->unknown_resource->handler[pdu->code - 1])) {
3700 /*
3701 * The unknown_resource can be used to handle undefined resources
3702 * for a PUT request and can support any other registered handler
3703 * defined for it
3704 * Example set up code:-
3705 * r = coap_resource_unknown_init(hnd_put_unknown);
3706 * coap_register_request_handler(r, COAP_REQUEST_POST,
3707 * hnd_post_unknown);
3708 * coap_register_request_handler(r, COAP_REQUEST_GET,
3709 * hnd_get_unknown);
3710 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3711 * hnd_delete_unknown);
3712 * coap_add_resource(ctx, r);
3713 *
3714 * Note: It is not possible to observe the unknown_resource, a separate
3715 * resource must be created (by PUT or POST) which has a GET
3716 * handler to be observed
3717 */
3718 resource = context->unknown_resource;
3719 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3720 /*
3721 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3722 */
3723 coap_log_debug("request for unknown resource '%*.*s',"
3724 " return 2.02\n",
3725 (int)uri_path->length,
3726 (int)uri_path->length,
3727 uri_path->s);
3728 resp = 202;
3729 goto fail_response;
3730 } else { /* request for any another resource, return 4.04 */
3731
3732 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3733 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3734 resp = 404;
3735 goto fail_response;
3736 }
3737
3738 }
3739
3740#if COAP_OSCORE_SUPPORT
3741 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3742 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3743 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3744 resp = 401;
3745 goto fail_response;
3746 }
3747#endif /* COAP_OSCORE_SUPPORT */
3748 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3749 /* Check for existing resource and If-Non-Match */
3750 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3751 if (opt) {
3752 resp = 412;
3753 goto fail_response;
3754 }
3755 }
3756
3757 /* the resource was found, check if there is a registered handler */
3758 if ((size_t)pdu->code - 1 <
3759 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3760 h = resource->handler[pdu->code - 1];
3761
3762 if (h == NULL) {
3763 resp = 405;
3764 goto fail_response;
3765 }
3766 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3767 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3768 if (opt == NULL) {
3769 /* RFC 8132 2.3.1 */
3770 resp = 415;
3771 goto fail_response;
3772 }
3773 }
3774 if (context->mcast_per_resource &&
3775 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3776 coap_is_mcast(&session->addr_info.local)) {
3777 resp = 405;
3778 goto fail_response;
3779 }
3780
3781 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3783 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3784 if (!response) {
3785 coap_log_err("could not create response PDU\n");
3786 resp = 500;
3787 goto fail_response;
3788 }
3789 response->session = session;
3790#if COAP_ASYNC_SUPPORT
3791 /* If handling a separate response, need CON, not ACK response */
3792 if (async && pdu->type == COAP_MESSAGE_CON)
3793 response->type = COAP_MESSAGE_CON;
3794#endif /* COAP_ASYNC_SUPPORT */
3795 /* A lot of the reliable code assumes type is CON */
3796 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3797 response->type = COAP_MESSAGE_CON;
3798
3799 if (!coap_add_token(response, pdu->actual_token.length,
3800 pdu->actual_token.s)) {
3801 resp = 500;
3802 goto fail_response;
3803 }
3804
3805 query = coap_get_query(pdu);
3806
3807 /* check for Observe option RFC7641 and RFC8132 */
3808 if (resource->observable &&
3809 (pdu->code == COAP_REQUEST_CODE_GET ||
3810 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3811 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3812 }
3813
3814 /*
3815 * See if blocks need to be aggregated or next requests sent off
3816 * before invoking application request handler
3817 */
3818 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3819 uint32_t block_mode = session->block_mode;
3820
3821 if (observe ||
3824 if (coap_handle_request_put_block(context, session, pdu, response,
3825 resource, uri_path, observe,
3826 &added_block, &free_lg_srcv)) {
3827 session->block_mode = block_mode;
3828 goto skip_handler;
3829 }
3830 session->block_mode = block_mode;
3831
3832 if (coap_handle_request_send_block(session, pdu, response, resource,
3833 query)) {
3834#if COAP_Q_BLOCK_SUPPORT
3835 lg_xmit_ctrl = 1;
3836#endif /* COAP_Q_BLOCK_SUPPORT */
3837 goto skip_handler;
3838 }
3839 }
3840
3841 if (observe) {
3842 observe_action =
3844 coap_opt_length(observe));
3845
3846 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3847 coap_subscription_t *subscription;
3848
3849 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3850 if (block.num != 0) {
3851 response->code = COAP_RESPONSE_CODE(400);
3852 goto skip_handler;
3853 }
3854#if COAP_Q_BLOCK_SUPPORT
3855 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3856 &block)) {
3857 if (block.num != 0) {
3858 response->code = COAP_RESPONSE_CODE(400);
3859 goto skip_handler;
3860 }
3861#endif /* COAP_Q_BLOCK_SUPPORT */
3862 }
3863 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3864 pdu);
3865 if (subscription) {
3866 uint8_t buf[4];
3867
3868 coap_touch_observer(context, session, &pdu->actual_token);
3870 coap_encode_var_safe(buf, sizeof(buf),
3871 resource->observe),
3872 buf);
3873 }
3874 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3875 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3876 } else {
3877 coap_log_info("observe: unexpected action %d\n", observe_action);
3878 }
3879 }
3880
3881 if ((resource == context->proxy_uri_resource ||
3882 (resource == context->unknown_resource &&
3883 context->unknown_resource->is_reverse_proxy)) &&
3884 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3885 pdu->type == COAP_MESSAGE_CON &&
3886 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
3887 /* Make the proxy response separate and fix response later */
3888 send_early_empty_ack = 1;
3889 }
3890 if (send_early_empty_ack) {
3891 coap_send_ack_lkd(session, pdu);
3892 if (pdu->mid == session->last_con_mid) {
3893 /* request has already been processed - do not process it again */
3894 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3895 pdu->mid);
3896 goto drop_it_no_debug;
3897 }
3898 session->last_con_mid = pdu->mid;
3899 }
3900#if COAP_WITH_OBSERVE_PERSIST
3901 /* If we are maintaining Observe persist */
3902 if (resource == context->unknown_resource) {
3903 context->unknown_pdu = pdu;
3904 context->unknown_session = session;
3905 } else
3906 context->unknown_pdu = NULL;
3907#endif /* COAP_WITH_OBSERVE_PERSIST */
3908
3909 /*
3910 * Call the request handler with everything set up
3911 */
3912 if (resource == &resource_uri_wellknown) {
3913 /* Leave context locked */
3914 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3915 (int)resource->uri_path->length, (int)resource->uri_path->length,
3916 resource->uri_path->s);
3917 h(resource, session, pdu, query, response);
3918 } else {
3919 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3920 (int)resource->uri_path->length, (int)resource->uri_path->length,
3921 resource->uri_path->s);
3922 coap_lock_callback_release(h(resource, session, pdu, query, response),
3923 /* context is being freed off */
3924 coap_delete_string(query); goto finish);
3925 }
3926
3927 /* Check validity of response code */
3928 if (!coap_check_code_class(session, response)) {
3929 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
3930 COAP_RESPONSE_CLASS(response->code),
3931 response->code & 0x1f);
3932 goto drop_it_no_debug;
3933 }
3934
3935 /* Check if lg_xmit generated and update PDU code if so */
3936 coap_check_code_lg_xmit(session, pdu, response, resource, query);
3937
3938 if (free_lg_srcv) {
3939 /* Check to see if the server is doing a 4.01 + Echo response */
3940 if (response->code == COAP_RESPONSE_CODE(401) &&
3941 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3942 /* Need to keep lg_srcv around for client's response */
3943 } else {
3944 LL_DELETE(session->lg_srcv, free_lg_srcv);
3945 coap_block_delete_lg_srcv(session, free_lg_srcv);
3946 }
3947 }
3948 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
3949 /* Just in case, as there are more to go */
3950 response->code = COAP_RESPONSE_CODE(231);
3951 }
3952
3953skip_handler:
3954 if (send_early_empty_ack &&
3955 response->type == COAP_MESSAGE_ACK) {
3956 /* Response is now separate - convert to CON as needed */
3957 response->type = COAP_MESSAGE_CON;
3958 /* Check for empty ACK - need to drop as already sent */
3959 if (response->code == 0) {
3960 goto drop_it_no_debug;
3961 }
3962 }
3963 respond = no_response(pdu, response, session, resource);
3964 if (respond != RESPONSE_DROP) {
3965#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
3966 coap_mid_t mid = pdu->mid;
3967#endif
3968 if (COAP_RESPONSE_CLASS(response->code) != 2) {
3969 if (observe) {
3971 }
3972 }
3973 if (COAP_RESPONSE_CLASS(response->code) > 2) {
3974 if (observe)
3975 coap_delete_observer(resource, session, &pdu->actual_token);
3976 if (response->code != COAP_RESPONSE_CODE(413))
3978 }
3979
3980 /* If original request contained a token, and the registered
3981 * application handler made no changes to the response, then
3982 * this is an empty ACK with a token, which is a malformed
3983 * PDU */
3984 if ((response->type == COAP_MESSAGE_ACK)
3985 && (response->code == 0)) {
3986 /* Remove token from otherwise-empty acknowledgment PDU */
3987 response->actual_token.length = 0;
3988 response->e_token_length = 0;
3989 response->used_size = 0;
3990 response->data = NULL;
3991 }
3992
3993 if (!coap_is_mcast(&session->addr_info.local) ||
3994 (context->mcast_per_resource &&
3995 resource &&
3997 /* No delays to response */
3998#if COAP_Q_BLOCK_SUPPORT
3999 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4000 !lg_xmit_ctrl && response->code == COAP_RESPONSE_CODE(205) &&
4001 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4002 block.m) {
4003 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4004 response,
4005 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4006 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4007 response = NULL;
4008 if (query)
4009 coap_delete_string(query);
4010 goto finish;
4011 }
4012#endif /* COAP_Q_BLOCK_SUPPORT */
4013 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4014 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4015 if (query)
4016 coap_delete_string(query);
4017 goto finish;
4018 }
4019 } else {
4020 /* Need to delay mcast response */
4021 coap_queue_t *node = coap_new_node();
4022 uint8_t r;
4023 coap_tick_t delay;
4024
4025 if (!node) {
4026 coap_log_debug("mcast delay: insufficient memory\n");
4027 goto drop_it_no_debug;
4028 }
4029 if (!coap_pdu_encode_header(response, session->proto)) {
4031 goto drop_it_no_debug;
4032 }
4033
4034 node->id = response->mid;
4035 node->pdu = response;
4036 node->is_mcast = 1;
4037 coap_prng_lkd(&r, sizeof(r));
4038 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4039 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4040 coap_session_str(session),
4041 response->mid,
4042 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4043 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4044 1000 / COAP_TICKS_PER_SECOND));
4045 node->timeout = (unsigned int)delay;
4046 /* Use this to delay transmission */
4047 coap_wait_ack(session->context, session, node);
4048 }
4049 } else {
4050 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4051 coap_session_str(session),
4052 response->mid);
4053 coap_show_pdu(COAP_LOG_DEBUG, response);
4054drop_it_no_debug:
4055 coap_delete_pdu_lkd(response);
4056 }
4057 if (query)
4058 coap_delete_string(query);
4059#if COAP_Q_BLOCK_SUPPORT
4060 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4061 if (COAP_PROTO_RELIABLE(session->proto)) {
4062 if (block.m) {
4063 /* All of the sequence not in yet */
4064 goto finish;
4065 }
4066 } else if (pdu->type == COAP_MESSAGE_NON) {
4067 /* More to go and not at a payload break */
4068 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4069 goto finish;
4070 }
4071 }
4072 }
4073#endif /* COAP_Q_BLOCK_SUPPORT */
4074
4075finish:
4076 coap_delete_string(uri_path);
4077 return;
4078
4079fail_response:
4080 coap_delete_pdu_lkd(response);
4081 response =
4083 &opt_filter);
4084 if (response)
4085 goto skip_handler;
4086 coap_delete_string(uri_path);
4087}
4088#endif /* COAP_SERVER_SUPPORT */
4089
4090#if COAP_CLIENT_SUPPORT
4091/* Call application-specific response handler when available. */
4092void
4094 coap_pdu_t *sent, coap_pdu_t *rcvd,
4095 void *body_data) {
4096 coap_context_t *context = session->context;
4097 coap_response_t ret;
4098
4099#if COAP_PROXY_SUPPORT
4100 if (context->proxy_response_handler) {
4101 coap_proxy_list_t *proxy_entry;
4102 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4103 rcvd,
4104 &proxy_entry);
4105
4106 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4107 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4108 proxy_entry);
4109 return;
4110 }
4111 }
4112#endif /* COAP_PROXY_SUPPORT */
4113 if (session->doing_send_recv && session->req_token &&
4114 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4115 /* processing coap_send_recv() call */
4116 session->resp_pdu = rcvd;
4118 /* Will get freed off when PDU is freed off */
4119 rcvd->data_free = body_data;
4120 coap_send_ack_lkd(session, rcvd);
4122 return;
4123 } else if (context->response_handler) {
4125 context->response_handler(session,
4126 sent,
4127 rcvd,
4128 rcvd->mid),
4129 /* context is being freed off */
4130 return);
4131 } else {
4132 ret = COAP_RESPONSE_OK;
4133 }
4134 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4135 coap_send_rst_lkd(session, rcvd);
4137 } else {
4138 coap_send_ack_lkd(session, rcvd);
4140 }
4141 coap_free_type(COAP_STRING, body_data);
4142}
4143
4144static void
4145handle_response(coap_context_t *context, coap_session_t *session,
4146 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4147
4148 /* Set in case there is a later call to coap_update_token() */
4149 rcvd->session = session;
4150
4151 /* Check for message duplication */
4152 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4153 if (rcvd->type == COAP_MESSAGE_CON) {
4154 if (rcvd->mid == session->last_con_mid) {
4155 /* Duplicate response: send ACK/RST, but don't process */
4156 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4157 coap_send_ack_lkd(session, rcvd);
4158 else
4159 coap_send_rst_lkd(session, rcvd);
4160 return;
4161 }
4162 session->last_con_mid = rcvd->mid;
4163 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4164 if (rcvd->mid == session->last_ack_mid) {
4165 /* Duplicate response */
4166 return;
4167 }
4168 session->last_ack_mid = rcvd->mid;
4169 }
4170 }
4171 /* Check to see if checking out extended token support */
4172 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4173 session->last_token) {
4174 coap_lg_crcv_t *lg_crcv;
4175
4176 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4177 rcvd->actual_token.length != session->max_token_size ||
4178 rcvd->code == COAP_RESPONSE_CODE(400) ||
4179 rcvd->code == COAP_RESPONSE_CODE(503)) {
4180 coap_log_debug("Extended Token requested size support not available\n");
4182 } else {
4183 coap_log_debug("Extended Token support available\n");
4184 }
4186 /* Need to remove lg_crcv set up for this test */
4187 lg_crcv = coap_find_lg_crcv(session, rcvd);
4188 if (lg_crcv) {
4189 LL_DELETE(session->lg_crcv, lg_crcv);
4190 coap_block_delete_lg_crcv(session, lg_crcv);
4191 }
4192 coap_send_ack_lkd(session, rcvd);
4193 session->doing_first = 0;
4194 return;
4195 }
4196#if COAP_Q_BLOCK_SUPPORT
4197 /* Check to see if checking out Q-Block support */
4198 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4199 session->remote_test_mid == rcvd->mid) {
4200 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4201 coap_log_debug("Q-Block support not available\n");
4202 set_block_mode_drop_q(session->block_mode);
4203 } else {
4204 coap_block_b_t qblock;
4205
4206 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4207 coap_log_debug("Q-Block support available\n");
4208 set_block_mode_has_q(session->block_mode);
4209 } else {
4210 coap_log_debug("Q-Block support not available\n");
4211 set_block_mode_drop_q(session->block_mode);
4212 }
4213 }
4214 session->doing_first = 0;
4215 return;
4216 }
4217#endif /* COAP_Q_BLOCK_SUPPORT */
4218
4219 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4220 /* See if need to send next block to server */
4221 if (coap_handle_response_send_block(session, sent, rcvd)) {
4222 /* Next block transmitted, no need to inform app */
4223 coap_send_ack_lkd(session, rcvd);
4224 return;
4225 }
4226
4227 /* Need to see if needing to request next block */
4228 if (coap_handle_response_get_block(context, session, sent, rcvd,
4229 COAP_RECURSE_OK)) {
4230 /* Next block transmitted, ack sent no need to inform app */
4231 return;
4232 }
4233 }
4234 if (session->doing_first)
4235 session->doing_first = 0;
4236
4237 /* Call application-specific response handler when available. */
4238 coap_call_response_handler(session, sent, rcvd, NULL);
4239}
4240#endif /* COAP_CLIENT_SUPPORT */
4241
4242#if !COAP_DISABLE_TCP
4243static void
4245 coap_pdu_t *pdu) {
4246 coap_opt_iterator_t opt_iter;
4247 coap_opt_t *option;
4248 int set_mtu = 0;
4249
4250 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4251
4252 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4253 if (session->csm_not_seen) {
4254 coap_tick_t now;
4255
4256 coap_ticks(&now);
4257 /* CSM timeout before CSM seen */
4258 coap_log_warn("***%s: CSM received after CSM timeout\n",
4259 coap_session_str(session));
4260 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4261 coap_session_str(session),
4262 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4263 }
4264 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4266 }
4267 while ((option = coap_option_next(&opt_iter))) {
4269 unsigned max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4270
4271 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4272 max_recv = COAP_DEFAULT_MAX_PDU_RX_SIZE;
4273 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4274 coap_session_str(session), max_recv);
4275 }
4276 coap_session_set_mtu(session, max_recv);
4277 set_mtu = 1;
4278 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4279 session->csm_block_supported = 1;
4280 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4281 session->max_token_size =
4283 coap_opt_length(option));
4286 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4289 }
4290 }
4291 if (set_mtu) {
4292 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4293 session->csm_bert_rem_support = 1;
4294 else
4295 session->csm_bert_rem_support = 0;
4296 }
4297 if (session->state == COAP_SESSION_STATE_CSM)
4298 coap_session_connected(session);
4299 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4301 if (context->ping_handler) {
4302 coap_lock_callback(context->ping_handler(session, pdu, pdu->mid));
4303 }
4304 if (pong) {
4306 coap_send_internal(session, pong, NULL);
4307 }
4308 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4309 session->last_pong = session->last_rx_tx;
4310 if (context->pong_handler) {
4311 coap_lock_callback(context->pong_handler(session, pdu, pdu->mid));
4312 }
4313 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4314 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4316 }
4317}
4318#endif /* !COAP_DISABLE_TCP */
4319
4320static int
4322 if (COAP_PDU_IS_REQUEST(pdu) &&
4323 pdu->actual_token.length >
4324 (session->type == COAP_SESSION_TYPE_CLIENT ?
4325 session->max_token_size : session->context->max_token_size)) {
4326 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4327 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4328 coap_opt_filter_t opt_filter;
4329 coap_pdu_t *response;
4330
4331 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4332 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4333 &opt_filter);
4334 if (!response) {
4335 coap_log_warn("coap_dispatch: cannot create error response\n");
4336 } else {
4337 /*
4338 * Note - have to leave in oversize token as per
4339 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4340 */
4341 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4342 coap_log_warn("coap_dispatch: error sending response\n");
4343 }
4344 } else {
4345 /* Indicate no extended token support */
4346 coap_send_rst_lkd(session, pdu);
4347 }
4348 return 0;
4349 }
4350 return 1;
4351}
4352
4353void
4355 coap_pdu_t *pdu) {
4356 coap_queue_t *sent = NULL;
4357 coap_pdu_t *response;
4358 coap_pdu_t *orig_pdu = NULL;
4359 coap_opt_filter_t opt_filter;
4360 int is_ping_rst;
4361 int packet_is_bad = 0;
4362#if COAP_OSCORE_SUPPORT
4363 coap_opt_iterator_t opt_iter;
4364 coap_pdu_t *dec_pdu = NULL;
4365#endif /* COAP_OSCORE_SUPPORT */
4366 int is_ext_token_rst;
4367 int oscore_invalid = 0;
4368
4369 pdu->session = session;
4371
4372 /* Check validity of received code */
4373 if (!coap_check_code_class(session, pdu)) {
4374 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4376 pdu->code & 0x1f);
4377 packet_is_bad = 1;
4378 if (pdu->type == COAP_MESSAGE_CON) {
4380 }
4381 /* find message id in sendqueue to stop retransmission */
4382 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4383 goto cleanup;
4384 }
4385
4386 coap_option_filter_clear(&opt_filter);
4387
4388#if COAP_SERVER_SUPPORT
4389 /* See if this a repeat request */
4390 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4392 coap_digest_t digest;
4393
4394 coap_pdu_cksum(pdu, &digest);
4395 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4396#if COAP_OSCORE_SUPPORT
4397 uint8_t oscore_encryption = session->oscore_encryption;
4398
4399 session->oscore_encryption = 0;
4400#endif /* COAP_OSCORE_SUPPORT */
4401 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4402 cached_pdu must not be removed */
4404 coap_log_debug("Retransmit response to duplicate request\n");
4405 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4406#if COAP_OSCORE_SUPPORT
4407 session->oscore_encryption = oscore_encryption;
4408#endif /* COAP_OSCORE_SUPPORT */
4409 return;
4410 }
4411#if COAP_OSCORE_SUPPORT
4412 session->oscore_encryption = oscore_encryption;
4413#endif /* COAP_OSCORE_SUPPORT */
4414 }
4415 }
4416#endif /* COAP_SERVER_SUPPORT */
4417 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4418 if (!check_token_size(session, pdu)) {
4419 goto cleanup;
4420 }
4421 }
4422#if COAP_OSCORE_SUPPORT
4423 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4424 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4425 if (pdu->type == COAP_MESSAGE_NON) {
4426 coap_send_rst_lkd(session, pdu);
4427 goto cleanup;
4428 } else if (pdu->type == COAP_MESSAGE_CON) {
4429 if (COAP_PDU_IS_REQUEST(pdu)) {
4430 response =
4431 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4432
4433 if (!response) {
4434 coap_log_warn("coap_dispatch: cannot create error response\n");
4435 } else {
4436 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4437 coap_log_warn("coap_dispatch: error sending response\n");
4438 }
4439 } else {
4440 coap_send_rst_lkd(session, pdu);
4441 }
4442 }
4443 goto cleanup;
4444 }
4445
4446 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4447 int decrypt = 1;
4448#if COAP_SERVER_SUPPORT
4449 coap_opt_t *opt;
4450 coap_resource_t *resource;
4451 coap_uri_t uri;
4452#endif /* COAP_SERVER_SUPPORT */
4453
4454 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4455 decrypt = 0;
4456
4457#if COAP_SERVER_SUPPORT
4458 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4459 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4460 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4461 != NULL) {
4462 /* Need to check whether this is a direct or proxy session */
4463 memset(&uri, 0, sizeof(uri));
4464 uri.host.length = coap_opt_length(opt);
4465 uri.host.s = coap_opt_value(opt);
4466 resource = context->proxy_uri_resource;
4467 if (uri.host.length && resource && resource->proxy_name_count &&
4468 resource->proxy_name_list) {
4469 size_t i;
4470 for (i = 0; i < resource->proxy_name_count; i++) {
4471 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4472 break;
4473 }
4474 }
4475 if (i == resource->proxy_name_count) {
4476 /* This server is not hosting the proxy connection endpoint */
4477 decrypt = 0;
4478 }
4479 }
4480 }
4481#endif /* COAP_SERVER_SUPPORT */
4482 if (decrypt) {
4483 /* find message id in sendqueue to stop retransmission and get sent */
4484 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4485 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4486 orig_pdu = pdu;
4487 coap_pdu_reference_lkd(orig_pdu);
4488 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4489 if (session->recipient_ctx == NULL ||
4490 session->recipient_ctx->initial_state == 0) {
4491 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4492 }
4494 coap_delete_pdu_lkd(orig_pdu);
4495 return;
4496 } else {
4497 session->oscore_encryption = 1;
4498 pdu = dec_pdu;
4499 }
4500 coap_log_debug("Decrypted PDU\n");
4502 }
4503 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4504 session->oscore_encryption &&
4505 pdu->type != COAP_MESSAGE_RST) {
4506 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4507 /* Violates RFC 8613 2 */
4508 coap_log_err("received an invalid response to the OSCORE request\n");
4509 oscore_invalid = 1;
4510 }
4511 }
4512#endif /* COAP_OSCORE_SUPPORT */
4513
4514 switch (pdu->type) {
4515 case COAP_MESSAGE_ACK:
4516 /* find message id in sendqueue to stop retransmission */
4517 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4518
4519 if (sent && session->con_active) {
4520 session->con_active--;
4521 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4522 /* Flush out any entries on session->delayqueue */
4523 coap_session_connected(session);
4524 }
4525 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4526 packet_is_bad = 1;
4527 goto cleanup;
4528 }
4529
4530#if COAP_SERVER_SUPPORT
4531 /* if sent code was >= 64 the message might have been a
4532 * notification. Then, we must flag the observer to be alive
4533 * by setting obs->fail_cnt = 0. */
4534 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4535 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4536 }
4537#endif /* COAP_SERVER_SUPPORT */
4538
4539 if (pdu->code == 0) {
4540#if COAP_Q_BLOCK_SUPPORT
4541 if (sent) {
4542 coap_block_b_t block;
4543
4544 if (sent->pdu->type == COAP_MESSAGE_CON &&
4545 COAP_PROTO_NOT_RELIABLE(session->proto) &&
4546 coap_get_block_b(session, sent->pdu,
4547 COAP_PDU_IS_REQUEST(sent->pdu) ?
4549 &block)) {
4550 if (block.m) {
4551#if COAP_CLIENT_SUPPORT
4552 if (COAP_PDU_IS_REQUEST(sent->pdu))
4553 coap_send_q_block1(session, block, sent->pdu,
4554 COAP_SEND_SKIP_PDU);
4555#endif /* COAP_CLIENT_SUPPORT */
4556 if (COAP_PDU_IS_RESPONSE(sent->pdu))
4557 coap_send_q_blocks(session, sent->pdu->lg_xmit, block,
4558 sent->pdu, COAP_SEND_SKIP_PDU);
4559 }
4560 }
4561 }
4562#endif /* COAP_Q_BLOCK_SUPPORT */
4563#if COAP_CLIENT_SUPPORT
4564 /*
4565 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4566 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4567 * response if the response was piggy-backed. Here, a separate response
4568 * detected and so the lg_crcv needs to be set up before the sent PDU
4569 * information is lost.
4570 *
4571 * lg_crcv was not set up if not a CoAP request.
4572 *
4573 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4574 * options.
4575 */
4576 if (sent &&
4577 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4578 COAP_PDU_IS_REQUEST(sent->pdu)) {
4579 /*
4580 * lg_crcv was not set up in coap_send(). It could have been set up
4581 * the first separate response.
4582 * See if there already is a lg_crcv set up.
4583 */
4584 coap_lg_crcv_t *lg_crcv;
4585 uint64_t token_match =
4587 sent->pdu->actual_token.length));
4588
4589 LL_FOREACH(session->lg_crcv, lg_crcv) {
4590 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4591 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4592 break;
4593 }
4594 }
4595 if (!lg_crcv) {
4596 /*
4597 * Need to set up a lg_crcv as it was not set up in coap_send()
4598 * to save time, but server has not sent back a piggy-back response.
4599 */
4600 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4601 if (lg_crcv) {
4602 LL_PREPEND(session->lg_crcv, lg_crcv);
4603 }
4604 }
4605 }
4606#endif /* COAP_CLIENT_SUPPORT */
4607 /* an empty ACK needs no further handling */
4608 goto cleanup;
4609 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4610 /* This is not legitimate - Request using ACK - ignore */
4611 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4613 pdu->code & 0x1f);
4614 packet_is_bad = 1;
4615 goto cleanup;
4616 }
4617
4618 break;
4619
4620 case COAP_MESSAGE_RST:
4621 /* We have sent something the receiver disliked, so we remove
4622 * not only the message id but also the subscriptions we might
4623 * have. */
4624 is_ping_rst = 0;
4625 if (pdu->mid == session->last_ping_mid &&
4626 context->ping_timeout && session->last_ping > 0)
4627 is_ping_rst = 1;
4628
4629#if COAP_Q_BLOCK_SUPPORT
4630 /* Check to see if checking out Q-Block support */
4631 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4632 session->remote_test_mid == pdu->mid) {
4633 coap_log_debug("Q-Block support not available\n");
4634 set_block_mode_drop_q(session->block_mode);
4635 }
4636#endif /* COAP_Q_BLOCK_SUPPORT */
4637
4638 /* Check to see if checking out extended token support */
4639 is_ext_token_rst = 0;
4640 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4641 session->remote_test_mid == pdu->mid) {
4642 coap_log_debug("Extended Token support not available\n");
4645 session->doing_first = 0;
4646 is_ext_token_rst = 1;
4647 }
4648
4649 if (!is_ping_rst && !is_ext_token_rst)
4650 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4651
4652 if (session->con_active) {
4653 session->con_active--;
4654 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4655 /* Flush out any entries on session->delayqueue */
4656 coap_session_connected(session);
4657 }
4658
4659 /* find message id in sendqueue to stop retransmission */
4660 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4661
4662 if (sent) {
4663 if (!is_ping_rst)
4664 coap_cancel(context, sent);
4665
4666 if (!is_ping_rst && !is_ext_token_rst) {
4667 if (sent->pdu->type==COAP_MESSAGE_CON) {
4668 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4669 }
4670 } else if (is_ping_rst) {
4671 if (context->pong_handler) {
4672 coap_lock_callback(context->pong_handler(session, pdu, pdu->mid));
4673 }
4674 session->last_pong = session->last_rx_tx;
4676 }
4677 } else {
4678#if COAP_SERVER_SUPPORT
4679 /* Need to check is there is a subscription active and delete it */
4680 RESOURCES_ITER(context->resources, r) {
4681 coap_subscription_t *obs, *tmp;
4682 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4683 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4684 /* Need to do this now as session may get de-referenced */
4686 coap_delete_observer(r, session, &obs->pdu->actual_token);
4687 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4688 coap_session_release_lkd(session);
4689 goto cleanup;
4690 }
4691 }
4692 }
4693#endif /* COAP_SERVER_SUPPORT */
4694 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4695 }
4696#if COAP_PROXY_SUPPORT
4697 if (!is_ping_rst) {
4698 /* Need to check is there is a proxy subscription active and delete it */
4699 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
4700 }
4701#endif /* COAP_PROXY_SUPPORT */
4702 goto cleanup;
4703
4704 case COAP_MESSAGE_NON:
4705 /* check for oscore issue or unknown critical options */
4706 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4707 packet_is_bad = 1;
4708 coap_send_rst_lkd(session, pdu);
4709 goto cleanup;
4710 }
4711 break;
4712
4713 case COAP_MESSAGE_CON:
4714 /* In a lossy context, the ACK of a separate response may have
4715 * been lost, so we need to stop retransmitting requests with the
4716 * same token. Matching on token potentially containing ext length bytes.
4717 */
4718 /* find message token in sendqueue to stop retransmission */
4719 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4720
4721 /* check for oscore issue or unknown critical options in non-signaling messages */
4722 if (oscore_invalid ||
4723 (!COAP_PDU_IS_SIGNALING(pdu) && coap_option_check_critical(session, pdu, &opt_filter) == 0)) {
4724 packet_is_bad = 1;
4725 if (COAP_PDU_IS_REQUEST(pdu)) {
4726 response =
4727 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4728
4729 if (!response) {
4730 coap_log_warn("coap_dispatch: cannot create error response\n");
4731 } else {
4732 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4733 coap_log_warn("coap_dispatch: error sending response\n");
4734 }
4735 } else {
4736 coap_send_rst_lkd(session, pdu);
4737 }
4738 goto cleanup;
4739 }
4740 break;
4741 default:
4742 break;
4743 }
4744
4745 /* Pass message to upper layer if a specific handler was
4746 * registered for a request that should be handled locally. */
4747#if !COAP_DISABLE_TCP
4748 if (COAP_PDU_IS_SIGNALING(pdu))
4749 handle_signaling(context, session, pdu);
4750 else
4751#endif /* !COAP_DISABLE_TCP */
4752#if COAP_SERVER_SUPPORT
4753 if (COAP_PDU_IS_REQUEST(pdu))
4754 handle_request(context, session, pdu, orig_pdu);
4755 else
4756#endif /* COAP_SERVER_SUPPORT */
4757#if COAP_CLIENT_SUPPORT
4758 if (COAP_PDU_IS_RESPONSE(pdu))
4759 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4760 else
4761#endif /* COAP_CLIENT_SUPPORT */
4762 {
4763 if (COAP_PDU_IS_EMPTY(pdu)) {
4764 if (context->ping_handler) {
4765 coap_lock_callback(context->ping_handler(session, pdu, pdu->mid));
4766 }
4767 } else {
4768 packet_is_bad = 1;
4769 }
4770 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4772 pdu->code & 0x1f);
4773
4774 if (!coap_is_mcast(&session->addr_info.local)) {
4775 if (COAP_PDU_IS_EMPTY(pdu)) {
4776 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4777 coap_tick_t now;
4778 coap_ticks(&now);
4779 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4781 session->last_tx_rst = now;
4782 }
4783 }
4784 } else {
4785 if (pdu->type == COAP_MESSAGE_CON)
4787 }
4788 }
4789 }
4790
4791cleanup:
4792 if (packet_is_bad) {
4793 if (sent) {
4794 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
4795 } else {
4797 }
4798 }
4799 coap_delete_pdu_lkd(orig_pdu);
4801#if COAP_OSCORE_SUPPORT
4802 coap_delete_pdu_lkd(dec_pdu);
4803#endif /* COAP_OSCORE_SUPPORT */
4804}
4805
4806#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4807static const char *
4809 switch (event) {
4811 return "COAP_EVENT_DTLS_CLOSED";
4813 return "COAP_EVENT_DTLS_CONNECTED";
4815 return "COAP_EVENT_DTLS_RENEGOTIATE";
4817 return "COAP_EVENT_DTLS_ERROR";
4819 return "COAP_EVENT_TCP_CONNECTED";
4821 return "COAP_EVENT_TCP_CLOSED";
4823 return "COAP_EVENT_TCP_FAILED";
4825 return "COAP_EVENT_SESSION_CONNECTED";
4827 return "COAP_EVENT_SESSION_CLOSED";
4829 return "COAP_EVENT_SESSION_FAILED";
4831 return "COAP_EVENT_PARTIAL_BLOCK";
4833 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4835 return "COAP_EVENT_SERVER_SESSION_NEW";
4837 return "COAP_EVENT_SERVER_SESSION_DEL";
4839 return "COAP_EVENT_BAD_PACKET";
4841 return "COAP_EVENT_MSG_RETRANSMITTED";
4843 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4845 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4847 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4849 return "COAP_EVENT_OSCORE_NO_SECURITY";
4851 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4853 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4855 return "COAP_EVENT_WS_PACKET_SIZE";
4857 return "COAP_EVENT_WS_CONNECTED";
4859 return "COAP_EVENT_WS_CLOSED";
4861 return "COAP_EVENT_KEEPALIVE_FAILURE";
4862 default:
4863 return "???";
4864 }
4865}
4866#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4867
4868COAP_API int
4870 coap_session_t *session) {
4871 int ret;
4872
4873 coap_lock_lock(return 0);
4874 ret = coap_handle_event_lkd(context, event, session);
4876 return ret;
4877}
4878
4879int
4881 coap_session_t *session) {
4882 int ret = 0;
4883
4884 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
4885
4886 if (context->handle_event) {
4887 coap_lock_callback_ret(ret, context->handle_event(session, event));
4888#if COAP_PROXY_SUPPORT
4889 if (event == COAP_EVENT_SERVER_SESSION_DEL)
4890 coap_proxy_remove_association(session, 0);
4891#endif /* COAP_PROXY_SUPPORT */
4892#if COAP_CLIENT_SUPPORT
4893 switch (event) {
4906 /* Those that are deemed fatal to end sending a request */
4907 session->doing_send_recv = 0;
4908 break;
4923 default:
4924 break;
4925 }
4926#endif /* COAP_CLIENT_SUPPORT */
4927 }
4928 return ret;
4929}
4930
4931COAP_API int
4933 int ret;
4934
4935 coap_lock_lock(return 0);
4936 ret = coap_can_exit_lkd(context);
4938 return ret;
4939}
4940
4941int
4943 coap_session_t *s, *rtmp;
4944 if (!context)
4945 return 1;
4947 if (context->sendqueue)
4948 return 0;
4949#if COAP_SERVER_SUPPORT
4950 coap_endpoint_t *ep;
4951
4952 LL_FOREACH(context->endpoint, ep) {
4953 SESSIONS_ITER(ep->sessions, s, rtmp) {
4954 if (s->delayqueue)
4955 return 0;
4956 if (s->lg_xmit)
4957 return 0;
4958 }
4959 }
4960#endif /* COAP_SERVER_SUPPORT */
4961#if COAP_CLIENT_SUPPORT
4962 SESSIONS_ITER(context->sessions, s, rtmp) {
4963 if (s->delayqueue)
4964 return 0;
4965 if (s->lg_xmit)
4966 return 0;
4967 }
4968#endif /* COAP_CLIENT_SUPPORT */
4969 return 1;
4970}
4971#if COAP_SERVER_SUPPORT
4972#if COAP_ASYNC_SUPPORT
4973/*
4974 * Return 1 if there is a future expire time, else 0.
4975 * Update tim_rem with remaining value if return is 1.
4976 */
4977int
4978coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
4980 coap_async_t *async, *tmp;
4981 int ret = 0;
4982
4983 if (context->async_state_traversing)
4984 return 0;
4985 context->async_state_traversing = 1;
4986 LL_FOREACH_SAFE(context->async_state, async, tmp) {
4987 if (async->delay != 0) {
4988 if (async->delay <= now) {
4989 /* Send off the request to the application */
4990 coap_log_debug("Async PDU presented to app.\n");
4991 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
4992 handle_request(context, async->session, async->pdu, NULL);
4993
4994 /* Remove this async entry as it has now fired */
4995 coap_free_async_lkd(async->session, async);
4996 } else {
4997 next_due = async->delay - now;
4998 ret = 1;
4999 }
5000 }
5001 }
5002 if (tim_rem)
5003 *tim_rem = next_due;
5004 context->async_state_traversing = 0;
5005 return ret;
5006}
5007#endif /* COAP_ASYNC_SUPPORT */
5008#endif /* COAP_SERVER_SUPPORT */
5009
5011
5012#if COAP_THREAD_SAFE
5013/*
5014 * Global lock for multi-thread support
5015 */
5016coap_lock_t global_lock;
5017/*
5018 * low level protection mutex
5019 */
5020coap_mutex_t m_show_pdu;
5021coap_mutex_t m_log_impl;
5022coap_mutex_t m_io_threads;
5023#endif /* COAP_THREAD_SAFE */
5024
5025void
5027 coap_tick_t now;
5028#ifndef WITH_CONTIKI
5029 uint64_t us;
5030#endif /* !WITH_CONTIKI */
5031
5032 if (coap_started)
5033 return;
5034 coap_started = 1;
5035
5036#if COAP_THREAD_SAFE
5038 coap_mutex_init(&m_show_pdu);
5039 coap_mutex_init(&m_log_impl);
5040 coap_mutex_init(&m_io_threads);
5041#endif /* COAP_THREAD_SAFE */
5042
5043#if defined(HAVE_WINSOCK2_H)
5044 WORD wVersionRequested = MAKEWORD(2, 2);
5045 WSADATA wsaData;
5046 WSAStartup(wVersionRequested, &wsaData);
5047#endif
5049 coap_ticks(&now);
5050#ifndef WITH_CONTIKI
5051 us = coap_ticks_to_rt_us(now);
5052 /* Be accurate to the nearest (approx) us */
5053 coap_prng_init_lkd((unsigned int)us);
5054#else /* WITH_CONTIKI */
5055 coap_start_io_process();
5056#endif /* WITH_CONTIKI */
5059#ifdef WITH_LWIP
5060 coap_io_lwip_init();
5061#endif /* WITH_LWIP */
5062#if COAP_SERVER_SUPPORT
5063 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5064 (const uint8_t *)".well-known/core"
5065 };
5066 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5067 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5068 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5069 resource_uri_wellknown.uri_path = &well_known;
5070#endif /* COAP_SERVER_SUPPORT */
5072}
5073
5074void
5076 if (!coap_started)
5077 return;
5078 coap_started = 0;
5079#if defined(HAVE_WINSOCK2_H)
5080 WSACleanup();
5081#elif defined(WITH_CONTIKI)
5082 coap_stop_io_process();
5083#endif
5084#ifdef WITH_LWIP
5085 coap_io_lwip_cleanup();
5086#endif /* WITH_LWIP */
5088
5089#if COAP_THREAD_SAFE
5090 coap_mutex_destroy(&m_show_pdu);
5091 coap_mutex_destroy(&m_log_impl);
5092 coap_mutex_destroy(&m_io_threads);
5093#endif /* COAP_THREAD_SAFE */
5094
5096}
5097
5098void
5100 coap_response_handler_t handler) {
5101#if COAP_CLIENT_SUPPORT
5102 context->response_handler = handler;
5103#else /* ! COAP_CLIENT_SUPPORT */
5104 (void)context;
5105 (void)handler;
5106#endif /* ! COAP_CLIENT_SUPPORT */
5107}
5108
5109void
5112#if COAP_PROXY_SUPPORT
5113 context->proxy_response_handler = handler;
5114#else /* ! COAP_PROXY_SUPPORT */
5115 (void)context;
5116 (void)handler;
5117#endif /* ! COAP_PROXY_SUPPORT */
5118}
5119
5120void
5122 coap_nack_handler_t handler) {
5123 context->nack_handler = handler;
5124}
5125
5126void
5128 coap_ping_handler_t handler) {
5129 context->ping_handler = handler;
5130}
5131
5132void
5134 coap_pong_handler_t handler) {
5135 context->pong_handler = handler;
5136}
5137
5138COAP_API void
5140 coap_lock_lock(return);
5141 coap_register_option_lkd(ctx, type);
5143}
5144
5145void
5148}
5149
5150#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5151#if COAP_SERVER_SUPPORT
5152COAP_API int
5153coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5154 const char *ifname) {
5155 int ret;
5156
5157 coap_lock_lock(return -1);
5158 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
5160 return ret;
5161}
5162
5163int
5164coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
5165 const char *ifname) {
5166#if COAP_IPV4_SUPPORT
5167 struct ip_mreq mreq4;
5168#endif /* COAP_IPV4_SUPPORT */
5169#if COAP_IPV6_SUPPORT
5170 struct ipv6_mreq mreq6;
5171#endif /* COAP_IPV6_SUPPORT */
5172 struct addrinfo *resmulti = NULL, hints, *ainfo;
5173 int result = -1;
5174 coap_endpoint_t *endpoint;
5175 int mgroup_setup = 0;
5176
5177 /* Need to have at least one endpoint! */
5178 assert(ctx->endpoint);
5179 if (!ctx->endpoint)
5180 return -1;
5181
5182 /* Default is let the kernel choose */
5183#if COAP_IPV6_SUPPORT
5184 mreq6.ipv6mr_interface = 0;
5185#endif /* COAP_IPV6_SUPPORT */
5186#if COAP_IPV4_SUPPORT
5187 mreq4.imr_interface.s_addr = INADDR_ANY;
5188#endif /* COAP_IPV4_SUPPORT */
5189
5190 memset(&hints, 0, sizeof(hints));
5191 hints.ai_socktype = SOCK_DGRAM;
5192
5193 /* resolve the multicast group address */
5194 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5195
5196 if (result != 0) {
5197 coap_log_err("coap_join_mcast_group_intf: %s: "
5198 "Cannot resolve multicast address: %s\n",
5199 group_name, gai_strerror(result));
5200 goto finish;
5201 }
5202
5203 /* Need to do a windows equivalent at some point */
5204#ifndef _WIN32
5205 if (ifname) {
5206 /* interface specified - check if we have correct IPv4/IPv6 information */
5207 int done_ip4 = 0;
5208 int done_ip6 = 0;
5209#if defined(ESPIDF_VERSION)
5210 struct netif *netif;
5211#else /* !ESPIDF_VERSION */
5212#if COAP_IPV4_SUPPORT
5213 int ip4fd;
5214#endif /* COAP_IPV4_SUPPORT */
5215 struct ifreq ifr;
5216#endif /* !ESPIDF_VERSION */
5217
5218 /* See which mcast address family types are being asked for */
5219 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5220 ainfo = ainfo->ai_next) {
5221 switch (ainfo->ai_family) {
5222#if COAP_IPV6_SUPPORT
5223 case AF_INET6:
5224 if (done_ip6)
5225 break;
5226 done_ip6 = 1;
5227#if defined(ESPIDF_VERSION)
5228 netif = netif_find(ifname);
5229 if (netif)
5230 mreq6.ipv6mr_interface = netif_get_index(netif);
5231 else
5232 coap_log_err("coap_join_mcast_group_intf: %s: "
5233 "Cannot get IPv4 address: %s\n",
5234 ifname, coap_socket_strerror());
5235#else /* !ESPIDF_VERSION */
5236 memset(&ifr, 0, sizeof(ifr));
5237 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5238 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5239
5240#ifdef HAVE_IF_NAMETOINDEX
5241 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5242 if (mreq6.ipv6mr_interface == 0) {
5243 coap_log_warn("coap_join_mcast_group_intf: "
5244 "cannot get interface index for '%s'\n",
5245 ifname);
5246 }
5247#elif defined(__QNXNTO__)
5248#else /* !HAVE_IF_NAMETOINDEX */
5249 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5250 if (result != 0) {
5251 coap_log_warn("coap_join_mcast_group_intf: "
5252 "cannot get interface index for '%s': %s\n",
5253 ifname, coap_socket_strerror());
5254 } else {
5255 /* Capture the IPv6 if_index for later */
5256 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5257 }
5258#endif /* !HAVE_IF_NAMETOINDEX */
5259#endif /* !ESPIDF_VERSION */
5260#endif /* COAP_IPV6_SUPPORT */
5261 break;
5262#if COAP_IPV4_SUPPORT
5263 case AF_INET:
5264 if (done_ip4)
5265 break;
5266 done_ip4 = 1;
5267#if defined(ESPIDF_VERSION)
5268 netif = netif_find(ifname);
5269 if (netif)
5270 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5271 else
5272 coap_log_err("coap_join_mcast_group_intf: %s: "
5273 "Cannot get IPv4 address: %s\n",
5274 ifname, coap_socket_strerror());
5275#else /* !ESPIDF_VERSION */
5276 /*
5277 * Need an AF_INET socket to do this unfortunately to stop
5278 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5279 */
5280 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5281 if (ip4fd == -1) {
5282 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5283 ifname, coap_socket_strerror());
5284 continue;
5285 }
5286 memset(&ifr, 0, sizeof(ifr));
5287 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5288 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5289 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5290 if (result != 0) {
5291 coap_log_err("coap_join_mcast_group_intf: %s: "
5292 "Cannot get IPv4 address: %s\n",
5293 ifname, coap_socket_strerror());
5294 } else {
5295 /* Capture the IPv4 address for later */
5296 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5297 }
5298 close(ip4fd);
5299#endif /* !ESPIDF_VERSION */
5300 break;
5301#endif /* COAP_IPV4_SUPPORT */
5302 default:
5303 break;
5304 }
5305 }
5306 }
5307#else /* _WIN32 */
5308 /*
5309 * On Windows this function ignores the ifname variable so we unset this
5310 * variable on this platform in any case in order to enable the interface
5311 * selection from the bind address below.
5312 */
5313 ifname = 0;
5314#endif /* _WIN32 */
5315
5316 /* Add in mcast address(es) to appropriate interface */
5317 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5318 LL_FOREACH(ctx->endpoint, endpoint) {
5319 /* Only UDP currently supported */
5320 if (endpoint->proto == COAP_PROTO_UDP) {
5321 coap_address_t gaddr;
5322
5323 coap_address_init(&gaddr);
5324#if COAP_IPV6_SUPPORT
5325 if (ainfo->ai_family == AF_INET6) {
5326 if (!ifname) {
5327 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5328 /*
5329 * Do it on the ifindex that the server is listening on
5330 * (sin6_scope_id could still be 0)
5331 */
5332 mreq6.ipv6mr_interface =
5333 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5334 } else {
5335 mreq6.ipv6mr_interface = 0;
5336 }
5337 }
5338 gaddr.addr.sin6.sin6_family = AF_INET6;
5339 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5340 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5341 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5342 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5343 (char *)&mreq6, sizeof(mreq6));
5344 }
5345#endif /* COAP_IPV6_SUPPORT */
5346#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5347 else
5348#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5349#if COAP_IPV4_SUPPORT
5350 if (ainfo->ai_family == AF_INET) {
5351 if (!ifname) {
5352 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5353 /*
5354 * Do it on the interface that the server is listening on
5355 * (sin_addr could still be INADDR_ANY)
5356 */
5357 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5358 } else {
5359 mreq4.imr_interface.s_addr = INADDR_ANY;
5360 }
5361 }
5362 gaddr.addr.sin.sin_family = AF_INET;
5363 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5364 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5365 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5366 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5367 (char *)&mreq4, sizeof(mreq4));
5368 }
5369#endif /* COAP_IPV4_SUPPORT */
5370 else {
5371 continue;
5372 }
5373
5374 if (result == COAP_SOCKET_ERROR) {
5375 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5376 group_name, coap_socket_strerror());
5377 } else {
5378 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5379
5380 addr_str[sizeof(addr_str)-1] = '\000';
5381 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5382 sizeof(addr_str) - 1)) {
5383 if (ifname)
5384 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5385 ifname);
5386 else
5387 coap_log_debug("added mcast group %s\n", addr_str);
5388 }
5389 mgroup_setup = 1;
5390 }
5391 }
5392 }
5393 }
5394 if (!mgroup_setup) {
5395 result = -1;
5396 }
5397
5398finish:
5399 freeaddrinfo(resmulti);
5400
5401 return result;
5402}
5403
5404void
5406 context->mcast_per_resource = 1;
5407}
5408
5409#endif /* ! COAP_SERVER_SUPPORT */
5410
5411#if COAP_CLIENT_SUPPORT
5412int
5413coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5414 if (session && coap_is_mcast(&session->addr_info.remote)) {
5415 switch (session->addr_info.remote.addr.sa.sa_family) {
5416#if COAP_IPV4_SUPPORT
5417 case AF_INET:
5418 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5419 (const char *)&hops, sizeof(hops)) < 0) {
5420 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5421 hops, coap_socket_strerror());
5422 return 0;
5423 }
5424 return 1;
5425#endif /* COAP_IPV4_SUPPORT */
5426#if COAP_IPV6_SUPPORT
5427 case AF_INET6:
5428 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5429 (const char *)&hops, sizeof(hops)) < 0) {
5430 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5431 hops, coap_socket_strerror());
5432 return 0;
5433 }
5434 return 1;
5435#endif /* COAP_IPV6_SUPPORT */
5436 default:
5437 break;
5438 }
5439 }
5440 return 0;
5441}
5442#endif /* COAP_CLIENT_SUPPORT */
5443
5444#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
5445COAP_API int
5447 const char *group_name COAP_UNUSED,
5448 const char *ifname COAP_UNUSED) {
5449 return -1;
5450}
5451
5452int
5454 size_t hops COAP_UNUSED) {
5455 return 0;
5456}
5457
5458void
5460}
5461#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:2355
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:1048
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:527
#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:1122
static int send_recv_terminate
Definition coap_net.c:2106
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:2988
#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:5075
#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:4808
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:3303
int coap_started
Definition coap_net.c:5010
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2375
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2416
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:4244
#define min(a, b)
Definition coap_net.c:76
void coap_startup(void)
Definition coap_net.c:5026
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4321
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:2777
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:1079
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:1203
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:1174
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:2712
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:2135
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1833
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:1292
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:1479
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:1094
#define COAP_IO_NO_WAIT
Definition coap_net.h:733
#define COAP_IO_WAIT
Definition coap_net.h:732
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:2766
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:2705
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.
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.
#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:4880
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:5146
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:2943
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:1347
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:4354
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:1231
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:1845
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:4942
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2253
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:1414
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:924
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1257
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:3047
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:2882
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:3086
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:2114
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:1469
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:1161
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:2109
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:5099
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:3119
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
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:1084
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:5127
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:1192
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:1069
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:4932
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:5139
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:5133
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:4869
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:5121
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:118
@ 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:116
@ 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:125
@ 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:110
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:127
@ 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:114
@ 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:100
@ COAP_EVENT_MSG_RETRANSMITTED
Triggered when a message is retransmitted.
Definition coap_event.h:102
@ COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD
Triggered when there is no OSCORE encrypted payload provided.
Definition coap_event.h:112
@ 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:123
@ 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:108
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:132
@ 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_WSS
Definition coap_pdu.h:320
@ COAP_SIGNALING_CODE_ABORT
Definition coap_pdu.h:370
@ 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:5110
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:2446
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:1109
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_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_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.
unsigned int is_proxy_uri
resource created for proxy URI handler
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