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