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