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