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