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