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