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