libcoap 4.3.5-develop-783b531
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_OSCORE_SUPPORT
875 coap_delete_all_oscore(context);
876#endif /* COAP_OSCORE_SUPPORT */
877
878#if COAP_SERVER_SUPPORT
879 coap_cache_entry_t *cp, *ctmp;
880 coap_endpoint_t *ep, *tmp;
881
882 HASH_ITER(hh, context->cache, cp, ctmp) {
883 coap_delete_cache_entry(context, cp);
884 }
885 if (context->cache_ignore_count) {
886 coap_free_type(COAP_STRING, context->cache_ignore_options);
887 }
888
889 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
890 coap_free_endpoint_lkd(ep);
891 }
892#endif /* COAP_SERVER_SUPPORT */
893
894#if COAP_CLIENT_SUPPORT
895 coap_session_t *sp, *rtmp;
896
897 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
899 }
900#endif /* COAP_CLIENT_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 if (ctx->p_osc_ctx)
1014 break;
1015#endif /* COAP_OSCORE_SUPPORT */
1016 /* Fall Through */
1017 default:
1018 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1019#if COAP_SERVER_SUPPORT
1020 if ((opt_iter.number & 0x02) == 0) {
1021 coap_opt_iterator_t t_iter;
1022
1023 /* Safe to forward - check if proxy pdu */
1024 if (session->proxy_session)
1025 break;
1026 if (COAP_PDU_IS_REQUEST(pdu) && ctx->proxy_uri_resource &&
1027 (coap_check_option(pdu, COAP_OPTION_PROXY_URI, &t_iter) ||
1029 pdu->crit_opt = 1;
1030 break;
1031 }
1032 if (COAP_PDU_IS_REQUEST(pdu) && ctx->unknown_resource &&
1033 ctx->unknown_resource->is_reverse_proxy) {
1034 pdu->crit_opt = 1;
1035 break;
1036 }
1037 }
1038#endif /* COAP_SERVER_SUPPORT */
1039 coap_log_debug("unknown critical option %d\n", opt_iter.number);
1040 ok = 0;
1041
1042 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1043 * slots have been used up and no more options can be tracked.
1044 * Safe to break out of this loop as ok is already set. */
1045 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1046 goto overflow;
1047 }
1048 }
1049 }
1050 }
1051 if (last_number == opt_iter.number) {
1052 /* Check for duplicated option RFC 5272 5.4.5 */
1053 if (!coap_option_check_repeatable(opt_iter.number)) {
1054 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1055 ok = 0;
1056 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1057 goto overflow;
1058 }
1059 }
1060 }
1061 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
1062 COAP_PDU_IS_REQUEST(pdu)) {
1063 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
1064 coap_block_b_t block;
1065
1066 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
1067 if (block.m) {
1068 size_t used_size = pdu->used_size;
1069 unsigned char buf[4];
1070
1071 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
1072 block.m = 0;
1073 coap_update_option(pdu, opt_iter.number,
1074 coap_encode_var_safe(buf, sizeof(buf),
1075 ((block.num << 4) |
1076 (block.m << 3) |
1077 block.aszx)),
1078 buf);
1079 if (used_size != pdu->used_size) {
1080 /* Unfortunately need to restart the scan */
1081 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1082 last_number = -1;
1083 continue;
1084 }
1085 }
1086 }
1087 }
1088 last_number = opt_iter.number;
1089 }
1090overflow:
1091 return ok;
1092}
1093
1095coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
1096 coap_mid_t mid;
1097
1099 mid = coap_send_rst_lkd(session, request);
1101 return mid;
1102}
1103
1106 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
1107}
1108
1110coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
1111 coap_mid_t mid;
1112
1114 mid = coap_send_ack_lkd(session, request);
1116 return mid;
1117}
1118
1121 coap_pdu_t *response;
1123
1125 if (request && request->type == COAP_MESSAGE_CON &&
1126 COAP_PROTO_NOT_RELIABLE(session->proto)) {
1127 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
1128 if (response)
1129 result = coap_send_internal(session, response, NULL);
1130 }
1131 return result;
1132}
1133
1134ssize_t
1136 ssize_t bytes_written = -1;
1137 assert(pdu->hdr_size > 0);
1138
1139 /* Caller handles partial writes */
1140 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1141 pdu->token - pdu->hdr_size,
1142 pdu->used_size + pdu->hdr_size);
1144 return bytes_written;
1145}
1146
1147static ssize_t
1149 ssize_t bytes_written;
1150
1151 if (session->state == COAP_SESSION_STATE_NONE) {
1152#if ! COAP_CLIENT_SUPPORT
1153 return -1;
1154#else /* COAP_CLIENT_SUPPORT */
1155 if (session->type != COAP_SESSION_TYPE_CLIENT)
1156 return -1;
1157#endif /* COAP_CLIENT_SUPPORT */
1158 }
1159
1160 if (pdu->type == COAP_MESSAGE_CON &&
1161 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1162 coap_is_mcast(&session->addr_info.remote)) {
1163 /* Violates RFC72522 8.1 */
1164 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1165 return -1;
1166 }
1167
1168 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1169 (pdu->type == COAP_MESSAGE_CON &&
1170 session->con_active >= COAP_NSTART(session))) {
1171 return coap_session_delay_pdu(session, pdu, node);
1172 }
1173
1174 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1175 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1176 return coap_session_delay_pdu(session, pdu, node);
1177
1178 bytes_written = coap_session_send_pdu(session, pdu);
1179 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1181 session->con_active++;
1182
1183 return bytes_written;
1184}
1185
1188 const coap_pdu_t *request,
1189 coap_pdu_code_t code,
1190 coap_opt_filter_t *opts) {
1191 coap_mid_t mid;
1192
1194 mid = coap_send_error_lkd(session, request, code, opts);
1196 return mid;
1197}
1198
1201 const coap_pdu_t *request,
1202 coap_pdu_code_t code,
1203 coap_opt_filter_t *opts) {
1204 coap_pdu_t *response;
1206
1207 assert(request);
1208 assert(session);
1209
1210 response = coap_new_error_response(request, code, opts);
1211 if (response)
1212 result = coap_send_internal(session, response, NULL);
1213
1214 return result;
1215}
1216
1219 coap_pdu_type_t type) {
1220 coap_mid_t mid;
1221
1223 mid = coap_send_message_type_lkd(session, request, type);
1225 return mid;
1226}
1227
1230 coap_pdu_type_t type) {
1231 coap_pdu_t *response;
1233
1235 if (request && COAP_PROTO_NOT_RELIABLE(session->proto)) {
1236 response = coap_pdu_init(type, 0, request->mid, 0);
1237 if (response)
1238 result = coap_send_internal(session, response, NULL);
1239 }
1240 return result;
1241}
1242
1256unsigned int
1257coap_calc_timeout(coap_session_t *session, unsigned char r) {
1258 unsigned int result;
1259
1260 /* The integer 1.0 as a Qx.FRAC_BITS */
1261#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1262
1263 /* rounds val up and right shifts by frac positions */
1264#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1265
1266 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1267 * make the result a rounded Qx.FRAC_BITS */
1268 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1269
1270 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1271 * make the result a rounded Qx.FRAC_BITS */
1272 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1273
1274 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1275 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1276 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1277
1278#undef FP1
1279#undef SHR_FP
1280}
1281
1284 coap_queue_t *node) {
1285 coap_tick_t now;
1286
1287 node->session = coap_session_reference_lkd(session);
1288
1289 /* Set timer for pdu retransmission. If this is the first element in
1290 * the retransmission queue, the base time is set to the current
1291 * time and the retransmission time is node->timeout. If there is
1292 * already an entry in the sendqueue, we must check if this node is
1293 * to be retransmitted earlier. Therefore, node->timeout is first
1294 * normalized to the base time and then inserted into the queue with
1295 * an adjusted relative time.
1296 */
1297 coap_ticks(&now);
1298 if (context->sendqueue == NULL) {
1299 node->t = node->timeout << node->retransmit_cnt;
1300 context->sendqueue_basetime = now;
1301 } else {
1302 /* make node->t relative to context->sendqueue_basetime */
1303 node->t = (now - context->sendqueue_basetime) +
1304 (node->timeout << node->retransmit_cnt);
1305 }
1306 coap_address_copy(&node->remote, &session->addr_info.remote);
1307
1308 coap_insert_node(&context->sendqueue, node);
1309
1310 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1311 coap_session_str(node->session), node->id,
1312 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1314
1315 coap_update_io_timer(context, node->t);
1316
1317 return node->id;
1318}
1319
1320#if COAP_CLIENT_SUPPORT
1321/*
1322 * Sent out a test PDU for Extended Token
1323 */
1324static coap_mid_t
1325coap_send_test_extended_token(coap_session_t *session) {
1326 coap_pdu_t *pdu;
1328 size_t i;
1329 coap_binary_t *token;
1330 coap_lg_crcv_t *lg_crcv;
1331
1332 coap_log_debug("Testing for Extended Token support\n");
1333 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1335 coap_new_message_id_lkd(session),
1337 if (!pdu)
1338 return COAP_INVALID_MID;
1339
1340 token = coap_new_binary(session->max_token_size);
1341 if (token == NULL) {
1343 return COAP_INVALID_MID;
1344 }
1345 for (i = 0; i < session->max_token_size; i++) {
1346 token->s[i] = (uint8_t)(i + 1);
1347 }
1348 coap_add_token(pdu, session->max_token_size, token->s);
1349 coap_delete_binary(token);
1350
1353 pdu->actual_token.length);
1354
1356
1357 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1358
1359 /* Need to track incase OSCORE / Echo etc. comes back after non-piggy-backed ACK */
1360 lg_crcv = coap_block_new_lg_crcv(session, pdu, NULL);
1361 if (lg_crcv) {
1362 LL_PREPEND(session->lg_crcv, lg_crcv);
1363 }
1364 mid = coap_send_internal(session, pdu, NULL);
1365 if (mid == COAP_INVALID_MID)
1366 return COAP_INVALID_MID;
1367 session->remote_test_mid = mid;
1368 return mid;
1369}
1370#endif /* COAP_CLIENT_SUPPORT */
1371
1372/*
1373 * Return: 0 Something failed
1374 * 1 Success
1375 */
1376int
1378#if COAP_CLIENT_SUPPORT
1379 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1380 int timeout_ms = 5000;
1381 coap_session_state_t current_state = session->state;
1382
1383 if (session->delay_recursive) {
1384 return 0;
1385 } else {
1386 session->delay_recursive = 1;
1387 }
1388 /*
1389 * Need to wait for first request to get out and response back before
1390 * continuing.. Response handler has to clear doing_first if not an error.
1391 */
1393 while (session->doing_first != 0) {
1394 int result = coap_io_process_lkd(session->context, 1000);
1395
1396 if (result < 0) {
1397 coap_reset_doing_first(session);
1398 session->delay_recursive = 0;
1399 coap_session_release_lkd(session);
1400 return 0;
1401 }
1402
1403 /* coap_io_process_lkd() may have updated session state */
1404 if (session->state == COAP_SESSION_STATE_CSM &&
1405 current_state != COAP_SESSION_STATE_CSM) {
1406 /* Update timeout and restart the clock for CSM timeout */
1407 current_state = COAP_SESSION_STATE_CSM;
1408 timeout_ms = session->context->csm_timeout_ms;
1409 result = 0;
1410 }
1411
1412 if (result < timeout_ms) {
1413 timeout_ms -= result;
1414 } else {
1415 if (session->doing_first == 1) {
1416 /* Timeout failure of some sort with first request */
1417 if (session->state == COAP_SESSION_STATE_CSM) {
1418 coap_log_debug("** %s: timeout waiting for CSM response\n",
1419 coap_session_str(session));
1420 session->csm_not_seen = 1;
1421 } else {
1422 coap_log_debug("** %s: timeout waiting for first response\n",
1423 coap_session_str(session));
1424 }
1425 coap_reset_doing_first(session);
1426 coap_session_connected(session);
1427 }
1428 }
1429 }
1430 session->delay_recursive = 0;
1431 coap_session_release_lkd(session);
1432 }
1433#else /* ! COAP_CLIENT_SUPPORT */
1434 (void)session;
1435#endif /* ! COAP_CLIENT_SUPPORT */
1436 return 1;
1437}
1438
1439/*
1440 * return 0 Invalid
1441 * 1 Valid
1442 */
1443int
1445
1446 /* Check validity of sending code */
1447 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1448 case 0: /* Empty or request */
1449 case 2: /* Success */
1450 case 3: /* Reserved for future use */
1451 case 4: /* Client error */
1452 case 5: /* Server error */
1453 break;
1454 case 7: /* Reliable signalling */
1455 if (COAP_PROTO_RELIABLE(session->proto))
1456 break;
1457 /* Not valid if UDP */
1458 /* Fall through */
1459 case 1: /* Invalid */
1460 case 6: /* Invalid */
1461 default:
1462 return 0;
1463 }
1464 return 1;
1465}
1466
1467#if COAP_CLIENT_SUPPORT
1468/*
1469 * If type is CON and protocol is not reliable, there is no need to set up
1470 * lg_crcv if it can be built up based on sent PDU if there is a
1471 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1472 * (Q-)Block1.
1473 */
1474static int
1475coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1476 coap_opt_iterator_t opt_iter;
1477
1478 if (!COAP_PDU_IS_REQUEST(pdu))
1479 return 0;
1480
1481 if (
1482#if COAP_OSCORE_SUPPORT
1483 session->oscore_encryption ||
1484#endif /* COAP_OSCORE_SUPPORT */
1485 pdu->type == COAP_MESSAGE_NON ||
1486 COAP_PROTO_RELIABLE(session->proto) ||
1487 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1488#if COAP_Q_BLOCK_SUPPORT
1489 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1490#endif /* COAP_Q_BLOCK_SUPPORT */
1491 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1492 return 1;
1493 }
1494 return 0;
1495}
1496#endif /* COAP_CLIENT_SUPPORT */
1497
1500 coap_mid_t mid;
1501
1503 mid = coap_send_lkd(session, pdu);
1505 return mid;
1506}
1507
1511#if COAP_CLIENT_SUPPORT
1512 coap_lg_crcv_t *lg_crcv = NULL;
1513 coap_opt_iterator_t opt_iter;
1514 coap_block_b_t block;
1515 int observe_action = -1;
1516 int have_block1 = 0;
1517 coap_opt_t *opt;
1518#endif /* COAP_CLIENT_SUPPORT */
1519
1520 assert(pdu);
1521
1523
1524 /* Check validity of sending code */
1525 if (!coap_check_code_class(session, pdu)) {
1526 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1528 pdu->code & 0x1f);
1529 goto error;
1530 }
1531 pdu->session = session;
1532#if COAP_CLIENT_SUPPORT
1533 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1534 !coap_netif_available(session) && !session->session_failed) {
1535 coap_log_debug("coap_send: Socket closed\n");
1536 goto error;
1537 }
1538
1539 if (session->doing_first) {
1540 LL_APPEND(session->doing_first_pdu, pdu);
1542 coap_log_debug("** %s: mid=0x%04x: queued\n",
1543 coap_session_str(session), pdu->mid);
1544 return pdu->mid;
1545 }
1546
1547 /* Indicate support for Extended Tokens if appropriate */
1548 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1550 session->type == COAP_SESSION_TYPE_CLIENT &&
1551 COAP_PDU_IS_REQUEST(pdu)) {
1552 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1553 /*
1554 * When the pass / fail response for Extended Token is received, this PDU
1555 * will get transmitted.
1556 */
1557 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1558 goto error;
1559 }
1560 }
1561 /*
1562 * For reliable protocols, this will get cleared after CSM exchanged
1563 * in coap_session_connected() where Token size support is indicated in the CSM.
1564 */
1565 session->doing_first = 1;
1566 coap_ticks(&session->doing_first_timeout);
1567 LL_PREPEND(session->doing_first_pdu, pdu);
1568 if (session->proto != COAP_PROTO_UDP) {
1569 /* In case the next handshake / CSM is already in */
1571 }
1572 /*
1573 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1574 * will get called again.
1575 */
1577 coap_log_debug("** %s: mid=0x%04x: queued\n",
1578 coap_session_str(session), pdu->mid);
1579 return pdu->mid;
1580 }
1581#if COAP_Q_BLOCK_SUPPORT
1582 /* Indicate support for Q-Block if appropriate */
1583 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1584 session->type == COAP_SESSION_TYPE_CLIENT &&
1585 COAP_PDU_IS_REQUEST(pdu)) {
1586 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1587 goto error;
1588 }
1589 session->doing_first = 1;
1590 coap_ticks(&session->doing_first_timeout);
1591 LL_PREPEND(session->doing_first_pdu, pdu);
1592 if (session->proto != COAP_PROTO_UDP) {
1593 /* In case the next handshake / CSM is already in */
1595 }
1596 /*
1597 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1598 * will get called again.
1599 */
1601 coap_log_debug("** %s: mid=0x%04x: queued\n",
1602 coap_session_str(session), pdu->mid);
1603 return pdu->mid;
1604 }
1605#endif /* COAP_Q_BLOCK_SUPPORT */
1606
1607 /*
1608 * Check validity of token length
1609 */
1610 if (COAP_PDU_IS_REQUEST(pdu) &&
1611 pdu->actual_token.length > session->max_token_size) {
1612 coap_log_warn("coap_send: PDU dropped as token too long (%" PRIuS " > %" PRIu32 ")\n",
1613 pdu->actual_token.length, session->max_token_size);
1614 goto error;
1615 }
1616
1617 /* A lot of the reliable code assumes type is CON */
1618 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1619 pdu->type = COAP_MESSAGE_CON;
1620
1621#if COAP_OSCORE_SUPPORT
1622 if (session->oscore_encryption) {
1623 if (session->recipient_ctx->initial_state == 1 &&
1624 !session->recipient_ctx->silent_server) {
1625 /*
1626 * Not sure if remote supports OSCORE, or is going to send us a
1627 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1628 * is OK. Continue sending current pdu to test things.
1629 */
1630 session->doing_first = 1;
1631 }
1632 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1634 goto error;
1635 }
1636 }
1637#endif /* COAP_OSCORE_SUPPORT */
1638
1639 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1640 return coap_send_internal(session, pdu, NULL);
1641 }
1642
1643 if (session->no_path_abbrev) {
1644 opt = coap_check_option(pdu, COAP_OPTION_URI_PATH_ABB, &opt_iter);
1645 if (opt) {
1646 /* Server cannot handle Uri-Path-Abbrev */
1647 coap_pdu_t *new;
1648 size_t data_len;
1649 const uint8_t *data;
1650
1651 new = coap_pdu_duplicate_lkd(pdu, session, pdu->actual_token.length,
1653 if (new) {
1654 if (coap_get_data(pdu, &data_len, &data)) {
1655 coap_add_data(pdu, data_len, data);
1656 }
1657 coap_log_debug("* Retransmitting PDU with Uri-Path-Abbrev replaced (3)\n");
1659 pdu = new;
1660 }
1661 }
1662 }
1663
1664 if (COAP_PDU_IS_REQUEST(pdu)) {
1665 uint8_t buf[4];
1666
1667 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1668
1669 if (opt) {
1670 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1671 coap_opt_length(opt));
1672 }
1673
1674 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1675 (block.m == 1 || block.bert == 1)) {
1676 have_block1 = 1;
1677 }
1678#if COAP_Q_BLOCK_SUPPORT
1679 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1680 (block.m == 1 || block.bert == 1)) {
1681 if (have_block1) {
1682 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1684 }
1685 have_block1 = 1;
1686 }
1687#endif /* COAP_Q_BLOCK_SUPPORT */
1688 if (observe_action != COAP_OBSERVE_CANCEL) {
1689 /* Warn about re-use of tokens */
1690 if (session->last_token &&
1691 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1693 char scratch[24];
1694 size_t size;
1695 size_t i;
1696
1697 scratch[0] = '\000';
1698 for (i = 0; i < pdu->actual_token.length; i++) {
1699 size = strlen(scratch);
1700 snprintf(&scratch[size], sizeof(scratch)-size,
1701 "%02x", pdu->actual_token.s[i]);
1702 }
1703 coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1704 scratch);
1705 }
1706 }
1709 pdu->actual_token.length);
1710 } else {
1711 /* observe_action == COAP_OBSERVE_CANCEL */
1712 coap_binary_t tmp;
1713 int ret;
1714
1715 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1716 /* Unfortunately need to change the ptr type to be r/w */
1717 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1718 tmp.length = pdu->actual_token.length;
1719 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1720 if (ret == 1) {
1721 /* Observe Cancel successfully sent */
1723 return ret;
1724 }
1725 /* Some mismatch somewhere - continue to send original packet */
1726 }
1727 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1728 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1732 coap_encode_var_safe(buf, sizeof(buf),
1733 ++session->tx_rtag),
1734 buf);
1735 } else {
1736 memset(&block, 0, sizeof(block));
1737 }
1738
1739#if COAP_Q_BLOCK_SUPPORT
1740 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1741#endif /* COAP_Q_BLOCK_SUPPORT */
1742 {
1743 /* Need to check if we need to reset Q-Block to Block */
1744 uint8_t buf[4];
1745
1746 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1749 coap_encode_var_safe(buf, sizeof(buf),
1750 (block.num << 4) | (0 << 3) | block.szx),
1751 buf);
1752 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1753 /* Need to update associated lg_xmit */
1754 coap_lg_xmit_t *lg_xmit;
1755
1756 LL_FOREACH(session->lg_xmit, lg_xmit) {
1757 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1758 lg_xmit->b.b1.app_token &&
1759 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1760 /* Update the skeletal PDU with the block1 option */
1763 coap_encode_var_safe(buf, sizeof(buf),
1764 (block.num << 4) | (0 << 3) | block.szx),
1765 buf);
1766 break;
1767 }
1768 }
1769 }
1770 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1773 coap_encode_var_safe(buf, sizeof(buf),
1774 (block.num << 4) | (block.m << 3) | block.szx),
1775 buf);
1776 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1777 /* Need to update associated lg_xmit */
1778 coap_lg_xmit_t *lg_xmit;
1779
1780 LL_FOREACH(session->lg_xmit, lg_xmit) {
1781 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1782 lg_xmit->b.b1.app_token &&
1783 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1784 /* Update the skeletal PDU with the block1 option */
1787 coap_encode_var_safe(buf, sizeof(buf),
1788 (block.num << 4) |
1789 (block.m << 3) |
1790 block.szx),
1791 buf);
1792 /* Update as this is a Request */
1793 lg_xmit->option = COAP_OPTION_BLOCK1;
1794 break;
1795 }
1796 }
1797 }
1798 }
1799
1800#if COAP_Q_BLOCK_SUPPORT
1801 if (COAP_PDU_IS_REQUEST(pdu) &&
1802 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1803 if (block.num == 0 && block.m == 0) {
1804 uint8_t buf[4];
1805
1806 /* M needs to be set as asking for all the blocks */
1808 coap_encode_var_safe(buf, sizeof(buf),
1809 (0 << 4) | (1 << 3) | block.szx),
1810 buf);
1811 }
1812 }
1813#endif /* COAP_Q_BLOCK_SUPPORT */
1814
1815 /*
1816 * If type is CON and protocol is not reliable, there is no need to set up
1817 * lg_crcv here as it can be built up based on sent PDU if there is a
1818 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1819 * (Q-)Block1.
1820 */
1821 if (coap_check_send_need_lg_crcv(session, pdu)) {
1822 coap_lg_xmit_t *lg_xmit = NULL;
1823
1824 if (!session->lg_xmit && have_block1) {
1825 coap_log_debug("PDU presented by app\n");
1827 }
1828 /* See if this token is already in use for large body responses */
1829 LL_FOREACH(session->lg_crcv, lg_crcv) {
1830 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1831 /* Need to terminate and clean up previous response setup */
1832 LL_DELETE(session->lg_crcv, lg_crcv);
1833 coap_block_delete_lg_crcv(session, lg_crcv);
1834 break;
1835 }
1836 }
1837
1838 if (have_block1 && session->lg_xmit) {
1839 LL_FOREACH(session->lg_xmit, lg_xmit) {
1840 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1841 lg_xmit->b.b1.app_token &&
1842 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1843 break;
1844 }
1845 }
1846 }
1847 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1848 if (lg_crcv == NULL) {
1849 goto error;
1850 }
1851 if (lg_xmit) {
1852 /* Need to update the token as set up in the session->lg_xmit */
1853 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1854 }
1855 }
1856 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1857 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1858
1859#if COAP_Q_BLOCK_SUPPORT
1860 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1861 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1862 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1863 } else
1864#endif /* COAP_Q_BLOCK_SUPPORT */
1865 mid = coap_send_internal(session, pdu, NULL);
1866#else /* !COAP_CLIENT_SUPPORT */
1867 mid = coap_send_internal(session, pdu, NULL);
1868#endif /* !COAP_CLIENT_SUPPORT */
1869#if COAP_CLIENT_SUPPORT
1870 if (lg_crcv) {
1871 if (mid != COAP_INVALID_MID) {
1872 LL_PREPEND(session->lg_crcv, lg_crcv);
1873 } else {
1874 coap_block_delete_lg_crcv(session, lg_crcv);
1875 }
1876 }
1877#endif /* COAP_CLIENT_SUPPORT */
1878 return mid;
1879
1880error:
1882 return COAP_INVALID_MID;
1883}
1884
1885#if COAP_SERVER_SUPPORT
1886static int
1887coap_pdu_cksum(const coap_pdu_t *pdu, coap_digest_t *digest_buffer) {
1888 coap_digest_ctx_t *digest_ctx = coap_digest_setup();
1889
1890 if (!digest_ctx || !pdu) {
1891 goto fail;
1892 }
1893 if (pdu->used_size && pdu->token) {
1894 if (!coap_digest_update(digest_ctx, pdu->token, pdu->used_size)) {
1895 goto fail;
1896 }
1897 }
1898 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->type, sizeof(pdu->type))) {
1899 goto fail;
1900 }
1901 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->code, sizeof(pdu->code))) {
1902 goto fail;
1903 }
1904 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->mid, sizeof(pdu->mid))) {
1905 goto fail;
1906 }
1907 if (!coap_digest_final(digest_ctx, digest_buffer))
1908 return 0;
1909
1910 return 1;
1911
1912fail:
1913 coap_digest_free(digest_ctx);
1914 return 0;
1915}
1916#endif /* COAP_SERVER_SUPPORT */
1917
1918static int
1920 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1921 coap_opt_t *opt;
1922 coap_opt_iterator_t opt_iter;
1923 size_t hop_limit;
1924
1925 addr_str[sizeof(addr_str)-1] = '\000';
1926 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1927 sizeof(addr_str) - 1)) {
1928 char *cp;
1929 size_t len;
1930
1931 if (addr_str[0] == '[') {
1932 cp = strchr(addr_str, ']');
1933 if (cp)
1934 *cp = '\000';
1935 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1936 /* IPv4 embedded into IPv6 */
1937 cp = &addr_str[8];
1938 } else {
1939 cp = &addr_str[1];
1940 }
1941 } else {
1942 cp = strchr(addr_str, ':');
1943 if (cp)
1944 *cp = '\000';
1945 cp = addr_str;
1946 }
1947 len = strlen(cp);
1948
1949 /* See if Hop Limit option is being used in return path */
1950 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1951 if (opt) {
1952 uint8_t buf[4];
1953
1954 hop_limit =
1956 if (hop_limit == 1) {
1957 coap_log_warn("Proxy loop detected '%s'\n",
1958 (char *)pdu->data);
1961 } else if (hop_limit < 1 || hop_limit > 255) {
1962 /* Something is bad - need to drop this pdu (TODO or delete option) */
1963 coap_log_warn("Proxy return has bad hop limit count '%" PRIuS "'\n",
1964 hop_limit);
1966 return 0;
1967 }
1968 hop_limit--;
1970 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1971 buf);
1972 }
1973
1974 /* Need to check that we are not seeing this proxy in the return loop */
1975 if (pdu->data && opt == NULL) {
1976 char *a_match;
1977 size_t data_len;
1978
1979 if (pdu->used_size + 1 > pdu->max_size) {
1980 /* No space */
1982 return 0;
1983 }
1984 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1985 /* Internal error */
1987 return 0;
1988 }
1989 data_len = pdu->used_size - (pdu->data - pdu->token);
1990 pdu->data[data_len] = '\000';
1991 a_match = strstr((char *)pdu->data, cp);
1992 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1993 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1994 a_match[len] == ' ')) {
1995 coap_log_warn("Proxy loop detected '%s'\n",
1996 (char *)pdu->data);
1998 return 0;
1999 }
2000 }
2001 if (pdu->used_size + len + 1 <= pdu->max_size) {
2002 size_t old_size = pdu->used_size;
2003 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
2004 if (pdu->data == NULL) {
2005 /*
2006 * Set Hop Limit to max for return path. If this libcoap is in
2007 * a proxy loop path, it will always decrement hop limit in code
2008 * above and hence timeout / drop the response as appropriate
2009 */
2010 hop_limit = 255;
2012 (uint8_t *)&hop_limit);
2013 coap_add_data(pdu, len, (uint8_t *)cp);
2014 } else {
2015 /* prepend with space separator, leaving hop limit "as is" */
2016 memmove(pdu->data + len + 1, pdu->data,
2017 old_size - (pdu->data - pdu->token));
2018 memcpy(pdu->data, cp, len);
2019 pdu->data[len] = ' ';
2020 pdu->used_size += len + 1;
2021 }
2022 }
2023 }
2024 }
2025 return 1;
2026}
2027
2030 uint8_t r;
2031 ssize_t bytes_written;
2032
2033#if ! COAP_SERVER_SUPPORT
2034 (void)request_pdu;
2035#endif /* COAP_SERVER_SUPPORT */
2036 pdu->session = session;
2037#if COAP_CLIENT_SUPPORT
2038 if (session->session_failed) {
2039 coap_session_reconnect(session);
2040 if (session->session_failed)
2041 goto error;
2042 }
2043#endif /* COAP_CLIENT_SUPPORT */
2044 if (pdu->type == COAP_MESSAGE_NON && session->rl_ticks_per_packet) {
2045 coap_tick_t now;
2046
2047 if (!session->is_rate_limiting) {
2048 coap_ticks(&now);
2049 while (1) {
2050 uint32_t timeout_ms;
2051
2052 if (now - session->last_tx >= session->rl_ticks_per_packet) {
2053 break;
2054 }
2055 timeout_ms = (uint32_t)((session->rl_ticks_per_packet - (now - session->last_tx)) /
2056 (COAP_TICKS_PER_SECOND / 1000));
2057
2058 if (timeout_ms == 0) {
2059 timeout_ms = COAP_IO_NO_WAIT;
2060 }
2061 session->is_rate_limiting = 1;
2062 coap_io_process_lkd(session->context, timeout_ms);
2063 session->is_rate_limiting = 0;
2064 coap_ticks(&now);
2065 }
2066 session->last_tx = now;
2067 }
2068 }
2069#if COAP_PROXY_SUPPORT
2070 if (session->server_list) {
2071 /* Local session wanting to use proxy logic */
2072 return coap_proxy_local_write(session, pdu);
2073 }
2074#endif /* COAP_PROXY_SUPPORT */
2075 if (pdu->code == COAP_RESPONSE_CODE(508)) {
2076 /*
2077 * Need to prepend our IP identifier to the data as per
2078 * https://rfc-editor.org/rfc/rfc8768.html#section-4
2079 */
2080 if (!prepend_508_ip(session, pdu)) {
2082 }
2083 }
2084
2085 if (session->echo) {
2086 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
2087 session->echo->s))
2088 goto error;
2089 coap_delete_bin_const(session->echo);
2090 session->echo = NULL;
2091 }
2092#if COAP_OSCORE_SUPPORT
2093 if (session->oscore_encryption) {
2094 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
2096 goto error;
2097 }
2098#endif /* COAP_OSCORE_SUPPORT */
2099
2100 if (!coap_pdu_encode_header(pdu, session->proto)) {
2101 goto error;
2102 }
2103
2104#if !COAP_DISABLE_TCP
2105 if (COAP_PROTO_RELIABLE(session->proto) &&
2107 coap_opt_iterator_t opt_iter;
2108
2109 if (!session->csm_block_supported) {
2110 /*
2111 * Need to check that this instance is not sending any block options as
2112 * the remote end via CSM has not informed us that there is support
2113 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2114 * This includes potential BERT blocks.
2115 */
2116 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2117 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2118 }
2119 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2120 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2121 }
2122 } else if (!session->csm_bert_rem_support) {
2123 coap_opt_t *opt;
2124
2125 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2126 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2127 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2128 }
2129 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2130 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2131 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2132 }
2133 }
2134 }
2135#endif /* !COAP_DISABLE_TCP */
2136
2137#if COAP_OSCORE_SUPPORT
2138 if (session->oscore_encryption &&
2139 pdu->type != COAP_MESSAGE_RST &&
2140 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2141 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2142 /* Refactor PDU as appropriate RFC8613 */
2143 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2144
2145 if (osc_pdu == NULL) {
2146 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2149 goto error;
2150 }
2151 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2153 pdu = osc_pdu;
2154 } else
2155#endif /* COAP_OSCORE_SUPPORT */
2156 bytes_written = coap_send_pdu(session, pdu, NULL);
2157
2158#if COAP_SERVER_SUPPORT
2159 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
2160 session->cached_pdu != pdu &&
2161 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2162 COAP_PDU_IS_REQUEST(request_pdu) &&
2163 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2164 coap_delete_pdu_lkd(session->cached_pdu);
2165 session->cached_pdu = pdu;
2166 coap_pdu_reference_lkd(session->cached_pdu);
2167 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
2168 }
2169#endif /* COAP_SERVER_SUPPORT */
2170
2171 if (bytes_written == COAP_PDU_DELAYED) {
2172 /* do not free pdu as it is stored with session for later use */
2173 return pdu->mid;
2174 }
2175 if (bytes_written < 0) {
2176 if (pdu->code != 0)
2178 goto error;
2179 }
2180
2181#if !COAP_DISABLE_TCP
2182 if (COAP_PROTO_RELIABLE(session->proto) &&
2183 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2184 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2185 session->partial_write = (size_t)bytes_written;
2186 /* do not free pdu as it is stored with session for later use */
2187 return pdu->mid;
2188 } else {
2189 goto error;
2190 }
2191 }
2192#endif /* !COAP_DISABLE_TCP */
2193
2194 if (pdu->type != COAP_MESSAGE_CON
2195 || COAP_PROTO_RELIABLE(session->proto)) {
2196 coap_mid_t id = pdu->mid;
2198 return id;
2199 }
2200
2201 coap_queue_t *node = coap_new_node();
2202 if (!node) {
2203 coap_log_debug("coap_wait_ack: insufficient memory\n");
2204 goto error;
2205 }
2206
2207 node->id = pdu->mid;
2208 node->pdu = pdu;
2209 coap_prng_lkd(&r, sizeof(r));
2210 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2211 node->timeout = coap_calc_timeout(session, r);
2212 return coap_wait_ack(session->context, session, node);
2213error:
2215 return COAP_INVALID_MID;
2216}
2217
2218static int send_recv_terminate = 0;
2219
2220void
2224
2225COAP_API int
2227 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2228 int ret;
2229
2230 coap_lock_lock(return 0);
2231 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2233 return ret;
2234}
2235
2236/*
2237 * Return 0 or +ve Time in function in ms after successful transfer
2238 * -1 Invalid timeout parameter
2239 * -2 Failed to transmit PDU
2240 * -3 Nack or Event handler invoked, cancelling request
2241 * -4 coap_io_process returned error (fail to re-lock or select())
2242 * -5 Response not received in the given time
2243 * -6 Terminated by user
2244 * -7 Client mode code not enabled
2245 */
2246int
2248 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2249#if COAP_CLIENT_SUPPORT
2251 uint32_t rem_timeout = timeout_ms;
2252 uint32_t block_mode = session->block_mode;
2253 int ret = 0;
2254 coap_tick_t now;
2255 coap_tick_t start;
2256 coap_tick_t ticks_so_far;
2257 uint32_t time_so_far_ms;
2258
2259 coap_ticks(&start);
2260 assert(request_pdu);
2261
2263
2264 session->resp_pdu = NULL;
2265 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2266 request_pdu->actual_token.length);
2267
2268 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2269 ret = -1;
2270 goto fail;
2271 }
2272 if (session->state == COAP_SESSION_STATE_NONE) {
2273 ret = -3;
2274 goto fail;
2275 }
2276
2278 if (coap_is_mcast(&session->addr_info.remote))
2279 block_mode = session->block_mode;
2280
2281 session->doing_send_recv = 1;
2282 /* So the user needs to delete the PDU */
2283 coap_pdu_reference_lkd(request_pdu);
2284 mid = coap_send_lkd(session, request_pdu);
2285 if (mid == COAP_INVALID_MID) {
2286 if (!session->doing_send_recv)
2287 ret = -3;
2288 else
2289 ret = -2;
2290 goto fail;
2291 }
2292
2293 /* Wait for the response to come in */
2294 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2295 if (send_recv_terminate) {
2296 ret = -6;
2297 goto fail;
2298 }
2299 ret = coap_io_process_lkd(session->context, rem_timeout);
2300 if (ret < 0) {
2301 ret = -4;
2302 goto fail;
2303 }
2304 /* timeout_ms is for timeout between specific request and response */
2305 coap_ticks(&now);
2306 ticks_so_far = now - session->last_rx_tx;
2307 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2308 if (time_so_far_ms >= timeout_ms) {
2309 rem_timeout = 0;
2310 } else {
2311 rem_timeout = timeout_ms - time_so_far_ms;
2312 }
2313 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2314 /* To pick up on (D)TLS setup issues */
2315 coap_ticks(&now);
2316 ticks_so_far = now - start;
2317 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2318 if (time_so_far_ms >= timeout_ms) {
2319 rem_timeout = 0;
2320 } else {
2321 rem_timeout = timeout_ms - time_so_far_ms;
2322 }
2323 }
2324 }
2325
2326 if (rem_timeout) {
2327 coap_ticks(&now);
2328 ticks_so_far = now - start;
2329 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2330 ret = time_so_far_ms;
2331 /* Give PDU to user who will be calling coap_delete_pdu() */
2332 *response_pdu = session->resp_pdu;
2333 session->resp_pdu = NULL;
2334 if (*response_pdu == NULL) {
2335 ret = -3;
2336 }
2337 } else {
2338 /* If there is a resp_pdu, it will get cleared below */
2339 ret = -5;
2340 }
2341
2342fail:
2343 session->block_mode = block_mode;
2344 session->doing_send_recv = 0;
2345 /* delete referenced copy */
2346 coap_delete_pdu_lkd(session->resp_pdu);
2347 session->resp_pdu = NULL;
2348 coap_delete_bin_const(session->req_token);
2349 session->req_token = NULL;
2350 return ret;
2351
2352#else /* !COAP_CLIENT_SUPPORT */
2353
2354 (void)session;
2355 (void)timeout_ms;
2356 (void)request_pdu;
2357 coap_log_warn("coap_send_recv: Client mode not supported\n");
2358 *response_pdu = NULL;
2359 return -7;
2360
2361#endif /* ! COAP_CLIENT_SUPPORT */
2362}
2363
2366 if (!context || !node || !node->session)
2367 return COAP_INVALID_MID;
2368
2369#if COAP_CLIENT_SUPPORT
2370 if (node->session->session_failed) {
2371 /* Force failure */
2372 node->retransmit_cnt = (unsigned char)node->session->max_retransmit;
2373 }
2374#endif /* COAP_CLIENT_SUPPORT */
2375
2376 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2377 if (node->retransmit_cnt < node->session->max_retransmit) {
2378 ssize_t bytes_written;
2379 coap_tick_t now;
2380 coap_tick_t next_delay;
2381 coap_address_t remote;
2382
2383 node->retransmit_cnt++;
2385
2386 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2387 if (context->ping_timeout &&
2388 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2389 uint8_t byte;
2390
2391 coap_prng_lkd(&byte, sizeof(byte));
2392 /* Don't exceed the ping timeout value */
2393 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2394 }
2395
2396 coap_ticks(&now);
2397 if (context->sendqueue == NULL) {
2398 node->t = next_delay;
2399 context->sendqueue_basetime = now;
2400 } else {
2401 /* make node->t relative to context->sendqueue_basetime */
2402 node->t = (now - context->sendqueue_basetime) + next_delay;
2403 }
2404 coap_insert_node(&context->sendqueue, node);
2405 coap_address_copy(&remote, &node->session->addr_info.remote);
2407
2408 if (node->is_mcast) {
2409 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2410 coap_session_str(node->session), node->id);
2411 } else {
2412 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2413 coap_session_str(node->session), node->id,
2414 node->retransmit_cnt,
2415 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2416 }
2417
2418 if (node->session->con_active)
2419 node->session->con_active--;
2420 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2421
2422 if (bytes_written == COAP_PDU_DELAYED) {
2423 /* PDU was not retransmitted immediately because a new handshake is
2424 in progress. node was moved to the send queue of the session. */
2425 return node->id;
2426 }
2427
2428 coap_address_copy(&node->session->addr_info.remote, &remote);
2429 if (node->is_mcast) {
2432 return COAP_INVALID_MID;
2433 }
2434
2435 if (bytes_written < 0)
2436 return (int)bytes_written;
2437
2438 return node->id;
2439 }
2440
2441#if COAP_CLIENT_SUPPORT
2442 if (node->session->session_failed) {
2443 coap_log_info("** %s: mid=0x%04x: deleted due to reconnection issue\n",
2444 coap_session_str(node->session), node->id);
2445 } else {
2446#endif /* COAP_CLIENT_SUPPORT */
2447 /* no more retransmissions, remove node from system */
2448 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2449 coap_session_str(node->session), node->id, node->retransmit_cnt);
2450#if COAP_CLIENT_SUPPORT
2451 }
2452#endif /* COAP_CLIENT_SUPPORT */
2453
2454#if COAP_SERVER_SUPPORT
2455 /* Check if subscriptions exist that should be canceled after
2456 COAP_OBS_MAX_FAIL */
2457 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2458 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2459 if (context->ping_timeout) {
2462 return COAP_INVALID_MID;
2463 } else {
2464 if (node->session->ref_subscriptions)
2465 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2466#if COAP_PROXY_SUPPORT
2467 /* Need to check is there is a proxy subscription active and delete it */
2468 if (node->session->ref_proxy_subs)
2469 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2470 0, COAP_PROXY_SUBS_TOKEN);
2471#endif /* COAP_PROXY_SUPPORT */
2472 }
2473 }
2474#endif /* COAP_SERVER_SUPPORT */
2475 if (node->session->con_active) {
2476 node->session->con_active--;
2478 /*
2479 * As there may be another CON in a different queue entry on the same
2480 * session that needs to be immediately released,
2481 * coap_session_connected() is called.
2482 * However, there is the possibility coap_wait_ack() may be called for
2483 * this node (queue) and re-added to context->sendqueue.
2484 * coap_delete_node_lkd(node) called shortly will handle this and
2485 * remove it.
2486 */
2488 }
2489 }
2490
2491 if (node->pdu->type == COAP_MESSAGE_CON) {
2493 }
2494#if COAP_CLIENT_SUPPORT
2495 node->session->doing_send_recv = 0;
2496#endif /* COAP_CLIENT_SUPPORT */
2497 /* And finally delete the node */
2499 return COAP_INVALID_MID;
2500}
2501
2502static int
2504 uint8_t *data;
2505 size_t data_len;
2506 int result = -1;
2507
2508 coap_packet_get_memmapped(packet, &data, &data_len);
2509 if (session->proto == COAP_PROTO_DTLS) {
2510#if COAP_SERVER_SUPPORT
2511 if (session->type == COAP_SESSION_TYPE_HELLO)
2512 result = coap_dtls_hello(session, data, data_len);
2513 else
2514#endif /* COAP_SERVER_SUPPORT */
2515 if (session->tls)
2516 result = coap_dtls_receive(session, data, data_len);
2517 } else if (session->proto == COAP_PROTO_UDP) {
2518 result = coap_handle_dgram(ctx, session, data, data_len);
2519 }
2520 return result;
2521}
2522
2523#if COAP_CLIENT_SUPPORT
2524void
2526#if COAP_DISABLE_TCP
2527 (void)now;
2528
2530#else /* !COAP_DISABLE_TCP */
2531 if (coap_netif_strm_connect2(session)) {
2532 session->last_rx_tx = now;
2534 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2535 } else {
2538 }
2539#endif /* !COAP_DISABLE_TCP */
2540}
2541#endif /* COAP_CLIENT_SUPPORT */
2542
2543static void
2545 (void)ctx;
2546 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2547
2548 while (session->delayqueue) {
2549 ssize_t bytes_written;
2550 coap_queue_t *q = session->delayqueue;
2551
2552 coap_address_copy(&session->addr_info.remote, &q->remote);
2553 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2554 coap_session_str(session), (int)q->pdu->mid);
2555 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2556 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2557 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2558 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2559 if (bytes_written > 0)
2560 session->last_rx_tx = now;
2561 if (bytes_written <= 0 ||
2562 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2563 if (bytes_written > 0)
2564 session->partial_write += (size_t)bytes_written;
2565 break;
2566 }
2567 session->delayqueue = q->next;
2568 session->partial_write = 0;
2570 }
2571}
2572
2573void
2575#if COAP_CONSTRAINED_STACK
2576 /* payload and packet can be protected by global_lock if needed */
2577 static unsigned char payload[COAP_RXBUFFER_SIZE];
2578 static coap_packet_t s_packet;
2579#else /* ! COAP_CONSTRAINED_STACK */
2580 unsigned char payload[COAP_RXBUFFER_SIZE];
2581 coap_packet_t s_packet;
2582#endif /* ! COAP_CONSTRAINED_STACK */
2583 coap_packet_t *packet = &s_packet;
2584
2586
2587 packet->length = sizeof(payload);
2588 packet->payload = payload;
2589
2590 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2591 ssize_t bytes_read;
2592 coap_address_t remote;
2593
2594 coap_address_copy(&remote, &session->addr_info.remote);
2595 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2596 bytes_read = coap_netif_dgrm_read(session, packet);
2597
2598 if (bytes_read < 0) {
2599 if (bytes_read == -2) {
2600 coap_address_copy(&session->addr_info.remote, &remote);
2601 /* Reset the session back to startup defaults */
2603 }
2604 } else if (bytes_read > 0) {
2605 session->last_rx_tx = now;
2606#if COAP_CLIENT_SUPPORT
2607 if (session->session_failed) {
2608 session->session_failed = 0;
2610 }
2611#endif /* COAP_CLIENT_SUPPORT */
2612 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2613 coap_handle_dgram_for_proto(ctx, session, packet);
2614 } else {
2615 coap_address_copy(&session->addr_info.remote, &remote);
2616 }
2617#if !COAP_DISABLE_TCP
2618 } else if (session->proto == COAP_PROTO_WS ||
2619 session->proto == COAP_PROTO_WSS) {
2620 ssize_t bytes_read = 0;
2621
2622 /* WebSocket layer passes us the whole packet */
2623 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2624 packet->payload,
2625 packet->length);
2626 if (bytes_read < 0) {
2628 } else if (bytes_read > 2) {
2629 coap_pdu_t *pdu;
2630
2631 session->last_rx_tx = now;
2632 /* Need max space incase PDU is updated with updated token etc. */
2633 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2634 if (!pdu) {
2635 return;
2636 }
2637
2638 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2640 coap_log_warn("discard malformed PDU\n");
2642 return;
2643 }
2644
2645 coap_dispatch(ctx, session, pdu);
2647 return;
2648 }
2649 } else {
2650 ssize_t bytes_read = 0;
2651 const uint8_t *p;
2652 int retry;
2653
2654 do {
2655 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2656 packet->payload,
2657 packet->length);
2658 if (bytes_read > 0) {
2659 session->last_rx_tx = now;
2660 }
2661 p = packet->payload;
2662 retry = bytes_read == (ssize_t)packet->length;
2663 while (bytes_read > 0) {
2664 if (session->partial_pdu) {
2665 size_t len = session->partial_pdu->used_size
2666 + session->partial_pdu->hdr_size
2667 - session->partial_read;
2668 size_t n = min(len, (size_t)bytes_read);
2669 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2670 + session->partial_read, p, n);
2671 p += n;
2672 bytes_read -= n;
2673 if (n == len) {
2674 coap_opt_filter_t error_opts;
2675 coap_pdu_t *pdu = session->partial_pdu;
2676
2677 session->partial_pdu = NULL;
2678 session->partial_read = 0;
2679
2680 coap_option_filter_clear(&error_opts);
2681 if (coap_pdu_parse_header(pdu, session->proto)
2682 && coap_pdu_parse_opt(pdu, &error_opts)) {
2683 coap_dispatch(ctx, session, pdu);
2684 } else if (error_opts.mask) {
2685 coap_pdu_t *response =
2687 COAP_RESPONSE_CODE(402), &error_opts);
2688 if (!response) {
2689 coap_log_warn("coap_read_session: cannot create error response\n");
2690 } else {
2691 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2692 coap_log_warn("coap_read_session: error sending response\n");
2693 }
2694 }
2696 } else {
2697 session->partial_read += n;
2698 }
2699 } else if (session->partial_read > 0) {
2700 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2701 session->read_header);
2702 size_t tkl = session->read_header[0] & 0x0f;
2703 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2704 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2705 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2706 size_t n = min(len, (size_t)bytes_read);
2707 memcpy(session->read_header + session->partial_read, p, n);
2708 p += n;
2709 bytes_read -= n;
2710 if (n == len) {
2711 /* Header now all in */
2712 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2713 hdr_size + tok_ext_bytes);
2714 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2715 coap_log_warn("** %s: incoming PDU length too large (%" PRIuS " > %lu)\n",
2716 coap_session_str(session),
2718 bytes_read = -1;
2719 break;
2720 }
2721 /* Need max space incase PDU is updated with updated token etc. */
2722 session->partial_pdu = coap_pdu_init(0, 0, 0,
2724 if (session->partial_pdu == NULL) {
2725 bytes_read = -1;
2726 break;
2727 }
2728 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2729 bytes_read = -1;
2730 break;
2731 }
2732 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2733 session->partial_pdu->used_size = size;
2734 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2735 session->partial_read = hdr_size + tok_ext_bytes;
2736 if (size == 0) {
2737 coap_pdu_t *pdu = session->partial_pdu;
2738
2739 session->partial_pdu = NULL;
2740 session->partial_read = 0;
2741 if (coap_pdu_parse_header(pdu, session->proto)) {
2742 coap_dispatch(ctx, session, pdu);
2743 }
2745 }
2746 } else {
2747 /* More of the header to go */
2748 session->partial_read += n;
2749 }
2750 } else {
2751 /* Get in first byte of the header */
2752 session->read_header[0] = *p++;
2753 bytes_read -= 1;
2754 if (!coap_pdu_parse_header_size(session->proto,
2755 session->read_header)) {
2756 bytes_read = -1;
2757 break;
2758 }
2759 session->partial_read = 1;
2760 }
2761 }
2762 } while (bytes_read == 0 && retry);
2763 if (bytes_read < 0)
2765#endif /* !COAP_DISABLE_TCP */
2766 }
2767}
2768
2769#if COAP_SERVER_SUPPORT
2770static int
2771coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2772 ssize_t bytes_read = -1;
2773 int result = -1; /* the value to be returned */
2774#if COAP_CONSTRAINED_STACK
2775 /* payload and e_packet can be protected by global_lock if needed */
2776 static unsigned char payload[COAP_RXBUFFER_SIZE];
2777 static coap_packet_t e_packet;
2778#else /* ! COAP_CONSTRAINED_STACK */
2779 unsigned char payload[COAP_RXBUFFER_SIZE];
2780 coap_packet_t e_packet;
2781#endif /* ! COAP_CONSTRAINED_STACK */
2782 coap_packet_t *packet = &e_packet;
2783
2784 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2785 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2786
2787 /* Need to do this as there may be holes in addr_info */
2788 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2789 packet->length = sizeof(payload);
2790 packet->payload = payload;
2792 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2793
2794 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2795 if (bytes_read < 0) {
2796 if (errno != EAGAIN) {
2797 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2798 }
2799 } else if (bytes_read > 0) {
2800 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2801 if (session) {
2803 coap_log_debug("* %s: netif: recv %4" PRIdS " bytes\n",
2804 coap_session_str(session), bytes_read);
2805 result = coap_handle_dgram_for_proto(ctx, session, packet);
2806 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2807 coap_session_new_dtls_session(session, now);
2808 coap_session_release_lkd(session);
2809 }
2810 }
2811 return result;
2812}
2813
2814static int
2815coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2816 (void)ctx;
2817 (void)endpoint;
2818 (void)now;
2819 return 0;
2820}
2821
2822#if !COAP_DISABLE_TCP
2823static int
2824coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2825 coap_tick_t now, void *extra) {
2826 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2827 if (session)
2828 session->last_rx_tx = now;
2829 return session != NULL;
2830}
2831#endif /* !COAP_DISABLE_TCP */
2832#endif /* COAP_SERVER_SUPPORT */
2833
2834COAP_API void
2836 coap_lock_lock(return);
2837 coap_io_do_io_lkd(ctx, now);
2839}
2840
2841void
2843#ifdef COAP_EPOLL_SUPPORT
2844 (void)ctx;
2845 (void)now;
2846 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2847#else /* ! COAP_EPOLL_SUPPORT */
2848 coap_session_t *s, *rtmp;
2849
2851#if COAP_SERVER_SUPPORT
2852 coap_endpoint_t *ep, *tmp;
2853 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2854 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2855 coap_read_endpoint(ctx, ep, now);
2856 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2857 coap_write_endpoint(ctx, ep, now);
2858#if !COAP_DISABLE_TCP
2859 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2860 coap_accept_endpoint(ctx, ep, now, NULL);
2861#endif /* !COAP_DISABLE_TCP */
2862 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2863 /* Make sure the session object is not deleted in one of the callbacks */
2865#if COAP_CLIENT_SUPPORT
2866 if (s->client_initiated && (s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2867 coap_connect_session(s, now);
2868 }
2869#endif /* COAP_CLIENT_SUPPORT */
2870 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2871 coap_read_session(ctx, s, now);
2872 }
2873 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2874 coap_write_session(ctx, s, now);
2875 }
2877 }
2878 }
2879#endif /* COAP_SERVER_SUPPORT */
2880
2881#if COAP_CLIENT_SUPPORT
2882 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2883 /* Make sure the session object is not deleted in one of the callbacks */
2885 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2886 coap_connect_session(s, now);
2887 }
2888 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2889 coap_read_session(ctx, s, now);
2890 }
2891 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2892 coap_write_session(ctx, s, now);
2893 }
2895 }
2896#endif /* COAP_CLIENT_SUPPORT */
2897#endif /* ! COAP_EPOLL_SUPPORT */
2898}
2899
2900COAP_API void
2901coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2902 coap_lock_lock(return);
2903 coap_io_do_epoll_lkd(ctx, events, nevents);
2905}
2906
2907/*
2908 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2909 * directly saves having to iterate through the endpoints / sessions.
2910 */
2911void
2912coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2913#ifndef COAP_EPOLL_SUPPORT
2914 (void)ctx;
2915 (void)events;
2916 (void)nevents;
2917 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2918#else /* COAP_EPOLL_SUPPORT */
2919 coap_tick_t now;
2920 size_t j;
2921
2923 coap_ticks(&now);
2924 for (j = 0; j < nevents; j++) {
2925 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2926
2927 /* Ignore 'timer trigger' ptr which is NULL */
2928 if (sock) {
2929#if COAP_SERVER_SUPPORT
2930 if (sock->endpoint) {
2931 coap_endpoint_t *endpoint = sock->endpoint;
2932 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2933 (events[j].events & EPOLLIN)) {
2934 sock->flags |= COAP_SOCKET_CAN_READ;
2935 coap_read_endpoint(endpoint->context, endpoint, now);
2936 }
2937
2938 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2939 (events[j].events & EPOLLOUT)) {
2940 /*
2941 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2942 * be true causing epoll_wait to return early
2943 */
2944 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2946 coap_write_endpoint(endpoint->context, endpoint, now);
2947 }
2948
2949#if !COAP_DISABLE_TCP
2950 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2951 (events[j].events & EPOLLIN)) {
2953 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2954 }
2955#endif /* !COAP_DISABLE_TCP */
2956
2957 } else
2958#endif /* COAP_SERVER_SUPPORT */
2959 if (sock->session) {
2960 coap_session_t *session = sock->session;
2961
2962 /* Make sure the session object is not deleted
2963 in one of the callbacks */
2965#if COAP_CLIENT_SUPPORT
2966 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2967 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2969 coap_connect_session(session, now);
2970 if (coap_netif_available(session) &&
2971 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2972 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2973 }
2974 }
2975#endif /* COAP_CLIENT_SUPPORT */
2976
2977 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2978 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2979 sock->flags |= COAP_SOCKET_CAN_READ;
2980 coap_read_session(session->context, session, now);
2981 }
2982
2983 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2984 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2985 /*
2986 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2987 * be true causing epoll_wait to return early
2988 */
2989 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2991 coap_write_session(session->context, session, now);
2992 }
2993 /* Now dereference session so it can go away if needed */
2994 coap_session_release_lkd(session);
2995 }
2996 } else if (ctx->eptimerfd != -1) {
2997 /*
2998 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2999 * it so that it does not set EPOLLIN in the next epoll_wait().
3000 */
3001 uint64_t count;
3002
3003 /* Check the result from read() to suppress the warning on
3004 * systems that declare read() with warn_unused_result. */
3005 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
3006 /* do nothing */;
3007 }
3008 }
3009 }
3010 /* And update eptimerfd as to when to next trigger */
3011 coap_ticks(&now);
3012 coap_io_prepare_epoll_lkd(ctx, now);
3013#endif /* COAP_EPOLL_SUPPORT */
3014}
3015
3016int
3018 uint8_t *msg, size_t msg_len) {
3019
3020 coap_pdu_t *pdu = NULL;
3021 coap_opt_filter_t error_opts;
3022
3023 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
3024 if (msg_len < 4) {
3025 /* Minimum size of CoAP header - ignore runt */
3026 return -1;
3027 }
3028 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
3029 /*
3030 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
3031 * this MUST be silently ignored.
3032 */
3033 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
3034 return -1;
3035 }
3036
3037 /* Need max space incase PDU is updated with updated token etc. */
3038 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
3039 if (!pdu)
3040 goto error;
3041
3042 coap_option_filter_clear(&error_opts);
3043 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
3045 coap_log_warn("discard malformed PDU\n");
3046 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
3047 coap_pdu_t *response =
3049 COAP_RESPONSE_CODE(402), &error_opts);
3050 if (!response) {
3051 coap_log_warn("coap_handle_dgram: cannot create error response\n");
3052 } else {
3053 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
3054 coap_log_warn("coap_handle_dgram: error sending response\n");
3055 }
3057 return -1;
3058 } else {
3059 goto error;
3060 }
3061 }
3062
3063 coap_dispatch(ctx, session, pdu);
3065 return 0;
3066
3067error:
3068 /*
3069 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
3070 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
3071 */
3072 coap_send_rst_lkd(session, pdu);
3074 return -1;
3075}
3076
3077int
3079 coap_queue_t **node) {
3080 coap_queue_t *p, *q;
3081
3082 if (!queue || !*queue) {
3083 *node = NULL;
3084 return 0;
3085 }
3086
3087 /* replace queue head if PDU's time is less than head's time */
3088
3089 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
3090 *node = *queue;
3091 *queue = (*queue)->next;
3092 if (*queue) { /* adjust relative time of new queue head */
3093 (*queue)->t += (*node)->t;
3094 }
3095 (*node)->next = NULL;
3096 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
3097 coap_session_str(session), id);
3098 return 1;
3099 }
3100
3101 /* search message id in queue to remove (only first occurence will be removed) */
3102 q = *queue;
3103 do {
3104 p = q;
3105 q = q->next;
3106 } while (q && (session != q->session || id != q->id));
3107
3108 if (q) { /* found message id */
3109 p->next = q->next;
3110 if (p->next) { /* must update relative time of p->next */
3111 p->next->t += q->t;
3112 }
3113 q->next = NULL;
3114 *node = q;
3115 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
3116 coap_session_str(session), id);
3117 return 1;
3118 }
3119
3120 *node = NULL;
3121 return 0;
3122
3123}
3124
3125static int
3127 coap_bin_const_t *token, coap_queue_t **node) {
3128 coap_queue_t *p, *q;
3129
3130 if (!queue || !*queue)
3131 return 0;
3132
3133 /* replace queue head if PDU's time is less than head's time */
3134
3135 if (session == (*queue)->session &&
3136 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
3137 *node = *queue;
3138 *queue = (*queue)->next;
3139 if (*queue) { /* adjust relative time of new queue head */
3140 (*queue)->t += (*node)->t;
3141 }
3142 (*node)->next = NULL;
3143 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3144 coap_session_str(session), (*node)->id);
3145 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3146 session->con_active--;
3147 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3148 /* Flush out any entries on session->delayqueue */
3149 coap_session_connected(session);
3150 }
3151 return 1;
3152 }
3153
3154 /* search token in queue to remove (only first occurence will be removed) */
3155 q = *queue;
3156 do {
3157 p = q;
3158 q = q->next;
3159 } while (q && (session != q->session ||
3160 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3161
3162 if (q) { /* found token */
3163 p->next = q->next;
3164 if (p->next) { /* must update relative time of p->next */
3165 p->next->t += q->t;
3166 }
3167 q->next = NULL;
3168 *node = q;
3169 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3170 coap_session_str(session), (*node)->id);
3171 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3172 session->con_active--;
3173 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3174 /* Flush out any entries on session->delayqueue */
3175 coap_session_connected(session);
3176 }
3177 return 1;
3178 }
3179
3180 return 0;
3181
3182}
3183
3184void
3186 coap_nack_reason_t reason) {
3187 coap_queue_t *p, *q;
3188
3189 while (context->sendqueue && context->sendqueue->session == session) {
3190 q = context->sendqueue;
3191 context->sendqueue = q->next;
3192 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3193 coap_session_str(session), q->id);
3194 if (q->pdu->type == COAP_MESSAGE_CON) {
3195 coap_handle_nack(session, q->pdu, reason, q->id);
3196 }
3198 }
3199
3200 if (!context->sendqueue)
3201 return;
3202
3203 p = context->sendqueue;
3204 q = p->next;
3205
3206 while (q) {
3207 if (q->session == session) {
3208 p->next = q->next;
3209 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3210 coap_session_str(session), q->id);
3211 if (q->pdu->type == COAP_MESSAGE_CON) {
3212 coap_handle_nack(session, q->pdu, reason, q->id);
3213 }
3215 q = p->next;
3216 } else {
3217 p = q;
3218 q = q->next;
3219 }
3220 }
3221}
3222
3223void
3225 coap_bin_const_t *token) {
3226 /* cancel all messages in sendqueue that belong to session
3227 * and use the specified token */
3228 coap_queue_t **p, *q;
3229
3230 if (!context->sendqueue)
3231 return;
3232
3233 p = &context->sendqueue;
3234 q = *p;
3235
3236 while (q) {
3237 if (q->session == session &&
3238 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3239 *p = q->next;
3240 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3241 coap_session_str(session), q->id);
3242 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3243 session->con_active--;
3244 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3245 /* Flush out any entries on session->delayqueue */
3246 coap_session_connected(session);
3247 }
3249 } else {
3250 p = &(q->next);
3251 }
3252 q = *p;
3253 }
3254}
3255
3256coap_pdu_t *
3258 coap_opt_filter_t *opts) {
3259 coap_opt_iterator_t opt_iter;
3260 coap_pdu_t *response;
3261 unsigned char type;
3262
3263#if COAP_ERROR_PHRASE_LENGTH > 0
3264 const char *phrase;
3265 if (code != COAP_RESPONSE_CODE(508)) {
3266 phrase = coap_response_phrase(code);
3267 } else {
3268 phrase = NULL;
3269 }
3270#endif
3271
3272 assert(request);
3273
3274 /* cannot send ACK if original request was not confirmable */
3275 type = request->type == COAP_MESSAGE_CON ?
3277
3278 /* Now create the response and fill with options and payload data. */
3279 response = coap_pdu_init(type, code, request->mid,
3280 request->session ?
3281 coap_session_max_pdu_size_lkd(request->session) : 512);
3282 if (response) {
3283 /* copy token */
3284 if (request->actual_token.length &&
3285 !coap_add_token(response, request->actual_token.length,
3286 request->actual_token.s)) {
3287 coap_log_debug("cannot add token to error response\n");
3288 coap_delete_pdu_lkd(response);
3289 return NULL;
3290 }
3291 if (response->code == COAP_RESPONSE_CODE(402)) {
3292 char buf[128];
3293 int first = 1;
3294
3295#if COAP_ERROR_PHRASE_LENGTH > 0
3296 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3297#else
3298 buf[0] = '\000';
3299#endif
3300 /* copy all options into diagnostic message */
3301 coap_option_iterator_init(request, &opt_iter, opts);
3302 while (coap_option_next(&opt_iter)) {
3303 size_t len = strlen(buf);
3304
3305 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",", opt_iter.number);
3306 first = 0;
3307 }
3308 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3309 } else if (opts && opts->mask) {
3310 coap_opt_t *option;
3311
3312 /* copy all options */
3313 coap_option_iterator_init(request, &opt_iter, opts);
3314 while ((option = coap_option_next(&opt_iter))) {
3315 coap_add_option_internal(response, opt_iter.number,
3316 coap_opt_length(option),
3317 coap_opt_value(option));
3318 }
3319#if COAP_ERROR_PHRASE_LENGTH > 0
3320 if (phrase)
3321 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3322 } else {
3323 /* note that diagnostic messages do not need a Content-Format option. */
3324 if (phrase)
3325 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3326#endif
3327 }
3328 }
3329
3330 return response;
3331}
3332
3333#if COAP_SERVER_SUPPORT
3334#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3335
3336static void
3337free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3338 coap_delete_string(app_ptr);
3339}
3340
3341/*
3342 * Caution: As this handler is in libcoap space, it is called with
3343 * context locked.
3344 */
3345static void
3346hnd_get_wellknown_lkd(coap_resource_t *resource,
3347 coap_session_t *session,
3348 const coap_pdu_t *request,
3349 const coap_string_t *query,
3350 coap_pdu_t *response) {
3351 size_t len = 0;
3352 coap_string_t *data_string = NULL;
3353 coap_print_status_t result = 0;
3354 size_t wkc_len = 0;
3355 uint8_t buf[4];
3356
3357 /*
3358 * Quick hack to determine the size of the resource descriptions for
3359 * .well-known/core.
3360 */
3361 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3362 if (result & COAP_PRINT_STATUS_ERROR) {
3363 coap_log_warn("cannot determine length of /.well-known/core\n");
3364 goto error;
3365 }
3366
3367 if (wkc_len > 0) {
3368 data_string = coap_new_string(wkc_len);
3369 if (!data_string)
3370 goto error;
3371
3372 len = wkc_len;
3373 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3374 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3375 coap_log_debug("coap_print_wellknown failed\n");
3376 goto error;
3377 }
3378 assert(len <= (size_t)wkc_len);
3379 data_string->length = len;
3380
3381 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3383 coap_encode_var_safe(buf, sizeof(buf),
3385 goto error;
3386 }
3387 if (response->used_size + len + 1 > response->max_size) {
3388 /*
3389 * Data does not fit into a packet and no libcoap block support
3390 * +1 for end of options marker
3391 */
3392 coap_log_debug(".well-known/core: truncating data length to %" PRIuS " from %" PRIuS "\n",
3393 len, response->max_size - response->used_size - 1);
3394 len = response->max_size - response->used_size - 1;
3395 }
3396 if (!coap_add_data(response, len, data_string->s)) {
3397 goto error;
3398 }
3399 free_wellknown_response(session, data_string);
3400 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3401 response, query,
3403 -1, 0, data_string->length,
3404 data_string->s,
3405 free_wellknown_response,
3406 data_string)) {
3407 goto error_released;
3408 }
3409 } else {
3411 coap_encode_var_safe(buf, sizeof(buf),
3413 goto error;
3414 }
3415 }
3416 response->code = COAP_RESPONSE_CODE(205);
3417 return;
3418
3419error:
3420 free_wellknown_response(session, data_string);
3421error_released:
3422 if (response->code == 0) {
3423 /* set error code 5.03 and remove all options and data from response */
3424 response->code = COAP_RESPONSE_CODE(503);
3425 response->used_size = response->e_token_length;
3426 response->data = NULL;
3427 }
3428}
3429#endif /* COAP_SERVER_SUPPORT */
3430
3441static int
3443 int num_cancelled = 0; /* the number of observers cancelled */
3444
3445#ifndef COAP_SERVER_SUPPORT
3446 (void)sent;
3447#endif /* ! COAP_SERVER_SUPPORT */
3448 (void)context;
3449
3450#if COAP_SERVER_SUPPORT
3451 /* remove observer for this resource, if any
3452 * Use token from sent and try to find a matching resource. Uh!
3453 */
3454 RESOURCES_ITER(context->resources, r) {
3455 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3456 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3457 }
3458#endif /* COAP_SERVER_SUPPORT */
3459
3460 return num_cancelled;
3461}
3462
3463#if COAP_SERVER_SUPPORT
3468enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3469
3470/*
3471 * Checks for No-Response option in given @p request and
3472 * returns @c RESPONSE_DROP if @p response should be suppressed
3473 * according to RFC 7967.
3474 *
3475 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3476 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3477 * on retrying.
3478 *
3479 * Checks if the response code is 0.00 and if either the session is reliable or
3480 * non-confirmable, @c RESPONSE_DROP is also returned.
3481 *
3482 * Multicast response checking is also carried out.
3483 *
3484 * NOTE: It is the responsibility of the application to determine whether
3485 * a delayed separate response should be sent as the original requesting packet
3486 * containing the No-Response option has long since gone.
3487 *
3488 * The value of the No-Response option is encoded as
3489 * follows:
3490 *
3491 * @verbatim
3492 * +-------+-----------------------+-----------------------------------+
3493 * | Value | Binary Representation | Description |
3494 * +-------+-----------------------+-----------------------------------+
3495 * | 0 | <empty> | Interested in all responses. |
3496 * +-------+-----------------------+-----------------------------------+
3497 * | 2 | 00000010 | Not interested in 2.xx responses. |
3498 * +-------+-----------------------+-----------------------------------+
3499 * | 8 | 00001000 | Not interested in 4.xx responses. |
3500 * +-------+-----------------------+-----------------------------------+
3501 * | 16 | 00010000 | Not interested in 5.xx responses. |
3502 * +-------+-----------------------+-----------------------------------+
3503 * @endverbatim
3504 *
3505 * @param request The CoAP request to check for the No-Response option.
3506 * This parameter must not be NULL.
3507 * @param response The response that is potentially suppressed.
3508 * This parameter must not be NULL.
3509 * @param session The session this request/response are associated with.
3510 * This parameter must not be NULL.
3511 * @return RESPONSE_DEFAULT when no special treatment is requested,
3512 * RESPONSE_DROP when the response must be discarded, or
3513 * RESPONSE_SEND when the response must be sent.
3514 */
3515static enum respond_t
3516no_response(coap_pdu_t *request, coap_pdu_t *response,
3517 coap_session_t *session, coap_resource_t *resource) {
3518 coap_opt_t *nores;
3519 coap_opt_iterator_t opt_iter;
3520 unsigned int val = 0;
3521
3522 assert(request);
3523 assert(response);
3524
3525 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3526 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3527
3528 if (nores) {
3530
3531 /* The response should be dropped when the bit corresponding to
3532 * the response class is set (cf. table in function
3533 * documentation). When a No-Response option is present and the
3534 * bit is not set, the sender explicitly indicates interest in
3535 * this response. */
3536 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3537 /* Should be dropping the response */
3538 if (response->type == COAP_MESSAGE_ACK &&
3539 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3540 /* Still need to ACK the request */
3541 response->code = 0;
3542 /* Remove token/data from piggybacked acknowledgment PDU */
3543 response->actual_token.length = 0;
3544 response->e_token_length = 0;
3545 response->used_size = 0;
3546 response->data = NULL;
3547 return RESPONSE_SEND;
3548 } else {
3549 return RESPONSE_DROP;
3550 }
3551 } else {
3552 /* True for mcast as well RFC7967 2.1 */
3553 return RESPONSE_SEND;
3554 }
3555 } else if (resource && session->context->mcast_per_resource &&
3556 coap_is_mcast(&session->addr_info.local)) {
3557 /* Handle any mcast suppression specifics if no NoResponse option */
3558 if ((resource->flags &
3560 COAP_RESPONSE_CLASS(response->code) == 2) {
3561 return RESPONSE_DROP;
3562 } else if ((resource->flags &
3564 response->code == COAP_RESPONSE_CODE(205)) {
3565 if (response->data == NULL)
3566 return RESPONSE_DROP;
3567 } else if ((resource->flags &
3569 COAP_RESPONSE_CLASS(response->code) == 4) {
3570 return RESPONSE_DROP;
3571 } else if ((resource->flags &
3573 COAP_RESPONSE_CLASS(response->code) == 5) {
3574 return RESPONSE_DROP;
3575 }
3576 }
3577 } else if (COAP_PDU_IS_EMPTY(response) &&
3578 (response->type == COAP_MESSAGE_NON ||
3579 COAP_PROTO_RELIABLE(session->proto))) {
3580 /* response is 0.00, and this is reliable or non-confirmable */
3581 return RESPONSE_DROP;
3582 }
3583
3584 /*
3585 * Do not send error responses for requests that were received via
3586 * IP multicast. RFC7252 8.1
3587 */
3588
3589 if (coap_is_mcast(&session->addr_info.local)) {
3590 if (request->type == COAP_MESSAGE_NON &&
3591 response->type == COAP_MESSAGE_RST)
3592 return RESPONSE_DROP;
3593
3594 if ((!resource || session->context->mcast_per_resource == 0) &&
3595 COAP_RESPONSE_CLASS(response->code) > 2)
3596 return RESPONSE_DROP;
3597 }
3598
3599 /* Default behavior applies when we are not dealing with a response
3600 * (class == 0) or the request did not contain a No-Response option.
3601 */
3602 return RESPONSE_DEFAULT;
3603}
3604
3605static coap_str_const_t coap_default_uri_wellknown = {
3607 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3608};
3609
3610/* Initialized in coap_startup() */
3611static coap_resource_t resource_uri_wellknown;
3612
3613static void
3614handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3615 coap_pdu_t *orig_pdu) {
3617 coap_pdu_t *response = NULL;
3618 coap_opt_filter_t opt_filter;
3619 coap_resource_t *resource = NULL;
3620 /* The respond field indicates whether a response must be treated
3621 * specially due to a No-Response option that declares disinterest
3622 * or interest in a specific response class. DEFAULT indicates that
3623 * No-Response has not been specified. */
3624 enum respond_t respond = RESPONSE_DEFAULT;
3625 coap_opt_iterator_t opt_iter;
3626 coap_opt_t *opt;
3627 int is_proxy_uri = 0;
3628 int is_proxy_scheme = 0;
3629 int skip_hop_limit_check = 0;
3630 int resp = 0;
3631 int send_early_empty_ack = 0;
3632 coap_string_t *query = NULL;
3633 coap_opt_t *observe = NULL;
3634 coap_string_t *uri_path = NULL;
3635 int observe_action = COAP_OBSERVE_CANCEL;
3636 coap_block_b_t block;
3637 int added_block = 0;
3638 coap_lg_srcv_t *free_lg_srcv = NULL;
3639#if COAP_Q_BLOCK_SUPPORT
3640 int lg_xmit_ctrl = 0;
3641#endif /* COAP_Q_BLOCK_SUPPORT */
3642#if COAP_ASYNC_SUPPORT
3643 coap_async_t *async;
3644#endif /* COAP_ASYNC_SUPPORT */
3645
3646 if (coap_is_mcast(&session->addr_info.local)) {
3647 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3648 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3649 return;
3650 }
3651 }
3652#if COAP_ASYNC_SUPPORT
3653 async = coap_find_async_lkd(session, pdu->actual_token);
3654 if (async) {
3655 coap_tick_t now;
3656
3657 coap_ticks(&now);
3658 if (async->delay == 0 || async->delay > now) {
3659 /* re-transmit missing ACK (only if CON) */
3660 coap_log_info("Retransmit async response\n");
3661 coap_send_ack_lkd(session, pdu);
3662 /* and do not pass on to the upper layers */
3663 return;
3664 }
3665 }
3666#endif /* COAP_ASYNC_SUPPORT */
3667
3668 coap_option_filter_clear(&opt_filter);
3669 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3670 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3671 if (opt) {
3672 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3673 if (!opt) {
3674 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3675 resp = 402;
3676 goto fail_response;
3677 }
3678 is_proxy_scheme = 1;
3679 }
3680
3681 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3682 if (opt)
3683 is_proxy_uri = 1;
3684 }
3685
3686 if (is_proxy_scheme || is_proxy_uri) {
3687 coap_uri_t uri;
3688
3689 if (!context->proxy_uri_resource) {
3690 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3691 coap_log_debug("Proxy-%s support not configured\n",
3692 is_proxy_scheme ? "Scheme" : "Uri");
3693 resp = 505;
3694 goto fail_response;
3695 }
3696 if (((size_t)pdu->code - 1 <
3697 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3698 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3699 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3700 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3701 is_proxy_scheme ? "Scheme" : "Uri",
3702 pdu->code/100, pdu->code%100);
3703 resp = 505;
3704 goto fail_response;
3705 }
3706
3707 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3708 if (is_proxy_uri) {
3710 coap_opt_length(opt), &uri) < 0) {
3711 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3712 coap_log_debug("Proxy-URI not decodable\n");
3713 resp = 505;
3714 goto fail_response;
3715 }
3716 } else {
3717 memset(&uri, 0, sizeof(uri));
3718 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3719 if (opt) {
3720 uri.host.length = coap_opt_length(opt);
3721 uri.host.s = coap_opt_value(opt);
3722 } else
3723 uri.host.length = 0;
3724 }
3725
3726 resource = context->proxy_uri_resource;
3727 if (uri.host.length && resource->proxy_name_count &&
3728 resource->proxy_name_list) {
3729 size_t i;
3730
3731 if (resource->proxy_name_count == 1 &&
3732 resource->proxy_name_list[0]->length == 0) {
3733 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3734 i = 0;
3735 } else {
3736 for (i = 0; i < resource->proxy_name_count; i++) {
3737 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3738 break;
3739 }
3740 }
3741 }
3742 if (i != resource->proxy_name_count) {
3743 /* This server is hosting the proxy connection endpoint */
3744 if (pdu->crit_opt) {
3745 /* Cannot handle critical option */
3746 pdu->crit_opt = 0;
3747 resp = 402;
3748 resource = NULL;
3749 goto fail_response;
3750 }
3751 is_proxy_uri = 0;
3752 is_proxy_scheme = 0;
3753 skip_hop_limit_check = 1;
3754 }
3755 }
3756 resource = NULL;
3757 }
3758 assert(resource == NULL);
3759
3760 if (!skip_hop_limit_check) {
3761 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3762 if (opt) {
3763 size_t hop_limit;
3764 uint8_t buf[4];
3765
3766 hop_limit =
3768 if (hop_limit == 1) {
3769 /* coap_send_internal() will fill in the IP address for us */
3770 resp = 508;
3771 goto fail_response;
3772 } else if (hop_limit < 1 || hop_limit > 255) {
3773 /* Need to return a 4.00 RFC8768 Section 3 */
3774 coap_log_info("Invalid Hop Limit\n");
3775 resp = 400;
3776 goto fail_response;
3777 }
3778 hop_limit--;
3780 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3781 buf);
3782 }
3783 }
3784
3785 uri_path = coap_get_uri_path(pdu);
3786 if (!uri_path) {
3787 resp = 402;
3788 goto fail_response;
3789 }
3790
3791 if (!is_proxy_uri && !is_proxy_scheme) {
3792 /* try to find the resource from the request URI */
3793 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3794 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3795 }
3796
3797 if ((resource == NULL) || (resource->is_unknown == 1) ||
3798 (resource->is_proxy_uri == 1)) {
3799 /* The resource was not found or there is an unexpected match against the
3800 * resource defined for handling unknown or proxy URIs.
3801 */
3802 if (resource != NULL)
3803 /* Close down unexpected match */
3804 resource = NULL;
3805 /*
3806 * Check if the request URI happens to be the well-known URI, or if the
3807 * unknown resource handler is defined, a PUT or optionally other methods,
3808 * if configured, for the unknown handler.
3809 *
3810 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3811 * proxy URI handler.
3812 *
3813 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3814 * set, call the unknown URI handler with any unknown URI (including
3815 * .well-known/core) if the appropriate method is defined.
3816 *
3817 * else if well-known URI generate a default response.
3818 *
3819 * else if unknown URI handler defined, call the unknown
3820 * URI handler (to allow for potential generation of resource
3821 * [RFC7272 5.8.3]) if the appropriate method is defined.
3822 *
3823 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3824 *
3825 * else return 4.04.
3826 */
3827
3828 if (is_proxy_uri || is_proxy_scheme) {
3829 resource = context->proxy_uri_resource;
3830 } else if (context->unknown_resource != NULL &&
3831 context->unknown_resource->flags & COAP_RESOURCE_HANDLE_WELLKNOWN_CORE &&
3832 ((size_t)pdu->code - 1 <
3833 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3834 (context->unknown_resource->handler[pdu->code - 1])) {
3835 resource = context->unknown_resource;
3836 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3837 /* request for .well-known/core */
3838 resource = &resource_uri_wellknown;
3839 } else if ((context->unknown_resource != NULL) &&
3840 ((size_t)pdu->code - 1 <
3841 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3842 (context->unknown_resource->handler[pdu->code - 1])) {
3843 /*
3844 * The unknown_resource can be used to handle undefined resources
3845 * for a PUT request and can support any other registered handler
3846 * defined for it
3847 * Example set up code:-
3848 * r = coap_resource_unknown_init(hnd_put_unknown);
3849 * coap_register_request_handler(r, COAP_REQUEST_POST,
3850 * hnd_post_unknown);
3851 * coap_register_request_handler(r, COAP_REQUEST_GET,
3852 * hnd_get_unknown);
3853 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3854 * hnd_delete_unknown);
3855 * coap_add_resource(ctx, r);
3856 *
3857 * Note: It is not possible to observe the unknown_resource, a separate
3858 * resource must be created (by PUT or POST) which has a GET
3859 * handler to be observed
3860 */
3861 resource = context->unknown_resource;
3862 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3863 /*
3864 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3865 */
3866 coap_log_debug("request for unknown resource '%*.*s',"
3867 " return 2.02\n",
3868 (int)uri_path->length,
3869 (int)uri_path->length,
3870 uri_path->s);
3871 resp = 202;
3872 goto fail_response;
3873 } else if ((context->dyn_create_handler != NULL) &&
3875 /* Above test must be the same as in coap_op_dyn_resource_load_disk() */
3876 if (context->dynamic_cur < context->dynamic_max || context->dynamic_max == 0) {
3877#if COAP_WITH_OBSERVE_PERSIST
3878 /* If we are maintaining Observe persist */
3879 context->unknown_pdu = pdu;
3880 context->unknown_session = session;
3881#endif /* COAP_WITH_OBSERVE_PERSIST */
3882 coap_lock_callback_ret(resource, context->dyn_create_handler(session, pdu));
3883#if COAP_WITH_OBSERVE_PERSIST
3884 /* If we are maintaining Observe persist */
3885 context->unknown_pdu = NULL;
3886 context->unknown_session = NULL;
3887#endif /* COAP_WITH_OBSERVE_PERSIST */
3888 }
3889 if (!resource) {
3890 resp = 406;
3891 goto fail_response;
3892 }
3893 context->dynamic_cur++;
3894 resource->is_dynamic = 1;
3895 } else { /* request for any another resource, return 4.04 */
3896
3897 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3898 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3899 resp = 404;
3900 goto fail_response;
3901 }
3902
3903 }
3904
3905 coap_resource_reference_lkd(resource);
3906
3907#if COAP_OSCORE_SUPPORT
3908 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3909 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3910 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3911 resp = 401;
3912 goto fail_response;
3913 }
3914#endif /* COAP_OSCORE_SUPPORT */
3915 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3916 /* Check for existing resource and If-Non-Match */
3917 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3918 if (opt) {
3919 resp = 412;
3920 goto fail_response;
3921 }
3922 }
3923
3924 /* the resource was found, check if there is a registered handler */
3925 if ((size_t)pdu->code - 1 <
3926 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3927 h = resource->handler[pdu->code - 1];
3928
3929 if (h == NULL) {
3930 resp = 405;
3931 goto fail_response;
3932 }
3933 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3934 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) == NULL) {
3935 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3936 if (opt == NULL) {
3937 /* RFC 8132 2.3.1 */
3938 resp = 415;
3939 goto fail_response;
3940 }
3941 }
3942 }
3943 if (context->mcast_per_resource &&
3944 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3945 coap_is_mcast(&session->addr_info.local)) {
3946 resp = 405;
3947 goto fail_response;
3948 }
3949
3950 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3952 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3953 if (!response) {
3954 coap_log_err("could not create response PDU\n");
3955 resp = 500;
3956 goto fail_response;
3957 }
3958 response->session = session;
3959#if COAP_ASYNC_SUPPORT
3960 /* If handling a separate response, need CON, not ACK response */
3961 if (async && pdu->type == COAP_MESSAGE_CON)
3962 response->type = COAP_MESSAGE_CON;
3963#endif /* COAP_ASYNC_SUPPORT */
3964 /* A lot of the reliable code assumes type is CON */
3965 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3966 response->type = COAP_MESSAGE_CON;
3967
3968 if (!coap_add_token(response, pdu->actual_token.length,
3969 pdu->actual_token.s)) {
3970 resp = 500;
3971 goto fail_response;
3972 }
3973
3974 query = coap_get_query(pdu);
3975
3976 /* check for Observe option RFC7641 and RFC8132 */
3977 if (resource->observable &&
3978 (pdu->code == COAP_REQUEST_CODE_GET ||
3979 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3980 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3981 }
3982
3983 /*
3984 * See if blocks need to be aggregated or next requests sent off
3985 * before invoking application request handler
3986 */
3987 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3988 uint32_t block_mode = session->block_mode;
3989
3990 if (observe ||
3991 resource->flags & COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY)
3993 if (coap_handle_request_put_block(context, session, pdu, response,
3994 resource, uri_path, observe,
3995 &added_block, &free_lg_srcv)) {
3996 session->block_mode = block_mode;
3997 goto skip_handler;
3998 }
3999 session->block_mode = block_mode;
4000
4001 if (coap_handle_request_send_block(session, pdu, response, resource,
4002 query)) {
4003#if COAP_Q_BLOCK_SUPPORT
4004 lg_xmit_ctrl = 1;
4005#endif /* COAP_Q_BLOCK_SUPPORT */
4006 goto skip_handler;
4007 }
4008 }
4009
4010 if (observe) {
4011 observe_action =
4013 coap_opt_length(observe));
4014
4015 if (observe_action == COAP_OBSERVE_ESTABLISH) {
4016 coap_subscription_t *subscription;
4017
4018 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
4019 if (block.num != 0) {
4020 response->code = COAP_RESPONSE_CODE(400);
4021 goto skip_handler;
4022 }
4023#if COAP_Q_BLOCK_SUPPORT
4024 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
4025 &block)) {
4026 if (block.num != 0) {
4027 response->code = COAP_RESPONSE_CODE(400);
4028 goto skip_handler;
4029 }
4030#endif /* COAP_Q_BLOCK_SUPPORT */
4031 }
4032 subscription = coap_add_observer(resource, session, &pdu->actual_token,
4033 pdu);
4034 if (subscription) {
4035 uint8_t buf[4];
4036
4037 coap_touch_observer(context, session, &pdu->actual_token);
4039 coap_encode_var_safe(buf, sizeof(buf),
4040 resource->observe),
4041 buf);
4042 }
4043 } else if (observe_action == COAP_OBSERVE_CANCEL) {
4044 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
4045 } else {
4046 coap_log_info("observe: unexpected action %d\n", observe_action);
4047 }
4048 }
4049
4050 if ((resource == context->proxy_uri_resource ||
4051 (resource == context->unknown_resource &&
4052 context->unknown_resource->is_reverse_proxy)) &&
4053 COAP_PROTO_NOT_RELIABLE(session->proto) &&
4054 pdu->type == COAP_MESSAGE_CON &&
4055 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
4056 /* Make the proxy response separate and fix response later */
4057 send_early_empty_ack = 1;
4058 }
4059 if (send_early_empty_ack) {
4060 coap_send_ack_lkd(session, pdu);
4061 if (pdu->mid == session->last_con_mid) {
4062 /* request has already been processed - do not process it again */
4063 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
4064 pdu->mid);
4065 goto drop_it_no_debug;
4066 }
4067 session->last_con_mid = pdu->mid;
4068 }
4069#if COAP_WITH_OBSERVE_PERSIST
4070 /* If we are maintaining Observe persist */
4071 if (resource == context->unknown_resource) {
4072 context->unknown_pdu = pdu;
4073 context->unknown_session = session;
4074 } else
4075 context->unknown_pdu = NULL;
4076#endif /* COAP_WITH_OBSERVE_PERSIST */
4077
4078 /*
4079 * Call the request handler with everything set up
4080 */
4081 if (resource == &resource_uri_wellknown) {
4082 /* Leave context locked */
4083 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
4084 (int)resource->uri_path->length, (int)resource->uri_path->length,
4085 resource->uri_path->s);
4086 h(resource, session, pdu, query, response);
4087 } else {
4088 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
4089 (int)resource->uri_path->length, (int)resource->uri_path->length,
4090 resource->uri_path->s);
4091 if (resource->flags & COAP_RESOURCE_SAFE_REQUEST_HANDLER) {
4092 coap_lock_callback_release(h(resource, session, pdu, query, response),
4093 /* context is being freed off */
4094 goto finish);
4095 } else {
4097 h(resource, session, pdu, query, response),
4098 /* context is being freed off */
4099 goto finish);
4100 }
4101 }
4102
4103 /* Check validity of response code */
4104 if (!coap_check_code_class(session, response)) {
4105 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
4106 COAP_RESPONSE_CLASS(response->code),
4107 response->code & 0x1f);
4108 goto drop_it_no_debug;
4109 }
4110
4111 /* Check if lg_xmit generated and update PDU code if so */
4112 coap_check_code_lg_xmit(session, pdu, response, resource, query);
4113
4114 if (free_lg_srcv) {
4115 /* Check to see if the server is doing a 4.01 + Echo response */
4116 if (response->code == COAP_RESPONSE_CODE(401) &&
4117 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
4118 /* Need to keep lg_srcv around for client's response */
4119 } else {
4120 coap_lg_srcv_t *lg_srcv;
4121 /*
4122 * Need to check free_lg_srcv still exists in case of error or timing window
4123 */
4124 LL_FOREACH(session->lg_srcv, lg_srcv) {
4125 if (lg_srcv == free_lg_srcv) {
4126 LL_DELETE(session->lg_srcv, free_lg_srcv);
4127 coap_block_delete_lg_srcv(session, free_lg_srcv);
4128 break;
4129 }
4130 }
4131 }
4132 }
4133 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
4134 /* Just in case, as there are more to go */
4135 response->code = COAP_RESPONSE_CODE(231);
4136 }
4137
4138skip_handler:
4139 if (send_early_empty_ack &&
4140 response->type == COAP_MESSAGE_ACK) {
4141 /* Response is now separate - convert to CON as needed */
4142 response->type = COAP_MESSAGE_CON;
4143 /* Check for empty ACK - need to drop as already sent */
4144 if (response->code == 0) {
4145 goto drop_it_no_debug;
4146 }
4147 }
4148 respond = no_response(pdu, response, session, resource);
4149 if (respond != RESPONSE_DROP) {
4150#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
4151 coap_mid_t mid = pdu->mid;
4152#endif
4153 if (COAP_RESPONSE_CLASS(response->code) != 2) {
4154 if (observe) {
4156 }
4157 }
4158 if (COAP_RESPONSE_CLASS(response->code) > 2) {
4159 if (observe)
4160 coap_delete_observer(resource, session, &pdu->actual_token);
4161 if (response->code != COAP_RESPONSE_CODE(413))
4163 }
4164
4165 /* If original request contained a token, and the registered
4166 * application handler made no changes to the response, then
4167 * this is an empty ACK with a token, which is a malformed
4168 * PDU */
4169 if ((response->type == COAP_MESSAGE_ACK)
4170 && (response->code == 0)) {
4171 /* Remove token from otherwise-empty acknowledgment PDU */
4172 response->actual_token.length = 0;
4173 response->e_token_length = 0;
4174 response->used_size = 0;
4175 response->data = NULL;
4176 }
4177
4178 if (!coap_is_mcast(&session->addr_info.local) ||
4179 (context->mcast_per_resource &&
4180 resource &&
4181 (resource->flags & COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS))) {
4182 /* No delays to response */
4183#if COAP_Q_BLOCK_SUPPORT
4184 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4185 !lg_xmit_ctrl && COAP_RESPONSE_CLASS(response->code) == 2 &&
4186 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4187 block.m) {
4188 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4189 response,
4190 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4191 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4192 response = NULL;
4193 goto finish;
4194 }
4195#endif /* COAP_Q_BLOCK_SUPPORT */
4196 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4197 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4198 goto finish;
4199 }
4200 } else {
4201 /* Need to delay mcast response */
4202 coap_queue_t *node = coap_new_node();
4203 uint8_t r;
4204 coap_tick_t delay;
4205
4206 if (!node) {
4207 coap_log_debug("mcast delay: insufficient memory\n");
4208 goto drop_it_no_debug;
4209 }
4210 if (!coap_pdu_encode_header(response, session->proto)) {
4212 goto drop_it_no_debug;
4213 }
4214
4215 node->id = response->mid;
4216 node->pdu = response;
4217 node->is_mcast = 1;
4218 coap_prng_lkd(&r, sizeof(r));
4219 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4220 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4221 coap_session_str(session),
4222 response->mid,
4223 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4224 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4225 1000 / COAP_TICKS_PER_SECOND));
4226 node->timeout = (unsigned int)delay;
4227 /* Use this to delay transmission */
4228 coap_wait_ack(session->context, session, node);
4229 }
4230 } else {
4231 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4232 coap_session_str(session),
4233 response->mid);
4234 coap_show_pdu(COAP_LOG_DEBUG, response);
4235drop_it_no_debug:
4236 coap_delete_pdu_lkd(response);
4237 }
4238#if COAP_Q_BLOCK_SUPPORT
4239 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4240 if (COAP_PROTO_RELIABLE(session->proto)) {
4241 if (block.m) {
4242 /* All of the sequence not in yet */
4243 goto finish;
4244 }
4245 } else if (pdu->type == COAP_MESSAGE_NON) {
4246 /* More to go and not at a payload break */
4247 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4248 goto finish;
4249 }
4250 }
4251 }
4252#endif /* COAP_Q_BLOCK_SUPPORT */
4253
4254finish:
4255 if (query)
4256 coap_delete_string(query);
4257 if (resource)
4258 coap_resource_release_lkd(resource);
4259 coap_delete_string(uri_path);
4260 return;
4261
4262fail_response:
4263 coap_delete_pdu_lkd(response);
4264 response =
4266 &opt_filter);
4267 if (response)
4268 goto skip_handler;
4269 if (resource)
4270 coap_resource_release_lkd(resource);
4271 coap_delete_string(uri_path);
4272}
4273#endif /* COAP_SERVER_SUPPORT */
4274
4275#if COAP_CLIENT_SUPPORT
4276/* Call application-specific response handler when available. */
4277void
4279 coap_pdu_t *sent, coap_pdu_t *rcvd,
4280 void *body_data) {
4281 coap_context_t *context = session->context;
4282 coap_response_t ret;
4283
4284#if COAP_PROXY_SUPPORT
4285 if (context->proxy_response_cb) {
4286 coap_proxy_entry_t *proxy_entry;
4287 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4288 rcvd,
4289 &proxy_entry);
4290
4291 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4292 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4293 proxy_entry);
4294 return;
4295 }
4296 }
4297#endif /* COAP_PROXY_SUPPORT */
4298 if (session->doing_send_recv && session->req_token &&
4299 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4300 /* processing coap_send_recv() call */
4301 session->resp_pdu = rcvd;
4303 /* Will get freed off when PDU is freed off */
4304 rcvd->data_free = body_data;
4305 coap_send_ack_lkd(session, rcvd);
4307 return;
4308 } else if (context->response_cb) {
4310 context->response_cb(session,
4311 sent,
4312 rcvd,
4313 rcvd->mid),
4314 /* context is being freed off */
4315 return);
4316 } else {
4317 ret = COAP_RESPONSE_OK;
4318 }
4319 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4320 coap_send_rst_lkd(session, rcvd);
4322 } else {
4323 coap_send_ack_lkd(session, rcvd);
4325 }
4326 coap_free_type(COAP_STRING, body_data);
4327}
4328
4329static void
4330handle_response(coap_context_t *context, coap_session_t *session,
4331 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4332
4333 /* Set in case there is a later call to coap_update_token() */
4334 rcvd->session = session;
4335
4336 /* Check for message duplication */
4337 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4338 if (rcvd->type == COAP_MESSAGE_CON) {
4339 if (rcvd->mid == session->last_con_mid) {
4340 /* Duplicate response: send ACK/RST, but don't process */
4341 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4342 coap_send_ack_lkd(session, rcvd);
4343 else
4344 coap_send_rst_lkd(session, rcvd);
4345 return;
4346 }
4347 session->last_con_mid = rcvd->mid;
4348 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4349 if (rcvd->mid == session->last_ack_mid) {
4350 /* Duplicate response */
4351 return;
4352 }
4353 session->last_ack_mid = rcvd->mid;
4354 }
4355 }
4356 /* Check to see if checking out extended token support */
4357 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4358 session->last_token) {
4359 coap_lg_crcv_t *lg_crcv;
4360
4361 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4362 rcvd->actual_token.length != session->max_token_size ||
4363 rcvd->code == COAP_RESPONSE_CODE(400) ||
4364 rcvd->code == COAP_RESPONSE_CODE(503)) {
4365 coap_log_debug("Extended Token requested size support not available\n");
4367 } else {
4368 coap_log_debug("Extended Token support available\n");
4369 }
4371 /* Need to remove lg_crcv set up for this test */
4372 lg_crcv = coap_find_lg_crcv(session, rcvd);
4373 if (lg_crcv) {
4374 LL_DELETE(session->lg_crcv, lg_crcv);
4375 coap_block_delete_lg_crcv(session, lg_crcv);
4376 }
4377 coap_send_ack_lkd(session, rcvd);
4378 coap_reset_doing_first(session);
4379 return;
4380 }
4381#if COAP_Q_BLOCK_SUPPORT
4382 /* Check to see if checking out Q-Block support */
4383 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
4384 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4385 coap_log_debug("Q-Block support not available\n");
4386 set_block_mode_drop_q(session->block_mode);
4387 } else {
4388 coap_block_b_t qblock;
4389
4390 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4391 coap_log_debug("Q-Block support available\n");
4392 set_block_mode_has_q(session->block_mode);
4393 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4394 /* Flush out any entries on session->delayqueue */
4395 coap_session_connected(session);
4396 } else {
4397 coap_log_debug("Q-Block support not available\n");
4398 set_block_mode_drop_q(session->block_mode);
4399 }
4400 }
4401 coap_send_ack_lkd(session, rcvd);
4402 coap_reset_doing_first(session);
4403 return;
4404 }
4405#endif /* COAP_Q_BLOCK_SUPPORT */
4406
4407 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4408 /* See if need to send next block to server */
4409 if (coap_handle_response_send_block(session, sent, rcvd)) {
4410 /* Next block transmitted, no need to inform app */
4411 coap_send_ack_lkd(session, rcvd);
4412 return;
4413 }
4414
4415 /* Need to see if needing to request next block */
4416 if (coap_handle_response_get_block(context, session, sent, rcvd,
4417 COAP_RECURSE_OK)) {
4418 /* Next block transmitted, ack sent no need to inform app */
4419 return;
4420 }
4421 }
4422 coap_reset_doing_first(session);
4423
4424 /* Call application-specific response handler when available. */
4425 coap_call_response_handler(session, sent, rcvd, NULL);
4426}
4427#endif /* COAP_CLIENT_SUPPORT */
4428
4429#if !COAP_DISABLE_TCP
4430static void
4432 coap_pdu_t *pdu) {
4433 coap_opt_iterator_t opt_iter;
4434 coap_opt_t *option;
4435 int set_mtu = 0;
4436
4437 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4438
4439 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4440 if (session->csm_not_seen) {
4441 coap_tick_t now;
4442
4443 coap_ticks(&now);
4444 /* CSM timeout before CSM seen */
4445 coap_log_warn("***%s: CSM received after CSM timeout\n",
4446 coap_session_str(session));
4447 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4448 coap_session_str(session),
4449 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4450 }
4451 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4453 }
4454 while ((option = coap_option_next(&opt_iter))) {
4456 unsigned max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4457
4458 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4460 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4461 coap_session_str(session), max_recv);
4462 }
4463 coap_session_set_mtu(session, max_recv);
4464 set_mtu = 1;
4465 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4466 session->csm_block_supported = 1;
4467 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4468 session->max_token_size =
4470 coap_opt_length(option));
4473 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4476 }
4477 }
4478 if (set_mtu) {
4479 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4480 session->csm_bert_rem_support = 1;
4481 else
4482 session->csm_bert_rem_support = 0;
4483 }
4484 if (session->state == COAP_SESSION_STATE_CSM)
4485 coap_session_connected(session);
4486 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4488 if (context->ping_cb) {
4489 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4490 }
4491 if (pong) {
4493 coap_send_internal(session, pong, NULL);
4494 }
4495 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4496 session->last_pong = session->last_rx_tx;
4497 session->ping_failed = 0;
4498 if (context->pong_cb) {
4499 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4500 }
4501 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4502 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4504 }
4505}
4506#endif /* !COAP_DISABLE_TCP */
4507
4508static int
4510 if (COAP_PDU_IS_REQUEST(pdu) &&
4511 pdu->actual_token.length >
4512 (session->type == COAP_SESSION_TYPE_CLIENT ?
4513 session->max_token_size : session->context->max_token_size)) {
4514 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4515 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4516 coap_opt_filter_t opt_filter;
4517 coap_pdu_t *response;
4518
4519 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4520 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4521 &opt_filter);
4522 if (!response) {
4523 coap_log_warn("coap_dispatch: cannot create error response\n");
4524 } else {
4525 /*
4526 * Note - have to leave in oversize token as per
4527 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4528 */
4529 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4530 coap_log_warn("coap_dispatch: error sending response\n");
4531 }
4532 } else {
4533 /* Indicate no extended token support */
4534 coap_send_rst_lkd(session, pdu);
4535 }
4536 return 0;
4537 }
4538 return 1;
4539}
4540
4541void
4543 coap_pdu_t *pdu) {
4544 coap_queue_t *sent = NULL;
4545 coap_pdu_t *response;
4546 coap_pdu_t *orig_pdu = NULL;
4547 coap_opt_filter_t opt_filter;
4548 int is_ping_rst;
4549 int packet_is_bad = 0;
4550#if COAP_OSCORE_SUPPORT
4551 coap_opt_iterator_t opt_iter;
4552 coap_pdu_t *dec_pdu = NULL;
4553#endif /* COAP_OSCORE_SUPPORT */
4554 int is_ext_token_rst = 0;
4555 int oscore_invalid = 0;
4556
4557 pdu->session = session;
4559
4560 /* Check validity of received code */
4561 if (!coap_check_code_class(session, pdu)) {
4562 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4564 pdu->code & 0x1f);
4565 packet_is_bad = 1;
4566 if (pdu->type == COAP_MESSAGE_CON) {
4568 }
4569 /* find message id in sendqueue to stop retransmission */
4570 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4571 goto cleanup;
4572 }
4573
4574 coap_option_filter_clear(&opt_filter);
4575
4576#if COAP_SERVER_SUPPORT
4577 /* See if this a repeat request */
4578 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4580 coap_digest_t digest;
4581
4582 coap_pdu_cksum(pdu, &digest);
4583 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4584#if COAP_OSCORE_SUPPORT
4585 uint8_t oscore_encryption = session->oscore_encryption;
4586
4587 session->oscore_encryption = 0;
4588#endif /* COAP_OSCORE_SUPPORT */
4589 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4590 cached_pdu must not be removed */
4591 coap_pdu_reference_lkd(session->cached_pdu);
4592 coap_log_debug("Retransmit response to duplicate request\n");
4593 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4594#if COAP_OSCORE_SUPPORT
4595 session->oscore_encryption = oscore_encryption;
4596#endif /* COAP_OSCORE_SUPPORT */
4597 return;
4598 }
4599#if COAP_OSCORE_SUPPORT
4600 session->oscore_encryption = oscore_encryption;
4601#endif /* COAP_OSCORE_SUPPORT */
4602 }
4603 }
4604#endif /* COAP_SERVER_SUPPORT */
4605 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4606 if (!check_token_size(session, pdu)) {
4607 goto cleanup;
4608 }
4609 }
4610#if COAP_OSCORE_SUPPORT
4611 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4612 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4613 if (pdu->type == COAP_MESSAGE_CON || pdu->type == COAP_MESSAGE_NON) {
4614 if (COAP_PDU_IS_REQUEST(pdu)) {
4615 response =
4616 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4617
4618 if (!response) {
4619 coap_log_warn("coap_dispatch: cannot create error response\n");
4620 } else {
4621 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4622 coap_log_warn("coap_dispatch: error sending response\n");
4623 }
4624 } else {
4625 coap_send_rst_lkd(session, pdu);
4626 }
4627 }
4628 goto cleanup;
4629 }
4630
4631 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4632 int decrypt = 1;
4633#if COAP_SERVER_SUPPORT
4634 coap_opt_t *opt;
4635 coap_resource_t *resource;
4636 coap_uri_t uri;
4637#endif /* COAP_SERVER_SUPPORT */
4638
4639 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4640 decrypt = 0;
4641
4642#if COAP_SERVER_SUPPORT
4643 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4644 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4645 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4646 != NULL) {
4647 /* Need to check whether this is a direct or proxy session */
4648 memset(&uri, 0, sizeof(uri));
4649 uri.host.length = coap_opt_length(opt);
4650 uri.host.s = coap_opt_value(opt);
4651 resource = context->proxy_uri_resource;
4652 if (uri.host.length && resource && resource->proxy_name_count &&
4653 resource->proxy_name_list) {
4654 size_t i;
4655 for (i = 0; i < resource->proxy_name_count; i++) {
4656 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4657 break;
4658 }
4659 }
4660 if (i == resource->proxy_name_count) {
4661 /* This server is not hosting the proxy connection endpoint */
4662 decrypt = 0;
4663 }
4664 }
4665 }
4666#endif /* COAP_SERVER_SUPPORT */
4667 if (decrypt) {
4668 /* find message id in sendqueue to stop retransmission and get sent */
4669 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4670 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4671 orig_pdu = pdu;
4672 coap_pdu_reference_lkd(orig_pdu);
4673 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4674 if (session->recipient_ctx == NULL ||
4675 session->recipient_ctx->initial_state == 0) {
4676 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4677 }
4679 coap_delete_pdu_lkd(orig_pdu);
4680 return;
4681 } else {
4682 session->oscore_encryption = 1;
4683 pdu = dec_pdu;
4684 }
4685 coap_log_debug("Decrypted PDU\n");
4687 }
4688 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4689 session->oscore_encryption &&
4690 pdu->type != COAP_MESSAGE_RST) {
4691 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4692 /* Violates RFC 8613 2 */
4693 coap_log_err("received an invalid response to the OSCORE request\n");
4694 oscore_invalid = 1;
4695 }
4696 }
4697#endif /* COAP_OSCORE_SUPPORT */
4698
4699 switch (pdu->type) {
4700 case COAP_MESSAGE_ACK:
4701 if (NULL == sent) {
4702 /* find message id in sendqueue to stop retransmission */
4703 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4704 }
4705
4706 if (sent && session->con_active) {
4707 session->con_active--;
4708 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4709 /* Flush out any entries on session->delayqueue */
4710 coap_session_connected(session);
4711 }
4712 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4713 packet_is_bad = 1;
4714 goto cleanup;
4715 }
4716
4717#if COAP_SERVER_SUPPORT
4718 /* if sent code was >= 64 the message might have been a
4719 * notification. Then, we must flag the observer to be alive
4720 * by setting obs->fail_cnt = 0. */
4721 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4722 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4723 }
4724#endif /* COAP_SERVER_SUPPORT */
4725
4726#if COAP_Q_BLOCK_SUPPORT
4727 if (session->lg_xmit && sent && sent->pdu && sent->pdu->type == COAP_MESSAGE_CON &&
4728 !(session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK)) {
4729 int doing_q_block = 0;
4730 coap_lg_xmit_t *lg_xmit = NULL;
4731
4732 LL_FOREACH(session->lg_xmit, lg_xmit) {
4733 if ((lg_xmit->option == COAP_OPTION_Q_BLOCK1 || lg_xmit->option == COAP_OPTION_Q_BLOCK2) &&
4734 lg_xmit->last_all_sent == 0 && lg_xmit->sent_pdu->type != COAP_MESSAGE_NON) {
4735 doing_q_block = 1;
4736 break;
4737 }
4738 }
4739 if (doing_q_block && lg_xmit) {
4740 coap_block_b_t block;
4741
4742 memset(&block, 0, sizeof(block));
4743 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
4744 block.num = lg_xmit->last_block + lg_xmit->b.b1.count;
4745 } else {
4746 block.num = lg_xmit->last_block;
4747 }
4748 block.m = 1;
4749 block.szx = block.aszx = lg_xmit->blk_size;
4750 block.defined = 1;
4751 block.bert = 0;
4752 block.chunk_size = 1024;
4753
4754 coap_send_q_blocks(session, lg_xmit, block,
4755 lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
4756 }
4757 }
4758#endif /* COAP_Q_BLOCK_SUPPORT */
4759 if (pdu->code == 0) {
4760#if COAP_CLIENT_SUPPORT
4761 /*
4762 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4763 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4764 * response if the response was piggy-backed. Here, a separate response
4765 * detected and so the lg_crcv needs to be set up before the sent PDU
4766 * information is lost.
4767 *
4768 * lg_crcv was not set up if not a CoAP request.
4769 *
4770 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4771 * options.
4772 */
4773 if (sent &&
4774 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4775 COAP_PDU_IS_REQUEST(sent->pdu)) {
4776 /*
4777 * lg_crcv was not set up in coap_send(). It could have been set up
4778 * the first separate response.
4779 * See if there already is a lg_crcv set up.
4780 */
4781 coap_lg_crcv_t *lg_crcv;
4782 uint64_t token_match =
4784 sent->pdu->actual_token.length));
4785
4786 LL_FOREACH(session->lg_crcv, lg_crcv) {
4787 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4788 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4789 break;
4790 }
4791 }
4792 if (!lg_crcv) {
4793 /*
4794 * Need to set up a lg_crcv as it was not set up in coap_send()
4795 * to save time, but server has not sent back a piggy-back response.
4796 */
4797 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4798 if (lg_crcv) {
4799 LL_PREPEND(session->lg_crcv, lg_crcv);
4800 }
4801 }
4802 }
4803#endif /* COAP_CLIENT_SUPPORT */
4804 /* an empty ACK needs no further handling */
4805 goto cleanup;
4806 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4807 /* This is not legitimate - Request using ACK - ignore */
4808 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4810 pdu->code & 0x1f);
4811 packet_is_bad = 1;
4812 goto cleanup;
4813 }
4814
4815 break;
4816
4817 case COAP_MESSAGE_RST:
4818 /* We have sent something the receiver disliked, so we remove
4819 * not only the message id but also the subscriptions we might
4820 * have. */
4821 is_ping_rst = 0;
4822 if (pdu->mid == session->last_ping_mid &&
4823 session->last_ping > 0)
4824 is_ping_rst = 1;
4825
4826#if COAP_CLIENT_SUPPORT
4827#if COAP_Q_BLOCK_SUPPORT
4828 /* Check to see if checking out Q-Block support */
4829 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4830 session->remote_test_mid == pdu->mid) {
4831 coap_log_debug("Q-Block support not available\n");
4832 set_block_mode_drop_q(session->block_mode);
4833 coap_reset_doing_first(session);
4834 }
4835#endif /* COAP_Q_BLOCK_SUPPORT */
4836
4837 /* Check to see if checking out extended token support */
4838 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4839 session->remote_test_mid == pdu->mid) {
4840 coap_log_debug("Extended Token support not available\n");
4843 coap_reset_doing_first(session);
4844 is_ext_token_rst = 1;
4845 }
4846#endif /* COAP_CLIENT_SUPPORT */
4847
4848 if (!is_ping_rst && !is_ext_token_rst)
4849 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4850
4851 if (session->con_active) {
4852 session->con_active--;
4853 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4854 /* Flush out any entries on session->delayqueue */
4855 coap_session_connected(session);
4856 }
4857
4858 /* find message id in sendqueue to stop retransmission */
4859 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4860
4861 if (sent) {
4862 if (!is_ping_rst)
4863 coap_cancel(context, sent);
4864
4865 if (!is_ping_rst && !is_ext_token_rst) {
4866 if (sent->pdu->type==COAP_MESSAGE_CON) {
4867 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4868 }
4869 } else if (is_ping_rst) {
4870 if (context->pong_cb) {
4871 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4872 }
4873 session->last_pong = session->last_rx_tx;
4874 session->ping_failed = 0;
4876 }
4877 } else {
4878#if COAP_SERVER_SUPPORT
4879 /* Need to check is there is a subscription active and delete it */
4880 RESOURCES_ITER(context->resources, r) {
4881 coap_subscription_t *obs, *tmp;
4882 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4883 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4884 /* Need to do this now as session may get de-referenced */
4886 coap_delete_observer(r, session, &obs->pdu->actual_token);
4887 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4888 coap_session_release_lkd(session);
4889 goto cleanup;
4890 }
4891 }
4892 }
4893#endif /* COAP_SERVER_SUPPORT */
4894 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4895 }
4896#if COAP_PROXY_SUPPORT
4897 if (!is_ping_rst) {
4898 /* Need to check is there is a proxy subscription active and delete it */
4899 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
4900 }
4901#endif /* COAP_PROXY_SUPPORT */
4902 goto cleanup;
4903
4904 case COAP_MESSAGE_NON:
4905 /* check for oscore issue or unknown critical options */
4906 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4907 packet_is_bad = 1;
4908 if (COAP_PDU_IS_REQUEST(pdu)) {
4909 response =
4910 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4911
4912 if (!response) {
4913 coap_log_warn("coap_dispatch: cannot create error response\n");
4914 } else {
4915 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4916 coap_log_warn("coap_dispatch: error sending response\n");
4917 }
4918 } else {
4919 coap_send_rst_lkd(session, pdu);
4920 }
4921 goto cleanup;
4922 }
4923 break;
4924
4925 case COAP_MESSAGE_CON:
4926 /* In a lossy context, the ACK of a separate response may have
4927 * been lost, so we need to stop retransmitting requests with the
4928 * same token. Matching on token potentially containing ext length bytes.
4929 */
4930 /* find message token in sendqueue to stop retransmission */
4931 if (pdu->code != 0)
4932 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4933
4934 /* check for oscore issue or unknown critical options in non-signaling messages */
4935 if (oscore_invalid ||
4936 (!COAP_PDU_IS_SIGNALING(pdu) && coap_option_check_critical(session, pdu, &opt_filter) == 0)) {
4937 packet_is_bad = 1;
4938 if (COAP_PDU_IS_REQUEST(pdu)) {
4939 response =
4940 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4941
4942 if (!response) {
4943 coap_log_warn("coap_dispatch: cannot create error response\n");
4944 } else {
4945 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4946 coap_log_warn("coap_dispatch: error sending response\n");
4947 }
4948 } else {
4949 coap_send_rst_lkd(session, pdu);
4950 }
4951 goto cleanup;
4952 }
4953 break;
4954 default:
4955 break;
4956 }
4957
4958 /* Pass message to upper layer if a specific handler was
4959 * registered for a request that should be handled locally. */
4960#if !COAP_DISABLE_TCP
4961 if (COAP_PDU_IS_SIGNALING(pdu))
4962 handle_signaling(context, session, pdu);
4963 else
4964#endif /* !COAP_DISABLE_TCP */
4965#if COAP_SERVER_SUPPORT
4966 if (COAP_PDU_IS_REQUEST(pdu))
4967 handle_request(context, session, pdu, orig_pdu);
4968 else
4969#endif /* COAP_SERVER_SUPPORT */
4970#if COAP_CLIENT_SUPPORT
4971 if (COAP_PDU_IS_RESPONSE(pdu))
4972 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4973 else
4974#endif /* COAP_CLIENT_SUPPORT */
4975 {
4976 if (COAP_PDU_IS_EMPTY(pdu)) {
4977 if (context->ping_cb) {
4978 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4979 }
4980 } else {
4981 packet_is_bad = 1;
4982 }
4983 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4985 pdu->code & 0x1f);
4986
4987 if (!coap_is_mcast(&session->addr_info.local)) {
4988 if (COAP_PDU_IS_EMPTY(pdu)) {
4989 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4990 coap_tick_t now;
4991 coap_ticks(&now);
4992 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4994 session->last_tx_rst = now;
4995 }
4996 }
4997 } else {
4998 if (pdu->type == COAP_MESSAGE_CON)
5000 }
5001 }
5002 }
5003
5004cleanup:
5005 if (packet_is_bad) {
5006 if (sent) {
5007 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
5008 } else {
5010 }
5011 }
5012 coap_delete_pdu_lkd(orig_pdu);
5014#if COAP_OSCORE_SUPPORT
5015 coap_delete_pdu_lkd(dec_pdu);
5016#endif /* COAP_OSCORE_SUPPORT */
5017}
5018
5019#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
5020static const char *
5022 switch (event) {
5024 return "COAP_EVENT_DTLS_CLOSED";
5026 return "COAP_EVENT_DTLS_CONNECTED";
5028 return "COAP_EVENT_DTLS_RENEGOTIATE";
5030 return "COAP_EVENT_DTLS_ERROR";
5032 return "COAP_EVENT_TCP_CONNECTED";
5034 return "COAP_EVENT_TCP_CLOSED";
5036 return "COAP_EVENT_TCP_FAILED";
5038 return "COAP_EVENT_SESSION_CONNECTED";
5040 return "COAP_EVENT_SESSION_CLOSED";
5042 return "COAP_EVENT_SESSION_FAILED";
5044 return "COAP_EVENT_PARTIAL_BLOCK";
5046 return "COAP_EVENT_XMIT_BLOCK_FAIL";
5048 return "COAP_EVENT_BLOCK_ISSUE";
5050 return "COAP_EVENT_SERVER_SESSION_NEW";
5052 return "COAP_EVENT_SERVER_SESSION_DEL";
5054 return "COAP_EVENT_SERVER_SESSION_CONNECTED";
5056 return "COAP_EVENT_BAD_PACKET";
5058 return "COAP_EVENT_MSG_RETRANSMITTED";
5060 return "COAP_EVENT_FIRST_PDU_FAIL";
5062 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
5064 return "COAP_EVENT_OSCORE_NOT_ENABLED";
5066 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
5068 return "COAP_EVENT_OSCORE_NO_SECURITY";
5070 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
5072 return "COAP_EVENT_OSCORE_DECODE_ERROR";
5074 return "COAP_EVENT_WS_PACKET_SIZE";
5076 return "COAP_EVENT_WS_CONNECTED";
5078 return "COAP_EVENT_WS_CLOSED";
5080 return "COAP_EVENT_KEEPALIVE_FAILURE";
5082 return "COAP_EVENT_RECONNECT_FAILED";
5084 return "COAP_EVENT_RECONNECT_SUCCESS";
5086 return "COAP_EVENT_RECONNECT_NO_MORE";
5088 return "COAP_EVENT_RECONNECT_STARTED";
5089 default:
5090 return "???";
5091 }
5092}
5093#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
5094
5095COAP_API int
5097 coap_session_t *session) {
5098 int ret;
5099
5100 coap_lock_lock(return 0);
5101 ret = coap_handle_event_lkd(context, event, session);
5103 return ret;
5104}
5105
5106int
5108 coap_session_t *session) {
5109 int ret = 0;
5110
5111 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
5112
5113 if (context->event_cb) {
5114 coap_lock_callback_ret(ret, context->event_cb(session, event));
5115#if COAP_PROXY_SUPPORT
5116 if (event == COAP_EVENT_SERVER_SESSION_DEL)
5117 coap_proxy_remove_association(session, 0);
5118#endif /* COAP_PROXY_SUPPORT */
5119#if COAP_CLIENT_SUPPORT
5120 switch (event) {
5135 /* Those that are deemed fatal to end sending a request */
5136 session->doing_send_recv = 0;
5137 break;
5139 /* Session will now be available as well - for call-home */
5140 if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
5142 session);
5143 }
5144 break;
5150 break;
5152 /* Session will now be available as well - for call-home if not (D)TLS */
5153 if (session->type == COAP_SESSION_TYPE_SERVER &&
5154 (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
5156 session);
5157 }
5158 break;
5163 break;
5165 /* Session will now be available as well - for call-home if not (D)TLS */
5166 if (session->proto == COAP_PROTO_UDP) {
5168 session);
5169 }
5170 break;
5178 default:
5179 break;
5180 }
5181#endif /* COAP_CLIENT_SUPPORT */
5182 }
5183 return ret;
5184}
5185
5186COAP_API int
5188 int ret;
5189
5190 coap_lock_lock(return 0);
5191 ret = coap_can_exit_lkd(context);
5193 return ret;
5194}
5195
5196int
5198 coap_session_t *s, *rtmp;
5199 if (!context)
5200 return 1;
5202 if (context->sendqueue)
5203 return 0;
5204#if COAP_SERVER_SUPPORT
5205 coap_endpoint_t *ep;
5206
5207 LL_FOREACH(context->endpoint, ep) {
5208 SESSIONS_ITER(ep->sessions, s, rtmp) {
5209 if (s->delayqueue)
5210 return 0;
5211 if (s->lg_xmit)
5212 return 0;
5213 }
5214 }
5215#endif /* COAP_SERVER_SUPPORT */
5216#if COAP_CLIENT_SUPPORT
5217 SESSIONS_ITER(context->sessions, s, rtmp) {
5218 if (s->delayqueue)
5219 return 0;
5220 if (s->lg_xmit)
5221 return 0;
5222 }
5223#endif /* COAP_CLIENT_SUPPORT */
5224 return 1;
5225}
5226#if COAP_SERVER_SUPPORT
5227#if COAP_ASYNC_SUPPORT
5228/*
5229 * Return 1 if there is a future expire time, else 0.
5230 * Update tim_rem with remaining value if return is 1.
5231 */
5232int
5233coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5235 coap_async_t *async, *tmp;
5236 int ret = 0;
5237
5238 if (context->async_state_traversing)
5239 return 0;
5240 context->async_state_traversing = 1;
5241 LL_FOREACH_SAFE(context->async_state, async, tmp) {
5242 if (async->delay != 0 && !async->session->is_rate_limiting) {
5243 if (async->delay <= now) {
5244 /* Send off the request to the application */
5245 coap_log_debug("Async PDU presented to app.\n");
5246 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5247 handle_request(context, async->session, async->pdu, NULL);
5248
5249 /* Remove this async entry as it has now fired */
5250 coap_free_async_lkd(async->session, async);
5251 } else {
5252 next_due = async->delay - now;
5253 ret = 1;
5254 }
5255 }
5256 }
5257 if (tim_rem)
5258 *tim_rem = next_due;
5259 context->async_state_traversing = 0;
5260 return ret;
5261}
5262#endif /* COAP_ASYNC_SUPPORT */
5263#endif /* COAP_SERVER_SUPPORT */
5264
5266uint8_t coap_unique_id[8] = { 0 };
5267
5268#if COAP_THREAD_SAFE
5269/*
5270 * Global lock for multi-thread support
5271 */
5272coap_lock_t global_lock;
5273/*
5274 * low level protection mutex
5275 */
5276coap_mutex_t m_show_pdu;
5277coap_mutex_t m_log_impl;
5278coap_mutex_t m_io_threads;
5279#endif /* COAP_THREAD_SAFE */
5280
5281void
5283 coap_tick_t now;
5284#ifndef WITH_CONTIKI
5285 uint64_t us;
5286#endif /* !WITH_CONTIKI */
5287
5288 if (coap_started)
5289 return;
5290 coap_started = 1;
5291
5292#if COAP_THREAD_SAFE
5293 coap_lock_init(&global_lock);
5294 coap_mutex_init(&m_show_pdu);
5295 coap_mutex_init(&m_log_impl);
5296 coap_mutex_init(&m_io_threads);
5297#endif /* COAP_THREAD_SAFE */
5298
5299#if defined(HAVE_WINSOCK2_H)
5300 WORD wVersionRequested = MAKEWORD(2, 2);
5301 WSADATA wsaData;
5302 WSAStartup(wVersionRequested, &wsaData);
5303#endif
5305 coap_ticks(&now);
5306#ifndef WITH_CONTIKI
5307 us = coap_ticks_to_rt_us(now);
5308 /* Be accurate to the nearest (approx) us */
5309 coap_prng_init_lkd((unsigned int)us);
5310#else /* WITH_CONTIKI */
5311 coap_start_io_process();
5312#endif /* WITH_CONTIKI */
5315#ifdef WITH_LWIP
5316 coap_io_lwip_init();
5317#endif /* WITH_LWIP */
5318#if COAP_SERVER_SUPPORT
5319 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5320 (const uint8_t *)".well-known/core"
5321 };
5322 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5323 resource_uri_wellknown.ref = 1;
5324 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5325 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5326 resource_uri_wellknown.uri_path = &well_known;
5327#endif /* COAP_SERVER_SUPPORT */
5330}
5331
5332void
5334 if (!coap_started)
5335 return;
5336 coap_started = 0;
5337#if defined(HAVE_WINSOCK2_H)
5338 WSACleanup();
5339#elif defined(WITH_CONTIKI)
5340 coap_stop_io_process();
5341#endif
5342#ifdef WITH_LWIP
5343 coap_io_lwip_cleanup();
5344#endif /* WITH_LWIP */
5346
5351#if COAP_THREAD_SAFE
5352 coap_mutex_destroy(&m_show_pdu);
5353 coap_mutex_destroy(&m_log_impl);
5354 coap_mutex_destroy(&m_io_threads);
5355#endif /* COAP_THREAD_SAFE */
5356
5358}
5359
5360void
5362 coap_response_handler_t handler) {
5363#if COAP_CLIENT_SUPPORT
5364 context->response_cb = handler;
5365#else /* ! COAP_CLIENT_SUPPORT */
5366 (void)context;
5367 (void)handler;
5368#endif /* ! COAP_CLIENT_SUPPORT */
5369}
5370
5371void
5374#if COAP_PROXY_SUPPORT
5375 context->proxy_response_cb = handler;
5376#else /* ! COAP_PROXY_SUPPORT */
5377 (void)context;
5378 (void)handler;
5379#endif /* ! COAP_PROXY_SUPPORT */
5380}
5381
5382void
5384 coap_nack_handler_t handler) {
5385 context->nack_cb = handler;
5386}
5387
5388void
5390 coap_ping_handler_t handler) {
5391 context->ping_cb = handler;
5392}
5393
5394void
5396 coap_pong_handler_t handler) {
5397 context->pong_cb = handler;
5398}
5399
5400void
5402 coap_resource_dynamic_create_t dyn_create_handler,
5403 uint32_t dynamic_max) {
5404 context->dyn_create_handler = dyn_create_handler;
5405 context->dynamic_max = dynamic_max;
5406 return;
5407}
5408
5409COAP_API void
5411 coap_lock_lock(return);
5412 coap_register_option_lkd(ctx, type);
5414}
5415
5416void
5419}
5420
5421#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5422#if COAP_SERVER_SUPPORT
5423COAP_API int
5424coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5425 const char *ifname) {
5426 int ret;
5427
5428 coap_lock_lock(return -1);
5429 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
5431 return ret;
5432}
5433
5434int
5435coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
5436 const char *ifname) {
5437#if COAP_IPV4_SUPPORT
5438 struct ip_mreq mreq4;
5439#endif /* COAP_IPV4_SUPPORT */
5440#if COAP_IPV6_SUPPORT
5441 struct ipv6_mreq mreq6;
5442#endif /* COAP_IPV6_SUPPORT */
5443 struct addrinfo *resmulti = NULL, hints, *ainfo;
5444 int result = -1;
5445 coap_endpoint_t *endpoint;
5446 int mgroup_setup = 0;
5447
5448 /* Need to have at least one endpoint! */
5449 assert(ctx->endpoint);
5450 if (!ctx->endpoint)
5451 return -1;
5452
5453 /* Default is let the kernel choose */
5454#if COAP_IPV6_SUPPORT
5455 mreq6.ipv6mr_interface = 0;
5456#endif /* COAP_IPV6_SUPPORT */
5457#if COAP_IPV4_SUPPORT
5458 mreq4.imr_interface.s_addr = INADDR_ANY;
5459#endif /* COAP_IPV4_SUPPORT */
5460
5461 memset(&hints, 0, sizeof(hints));
5462 hints.ai_socktype = SOCK_DGRAM;
5463
5464 /* resolve the multicast group address */
5465 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5466
5467 if (result != 0) {
5468 coap_log_err("coap_join_mcast_group_intf: %s: "
5469 "Cannot resolve multicast address: %s\n",
5470 group_name, gai_strerror(result));
5471 goto finish;
5472 }
5473
5474 /* Need to do a windows equivalent at some point */
5475#ifndef _WIN32
5476 if (ifname) {
5477 /* interface specified - check if we have correct IPv4/IPv6 information */
5478 int done_ip4 = 0;
5479 int done_ip6 = 0;
5480#if defined(ESPIDF_VERSION)
5481 struct netif *netif;
5482#else /* !ESPIDF_VERSION */
5483#if COAP_IPV4_SUPPORT
5484 int ip4fd;
5485#endif /* COAP_IPV4_SUPPORT */
5486 struct ifreq ifr;
5487#endif /* !ESPIDF_VERSION */
5488
5489 /* See which mcast address family types are being asked for */
5490 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5491 ainfo = ainfo->ai_next) {
5492 switch (ainfo->ai_family) {
5493#if COAP_IPV6_SUPPORT
5494 case AF_INET6:
5495 if (done_ip6)
5496 break;
5497 done_ip6 = 1;
5498#if defined(ESPIDF_VERSION)
5499 netif = netif_find(ifname);
5500 if (netif)
5501 mreq6.ipv6mr_interface = netif_get_index(netif);
5502 else
5503 coap_log_err("coap_join_mcast_group_intf: %s: "
5504 "Cannot get IPv4 address: %s\n",
5505 ifname, coap_socket_strerror());
5506#else /* !ESPIDF_VERSION */
5507 memset(&ifr, 0, sizeof(ifr));
5508 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5509 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5510
5511#ifdef HAVE_IF_NAMETOINDEX
5512 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5513 if (mreq6.ipv6mr_interface == 0) {
5514 coap_log_warn("coap_join_mcast_group_intf: "
5515 "cannot get interface index for '%s'\n",
5516 ifname);
5517 }
5518#elif defined(__QNXNTO__)
5519#else /* !HAVE_IF_NAMETOINDEX */
5520 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5521 if (result != 0) {
5522 coap_log_warn("coap_join_mcast_group_intf: "
5523 "cannot get interface index for '%s': %s\n",
5524 ifname, coap_socket_strerror());
5525 } else {
5526 /* Capture the IPv6 if_index for later */
5527 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5528 }
5529#endif /* !HAVE_IF_NAMETOINDEX */
5530#endif /* !ESPIDF_VERSION */
5531#endif /* COAP_IPV6_SUPPORT */
5532 break;
5533#if COAP_IPV4_SUPPORT
5534 case AF_INET:
5535 if (done_ip4)
5536 break;
5537 done_ip4 = 1;
5538#if defined(ESPIDF_VERSION)
5539 netif = netif_find(ifname);
5540 if (netif)
5541 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5542 else
5543 coap_log_err("coap_join_mcast_group_intf: %s: "
5544 "Cannot get IPv4 address: %s\n",
5545 ifname, coap_socket_strerror());
5546#else /* !ESPIDF_VERSION */
5547 /*
5548 * Need an AF_INET socket to do this unfortunately to stop
5549 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5550 */
5551 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5552 if (ip4fd == -1) {
5553 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5554 ifname, coap_socket_strerror());
5555 continue;
5556 }
5557 memset(&ifr, 0, sizeof(ifr));
5558 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5559 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5560 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5561 if (result != 0) {
5562 coap_log_err("coap_join_mcast_group_intf: %s: "
5563 "Cannot get IPv4 address: %s\n",
5564 ifname, coap_socket_strerror());
5565 } else {
5566 /* Capture the IPv4 address for later */
5567 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5568 }
5569 close(ip4fd);
5570#endif /* !ESPIDF_VERSION */
5571 break;
5572#endif /* COAP_IPV4_SUPPORT */
5573 default:
5574 break;
5575 }
5576 }
5577 }
5578#else /* _WIN32 */
5579 /*
5580 * On Windows this function ignores the ifname variable so we unset this
5581 * variable on this platform in any case in order to enable the interface
5582 * selection from the bind address below.
5583 */
5584 ifname = 0;
5585#endif /* _WIN32 */
5586
5587 /* Add in mcast address(es) to appropriate interface */
5588 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5589 LL_FOREACH(ctx->endpoint, endpoint) {
5590 /* Only UDP currently supported */
5591 if (endpoint->proto == COAP_PROTO_UDP) {
5592 coap_address_t gaddr;
5593
5594 coap_address_init(&gaddr);
5595#if COAP_IPV6_SUPPORT
5596 if (ainfo->ai_family == AF_INET6) {
5597 if (!ifname) {
5598 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5599 /*
5600 * Do it on the ifindex that the server is listening on
5601 * (sin6_scope_id could still be 0)
5602 */
5603 mreq6.ipv6mr_interface =
5604 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5605 } else {
5606 mreq6.ipv6mr_interface = 0;
5607 }
5608 }
5609 gaddr.addr.sin6.sin6_family = AF_INET6;
5610 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5611 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5612 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5613 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5614 (char *)&mreq6, sizeof(mreq6));
5615 }
5616#endif /* COAP_IPV6_SUPPORT */
5617#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5618 else
5619#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5620#if COAP_IPV4_SUPPORT
5621 if (ainfo->ai_family == AF_INET) {
5622 if (!ifname) {
5623 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5624 /*
5625 * Do it on the interface that the server is listening on
5626 * (sin_addr could still be INADDR_ANY)
5627 */
5628 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5629 } else {
5630 mreq4.imr_interface.s_addr = INADDR_ANY;
5631 }
5632 }
5633 gaddr.addr.sin.sin_family = AF_INET;
5634 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5635 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5636 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5637 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5638 (char *)&mreq4, sizeof(mreq4));
5639 }
5640#endif /* COAP_IPV4_SUPPORT */
5641 else {
5642 continue;
5643 }
5644
5645 if (result == COAP_SOCKET_ERROR) {
5646 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5647 group_name, coap_socket_strerror());
5648 } else {
5649 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5650
5651 addr_str[sizeof(addr_str)-1] = '\000';
5652 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5653 sizeof(addr_str) - 1)) {
5654 if (ifname)
5655 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5656 ifname);
5657 else
5658 coap_log_debug("added mcast group %s\n", addr_str);
5659 }
5660 mgroup_setup = 1;
5661 }
5662 }
5663 }
5664 }
5665 if (!mgroup_setup) {
5666 result = -1;
5667 }
5668
5669finish:
5670 freeaddrinfo(resmulti);
5671
5672 return result;
5673}
5674
5675void
5677 context->mcast_per_resource = 1;
5678}
5679
5680#endif /* ! COAP_SERVER_SUPPORT */
5681
5682#if COAP_CLIENT_SUPPORT
5683int
5684coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5685 if (session && coap_is_mcast(&session->addr_info.remote)) {
5686 switch (session->addr_info.remote.addr.sa.sa_family) {
5687#if COAP_IPV4_SUPPORT
5688 case AF_INET:
5689 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5690 (const char *)&hops, sizeof(hops)) < 0) {
5691 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5692 hops, coap_socket_strerror());
5693 return 0;
5694 }
5695 return 1;
5696#endif /* COAP_IPV4_SUPPORT */
5697#if COAP_IPV6_SUPPORT
5698 case AF_INET6:
5699 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5700 (const char *)&hops, sizeof(hops)) < 0) {
5701 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5702 hops, coap_socket_strerror());
5703 return 0;
5704 }
5705 return 1;
5706#endif /* COAP_IPV6_SUPPORT */
5707 default:
5708 break;
5709 }
5710 }
5711 return 0;
5712}
5713#endif /* COAP_CLIENT_SUPPORT */
5714
5715#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
5716COAP_API int
5718 const char *group_name COAP_UNUSED,
5719 const char *ifname COAP_UNUSED) {
5720 return -1;
5721}
5722
5723int
5725 size_t hops COAP_UNUSED) {
5726 return 0;
5727}
5728
5729void
5731}
5732#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:748
void coap_memory_init(void)
Initializes libcoap's memory management.
@ COAP_NODE
Definition coap_mem.h:37
@ COAP_CONTEXT
Definition coap_mem.h:38
@ COAP_STRING
Definition coap_mem.h:33
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
CoAP mutex mechanism wrapper.
#define coap_mutex_init(a)
int coap_mutex_t
#define coap_mutex_destroy(a)
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition coap_net.c:83
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition coap_net.c:1148
static int send_recv_terminate
Definition coap_net.c:2218
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:3126
#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:5333
#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:5021
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:3442
int coap_started
Definition coap_net.c:5265
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2503
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2544
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:4431
#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:1919
void coap_startup(void)
Definition coap_net.c:5282
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4509
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:5266
#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:2912
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:1105
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:1229
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:1200
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:2842
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:2247
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:1509
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:1120
#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:2901
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:2835
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:5107
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:5417
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:3078
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:1377
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:4542
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:1257
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:2029
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:5197
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2365
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:1444
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:1283
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:3185
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:3017
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:3224
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:2226
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:1499
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:1187
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:2221
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:5361
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:3257
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:5401
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:1110
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:5389
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:1218
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:1095
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:5187
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:5410
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:5395
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:5096
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:5383
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_ALL
Pre-defined filter that includes all options.
void coap_option_filter_clear(coap_opt_filter_t *filter)
Clears filter filter.
coap_opt_t * coap_check_option(const coap_pdu_t *pdu, coap_option_num_t number, coap_opt_iterator_t *oi)
Retrieves the first option of number number from pdu.
const uint8_t * coap_opt_value(const coap_opt_t *opt)
Returns a pointer to the value of the given option.
int coap_option_filter_get(coap_opt_filter_t *filter, coap_option_num_t option)
Checks if number is contained in filter.
int coap_option_filter_set(coap_opt_filter_t *filter, coap_option_num_t option)
Sets the corresponding entry for number in filter.
coap_pdu_t * coap_oscore_new_pdu_encrypted_lkd(coap_session_t *session, coap_pdu_t *pdu, coap_bin_const_t *kid_context, oscore_partial_iv_t send_partial_iv)
Encrypts the specified pdu when OSCORE encryption is required on session.
struct coap_pdu_t * coap_oscore_decrypt_pdu(coap_session_t *session, coap_pdu_t *pdu)
Decrypts the OSCORE-encrypted parts of pdu when OSCORE is used.
int coap_rebuild_pdu_for_proxy(coap_pdu_t *pdu)
Convert PDU to use Proxy-Scheme option if Proxy-Uri option is present.
void coap_delete_all_oscore(coap_context_t *context)
Cleanup all allocated OSCORE information.
#define COAP_PDU_IS_RESPONSE(pdu)
coap_pdu_t * coap_pdu_reference_lkd(coap_pdu_t *pdu)
Increment reference counter on a pdu to stop it prematurely getting freed off when coap_delete_pdu() ...
Definition coap_pdu.c:1711
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:194
#define COAP_TOKEN_EXT_2B_TKL
size_t coap_insert_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Inserts option of given number in the pdu with the appropriate data.
Definition coap_pdu.c:683
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:542
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:1407
#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:1133
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:1049
#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:636
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:234
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:782
#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:1573
#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:1549
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:1080
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:337
#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:838
#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:1009
#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:409
#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:934
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:1539
#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:903
@ 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_REQUEST_CODE_PUT
Definition coap_pdu.h:336
@ COAP_REQUEST_CODE_POST
Definition coap_pdu.h:335
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:370
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:371
@ COAP_REQUEST_CODE_DELETE
Definition coap_pdu.h:337
@ COAP_SIGNALING_CODE_PONG
Definition coap_pdu.h:372
@ COAP_EMPTY_CODE
Definition coap_pdu.h:332
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:334
@ COAP_SIGNALING_CODE_RELEASE
Definition coap_pdu.h:373
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:338
@ COAP_MESSAGE_NON
Definition coap_pdu.h: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:5372
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:2574
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:1135
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.
uint32_t dynamic_cur
Current number of dynamic resources.
coap_app_data_free_callback_t app_cb
call-back to release app_data
coap_pong_handler_t pong_cb
Called when a ping response is received.
coap_nack_handler_t nack_cb
Called when a response issue has occurred.
coap_resource_dynamic_create_t dyn_create_handler
Dynamc resource create handler.
uint32_t max_body_size
Max supported body size or 0 is unlimited.
void * app_data
application-specific data
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
uint32_t dynamic_max
Max number of dynamic resources or 0 is unlimited.
coap_event_handler_t event_cb
Callback function that is used to signal events to the application.
coap_opt_filter_t known_options
uint32_t csm_max_message_size
Value for CSM Max-Message-Size.
unsigned int max_handshake_sessions
Maximum number of simultaneous negotating sessions per endpoint.
coap_ping_handler_t ping_cb
Called when a CoAP ping is received.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
uint32_t csm_timeout_ms
Timeout for waiting for a CSM from the remote side.
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
coap_bin_const_t key
Definition coap_dtls.h:385
coap_bin_const_t identity
Definition coap_dtls.h:384
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:447
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:316
uint8_t version
Definition coap_dtls.h:317
coap_bin_const_t hint
Definition coap_dtls.h:455
coap_bin_const_t key
Definition coap_dtls.h:456
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:505
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:537
uint64_t state_token
state token
uint32_t count
the number of packets sent for payload
coap_binary_t * app_token
original PDU token
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
Structure to hold large body (many blocks) transmission information.
coap_tick_t last_all_sent
Last time all data sent or 0.
uint8_t blk_size
large block transmission size
union coap_lg_xmit_t::@1 b
int last_block
last acknowledged block number Block1 last transmitted Q-Block2
coap_pdu_t * sent_pdu
The sent pdu with all the data.
coap_l_block1_t b1
uint16_t option
large block transmisson CoAP option
Iterator to run through PDU options.
coap_option_num_t number
decoded option number
size_t length
length of payload
coap_addr_tuple_t addr_info
local and remote addresses
unsigned char * payload
payload
structure for CoAP PDUs
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
coap_pdu_code_t code
request method (value 1–31) or response code (value 64-255)
uint8_t hdr_size
actual size used for protocol-specific header (0 until header is encoded)
coap_bin_const_t actual_token
Actual token in pdu.
uint8_t * data
first byte of payload, if any
coap_mid_t mid
message id, if any, in regular host byte order
uint32_t e_token_length
length of Token space (includes leading extended bytes
size_t used_size
used bytes of storage for token, options and payload
uint8_t crit_opt
Set if unknown critical option for proxy.
coap_binary_t * data_free
Data to be freed off by coap_delete_pdu()
size_t alloc_size
allocated storage for token, options and payload
coap_session_t * session
Session responsible for PDU or NULL.
coap_pdu_type_t type
message type
Queue entry.
coap_address_t remote
For re-transmission - where the node is going.
coap_session_t * session
the CoAP session
coap_pdu_t * pdu
the CoAP PDU to send
unsigned int timeout
the randomized timeout value
uint8_t is_mcast
Set if this is a queued mcast response.
struct coap_queue_t * next
coap_mid_t id
CoAP message id.
coap_tick_t t
when to send PDU for the next time
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
volatile uint8_t max_token_checked
Check for max token size coap_ext_token_check_t.
uint8_t csm_not_seen
Set if timeout waiting for CSM.
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
uint8_t delay_recursive
Set if in coap_client_delay_first()
coap_socket_t sock
socket object for the session, if any
coap_pdu_t * partial_pdu
incomplete incoming pdu
uint32_t max_token_size
Largest token size supported RFC8974.
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