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