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