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