libcoap 4.3.5-develop-07c7a7a
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;
119 coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
120
121 if (ctx->sendqueue) {
122 /* delta < 0 means that the new time stamp is before the old. */
123 if (delta <= 0) {
124 ctx->sendqueue->t -= delta;
125 } else {
126 /* This case is more complex: The time must be advanced forward,
127 * thus possibly leading to timed out elements at the queue's
128 * start. For every element that has timed out, its relative
129 * time is set to zero and the result counter is increased. */
130
131 coap_queue_t *q = ctx->sendqueue;
132 coap_tick_t t = 0;
133 while (q && (t + q->t < (coap_tick_t)delta)) {
134 t += q->t;
135 q->t = 0;
136 result++;
137 q = q->next;
138 }
139
140 /* finally adjust the first element that has not expired */
141 if (q) {
142 q->t = (coap_tick_t)delta - t;
143 }
144 }
145 }
146
147 /* adjust basetime */
148 ctx->sendqueue_basetime += delta;
149
150 return result;
151}
152
153int
155 coap_queue_t *p, *q;
156 if (!queue || !node)
157 return 0;
158
159 /* set queue head if empty */
160 if (!*queue) {
161 *queue = node;
162 return 1;
163 }
164
165 /* replace queue head if PDU's time is less than head's time */
166 q = *queue;
167 if (node->t < q->t) {
168 node->next = q;
169 *queue = node;
170 q->t -= node->t; /* make q->t relative to node->t */
171 return 1;
172 }
173
174 /* search for right place to insert */
175 do {
176 node->t -= q->t; /* make node-> relative to q->t */
177 p = q;
178 q = q->next;
179 } while (q && q->t <= node->t);
180
181 /* insert new item */
182 if (q) {
183 q->t -= node->t; /* make q->t relative to node->t */
184 }
185 node->next = q;
186 p->next = node;
187 return 1;
188}
189
190COAP_API int
192 int ret;
193#if COAP_THREAD_SAFE
194 coap_context_t *context;
195#endif /* COAP_THREAD_SAFE */
196
197 if (!node)
198 return 0;
199 if (!node->session)
200 return coap_delete_node_lkd(node);
201
202#if COAP_THREAD_SAFE
203 /* Keep copy as node will be going away */
204 context = node->session->context;
205 (void)context;
206#endif /* COAP_THREAD_SAFE */
207 coap_lock_lock(return 0);
208 ret = coap_delete_node_lkd(node);
210 return ret;
211}
212
213int
215 if (!node)
216 return 0;
217
219 if (node->session) {
220 /*
221 * Need to remove out of context->sendqueue as added in by coap_wait_ack()
222 */
223 if (node->session->context->sendqueue) {
224 LL_DELETE(node->session->context->sendqueue, node);
225 }
227 }
228 coap_free_node(node);
229
230 return 1;
231}
232
233void
235 if (!queue)
236 return;
237
238 coap_delete_all(queue->next);
240}
241
244 coap_queue_t *node;
245 node = coap_malloc_node();
246
247 if (!node) {
248 coap_log_warn("coap_new_node: malloc failed\n");
249 return NULL;
250 }
251
252 memset(node, 0, sizeof(*node));
253 return node;
254}
255
258 if (!context || !context->sendqueue)
259 return NULL;
260
261 return context->sendqueue;
262}
263
266 coap_queue_t *next;
267
268 if (!context || !context->sendqueue)
269 return NULL;
270
271 next = context->sendqueue;
272 context->sendqueue = context->sendqueue->next;
273 if (context->sendqueue) {
274 context->sendqueue->t += next->t;
275 }
276 next->next = NULL;
277 return next;
278}
279
280#if COAP_CLIENT_SUPPORT
281const coap_bin_const_t *
283
284 if (session->psk_key) {
285 return session->psk_key;
286 }
287 if (session->cpsk_setup_data.psk_info.key.length)
288 return &session->cpsk_setup_data.psk_info.key;
289
290 /* Not defined in coap_new_client_session_psk2() */
291 return NULL;
292}
293
294const coap_bin_const_t *
296
297 if (session->psk_identity) {
298 return session->psk_identity;
299 }
301 return &session->cpsk_setup_data.psk_info.identity;
302
303 /* Not defined in coap_new_client_session_psk2() */
304 return NULL;
305}
306#endif /* COAP_CLIENT_SUPPORT */
307
308#if COAP_SERVER_SUPPORT
309const coap_bin_const_t *
311
312 if (session->psk_key)
313 return session->psk_key;
314
316 return &session->context->spsk_setup_data.psk_info.key;
317
318 /* Not defined in coap_context_set_psk2() */
319 return NULL;
320}
321
322const coap_bin_const_t *
324
325 if (session->psk_hint)
326 return session->psk_hint;
327
329 return &session->context->spsk_setup_data.psk_info.hint;
330
331 /* Not defined in coap_context_set_psk2() */
332 return NULL;
333}
334
335COAP_API int
337 const char *hint,
338 const uint8_t *key,
339 size_t key_len) {
340 int ret;
341
342 coap_lock_lock(return 0);
343 ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
345 return ret;
346}
347
348int
350 const char *hint,
351 const uint8_t *key,
352 size_t key_len) {
353 coap_dtls_spsk_t setup_data;
354
356 memset(&setup_data, 0, sizeof(setup_data));
357 if (hint) {
358 setup_data.psk_info.hint.s = (const uint8_t *)hint;
359 setup_data.psk_info.hint.length = strlen(hint);
360 }
361
362 if (key && key_len > 0) {
363 setup_data.psk_info.key.s = key;
364 setup_data.psk_info.key.length = key_len;
365 }
366
367 return coap_context_set_psk2_lkd(ctx, &setup_data);
368}
369
370COAP_API int
372 int ret;
373
374 coap_lock_lock(return 0);
375 ret = coap_context_set_psk2_lkd(ctx, setup_data);
377 return ret;
378}
379
380int
382 if (!setup_data)
383 return 0;
384
386 ctx->spsk_setup_data = *setup_data;
387
389 return coap_dtls_context_set_spsk(ctx, setup_data);
390 }
391 return 0;
392}
393
394COAP_API int
396 const coap_dtls_pki_t *setup_data) {
397 int ret;
398
399 coap_lock_lock(return 0);
400 ret = coap_context_set_pki_lkd(ctx, setup_data);
402 return ret;
403}
404
405int
407 const coap_dtls_pki_t *setup_data) {
409 if (!setup_data)
410 return 0;
411 if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
412 coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
413 return 0;
414 }
416 return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
417 }
418 return 0;
419}
420#endif /* ! COAP_SERVER_SUPPORT */
421
422COAP_API int
424 const char *ca_file,
425 const char *ca_dir) {
426 int ret;
427
428 coap_lock_lock(return 0);
429 ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
431 return ret;
432}
433
434int
436 const char *ca_file,
437 const char *ca_dir) {
439 return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
440 }
441 return 0;
442}
443
444COAP_API int
446 int ret;
447
448 coap_lock_lock(return 0);
451 return ret;
452}
453
454int
461
462
463void
464coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
465 context->ping_timeout = seconds;
466}
467
468int
470#if COAP_CLIENT_SUPPORT
471 return coap_dtls_set_cid_tuple_change(context, every);
472#else /* ! COAP_CLIENT_SUPPORT */
473 (void)context;
474 (void)every;
475 return 0;
476#endif /* ! COAP_CLIENT_SUPPORT */
477}
478
479void
481 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");
780 return NULL;
781 }
782 }
783
784 /* set default CSM values */
785 c->csm_timeout_ms = 1000;
786 c->csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
787
788#if COAP_SERVER_SUPPORT
789 if (listen_addr) {
790 coap_endpoint_t *endpoint = coap_new_endpoint_lkd(c, listen_addr, COAP_PROTO_UDP);
791 if (endpoint == NULL) {
792 goto onerror;
793 }
794 }
795#endif /* COAP_SERVER_SUPPORT */
796
797 c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
798
800 return c;
801
802#if defined(COAP_EPOLL_SUPPORT) || COAP_SERVER_SUPPORT
803onerror:
805 return NULL;
806#endif /* COAP_EPOLL_SUPPORT || COAP_SERVER_SUPPORT */
807}
808
809COAP_API void
810coap_set_app_data(coap_context_t *context, void *app_data) {
811 assert(context);
812 coap_lock_lock(return);
813 coap_context_set_app_data2_lkd(context, app_data, NULL);
815}
816
817void *
819 assert(ctx);
820 return ctx->app_data;
821}
822
823COAP_API void
825 if (!context)
826 return;
827 coap_lock_lock(return);
828 coap_free_context_lkd(context);
830}
831
832void
834 if (!context)
835 return;
836
838#if COAP_SERVER_SUPPORT
839 /* Removing a resource may cause a NON unsolicited observe to be sent */
840 if (context->shutdown_no_send_observe)
841 context->observe_no_clear = 1;
843#endif /* COAP_SERVER_SUPPORT */
844#if COAP_CLIENT_SUPPORT
845 /* Stop any attempts at reconnection */
846 context->reconnect_time = 0;
847#endif /* COAP_CLIENT_SUPPORT */
848
849 coap_delete_all(context->sendqueue);
850 context->sendqueue = NULL;
851
852#ifdef WITH_LWIP
853 if (context->timer_configured) {
854 LOCK_TCPIP_CORE();
855 sys_untimeout(coap_io_process_timeout, (void *)context);
856 UNLOCK_TCPIP_CORE();
857 context->timer_configured = 0;
858 }
859#endif /* WITH_LWIP */
860
861#if COAP_ASYNC_SUPPORT
862 coap_delete_all_async(context);
863#endif /* COAP_ASYNC_SUPPORT */
864
865#if COAP_OSCORE_SUPPORT
866 coap_delete_all_oscore(context);
867#endif /* COAP_OSCORE_SUPPORT */
868
869#if COAP_SERVER_SUPPORT
870 coap_cache_entry_t *cp, *ctmp;
871 coap_endpoint_t *ep, *tmp;
872
873 HASH_ITER(hh, context->cache, cp, ctmp) {
874 coap_delete_cache_entry(context, cp);
875 }
876 if (context->cache_ignore_count) {
878 }
879
880 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
882 }
883#endif /* COAP_SERVER_SUPPORT */
884
885#if COAP_CLIENT_SUPPORT
886 coap_session_t *sp, *rtmp;
887
888 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
890 }
891#endif /* COAP_CLIENT_SUPPORT */
892
893 if (context->dtls_context)
895#ifdef COAP_EPOLL_SUPPORT
896 if (context->eptimerfd != -1) {
897 int ret;
898 struct epoll_event event;
899
900 /* Kernels prior to 2.6.9 expect non NULL event parameter */
901 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
902 if (ret == -1) {
903 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
904 "coap_free_context",
905 coap_socket_strerror(), errno);
906 }
907 close(context->eptimerfd);
908 context->eptimerfd = -1;
909 }
910 if (context->epfd != -1) {
911 close(context->epfd);
912 context->epfd = -1;
913 }
914#endif /* COAP_EPOLL_SUPPORT */
915#if COAP_SERVER_SUPPORT
916#if COAP_WITH_OBSERVE_PERSIST
917 coap_persist_cleanup(context);
918#endif /* COAP_WITH_OBSERVE_PERSIST */
919#endif /* COAP_SERVER_SUPPORT */
920#if COAP_PROXY_SUPPORT
921 coap_proxy_cleanup(context);
922#endif /* COAP_PROXY_SUPPORT */
923
924 if (context->app_cb) {
925 coap_lock_callback(context->app_cb(context->app_data));
926 }
929}
930
931int
933 coap_pdu_t *pdu,
934 coap_opt_filter_t *unknown) {
935 coap_context_t *ctx = session->context;
936 coap_opt_iterator_t opt_iter;
937 int ok = 1;
938 coap_option_num_t last_number = -1;
939
941
942 while (coap_option_next(&opt_iter)) {
943 /* Check for explicitely reserved option RFC 5272 12.2 Table 7 */
944 /* Need to check reserved options */
945 switch (opt_iter.number) {
946 case 0:
947 case 128:
948 case 132:
949 case 136:
950 case 140:
951 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
952 coap_log_debug("unknown reserved option %d\n", opt_iter.number);
953 ok = 0;
954
955 /* When opt_iter.number cannot be set in unknown, all of the appropriate
956 * slots have been used up and no more options can be tracked.
957 * Safe to break out of this loop as ok is already set. */
958 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
959 goto overflow;
960 }
961 }
962 break;
963 default:
964 break;
965 }
966 if (opt_iter.number & 0x01) {
967 /* first check the known built-in critical options */
968 switch (opt_iter.number) {
969#if COAP_Q_BLOCK_SUPPORT
972 if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
973 coap_log_debug("disabled support for critical option %u\n",
974 opt_iter.number);
975 ok = 0;
976 /* When opt_iter.number cannot be set in unknown, all of the appropriate
977 * slots have been used up and no more options can be tracked.
978 * Safe to break out of this loop as ok is already set. */
979 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
980 goto overflow;
981 }
982 }
983 break;
984#endif /* COAP_Q_BLOCK_SUPPORT */
996 break;
998 /* Valid critical if doing OSCORE */
999#if COAP_OSCORE_SUPPORT
1000 if (ctx->p_osc_ctx)
1001 break;
1002#endif /* COAP_OSCORE_SUPPORT */
1003 /* Fall Through */
1004 default:
1005 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1006#if COAP_SERVER_SUPPORT
1007 if ((opt_iter.number & 0x02) == 0) {
1008 coap_opt_iterator_t t_iter;
1009
1010 /* Safe to forward - check if proxy pdu */
1011 if (session->proxy_session)
1012 break;
1013 if (COAP_PDU_IS_REQUEST(pdu) && ctx->proxy_uri_resource &&
1014 (coap_check_option(pdu, COAP_OPTION_PROXY_URI, &t_iter) ||
1016 pdu->crit_opt = 1;
1017 break;
1018 }
1019 if (COAP_PDU_IS_REQUEST(pdu) && ctx->unknown_resource &&
1021 pdu->crit_opt = 1;
1022 break;
1023 }
1024 }
1025#endif /* COAP_SERVER_SUPPORT */
1026 coap_log_debug("unknown critical option %d\n", opt_iter.number);
1027 ok = 0;
1028
1029 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1030 * slots have been used up and no more options can be tracked.
1031 * Safe to break out of this loop as ok is already set. */
1032 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1033 goto overflow;
1034 }
1035 }
1036 }
1037 }
1038 if (last_number == opt_iter.number) {
1039 /* Check for duplicated option RFC 5272 5.4.5 */
1040 if (!coap_option_check_repeatable(opt_iter.number)) {
1041 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1042 ok = 0;
1043 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1044 goto overflow;
1045 }
1046 }
1047 }
1048 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
1049 COAP_PDU_IS_REQUEST(pdu)) {
1050 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
1051 coap_block_b_t block;
1052
1053 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
1054 if (block.m) {
1055 size_t used_size = pdu->used_size;
1056 unsigned char buf[4];
1057
1058 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
1059 block.m = 0;
1060 coap_update_option(pdu, opt_iter.number,
1061 coap_encode_var_safe(buf, sizeof(buf),
1062 ((block.num << 4) |
1063 (block.m << 3) |
1064 block.aszx)),
1065 buf);
1066 if (used_size != pdu->used_size) {
1067 /* Unfortunately need to restart the scan */
1068 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1069 last_number = -1;
1070 continue;
1071 }
1072 }
1073 }
1074 }
1075 last_number = opt_iter.number;
1076 }
1077overflow:
1078 return ok;
1079}
1080
1082coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
1083 coap_mid_t mid;
1084
1086 mid = coap_send_rst_lkd(session, request);
1088 return mid;
1089}
1090
1093 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
1094}
1095
1097coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
1098 coap_mid_t mid;
1099
1101 mid = coap_send_ack_lkd(session, request);
1103 return mid;
1104}
1105
1108 coap_pdu_t *response;
1110
1112 if (request && request->type == COAP_MESSAGE_CON &&
1113 COAP_PROTO_NOT_RELIABLE(session->proto)) {
1114 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
1115 if (response)
1116 result = coap_send_internal(session, response, NULL);
1117 }
1118 return result;
1119}
1120
1121ssize_t
1123 ssize_t bytes_written = -1;
1124 assert(pdu->hdr_size > 0);
1125
1126 /* Caller handles partial writes */
1127 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1128 pdu->token - pdu->hdr_size,
1129 pdu->used_size + pdu->hdr_size);
1131 return bytes_written;
1132}
1133
1134static ssize_t
1136 ssize_t bytes_written;
1137
1138 if (session->state == COAP_SESSION_STATE_NONE) {
1139#if ! COAP_CLIENT_SUPPORT
1140 return -1;
1141#else /* COAP_CLIENT_SUPPORT */
1142 if (session->type != COAP_SESSION_TYPE_CLIENT)
1143 return -1;
1144#endif /* COAP_CLIENT_SUPPORT */
1145 }
1146
1147 if (pdu->type == COAP_MESSAGE_CON &&
1148 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1149 coap_is_mcast(&session->addr_info.remote)) {
1150 /* Violates RFC72522 8.1 */
1151 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1152 return -1;
1153 }
1154
1155 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1156 (pdu->type == COAP_MESSAGE_CON &&
1157 session->con_active >= COAP_NSTART(session))) {
1158 return coap_session_delay_pdu(session, pdu, node);
1159 }
1160
1161 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1162 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1163 return coap_session_delay_pdu(session, pdu, node);
1164
1165 bytes_written = coap_session_send_pdu(session, pdu);
1166 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1168 session->con_active++;
1169
1170 return bytes_written;
1171}
1172
1175 const coap_pdu_t *request,
1176 coap_pdu_code_t code,
1177 coap_opt_filter_t *opts) {
1178 coap_mid_t mid;
1179
1181 mid = coap_send_error_lkd(session, request, code, opts);
1183 return mid;
1184}
1185
1188 const coap_pdu_t *request,
1189 coap_pdu_code_t code,
1190 coap_opt_filter_t *opts) {
1191 coap_pdu_t *response;
1193
1194 assert(request);
1195 assert(session);
1196
1197 response = coap_new_error_response(request, code, opts);
1198 if (response)
1199 result = coap_send_internal(session, response, NULL);
1200
1201 return result;
1202}
1203
1206 coap_pdu_type_t type) {
1207 coap_mid_t mid;
1208
1210 mid = coap_send_message_type_lkd(session, request, type);
1212 return mid;
1213}
1214
1217 coap_pdu_type_t type) {
1218 coap_pdu_t *response;
1220
1222 if (request && COAP_PROTO_NOT_RELIABLE(session->proto)) {
1223 response = coap_pdu_init(type, 0, request->mid, 0);
1224 if (response)
1225 result = coap_send_internal(session, response, NULL);
1226 }
1227 return result;
1228}
1229
1243unsigned int
1244coap_calc_timeout(coap_session_t *session, unsigned char r) {
1245 unsigned int result;
1246
1247 /* The integer 1.0 as a Qx.FRAC_BITS */
1248#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1249
1250 /* rounds val up and right shifts by frac positions */
1251#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1252
1253 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1254 * make the result a rounded Qx.FRAC_BITS */
1255 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1256
1257 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1258 * make the result a rounded Qx.FRAC_BITS */
1259 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1260
1261 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1262 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1263 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1264
1265#undef FP1
1266#undef SHR_FP
1267}
1268
1271 coap_queue_t *node) {
1272 coap_tick_t now;
1273
1274 node->session = coap_session_reference_lkd(session);
1275
1276 /* Set timer for pdu retransmission. If this is the first element in
1277 * the retransmission queue, the base time is set to the current
1278 * time and the retransmission time is node->timeout. If there is
1279 * already an entry in the sendqueue, we must check if this node is
1280 * to be retransmitted earlier. Therefore, node->timeout is first
1281 * normalized to the base time and then inserted into the queue with
1282 * an adjusted relative time.
1283 */
1284 coap_ticks(&now);
1285 if (context->sendqueue == NULL) {
1286 node->t = node->timeout << node->retransmit_cnt;
1287 context->sendqueue_basetime = now;
1288 } else {
1289 /* make node->t relative to context->sendqueue_basetime */
1290 node->t = (now - context->sendqueue_basetime) +
1291 (node->timeout << node->retransmit_cnt);
1292 }
1293 coap_address_copy(&node->remote, &session->addr_info.remote);
1294
1295 coap_insert_node(&context->sendqueue, node);
1296
1297 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1298 coap_session_str(node->session), node->id,
1299 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1301
1302 coap_update_io_timer(context, node->t);
1303
1304 return node->id;
1305}
1306
1307#if COAP_CLIENT_SUPPORT
1308/*
1309 * Sent out a test PDU for Extended Token
1310 */
1311static coap_mid_t
1312coap_send_test_extended_token(coap_session_t *session) {
1313 coap_pdu_t *pdu;
1315 size_t i;
1316 coap_binary_t *token;
1317 coap_lg_crcv_t *lg_crcv;
1318
1319 coap_log_debug("Testing for Extended Token support\n");
1320 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1322 coap_new_message_id_lkd(session),
1324 if (!pdu)
1325 return COAP_INVALID_MID;
1326
1327 token = coap_new_binary(session->max_token_size);
1328 if (token == NULL) {
1330 return COAP_INVALID_MID;
1331 }
1332 for (i = 0; i < session->max_token_size; i++) {
1333 token->s[i] = (uint8_t)(i + 1);
1334 }
1335 coap_add_token(pdu, session->max_token_size, token->s);
1336 coap_delete_binary(token);
1337
1340 pdu->actual_token.length);
1341
1343
1344 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1345
1346 /* Need to track incase OSCORE / Echo etc. comes back after non-piggy-backed ACK */
1347 lg_crcv = coap_block_new_lg_crcv(session, pdu, NULL);
1348 if (lg_crcv) {
1349 LL_PREPEND(session->lg_crcv, lg_crcv);
1350 }
1351 mid = coap_send_internal(session, pdu, NULL);
1352 if (mid == COAP_INVALID_MID)
1353 return COAP_INVALID_MID;
1354 session->remote_test_mid = mid;
1355 return mid;
1356}
1357#endif /* COAP_CLIENT_SUPPORT */
1358
1359/*
1360 * Return: 0 Something failed
1361 * 1 Success
1362 */
1363int
1365#if COAP_CLIENT_SUPPORT
1366 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1367 int timeout_ms = 5000;
1368 coap_session_state_t current_state = session->state;
1369
1370 if (session->delay_recursive) {
1371 return 0;
1372 } else {
1373 session->delay_recursive = 1;
1374 }
1375 /*
1376 * Need to wait for first request to get out and response back before
1377 * continuing.. Response handler has to clear doing_first if not an error.
1378 */
1380 while (session->doing_first != 0) {
1381 int result = coap_io_process_lkd(session->context, 1000);
1382
1383 if (result < 0) {
1384 coap_reset_doing_first(session);
1385 session->delay_recursive = 0;
1386 coap_session_release_lkd(session);
1387 return 0;
1388 }
1389
1390 /* coap_io_process_lkd() may have updated session state */
1391 if (session->state == COAP_SESSION_STATE_CSM &&
1392 current_state != COAP_SESSION_STATE_CSM) {
1393 /* Update timeout and restart the clock for CSM timeout */
1394 current_state = COAP_SESSION_STATE_CSM;
1395 timeout_ms = session->context->csm_timeout_ms;
1396 result = 0;
1397 }
1398
1399 if (result < timeout_ms) {
1400 timeout_ms -= result;
1401 } else {
1402 if (session->doing_first == 1) {
1403 /* Timeout failure of some sort with first request */
1404 if (session->state == COAP_SESSION_STATE_CSM) {
1405 coap_log_debug("** %s: timeout waiting for CSM response\n",
1406 coap_session_str(session));
1407 session->csm_not_seen = 1;
1408 } else {
1409 coap_log_debug("** %s: timeout waiting for first response\n",
1410 coap_session_str(session));
1411 }
1412 coap_reset_doing_first(session);
1413 coap_session_connected(session);
1414 }
1415 }
1416 }
1417 session->delay_recursive = 0;
1418 coap_session_release_lkd(session);
1419 }
1420#else /* ! COAP_CLIENT_SUPPORT */
1421 (void)session;
1422#endif /* ! COAP_CLIENT_SUPPORT */
1423 return 1;
1424}
1425
1426/*
1427 * return 0 Invalid
1428 * 1 Valid
1429 */
1430int
1432
1433 /* Check validity of sending code */
1434 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1435 case 0: /* Empty or request */
1436 case 2: /* Success */
1437 case 3: /* Reserved for future use */
1438 case 4: /* Client error */
1439 case 5: /* Server error */
1440 break;
1441 case 7: /* Reliable signalling */
1442 if (COAP_PROTO_RELIABLE(session->proto))
1443 break;
1444 /* Not valid if UDP */
1445 /* Fall through */
1446 case 1: /* Invalid */
1447 case 6: /* Invalid */
1448 default:
1449 return 0;
1450 }
1451 return 1;
1452}
1453
1454#if COAP_CLIENT_SUPPORT
1455/*
1456 * If type is CON and protocol is not reliable, there is no need to set up
1457 * lg_crcv if it can be built up based on sent PDU if there is a
1458 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1459 * (Q-)Block1.
1460 */
1461static int
1462coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1463 coap_opt_iterator_t opt_iter;
1464
1465 if (!COAP_PDU_IS_REQUEST(pdu))
1466 return 0;
1467
1468 if (
1469#if COAP_OSCORE_SUPPORT
1470 session->oscore_encryption ||
1471#endif /* COAP_OSCORE_SUPPORT */
1472 pdu->type == COAP_MESSAGE_NON ||
1473 COAP_PROTO_RELIABLE(session->proto) ||
1474 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1475#if COAP_Q_BLOCK_SUPPORT
1476 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1477#endif /* COAP_Q_BLOCK_SUPPORT */
1478 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1479 return 1;
1480 }
1481 return 0;
1482}
1483#endif /* COAP_CLIENT_SUPPORT */
1484
1487 coap_mid_t mid;
1488
1490 mid = coap_send_lkd(session, pdu);
1492 return mid;
1493}
1494
1498#if COAP_CLIENT_SUPPORT
1499 coap_lg_crcv_t *lg_crcv = NULL;
1500 coap_opt_iterator_t opt_iter;
1501 coap_block_b_t block;
1502 int observe_action = -1;
1503 int have_block1 = 0;
1504 coap_opt_t *opt;
1505#endif /* COAP_CLIENT_SUPPORT */
1506
1507 assert(pdu);
1508
1510
1511 /* Check validity of sending code */
1512 if (!coap_check_code_class(session, pdu)) {
1513 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1515 pdu->code & 0x1f);
1516 goto error;
1517 }
1518 pdu->session = session;
1519#if COAP_CLIENT_SUPPORT
1520 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1521 !coap_netif_available(session) && !session->session_failed) {
1522 coap_log_debug("coap_send: Socket closed\n");
1523 goto error;
1524 }
1525
1526 if (session->doing_first) {
1527 LL_APPEND(session->doing_first_pdu, pdu);
1529 coap_log_debug("** %s: mid=0x%04x: queued\n",
1530 coap_session_str(session), pdu->mid);
1531 return pdu->mid;
1532 }
1533
1534 /* Indicate support for Extended Tokens if appropriate */
1535 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1537 session->type == COAP_SESSION_TYPE_CLIENT &&
1538 COAP_PDU_IS_REQUEST(pdu)) {
1539 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1540 /*
1541 * When the pass / fail response for Extended Token is received, this PDU
1542 * will get transmitted.
1543 */
1544 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1545 goto error;
1546 }
1547 }
1548 /*
1549 * For reliable protocols, this will get cleared after CSM exchanged
1550 * in coap_session_connected() where Token size support is indicated in the CSM.
1551 */
1552 session->doing_first = 1;
1554 LL_PREPEND(session->doing_first_pdu, pdu);
1555 if (session->proto != COAP_PROTO_UDP) {
1556 /* In case the next handshake / CSM is already in */
1558 }
1559 /*
1560 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1561 * will get called again.
1562 */
1564 coap_log_debug("** %s: mid=0x%04x: queued\n",
1565 coap_session_str(session), pdu->mid);
1566 return pdu->mid;
1567 }
1568#if COAP_Q_BLOCK_SUPPORT
1569 /* Indicate support for Q-Block if appropriate */
1570 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1571 session->type == COAP_SESSION_TYPE_CLIENT &&
1572 COAP_PDU_IS_REQUEST(pdu)) {
1573 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1574 goto error;
1575 }
1576 session->doing_first = 1;
1578 LL_PREPEND(session->doing_first_pdu, pdu);
1579 if (session->proto != COAP_PROTO_UDP) {
1580 /* In case the next handshake / CSM is already in */
1582 }
1583 /*
1584 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1585 * will get called again.
1586 */
1588 coap_log_debug("** %s: mid=0x%04x: queued\n",
1589 coap_session_str(session), pdu->mid);
1590 return pdu->mid;
1591 }
1592#endif /* COAP_Q_BLOCK_SUPPORT */
1593
1594 /*
1595 * Check validity of token length
1596 */
1597 if (COAP_PDU_IS_REQUEST(pdu) &&
1598 pdu->actual_token.length > session->max_token_size) {
1599 coap_log_warn("coap_send: PDU dropped as token too long (%" PRIuS " > %" PRIu32 ")\n",
1600 pdu->actual_token.length, session->max_token_size);
1601 goto error;
1602 }
1603
1604 /* A lot of the reliable code assumes type is CON */
1605 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1606 pdu->type = COAP_MESSAGE_CON;
1607
1608#if COAP_OSCORE_SUPPORT
1609 if (session->oscore_encryption) {
1610 if (session->recipient_ctx->initial_state == 1) {
1611 /*
1612 * Not sure if remote supports OSCORE, or is going to send us a
1613 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1614 * is OK. Continue sending current pdu to test things.
1615 */
1616 session->doing_first = 1;
1617 }
1618 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1620 goto error;
1621 }
1622 }
1623#endif /* COAP_OSCORE_SUPPORT */
1624
1625 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1626 return coap_send_internal(session, pdu, NULL);
1627 }
1628
1629 if (COAP_PDU_IS_REQUEST(pdu)) {
1630 uint8_t buf[4];
1631
1632 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1633
1634 if (opt) {
1635 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1636 coap_opt_length(opt));
1637 }
1638
1639 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1640 (block.m == 1 || block.bert == 1)) {
1641 have_block1 = 1;
1642 }
1643#if COAP_Q_BLOCK_SUPPORT
1644 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1645 (block.m == 1 || block.bert == 1)) {
1646 if (have_block1) {
1647 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1649 }
1650 have_block1 = 1;
1651 }
1652#endif /* COAP_Q_BLOCK_SUPPORT */
1653 if (observe_action != COAP_OBSERVE_CANCEL) {
1654 /* Warn about re-use of tokens */
1655 if (session->last_token &&
1656 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1658 char scratch[24];
1659 size_t size;
1660 size_t i;
1661
1662 scratch[0] = '\000';
1663 for (i = 0; i < pdu->actual_token.length; i++) {
1664 size = strlen(scratch);
1665 snprintf(&scratch[size], sizeof(scratch)-size,
1666 "%02x", pdu->actual_token.s[i]);
1667 }
1668 coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1669 scratch);
1670 }
1671 }
1674 pdu->actual_token.length);
1675 } else {
1676 /* observe_action == COAP_OBSERVE_CANCEL */
1677 coap_binary_t tmp;
1678 int ret;
1679
1680 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1681 /* Unfortunately need to change the ptr type to be r/w */
1682 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1683 tmp.length = pdu->actual_token.length;
1684 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1685 if (ret == 1) {
1686 /* Observe Cancel successfully sent */
1688 return ret;
1689 }
1690 /* Some mismatch somewhere - continue to send original packet */
1691 }
1692 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1693 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1697 coap_encode_var_safe(buf, sizeof(buf),
1698 ++session->tx_rtag),
1699 buf);
1700 } else {
1701 memset(&block, 0, sizeof(block));
1702 }
1703
1704#if COAP_Q_BLOCK_SUPPORT
1705 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1706#endif /* COAP_Q_BLOCK_SUPPORT */
1707 {
1708 /* Need to check if we need to reset Q-Block to Block */
1709 uint8_t buf[4];
1710
1711 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1714 coap_encode_var_safe(buf, sizeof(buf),
1715 (block.num << 4) | (0 << 3) | block.szx),
1716 buf);
1717 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1718 /* Need to update associated lg_xmit */
1719 coap_lg_xmit_t *lg_xmit;
1720
1721 LL_FOREACH(session->lg_xmit, lg_xmit) {
1722 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1723 lg_xmit->b.b1.app_token &&
1724 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1725 /* Update the skeletal PDU with the block1 option */
1728 coap_encode_var_safe(buf, sizeof(buf),
1729 (block.num << 4) | (0 << 3) | block.szx),
1730 buf);
1731 break;
1732 }
1733 }
1734 }
1735 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1738 coap_encode_var_safe(buf, sizeof(buf),
1739 (block.num << 4) | (block.m << 3) | block.szx),
1740 buf);
1741 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1742 /* Need to update associated lg_xmit */
1743 coap_lg_xmit_t *lg_xmit;
1744
1745 LL_FOREACH(session->lg_xmit, lg_xmit) {
1746 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1747 lg_xmit->b.b1.app_token &&
1748 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1749 /* Update the skeletal PDU with the block1 option */
1752 coap_encode_var_safe(buf, sizeof(buf),
1753 (block.num << 4) |
1754 (block.m << 3) |
1755 block.szx),
1756 buf);
1757 /* Update as this is a Request */
1758 lg_xmit->option = COAP_OPTION_BLOCK1;
1759 break;
1760 }
1761 }
1762 }
1763 }
1764
1765#if COAP_Q_BLOCK_SUPPORT
1766 if (COAP_PDU_IS_REQUEST(pdu) &&
1767 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1768 if (block.num == 0 && block.m == 0) {
1769 uint8_t buf[4];
1770
1771 /* M needs to be set as asking for all the blocks */
1773 coap_encode_var_safe(buf, sizeof(buf),
1774 (0 << 4) | (1 << 3) | block.szx),
1775 buf);
1776 }
1777 }
1778#endif /* COAP_Q_BLOCK_SUPPORT */
1779
1780 /*
1781 * If type is CON and protocol is not reliable, there is no need to set up
1782 * lg_crcv here as it can be built up based on sent PDU if there is a
1783 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1784 * (Q-)Block1.
1785 */
1786 if (coap_check_send_need_lg_crcv(session, pdu)) {
1787 coap_lg_xmit_t *lg_xmit = NULL;
1788
1789 if (!session->lg_xmit && have_block1) {
1790 coap_log_debug("PDU presented by app\n");
1792 }
1793 /* See if this token is already in use for large body responses */
1794 LL_FOREACH(session->lg_crcv, lg_crcv) {
1795 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1796 /* Need to terminate and clean up previous response setup */
1797 LL_DELETE(session->lg_crcv, lg_crcv);
1798 coap_block_delete_lg_crcv(session, lg_crcv);
1799 break;
1800 }
1801 }
1802
1803 if (have_block1 && session->lg_xmit) {
1804 LL_FOREACH(session->lg_xmit, lg_xmit) {
1805 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1806 lg_xmit->b.b1.app_token &&
1807 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1808 break;
1809 }
1810 }
1811 }
1812 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1813 if (lg_crcv == NULL) {
1814 goto error;
1815 }
1816 if (lg_xmit) {
1817 /* Need to update the token as set up in the session->lg_xmit */
1818 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1819 }
1820 }
1821 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1822 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1823
1824#if COAP_Q_BLOCK_SUPPORT
1825 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1826 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1827 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1828 } else
1829#endif /* COAP_Q_BLOCK_SUPPORT */
1830 mid = coap_send_internal(session, pdu, NULL);
1831#else /* !COAP_CLIENT_SUPPORT */
1832 mid = coap_send_internal(session, pdu, NULL);
1833#endif /* !COAP_CLIENT_SUPPORT */
1834#if COAP_CLIENT_SUPPORT
1835 if (lg_crcv) {
1836 if (mid != COAP_INVALID_MID) {
1837 LL_PREPEND(session->lg_crcv, lg_crcv);
1838 } else {
1839 coap_block_delete_lg_crcv(session, lg_crcv);
1840 }
1841 }
1842#endif /* COAP_CLIENT_SUPPORT */
1843 return mid;
1844
1845error:
1847 return COAP_INVALID_MID;
1848}
1849
1850#if COAP_SERVER_SUPPORT
1851static int
1852coap_pdu_cksum(const coap_pdu_t *pdu, coap_digest_t *digest_buffer) {
1853 coap_digest_ctx_t *digest_ctx = coap_digest_setup();
1854
1855 if (!digest_ctx || !pdu) {
1856 goto fail;
1857 }
1858 if (pdu->used_size && pdu->token) {
1859 if (!coap_digest_update(digest_ctx, pdu->token, pdu->used_size)) {
1860 goto fail;
1861 }
1862 }
1863 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->type, sizeof(pdu->type))) {
1864 goto fail;
1865 }
1866 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->code, sizeof(pdu->code))) {
1867 goto fail;
1868 }
1869 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->mid, sizeof(pdu->mid))) {
1870 goto fail;
1871 }
1872 if (!coap_digest_final(digest_ctx, digest_buffer))
1873 return 0;
1874
1875 return 1;
1876
1877fail:
1878 coap_digest_free(digest_ctx);
1879 return 0;
1880}
1881#endif /* COAP_SERVER_SUPPORT */
1882
1885 uint8_t r;
1886 ssize_t bytes_written;
1887 coap_opt_iterator_t opt_iter;
1888
1889#if ! COAP_SERVER_SUPPORT
1890 (void)request_pdu;
1891#endif /* COAP_SERVER_SUPPORT */
1892 pdu->session = session;
1893#if COAP_CLIENT_SUPPORT
1894 if (session->session_failed) {
1895 coap_session_reconnect(session);
1896 if (session->session_failed)
1897 goto error;
1898 }
1899#endif /* COAP_CLIENT_SUPPORT */
1900#if COAP_PROXY_SUPPORT
1901 if (session->server_list) {
1902 /* Local session wanting to use proxy logic */
1903 return coap_proxy_local_write(session, pdu);
1904 }
1905#endif /* COAP_PROXY_SUPPORT */
1906 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1907 /*
1908 * Need to prepend our IP identifier to the data as per
1909 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1910 */
1911 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1912 coap_opt_t *opt;
1913 size_t hop_limit;
1914
1915 addr_str[sizeof(addr_str)-1] = '\000';
1916 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1917 sizeof(addr_str) - 1)) {
1918 char *cp;
1919 size_t len;
1920
1921 if (addr_str[0] == '[') {
1922 cp = strchr(addr_str, ']');
1923 if (cp)
1924 *cp = '\000';
1925 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1926 /* IPv4 embedded into IPv6 */
1927 cp = &addr_str[8];
1928 } else {
1929 cp = &addr_str[1];
1930 }
1931 } else {
1932 cp = strchr(addr_str, ':');
1933 if (cp)
1934 *cp = '\000';
1935 cp = addr_str;
1936 }
1937 len = strlen(cp);
1938
1939 /* See if Hop Limit option is being used in return path */
1940 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1941 if (opt) {
1942 uint8_t buf[4];
1943
1944 hop_limit =
1946 if (hop_limit == 1) {
1947 coap_log_warn("Proxy loop detected '%s'\n",
1948 (char *)pdu->data);
1951 } else if (hop_limit < 1 || hop_limit > 255) {
1952 /* Something is bad - need to drop this pdu (TODO or delete option) */
1953 coap_log_warn("Proxy return has bad hop limit count '%" PRIuS "'\n",
1954 hop_limit);
1957 }
1958 hop_limit--;
1960 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1961 buf);
1962 }
1963
1964 /* Need to check that we are not seeing this proxy in the return loop */
1965 if (pdu->data && opt == NULL) {
1966 char *a_match;
1967 size_t data_len;
1968
1969 if (pdu->used_size + 1 > pdu->max_size) {
1970 /* No space */
1973 }
1974 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1975 /* Internal error */
1978 }
1979 data_len = pdu->used_size - (pdu->data - pdu->token);
1980 pdu->data[data_len] = '\000';
1981 a_match = strstr((char *)pdu->data, cp);
1982 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1983 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1984 a_match[len] == ' ')) {
1985 coap_log_warn("Proxy loop detected '%s'\n",
1986 (char *)pdu->data);
1989 }
1990 }
1991 if (pdu->used_size + len + 1 <= pdu->max_size) {
1992 size_t old_size = pdu->used_size;
1993 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1994 if (pdu->data == NULL) {
1995 /*
1996 * Set Hop Limit to max for return path. If this libcoap is in
1997 * a proxy loop path, it will always decrement hop limit in code
1998 * above and hence timeout / drop the response as appropriate
1999 */
2000 hop_limit = 255;
2002 (uint8_t *)&hop_limit);
2003 coap_add_data(pdu, len, (uint8_t *)cp);
2004 } else {
2005 /* prepend with space separator, leaving hop limit "as is" */
2006 memmove(pdu->data + len + 1, pdu->data,
2007 old_size - (pdu->data - pdu->token));
2008 memcpy(pdu->data, cp, len);
2009 pdu->data[len] = ' ';
2010 pdu->used_size += len + 1;
2011 }
2012 }
2013 }
2014 }
2015 }
2016
2017 if (session->echo) {
2018 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
2019 session->echo->s))
2020 goto error;
2021 coap_delete_bin_const(session->echo);
2022 session->echo = NULL;
2023 }
2024#if COAP_OSCORE_SUPPORT
2025 if (session->oscore_encryption) {
2026 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
2028 goto error;
2029 }
2030#endif /* COAP_OSCORE_SUPPORT */
2031
2032 if (!coap_pdu_encode_header(pdu, session->proto)) {
2033 goto error;
2034 }
2035
2036#if !COAP_DISABLE_TCP
2037 if (COAP_PROTO_RELIABLE(session->proto) &&
2039 if (!session->csm_block_supported) {
2040 /*
2041 * Need to check that this instance is not sending any block options as
2042 * the remote end via CSM has not informed us that there is support
2043 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2044 * This includes potential BERT blocks.
2045 */
2046 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2047 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2048 }
2049 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2050 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2051 }
2052 } else if (!session->csm_bert_rem_support) {
2053 coap_opt_t *opt;
2054
2055 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2056 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2057 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2058 }
2059 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2060 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2061 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2062 }
2063 }
2064 }
2065#endif /* !COAP_DISABLE_TCP */
2066
2067#if COAP_OSCORE_SUPPORT
2068 if (session->oscore_encryption &&
2069 pdu->type != COAP_MESSAGE_RST &&
2070 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2071 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2072 /* Refactor PDU as appropriate RFC8613 */
2073 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2074
2075 if (osc_pdu == NULL) {
2076 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2079 goto error;
2080 }
2081 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2083 pdu = osc_pdu;
2084 } else
2085#endif /* COAP_OSCORE_SUPPORT */
2086 bytes_written = coap_send_pdu(session, pdu, NULL);
2087
2088#if COAP_SERVER_SUPPORT
2089 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
2090 session->cached_pdu != pdu &&
2091 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2092 COAP_PDU_IS_REQUEST(request_pdu) &&
2093 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2095 session->cached_pdu = pdu;
2097 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
2098 }
2099#endif /* COAP_SERVER_SUPPORT */
2100
2101 if (bytes_written == COAP_PDU_DELAYED) {
2102 /* do not free pdu as it is stored with session for later use */
2103 return pdu->mid;
2104 }
2105 if (bytes_written < 0) {
2107 goto error;
2108 }
2109
2110#if !COAP_DISABLE_TCP
2111 if (COAP_PROTO_RELIABLE(session->proto) &&
2112 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2113 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2114 session->partial_write = (size_t)bytes_written;
2115 /* do not free pdu as it is stored with session for later use */
2116 return pdu->mid;
2117 } else {
2118 goto error;
2119 }
2120 }
2121#endif /* !COAP_DISABLE_TCP */
2122
2123 if (pdu->type != COAP_MESSAGE_CON
2124 || COAP_PROTO_RELIABLE(session->proto)) {
2125 coap_mid_t id = pdu->mid;
2127 return id;
2128 }
2129
2130 coap_queue_t *node = coap_new_node();
2131 if (!node) {
2132 coap_log_debug("coap_wait_ack: insufficient memory\n");
2133 goto error;
2134 }
2135
2136 node->id = pdu->mid;
2137 node->pdu = pdu;
2138 coap_prng_lkd(&r, sizeof(r));
2139 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2140 node->timeout = coap_calc_timeout(session, r);
2141 return coap_wait_ack(session->context, session, node);
2142error:
2144 return COAP_INVALID_MID;
2145}
2146
2147static int send_recv_terminate = 0;
2148
2149void
2153
2154COAP_API int
2156 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2157 int ret;
2158
2159 coap_lock_lock(return 0);
2160 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2162 return ret;
2163}
2164
2165/*
2166 * Return 0 or +ve Time in function in ms after successful transfer
2167 * -1 Invalid timeout parameter
2168 * -2 Failed to transmit PDU
2169 * -3 Nack or Event handler invoked, cancelling request
2170 * -4 coap_io_process returned error (fail to re-lock or select())
2171 * -5 Response not received in the given time
2172 * -6 Terminated by user
2173 * -7 Client mode code not enabled
2174 */
2175int
2177 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2178#if COAP_CLIENT_SUPPORT
2180 uint32_t rem_timeout = timeout_ms;
2181 uint32_t block_mode = session->block_mode;
2182 int ret = 0;
2183 coap_tick_t now;
2184 coap_tick_t start;
2185 coap_tick_t ticks_so_far;
2186 uint32_t time_so_far_ms;
2187
2188 coap_ticks(&start);
2189 assert(request_pdu);
2190
2192
2193 session->resp_pdu = NULL;
2194 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2195 request_pdu->actual_token.length);
2196
2197 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2198 ret = -1;
2199 goto fail;
2200 }
2201 if (session->state == COAP_SESSION_STATE_NONE) {
2202 ret = -3;
2203 goto fail;
2204 }
2205
2207 if (coap_is_mcast(&session->addr_info.remote))
2208 block_mode = session->block_mode;
2209
2210 session->doing_send_recv = 1;
2211 /* So the user needs to delete the PDU */
2212 coap_pdu_reference_lkd(request_pdu);
2213 mid = coap_send_lkd(session, request_pdu);
2214 if (mid == COAP_INVALID_MID) {
2215 if (!session->doing_send_recv)
2216 ret = -3;
2217 else
2218 ret = -2;
2219 goto fail;
2220 }
2221
2222 /* Wait for the response to come in */
2223 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2224 if (send_recv_terminate) {
2225 ret = -6;
2226 goto fail;
2227 }
2228 ret = coap_io_process_lkd(session->context, rem_timeout);
2229 if (ret < 0) {
2230 ret = -4;
2231 goto fail;
2232 }
2233 /* timeout_ms is for timeout between specific request and response */
2234 coap_ticks(&now);
2235 ticks_so_far = now - session->last_rx_tx;
2236 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2237 if (time_so_far_ms >= timeout_ms) {
2238 rem_timeout = 0;
2239 } else {
2240 rem_timeout = timeout_ms - time_so_far_ms;
2241 }
2242 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2243 /* To pick up on (D)TLS setup issues */
2244 coap_ticks(&now);
2245 ticks_so_far = now - start;
2246 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2247 if (time_so_far_ms >= timeout_ms) {
2248 rem_timeout = 0;
2249 } else {
2250 rem_timeout = timeout_ms - time_so_far_ms;
2251 }
2252 }
2253 }
2254
2255 if (rem_timeout) {
2256 coap_ticks(&now);
2257 ticks_so_far = now - start;
2258 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2259 ret = time_so_far_ms;
2260 /* Give PDU to user who will be calling coap_delete_pdu() */
2261 *response_pdu = session->resp_pdu;
2262 session->resp_pdu = NULL;
2263 if (*response_pdu == NULL) {
2264 ret = -3;
2265 }
2266 } else {
2267 /* If there is a resp_pdu, it will get cleared below */
2268 ret = -5;
2269 }
2270
2271fail:
2272 session->block_mode = block_mode;
2273 session->doing_send_recv = 0;
2274 /* delete referenced copy */
2275 coap_delete_pdu_lkd(session->resp_pdu);
2276 session->resp_pdu = NULL;
2278 session->req_token = NULL;
2279 return ret;
2280
2281#else /* !COAP_CLIENT_SUPPORT */
2282
2283 (void)session;
2284 (void)timeout_ms;
2285 (void)request_pdu;
2286 coap_log_warn("coap_send_recv: Client mode not supported\n");
2287 *response_pdu = NULL;
2288 return -7;
2289
2290#endif /* ! COAP_CLIENT_SUPPORT */
2291}
2292
2295 if (!context || !node || !node->session)
2296 return COAP_INVALID_MID;
2297
2298#if COAP_CLIENT_SUPPORT
2299 if (node->session->session_failed) {
2300 /* Force failure */
2301 node->retransmit_cnt = (unsigned char)node->session->max_retransmit;
2302 }
2303#endif /* COAP_CLIENT_SUPPORT */
2304
2305 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2306 if (node->retransmit_cnt < node->session->max_retransmit) {
2307 ssize_t bytes_written;
2308 coap_tick_t now;
2309 coap_tick_t next_delay;
2310 coap_address_t remote;
2311
2312 node->retransmit_cnt++;
2314
2315 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2316 if (context->ping_timeout &&
2317 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2318 uint8_t byte;
2319
2320 coap_prng_lkd(&byte, sizeof(byte));
2321 /* Don't exceed the ping timeout value */
2322 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2323 }
2324
2325 coap_ticks(&now);
2326 if (context->sendqueue == NULL) {
2327 node->t = next_delay;
2328 context->sendqueue_basetime = now;
2329 } else {
2330 /* make node->t relative to context->sendqueue_basetime */
2331 node->t = (now - context->sendqueue_basetime) + next_delay;
2332 }
2333 coap_insert_node(&context->sendqueue, node);
2334 coap_address_copy(&remote, &node->session->addr_info.remote);
2336
2337 if (node->is_mcast) {
2338 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2339 coap_session_str(node->session), node->id);
2340 } else {
2341 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2342 coap_session_str(node->session), node->id,
2343 node->retransmit_cnt,
2344 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2345 }
2346
2347 if (node->session->con_active)
2348 node->session->con_active--;
2349 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2350
2351 if (bytes_written == COAP_PDU_DELAYED) {
2352 /* PDU was not retransmitted immediately because a new handshake is
2353 in progress. node was moved to the send queue of the session. */
2354 return node->id;
2355 }
2356
2357 coap_address_copy(&node->session->addr_info.remote, &remote);
2358 if (node->is_mcast) {
2361 return COAP_INVALID_MID;
2362 }
2363
2364 if (bytes_written < 0)
2365 return (int)bytes_written;
2366
2367 return node->id;
2368 }
2369
2370#if COAP_CLIENT_SUPPORT
2371 if (node->session->session_failed) {
2372 coap_log_info("** %s: mid=0x%04x: deleted due to reconnection issue\n",
2373 coap_session_str(node->session), node->id);
2374 } else {
2375#endif /* COAP_CLIENT_SUPPORT */
2376 /* no more retransmissions, remove node from system */
2377 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2378 coap_session_str(node->session), node->id, node->retransmit_cnt);
2379#if COAP_CLIENT_SUPPORT
2380 }
2381#endif /* COAP_CLIENT_SUPPORT */
2382
2383#if COAP_SERVER_SUPPORT
2384 /* Check if subscriptions exist that should be canceled after
2385 COAP_OBS_MAX_FAIL */
2386 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2387 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2388 if (context->ping_timeout) {
2391 return COAP_INVALID_MID;
2392 } else {
2393 if (node->session->ref_subscriptions)
2394 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2395#if COAP_PROXY_SUPPORT
2396 /* Need to check is there is a proxy subscription active and delete it */
2397 if (node->session->ref_proxy_subs)
2398 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2399 0, COAP_PROXY_SUBS_TOKEN);
2400#endif /* COAP_PROXY_SUPPORT */
2401 }
2402 }
2403#endif /* COAP_SERVER_SUPPORT */
2404 if (node->session->con_active) {
2405 node->session->con_active--;
2407 /*
2408 * As there may be another CON in a different queue entry on the same
2409 * session that needs to be immediately released,
2410 * coap_session_connected() is called.
2411 * However, there is the possibility coap_wait_ack() may be called for
2412 * this node (queue) and re-added to context->sendqueue.
2413 * coap_delete_node_lkd(node) called shortly will handle this and
2414 * remove it.
2415 */
2417 }
2418 }
2419
2420 if (node->pdu->type == COAP_MESSAGE_CON) {
2422 }
2423#if COAP_CLIENT_SUPPORT
2424 node->session->doing_send_recv = 0;
2425#endif /* COAP_CLIENT_SUPPORT */
2426 /* And finally delete the node */
2428 return COAP_INVALID_MID;
2429}
2430
2431static int
2433 uint8_t *data;
2434 size_t data_len;
2435 int result = -1;
2436
2437 coap_packet_get_memmapped(packet, &data, &data_len);
2438 if (session->proto == COAP_PROTO_DTLS) {
2439#if COAP_SERVER_SUPPORT
2440 if (session->type == COAP_SESSION_TYPE_HELLO)
2441 result = coap_dtls_hello(session, data, data_len);
2442 else
2443#endif /* COAP_SERVER_SUPPORT */
2444 if (session->tls)
2445 result = coap_dtls_receive(session, data, data_len);
2446 } else if (session->proto == COAP_PROTO_UDP) {
2447 result = coap_handle_dgram(ctx, session, data, data_len);
2448 }
2449 return result;
2450}
2451
2452#if COAP_CLIENT_SUPPORT
2453void
2455#if COAP_DISABLE_TCP
2456 (void)now;
2457
2459#else /* !COAP_DISABLE_TCP */
2460 if (coap_netif_strm_connect2(session)) {
2461 session->last_rx_tx = now;
2463 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2464 } else {
2467 }
2468#endif /* !COAP_DISABLE_TCP */
2469}
2470#endif /* COAP_CLIENT_SUPPORT */
2471
2472static void
2474 (void)ctx;
2475 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2476
2477 while (session->delayqueue) {
2478 ssize_t bytes_written;
2479 coap_queue_t *q = session->delayqueue;
2480
2481 coap_address_copy(&session->addr_info.remote, &q->remote);
2482 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2483 coap_session_str(session), (int)q->pdu->mid);
2484 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2485 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2486 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2487 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2488 if (bytes_written > 0)
2489 session->last_rx_tx = now;
2490 if (bytes_written <= 0 ||
2491 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2492 if (bytes_written > 0)
2493 session->partial_write += (size_t)bytes_written;
2494 break;
2495 }
2496 session->delayqueue = q->next;
2497 session->partial_write = 0;
2499 }
2500}
2501
2502void
2504#if COAP_CONSTRAINED_STACK
2505 /* payload and packet can be protected by global_lock if needed */
2506 static unsigned char payload[COAP_RXBUFFER_SIZE];
2507 static coap_packet_t s_packet;
2508#else /* ! COAP_CONSTRAINED_STACK */
2509 unsigned char payload[COAP_RXBUFFER_SIZE];
2510 coap_packet_t s_packet;
2511#endif /* ! COAP_CONSTRAINED_STACK */
2512 coap_packet_t *packet = &s_packet;
2513
2515
2516 packet->length = sizeof(payload);
2517 packet->payload = payload;
2518
2519 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2520 ssize_t bytes_read;
2521 coap_address_t remote;
2522
2523 coap_address_copy(&remote, &session->addr_info.remote);
2524 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2525 bytes_read = coap_netif_dgrm_read(session, packet);
2526
2527 if (bytes_read < 0) {
2528 if (bytes_read == -2) {
2529 coap_address_copy(&session->addr_info.remote, &remote);
2530 /* Reset the session back to startup defaults */
2532 }
2533 } else if (bytes_read > 0) {
2534 session->last_rx_tx = now;
2535#if COAP_CLIENT_SUPPORT
2536 if (session->session_failed) {
2537 session->session_failed = 0;
2539 }
2540#endif /* COAP_CLIENT_SUPPORT */
2541 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2542 coap_handle_dgram_for_proto(ctx, session, packet);
2543 } else {
2544 coap_address_copy(&session->addr_info.remote, &remote);
2545 }
2546#if !COAP_DISABLE_TCP
2547 } else if (session->proto == COAP_PROTO_WS ||
2548 session->proto == COAP_PROTO_WSS) {
2549 ssize_t bytes_read = 0;
2550
2551 /* WebSocket layer passes us the whole packet */
2552 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2553 packet->payload,
2554 packet->length);
2555 if (bytes_read < 0) {
2557 } else if (bytes_read > 2) {
2558 coap_pdu_t *pdu;
2559
2560 session->last_rx_tx = now;
2561 /* Need max space incase PDU is updated with updated token etc. */
2562 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2563 if (!pdu) {
2564 return;
2565 }
2566
2567 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2569 coap_log_warn("discard malformed PDU\n");
2571 return;
2572 }
2573
2574 coap_dispatch(ctx, session, pdu);
2576 return;
2577 }
2578 } else {
2579 ssize_t bytes_read = 0;
2580 const uint8_t *p;
2581 int retry;
2582
2583 do {
2584 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2585 packet->payload,
2586 packet->length);
2587 if (bytes_read > 0) {
2588 session->last_rx_tx = now;
2589 }
2590 p = packet->payload;
2591 retry = bytes_read == (ssize_t)packet->length;
2592 while (bytes_read > 0) {
2593 if (session->partial_pdu) {
2594 size_t len = session->partial_pdu->used_size
2595 + session->partial_pdu->hdr_size
2596 - session->partial_read;
2597 size_t n = min(len, (size_t)bytes_read);
2598 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2599 + session->partial_read, p, n);
2600 p += n;
2601 bytes_read -= n;
2602 if (n == len) {
2603 coap_opt_filter_t error_opts;
2604 coap_pdu_t *pdu = session->partial_pdu;
2605
2606 session->partial_pdu = NULL;
2607 session->partial_read = 0;
2608
2609 coap_option_filter_clear(&error_opts);
2610 if (coap_pdu_parse_header(pdu, session->proto)
2611 && coap_pdu_parse_opt(pdu, &error_opts)) {
2612 coap_dispatch(ctx, session, pdu);
2613 } else if (error_opts.mask) {
2614 coap_pdu_t *response =
2616 COAP_RESPONSE_CODE(402), &error_opts);
2617 if (!response) {
2618 coap_log_warn("coap_read_session: cannot create error response\n");
2619 } else {
2620 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2621 coap_log_warn("coap_read_session: error sending response\n");
2622 }
2623 }
2625 } else {
2626 session->partial_read += n;
2627 }
2628 } else if (session->partial_read > 0) {
2629 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2630 session->read_header);
2631 size_t tkl = session->read_header[0] & 0x0f;
2632 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2633 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2634 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2635 size_t n = min(len, (size_t)bytes_read);
2636 memcpy(session->read_header + session->partial_read, p, n);
2637 p += n;
2638 bytes_read -= n;
2639 if (n == len) {
2640 /* Header now all in */
2641 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2642 hdr_size + tok_ext_bytes);
2643 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2644 coap_log_warn("** %s: incoming PDU length too large (%" PRIuS " > %lu)\n",
2645 coap_session_str(session),
2646 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2647 bytes_read = -1;
2648 break;
2649 }
2650 /* Need max space incase PDU is updated with updated token etc. */
2651 session->partial_pdu = coap_pdu_init(0, 0, 0,
2653 if (session->partial_pdu == NULL) {
2654 bytes_read = -1;
2655 break;
2656 }
2657 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2658 bytes_read = -1;
2659 break;
2660 }
2661 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2662 session->partial_pdu->used_size = size;
2663 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2664 session->partial_read = hdr_size + tok_ext_bytes;
2665 if (size == 0) {
2666 coap_pdu_t *pdu = session->partial_pdu;
2667
2668 session->partial_pdu = NULL;
2669 session->partial_read = 0;
2670 if (coap_pdu_parse_header(pdu, session->proto)) {
2671 coap_dispatch(ctx, session, pdu);
2672 }
2674 }
2675 } else {
2676 /* More of the header to go */
2677 session->partial_read += n;
2678 }
2679 } else {
2680 /* Get in first byte of the header */
2681 session->read_header[0] = *p++;
2682 bytes_read -= 1;
2683 if (!coap_pdu_parse_header_size(session->proto,
2684 session->read_header)) {
2685 bytes_read = -1;
2686 break;
2687 }
2688 session->partial_read = 1;
2689 }
2690 }
2691 } while (bytes_read == 0 && retry);
2692 if (bytes_read < 0)
2694#endif /* !COAP_DISABLE_TCP */
2695 }
2696}
2697
2698#if COAP_SERVER_SUPPORT
2699static int
2700coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2701 ssize_t bytes_read = -1;
2702 int result = -1; /* the value to be returned */
2703#if COAP_CONSTRAINED_STACK
2704 /* payload and e_packet can be protected by global_lock if needed */
2705 static unsigned char payload[COAP_RXBUFFER_SIZE];
2706 static coap_packet_t e_packet;
2707#else /* ! COAP_CONSTRAINED_STACK */
2708 unsigned char payload[COAP_RXBUFFER_SIZE];
2709 coap_packet_t e_packet;
2710#endif /* ! COAP_CONSTRAINED_STACK */
2711 coap_packet_t *packet = &e_packet;
2712
2713 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2714 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2715
2716 /* Need to do this as there may be holes in addr_info */
2717 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2718 packet->length = sizeof(payload);
2719 packet->payload = payload;
2721 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2722
2723 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2724 if (bytes_read < 0) {
2725 if (errno != EAGAIN) {
2726 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2727 }
2728 } else if (bytes_read > 0) {
2729 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2730 if (session) {
2732 coap_log_debug("* %s: netif: recv %4" PRIdS " bytes\n",
2733 coap_session_str(session), bytes_read);
2734 result = coap_handle_dgram_for_proto(ctx, session, packet);
2735 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2736 coap_session_new_dtls_session(session, now);
2737 coap_session_release_lkd(session);
2738 }
2739 }
2740 return result;
2741}
2742
2743static int
2744coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2745 (void)ctx;
2746 (void)endpoint;
2747 (void)now;
2748 return 0;
2749}
2750
2751#if !COAP_DISABLE_TCP
2752static int
2753coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2754 coap_tick_t now, void *extra) {
2755 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2756 if (session)
2757 session->last_rx_tx = now;
2758 return session != NULL;
2759}
2760#endif /* !COAP_DISABLE_TCP */
2761#endif /* COAP_SERVER_SUPPORT */
2762
2763COAP_API void
2765 coap_lock_lock(return);
2766 coap_io_do_io_lkd(ctx, now);
2768}
2769
2770void
2772#ifdef COAP_EPOLL_SUPPORT
2773 (void)ctx;
2774 (void)now;
2775 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2776#else /* ! COAP_EPOLL_SUPPORT */
2777 coap_session_t *s, *rtmp;
2778
2780#if COAP_SERVER_SUPPORT
2781 coap_endpoint_t *ep, *tmp;
2782 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2783 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2784 coap_read_endpoint(ctx, ep, now);
2785 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2786 coap_write_endpoint(ctx, ep, now);
2787#if !COAP_DISABLE_TCP
2788 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2789 coap_accept_endpoint(ctx, ep, now, NULL);
2790#endif /* !COAP_DISABLE_TCP */
2791 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2792 /* Make sure the session object is not deleted in one of the callbacks */
2794#if COAP_CLIENT_SUPPORT
2795 if (s->client_initiated && (s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2796 coap_connect_session(s, now);
2797 }
2798#endif /* COAP_CLIENT_SUPPORT */
2799 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2800 coap_read_session(ctx, s, now);
2801 }
2802 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2803 coap_write_session(ctx, s, now);
2804 }
2806 }
2807 }
2808#endif /* COAP_SERVER_SUPPORT */
2809
2810#if COAP_CLIENT_SUPPORT
2811 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2812 /* Make sure the session object is not deleted in one of the callbacks */
2814 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2815 coap_connect_session(s, now);
2816 }
2817 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2818 coap_read_session(ctx, s, now);
2819 }
2820 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2821 coap_write_session(ctx, s, now);
2822 }
2824 }
2825#endif /* COAP_CLIENT_SUPPORT */
2826#endif /* ! COAP_EPOLL_SUPPORT */
2827}
2828
2829COAP_API void
2830coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2831 coap_lock_lock(return);
2832 coap_io_do_epoll_lkd(ctx, events, nevents);
2834}
2835
2836/*
2837 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2838 * directly saves having to iterate through the endpoints / sessions.
2839 */
2840void
2841coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2842#ifndef COAP_EPOLL_SUPPORT
2843 (void)ctx;
2844 (void)events;
2845 (void)nevents;
2846 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2847#else /* COAP_EPOLL_SUPPORT */
2848 coap_tick_t now;
2849 size_t j;
2850
2852 coap_ticks(&now);
2853 for (j = 0; j < nevents; j++) {
2854 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2855
2856 /* Ignore 'timer trigger' ptr which is NULL */
2857 if (sock) {
2858#if COAP_SERVER_SUPPORT
2859 if (sock->endpoint) {
2860 coap_endpoint_t *endpoint = sock->endpoint;
2861 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2862 (events[j].events & EPOLLIN)) {
2863 sock->flags |= COAP_SOCKET_CAN_READ;
2864 coap_read_endpoint(endpoint->context, endpoint, now);
2865 }
2866
2867 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2868 (events[j].events & EPOLLOUT)) {
2869 /*
2870 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2871 * be true causing epoll_wait to return early
2872 */
2873 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2875 coap_write_endpoint(endpoint->context, endpoint, now);
2876 }
2877
2878#if !COAP_DISABLE_TCP
2879 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2880 (events[j].events & EPOLLIN)) {
2882 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2883 }
2884#endif /* !COAP_DISABLE_TCP */
2885
2886 } else
2887#endif /* COAP_SERVER_SUPPORT */
2888 if (sock->session) {
2889 coap_session_t *session = sock->session;
2890
2891 /* Make sure the session object is not deleted
2892 in one of the callbacks */
2894#if COAP_CLIENT_SUPPORT
2895 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2896 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2898 coap_connect_session(session, now);
2899 if (coap_netif_available(session) &&
2900 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2901 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2902 }
2903 }
2904#endif /* COAP_CLIENT_SUPPORT */
2905
2906 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2907 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2908 sock->flags |= COAP_SOCKET_CAN_READ;
2909 coap_read_session(session->context, session, now);
2910 }
2911
2912 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2913 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2914 /*
2915 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2916 * be true causing epoll_wait to return early
2917 */
2918 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2920 coap_write_session(session->context, session, now);
2921 }
2922 /* Now dereference session so it can go away if needed */
2923 coap_session_release_lkd(session);
2924 }
2925 } else if (ctx->eptimerfd != -1) {
2926 /*
2927 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2928 * it so that it does not set EPOLLIN in the next epoll_wait().
2929 */
2930 uint64_t count;
2931
2932 /* Check the result from read() to suppress the warning on
2933 * systems that declare read() with warn_unused_result. */
2934 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2935 /* do nothing */;
2936 }
2937 }
2938 }
2939 /* And update eptimerfd as to when to next trigger */
2940 coap_ticks(&now);
2941 coap_io_prepare_epoll_lkd(ctx, now);
2942#endif /* COAP_EPOLL_SUPPORT */
2943}
2944
2945int
2947 uint8_t *msg, size_t msg_len) {
2948
2949 coap_pdu_t *pdu = NULL;
2950 coap_opt_filter_t error_opts;
2951
2952 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2953 if (msg_len < 4) {
2954 /* Minimum size of CoAP header - ignore runt */
2955 return -1;
2956 }
2957 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2958 /*
2959 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2960 * this MUST be silently ignored.
2961 */
2962 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2963 return -1;
2964 }
2965
2966 /* Need max space incase PDU is updated with updated token etc. */
2967 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2968 if (!pdu)
2969 goto error;
2970
2971 coap_option_filter_clear(&error_opts);
2972 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
2974 coap_log_warn("discard malformed PDU\n");
2975 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
2976 coap_pdu_t *response =
2978 COAP_RESPONSE_CODE(402), &error_opts);
2979 if (!response) {
2980 coap_log_warn("coap_handle_dgram: cannot create error response\n");
2981 } else {
2982 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2983 coap_log_warn("coap_handle_dgram: error sending response\n");
2984 }
2986 return -1;
2987 } else {
2988 goto error;
2989 }
2990 }
2991
2992 coap_dispatch(ctx, session, pdu);
2994 return 0;
2995
2996error:
2997 /*
2998 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2999 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
3000 */
3001 coap_send_rst_lkd(session, pdu);
3003 return -1;
3004}
3005
3006int
3008 coap_queue_t **node) {
3009 coap_queue_t *p, *q;
3010
3011 if (!queue || !*queue) {
3012 *node = NULL;
3013 return 0;
3014 }
3015
3016 /* replace queue head if PDU's time is less than head's time */
3017
3018 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
3019 *node = *queue;
3020 *queue = (*queue)->next;
3021 if (*queue) { /* adjust relative time of new queue head */
3022 (*queue)->t += (*node)->t;
3023 }
3024 (*node)->next = NULL;
3025 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
3026 coap_session_str(session), id);
3027 return 1;
3028 }
3029
3030 /* search message id in queue to remove (only first occurence will be removed) */
3031 q = *queue;
3032 do {
3033 p = q;
3034 q = q->next;
3035 } while (q && (session != q->session || id != q->id));
3036
3037 if (q) { /* found message id */
3038 p->next = q->next;
3039 if (p->next) { /* must update relative time of p->next */
3040 p->next->t += q->t;
3041 }
3042 q->next = NULL;
3043 *node = q;
3044 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
3045 coap_session_str(session), id);
3046 return 1;
3047 }
3048
3049 *node = NULL;
3050 return 0;
3051
3052}
3053
3054static int
3056 coap_bin_const_t *token, coap_queue_t **node) {
3057 coap_queue_t *p, *q;
3058
3059 if (!queue || !*queue)
3060 return 0;
3061
3062 /* replace queue head if PDU's time is less than head's time */
3063
3064 if (session == (*queue)->session &&
3065 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
3066 *node = *queue;
3067 *queue = (*queue)->next;
3068 if (*queue) { /* adjust relative time of new queue head */
3069 (*queue)->t += (*node)->t;
3070 }
3071 (*node)->next = NULL;
3072 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3073 coap_session_str(session), (*node)->id);
3074 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3075 session->con_active--;
3076 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3077 /* Flush out any entries on session->delayqueue */
3078 coap_session_connected(session);
3079 }
3080 return 1;
3081 }
3082
3083 /* search token in queue to remove (only first occurence will be removed) */
3084 q = *queue;
3085 do {
3086 p = q;
3087 q = q->next;
3088 } while (q && (session != q->session ||
3089 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3090
3091 if (q) { /* found token */
3092 p->next = q->next;
3093 if (p->next) { /* must update relative time of p->next */
3094 p->next->t += q->t;
3095 }
3096 q->next = NULL;
3097 *node = q;
3098 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3099 coap_session_str(session), (*node)->id);
3100 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3101 session->con_active--;
3102 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3103 /* Flush out any entries on session->delayqueue */
3104 coap_session_connected(session);
3105 }
3106 return 1;
3107 }
3108
3109 return 0;
3110
3111}
3112
3113void
3115 coap_nack_reason_t reason) {
3116 coap_queue_t *p, *q;
3117
3118 while (context->sendqueue && context->sendqueue->session == session) {
3119 q = context->sendqueue;
3120 context->sendqueue = q->next;
3121 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3122 coap_session_str(session), q->id);
3123 if (q->pdu->type == COAP_MESSAGE_CON) {
3124 coap_handle_nack(session, q->pdu, reason, q->id);
3125 }
3127 }
3128
3129 if (!context->sendqueue)
3130 return;
3131
3132 p = context->sendqueue;
3133 q = p->next;
3134
3135 while (q) {
3136 if (q->session == session) {
3137 p->next = q->next;
3138 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3139 coap_session_str(session), q->id);
3140 if (q->pdu->type == COAP_MESSAGE_CON) {
3141 coap_handle_nack(session, q->pdu, reason, q->id);
3142 }
3144 q = p->next;
3145 } else {
3146 p = q;
3147 q = q->next;
3148 }
3149 }
3150}
3151
3152void
3154 coap_bin_const_t *token) {
3155 /* cancel all messages in sendqueue that belong to session
3156 * and use the specified token */
3157 coap_queue_t **p, *q;
3158
3159 if (!context->sendqueue)
3160 return;
3161
3162 p = &context->sendqueue;
3163 q = *p;
3164
3165 while (q) {
3166 if (q->session == session &&
3167 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3168 *p = q->next;
3169 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3170 coap_session_str(session), q->id);
3171 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3172 session->con_active--;
3173 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3174 /* Flush out any entries on session->delayqueue */
3175 coap_session_connected(session);
3176 }
3178 } else {
3179 p = &(q->next);
3180 }
3181 q = *p;
3182 }
3183}
3184
3185coap_pdu_t *
3187 coap_opt_filter_t *opts) {
3188 coap_opt_iterator_t opt_iter;
3189 coap_pdu_t *response;
3190 unsigned char type;
3191
3192#if COAP_ERROR_PHRASE_LENGTH > 0
3193 const char *phrase;
3194 if (code != COAP_RESPONSE_CODE(508)) {
3195 phrase = coap_response_phrase(code);
3196 } else {
3197 phrase = NULL;
3198 }
3199#endif
3200
3201 assert(request);
3202
3203 /* cannot send ACK if original request was not confirmable */
3204 type = request->type == COAP_MESSAGE_CON ?
3206
3207 /* Now create the response and fill with options and payload data. */
3208 response = coap_pdu_init(type, code, request->mid,
3209 request->session ?
3210 coap_session_max_pdu_size_lkd(request->session) : 512);
3211 if (response) {
3212 /* copy token */
3213 if (!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) {
3544 coap_method_handler_t h = NULL;
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 &&
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
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 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3861 if (opt == NULL) {
3862 /* RFC 8132 2.3.1 */
3863 resp = 415;
3864 goto fail_response;
3865 }
3866 }
3867 if (context->mcast_per_resource &&
3868 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3869 coap_is_mcast(&session->addr_info.local)) {
3870 resp = 405;
3871 goto fail_response;
3872 }
3873
3874 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3876 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3877 if (!response) {
3878 coap_log_err("could not create response PDU\n");
3879 resp = 500;
3880 goto fail_response;
3881 }
3882 response->session = session;
3883#if COAP_ASYNC_SUPPORT
3884 /* If handling a separate response, need CON, not ACK response */
3885 if (async && pdu->type == COAP_MESSAGE_CON)
3886 response->type = COAP_MESSAGE_CON;
3887#endif /* COAP_ASYNC_SUPPORT */
3888 /* A lot of the reliable code assumes type is CON */
3889 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3890 response->type = COAP_MESSAGE_CON;
3891
3892 if (!coap_add_token(response, pdu->actual_token.length,
3893 pdu->actual_token.s)) {
3894 resp = 500;
3895 goto fail_response;
3896 }
3897
3898 query = coap_get_query(pdu);
3899
3900 /* check for Observe option RFC7641 and RFC8132 */
3901 if (resource->observable &&
3902 (pdu->code == COAP_REQUEST_CODE_GET ||
3903 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3904 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3905 }
3906
3907 /*
3908 * See if blocks need to be aggregated or next requests sent off
3909 * before invoking application request handler
3910 */
3911 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3912 uint32_t block_mode = session->block_mode;
3913
3914 if (observe ||
3917 if (coap_handle_request_put_block(context, session, pdu, response,
3918 resource, uri_path, observe,
3919 &added_block, &free_lg_srcv)) {
3920 session->block_mode = block_mode;
3921 goto skip_handler;
3922 }
3923 session->block_mode = block_mode;
3924
3925 if (coap_handle_request_send_block(session, pdu, response, resource,
3926 query)) {
3927#if COAP_Q_BLOCK_SUPPORT
3928 lg_xmit_ctrl = 1;
3929#endif /* COAP_Q_BLOCK_SUPPORT */
3930 goto skip_handler;
3931 }
3932 }
3933
3934 if (observe) {
3935 observe_action =
3937 coap_opt_length(observe));
3938
3939 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3940 coap_subscription_t *subscription;
3941
3942 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3943 if (block.num != 0) {
3944 response->code = COAP_RESPONSE_CODE(400);
3945 goto skip_handler;
3946 }
3947#if COAP_Q_BLOCK_SUPPORT
3948 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3949 &block)) {
3950 if (block.num != 0) {
3951 response->code = COAP_RESPONSE_CODE(400);
3952 goto skip_handler;
3953 }
3954#endif /* COAP_Q_BLOCK_SUPPORT */
3955 }
3956 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3957 pdu);
3958 if (subscription) {
3959 uint8_t buf[4];
3960
3961 coap_touch_observer(context, session, &pdu->actual_token);
3963 coap_encode_var_safe(buf, sizeof(buf),
3964 resource->observe),
3965 buf);
3966 }
3967 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3968 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3969 } else {
3970 coap_log_info("observe: unexpected action %d\n", observe_action);
3971 }
3972 }
3973
3974 if ((resource == context->proxy_uri_resource ||
3975 (resource == context->unknown_resource &&
3976 context->unknown_resource->is_reverse_proxy)) &&
3977 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3978 pdu->type == COAP_MESSAGE_CON &&
3979 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
3980 /* Make the proxy response separate and fix response later */
3981 send_early_empty_ack = 1;
3982 }
3983 if (send_early_empty_ack) {
3984 coap_send_ack_lkd(session, pdu);
3985 if (pdu->mid == session->last_con_mid) {
3986 /* request has already been processed - do not process it again */
3987 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3988 pdu->mid);
3989 goto drop_it_no_debug;
3990 }
3991 session->last_con_mid = pdu->mid;
3992 }
3993#if COAP_WITH_OBSERVE_PERSIST
3994 /* If we are maintaining Observe persist */
3995 if (resource == context->unknown_resource) {
3996 context->unknown_pdu = pdu;
3997 context->unknown_session = session;
3998 } else
3999 context->unknown_pdu = NULL;
4000#endif /* COAP_WITH_OBSERVE_PERSIST */
4001
4002 /*
4003 * Call the request handler with everything set up
4004 */
4005 if (resource == &resource_uri_wellknown) {
4006 /* Leave context locked */
4007 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
4008 (int)resource->uri_path->length, (int)resource->uri_path->length,
4009 resource->uri_path->s);
4010 h(resource, session, pdu, query, response);
4011 } else {
4012 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
4013 (int)resource->uri_path->length, (int)resource->uri_path->length,
4014 resource->uri_path->s);
4015 coap_lock_callback_release(h(resource, session, pdu, query, response),
4016 /* context is being freed off */
4017 goto finish);
4018 }
4019
4020 /* Check validity of response code */
4021 if (!coap_check_code_class(session, response)) {
4022 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
4023 COAP_RESPONSE_CLASS(response->code),
4024 response->code & 0x1f);
4025 goto drop_it_no_debug;
4026 }
4027
4028 /* Check if lg_xmit generated and update PDU code if so */
4029 coap_check_code_lg_xmit(session, pdu, response, resource, query);
4030
4031 if (free_lg_srcv) {
4032 /* Check to see if the server is doing a 4.01 + Echo response */
4033 if (response->code == COAP_RESPONSE_CODE(401) &&
4034 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
4035 /* Need to keep lg_srcv around for client's response */
4036 } else {
4037 coap_lg_srcv_t *lg_srcv;
4038 /*
4039 * Need to check free_lg_srcv still exists in case of error or timing window
4040 */
4041 LL_FOREACH(session->lg_srcv, lg_srcv) {
4042 if (lg_srcv == free_lg_srcv) {
4043 LL_DELETE(session->lg_srcv, free_lg_srcv);
4044 coap_block_delete_lg_srcv(session, free_lg_srcv);
4045 break;
4046 }
4047 }
4048 }
4049 }
4050 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
4051 /* Just in case, as there are more to go */
4052 response->code = COAP_RESPONSE_CODE(231);
4053 }
4054
4055skip_handler:
4056 if (send_early_empty_ack &&
4057 response->type == COAP_MESSAGE_ACK) {
4058 /* Response is now separate - convert to CON as needed */
4059 response->type = COAP_MESSAGE_CON;
4060 /* Check for empty ACK - need to drop as already sent */
4061 if (response->code == 0) {
4062 goto drop_it_no_debug;
4063 }
4064 }
4065 respond = no_response(pdu, response, session, resource);
4066 if (respond != RESPONSE_DROP) {
4067#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
4068 coap_mid_t mid = pdu->mid;
4069#endif
4070 if (COAP_RESPONSE_CLASS(response->code) != 2) {
4071 if (observe) {
4073 }
4074 }
4075 if (COAP_RESPONSE_CLASS(response->code) > 2) {
4076 if (observe)
4077 coap_delete_observer(resource, session, &pdu->actual_token);
4078 if (response->code != COAP_RESPONSE_CODE(413))
4080 }
4081
4082 /* If original request contained a token, and the registered
4083 * application handler made no changes to the response, then
4084 * this is an empty ACK with a token, which is a malformed
4085 * PDU */
4086 if ((response->type == COAP_MESSAGE_ACK)
4087 && (response->code == 0)) {
4088 /* Remove token from otherwise-empty acknowledgment PDU */
4089 response->actual_token.length = 0;
4090 response->e_token_length = 0;
4091 response->used_size = 0;
4092 response->data = NULL;
4093 }
4094
4095 if (!coap_is_mcast(&session->addr_info.local) ||
4096 (context->mcast_per_resource &&
4097 resource &&
4099 /* No delays to response */
4100#if COAP_Q_BLOCK_SUPPORT
4101 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4102 !lg_xmit_ctrl && COAP_RESPONSE_CLASS(response->code) == 2 &&
4103 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4104 block.m) {
4105 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4106 response,
4107 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4108 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4109 response = NULL;
4110 if (query)
4111 coap_delete_string(query);
4112 goto finish;
4113 }
4114#endif /* COAP_Q_BLOCK_SUPPORT */
4115 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4116 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4117 if (query)
4118 coap_delete_string(query);
4119 goto finish;
4120 }
4121 } else {
4122 /* Need to delay mcast response */
4123 coap_queue_t *node = coap_new_node();
4124 uint8_t r;
4125 coap_tick_t delay;
4126
4127 if (!node) {
4128 coap_log_debug("mcast delay: insufficient memory\n");
4129 goto drop_it_no_debug;
4130 }
4131 if (!coap_pdu_encode_header(response, session->proto)) {
4133 goto drop_it_no_debug;
4134 }
4135
4136 node->id = response->mid;
4137 node->pdu = response;
4138 node->is_mcast = 1;
4139 coap_prng_lkd(&r, sizeof(r));
4140 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4141 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4142 coap_session_str(session),
4143 response->mid,
4144 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4145 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4146 1000 / COAP_TICKS_PER_SECOND));
4147 node->timeout = (unsigned int)delay;
4148 /* Use this to delay transmission */
4149 coap_wait_ack(session->context, session, node);
4150 }
4151 } else {
4152 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4153 coap_session_str(session),
4154 response->mid);
4155 coap_show_pdu(COAP_LOG_DEBUG, response);
4156drop_it_no_debug:
4157 coap_delete_pdu_lkd(response);
4158 }
4159 if (query)
4160 coap_delete_string(query);
4161#if COAP_Q_BLOCK_SUPPORT
4162 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4163 if (COAP_PROTO_RELIABLE(session->proto)) {
4164 if (block.m) {
4165 /* All of the sequence not in yet */
4166 goto finish;
4167 }
4168 } else if (pdu->type == COAP_MESSAGE_NON) {
4169 /* More to go and not at a payload break */
4170 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4171 goto finish;
4172 }
4173 }
4174 }
4175#endif /* COAP_Q_BLOCK_SUPPORT */
4176
4177finish:
4178 if (resource)
4179 coap_resource_release_lkd(resource);
4180 coap_delete_string(uri_path);
4181 return;
4182
4183fail_response:
4184 coap_delete_pdu_lkd(response);
4185 response =
4187 &opt_filter);
4188 if (response)
4189 goto skip_handler;
4190 if (resource)
4191 coap_resource_release_lkd(resource);
4192 coap_delete_string(uri_path);
4193}
4194#endif /* COAP_SERVER_SUPPORT */
4195
4196#if COAP_CLIENT_SUPPORT
4197/* Call application-specific response handler when available. */
4198void
4200 coap_pdu_t *sent, coap_pdu_t *rcvd,
4201 void *body_data) {
4202 coap_context_t *context = session->context;
4203 coap_response_t ret;
4204
4205#if COAP_PROXY_SUPPORT
4206 if (context->proxy_response_cb) {
4207 coap_proxy_entry_t *proxy_entry;
4208 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4209 rcvd,
4210 &proxy_entry);
4211
4212 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4213 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4214 proxy_entry);
4215 return;
4216 }
4217 }
4218#endif /* COAP_PROXY_SUPPORT */
4219 if (session->doing_send_recv && session->req_token &&
4220 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4221 /* processing coap_send_recv() call */
4222 session->resp_pdu = rcvd;
4224 /* Will get freed off when PDU is freed off */
4225 rcvd->data_free = body_data;
4226 coap_send_ack_lkd(session, rcvd);
4228 return;
4229 } else if (context->response_cb) {
4231 context->response_cb(session,
4232 sent,
4233 rcvd,
4234 rcvd->mid),
4235 /* context is being freed off */
4236 return);
4237 } else {
4238 ret = COAP_RESPONSE_OK;
4239 }
4240 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4241 coap_send_rst_lkd(session, rcvd);
4243 } else {
4244 coap_send_ack_lkd(session, rcvd);
4246 }
4247 coap_free_type(COAP_STRING, body_data);
4248}
4249
4250static void
4251handle_response(coap_context_t *context, coap_session_t *session,
4252 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4253
4254 /* Set in case there is a later call to coap_update_token() */
4255 rcvd->session = session;
4256
4257 /* Check for message duplication */
4258 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4259 if (rcvd->type == COAP_MESSAGE_CON) {
4260 if (rcvd->mid == session->last_con_mid) {
4261 /* Duplicate response: send ACK/RST, but don't process */
4262 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4263 coap_send_ack_lkd(session, rcvd);
4264 else
4265 coap_send_rst_lkd(session, rcvd);
4266 return;
4267 }
4268 session->last_con_mid = rcvd->mid;
4269 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4270 if (rcvd->mid == session->last_ack_mid) {
4271 /* Duplicate response */
4272 return;
4273 }
4274 session->last_ack_mid = rcvd->mid;
4275 }
4276 }
4277 /* Check to see if checking out extended token support */
4278 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4279 session->last_token) {
4280 coap_lg_crcv_t *lg_crcv;
4281
4282 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4283 rcvd->actual_token.length != session->max_token_size ||
4284 rcvd->code == COAP_RESPONSE_CODE(400) ||
4285 rcvd->code == COAP_RESPONSE_CODE(503)) {
4286 coap_log_debug("Extended Token requested size support not available\n");
4288 } else {
4289 coap_log_debug("Extended Token support available\n");
4290 }
4292 /* Need to remove lg_crcv set up for this test */
4293 lg_crcv = coap_find_lg_crcv(session, rcvd);
4294 if (lg_crcv) {
4295 LL_DELETE(session->lg_crcv, lg_crcv);
4296 coap_block_delete_lg_crcv(session, lg_crcv);
4297 }
4298 coap_send_ack_lkd(session, rcvd);
4299 coap_reset_doing_first(session);
4300 return;
4301 }
4302#if COAP_Q_BLOCK_SUPPORT
4303 /* Check to see if checking out Q-Block support */
4304 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
4305 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4306 coap_log_debug("Q-Block support not available\n");
4307 set_block_mode_drop_q(session->block_mode);
4308 } else {
4309 coap_block_b_t qblock;
4310
4311 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4312 coap_log_debug("Q-Block support available\n");
4313 set_block_mode_has_q(session->block_mode);
4314 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4315 /* Flush out any entries on session->delayqueue */
4316 coap_session_connected(session);
4317 } else {
4318 coap_log_debug("Q-Block support not available\n");
4319 set_block_mode_drop_q(session->block_mode);
4320 }
4321 }
4322 coap_send_ack_lkd(session, rcvd);
4323 coap_reset_doing_first(session);
4324 return;
4325 }
4326#endif /* COAP_Q_BLOCK_SUPPORT */
4327
4328 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4329 /* See if need to send next block to server */
4330 if (coap_handle_response_send_block(session, sent, rcvd)) {
4331 /* Next block transmitted, no need to inform app */
4332 coap_send_ack_lkd(session, rcvd);
4333 return;
4334 }
4335
4336 /* Need to see if needing to request next block */
4337 if (coap_handle_response_get_block(context, session, sent, rcvd,
4338 COAP_RECURSE_OK)) {
4339 /* Next block transmitted, ack sent no need to inform app */
4340 return;
4341 }
4342 }
4343 coap_reset_doing_first(session);
4344
4345 /* Call application-specific response handler when available. */
4346 coap_call_response_handler(session, sent, rcvd, NULL);
4347}
4348#endif /* COAP_CLIENT_SUPPORT */
4349
4350#if !COAP_DISABLE_TCP
4351static void
4353 coap_pdu_t *pdu) {
4354 coap_opt_iterator_t opt_iter;
4355 coap_opt_t *option;
4356 int set_mtu = 0;
4357
4358 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4359
4360 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4361 if (session->csm_not_seen) {
4362 coap_tick_t now;
4363
4364 coap_ticks(&now);
4365 /* CSM timeout before CSM seen */
4366 coap_log_warn("***%s: CSM received after CSM timeout\n",
4367 coap_session_str(session));
4368 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4369 coap_session_str(session),
4370 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4371 }
4372 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4374 }
4375 while ((option = coap_option_next(&opt_iter))) {
4377 unsigned max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4378
4379 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4380 max_recv = COAP_DEFAULT_MAX_PDU_RX_SIZE;
4381 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4382 coap_session_str(session), max_recv);
4383 }
4384 coap_session_set_mtu(session, max_recv);
4385 set_mtu = 1;
4386 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4387 session->csm_block_supported = 1;
4388 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4389 session->max_token_size =
4391 coap_opt_length(option));
4394 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4397 }
4398 }
4399 if (set_mtu) {
4400 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4401 session->csm_bert_rem_support = 1;
4402 else
4403 session->csm_bert_rem_support = 0;
4404 }
4405 if (session->state == COAP_SESSION_STATE_CSM)
4406 coap_session_connected(session);
4407 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4409 if (context->ping_cb) {
4410 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4411 }
4412 if (pong) {
4414 coap_send_internal(session, pong, NULL);
4415 }
4416 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4417 session->last_pong = session->last_rx_tx;
4418 if (context->pong_cb) {
4419 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4420 }
4421 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4422 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4424 }
4425}
4426#endif /* !COAP_DISABLE_TCP */
4427
4428static int
4430 if (COAP_PDU_IS_REQUEST(pdu) &&
4431 pdu->actual_token.length >
4432 (session->type == COAP_SESSION_TYPE_CLIENT ?
4433 session->max_token_size : session->context->max_token_size)) {
4434 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4435 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4436 coap_opt_filter_t opt_filter;
4437 coap_pdu_t *response;
4438
4439 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4440 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4441 &opt_filter);
4442 if (!response) {
4443 coap_log_warn("coap_dispatch: cannot create error response\n");
4444 } else {
4445 /*
4446 * Note - have to leave in oversize token as per
4447 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4448 */
4449 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4450 coap_log_warn("coap_dispatch: error sending response\n");
4451 }
4452 } else {
4453 /* Indicate no extended token support */
4454 coap_send_rst_lkd(session, pdu);
4455 }
4456 return 0;
4457 }
4458 return 1;
4459}
4460
4461void
4463 coap_pdu_t *pdu) {
4464 coap_queue_t *sent = NULL;
4465 coap_pdu_t *response;
4466 coap_pdu_t *orig_pdu = NULL;
4467 coap_opt_filter_t opt_filter;
4468 int is_ping_rst;
4469 int packet_is_bad = 0;
4470#if COAP_OSCORE_SUPPORT
4471 coap_opt_iterator_t opt_iter;
4472 coap_pdu_t *dec_pdu = NULL;
4473#endif /* COAP_OSCORE_SUPPORT */
4474 int is_ext_token_rst = 0;
4475 int oscore_invalid = 0;
4476
4477 pdu->session = session;
4479
4480 /* Check validity of received code */
4481 if (!coap_check_code_class(session, pdu)) {
4482 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4484 pdu->code & 0x1f);
4485 packet_is_bad = 1;
4486 if (pdu->type == COAP_MESSAGE_CON) {
4488 }
4489 /* find message id in sendqueue to stop retransmission */
4490 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4491 goto cleanup;
4492 }
4493
4494 coap_option_filter_clear(&opt_filter);
4495
4496#if COAP_SERVER_SUPPORT
4497 /* See if this a repeat request */
4498 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4500 coap_digest_t digest;
4501
4502 coap_pdu_cksum(pdu, &digest);
4503 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4504#if COAP_OSCORE_SUPPORT
4505 uint8_t oscore_encryption = session->oscore_encryption;
4506
4507 session->oscore_encryption = 0;
4508#endif /* COAP_OSCORE_SUPPORT */
4509 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4510 cached_pdu must not be removed */
4512 coap_log_debug("Retransmit response to duplicate request\n");
4513 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4514#if COAP_OSCORE_SUPPORT
4515 session->oscore_encryption = oscore_encryption;
4516#endif /* COAP_OSCORE_SUPPORT */
4517 return;
4518 }
4519#if COAP_OSCORE_SUPPORT
4520 session->oscore_encryption = oscore_encryption;
4521#endif /* COAP_OSCORE_SUPPORT */
4522 }
4523 }
4524#endif /* COAP_SERVER_SUPPORT */
4525 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4526 if (!check_token_size(session, pdu)) {
4527 goto cleanup;
4528 }
4529 }
4530#if COAP_OSCORE_SUPPORT
4531 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4532 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4533 if (pdu->type == COAP_MESSAGE_NON) {
4534 coap_send_rst_lkd(session, pdu);
4535 goto cleanup;
4536 } else if (pdu->type == COAP_MESSAGE_CON) {
4537 if (COAP_PDU_IS_REQUEST(pdu)) {
4538 response =
4539 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4540
4541 if (!response) {
4542 coap_log_warn("coap_dispatch: cannot create error response\n");
4543 } else {
4544 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4545 coap_log_warn("coap_dispatch: error sending response\n");
4546 }
4547 } else {
4548 coap_send_rst_lkd(session, pdu);
4549 }
4550 }
4551 goto cleanup;
4552 }
4553
4554 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4555 int decrypt = 1;
4556#if COAP_SERVER_SUPPORT
4557 coap_opt_t *opt;
4558 coap_resource_t *resource;
4559 coap_uri_t uri;
4560#endif /* COAP_SERVER_SUPPORT */
4561
4562 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4563 decrypt = 0;
4564
4565#if COAP_SERVER_SUPPORT
4566 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4567 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4568 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4569 != NULL) {
4570 /* Need to check whether this is a direct or proxy session */
4571 memset(&uri, 0, sizeof(uri));
4572 uri.host.length = coap_opt_length(opt);
4573 uri.host.s = coap_opt_value(opt);
4574 resource = context->proxy_uri_resource;
4575 if (uri.host.length && resource && resource->proxy_name_count &&
4576 resource->proxy_name_list) {
4577 size_t i;
4578 for (i = 0; i < resource->proxy_name_count; i++) {
4579 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4580 break;
4581 }
4582 }
4583 if (i == resource->proxy_name_count) {
4584 /* This server is not hosting the proxy connection endpoint */
4585 decrypt = 0;
4586 }
4587 }
4588 }
4589#endif /* COAP_SERVER_SUPPORT */
4590 if (decrypt) {
4591 /* find message id in sendqueue to stop retransmission and get sent */
4592 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4593 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4594 orig_pdu = pdu;
4595 coap_pdu_reference_lkd(orig_pdu);
4596 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4597 if (session->recipient_ctx == NULL ||
4598 session->recipient_ctx->initial_state == 0) {
4599 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4600 }
4602 coap_delete_pdu_lkd(orig_pdu);
4603 return;
4604 } else {
4605 session->oscore_encryption = 1;
4606 pdu = dec_pdu;
4607 }
4608 coap_log_debug("Decrypted PDU\n");
4610 }
4611 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4612 session->oscore_encryption &&
4613 pdu->type != COAP_MESSAGE_RST) {
4614 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4615 /* Violates RFC 8613 2 */
4616 coap_log_err("received an invalid response to the OSCORE request\n");
4617 oscore_invalid = 1;
4618 }
4619 }
4620#endif /* COAP_OSCORE_SUPPORT */
4621
4622 switch (pdu->type) {
4623 case COAP_MESSAGE_ACK:
4624 /* find message id in sendqueue to stop retransmission */
4625 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4626
4627 if (sent && session->con_active) {
4628 session->con_active--;
4629 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4630 /* Flush out any entries on session->delayqueue */
4631 coap_session_connected(session);
4632 }
4633 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4634 packet_is_bad = 1;
4635 goto cleanup;
4636 }
4637
4638#if COAP_SERVER_SUPPORT
4639 /* if sent code was >= 64 the message might have been a
4640 * notification. Then, we must flag the observer to be alive
4641 * by setting obs->fail_cnt = 0. */
4642 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4643 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4644 }
4645#endif /* COAP_SERVER_SUPPORT */
4646
4647#if COAP_Q_BLOCK_SUPPORT
4648 if (session->lg_xmit && sent && sent->pdu && sent->pdu->type == COAP_MESSAGE_CON &&
4649 !(session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK)) {
4650 int doing_q_block = 0;
4651 coap_lg_xmit_t *lg_xmit = NULL;
4652
4653 LL_FOREACH(session->lg_xmit, lg_xmit) {
4654 if ((lg_xmit->option == COAP_OPTION_Q_BLOCK1 || lg_xmit->option == COAP_OPTION_Q_BLOCK2) &&
4655 lg_xmit->last_all_sent == 0 && lg_xmit->sent_pdu->type != COAP_MESSAGE_NON) {
4656 doing_q_block = 1;
4657 break;
4658 }
4659 }
4660 if (doing_q_block && lg_xmit) {
4661 coap_block_b_t block;
4662
4663 memset(&block, 0, sizeof(block));
4664 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
4665 block.num = lg_xmit->last_block + lg_xmit->b.b1.count;
4666 } else {
4667 block.num = lg_xmit->last_block;
4668 }
4669 block.m = 1;
4670 block.szx = block.aszx = lg_xmit->blk_size;
4671 block.defined = 1;
4672 block.bert = 0;
4673 block.chunk_size = 1024;
4674
4675 coap_send_q_blocks(session, lg_xmit, block,
4676 lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
4677 }
4678 }
4679#endif /* COAP_Q_BLOCK_SUPPORT */
4680 if (pdu->code == 0) {
4681#if COAP_CLIENT_SUPPORT
4682 /*
4683 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4684 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4685 * response if the response was piggy-backed. Here, a separate response
4686 * detected and so the lg_crcv needs to be set up before the sent PDU
4687 * information is lost.
4688 *
4689 * lg_crcv was not set up if not a CoAP request.
4690 *
4691 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4692 * options.
4693 */
4694 if (sent &&
4695 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4696 COAP_PDU_IS_REQUEST(sent->pdu)) {
4697 /*
4698 * lg_crcv was not set up in coap_send(). It could have been set up
4699 * the first separate response.
4700 * See if there already is a lg_crcv set up.
4701 */
4702 coap_lg_crcv_t *lg_crcv;
4703 uint64_t token_match =
4705 sent->pdu->actual_token.length));
4706
4707 LL_FOREACH(session->lg_crcv, lg_crcv) {
4708 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4709 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4710 break;
4711 }
4712 }
4713 if (!lg_crcv) {
4714 /*
4715 * Need to set up a lg_crcv as it was not set up in coap_send()
4716 * to save time, but server has not sent back a piggy-back response.
4717 */
4718 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4719 if (lg_crcv) {
4720 LL_PREPEND(session->lg_crcv, lg_crcv);
4721 }
4722 }
4723 }
4724#endif /* COAP_CLIENT_SUPPORT */
4725 /* an empty ACK needs no further handling */
4726 goto cleanup;
4727 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4728 /* This is not legitimate - Request using ACK - ignore */
4729 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4731 pdu->code & 0x1f);
4732 packet_is_bad = 1;
4733 goto cleanup;
4734 }
4735
4736 break;
4737
4738 case COAP_MESSAGE_RST:
4739 /* We have sent something the receiver disliked, so we remove
4740 * not only the message id but also the subscriptions we might
4741 * have. */
4742 is_ping_rst = 0;
4743 if (pdu->mid == session->last_ping_mid &&
4744 session->last_ping > 0)
4745 is_ping_rst = 1;
4746
4747#if COAP_CLIENT_SUPPORT
4748#if COAP_Q_BLOCK_SUPPORT
4749 /* Check to see if checking out Q-Block support */
4750 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4751 session->remote_test_mid == pdu->mid) {
4752 coap_log_debug("Q-Block support not available\n");
4753 set_block_mode_drop_q(session->block_mode);
4754 coap_reset_doing_first(session);
4755 }
4756#endif /* COAP_Q_BLOCK_SUPPORT */
4757
4758 /* Check to see if checking out extended token support */
4759 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4760 session->remote_test_mid == pdu->mid) {
4761 coap_log_debug("Extended Token support not available\n");
4764 coap_reset_doing_first(session);
4765 is_ext_token_rst = 1;
4766 }
4767#endif /* COAP_CLIENT_SUPPORT */
4768
4769 if (!is_ping_rst && !is_ext_token_rst)
4770 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4771
4772 if (session->con_active) {
4773 session->con_active--;
4774 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4775 /* Flush out any entries on session->delayqueue */
4776 coap_session_connected(session);
4777 }
4778
4779 /* find message id in sendqueue to stop retransmission */
4780 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4781
4782 if (sent) {
4783 if (!is_ping_rst)
4784 coap_cancel(context, sent);
4785
4786 if (!is_ping_rst && !is_ext_token_rst) {
4787 if (sent->pdu->type==COAP_MESSAGE_CON) {
4788 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4789 }
4790 } else if (is_ping_rst) {
4791 if (context->pong_cb) {
4792 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4793 }
4794 session->last_pong = session->last_rx_tx;
4796 }
4797 } else {
4798#if COAP_SERVER_SUPPORT
4799 /* Need to check is there is a subscription active and delete it */
4800 RESOURCES_ITER(context->resources, r) {
4801 coap_subscription_t *obs, *tmp;
4802 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4803 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4804 /* Need to do this now as session may get de-referenced */
4806 coap_delete_observer(r, session, &obs->pdu->actual_token);
4807 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4808 coap_session_release_lkd(session);
4809 goto cleanup;
4810 }
4811 }
4812 }
4813#endif /* COAP_SERVER_SUPPORT */
4814 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4815 }
4816#if COAP_PROXY_SUPPORT
4817 if (!is_ping_rst) {
4818 /* Need to check is there is a proxy subscription active and delete it */
4819 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
4820 }
4821#endif /* COAP_PROXY_SUPPORT */
4822 goto cleanup;
4823
4824 case COAP_MESSAGE_NON:
4825 /* check for oscore issue or unknown critical options */
4826 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4827 packet_is_bad = 1;
4828 coap_send_rst_lkd(session, pdu);
4829 goto cleanup;
4830 }
4831 break;
4832
4833 case COAP_MESSAGE_CON:
4834 /* In a lossy context, the ACK of a separate response may have
4835 * been lost, so we need to stop retransmitting requests with the
4836 * same token. Matching on token potentially containing ext length bytes.
4837 */
4838 /* find message token in sendqueue to stop retransmission */
4839 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4840
4841 /* check for oscore issue or unknown critical options in non-signaling messages */
4842 if (oscore_invalid ||
4843 (!COAP_PDU_IS_SIGNALING(pdu) && coap_option_check_critical(session, pdu, &opt_filter) == 0)) {
4844 packet_is_bad = 1;
4845 if (COAP_PDU_IS_REQUEST(pdu)) {
4846 response =
4847 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4848
4849 if (!response) {
4850 coap_log_warn("coap_dispatch: cannot create error response\n");
4851 } else {
4852 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4853 coap_log_warn("coap_dispatch: error sending response\n");
4854 }
4855 } else {
4856 coap_send_rst_lkd(session, pdu);
4857 }
4858 goto cleanup;
4859 }
4860 break;
4861 default:
4862 break;
4863 }
4864
4865 /* Pass message to upper layer if a specific handler was
4866 * registered for a request that should be handled locally. */
4867#if !COAP_DISABLE_TCP
4868 if (COAP_PDU_IS_SIGNALING(pdu))
4869 handle_signaling(context, session, pdu);
4870 else
4871#endif /* !COAP_DISABLE_TCP */
4872#if COAP_SERVER_SUPPORT
4873 if (COAP_PDU_IS_REQUEST(pdu))
4874 handle_request(context, session, pdu, orig_pdu);
4875 else
4876#endif /* COAP_SERVER_SUPPORT */
4877#if COAP_CLIENT_SUPPORT
4878 if (COAP_PDU_IS_RESPONSE(pdu))
4879 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4880 else
4881#endif /* COAP_CLIENT_SUPPORT */
4882 {
4883 if (COAP_PDU_IS_EMPTY(pdu)) {
4884 if (context->ping_cb) {
4885 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4886 }
4887 } else {
4888 packet_is_bad = 1;
4889 }
4890 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4892 pdu->code & 0x1f);
4893
4894 if (!coap_is_mcast(&session->addr_info.local)) {
4895 if (COAP_PDU_IS_EMPTY(pdu)) {
4896 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4897 coap_tick_t now;
4898 coap_ticks(&now);
4899 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4901 session->last_tx_rst = now;
4902 }
4903 }
4904 } else {
4905 if (pdu->type == COAP_MESSAGE_CON)
4907 }
4908 }
4909 }
4910
4911cleanup:
4912 if (packet_is_bad) {
4913 if (sent) {
4914 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
4915 } else {
4917 }
4918 }
4919 coap_delete_pdu_lkd(orig_pdu);
4921#if COAP_OSCORE_SUPPORT
4922 coap_delete_pdu_lkd(dec_pdu);
4923#endif /* COAP_OSCORE_SUPPORT */
4924}
4925
4926#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4927static const char *
4929 switch (event) {
4931 return "COAP_EVENT_DTLS_CLOSED";
4933 return "COAP_EVENT_DTLS_CONNECTED";
4935 return "COAP_EVENT_DTLS_RENEGOTIATE";
4937 return "COAP_EVENT_DTLS_ERROR";
4939 return "COAP_EVENT_TCP_CONNECTED";
4941 return "COAP_EVENT_TCP_CLOSED";
4943 return "COAP_EVENT_TCP_FAILED";
4945 return "COAP_EVENT_SESSION_CONNECTED";
4947 return "COAP_EVENT_SESSION_CLOSED";
4949 return "COAP_EVENT_SESSION_FAILED";
4951 return "COAP_EVENT_PARTIAL_BLOCK";
4953 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4955 return "COAP_EVENT_BLOCK_ISSUE";
4957 return "COAP_EVENT_SERVER_SESSION_NEW";
4959 return "COAP_EVENT_SERVER_SESSION_DEL";
4961 return "COAP_EVENT_SERVER_SESSION_CONNECTED";
4963 return "COAP_EVENT_BAD_PACKET";
4965 return "COAP_EVENT_MSG_RETRANSMITTED";
4967 return "COAP_EVENT_FIRST_PDU_FAIL";
4969 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4971 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4973 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4975 return "COAP_EVENT_OSCORE_NO_SECURITY";
4977 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4979 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4981 return "COAP_EVENT_WS_PACKET_SIZE";
4983 return "COAP_EVENT_WS_CONNECTED";
4985 return "COAP_EVENT_WS_CLOSED";
4987 return "COAP_EVENT_KEEPALIVE_FAILURE";
4989 return "COAP_EVENT_RECONNECT_FAILED";
4991 return "COAP_EVENT_RECONNECT_SUCCESS";
4993 return "COAP_EVENT_RECONNECT_NO_MORE";
4995 return "COAP_EVENT_RECONNECT_STARTED";
4996 default:
4997 return "???";
4998 }
4999}
5000#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
5001
5002COAP_API int
5004 coap_session_t *session) {
5005 int ret;
5006
5007 coap_lock_lock(return 0);
5008 ret = coap_handle_event_lkd(context, event, session);
5010 return ret;
5011}
5012
5013int
5015 coap_session_t *session) {
5016 int ret = 0;
5017
5018 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
5019
5020 if (context->event_cb) {
5021 coap_lock_callback_ret(ret, context->event_cb(session, event));
5022#if COAP_PROXY_SUPPORT
5023 if (event == COAP_EVENT_SERVER_SESSION_DEL)
5024 coap_proxy_remove_association(session, 0);
5025#endif /* COAP_PROXY_SUPPORT */
5026#if COAP_CLIENT_SUPPORT
5027 switch (event) {
5042 /* Those that are deemed fatal to end sending a request */
5043 session->doing_send_recv = 0;
5044 break;
5046 /* Session will now be available as well - for call-home */
5047 if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
5049 session);
5050 }
5051 break;
5057 break;
5059 /* Session will now be available as well - for call-home if not (D)TLS */
5060 if (session->type == COAP_SESSION_TYPE_SERVER &&
5061 (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
5063 session);
5064 }
5065 break;
5070 break;
5072 /* Session will now be available as well - for call-home if not (D)TLS */
5073 if (session->proto == COAP_PROTO_UDP) {
5075 session);
5076 }
5077 break;
5085 default:
5086 break;
5087 }
5088#endif /* COAP_CLIENT_SUPPORT */
5089 }
5090 return ret;
5091}
5092
5093COAP_API int
5095 int ret;
5096
5097 coap_lock_lock(return 0);
5098 ret = coap_can_exit_lkd(context);
5100 return ret;
5101}
5102
5103int
5105 coap_session_t *s, *rtmp;
5106 if (!context)
5107 return 1;
5109 if (context->sendqueue)
5110 return 0;
5111#if COAP_SERVER_SUPPORT
5112 coap_endpoint_t *ep;
5113
5114 LL_FOREACH(context->endpoint, ep) {
5115 SESSIONS_ITER(ep->sessions, s, rtmp) {
5116 if (s->delayqueue)
5117 return 0;
5118 if (s->lg_xmit)
5119 return 0;
5120 }
5121 }
5122#endif /* COAP_SERVER_SUPPORT */
5123#if COAP_CLIENT_SUPPORT
5124 SESSIONS_ITER(context->sessions, s, rtmp) {
5125 if (s->delayqueue)
5126 return 0;
5127 if (s->lg_xmit)
5128 return 0;
5129 }
5130#endif /* COAP_CLIENT_SUPPORT */
5131 return 1;
5132}
5133#if COAP_SERVER_SUPPORT
5134#if COAP_ASYNC_SUPPORT
5135/*
5136 * Return 1 if there is a future expire time, else 0.
5137 * Update tim_rem with remaining value if return is 1.
5138 */
5139int
5140coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5142 coap_async_t *async, *tmp;
5143 int ret = 0;
5144
5145 if (context->async_state_traversing)
5146 return 0;
5147 context->async_state_traversing = 1;
5148 LL_FOREACH_SAFE(context->async_state, async, tmp) {
5149 if (async->delay != 0) {
5150 if (async->delay <= now) {
5151 /* Send off the request to the application */
5152 coap_log_debug("Async PDU presented to app.\n");
5153 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5154 handle_request(context, async->session, async->pdu, NULL);
5155
5156 /* Remove this async entry as it has now fired */
5157 coap_free_async_lkd(async->session, async);
5158 } else {
5159 next_due = async->delay - now;
5160 ret = 1;
5161 }
5162 }
5163 }
5164 if (tim_rem)
5165 *tim_rem = next_due;
5166 context->async_state_traversing = 0;
5167 return ret;
5168}
5169#endif /* COAP_ASYNC_SUPPORT */
5170#endif /* COAP_SERVER_SUPPORT */
5171
5173uint8_t coap_unique_id[8] = { 0 };
5174
5175#if COAP_THREAD_SAFE
5176/*
5177 * Global lock for multi-thread support
5178 */
5179coap_lock_t global_lock;
5180/*
5181 * low level protection mutex
5182 */
5183coap_mutex_t m_show_pdu;
5184coap_mutex_t m_log_impl;
5185coap_mutex_t m_io_threads;
5186#endif /* COAP_THREAD_SAFE */
5187
5188void
5190 coap_tick_t now;
5191#ifndef WITH_CONTIKI
5192 uint64_t us;
5193#endif /* !WITH_CONTIKI */
5194
5195 if (coap_started)
5196 return;
5197 coap_started = 1;
5198
5199#if COAP_THREAD_SAFE
5201 coap_mutex_init(&m_show_pdu);
5202 coap_mutex_init(&m_log_impl);
5203 coap_mutex_init(&m_io_threads);
5204#endif /* COAP_THREAD_SAFE */
5205
5206#if defined(HAVE_WINSOCK2_H)
5207 WORD wVersionRequested = MAKEWORD(2, 2);
5208 WSADATA wsaData;
5209 WSAStartup(wVersionRequested, &wsaData);
5210#endif
5212 coap_ticks(&now);
5213#ifndef WITH_CONTIKI
5214 us = coap_ticks_to_rt_us(now);
5215 /* Be accurate to the nearest (approx) us */
5216 coap_prng_init_lkd((unsigned int)us);
5217#else /* WITH_CONTIKI */
5218 coap_start_io_process();
5219#endif /* WITH_CONTIKI */
5222#ifdef WITH_LWIP
5223 coap_io_lwip_init();
5224#endif /* WITH_LWIP */
5225#if COAP_SERVER_SUPPORT
5226 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5227 (const uint8_t *)".well-known/core"
5228 };
5229 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5230 resource_uri_wellknown.ref = 1;
5231 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5232 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5233 resource_uri_wellknown.uri_path = &well_known;
5234#endif /* COAP_SERVER_SUPPORT */
5237}
5238
5239void
5241 if (!coap_started)
5242 return;
5243 coap_started = 0;
5244#if defined(HAVE_WINSOCK2_H)
5245 WSACleanup();
5246#elif defined(WITH_CONTIKI)
5247 coap_stop_io_process();
5248#endif
5249#ifdef WITH_LWIP
5250 coap_io_lwip_cleanup();
5251#endif /* WITH_LWIP */
5253
5254#if COAP_THREAD_SAFE
5255 coap_mutex_destroy(&m_show_pdu);
5256 coap_mutex_destroy(&m_log_impl);
5257 coap_mutex_destroy(&m_io_threads);
5258#endif /* COAP_THREAD_SAFE */
5259
5261}
5262
5263void
5265 coap_response_handler_t handler) {
5266#if COAP_CLIENT_SUPPORT
5267 context->response_cb = handler;
5268#else /* ! COAP_CLIENT_SUPPORT */
5269 (void)context;
5270 (void)handler;
5271#endif /* ! COAP_CLIENT_SUPPORT */
5272}
5273
5274void
5277#if COAP_PROXY_SUPPORT
5278 context->proxy_response_cb = handler;
5279#else /* ! COAP_PROXY_SUPPORT */
5280 (void)context;
5281 (void)handler;
5282#endif /* ! COAP_PROXY_SUPPORT */
5283}
5284
5285void
5287 coap_nack_handler_t handler) {
5288 context->nack_cb = handler;
5289}
5290
5291void
5293 coap_ping_handler_t handler) {
5294 context->ping_cb = handler;
5295}
5296
5297void
5299 coap_pong_handler_t handler) {
5300 context->pong_cb = handler;
5301}
5302
5303void
5305 coap_resource_dynamic_create_t dyn_create_handler,
5306 uint32_t dynamic_max) {
5307 context->dyn_create_handler = dyn_create_handler;
5308 context->dynamic_max = dynamic_max;
5309 return;
5310}
5311
5312COAP_API void
5314 coap_lock_lock(return);
5315 coap_register_option_lkd(ctx, type);
5317}
5318
5319void
5322}
5323
5324#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5325#if COAP_SERVER_SUPPORT
5326COAP_API int
5327coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5328 const char *ifname) {
5329 int ret;
5330
5331 coap_lock_lock(return -1);
5332 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
5334 return ret;
5335}
5336
5337int
5338coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
5339 const char *ifname) {
5340#if COAP_IPV4_SUPPORT
5341 struct ip_mreq mreq4;
5342#endif /* COAP_IPV4_SUPPORT */
5343#if COAP_IPV6_SUPPORT
5344 struct ipv6_mreq mreq6;
5345#endif /* COAP_IPV6_SUPPORT */
5346 struct addrinfo *resmulti = NULL, hints, *ainfo;
5347 int result = -1;
5348 coap_endpoint_t *endpoint;
5349 int mgroup_setup = 0;
5350
5351 /* Need to have at least one endpoint! */
5352 assert(ctx->endpoint);
5353 if (!ctx->endpoint)
5354 return -1;
5355
5356 /* Default is let the kernel choose */
5357#if COAP_IPV6_SUPPORT
5358 mreq6.ipv6mr_interface = 0;
5359#endif /* COAP_IPV6_SUPPORT */
5360#if COAP_IPV4_SUPPORT
5361 mreq4.imr_interface.s_addr = INADDR_ANY;
5362#endif /* COAP_IPV4_SUPPORT */
5363
5364 memset(&hints, 0, sizeof(hints));
5365 hints.ai_socktype = SOCK_DGRAM;
5366
5367 /* resolve the multicast group address */
5368 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5369
5370 if (result != 0) {
5371 coap_log_err("coap_join_mcast_group_intf: %s: "
5372 "Cannot resolve multicast address: %s\n",
5373 group_name, gai_strerror(result));
5374 goto finish;
5375 }
5376
5377 /* Need to do a windows equivalent at some point */
5378#ifndef _WIN32
5379 if (ifname) {
5380 /* interface specified - check if we have correct IPv4/IPv6 information */
5381 int done_ip4 = 0;
5382 int done_ip6 = 0;
5383#if defined(ESPIDF_VERSION)
5384 struct netif *netif;
5385#else /* !ESPIDF_VERSION */
5386#if COAP_IPV4_SUPPORT
5387 int ip4fd;
5388#endif /* COAP_IPV4_SUPPORT */
5389 struct ifreq ifr;
5390#endif /* !ESPIDF_VERSION */
5391
5392 /* See which mcast address family types are being asked for */
5393 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5394 ainfo = ainfo->ai_next) {
5395 switch (ainfo->ai_family) {
5396#if COAP_IPV6_SUPPORT
5397 case AF_INET6:
5398 if (done_ip6)
5399 break;
5400 done_ip6 = 1;
5401#if defined(ESPIDF_VERSION)
5402 netif = netif_find(ifname);
5403 if (netif)
5404 mreq6.ipv6mr_interface = netif_get_index(netif);
5405 else
5406 coap_log_err("coap_join_mcast_group_intf: %s: "
5407 "Cannot get IPv4 address: %s\n",
5408 ifname, coap_socket_strerror());
5409#else /* !ESPIDF_VERSION */
5410 memset(&ifr, 0, sizeof(ifr));
5411 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5412 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5413
5414#ifdef HAVE_IF_NAMETOINDEX
5415 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5416 if (mreq6.ipv6mr_interface == 0) {
5417 coap_log_warn("coap_join_mcast_group_intf: "
5418 "cannot get interface index for '%s'\n",
5419 ifname);
5420 }
5421#elif defined(__QNXNTO__)
5422#else /* !HAVE_IF_NAMETOINDEX */
5423 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5424 if (result != 0) {
5425 coap_log_warn("coap_join_mcast_group_intf: "
5426 "cannot get interface index for '%s': %s\n",
5427 ifname, coap_socket_strerror());
5428 } else {
5429 /* Capture the IPv6 if_index for later */
5430 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5431 }
5432#endif /* !HAVE_IF_NAMETOINDEX */
5433#endif /* !ESPIDF_VERSION */
5434#endif /* COAP_IPV6_SUPPORT */
5435 break;
5436#if COAP_IPV4_SUPPORT
5437 case AF_INET:
5438 if (done_ip4)
5439 break;
5440 done_ip4 = 1;
5441#if defined(ESPIDF_VERSION)
5442 netif = netif_find(ifname);
5443 if (netif)
5444 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5445 else
5446 coap_log_err("coap_join_mcast_group_intf: %s: "
5447 "Cannot get IPv4 address: %s\n",
5448 ifname, coap_socket_strerror());
5449#else /* !ESPIDF_VERSION */
5450 /*
5451 * Need an AF_INET socket to do this unfortunately to stop
5452 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5453 */
5454 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5455 if (ip4fd == -1) {
5456 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5457 ifname, coap_socket_strerror());
5458 continue;
5459 }
5460 memset(&ifr, 0, sizeof(ifr));
5461 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5462 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5463 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5464 if (result != 0) {
5465 coap_log_err("coap_join_mcast_group_intf: %s: "
5466 "Cannot get IPv4 address: %s\n",
5467 ifname, coap_socket_strerror());
5468 } else {
5469 /* Capture the IPv4 address for later */
5470 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5471 }
5472 close(ip4fd);
5473#endif /* !ESPIDF_VERSION */
5474 break;
5475#endif /* COAP_IPV4_SUPPORT */
5476 default:
5477 break;
5478 }
5479 }
5480 }
5481#else /* _WIN32 */
5482 /*
5483 * On Windows this function ignores the ifname variable so we unset this
5484 * variable on this platform in any case in order to enable the interface
5485 * selection from the bind address below.
5486 */
5487 ifname = 0;
5488#endif /* _WIN32 */
5489
5490 /* Add in mcast address(es) to appropriate interface */
5491 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5492 LL_FOREACH(ctx->endpoint, endpoint) {
5493 /* Only UDP currently supported */
5494 if (endpoint->proto == COAP_PROTO_UDP) {
5495 coap_address_t gaddr;
5496
5497 coap_address_init(&gaddr);
5498#if COAP_IPV6_SUPPORT
5499 if (ainfo->ai_family == AF_INET6) {
5500 if (!ifname) {
5501 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5502 /*
5503 * Do it on the ifindex that the server is listening on
5504 * (sin6_scope_id could still be 0)
5505 */
5506 mreq6.ipv6mr_interface =
5507 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5508 } else {
5509 mreq6.ipv6mr_interface = 0;
5510 }
5511 }
5512 gaddr.addr.sin6.sin6_family = AF_INET6;
5513 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5514 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5515 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5516 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5517 (char *)&mreq6, sizeof(mreq6));
5518 }
5519#endif /* COAP_IPV6_SUPPORT */
5520#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5521 else
5522#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5523#if COAP_IPV4_SUPPORT
5524 if (ainfo->ai_family == AF_INET) {
5525 if (!ifname) {
5526 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5527 /*
5528 * Do it on the interface that the server is listening on
5529 * (sin_addr could still be INADDR_ANY)
5530 */
5531 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5532 } else {
5533 mreq4.imr_interface.s_addr = INADDR_ANY;
5534 }
5535 }
5536 gaddr.addr.sin.sin_family = AF_INET;
5537 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5538 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5539 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5540 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5541 (char *)&mreq4, sizeof(mreq4));
5542 }
5543#endif /* COAP_IPV4_SUPPORT */
5544 else {
5545 continue;
5546 }
5547
5548 if (result == COAP_SOCKET_ERROR) {
5549 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5550 group_name, coap_socket_strerror());
5551 } else {
5552 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5553
5554 addr_str[sizeof(addr_str)-1] = '\000';
5555 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5556 sizeof(addr_str) - 1)) {
5557 if (ifname)
5558 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5559 ifname);
5560 else
5561 coap_log_debug("added mcast group %s\n", addr_str);
5562 }
5563 mgroup_setup = 1;
5564 }
5565 }
5566 }
5567 }
5568 if (!mgroup_setup) {
5569 result = -1;
5570 }
5571
5572finish:
5573 freeaddrinfo(resmulti);
5574
5575 return result;
5576}
5577
5578void
5580 context->mcast_per_resource = 1;
5581}
5582
5583#endif /* ! COAP_SERVER_SUPPORT */
5584
5585#if COAP_CLIENT_SUPPORT
5586int
5587coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5588 if (session && coap_is_mcast(&session->addr_info.remote)) {
5589 switch (session->addr_info.remote.addr.sa.sa_family) {
5590#if COAP_IPV4_SUPPORT
5591 case AF_INET:
5592 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5593 (const char *)&hops, sizeof(hops)) < 0) {
5594 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5595 hops, coap_socket_strerror());
5596 return 0;
5597 }
5598 return 1;
5599#endif /* COAP_IPV4_SUPPORT */
5600#if COAP_IPV6_SUPPORT
5601 case AF_INET6:
5602 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5603 (const char *)&hops, sizeof(hops)) < 0) {
5604 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5605 hops, coap_socket_strerror());
5606 return 0;
5607 }
5608 return 1;
5609#endif /* COAP_IPV6_SUPPORT */
5610 default:
5611 break;
5612 }
5613 }
5614 return 0;
5615}
5616#endif /* COAP_CLIENT_SUPPORT */
5617
5618#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
5619COAP_API int
5621 const char *group_name COAP_UNUSED,
5622 const char *ifname COAP_UNUSED) {
5623 return -1;
5624}
5625
5626int
5628 size_t hops COAP_UNUSED) {
5629 return 0;
5630}
5631
5632void
5634}
5635#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_async_t coap_async_t
Async Entry information.
struct coap_proxy_entry_t coap_proxy_entry_t
Proxy information.
#define PRIuS
#define PRIdS
#define PRIu32
const char * coap_socket_strerror(void)
Definition coap_io.c:935
void coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length)
Given a packet, set msg and msg_len to an address and length of the packet's data in memory.
Definition coap_io.c:203
void coap_update_io_timer(coap_context_t *context, coap_tick_t delay)
Update when to continue with I/O processing, unless packets come in in the meantime.
Definition coap_io.c:70
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:33
#define COAP_SOCKET_ERROR
Definition coap_io.h:53
coap_nack_reason_t
Definition coap_io.h:66
@ COAP_NACK_NOT_DELIVERABLE
Definition coap_io.h:68
@ COAP_NACK_TOO_MANY_RETRIES
Definition coap_io.h:67
@ COAP_NACK_ICMP_ISSUE
Definition coap_io.h:71
@ COAP_NACK_RST
Definition coap_io.h:69
@ COAP_NACK_BAD_RESPONSE
Definition coap_io.h:72
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
#define COAP_SOCKET_WANT_ACCEPT
non blocking server socket is waiting for accept
#define COAP_SOCKET_NOT_EMPTY
the socket is not empty
#define COAP_SOCKET_CAN_WRITE
non blocking socket can now write without blocking
#define COAP_SOCKET_BOUND
the socket is bound
#define COAP_SOCKET_WANT_READ
non blocking socket is waiting for reading
#define COAP_SOCKET_CAN_ACCEPT
non blocking server socket can now accept without blocking
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
#define COAP_SOCKET_CAN_CONNECT
non blocking client socket can now connect without blocking
void coap_epoll_ctl_mod(coap_socket_t *sock, uint32_t events, const char *func)
Epoll specific function to modify the state of events that epoll is tracking on the appropriate file ...
#define COAP_SOCKET_WANT_CONNECT
non blocking client socket is waiting for connect
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
#define COAP_SOCKET_CONNECTED
the socket is connected
@ COAP_LAYER_SESSION
Library specific build wrapper for coap_internal.h.
#define COAP_API
void coap_dump_memory_type_counts(coap_log_t level)
Dumps the current usage of malloc'd memory types.
Definition coap_mem.c:747
void coap_memory_init(void)
Initializes libcoap's memory management.
@ COAP_NODE
Definition coap_mem.h:38
@ COAP_CONTEXT
Definition coap_mem.h:39
@ COAP_STRING
Definition coap_mem.h:34
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
CoAP mutex mechanism wrapper.
#define coap_mutex_init(a)
int coap_mutex_t
#define coap_mutex_destroy(a)
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition coap_net.c:83
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition coap_net.c:1135
static int send_recv_terminate
Definition coap_net.c:2147
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:3055
#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:5240
#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:4928
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:5172
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2432
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2473
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:4352
#define min(a, b)
Definition coap_net.c:76
void coap_startup(void)
Definition coap_net.c:5189
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4429
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:5173
#define FP1
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition coap_net.c:100
#define INET6_ADDRSTRLEN
Definition coap_net.c:72
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c:108
int coap_dtls_receive(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:243
int coap_dtls_context_load_pki_trust_store(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:124
int coap_dtls_context_set_pki_root_cas(coap_context_t *ctx COAP_UNUSED, const char *ca_file COAP_UNUSED, const char *ca_path COAP_UNUSED)
Definition coap_notls.c:116
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:186
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:181
uint16_t coap_option_num_t
Definition coap_option.h:24
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
Definition coap_option.h:30
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define SESSIONS_ITER(e, el, rtmp)
void coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition coap_net.c:2841
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:1092
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:1216
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:1187
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:2771
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:2176
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:1496
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:1107
#define COAP_IO_NO_WAIT
Definition coap_net.h:835
#define COAP_IO_WAIT
Definition coap_net.h:834
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:2830
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:2764
int coap_add_data_large_response_lkd(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_string_t *query, uint16_t media_type, int maxage, uint64_t etag, size_t length, const uint8_t *data, coap_release_large_data_t release_func, void *app_ptr)
Associates given data with the response pdu that is passed as fourth parameter.
void coap_block_delete_lg_srcv(coap_session_t *session, coap_lg_srcv_t *lg_srcv)
void coap_block_delete_lg_crcv(coap_session_t *session, coap_lg_crcv_t *lg_crcv)
int coap_handle_response_get_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd, coap_recurse_t recursive)
void coap_check_code_lg_xmit(const coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_resource_t *resource, const coap_string_t *query)
The function checks that the code in a newly formed lg_xmit created by coap_add_data_large_response_l...
int coap_handle_response_send_block(coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd)
coap_lg_crcv_t * coap_find_lg_crcv(coap_session_t *session, coap_pdu_t *pdu)
Find the current lg_crcv for the session that matches the pdu.
int coap_handle_request_put_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *uri_path, coap_opt_t *observe, int *added_block, coap_lg_srcv_t **free_lg_srcv)
#define STATE_TOKEN_BASE(t)
coap_lg_crcv_t * coap_block_new_lg_crcv(coap_session_t *session, coap_pdu_t *pdu, coap_lg_xmit_t *lg_xmit)
int coap_handle_request_send_block(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *query)
@ COAP_RECURSE_OK
#define COAP_OPT_BLOCK_SZX(opt)
Returns the value of the SZX-field of a Block option opt.
Definition coap_block.h:95
#define COAP_BLOCK_TRY_Q_BLOCK
Definition coap_block.h:67
#define COAP_BLOCK_SINGLE_BODY
Definition coap_block.h:66
int coap_get_block_b(const coap_session_t *session, const coap_pdu_t *pdu, coap_option_num_t number, coap_block_b_t *block)
Initializes block from pdu.
Definition coap_block.c: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_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
int coap_digest_final(coap_digest_ctx_t *digest_ctx, coap_digest_t *digest_buffer)
Finalize the coap_digest information into the provided digest_buffer.
int coap_digest_update(coap_digest_ctx_t *digest_ctx, const uint8_t *data, size_t data_len)
Update the coap_digest information with the next chunk of data.
void coap_digest_ctx_t
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
void coap_delete_cache_entry(coap_context_t *context, coap_cache_entry_t *cache_entry)
Remove a cache-entry from the hash list and free off all the appropriate contents apart from app_data...
int64_t coap_tick_diff_t
This data type is used to represent the difference between two clock_tick_t values.
Definition coap_time.h:163
void coap_clock_init(void)
Initializes the internal clock.
Definition coap_time.c:68
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:151
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:166
#define COAP_MAX_DELAY_TICKS
Definition coap_time.h:233
uint64_t coap_ticks_to_rt_us(coap_tick_t t)
Helper function that converts coap ticks to POSIX wallclock time in us.
Definition coap_time.c:128
void coap_prng_init_lkd(unsigned int seed)
Seeds the default random number generation function with the given seed.
Definition coap_prng.c:178
int coap_prng_lkd(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition coap_prng.c:190
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
void coap_resource_release_lkd(coap_resource_t *resource)
Decrement reference counter on a resource.
coap_print_status_t coap_print_wellknown_lkd(coap_context_t *context, unsigned char *buf, size_t *buflen, size_t offset, const coap_string_t *query_filter)
Prints the names of all known resources for context to buf.
coap_resource_t * coap_get_resource_from_uri_path_lkd(coap_context_t *context, coap_str_const_t *uri_path)
Returns the resource identified by the unique string uri_path.
void coap_resource_reference_lkd(coap_resource_t *resource)
Increment reference counter on a resource.
#define RESOURCES_ITER(r, tmp)
#define COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
Define this when invoking coap_resource_unknown_init2() if .well-known/core is to be passed to the un...
#define COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT
This resource has support for multicast requests.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_4_XX
Disable libcoap library suppressing 4.xx multicast responses (overridden by RFC7969 No-Response optio...
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS
Disable libcoap library from adding in delays to multicast requests before releasing the response bac...
void(* coap_method_handler_t)(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
Definition of message handler function.
#define COAP_RESOURCE_FLAGS_OSCORE_ONLY
Define this resource as an OSCORE enabled access only.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_5_XX
Disable libcoap library suppressing 5.xx multicast responses (overridden by RFC7969 No-Response optio...
uint32_t coap_print_status_t
Status word to encode the result of conditional print or copy operations such as coap_print_link().
#define COAP_PRINT_STATUS_ERROR
#define COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY
Force all large traffic to this resource to be presented as a single body to the request handler.
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_05
Enable libcoap library suppression of 205 multicast responses that are empty (overridden by RFC7969 N...
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_XX
Enable libcoap library suppressing 2.xx multicast responses (overridden by RFC7969 No-Response option...
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:5014
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:5320
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:3007
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:1364
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:4462
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:1244
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:833
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:1884
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:5104
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2294
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:1431
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:932
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1270
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:3114
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:2946
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:3153
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:106
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:2155
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:1486
COAP_API int coap_context_set_pki(coap_context_t *context, const coap_dtls_pki_t *setup_data)
Set the context's default PKI information for a server.
void coap_mcast_per_resource(coap_context_t *context)
Function interface to enable processing mcast requests on a per resource basis.
coap_response_t(* coap_response_handler_t)(coap_session_t *session, const coap_pdu_t *sent, const coap_pdu_t *received, const coap_mid_t mid)
Response handler that is used as callback in coap_context_t.
Definition coap_net.h:70
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:1174
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:2150
coap_resource_t *(* coap_resource_dynamic_create_t)(coap_session_t *session, const coap_pdu_t *request)
Definition of resource dynamic creation handler function.
Definition coap_net.h:118
void coap_register_response_handler(coap_context_t *context, coap_response_handler_t handler)
Registers a new message handler that is called whenever a response is received.
Definition coap_net.c:5264
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:3186
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:5304
COAP_API void coap_set_app_data(coap_context_t *context, void *app_data)
Definition coap_net.c:810
int coap_mcast_set_hops(coap_session_t *session, size_t hops)
Function interface for defining the hop count (ttl) for sending multicast traffic.
coap_response_t
Definition coap_net.h:54
void(* coap_ping_handler_t)(coap_session_t *session, const coap_pdu_t *received, const coap_mid_t mid)
Received Ping handler that is used as callback in coap_context_t.
Definition coap_net.h:95
void coap_ticks(coap_tick_t *t)
Returns the current value of an internal tick counter.
Definition coap_time.c:90
COAP_API void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition coap_net.c:824
void(* coap_nack_handler_t)(coap_session_t *session, const coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
Negative Acknowedge handler that is used as callback in coap_context_t.
Definition coap_net.h:83
void coap_context_set_shutdown_no_observe(coap_context_t *context)
Definition coap_net.c: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:1097
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:5292
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:818
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:1205
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:1082
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:5094
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:5313
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:5298
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:5003
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:5286
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:55
@ COAP_RESPONSE_OK
Response is fine.
Definition coap_net.h:56
const coap_bin_const_t * coap_get_session_client_psk_identity(const coap_session_t *coap_session)
Get the current client's PSK identity.
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition coap_notls.c:154
coap_session_t * coap_session_new_dtls_session(coap_session_t *session, coap_tick_t now)
Create a new DTLS session for the session.
int coap_dtls_hello(coap_session_t *coap_session, const uint8_t *data, size_t data_len)
Handling client HELLO messages from a new candiate peer.
int coap_dtls_set_cid_tuple_change(coap_context_t *context, uint8_t every)
Set the Connection ID client tuple frequency change for testing CIDs.
int coap_dtls_context_set_spsk(coap_context_t *coap_context, coap_dtls_spsk_t *setup_data)
Set the DTLS context's default server PSK information.
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:166
const coap_bin_const_t * coap_get_session_client_psk_key(const coap_session_t *coap_session)
Get the current client's PSK key.
const coap_bin_const_t * coap_get_session_server_psk_key(const coap_session_t *coap_session)
Get the current server's PSK key.
const coap_bin_const_t * coap_get_session_server_psk_hint(const coap_session_t *coap_session)
Get the current server's PSK identity hint.
#define COAP_DTLS_PKI_SETUP_VERSION
Latest PKI setup version.
Definition coap_dtls.h:311
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:50
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:47
unsigned int coap_decode_var_bytes(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:38
uint64_t coap_decode_var_bytes8(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:70
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:80
coap_event_t
Scalar type to represent different events, e.g.
Definition coap_event.h:38
@ COAP_EVENT_OSCORE_DECODE_ERROR
Triggered when there is an OSCORE decode of OSCORE option failure.
Definition coap_event.h:132
@ COAP_EVENT_SESSION_CONNECTED
Triggered when TCP layer completes exchange of CSM information.
Definition coap_event.h:65
@ COAP_EVENT_RECONNECT_FAILED
Triggered when a session failed, and a reconnect is going to be attempted.
Definition coap_event.h:151
@ COAP_EVENT_OSCORE_INTERNAL_ERROR
Triggered when there is an OSCORE internal error i.e malloc failed.
Definition coap_event.h:130
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition coap_event.h:43
@ COAP_EVENT_TCP_FAILED
Triggered when TCP layer fails for some reason.
Definition coap_event.h:59
@ COAP_EVENT_WS_CONNECTED
Triggered when the WebSockets layer is up.
Definition coap_event.h:139
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:45
@ COAP_EVENT_BLOCK_ISSUE
Triggered when a block transfer could not be handled.
Definition coap_event.h:79
@ COAP_EVENT_SESSION_FAILED
Triggered when TCP layer fails following exchange of CSM information.
Definition coap_event.h:69
@ COAP_EVENT_PARTIAL_BLOCK
Triggered when not all of a large body has been received.
Definition coap_event.h:75
@ COAP_EVENT_XMIT_BLOCK_FAIL
Triggered when not all of a large body has been transmitted.
Definition coap_event.h:77
@ COAP_EVENT_SERVER_SESSION_NEW
Called in the CoAP IO loop if a new server-side session is created due to an incoming connection.
Definition coap_event.h:91
@ COAP_EVENT_OSCORE_NOT_ENABLED
Triggered when trying to use OSCORE to decrypt, but it is not enabled.
Definition coap_event.h:124
@ COAP_EVENT_RECONNECT_STARTED
Triggered when a session starts to reconnect.
Definition coap_event.h:157
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:141
@ COAP_EVENT_RECONNECT_NO_MORE
Triggered when a session failed, and retry reconnect attempts failed.
Definition coap_event.h:155
@ COAP_EVENT_SESSION_CLOSED
Triggered when TCP layer closes following exchange of CSM information.
Definition coap_event.h:67
@ COAP_EVENT_FIRST_PDU_FAIL
Triggered when the initial app PDU cannot be transmitted.
Definition coap_event.h:116
@ 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:100
@ COAP_EVENT_OSCORE_NO_SECURITY
Triggered when there is no OSCORE security definition found.
Definition coap_event.h:128
@ COAP_EVENT_DTLS_RENEGOTIATE
Triggered when (D)TLS session renegotiated.
Definition coap_event.h:47
@ COAP_EVENT_BAD_PACKET
Triggered when badly formatted packet received.
Definition coap_event.h:112
@ 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:106
@ COAP_EVENT_MSG_RETRANSMITTED
Triggered when a message is retransmitted.
Definition coap_event.h:114
@ COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD
Triggered when there is no OSCORE encrypted payload provided.
Definition coap_event.h:126
@ COAP_EVENT_RECONNECT_SUCCESS
Triggered when a session failed, and a reconnect is successful.
Definition coap_event.h:153
@ COAP_EVENT_TCP_CLOSED
Triggered when TCP layer is closed.
Definition coap_event.h:57
@ COAP_EVENT_WS_PACKET_SIZE
Triggered when there is an oversize WebSockets packet.
Definition coap_event.h:137
@ COAP_EVENT_TCP_CONNECTED
Triggered when TCP layer connects.
Definition coap_event.h:55
@ COAP_EVENT_OSCORE_DECRYPTION_FAILURE
Triggered when there is an OSCORE decryption failure.
Definition coap_event.h:122
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:146
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:49
coap_mutex_t coap_lock_t
#define coap_lock_callback(func)
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, func)
Dummy for no thread-safe code.
#define coap_lock_callback_ret_release(r, func, failed)
Dummy for no thread-safe code.
#define coap_lock_unlock()
Dummy for no thread-safe code.
#define coap_lock_check_locked()
Dummy for no thread-safe code.
#define coap_lock_callback_release(func, failed)
Dummy for no thread-safe code.
#define coap_lock_lock(failed)
Dummy for no thread-safe code.
#define coap_lock_init()
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:126
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition coap_debug.c:103
#define coap_log_alert(...)
Definition coap_debug.h:90
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition coap_debug.c:793
#define coap_log_emerg(...)
Definition coap_debug.h:87
size_t coap_print_addr(const coap_address_t *addr, unsigned char *buf, size_t len)
Print the address into the defined buffer.
Definition coap_debug.c:241
const char * coap_endpoint_str(const coap_endpoint_t *endpoint)
Get endpoint description.
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:114
#define coap_log_warn(...)
Definition coap_debug.h:108
#define coap_log_err(...)
Definition coap_debug.h:102
@ COAP_LOG_DEBUG
Definition coap_debug.h:64
@ COAP_LOG_WARN
Definition coap_debug.h:61
int coap_netif_strm_connect2(coap_session_t *session)
Layer function interface for Netif stream connect (tcp).
ssize_t coap_netif_dgrm_read(coap_session_t *session, coap_packet_t *packet)
Function interface for layer data datagram receiving for sessions.
Definition coap_netif.c:72
ssize_t coap_netif_dgrm_read_ep(coap_endpoint_t *endpoint, coap_packet_t *packet)
Function interface for layer data datagram receiving for endpoints.
int coap_netif_available(coap_session_t *session)
Function interface to check whether netif for session is still available.
Definition coap_netif.c:25
#define COAP_OBSERVE_CANCEL
The value COAP_OBSERVE_CANCEL in a GET/FETCH request option COAP_OPTION_OBSERVE indicates that the ob...
#define COAP_OBSERVE_ESTABLISH
The value COAP_OBSERVE_ESTABLISH in a GET/FETCH request option COAP_OPTION_OBSERVE indicates a new ob...
coap_opt_t * coap_option_next(coap_opt_iterator_t *oi)
Updates the iterator oi to point to the next option.
uint32_t coap_opt_length(const coap_opt_t *opt)
Returns the length of the given option.
coap_opt_iterator_t * coap_option_iterator_init(const coap_pdu_t *pdu, coap_opt_iterator_t *oi, const coap_opt_filter_t *filter)
Initializes the given option iterator oi to point to the beginning of the pdu's option list.
#define COAP_OPT_ALL
Pre-defined filter that includes all options.
void coap_option_filter_clear(coap_opt_filter_t *filter)
Clears filter filter.
coap_opt_t * coap_check_option(const coap_pdu_t *pdu, coap_option_num_t number, coap_opt_iterator_t *oi)
Retrieves the first option of number number from pdu.
const uint8_t * coap_opt_value(const coap_opt_t *opt)
Returns a pointer to the value of the given option.
int coap_option_filter_get(coap_opt_filter_t *filter, coap_option_num_t option)
Checks if number is contained in filter.
int coap_option_filter_set(coap_opt_filter_t *filter, coap_option_num_t option)
Sets the corresponding entry for number in filter.
coap_pdu_t * coap_oscore_new_pdu_encrypted_lkd(coap_session_t *session, coap_pdu_t *pdu, coap_bin_const_t *kid_context, oscore_partial_iv_t send_partial_iv)
Encrypts the specified pdu when OSCORE encryption is required on session.
struct coap_pdu_t * coap_oscore_decrypt_pdu(coap_session_t *session, coap_pdu_t *pdu)
Decrypts the OSCORE-encrypted parts of pdu when OSCORE is used.
int coap_rebuild_pdu_for_proxy(coap_pdu_t *pdu)
Convert PDU to use Proxy-Scheme option if Proxy-Uri option is present.
void coap_delete_all_oscore(coap_context_t *context)
Cleanup all allocated OSCORE information.
#define COAP_PDU_IS_RESPONSE(pdu)
coap_pdu_t * coap_pdu_reference_lkd(coap_pdu_t *pdu)
Increment reference counter on a pdu to stop it prematurely getting freed off when coap_delete_pdu() ...
Definition coap_pdu.c:1661
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:194
#define COAP_TOKEN_EXT_2B_TKL
size_t coap_insert_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Inserts option of given number in the pdu with the appropriate data.
Definition coap_pdu.c:639
int coap_remove_option(coap_pdu_t *pdu, coap_option_num_t number)
Removes (first) option of given number from the pdu.
Definition coap_pdu.c:499
int coap_pdu_parse_opt(coap_pdu_t *pdu, coap_opt_filter_t *error_opts)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition coap_pdu.c:1358
#define COAP_DROPPED_RESPONSE
Indicates that a response is suppressed.
int coap_pdu_parse_header(coap_pdu_t *pdu, coap_proto_t proto)
Decode the protocol specific header for the specified PDU.
Definition coap_pdu.c:1084
size_t coap_pdu_parse_header_size(coap_proto_t proto, const uint8_t *data)
Interprets data to determine the number of bytes in the header.
Definition coap_pdu.c:1000
#define COAP_PDU_DELAYED
#define COAP_PDU_IS_EMPTY(pdu)
#define COAP_PDU_IS_SIGNALING(pdu)
int coap_option_check_repeatable(coap_option_num_t number)
Check whether the option is allowed to be repeated or not.
Definition coap_pdu.c:593
size_t coap_update_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Updates existing first option of given number in the pdu with the new data.
Definition coap_pdu.c:733
#define COAP_TOKEN_EXT_1B_TKL
size_t coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto)
Compose the protocol specific header for the specified PDU.
Definition coap_pdu.c:1523
#define COAP_DEFAULT_VERSION
int coap_pdu_parse2(coap_proto_t proto, const uint8_t *data, size_t length, coap_pdu_t *pdu, coap_opt_filter_t *error_opts)
Parses data into the CoAP PDU structure given in result.
Definition coap_pdu.c:1499
size_t coap_pdu_parse_size(coap_proto_t proto, const uint8_t *data, size_t length)
Parses data to extract the message size.
Definition coap_pdu.c:1031
int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size)
Dynamically grows the size of pdu to new_size.
Definition coap_pdu.c:307
#define COAP_PDU_IS_REQUEST(pdu)
size_t coap_add_option_internal(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Adds option of given number to pdu that is passed as first parameter.
Definition coap_pdu.c:789
#define COAP_OPTION_HOP_LIMIT
Definition coap_pdu.h:137
#define COAP_OPTION_NORESPONSE
Definition coap_pdu.h:150
#define COAP_OPTION_URI_HOST
Definition coap_pdu.h:124
#define COAP_OPTION_IF_MATCH
Definition coap_pdu.h:123
#define COAP_OPTION_BLOCK2
Definition coap_pdu.h:142
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition coap_pdu.c:960
#define COAP_OPTION_CONTENT_FORMAT
Definition coap_pdu.h:132
#define COAP_OPTION_BLOCK1
Definition coap_pdu.h:143
#define COAP_OPTION_Q_BLOCK1
Definition coap_pdu.h:139
#define COAP_OPTION_PROXY_SCHEME
Definition coap_pdu.h:147
#define COAP_OPTION_URI_QUERY
Definition coap_pdu.h:136
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:268
#define COAP_TOKEN_DEFAULT_MAX
Definition coap_pdu.h:60
#define COAP_OPTION_IF_NONE_MATCH
Definition coap_pdu.h:126
#define COAP_TOKEN_EXT_MAX
Definition coap_pdu.h:64
#define COAP_OPTION_URI_PATH
Definition coap_pdu.h:131
#define COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH
Definition coap_pdu.h:204
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:165
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:168
coap_pdu_code_t
Set of codes available for a PDU.
Definition coap_pdu.h:332
#define COAP_OPTION_OSCORE
Definition coap_pdu.h:130
coap_pdu_type_t
CoAP PDU message type definitions.
Definition coap_pdu.h:72
#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
Definition coap_pdu.h:203
int coap_add_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds token of length len to pdu.
Definition coap_pdu.c:366
#define COAP_OPTION_Q_BLOCK2
Definition coap_pdu.h:145
#define COAP_SIGNALING_OPTION_CUSTODY
Definition coap_pdu.h:207
int coap_pdu_parse(coap_proto_t proto, const uint8_t *data, size_t length, coap_pdu_t *pdu)
Parses data into the CoAP PDU structure given in result.
Definition coap_pdu.c:1489
#define COAP_OPTION_RTAG
Definition coap_pdu.h:151
#define COAP_OPTION_URI_PORT
Definition coap_pdu.h:128
coap_pdu_t * coap_pdu_init(coap_pdu_type_t type, coap_pdu_code_t code, coap_mid_t mid, size_t size)
Creates a new CoAP PDU with at least enough storage space for the given size maximum message size.
Definition coap_pdu.c:102
#define COAP_OPTION_ACCEPT
Definition coap_pdu.h:138
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:271
#define COAP_OPTION_PROXY_URI
Definition coap_pdu.h:146
#define COAP_OPTION_OBSERVE
Definition coap_pdu.h:127
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition coap_pdu.h:57
#define COAP_BERT_BASE
Definition coap_pdu.h:48
#define COAP_OPTION_ECHO
Definition coap_pdu.h:149
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition coap_pdu.h:219
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition coap_pdu.h:202
int coap_add_data(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds given data to the pdu that is passed as first parameter.
Definition coap_pdu.c:854
@ COAP_REQUEST_GET
Definition coap_pdu.h:83
@ COAP_PROTO_WS
Definition coap_pdu.h:324
@ COAP_PROTO_DTLS
Definition coap_pdu.h:321
@ COAP_PROTO_UDP
Definition coap_pdu.h:320
@ COAP_PROTO_TLS
Definition coap_pdu.h:323
@ COAP_PROTO_WSS
Definition coap_pdu.h:325
@ COAP_PROTO_TCP
Definition coap_pdu.h:322
@ COAP_SIGNALING_CODE_ABORT
Definition coap_pdu.h:375
@ COAP_REQUEST_CODE_PUT
Definition coap_pdu.h:337
@ COAP_REQUEST_CODE_POST
Definition coap_pdu.h:336
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:371
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:372
@ COAP_REQUEST_CODE_DELETE
Definition coap_pdu.h:338
@ COAP_SIGNALING_CODE_PONG
Definition coap_pdu.h:373
@ COAP_EMPTY_CODE
Definition coap_pdu.h:333
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:335
@ COAP_SIGNALING_CODE_RELEASE
Definition coap_pdu.h:374
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:339
@ COAP_MESSAGE_NON
Definition coap_pdu.h:74
@ COAP_MESSAGE_ACK
Definition coap_pdu.h:75
@ COAP_MESSAGE_CON
Definition coap_pdu.h:73
@ COAP_MESSAGE_RST
Definition coap_pdu.h:76
void coap_register_proxy_response_handler(coap_context_t *context, coap_proxy_response_handler_t handler)
Registers a new message handler that is called whenever a response is received by the proxy logic.
Definition coap_net.c:5275
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.
coap_session_t * coap_endpoint_get_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Lookup the server session for the packet received on an endpoint, or create a new one.
void coap_free_endpoint_lkd(coap_endpoint_t *endpoint)
Release an endpoint and all the structures associated with it.
void coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2503
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:1122
size_t coap_session_max_pdu_size_lkd(const coap_session_t *session)
Get maximum acceptable PDU size.
void coap_session_release_lkd(coap_session_t *session)
Decrement reference counter on a session.
coap_session_t * coap_session_reference_lkd(coap_session_t *session)
Increment reference counter on a session.
void coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
coap_endpoint_t * coap_new_endpoint_lkd(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto)
Create a new endpoint for communicating with peers.
coap_session_t * coap_new_server_session(coap_context_t *ctx, coap_endpoint_t *ep, void *extra)
Creates a new server session for the specified endpoint.
@ COAP_EXT_T_NOT_CHECKED
Not checked.
@ COAP_EXT_T_CHECKING
Token size check request sent.
@ COAP_EXT_T_CHECKED
Token size valid.
void coap_session_set_mtu(coap_session_t *session, unsigned mtu)
Set the session MTU.
coap_session_state_t
coap_session_state_t values
#define COAP_PROTO_NOT_RELIABLE(p)
#define COAP_PROTO_RELIABLE(p)
void(* coap_app_data_free_callback_t)(void *data)
Callback to free off the app data when the entry is being deleted / freed off.
@ COAP_SESSION_TYPE_HELLO
server-side ephemeral session for responding to a client hello
@ COAP_SESSION_TYPE_SERVER
server-side
@ COAP_SESSION_TYPE_CLIENT
client-side
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_ESTABLISHED
@ COAP_SESSION_STATE_NONE
void coap_delete_bin_const(coap_bin_const_t *s)
Deletes the given const binary data and releases any memory allocated.
Definition coap_str.c:120
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:77
coap_bin_const_t * coap_new_bin_const(const uint8_t *data, size_t size)
Take the specified byte array (text) and create a coap_bin_const_t * Returns a new const binary objec...
Definition coap_str.c:110
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:105
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:214
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:200
coap_string_t * coap_new_string(size_t size)
Returns a new string object with at least size+1 bytes storage allocated.
Definition coap_str.c:21
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition coap_str.c:46
int coap_delete_observer_request(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, coap_pdu_t *request)
Removes any subscription for session observer from resource and releases the allocated storage.
void coap_persist_cleanup(coap_context_t *context)
Close down persist tracking, releasing any memory used.
int coap_delete_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token)
Removes any subscription for session observer from resource and releases the allocated storage.
int coap_cancel_observe_lkd(coap_session_t *session, coap_binary_t *token, coap_pdu_type_t message_type)
Cancel an observe that is being tracked by the client large receive logic.
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Handles a failed observe notify.
coap_subscription_t * coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, const coap_pdu_t *pdu)
Adds the specified peer as observer for resource.
void coap_touch_observer(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Flags that data is ready to be sent to observers.
int coap_epoll_is_supported(void)
Determine whether epoll is supported or not.
Definition coap_net.c: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:1020
int coap_split_proxy_uri(const uint8_t *str_var, size_t len, coap_uri_t *uri)
Parses a given string into URI components.
Definition coap_uri.c:299
coap_string_t * coap_get_query(const coap_pdu_t *request)
Extract query string from request PDU according to escape rules in 6.5.8.
Definition coap_uri.c:969
#define COAP_UNUSED
Definition libcoap.h:74
#define COAP_STATIC_INLINE
Definition libcoap.h:57
coap_address_t remote
remote address and port
Definition coap_io.h:60
coap_address_t local
local address and port
Definition coap_io.h:61
Multi-purpose address abstraction.
struct sockaddr_in sin
struct sockaddr_in6 sin6
struct sockaddr sa
union coap_address_t::@0 addr
CoAP binary data definition with const data.
Definition coap_str.h:67
size_t length
length of binary data
Definition coap_str.h:68
const uint8_t * s
read-only binary data
Definition coap_str.h:69
CoAP binary data definition.
Definition coap_str.h:59
size_t length
length of binary data
Definition coap_str.h:60
uint8_t * s
binary data
Definition coap_str.h:61
Structure of Block options with BERT support.
Definition coap_block.h:55
unsigned int num
block number
Definition coap_block.h:56
uint32_t chunk_size
‍1024 if BERT
Definition coap_block.h:62
unsigned int bert
Operating as BERT.
Definition coap_block.h:61
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:59
unsigned int defined
Set if block found.
Definition coap_block.h:60
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:57
unsigned int szx
block size (0-6)
Definition coap_block.h:58
The CoAP stack's global state is stored in a coap_context_t object.
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
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.
unsigned int reconnect_time
Time to wait before reconnecting a failed client session.
uint8_t shutdown_no_send_observe
Do not send out unsolicited observe when coap_free_context() is called.
coap_nack_handler_t nack_cb
Called when a response issue has occurred.
coap_response_handler_t response_cb
Called when a response is received.
coap_resource_dynamic_create_t dyn_create_handler
Dynamc resource create handler.
coap_session_t * sessions
client sessions
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.
uint8_t retry_count
Number of times to retry reconnecting a.
coap_event_handler_t event_cb
Callback function that is used to signal events to the application.
coap_resource_t * resources
hash table or list of known resources
uint16_t * cache_ignore_options
CoAP options to ignore when creating a cache-key.
coap_opt_filter_t known_options
uint32_t csm_max_message_size
Value for CSM Max-Message-Size.
size_t cache_ignore_count
The number of CoAP options to ignore when creating a cache-key.
unsigned int max_handshake_sessions
Maximum number of simultaneous negotating sessions per endpoint.
coap_ping_handler_t ping_cb
Called when a CoAP ping is received.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
coap_cache_entry_t * cache
CoAP cache-entry cache.
uint8_t mcast_per_resource
Mcast controlled on a per resource basis.
coap_endpoint_t * endpoint
the endpoints used for listening
uint32_t csm_timeout_ms
Timeout for waiting for a CSM from the remote side.
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
uint8_t observe_no_clear
Observe 4.04 not to be sent on deleting resource.
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
coap_resource_t * unknown_resource
can be used for handling unknown resources
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
coap_bin_const_t key
Definition coap_dtls.h:385
coap_bin_const_t identity
Definition coap_dtls.h:384
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:447
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:316
uint8_t version
Definition coap_dtls.h:317
coap_bin_const_t hint
Definition coap_dtls.h:455
coap_bin_const_t key
Definition coap_dtls.h:456
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:505
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:537
Abstraction of virtual endpoint that can be attached to coap_context_t.
coap_context_t * context
endpoint's context
coap_session_t * sessions
hash table or list of active sessions
coap_address_t bind_addr
local interface address
coap_socket_t sock
socket object for the interface, if any
coap_proto_t proto
protocol used on this interface
uint64_t state_token
state token
uint32_t count
the number of packets sent for payload
coap_binary_t * app_token
original PDU token
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
Structure to hold large body (many blocks) client receive information.
uint64_t state_token
state token
coap_binary_t * app_token
app requesting PDU token
Structure to hold large body (many blocks) server receive information.
Structure to hold large body (many blocks) transmission information.
coap_tick_t last_all_sent
Last time all data sent or 0.
uint8_t blk_size
large block transmission size
union coap_lg_xmit_t::@1 b
int last_block
last acknowledged block number Block1 last transmitted Q-Block2
coap_pdu_t * sent_pdu
The sent pdu with all the data.
coap_l_block1_t b1
uint16_t option
large block transmisson CoAP option
Iterator to run through PDU options.
coap_option_num_t number
decoded option number
size_t length
length of payload
coap_addr_tuple_t addr_info
local and remote addresses
unsigned char * payload
payload
structure for CoAP PDUs
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
coap_pdu_code_t code
request method (value 1–31) or response code (value 64-255)
uint8_t hdr_size
actual size used for protocol-specific header (0 until header is encoded)
coap_bin_const_t actual_token
Actual token in pdu.
uint8_t * data
first byte of payload, if any
coap_mid_t mid
message id, if any, in regular host byte order
uint32_t e_token_length
length of Token space (includes leading extended bytes
size_t used_size
used bytes of storage for token, options and payload
uint8_t crit_opt
Set if unknown critical option for proxy.
coap_binary_t * data_free
Data to be freed off by coap_delete_pdu()
size_t alloc_size
allocated storage for token, options and payload
coap_session_t * session
Session responsible for PDU or NULL.
coap_pdu_type_t type
message type
Queue entry.
coap_address_t remote
For re-transmission - where the node is going.
coap_session_t * session
the CoAP session
coap_pdu_t * pdu
the CoAP PDU to send
unsigned int timeout
the randomized timeout value
uint8_t is_mcast
Set if this is a queued mcast response.
struct coap_queue_t * next
coap_mid_t id
CoAP message id.
coap_tick_t t
when to send PDU for the next time
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Abstraction of resource that can be attached to coap_context_t.
coap_str_const_t ** proxy_name_list
Array valid names this host is known by (proxy support)
coap_str_const_t * uri_path
Request URI Path for this resource.
unsigned int observe
The next value for the Observe option.
coap_method_handler_t handler[7]
Used to store handlers for the seven coap methods GET, POST, PUT, DELETE, FETCH, PATCH and IPATCH.
uint32_t ref
Resource reference count.
unsigned int is_proxy_uri
resource created for proxy URI handler
unsigned int is_dynamic
create unknown resource dynamically
unsigned int is_unknown
resource created for unknown handler
unsigned int is_reverse_proxy
resource created for reverse proxy URI handler
unsigned int observable
can be observed
size_t proxy_name_count
Count of valid names this host is known by (proxy support)
int flags
zero or more COAP_RESOURCE_FLAGS_* or'd together
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
volatile uint8_t max_token_checked
Check for max token size coap_ext_token_check_t.
uint8_t csm_not_seen
Set if timeout waiting for CSM.
unsigned ref_subscriptions
reference count of current subscriptions
coap_tick_t doing_first_timeout
If doing_first, when to timeout.
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
uint8_t doing_first
Set if doing client's first request.
uint8_t delay_recursive
Set if in coap_client_delay_first()
coap_socket_t sock
socket object for the session, if any
coap_pdu_t * partial_pdu
incomplete incoming pdu
uint32_t max_token_size
Largest token size supported RFC8974.
coap_bin_const_t * psk_identity
If client, this field contains the current identity for server; When this field is NULL,...
coap_session_state_t state
current state of relationship with peer
uint8_t csm_bert_rem_support
CSM TCP BERT blocks supported (remote)
uint8_t client_initiated
Session initially started as a client.
coap_digest_t cached_pdu_cksum
Checksum of last CON request PDU.
coap_mid_t remote_test_mid
mid used for checking remote support
uint8_t read_header[8]
storage space for header of incoming message header
unsigned ref_proxy_subs
reference count of current proxy subscriptions
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
unsigned ref
reference count from queues
coap_response_t last_con_handler_res
The result of calling the response handler of the last CON.
coap_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
coap_bin_const_t * last_token
uint8_t doing_send_recv
Set if coap_send_recv() active.
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
size_t partial_read
if > 0 indicates number of bytes already read for an incoming message
void * tls
security parameters
uint16_t max_retransmit
maximum re-transmit count (default 4)
uint8_t csm_block_supported
CSM TCP blocks supported.
uint8_t proxy_session
Set if this is an ongoing proxy session.
uint8_t con_active
Active CON request sent.
coap_queue_t * delayqueue
list of delayed messages waiting to be sent
uint32_t tx_rtag
Next Request-Tag number to use.
coap_mid_t last_ping_mid
the last keepalive message id that was used in this session
coap_lg_srcv_t * lg_srcv
Server list of expected large receives.
coap_bin_const_t * req_token
Token in request pdu of coap_send_recv()
coap_pdu_t * resp_pdu
PDU returned in coap_send_recv() call.
coap_lg_crcv_t * lg_crcv
Client list of expected large receives.
coap_mid_t last_con_mid
The last CON mid that has been been processed.
coap_session_type_t type
client or server side socket
coap_mid_t last_ack_mid
The last ACK mid that has been been processed.
coap_pdu_t * doing_first_pdu
If doing fist, PDU to retry sending.
coap_context_t * context
session's context
uint8_t session_failed
Set if session failed and can try re-connect.
size_t partial_write
if > 0 indicates number of bytes already written from the pdu at the head of sendqueue
coap_pdu_t * cached_pdu
Cached copy of last ACK response PDU.
coap_bin_const_t * echo
last token used to make a request
coap_layer_func_t lfunc[COAP_LAYER_LAST]
Layer functions to use.
coap_session_t * session
Used to determine session owner.
coap_endpoint_t * endpoint
Used by the epoll logic for a listening endpoint.
coap_address_t mcast_addr
remote address and port (multicast track)
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values
CoAP string data definition with const data.
Definition coap_str.h:49
const uint8_t * s
read-only string data
Definition coap_str.h:51
size_t length
length of string
Definition coap_str.h:50
CoAP string data definition.
Definition coap_str.h:41
uint8_t * s
string data
Definition coap_str.h:43
size_t length
length of string
Definition coap_str.h:42
Number of notifications that may be sent non-confirmable before a confirmable message is sent to dete...
struct coap_session_t * session
subscriber session
coap_pdu_t * pdu
cache_key to identify requester
Representation of parsed URI.
Definition coap_uri.h:72
coap_str_const_t host
The host part of the URI.
Definition coap_uri.h:73