libcoap 4.3.5-develop-f52fada
Loading...
Searching...
No Matches
coap_net.c
Go to the documentation of this file.
1/* coap_net.c -- CoAP context inteface
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 uint32_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_token_size) {
493 assert(max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
494 max_token_size <= COAP_TOKEN_EXT_MAX);
495 if (max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
496 max_token_size <= COAP_TOKEN_EXT_MAX) {
497 context->max_token_size = (uint32_t)max_token_size;
498 }
499}
500
501void
503 unsigned int max_idle_sessions) {
504 context->max_idle_sessions = max_idle_sessions;
505}
506
507unsigned int
509 return context->max_idle_sessions;
510}
511
512void
514 unsigned int max_handshake_sessions) {
515 context->max_handshake_sessions = max_handshake_sessions;
516}
517
518unsigned int
522
523static unsigned int s_csm_timeout = 30;
524
525void
527 unsigned int csm_timeout) {
528 s_csm_timeout = csm_timeout;
529 coap_context_set_csm_timeout_ms(context, csm_timeout * 1000);
530}
531
532unsigned int
534 (void)context;
535 return s_csm_timeout;
536}
537
538void
540 unsigned int csm_timeout_ms) {
541 if (csm_timeout_ms < 10)
542 csm_timeout_ms = 10;
543 if (csm_timeout_ms > 10000)
544 csm_timeout_ms = 10000;
545 context->csm_timeout_ms = csm_timeout_ms;
546}
547
548unsigned int
550 return context->csm_timeout_ms;
551}
552
553void
555 uint32_t csm_max_message_size) {
556 assert(csm_max_message_size >= 64);
557 if (csm_max_message_size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
558 csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
559 coap_log_debug("Restricting CSM Max-Message-Size size to %" PRIu32 "\n",
560 csm_max_message_size);
561 }
562
563 context->csm_max_message_size = csm_max_message_size;
564}
565
566uint32_t
570
571void
573 unsigned int session_timeout) {
574 context->session_timeout = session_timeout;
575}
576
577void
579 unsigned int reconnect_time) {
580 coap_context_set_session_reconnect_time2(context, reconnect_time, 0);
581}
582
583void
585 unsigned int reconnect_time,
586 uint8_t retry_count) {
587#if COAP_CLIENT_SUPPORT
588 context->reconnect_time = reconnect_time;
589 context->retry_count = retry_count;
590#else /* ! COAP_CLIENT_SUPPORT */
591 (void)context;
592 (void)reconnect_time;
593 (void)retry_count;
594#endif /* ! COAP_CLIENT_SUPPORT */
595}
596
597unsigned int
599 return context->session_timeout;
600}
601
602void
604#if COAP_SERVER_SUPPORT
605 context->shutdown_no_send_observe = 1;
606#else /* ! COAP_SERVER_SUPPORT */
607 (void)context;
608#endif /* ! COAP_SERVER_SUPPORT */
609}
610
611int
613#if COAP_EPOLL_SUPPORT
614 return context->epfd;
615#else /* ! COAP_EPOLL_SUPPORT */
616 (void)context;
617 return -1;
618#endif /* ! COAP_EPOLL_SUPPORT */
619}
620
621int
623#if COAP_EPOLL_SUPPORT
624 return 1;
625#else /* ! COAP_EPOLL_SUPPORT */
626 return 0;
627#endif /* ! COAP_EPOLL_SUPPORT */
628}
629
630int
632#if COAP_THREAD_SAFE
633 return 1;
634#else /* ! COAP_THREAD_SAFE */
635 return 0;
636#endif /* ! COAP_THREAD_SAFE */
637}
638
639int
641#if COAP_IPV4_SUPPORT
642 return 1;
643#else /* ! COAP_IPV4_SUPPORT */
644 return 0;
645#endif /* ! COAP_IPV4_SUPPORT */
646}
647
648int
650#if COAP_IPV6_SUPPORT
651 return 1;
652#else /* ! COAP_IPV6_SUPPORT */
653 return 0;
654#endif /* ! COAP_IPV6_SUPPORT */
655}
656
657int
659#if COAP_CLIENT_SUPPORT
660 return 1;
661#else /* ! COAP_CLIENT_SUPPORT */
662 return 0;
663#endif /* ! COAP_CLIENT_SUPPORT */
664}
665
666int
668#if COAP_SERVER_SUPPORT
669 return 1;
670#else /* ! COAP_SERVER_SUPPORT */
671 return 0;
672#endif /* ! COAP_SERVER_SUPPORT */
673}
674
675int
677#if COAP_AF_UNIX_SUPPORT
678 return 1;
679#else /* ! COAP_AF_UNIX_SUPPORT */
680 return 0;
681#endif /* ! COAP_AF_UNIX_SUPPORT */
682}
683
684COAP_API void
685coap_context_set_app_data(coap_context_t *context, void *app_data) {
686 assert(context);
687 coap_lock_lock(return);
688 coap_context_set_app_data2_lkd(context, app_data, NULL);
690}
691
692void *
694 assert(context);
695 return context->app_data;
696}
697
698COAP_API void *
701 void *old_data;
702
703 coap_lock_lock(return NULL);
704 old_data = coap_context_set_app_data2_lkd(context, app_data, callback);
706 return old_data;
707}
708
709void *
712 void *old_data = context->app_data;
713
714 context->app_data = app_data;
715 context->app_cb = app_data ? callback : NULL;
716 return old_data;
717}
718
720coap_new_context(const coap_address_t *listen_addr) {
722
723#if ! COAP_SERVER_SUPPORT
724 (void)listen_addr;
725#endif /* COAP_SERVER_SUPPORT */
726
727 if (!coap_started) {
728 coap_startup();
729 coap_log_warn("coap_startup() should be called before any other "
730 "coap_*() functions are called\n");
731 }
732
734 if (!c) {
735 coap_log_emerg("coap_init: malloc: failed\n");
736 return NULL;
737 }
738 memset(c, 0, sizeof(coap_context_t));
739
741#ifdef COAP_EPOLL_SUPPORT
742 c->epfd = epoll_create1(0);
743 if (c->epfd == -1) {
744 coap_log_err("coap_new_context: Unable to epoll_create: %s (%d)\n",
746 errno);
747 goto onerror;
748 }
749 if (c->epfd != -1) {
750 c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
751 if (c->eptimerfd == -1) {
752 coap_log_err("coap_new_context: Unable to timerfd_create: %s (%d)\n",
754 errno);
755 goto onerror;
756 } else {
757 int ret;
758 struct epoll_event event;
759
760 /* Needed if running 32bit as ptr is only 32bit */
761 memset(&event, 0, sizeof(event));
762 event.events = EPOLLIN;
763 /* We special case this event by setting to NULL */
764 event.data.ptr = NULL;
765
766 ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
767 if (ret == -1) {
768 coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
769 "coap_new_context",
770 coap_socket_strerror(), errno);
771 goto onerror;
772 }
773 }
774 }
775#endif /* COAP_EPOLL_SUPPORT */
776
779 if (!c->dtls_context) {
780 coap_log_emerg("coap_init: no DTLS context available\n");
781 goto onerror;
782 }
783 }
784
785 /* set default CSM values */
786 c->csm_timeout_ms = 1000;
788
789#if COAP_SERVER_SUPPORT
790 if (listen_addr) {
791 coap_endpoint_t *endpoint = coap_new_endpoint_lkd(c, listen_addr, COAP_PROTO_UDP);
792 if (endpoint == NULL) {
793 goto onerror;
794 }
795 }
796#endif /* COAP_SERVER_SUPPORT */
797
798 c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
799
800#if defined(WITH_LWIP)
801#if NO_SYS == 0
802 if (sys_sem_new(&c->coap_io_timeout_sem, 0) != ERR_OK)
803 coap_log_warn("coap_new_context: Failed to set up semaphore\n");
804#endif /* NO_SYS == 0 */
805#endif /* ! WITH_LWIP */
807 return c;
808
809onerror:
812 return NULL;
813}
814
815COAP_API void
816coap_set_app_data(coap_context_t *context, void *app_data) {
817 assert(context);
818 coap_lock_lock(return);
819 coap_context_set_app_data2_lkd(context, app_data, NULL);
821}
822
823void *
825 assert(ctx);
826 return ctx->app_data;
827}
828
829COAP_API void
831 if (!context)
832 return;
833 coap_lock_lock(return);
834 coap_free_context_lkd(context);
836}
837
838void
840 if (!context)
841 return;
842
844#if COAP_SERVER_SUPPORT
845 /* Removing a resource may cause a NON unsolicited observe to be sent */
846 context->context_going_away = 1;
847 if (context->shutdown_no_send_observe)
848 context->observe_no_clear = 1;
849 coap_delete_all_resources(context);
850#endif /* COAP_SERVER_SUPPORT */
851#if COAP_CLIENT_SUPPORT
852 /* Stop any attempts at reconnection */
853 context->reconnect_time = 0;
854#endif /* COAP_CLIENT_SUPPORT */
855
856 coap_delete_all(context->sendqueue);
857 context->sendqueue = NULL;
858
859#ifdef WITH_LWIP
860 if (context->timer_configured) {
861 LOCK_TCPIP_CORE();
862 sys_untimeout(coap_io_process_timeout, (void *)context);
863 UNLOCK_TCPIP_CORE();
864 context->timer_configured = 0;
865 }
866#endif /* WITH_LWIP */
867
868#if COAP_ASYNC_SUPPORT
869 coap_delete_all_async(context);
870#endif /* COAP_ASYNC_SUPPORT */
871
872#if COAP_SERVER_SUPPORT
873 coap_cache_entry_t *cp, *ctmp;
874 coap_endpoint_t *ep, *tmp;
875
876 HASH_ITER(hh, context->cache, cp, ctmp) {
877 coap_delete_cache_entry(context, cp);
878 }
879 if (context->cache_ignore_count) {
880 coap_free_type(COAP_STRING, context->cache_ignore_options);
881 }
882
883 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
884 coap_free_endpoint_lkd(ep);
885 }
886#endif /* COAP_SERVER_SUPPORT */
887
888#if COAP_CLIENT_SUPPORT
889 coap_session_t *sp, *rtmp;
890
891 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
893 }
894#endif /* COAP_CLIENT_SUPPORT */
895
896#if COAP_OSCORE_SUPPORT
897 coap_delete_all_oscore(context);
898#endif /* COAP_OSCORE_SUPPORT */
899
900 if (context->dtls_context)
902#ifdef COAP_EPOLL_SUPPORT
903 if (context->eptimerfd != -1) {
904 int ret;
905 struct epoll_event event;
906
907 /* Kernels prior to 2.6.9 expect non NULL event parameter */
908 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
909 if (ret == -1) {
910 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
911 "coap_free_context",
912 coap_socket_strerror(), errno);
913 }
914 close(context->eptimerfd);
915 context->eptimerfd = -1;
916 }
917 if (context->epfd != -1) {
918 close(context->epfd);
919 context->epfd = -1;
920 }
921#endif /* COAP_EPOLL_SUPPORT */
922#if COAP_SERVER_SUPPORT
923#if COAP_WITH_OBSERVE_PERSIST
924 coap_persist_cleanup(context);
925#endif /* COAP_WITH_OBSERVE_PERSIST */
926#endif /* COAP_SERVER_SUPPORT */
927#if COAP_PROXY_SUPPORT
928 coap_proxy_cleanup(context);
929#endif /* COAP_PROXY_SUPPORT */
930
931 if (context->app_cb) {
932 coap_lock_callback(context->app_cb(context->app_data));
933 }
934#if defined(WITH_LWIP)
935#if NO_SYS == 0
936 sys_sem_free(&context->coap_io_timeout_sem);
937#endif /* NO_SYS == 0 */
938#endif /* ! WITH_LWIP */
939#if COAP_THREAD_SAFE && !WITH_LWIP
941#endif /* COAP_THREAD_SAFE && !WITH_LWIP */
944}
945
946static coap_crit_type_t
948#if COAP_SERVER_SUPPORT
949 coap_opt_iterator_t t_iter;
950 coap_opt_t *proxy_uri = NULL;
951 coap_opt_t *proxy_scheme = NULL;
952
953 if (session->proxy_session) {
954 return COAP_CRIT_PROXY;
955 } else if (COAP_PDU_IS_REQUEST(pdu) && session->context->unknown_resource &&
956 session->context->unknown_resource->is_reverse_proxy) {
957 return COAP_CRIT_PROXY;
958 } else if (COAP_PDU_IS_REQUEST(pdu) && session->context->proxy_uri_resource &&
959 ((proxy_uri = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &t_iter)) ||
960 (proxy_scheme = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &t_iter)))) {
961 if (proxy_uri || proxy_scheme) {
962 coap_uri_t uri;
963
964 /* Duplicates some of the code in handle_request() */
965 if (proxy_uri) {
967 coap_opt_length(proxy_uri), &uri) < 0) {
968 return COAP_CRIT_PROXY;
969 }
970 } else {
971 coap_opt_t *opt;
972 coap_resource_t *resource;
973
974 memset(&uri, 0, sizeof(uri));
975 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &t_iter);
976 if (opt) {
977 uri.host.length = coap_opt_length(opt);
978 uri.host.s = coap_opt_value(opt);
979 } else {
980 uri.host.length = 0;
981 }
982 /* See if we are the endpoint */
983 resource = session->context->proxy_uri_resource;
984 if (uri.host.length && resource->proxy_name_count &&
985 resource->proxy_name_list) {
986 size_t i;
987
988 if (resource->proxy_name_count == 1 &&
989 resource->proxy_name_list[0]->length == 0) {
990 /* If proxy_name_list[0] is zero length, then this is the endpoint */
991 i = 0;
992 } else {
993 for (i = 0; i < resource->proxy_name_count; i++) {
994 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
995 break;
996 }
997 }
998 }
999 if (i != resource->proxy_name_count) {
1000 return COAP_CRIT_NOT_PROXY;
1001 }
1002 }
1003 }
1004 return COAP_CRIT_PROXY;
1005 }
1006 }
1007 return COAP_CRIT_NOT_PROXY;
1008#else /* ! COAP_SERVER_SUPPORT */
1009#endif /* ! COAP_SERVER_SUPPORT */
1010 (void)session;
1011 (void)pdu;
1012 return COAP_CRIT_NOT_PROXY;
1013}
1014
1015int
1017 coap_pdu_t *pdu,
1018 coap_opt_filter_t *unknown,
1019 coap_crit_type_t is_proxy) {
1020 coap_context_t *ctx = session->context;
1021 coap_opt_iterator_t opt_iter;
1022 int ok = 1;
1023 coap_option_num_t last_number = -1;
1024
1025 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1026
1027 while (coap_option_next(&opt_iter)) {
1028 /* Check for explicitely reserved option RFC 5272 12.2 Table 7 */
1029 /* Need to check reserved options */
1030 switch (opt_iter.number) {
1031 case 0:
1032 case 128:
1033 case 132:
1034 case 136:
1035 case 140:
1036 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1037 coap_log_debug("Unknown reserved option %d\n", opt_iter.number);
1038 ok = 0;
1039
1040 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1041 * slots have been used up and no more options can be tracked.
1042 * Safe to break out of this loop as ok is already set. */
1043 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1044 goto overflow;
1045 }
1046 }
1047 break;
1048 default:
1049 break;
1050 }
1051 if (opt_iter.number & 0x01) {
1052 /* first check the known built-in critical options */
1053 switch (opt_iter.number) {
1054#if COAP_Q_BLOCK_SUPPORT
1057 if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
1058 coap_log_debug("Critical option '%s' (%d) disabled - not supported\n",
1059 coap_option_string(pdu->code, opt_iter.number), opt_iter.number);
1060 ok = 0;
1061 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1062 * slots have been used up and no more options can be tracked.
1063 * Safe to break out of this loop as ok is already set. */
1064 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1065 goto overflow;
1066 }
1067 }
1068 break;
1069#endif /* COAP_Q_BLOCK_SUPPORT */
1077 case COAP_OPTION_ACCEPT:
1078 case COAP_OPTION_BLOCK2:
1079 case COAP_OPTION_BLOCK1:
1082 break;
1083 case COAP_OPTION_OSCORE:
1084 /* Valid critical if doing OSCORE */
1085#if COAP_OSCORE_SUPPORT
1086 /* Generally configured or has coap oscore enabled helper function */
1087 if (ctx->p_osc_ctx || ctx->oscore_find_cb)
1088 break;
1089#endif /* COAP_OSCORE_SUPPORT */
1090 /* Fall Through */
1091 default:
1092 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1093#if COAP_SERVER_SUPPORT
1094 if ((opt_iter.number & 0x02) == 0) {
1095 /* Safe to forward critical? - check if proxy pdu */
1096 if (is_proxy == COAP_CRIT_UNKNOWN) {
1097 is_proxy = coap_is_session_proxy(session, pdu);
1098 }
1099 if (is_proxy == COAP_CRIT_PROXY) {
1100 pdu->crit_opt = 1;
1101 break;
1102 }
1103 }
1104#endif /* COAP_SERVER_SUPPORT */
1105 coap_log_debug("Critical option %u dropped\n", opt_iter.number);
1106 ok = 0;
1107
1108 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1109 * slots have been used up and no more options can be tracked.
1110 * Safe to break out of this loop as ok is already set. */
1111 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1112 goto overflow;
1113 }
1114 }
1115 }
1116 }
1117 if (opt_iter.number & 0x02) {
1118 /* Check for safe to forward for a proxy */
1119 if (is_proxy == COAP_CRIT_UNKNOWN) {
1120 is_proxy = coap_is_session_proxy(session, pdu);
1121 }
1122 if (is_proxy == COAP_CRIT_PROXY) {
1123 switch (opt_iter.number) {
1128 case COAP_OPTION_MAXAGE:
1131 case COAP_OPTION_BLOCK2:
1132 case COAP_OPTION_BLOCK1:
1136 break;
1137 default:
1138 coap_log_debug("Not Safe option %u cannot be forwarded - dropped\n",
1139 opt_iter.number);
1140 ok = 0;
1141
1142 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1143 * slots have been used up and no more options can be tracked.
1144 * Safe to break out of this loop as ok is already set. */
1145 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1146 goto overflow;
1147 }
1148 }
1149 }
1150 }
1151 if (last_number == opt_iter.number) {
1152 /* Check for duplicated option RFC 5272 5.4.5 */
1153 if (!coap_option_check_repeatable(pdu, opt_iter.number)) {
1154 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1155 ok = 0;
1156 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1157 goto overflow;
1158 }
1159 }
1160 }
1161 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
1162 COAP_PDU_IS_REQUEST(pdu)) {
1163 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
1164 coap_block_b_t block;
1165
1166 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
1167 if (block.m) {
1168 size_t used_size = pdu->used_size;
1169 unsigned char buf[4];
1170
1171 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
1172 block.m = 0;
1173 coap_update_option(pdu, opt_iter.number,
1174 coap_encode_var_safe(buf, sizeof(buf),
1175 ((block.num << 4) |
1176 (block.m << 3) |
1177 block.aszx)),
1178 buf);
1179 if (used_size != pdu->used_size) {
1180 /* Unfortunately need to restart the scan */
1181 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1182 last_number = -1;
1183 continue;
1184 }
1185 }
1186 }
1187 }
1188 last_number = opt_iter.number;
1189 }
1190overflow:
1191 return ok;
1192}
1193
1195coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
1196 coap_mid_t mid;
1197
1199 mid = coap_send_rst_lkd(session, request);
1201 return mid;
1202}
1203
1206 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
1207}
1208
1210coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
1211 coap_mid_t mid;
1212
1214 mid = coap_send_ack_lkd(session, request);
1216 return mid;
1217}
1218
1221 coap_pdu_t *response;
1223
1225 if (request && request->type == COAP_MESSAGE_CON &&
1226 COAP_PROTO_NOT_RELIABLE(session->proto)) {
1227 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
1228 if (response)
1229 result = coap_send_internal(session, response, NULL);
1230 }
1231 return result;
1232}
1233
1234ssize_t
1236 ssize_t bytes_written = -1;
1237 assert(pdu->hdr_size > 0);
1238
1239 /* Caller handles partial writes */
1240 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1241 pdu->token - pdu->hdr_size,
1242 pdu->used_size + pdu->hdr_size);
1244 return bytes_written;
1245}
1246
1247static ssize_t
1249 ssize_t bytes_written;
1250
1251 if (session->state == COAP_SESSION_STATE_NONE) {
1252#if ! COAP_CLIENT_SUPPORT
1253 return -1;
1254#else /* COAP_CLIENT_SUPPORT */
1255 if (session->type != COAP_SESSION_TYPE_CLIENT)
1256 return -1;
1257#endif /* COAP_CLIENT_SUPPORT */
1258 }
1259
1260 if (pdu->type == COAP_MESSAGE_CON &&
1261 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1262 coap_is_mcast(&session->addr_info.remote)) {
1263 /* Violates RFC72522 8.1 */
1264 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1265 return -1;
1266 }
1267
1268 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1269 (pdu->type == COAP_MESSAGE_CON &&
1270 session->con_active >= COAP_NSTART(session))) {
1271 return coap_session_delay_pdu(session, pdu, node);
1272 }
1273
1274 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1275 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1276 return coap_session_delay_pdu(session, pdu, node);
1277
1278 bytes_written = coap_session_send_pdu(session, pdu);
1279 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1281 session->con_active++;
1282
1283 return bytes_written;
1284}
1285
1288 const coap_pdu_t *request,
1289 coap_pdu_code_t code,
1290 coap_opt_filter_t *opts) {
1291 coap_mid_t mid;
1292
1294 mid = coap_send_error_lkd(session, request, code, opts);
1296 return mid;
1297}
1298
1301 const coap_pdu_t *request,
1302 coap_pdu_code_t code,
1303 coap_opt_filter_t *opts) {
1304 coap_pdu_t *response;
1306
1307 assert(request);
1308 assert(session);
1309
1310 response = coap_new_error_response(request, code, opts);
1311 if (response)
1312 result = coap_send_internal(session, response, NULL);
1313
1314 return result;
1315}
1316
1319 coap_pdu_type_t type) {
1320 coap_mid_t mid;
1321
1323 mid = coap_send_message_type_lkd(session, request, type);
1325 return mid;
1326}
1327
1330 coap_pdu_type_t type) {
1331 coap_pdu_t *response;
1333
1335 if (request && COAP_PROTO_NOT_RELIABLE(session->proto) &&
1336 !(type == COAP_MESSAGE_RST && coap_is_mcast(&session->addr_info.local))) {
1337 response = coap_pdu_init(type, 0, request->mid, 0);
1338 if (response)
1339 result = coap_send_internal(session, response, NULL);
1340 }
1341 return result;
1342}
1343
1357unsigned int
1358coap_calc_timeout(coap_session_t *session, unsigned char r) {
1359 unsigned int result;
1360
1361 /* The integer 1.0 as a Qx.FRAC_BITS */
1362#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1363
1364 /* rounds val up and right shifts by frac positions */
1365#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1366
1367 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1368 * make the result a rounded Qx.FRAC_BITS */
1369 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1370
1371 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1372 * make the result a rounded Qx.FRAC_BITS */
1373 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1374
1375 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1376 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1377 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1378
1379#undef FP1
1380#undef SHR_FP
1381}
1382
1385 coap_queue_t *node) {
1386 coap_tick_t now;
1387
1388 node->session = coap_session_reference_lkd(session);
1389
1390 /* Set timer for pdu retransmission. If this is the first element in
1391 * the retransmission queue, the base time is set to the current
1392 * time and the retransmission time is node->timeout. If there is
1393 * already an entry in the sendqueue, we must check if this node is
1394 * to be retransmitted earlier. Therefore, node->timeout is first
1395 * normalized to the base time and then inserted into the queue with
1396 * an adjusted relative time.
1397 */
1398 coap_ticks(&now);
1399 if (context->sendqueue == NULL) {
1400 node->t = node->timeout << node->retransmit_cnt;
1401 context->sendqueue_basetime = now;
1402 } else {
1403 /* make node->t relative to context->sendqueue_basetime */
1404 node->t = (now - context->sendqueue_basetime) +
1405 (node->timeout << node->retransmit_cnt);
1406 }
1407 coap_address_copy(&node->remote, &session->addr_info.remote);
1408
1409 coap_insert_node(&context->sendqueue, node);
1410
1411 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1412 coap_session_str(node->session), node->id,
1413 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1415
1416 coap_update_io_timer(context, node->t);
1417
1418 return node->id;
1419}
1420
1421#if COAP_CLIENT_SUPPORT
1422/*
1423 * Sent out a test PDU for Extended Token
1424 */
1425static coap_mid_t
1426coap_send_test_extended_token(coap_session_t *session) {
1427 coap_pdu_t *pdu;
1429 size_t i;
1430 coap_binary_t *token;
1431 coap_lg_crcv_t *lg_crcv;
1432
1433 coap_log_debug("Testing for Extended Token support\n");
1434 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1436 coap_new_message_id_lkd(session),
1438 if (!pdu)
1439 return COAP_INVALID_MID;
1440
1441 token = coap_new_binary(session->max_token_size);
1442 if (token == NULL) {
1444 return COAP_INVALID_MID;
1445 }
1446 for (i = 0; i < session->max_token_size; i++) {
1447 token->s[i] = (uint8_t)(i + 1);
1448 }
1449 coap_add_token(pdu, session->max_token_size, token->s);
1450 coap_delete_binary(token);
1451
1454 pdu->actual_token.length);
1455
1457
1458 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1459
1460 /* Need to track incase OSCORE / Echo etc. comes back after non-piggy-backed ACK */
1461 lg_crcv = coap_block_new_lg_crcv(session, pdu, NULL);
1462 if (lg_crcv) {
1463 LL_PREPEND(session->lg_crcv, lg_crcv);
1464 }
1465 mid = coap_send_internal(session, pdu, NULL);
1466 if (mid == COAP_INVALID_MID)
1467 return COAP_INVALID_MID;
1468 session->remote_test_mid = mid;
1469 return mid;
1470}
1471#endif /* COAP_CLIENT_SUPPORT */
1472
1473/*
1474 * Return: 0 Something failed
1475 * 1 Success
1476 */
1477int
1479#if COAP_CLIENT_SUPPORT
1480 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1481 int timeout_ms = 5000;
1482 coap_session_state_t current_state = session->state;
1483
1484 if (session->delay_recursive) {
1485 return 0;
1486 } else {
1487 session->delay_recursive = 1;
1488 }
1489 /*
1490 * Need to wait for first request to get out and response back before
1491 * continuing.. Response handler has to clear doing_first if not an error.
1492 */
1494 while (session->doing_first != 0) {
1495 int result = coap_io_process_lkd(session->context, 1000);
1496
1497 if (result < 0) {
1498 coap_reset_doing_first(session);
1499 session->delay_recursive = 0;
1500 coap_session_release_lkd(session);
1501 return 0;
1502 }
1503
1504 /* coap_io_process_lkd() may have updated session state */
1505 if (session->state == COAP_SESSION_STATE_CSM &&
1506 current_state != COAP_SESSION_STATE_CSM) {
1507 /* Update timeout and restart the clock for CSM timeout */
1508 current_state = COAP_SESSION_STATE_CSM;
1509 timeout_ms = session->context->csm_timeout_ms;
1510 result = 0;
1511 }
1512
1513 if (result < timeout_ms) {
1514 timeout_ms -= result;
1515 } else {
1516 if (session->doing_first == 1) {
1517 /* Timeout failure of some sort with first request */
1518 if (session->state == COAP_SESSION_STATE_CSM) {
1519 coap_log_debug("** %s: timeout waiting for CSM response\n",
1520 coap_session_str(session));
1521 session->csm_not_seen = 1;
1522 } else {
1523 coap_log_debug("** %s: timeout waiting for first response\n",
1524 coap_session_str(session));
1525 }
1526 coap_reset_doing_first(session);
1527 coap_session_connected(session);
1528 }
1529 }
1530 }
1531 session->delay_recursive = 0;
1532 coap_session_release_lkd(session);
1533 }
1534#else /* ! COAP_CLIENT_SUPPORT */
1535 (void)session;
1536#endif /* ! COAP_CLIENT_SUPPORT */
1537 return 1;
1538}
1539
1540/*
1541 * return 0 Invalid
1542 * 1 Valid
1543 */
1544int
1546
1547 /* Check validity of sending code */
1548 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1549 case 0: /* Empty or request */
1550 case 2: /* Success */
1551 case 3: /* Reserved for future use */
1552 case 4: /* Client error */
1553 case 5: /* Server error */
1554 break;
1555 case 7: /* Reliable signalling */
1556 if (COAP_PROTO_RELIABLE(session->proto))
1557 break;
1558 /* Not valid if UDP */
1559 /* Fall through */
1560 case 1: /* Invalid */
1561 case 6: /* Invalid */
1562 default:
1563 return 0;
1564 }
1565 return 1;
1566}
1567
1568#if COAP_CLIENT_SUPPORT
1569/*
1570 * If type is CON and protocol is not reliable, there is no need to set up
1571 * lg_crcv if it can be built up based on sent PDU if there is a
1572 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1573 * (Q-)Block1.
1574 */
1575static int
1576coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1577 coap_opt_iterator_t opt_iter;
1578
1579 if (!COAP_PDU_IS_REQUEST(pdu))
1580 return 0;
1581
1582 if (
1583#if COAP_OSCORE_SUPPORT
1584 session->oscore_encryption ||
1585#endif /* COAP_OSCORE_SUPPORT */
1586 pdu->type == COAP_MESSAGE_NON ||
1587 COAP_PROTO_RELIABLE(session->proto) ||
1588 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1589#if COAP_Q_BLOCK_SUPPORT
1590 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1591#endif /* COAP_Q_BLOCK_SUPPORT */
1592 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1593 return 1;
1594 }
1595 return 0;
1596}
1597#endif /* COAP_CLIENT_SUPPORT */
1598
1601 coap_mid_t mid;
1602
1604 mid = coap_send_lkd(session, pdu);
1606 return mid;
1607}
1608
1612#if COAP_CLIENT_SUPPORT
1613 coap_lg_crcv_t *lg_crcv = NULL;
1614 coap_opt_iterator_t opt_iter;
1615 coap_block_b_t block;
1616 int observe_action = -1;
1617 int have_block1 = 0;
1618 coap_opt_t *opt;
1619#endif /* COAP_CLIENT_SUPPORT */
1620
1621 assert(pdu);
1622
1624
1625 /* Check validity of sending code */
1626 if (!coap_check_code_class(session, pdu)) {
1627 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1629 pdu->code & 0x1f);
1630 goto error;
1631 }
1632 pdu->session = session;
1633#if COAP_CLIENT_SUPPORT
1634 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1635 !coap_netif_available(session) && !session->session_failed) {
1636 coap_log_debug("coap_send: Socket closed\n");
1637 goto error;
1638 }
1639
1640 if (session->doing_first) {
1641 LL_APPEND(session->doing_first_pdu, pdu);
1643 coap_log_debug("** %s: mid=0x%04x: queued\n",
1644 coap_session_str(session), pdu->mid);
1645 return pdu->mid;
1646 }
1647
1648 /* Indicate support for Extended Tokens if appropriate */
1649 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1651 session->type == COAP_SESSION_TYPE_CLIENT &&
1652 COAP_PDU_IS_REQUEST(pdu)) {
1653 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1654 /*
1655 * When the pass / fail response for Extended Token is received, this PDU
1656 * will get transmitted.
1657 */
1658 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1659 goto error;
1660 }
1661 }
1662 /*
1663 * For reliable protocols, this will get cleared after CSM exchanged
1664 * in coap_session_connected() where Token size support is indicated in the CSM.
1665 */
1666 session->doing_first = 1;
1667 coap_ticks(&session->doing_first_timeout);
1668 LL_PREPEND(session->doing_first_pdu, pdu);
1669 if (session->proto != COAP_PROTO_UDP) {
1670 /* In case the next handshake / CSM is already in */
1672 }
1673 /*
1674 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1675 * will get called again.
1676 */
1678 coap_log_debug("** %s: mid=0x%04x: queued\n",
1679 coap_session_str(session), pdu->mid);
1680 return pdu->mid;
1681 }
1682#if COAP_Q_BLOCK_SUPPORT
1683 /* Indicate support for Q-Block if appropriate */
1684 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1685 session->type == COAP_SESSION_TYPE_CLIENT &&
1686 COAP_PDU_IS_REQUEST(pdu)) {
1687 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1688 goto error;
1689 }
1690 session->doing_first = 1;
1691 coap_ticks(&session->doing_first_timeout);
1692 LL_PREPEND(session->doing_first_pdu, pdu);
1693 if (session->proto != COAP_PROTO_UDP) {
1694 /* In case the next handshake / CSM is already in */
1696 }
1697 /*
1698 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1699 * will get called again.
1700 */
1702 coap_log_debug("** %s: mid=0x%04x: queued\n",
1703 coap_session_str(session), pdu->mid);
1704 return pdu->mid;
1705 }
1706#endif /* COAP_Q_BLOCK_SUPPORT */
1707
1708 /*
1709 * Check validity of token length
1710 */
1711 if (COAP_PDU_IS_REQUEST(pdu) &&
1712 pdu->actual_token.length > session->max_token_size) {
1713 coap_log_warn("coap_send: PDU dropped as token too long (%" PRIuS " > %" PRIu32 ")\n",
1714 pdu->actual_token.length, session->max_token_size);
1715 goto error;
1716 }
1717
1718 /* A lot of the reliable code assumes type is CON */
1719 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1720 pdu->type = COAP_MESSAGE_CON;
1721
1722#if COAP_OSCORE_SUPPORT
1723 if (session->oscore_encryption) {
1724 if (session->recipient_ctx->initial_state == 1 &&
1725 !session->recipient_ctx->silent_server) {
1726 /*
1727 * Not sure if remote supports OSCORE, or is going to send us a
1728 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1729 * is OK. Continue sending current pdu to test things.
1730 */
1731 session->doing_first = 1;
1732 }
1733 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1735 goto error;
1736 }
1737 }
1738#endif /* COAP_OSCORE_SUPPORT */
1739
1740 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1741 return coap_send_internal(session, pdu, NULL);
1742 }
1743
1744 if (session->no_path_abbrev) {
1745 opt = coap_check_option(pdu, COAP_OPTION_URI_PATH_ABB, &opt_iter);
1746 if (opt) {
1747 /* Server cannot handle Uri-Path-Abbrev */
1748 coap_pdu_t *new;
1749 size_t data_len;
1750 const uint8_t *data;
1751
1752 new = coap_pdu_duplicate_lkd(pdu, session, pdu->actual_token.length,
1754 if (new) {
1755 if (coap_get_data(pdu, &data_len, &data)) {
1756 coap_add_data(pdu, data_len, data);
1757 }
1758 coap_log_debug("* Retransmitting PDU with Uri-Path-Abbrev replaced (3)\n");
1760 pdu = new;
1761 }
1762 }
1763 }
1764
1765 if (COAP_PDU_IS_REQUEST(pdu)) {
1766 uint8_t buf[4];
1767
1768 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1769
1770 if (opt) {
1771 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1772 coap_opt_length(opt));
1773 }
1774
1775 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1776 (block.m == 1 || block.bert == 1)) {
1777 have_block1 = 1;
1778 }
1779#if COAP_Q_BLOCK_SUPPORT
1780 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1781 (block.m == 1 || block.bert == 1)) {
1782 if (have_block1) {
1783 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1785 }
1786 have_block1 = 1;
1787 }
1788#endif /* COAP_Q_BLOCK_SUPPORT */
1789 if (observe_action != COAP_OBSERVE_CANCEL) {
1790 /* Warn about re-use of tokens */
1791 if (session->last_token &&
1792 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1794 char scratch[24];
1795 size_t size;
1796 size_t i;
1797
1798 scratch[0] = '\000';
1799 for (i = 0; i < pdu->actual_token.length; i++) {
1800 size = strlen(scratch);
1801 snprintf(&scratch[size], sizeof(scratch)-size,
1802 "%02x", pdu->actual_token.s[i]);
1803 }
1804 coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1805 scratch);
1806 }
1807 }
1810 pdu->actual_token.length);
1811 } else {
1812 /* observe_action == COAP_OBSERVE_CANCEL */
1813 coap_binary_t tmp;
1814 int ret;
1815
1816 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1817 /* Unfortunately need to change the ptr type to be r/w */
1818 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1819 tmp.length = pdu->actual_token.length;
1820 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1821 if (ret == 1) {
1822 /* Observe Cancel successfully sent */
1824 return ret;
1825 }
1826 /* Some mismatch somewhere - continue to send original packet */
1827 }
1828 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1829 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1833 coap_encode_var_safe(buf, sizeof(buf),
1834 ++session->tx_rtag),
1835 buf);
1836 } else {
1837 memset(&block, 0, sizeof(block));
1838 }
1839
1840#if COAP_Q_BLOCK_SUPPORT
1841 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1842#endif /* COAP_Q_BLOCK_SUPPORT */
1843 {
1844 /* Need to check if we need to reset Q-Block to Block */
1845 uint8_t buf[4];
1846
1847 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1850 coap_encode_var_safe(buf, sizeof(buf),
1851 (block.num << 4) | (0 << 3) | block.szx),
1852 buf);
1853 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1854 /* Need to update associated lg_xmit */
1855 coap_lg_xmit_t *lg_xmit;
1856
1857 LL_FOREACH(session->lg_xmit, lg_xmit) {
1858 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1859 lg_xmit->b.b1.app_token &&
1860 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1861 /* Update the skeletal PDU with the block1 option */
1864 coap_encode_var_safe(buf, sizeof(buf),
1865 (block.num << 4) | (0 << 3) | block.szx),
1866 buf);
1867 break;
1868 }
1869 }
1870 }
1871 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1874 coap_encode_var_safe(buf, sizeof(buf),
1875 (block.num << 4) | (block.m << 3) | block.szx),
1876 buf);
1877 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1878 /* Need to update associated lg_xmit */
1879 coap_lg_xmit_t *lg_xmit;
1880
1881 LL_FOREACH(session->lg_xmit, lg_xmit) {
1882 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1883 lg_xmit->b.b1.app_token &&
1884 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1885 /* Update the skeletal PDU with the block1 option */
1888 coap_encode_var_safe(buf, sizeof(buf),
1889 (block.num << 4) |
1890 (block.m << 3) |
1891 block.szx),
1892 buf);
1893 /* Update as this is a Request */
1894 lg_xmit->option = COAP_OPTION_BLOCK1;
1895 break;
1896 }
1897 }
1898 }
1899 }
1900
1901#if COAP_Q_BLOCK_SUPPORT
1902 if (COAP_PDU_IS_REQUEST(pdu) &&
1903 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1904 if (block.num == 0 && block.m == 0) {
1905 uint8_t buf[4];
1906
1907 /* M needs to be set as asking for all the blocks */
1909 coap_encode_var_safe(buf, sizeof(buf),
1910 (0 << 4) | (1 << 3) | block.szx),
1911 buf);
1912 }
1913 }
1914#endif /* COAP_Q_BLOCK_SUPPORT */
1915
1916 /*
1917 * If type is CON and protocol is not reliable, there is no need to set up
1918 * lg_crcv here as it can be built up based on sent PDU if there is a
1919 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1920 * (Q-)Block1.
1921 */
1922 if (coap_check_send_need_lg_crcv(session, pdu)) {
1923 coap_lg_xmit_t *lg_xmit = NULL;
1924
1925 if (!session->lg_xmit && have_block1) {
1926 coap_log_debug("PDU presented by app\n");
1928 }
1929 /* See if this token is already in use for large body responses */
1930 LL_FOREACH(session->lg_crcv, lg_crcv) {
1931 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1932 /* Need to terminate and clean up previous response setup */
1933 LL_DELETE(session->lg_crcv, lg_crcv);
1934 coap_block_delete_lg_crcv(session, lg_crcv);
1935 break;
1936 }
1937 }
1938
1939 if (have_block1 && session->lg_xmit) {
1940 LL_FOREACH(session->lg_xmit, lg_xmit) {
1941 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1942 lg_xmit->b.b1.app_token &&
1943 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1944 break;
1945 }
1946 }
1947 }
1948 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1949 if (lg_crcv == NULL) {
1950 goto error;
1951 }
1952 if (lg_xmit) {
1953 /* Need to update the token as set up in the session->lg_xmit */
1954 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1955 }
1956 }
1957 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1958 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1959
1960#if COAP_Q_BLOCK_SUPPORT
1961 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1962 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1963 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1964 } else
1965#endif /* COAP_Q_BLOCK_SUPPORT */
1966 mid = coap_send_internal(session, pdu, NULL);
1967#else /* !COAP_CLIENT_SUPPORT */
1968 mid = coap_send_internal(session, pdu, NULL);
1969#endif /* !COAP_CLIENT_SUPPORT */
1970#if COAP_CLIENT_SUPPORT
1971 if (lg_crcv) {
1972 if (mid != COAP_INVALID_MID) {
1973 LL_PREPEND(session->lg_crcv, lg_crcv);
1974 } else {
1975 coap_block_delete_lg_crcv(session, lg_crcv);
1976 }
1977 }
1978#endif /* COAP_CLIENT_SUPPORT */
1979 return mid;
1980
1981error:
1983 return COAP_INVALID_MID;
1984}
1985
1986static int
1988 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1989 coap_opt_t *opt;
1990 coap_opt_iterator_t opt_iter;
1991 size_t hop_limit;
1992
1993 addr_str[sizeof(addr_str)-1] = '\000';
1994 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1995 sizeof(addr_str) - 1)) {
1996 char *cp;
1997 size_t len;
1998
1999 if (addr_str[0] == '[') {
2000 cp = strchr(addr_str, ']');
2001 if (cp)
2002 *cp = '\000';
2003 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
2004 /* IPv4 embedded into IPv6 */
2005 cp = &addr_str[8];
2006 } else {
2007 cp = &addr_str[1];
2008 }
2009 } else {
2010 cp = strchr(addr_str, ':');
2011 if (cp)
2012 *cp = '\000';
2013 cp = addr_str;
2014 }
2015 len = strlen(cp);
2016
2017 /* See if Hop Limit option is being used in return path */
2018 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2019 if (opt) {
2020 uint8_t buf[4];
2021
2022 hop_limit =
2024 if (hop_limit == 1) {
2025 coap_log_warn("Proxy loop detected '%s'\n",
2026 (char *)pdu->data);
2029 } else if (hop_limit < 1 || hop_limit > 255) {
2030 /* Something is bad - need to drop this pdu (TODO or delete option) */
2031 coap_log_warn("Proxy return has bad hop limit count '%" PRIuS "'\n",
2032 hop_limit);
2034 return 0;
2035 }
2036 hop_limit--;
2038 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2039 buf);
2040 }
2041
2042 /* Need to check that we are not seeing this proxy in the return loop */
2043 if (pdu->data && opt == NULL) {
2044 char *a_match;
2045 size_t data_len;
2046
2047 if (pdu->used_size + 1 > pdu->max_size) {
2048 /* No space */
2050 return 0;
2051 }
2052 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
2053 /* Internal error */
2055 return 0;
2056 }
2057 data_len = pdu->used_size - (pdu->data - pdu->token);
2058 pdu->data[data_len] = '\000';
2059 a_match = strstr((char *)pdu->data, cp);
2060 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
2061 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
2062 a_match[len] == ' ')) {
2063 coap_log_warn("Proxy loop detected '%s'\n",
2064 (char *)pdu->data);
2066 return 0;
2067 }
2068 }
2069 if (pdu->used_size + len + 1 <= pdu->max_size) {
2070 size_t old_size = pdu->used_size;
2071 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
2072 if (pdu->data == NULL) {
2073 /*
2074 * Set Hop Limit to max for return path. If this libcoap is in
2075 * a proxy loop path, it will always decrement hop limit in code
2076 * above and hence timeout / drop the response as appropriate
2077 */
2078 hop_limit = 255;
2080 (uint8_t *)&hop_limit);
2081 coap_add_data(pdu, len, (uint8_t *)cp);
2082 } else {
2083 /* prepend with space separator, leaving hop limit "as is" */
2084 memmove(pdu->data + len + 1, pdu->data,
2085 old_size - (pdu->data - pdu->token));
2086 memcpy(pdu->data, cp, len);
2087 pdu->data[len] = ' ';
2088 pdu->used_size += len + 1;
2089 }
2090 }
2091 }
2092 }
2093 return 1;
2094}
2095
2098 uint8_t r;
2099 ssize_t bytes_written;
2100
2101#if ! COAP_SERVER_SUPPORT
2102 (void)request_pdu;
2103#endif /* COAP_SERVER_SUPPORT */
2104 pdu->session = session;
2105#if COAP_CLIENT_SUPPORT
2106 if (session->session_failed) {
2107 coap_session_reconnect(session);
2108 if (session->session_failed)
2109 goto error;
2110 }
2111#endif /* COAP_CLIENT_SUPPORT */
2112 if (pdu->type == COAP_MESSAGE_NON && session->rl_ticks_per_packet) {
2113 coap_tick_t now;
2114
2115 if (!session->is_rate_limiting) {
2116 coap_ticks(&now);
2117#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
2118 if (now - session->last_tx < session->rl_ticks_per_packet) {
2119 uint32_t rem = (uint32_t)(session->rl_ticks_per_packet -
2120 (now - session->last_tx)) * 1000 / COAP_TICKS_PER_SECOND;
2121 coap_log_debug("** %s: mid 0x%04x: delaying transmission (%d.%03ds)\n",
2122 coap_session_str(session), pdu->mid, rem / 1000, rem %1000);
2124 }
2125#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
2126 while (1) {
2127 uint32_t timeout_ms;
2128
2129 if (send_recv_terminate) {
2130 goto error;
2131 }
2132
2133 if (now - session->last_tx >= session->rl_ticks_per_packet) {
2134 break;
2135 }
2136 timeout_ms = (uint32_t)((session->rl_ticks_per_packet - (now - session->last_tx)) /
2137 (COAP_TICKS_PER_SECOND / 1000));
2138
2139 if (timeout_ms == 0) {
2140 timeout_ms = COAP_IO_NO_WAIT;
2141 }
2142
2143 session->is_rate_limiting = 1;
2144 coap_io_process_lkd(session->context, timeout_ms);
2145 session->is_rate_limiting = 0;
2146 coap_ticks(&now);
2147 }
2148 coap_log_debug("** %s: mid 0x%04x: now transmitting\n",
2149 coap_session_str(session), pdu->mid);
2150 session->last_tx = now;
2151 }
2152 }
2153#if COAP_PROXY_SUPPORT
2154 if (session->server_list) {
2155 /* Local session wanting to use proxy logic */
2156 return coap_proxy_local_write(session, pdu);
2157 }
2158#endif /* COAP_PROXY_SUPPORT */
2159 if (pdu->code == COAP_RESPONSE_CODE(508)) {
2160 /*
2161 * Need to prepend our IP identifier to the data as per
2162 * https://rfc-editor.org/rfc/rfc8768.html#section-4
2163 */
2164 if (!prepend_508_ip(session, pdu)) {
2166 }
2167 }
2168
2169 if (session->echo) {
2170 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
2171 session->echo->s))
2172 goto error;
2173 coap_delete_bin_const(session->echo);
2174 session->echo = NULL;
2175 }
2176#if COAP_OSCORE_SUPPORT
2177 if (session->oscore_encryption) {
2178 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
2180 goto error;
2181 }
2182#endif /* COAP_OSCORE_SUPPORT */
2183
2184 if (!coap_pdu_encode_header(pdu, session->proto)) {
2185 goto error;
2186 }
2187
2188#if !COAP_DISABLE_TCP
2189 if (COAP_PROTO_RELIABLE(session->proto) &&
2191 coap_opt_iterator_t opt_iter;
2192
2193 if (!session->csm_block_supported) {
2194 /*
2195 * Need to check that this instance is not sending any block options as
2196 * the remote end via CSM has not informed us that there is support
2197 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2198 * This includes potential BERT blocks.
2199 */
2200 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2201 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2202 }
2203 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2204 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2205 }
2206 } else if (!session->csm_bert_rem_support) {
2207 coap_opt_t *opt;
2208
2209 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2210 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2211 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2212 }
2213 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2214 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2215 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2216 }
2217 }
2218 }
2219#endif /* !COAP_DISABLE_TCP */
2220
2221#if COAP_OSCORE_SUPPORT
2222 if (session->oscore_encryption &&
2223 pdu->type != COAP_MESSAGE_RST &&
2224 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2225 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2226 /* Refactor PDU as appropriate RFC8613 */
2227 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2228
2229 if (osc_pdu == NULL) {
2230 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2233 goto error;
2234 }
2235 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2237 pdu = osc_pdu;
2238 } else
2239#endif /* COAP_OSCORE_SUPPORT */
2240 bytes_written = coap_send_pdu(session, pdu, NULL);
2241
2242#if COAP_SERVER_SUPPORT
2243 if (session->last_resp_pdu != pdu &&
2244 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2245 COAP_PDU_IS_REQUEST(request_pdu) &&
2246 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2247 coap_delete_pdu_lkd(session->last_resp_pdu);
2248 session->last_resp_pdu = pdu;
2249 coap_pdu_reference_lkd(session->last_resp_pdu);
2250 }
2251#endif /* COAP_SERVER_SUPPORT */
2252
2253 if (bytes_written == COAP_PDU_DELAYED) {
2254 /* do not free pdu as it is stored with session for later use */
2255 return pdu->mid;
2256 }
2257 if (bytes_written < 0) {
2258 if (pdu->code != 0)
2260 goto error;
2261 }
2262
2263#if !COAP_DISABLE_TCP
2264 if (COAP_PROTO_RELIABLE(session->proto) &&
2265 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2266 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2267 session->partial_write = (size_t)bytes_written;
2268 /* do not free pdu as it is stored with session for later use */
2269 return pdu->mid;
2270 } else {
2271 goto error;
2272 }
2273 }
2274#endif /* !COAP_DISABLE_TCP */
2275
2276 if (pdu->type != COAP_MESSAGE_CON
2277 || COAP_PROTO_RELIABLE(session->proto)) {
2278 coap_mid_t id = pdu->mid;
2280 return id;
2281 }
2282
2283 coap_queue_t *node = coap_new_node();
2284 if (!node) {
2285 coap_log_debug("coap_wait_ack: insufficient memory\n");
2286 goto error;
2287 }
2288
2289 node->id = pdu->mid;
2290 node->pdu = pdu;
2291 coap_prng_lkd(&r, sizeof(r));
2292 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2293 node->timeout = coap_calc_timeout(session, r);
2294 return coap_wait_ack(session->context, session, node);
2295error:
2297 return COAP_INVALID_MID;
2298}
2299
2300void
2304
2305COAP_API int
2307 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2308 int ret;
2309
2310 coap_lock_lock(return 0);
2311 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2313 return ret;
2314}
2315
2316/*
2317 * Return 0 or +ve Time in function in ms after successful transfer
2318 * -1 Invalid timeout parameter
2319 * -2 Failed to transmit PDU
2320 * -3 Nack or Event handler invoked, cancelling request
2321 * -4 coap_io_process returned error (fail to re-lock or select())
2322 * -5 Response not received in the given time
2323 * -6 Terminated by user
2324 * -7 Client mode code not enabled
2325 */
2326int
2328 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2329#if COAP_CLIENT_SUPPORT
2331 uint32_t rem_timeout = timeout_ms;
2332 uint32_t block_mode = session->block_mode;
2333 int ret = 0;
2334 coap_tick_t now;
2335 coap_tick_t start;
2336 coap_tick_t ticks_so_far;
2337 uint32_t time_so_far_ms;
2338
2339 coap_ticks(&start);
2340 assert(request_pdu);
2341
2343
2344 session->resp_pdu = NULL;
2345 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2346 request_pdu->actual_token.length);
2347
2348 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2349 ret = -1;
2350 goto fail;
2351 }
2352 if (session->state == COAP_SESSION_STATE_NONE) {
2353 ret = -3;
2354 goto fail;
2355 }
2356
2358 if (coap_is_mcast(&session->addr_info.remote))
2359 block_mode = session->block_mode;
2360
2361 session->doing_send_recv = 1;
2362 /* So the user needs to delete the PDU */
2363 coap_pdu_reference_lkd(request_pdu);
2364 mid = coap_send_lkd(session, request_pdu);
2365 if (mid == COAP_INVALID_MID) {
2366 if (!session->doing_send_recv)
2367 ret = -3;
2368 else
2369 ret = -2;
2370 goto fail;
2371 }
2372
2373 /* Wait for the response to come in */
2374 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2375 if (send_recv_terminate) {
2376 ret = -6;
2377 goto fail;
2378 }
2379 ret = coap_io_process_lkd(session->context, rem_timeout);
2380 if (ret < 0) {
2381 ret = -4;
2382 goto fail;
2383 }
2384 /* timeout_ms is for timeout between specific request and response */
2385 coap_ticks(&now);
2386 ticks_so_far = now - session->last_rx_tx;
2387 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2388 if (time_so_far_ms >= timeout_ms) {
2389 rem_timeout = 0;
2390 } else {
2391 rem_timeout = timeout_ms - time_so_far_ms;
2392 }
2393 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2394 /* To pick up on (D)TLS setup issues */
2395 coap_ticks(&now);
2396 ticks_so_far = now - start;
2397 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2398 if (time_so_far_ms >= timeout_ms) {
2399 rem_timeout = 0;
2400 } else {
2401 rem_timeout = timeout_ms - time_so_far_ms;
2402 }
2403 }
2404 }
2405
2406 if (rem_timeout) {
2407 coap_ticks(&now);
2408 ticks_so_far = now - start;
2409 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2410 ret = time_so_far_ms;
2411 /* Give PDU to user who will be calling coap_delete_pdu() */
2412 *response_pdu = session->resp_pdu;
2413 session->resp_pdu = NULL;
2414 if (*response_pdu == NULL) {
2415 ret = -3;
2416 }
2417 } else {
2418 /* If there is a resp_pdu, it will get cleared below */
2419 ret = -5;
2420 }
2421
2422fail:
2423 session->block_mode = block_mode;
2424 session->doing_send_recv = 0;
2425 /* delete referenced copy */
2426 coap_delete_pdu_lkd(session->resp_pdu);
2427 session->resp_pdu = NULL;
2428 coap_delete_bin_const(session->req_token);
2429 session->req_token = NULL;
2430 return ret;
2431
2432#else /* !COAP_CLIENT_SUPPORT */
2433
2434 (void)session;
2435 (void)timeout_ms;
2436 (void)request_pdu;
2437 coap_log_warn("coap_send_recv: Client mode not supported\n");
2438 *response_pdu = NULL;
2439 return -7;
2440
2441#endif /* ! COAP_CLIENT_SUPPORT */
2442}
2443
2446 if (!context || !node || !node->session)
2447 return COAP_INVALID_MID;
2448
2449#if COAP_CLIENT_SUPPORT
2450 if (node->session->session_failed) {
2451 /* Force failure */
2452 node->retransmit_cnt = (unsigned char)node->session->max_retransmit;
2453 }
2454#endif /* COAP_CLIENT_SUPPORT */
2455
2456 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2457 if (node->retransmit_cnt < node->session->max_retransmit) {
2458 ssize_t bytes_written;
2459 coap_tick_t now;
2460 coap_tick_t next_delay;
2461 coap_address_t remote;
2462
2463 node->retransmit_cnt++;
2465
2466 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2467 if (context->ping_timeout &&
2468 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2469 uint8_t byte;
2470
2471 coap_prng_lkd(&byte, sizeof(byte));
2472 /* Don't exceed the ping timeout value */
2473 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2474 }
2475
2476 coap_ticks(&now);
2477 if (context->sendqueue == NULL) {
2478 node->t = next_delay;
2479 context->sendqueue_basetime = now;
2480 } else {
2481 /* make node->t relative to context->sendqueue_basetime */
2482 node->t = (now - context->sendqueue_basetime) + next_delay;
2483 }
2484 coap_insert_node(&context->sendqueue, node);
2485 coap_address_copy(&remote, &node->session->addr_info.remote);
2487
2488 if (node->is_mcast) {
2489 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2490 coap_session_str(node->session), node->id);
2491 } else {
2492 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2493 coap_session_str(node->session), node->id,
2494 node->retransmit_cnt,
2495 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2496 }
2497
2498 if (node->session->con_active)
2499 node->session->con_active--;
2500 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2501
2502 if (bytes_written == COAP_PDU_DELAYED) {
2503 /* PDU was not retransmitted immediately because a new handshake is
2504 in progress. node was moved to the send queue of the session. */
2505 return node->id;
2506 }
2507
2508 coap_address_copy(&node->session->addr_info.remote, &remote);
2509 if (node->is_mcast) {
2512 return COAP_INVALID_MID;
2513 }
2514
2515 if (bytes_written < 0)
2516 return (int)bytes_written;
2517
2518 return node->id;
2519 }
2520
2521#if COAP_CLIENT_SUPPORT
2522 if (node->session->session_failed) {
2523 coap_log_info("** %s: mid=0x%04x: deleted due to reconnection issue\n",
2524 coap_session_str(node->session), node->id);
2525 } else {
2526#endif /* COAP_CLIENT_SUPPORT */
2527 /* no more retransmissions, remove node from system */
2528 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2529 coap_session_str(node->session), node->id, node->retransmit_cnt);
2530#if COAP_CLIENT_SUPPORT
2531 }
2532#endif /* COAP_CLIENT_SUPPORT */
2533
2534#if COAP_SERVER_SUPPORT
2535 /* Check if subscriptions exist that should be canceled after
2536 COAP_OBS_MAX_FAIL */
2537 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2538 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2539 if (context->ping_timeout) {
2542 return COAP_INVALID_MID;
2543 } else {
2544 if (node->session->ref_subscriptions)
2545 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2546#if COAP_PROXY_SUPPORT
2547 /* Need to check is there is a proxy subscription active and delete it */
2548 if (node->session->ref_proxy_subs)
2549 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2550 0, COAP_PROXY_SUBS_TOKEN);
2551#endif /* COAP_PROXY_SUPPORT */
2552 }
2553 }
2554#endif /* COAP_SERVER_SUPPORT */
2555 if (node->session->con_active) {
2556 node->session->con_active--;
2558 /*
2559 * As there may be another CON in a different queue entry on the same
2560 * session that needs to be immediately released,
2561 * coap_session_connected() is called.
2562 * However, there is the possibility coap_wait_ack() may be called for
2563 * this node (queue) and re-added to context->sendqueue.
2564 * coap_delete_node_lkd(node) called shortly will handle this and
2565 * remove it.
2566 */
2568 }
2569 }
2570
2571 if (node->pdu->type == COAP_MESSAGE_CON) {
2573 }
2574#if COAP_CLIENT_SUPPORT
2575 node->session->doing_send_recv = 0;
2576#endif /* COAP_CLIENT_SUPPORT */
2577 /* And finally delete the node */
2579 return COAP_INVALID_MID;
2580}
2581
2582static int
2584 uint8_t *data;
2585 size_t data_len;
2586 int result = -1;
2587
2588 coap_packet_get_memmapped(packet, &data, &data_len);
2589 if (session->proto == COAP_PROTO_DTLS) {
2590#if COAP_SERVER_SUPPORT
2591 if (session->type == COAP_SESSION_TYPE_HELLO)
2592 result = coap_dtls_hello(session, data, data_len);
2593 else
2594#endif /* COAP_SERVER_SUPPORT */
2595 if (session->tls)
2596 result = coap_dtls_receive(session, data, data_len);
2597 } else if (session->proto == COAP_PROTO_UDP) {
2598 result = coap_handle_dgram(ctx, session, data, data_len);
2599 }
2600 return result;
2601}
2602
2603#if COAP_CLIENT_SUPPORT
2604void
2606#if COAP_DISABLE_TCP
2607 (void)now;
2608
2610#else /* !COAP_DISABLE_TCP */
2611 if (coap_netif_strm_connect2(session)) {
2612 session->last_rx_tx = now;
2614 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2615 } else {
2618 }
2619#endif /* !COAP_DISABLE_TCP */
2620}
2621#endif /* COAP_CLIENT_SUPPORT */
2622
2623static void
2625 (void)ctx;
2626 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2627
2628 while (session->delayqueue) {
2629 ssize_t bytes_written;
2630 coap_queue_t *q = session->delayqueue;
2631
2632 coap_address_copy(&session->addr_info.remote, &q->remote);
2633 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2634 coap_session_str(session), (int)q->id);
2635 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2636 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2637 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2638 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2639 if (bytes_written > 0)
2640 session->last_rx_tx = now;
2641 if (bytes_written <= 0 ||
2642 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2643 if (bytes_written > 0)
2644 session->partial_write += (size_t)bytes_written;
2645 break;
2646 }
2647 session->delayqueue = q->next;
2648 session->partial_write = 0;
2650 }
2651}
2652
2653void
2655#if COAP_CONSTRAINED_STACK
2656 /* payload and packet can be protected by global_lock if needed */
2657 static unsigned char payload[COAP_RXBUFFER_SIZE];
2658 static coap_packet_t s_packet;
2659#else /* ! COAP_CONSTRAINED_STACK */
2660 unsigned char payload[COAP_RXBUFFER_SIZE];
2661 coap_packet_t s_packet;
2662#endif /* ! COAP_CONSTRAINED_STACK */
2663 coap_packet_t *packet = &s_packet;
2664
2666
2667 packet->length = sizeof(payload);
2668 packet->payload = payload;
2669
2670 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2671 ssize_t bytes_read;
2672 coap_address_t remote;
2673
2674 coap_address_copy(&remote, &session->addr_info.remote);
2675 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2676 bytes_read = coap_netif_dgrm_read(session, packet);
2677
2678 if (bytes_read < 0) {
2679 if (bytes_read == -2) {
2680 coap_address_copy(&session->addr_info.remote, &remote);
2681 /* Reset the session back to startup defaults */
2683 }
2684 } else if (bytes_read > 0) {
2685 session->last_rx_tx = now;
2686#if COAP_CLIENT_SUPPORT
2687 if (session->session_failed) {
2688 session->session_failed = 0;
2690 }
2691#endif /* COAP_CLIENT_SUPPORT */
2692 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2693 coap_handle_dgram_for_proto(ctx, session, packet);
2694 } else {
2695 coap_address_copy(&session->addr_info.remote, &remote);
2696 }
2697#if !COAP_DISABLE_TCP
2698 } else if (session->proto == COAP_PROTO_WS ||
2699 session->proto == COAP_PROTO_WSS) {
2700 ssize_t bytes_read = 0;
2701
2702 /* WebSocket layer passes us the whole packet */
2703 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2704 packet->payload,
2705 packet->length);
2706 if (bytes_read < 0) {
2708 } else if (bytes_read > 2) {
2709 coap_pdu_t *pdu;
2710
2711 session->last_rx_tx = now;
2712 /* Need max space incase PDU is updated with updated token etc. */
2713 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2714 if (!pdu) {
2715 return;
2716 }
2717
2718 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2720 coap_log_warn("discard malformed PDU\n");
2722 return;
2723 }
2724
2725 coap_dispatch(ctx, session, pdu);
2727 return;
2728 }
2729 } else {
2730 ssize_t bytes_read = 0;
2731 const uint8_t *p;
2732 int retry;
2733
2734 do {
2735 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2736 packet->payload,
2737 packet->length);
2738 if (bytes_read > 0) {
2739 session->last_rx_tx = now;
2740 }
2741 p = packet->payload;
2742 retry = bytes_read == (ssize_t)packet->length;
2743 while (bytes_read > 0) {
2744 if (session->partial_pdu) {
2745 size_t len = session->partial_pdu->used_size
2746 + session->partial_pdu->hdr_size
2747 - session->partial_read;
2748 size_t n = min(len, (size_t)bytes_read);
2749 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2750 + session->partial_read, p, n);
2751 p += n;
2752 bytes_read -= n;
2753 if (n == len) {
2754 coap_opt_filter_t error_opts;
2755 coap_pdu_t *pdu = session->partial_pdu;
2756
2757 session->partial_pdu = NULL;
2758 session->partial_read = 0;
2759
2760 coap_option_filter_clear(&error_opts);
2761 if (coap_pdu_parse_header(pdu, session->proto)
2762 && coap_pdu_parse_opt(pdu, &error_opts)) {
2763 coap_dispatch(ctx, session, pdu);
2764 } else if (error_opts.mask) {
2765 coap_pdu_t *response =
2767 COAP_RESPONSE_CODE(402), &error_opts);
2768 if (!response) {
2769 coap_log_warn("coap_read_session: cannot create error response\n");
2770 } else {
2771 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2772 coap_log_warn("coap_read_session: error sending response\n");
2773 }
2774 }
2776 } else {
2777 session->partial_read += n;
2778 }
2779 } else if (session->partial_read > 0) {
2780 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2781 session->read_header);
2782 size_t tkl = session->read_header[0] & 0x0f;
2783 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2784 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2785 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2786 size_t n = min(len, (size_t)bytes_read);
2787 memcpy(session->read_header + session->partial_read, p, n);
2788 p += n;
2789 bytes_read -= n;
2790 if (n == len) {
2791 /* Header now all in */
2792 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2793 hdr_size + tok_ext_bytes);
2794 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2795 coap_log_warn("** %s: incoming PDU length too large (%" PRIuS " > %lu)\n",
2796 coap_session_str(session),
2798 bytes_read = -1;
2799 break;
2800 }
2801 /* Need max space incase PDU is updated with updated token etc. */
2802 session->partial_pdu = coap_pdu_init(0, 0, 0,
2804 if (session->partial_pdu == NULL) {
2805 bytes_read = -1;
2806 break;
2807 }
2808 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2809 bytes_read = -1;
2810 break;
2811 }
2812 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2813 session->partial_pdu->used_size = size;
2814 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2815 session->partial_read = hdr_size + tok_ext_bytes;
2816 if (size == 0) {
2817 coap_pdu_t *pdu = session->partial_pdu;
2818
2819 session->partial_pdu = NULL;
2820 session->partial_read = 0;
2821 if (coap_pdu_parse_header(pdu, session->proto)) {
2822 coap_dispatch(ctx, session, pdu);
2823 }
2825 }
2826 } else {
2827 /* More of the header to go */
2828 session->partial_read += n;
2829 }
2830 } else {
2831 /* Get in first byte of the header */
2832 session->read_header[0] = *p++;
2833 bytes_read -= 1;
2834 if (!coap_pdu_parse_header_size(session->proto,
2835 session->read_header)) {
2836 bytes_read = -1;
2837 break;
2838 }
2839 session->partial_read = 1;
2840 }
2841 }
2842 } while (bytes_read == 0 && retry);
2843 if (bytes_read < 0)
2845#endif /* !COAP_DISABLE_TCP */
2846 }
2847}
2848
2849#if COAP_SERVER_SUPPORT
2850static int
2851coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2852 ssize_t bytes_read = -1;
2853 int result = -1; /* the value to be returned */
2854#if COAP_CONSTRAINED_STACK
2855 /* payload and e_packet can be protected by global_lock if needed */
2856 static unsigned char payload[COAP_RXBUFFER_SIZE];
2857 static coap_packet_t e_packet;
2858#else /* ! COAP_CONSTRAINED_STACK */
2859 unsigned char payload[COAP_RXBUFFER_SIZE];
2860 coap_packet_t e_packet;
2861#endif /* ! COAP_CONSTRAINED_STACK */
2862 coap_packet_t *packet = &e_packet;
2863
2864 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2865 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2866
2867 /* Need to do this as there may be holes in addr_info */
2868 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2869 packet->length = sizeof(payload);
2870 packet->payload = payload;
2872 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2873
2874 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2875 if (bytes_read < 0) {
2876 if (errno != EAGAIN) {
2877 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2878 }
2879 } else if (bytes_read > 0) {
2880 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2881 if (session) {
2883 coap_log_debug("* %s: netif: recv %4" PRIdS " bytes\n",
2884 coap_session_str(session), bytes_read);
2885 result = coap_handle_dgram_for_proto(ctx, session, packet);
2886 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2887 coap_session_new_dtls_session(session, now);
2888 coap_session_release_lkd(session);
2889 }
2890 }
2891 return result;
2892}
2893
2894static int
2895coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2896 (void)ctx;
2897 (void)endpoint;
2898 (void)now;
2899 return 0;
2900}
2901
2902#if !COAP_DISABLE_TCP
2903static int
2904coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2905 coap_tick_t now, void *extra) {
2906 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2907 if (session)
2908 session->last_rx_tx = now;
2909 return session != NULL;
2910}
2911#endif /* !COAP_DISABLE_TCP */
2912#endif /* COAP_SERVER_SUPPORT */
2913
2914COAP_API void
2916 coap_lock_lock(return);
2917 coap_io_do_io_lkd(ctx, now);
2919}
2920
2921void
2923#ifdef COAP_EPOLL_SUPPORT
2924 (void)ctx;
2925 (void)now;
2926 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2927#else /* ! COAP_EPOLL_SUPPORT */
2928 coap_session_t *s, *rtmp;
2929
2931#if COAP_SERVER_SUPPORT
2932 coap_endpoint_t *ep, *tmp;
2933 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2934 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2935 coap_read_endpoint(ctx, ep, now);
2936 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2937 coap_write_endpoint(ctx, ep, now);
2938#if !COAP_DISABLE_TCP
2939 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2940 coap_accept_endpoint(ctx, ep, now, NULL);
2941#endif /* !COAP_DISABLE_TCP */
2942 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2943 /* Make sure the session object is not deleted in one of the callbacks */
2945#if COAP_CLIENT_SUPPORT
2946 if (s->client_initiated && (s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2947 coap_connect_session(s, now);
2948 }
2949#endif /* COAP_CLIENT_SUPPORT */
2950 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2951 coap_read_session(ctx, s, now);
2952 }
2953 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2954 coap_write_session(ctx, s, now);
2955 }
2957 }
2958 }
2959#endif /* COAP_SERVER_SUPPORT */
2960
2961#if COAP_CLIENT_SUPPORT
2962 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2963 /* Make sure the session object is not deleted in one of the callbacks */
2965 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2966 coap_connect_session(s, now);
2967 }
2968 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2969 coap_read_session(ctx, s, now);
2970 }
2971 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2972 coap_write_session(ctx, s, now);
2973 }
2975 }
2976#endif /* COAP_CLIENT_SUPPORT */
2977#endif /* ! COAP_EPOLL_SUPPORT */
2978}
2979
2980COAP_API void
2981coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2982 coap_lock_lock(return);
2983 coap_io_do_epoll_lkd(ctx, events, nevents);
2985}
2986
2987/*
2988 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2989 * directly saves having to iterate through the endpoints / sessions.
2990 */
2991void
2992coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2993#ifndef COAP_EPOLL_SUPPORT
2994 (void)ctx;
2995 (void)events;
2996 (void)nevents;
2997 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2998#else /* COAP_EPOLL_SUPPORT */
2999 coap_tick_t now;
3000 size_t j;
3001
3003 coap_ticks(&now);
3004 for (j = 0; j < nevents; j++) {
3005 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
3006
3007 /* Ignore 'timer trigger' ptr which is NULL */
3008 if (sock) {
3009#if COAP_SERVER_SUPPORT
3010 if (sock->endpoint) {
3011 coap_endpoint_t *endpoint = sock->endpoint;
3012 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
3013 (events[j].events & EPOLLIN)) {
3014 sock->flags |= COAP_SOCKET_CAN_READ;
3015 coap_read_endpoint(endpoint->context, endpoint, now);
3016 }
3017
3018 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
3019 (events[j].events & EPOLLOUT)) {
3020 /*
3021 * Need to update this to EPOLLIN as EPOLLOUT will normally always
3022 * be true causing epoll_wait to return early
3023 */
3024 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3026 coap_write_endpoint(endpoint->context, endpoint, now);
3027 }
3028
3029#if !COAP_DISABLE_TCP
3030 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
3031 (events[j].events & EPOLLIN)) {
3033 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
3034 }
3035#endif /* !COAP_DISABLE_TCP */
3036
3037 } else
3038#endif /* COAP_SERVER_SUPPORT */
3039 if (sock->session) {
3040 coap_session_t *session = sock->session;
3041
3042 /* Make sure the session object is not deleted
3043 in one of the callbacks */
3045#if COAP_CLIENT_SUPPORT
3046 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
3047 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3049 coap_connect_session(session, now);
3050 if (coap_netif_available(session) &&
3051 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
3052 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3053 }
3054 }
3055#endif /* COAP_CLIENT_SUPPORT */
3056
3057 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
3058 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3059 sock->flags |= COAP_SOCKET_CAN_READ;
3060 coap_read_session(session->context, session, now);
3061 }
3062
3063 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
3064 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3065 /*
3066 * Need to update this to EPOLLIN as EPOLLOUT will normally always
3067 * be true causing epoll_wait to return early
3068 */
3069 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3071 coap_write_session(session->context, session, now);
3072 }
3073 /* Now dereference session so it can go away if needed */
3074 coap_session_release_lkd(session);
3075 }
3076 } else if (ctx->eptimerfd != -1) {
3077 /*
3078 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
3079 * it so that it does not set EPOLLIN in the next epoll_wait().
3080 */
3081 uint64_t count;
3082
3083 /* Check the result from read() to suppress the warning on
3084 * systems that declare read() with warn_unused_result. */
3085 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
3086 /* do nothing */;
3087 }
3088 }
3089 }
3090 /* And update eptimerfd as to when to next trigger */
3091 coap_ticks(&now);
3092 coap_io_prepare_epoll_lkd(ctx, now);
3093#endif /* COAP_EPOLL_SUPPORT */
3094}
3095
3096int
3098 uint8_t *msg, size_t msg_len) {
3099
3100 coap_pdu_t *pdu = NULL;
3101 coap_opt_filter_t error_opts;
3102
3103 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
3104 if (msg_len < 4) {
3105 /* Minimum size of CoAP header - ignore runt */
3106 return -1;
3107 }
3108 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
3109 /*
3110 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
3111 * this MUST be silently ignored.
3112 */
3113 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
3114 return -1;
3115 }
3116
3117 /* Need max space incase PDU is updated with updated token etc. */
3118 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
3119 if (!pdu)
3120 goto error;
3121
3122 coap_option_filter_clear(&error_opts);
3123 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
3125 coap_log_warn("discard malformed PDU\n");
3126 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
3127 coap_pdu_t *response =
3129 COAP_RESPONSE_CODE(402), &error_opts);
3130 if (!response) {
3131 coap_log_warn("coap_handle_dgram: cannot create error response\n");
3132 } else {
3133 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
3134 coap_log_warn("coap_handle_dgram: error sending response\n");
3135 }
3137 return -1;
3138 } else {
3139 goto error;
3140 }
3141 }
3142
3143 coap_dispatch(ctx, session, pdu);
3145 return 0;
3146
3147error:
3148 /*
3149 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
3150 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
3151 */
3152 coap_send_rst_lkd(session, pdu);
3154 return -1;
3155}
3156
3157int
3159 coap_bin_const_t *token, coap_queue_t **node) {
3160 coap_queue_t *p, *q;
3161
3162 if (!queue || !*queue) {
3163 *node = NULL;
3164 return 0;
3165 }
3166
3167 /* replace queue head if PDU's time is less than head's time */
3168
3169 if (session == (*queue)->session && mid == (*queue)->id &&
3170 (!token || coap_binary_equal(token, &(*queue)->pdu->actual_token))) { /* found message id */
3171 *node = *queue;
3172 *queue = (*queue)->next;
3173 if (*queue) { /* adjust relative time of new queue head */
3174 (*queue)->t += (*node)->t;
3175 }
3176 (*node)->next = NULL;
3177 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
3178 coap_session_str(session), mid);
3179 return 1;
3180 }
3181
3182 /* search message id in queue to remove (only first occurence will be removed) */
3183 q = *queue;
3184 do {
3185 p = q;
3186 q = q->next;
3187 } while (q && (session != q->session || mid != q->id ||
3188 (token && ! coap_binary_equal(token, &q->pdu->actual_token))));
3189
3190 if (q) { /* found message id */
3191 p->next = q->next;
3192 if (p->next) { /* must update relative time of p->next */
3193 p->next->t += q->t;
3194 }
3195 q->next = NULL;
3196 *node = q;
3197 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
3198 coap_session_str(session), mid);
3199 return 1;
3200 }
3201
3202 *node = NULL;
3203 return 0;
3204
3205}
3206
3207static int
3209 coap_bin_const_t *token, coap_queue_t **node) {
3210 coap_queue_t *p, *q;
3211
3212 if (!queue || !*queue)
3213 return 0;
3214
3215 /* replace queue head if PDU's time is less than head's time */
3216
3217 if (session == (*queue)->session &&
3218 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
3219 *node = *queue;
3220 *queue = (*queue)->next;
3221 if (*queue) { /* adjust relative time of new queue head */
3222 (*queue)->t += (*node)->t;
3223 }
3224 (*node)->next = NULL;
3225 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3226 coap_session_str(session), (*node)->id);
3227 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3228 session->con_active--;
3229 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3230 /* Flush out any entries on session->delayqueue */
3231 coap_session_connected(session);
3232 }
3233 return 1;
3234 }
3235
3236 /* search token in queue to remove (only first occurence will be removed) */
3237 q = *queue;
3238 do {
3239 p = q;
3240 q = q->next;
3241 } while (q && (session != q->session ||
3242 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3243
3244 if (q) { /* found token */
3245 p->next = q->next;
3246 if (p->next) { /* must update relative time of p->next */
3247 p->next->t += q->t;
3248 }
3249 q->next = NULL;
3250 *node = q;
3251 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3252 coap_session_str(session), (*node)->id);
3253 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3254 session->con_active--;
3255 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3256 /* Flush out any entries on session->delayqueue */
3257 coap_session_connected(session);
3258 }
3259 return 1;
3260 }
3261
3262 return 0;
3263
3264}
3265
3266void
3268 coap_nack_reason_t reason) {
3269 coap_queue_t *p, *q;
3270
3271 while (context->sendqueue && context->sendqueue->session == session) {
3272 q = context->sendqueue;
3273 context->sendqueue = q->next;
3274 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3275 coap_session_str(session), q->id);
3276 if (q->pdu->type == COAP_MESSAGE_CON) {
3277 coap_handle_nack(session, q->pdu, reason, q->id);
3278 }
3280 }
3281
3282 if (!context->sendqueue)
3283 return;
3284
3285 p = context->sendqueue;
3286 q = p->next;
3287
3288 while (q) {
3289 if (q->session == session) {
3290 p->next = q->next;
3291 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3292 coap_session_str(session), q->id);
3293 if (q->pdu->type == COAP_MESSAGE_CON) {
3294 coap_handle_nack(session, q->pdu, reason, q->id);
3295 }
3297 q = p->next;
3298 } else {
3299 p = q;
3300 q = q->next;
3301 }
3302 }
3303}
3304
3305void
3307 coap_bin_const_t *token) {
3308 /* cancel all messages in sendqueue that belong to session
3309 * and use the specified token */
3310 coap_queue_t **p, *q;
3311
3312 if (!context->sendqueue)
3313 return;
3314
3315 p = &context->sendqueue;
3316 q = *p;
3317
3318 while (q) {
3319 if (q->session == session &&
3320 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3321 *p = q->next;
3322 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3323 coap_session_str(session), q->id);
3324 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3325 session->con_active--;
3326 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3327 /* Flush out any entries on session->delayqueue */
3328 coap_session_connected(session);
3329 }
3331 } else {
3332 p = &(q->next);
3333 }
3334 q = *p;
3335 }
3336}
3337
3338coap_pdu_t *
3340 coap_opt_filter_t *opts) {
3341 coap_opt_iterator_t opt_iter;
3342 coap_pdu_t *response;
3343 unsigned char type;
3344
3345#if COAP_ERROR_PHRASE_LENGTH > 0
3346 const char *phrase;
3347 if (code != COAP_RESPONSE_CODE(508)) {
3348 phrase = coap_response_phrase(code);
3349 } else {
3350 phrase = NULL;
3351 }
3352#endif
3353
3354 assert(request);
3355
3356 /* cannot send ACK if original request was not confirmable */
3357 type = request->type == COAP_MESSAGE_CON ?
3359
3360 /* Now create the response and fill with options and payload data. */
3361 response = coap_pdu_init(type, code, request->mid,
3362 request->session ?
3363 coap_session_max_pdu_size_lkd(request->session) : 512);
3364 if (response) {
3365 /* copy token */
3366 if (request->actual_token.length &&
3367 !coap_add_token(response, request->actual_token.length,
3368 request->actual_token.s)) {
3369 coap_log_debug("cannot add token to error response\n");
3370 coap_delete_pdu_lkd(response);
3371 return NULL;
3372 }
3373 if (response->code == COAP_RESPONSE_CODE(402)) {
3374 char buf[128];
3375 int first = 1;
3376 int i;
3377 size_t len;
3378
3379#if COAP_ERROR_PHRASE_LENGTH > 0
3380 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3381#else
3382 buf[0] = '\000';
3383#endif
3384 /* copy all reported options into diagnostic message */
3385 for (i = COAP_OPT_FILTER_SHORT - 1; i >= 0; i--) {
3386 if (opts->mask & (1 << (COAP_OPT_FILTER_LONG + i))) {
3387 len = strlen(buf);
3388 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",",
3389 opts->short_opts[i]);
3390 first = 0;
3391 }
3392 }
3393 for (i = COAP_OPT_FILTER_LONG - 1; i >= 0; i--) {
3394 if (opts->mask & (1 << i)) {
3395 len = strlen(buf);
3396 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",",
3397 opts->long_opts[i]);
3398 first = 0;
3399 }
3400 }
3401 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3402 } else if (opts && opts->mask) {
3403 coap_opt_t *option;
3404
3405 /* copy all options */
3406 coap_option_iterator_init(request, &opt_iter, opts);
3407 while ((option = coap_option_next(&opt_iter))) {
3408 coap_add_option_internal(response, opt_iter.number,
3409 coap_opt_length(option),
3410 coap_opt_value(option));
3411 }
3412#if COAP_ERROR_PHRASE_LENGTH > 0
3413 if (phrase)
3414 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3415 } else {
3416 /* note that diagnostic messages do not need a Content-Format option. */
3417 if (phrase)
3418 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3419#endif
3420 }
3421 }
3422
3423 return response;
3424}
3425
3426#if COAP_SERVER_SUPPORT
3427#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3428
3429static void
3430free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3431 coap_delete_string(app_ptr);
3432}
3433
3434/*
3435 * Caution: As this handler is in libcoap space, it is called with
3436 * context locked.
3437 */
3438static void
3439hnd_get_wellknown_lkd(coap_resource_t *resource,
3440 coap_session_t *session,
3441 const coap_pdu_t *request,
3442 const coap_string_t *query,
3443 coap_pdu_t *response) {
3444 size_t len = 0;
3445 coap_string_t *data_string = NULL;
3446 coap_print_status_t result = 0;
3447 size_t wkc_len = 0;
3448 uint8_t buf[4];
3449
3450 /*
3451 * Quick hack to determine the size of the resource descriptions for
3452 * .well-known/core.
3453 */
3454 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3455 if (result & COAP_PRINT_STATUS_ERROR) {
3456 coap_log_warn("cannot determine length of /.well-known/core\n");
3457 goto error;
3458 }
3459
3460 if (wkc_len > 0) {
3461 data_string = coap_new_string(wkc_len);
3462 if (!data_string)
3463 goto error;
3464
3465 len = wkc_len;
3466 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3467 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3468 coap_log_debug("coap_print_wellknown failed\n");
3469 goto error;
3470 }
3471 assert(len <= (size_t)wkc_len);
3472 data_string->length = len;
3473
3474 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3476 coap_encode_var_safe(buf, sizeof(buf),
3478 goto error;
3479 }
3480 if (response->used_size + len + 1 > response->max_size) {
3481 /*
3482 * Data does not fit into a packet and no libcoap block support
3483 * +1 for end of options marker
3484 */
3485 coap_log_debug(".well-known/core: truncating data length to %" PRIuS " from %" PRIuS "\n",
3486 len, response->max_size - response->used_size - 1);
3487 len = response->max_size - response->used_size - 1;
3488 }
3489 if (!coap_add_data(response, len, data_string->s)) {
3490 goto error;
3491 }
3492 free_wellknown_response(session, data_string);
3493 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3494 response, query,
3496 -1, 0, data_string->length,
3497 data_string->s,
3498 free_wellknown_response,
3499 data_string)) {
3500 goto error_released;
3501 }
3502 } else {
3504 coap_encode_var_safe(buf, sizeof(buf),
3506 goto error;
3507 }
3508 }
3509 response->code = COAP_RESPONSE_CODE(205);
3510 return;
3511
3512error:
3513 free_wellknown_response(session, data_string);
3514error_released:
3515 if (response->code == 0) {
3516 /* set error code 5.03 and remove all options and data from response */
3517 response->code = COAP_RESPONSE_CODE(503);
3518 response->used_size = response->e_token_length;
3519 response->data = NULL;
3520 }
3521}
3522#endif /* COAP_SERVER_SUPPORT */
3523
3534static int
3536 int num_cancelled = 0; /* the number of observers cancelled */
3537
3538#ifndef COAP_SERVER_SUPPORT
3539 (void)sent;
3540#endif /* ! COAP_SERVER_SUPPORT */
3541 (void)context;
3542
3543#if COAP_SERVER_SUPPORT
3544 /* remove observer for this resource, if any
3545 * Use token from sent and try to find a matching resource. Uh!
3546 */
3547 RESOURCES_ITER(context->resources, r) {
3548 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3549 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3550 }
3551#endif /* COAP_SERVER_SUPPORT */
3552
3553 return num_cancelled;
3554}
3555
3556#if COAP_SERVER_SUPPORT
3561enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3562
3563/*
3564 * Checks for No-Response option in given @p request and
3565 * returns @c RESPONSE_DROP if @p response should be suppressed
3566 * according to RFC 7967.
3567 *
3568 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3569 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3570 * on retrying.
3571 *
3572 * Checks if the response code is 0.00 and if either the session is reliable or
3573 * non-confirmable, @c RESPONSE_DROP is also returned.
3574 *
3575 * Multicast response checking is also carried out.
3576 *
3577 * NOTE: It is the responsibility of the application to determine whether
3578 * a delayed separate response should be sent as the original requesting packet
3579 * containing the No-Response option has long since gone.
3580 *
3581 * The value of the No-Response option is encoded as
3582 * follows:
3583 *
3584 * @verbatim
3585 * +-------+-----------------------+-----------------------------------+
3586 * | Value | Binary Representation | Description |
3587 * +-------+-----------------------+-----------------------------------+
3588 * | 0 | <empty> | Interested in all responses. |
3589 * +-------+-----------------------+-----------------------------------+
3590 * | 2 | 00000010 | Not interested in 2.xx responses. |
3591 * +-------+-----------------------+-----------------------------------+
3592 * | 8 | 00001000 | Not interested in 4.xx responses. |
3593 * +-------+-----------------------+-----------------------------------+
3594 * | 16 | 00010000 | Not interested in 5.xx responses. |
3595 * +-------+-----------------------+-----------------------------------+
3596 * @endverbatim
3597 *
3598 * @param request The CoAP request to check for the No-Response option.
3599 * This parameter must not be NULL.
3600 * @param response The response that is potentially suppressed.
3601 * This parameter must not be NULL.
3602 * @param session The session this request/response are associated with.
3603 * This parameter must not be NULL.
3604 * @return RESPONSE_DEFAULT when no special treatment is requested,
3605 * RESPONSE_DROP when the response must be discarded, or
3606 * RESPONSE_SEND when the response must be sent.
3607 */
3608static enum respond_t
3609no_response(coap_pdu_t *request, coap_pdu_t *response,
3610 coap_session_t *session, coap_resource_t *resource) {
3611 coap_opt_t *nores;
3612 coap_opt_iterator_t opt_iter;
3613 unsigned int val = 0;
3614
3615 assert(request);
3616 assert(response);
3617
3618 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3619 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3620
3621 if (nores) {
3623
3624 /* The response should be dropped when the bit corresponding to
3625 * the response class is set (cf. table in function
3626 * documentation). When a No-Response option is present and the
3627 * bit is not set, the sender explicitly indicates interest in
3628 * this response. */
3629 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3630 /* Should be dropping the response */
3631 if (response->type == COAP_MESSAGE_ACK &&
3632 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3633 /* Still need to ACK the request */
3634 response->code = 0;
3635 /* Remove token/data from piggybacked acknowledgment PDU */
3636 response->actual_token.length = 0;
3637 response->e_token_length = 0;
3638 response->used_size = 0;
3639 response->data = NULL;
3640 return RESPONSE_SEND;
3641 } else {
3642 return RESPONSE_DROP;
3643 }
3644 } else {
3645 /* True for mcast as well RFC7967 2.1 */
3646 return RESPONSE_SEND;
3647 }
3648 } else if (resource && session->context->mcast_per_resource &&
3649 coap_is_mcast(&session->addr_info.local)) {
3650 /* Handle any mcast suppression specifics if no NoResponse option */
3651 if ((resource->flags &
3653 COAP_RESPONSE_CLASS(response->code) == 2) {
3654 return RESPONSE_DROP;
3655 } else if ((resource->flags &
3657 response->code == COAP_RESPONSE_CODE(205)) {
3658 if (response->data == NULL)
3659 return RESPONSE_DROP;
3660 } else if ((resource->flags &
3662 COAP_RESPONSE_CLASS(response->code) == 4) {
3663 return RESPONSE_DROP;
3664 } else if ((resource->flags &
3666 COAP_RESPONSE_CLASS(response->code) == 5) {
3667 return RESPONSE_DROP;
3668 }
3669 }
3670 } else if (COAP_PDU_IS_EMPTY(response) &&
3671 (response->type == COAP_MESSAGE_NON ||
3672 COAP_PROTO_RELIABLE(session->proto))) {
3673 /* response is 0.00, and this is reliable or non-confirmable */
3674 return RESPONSE_DROP;
3675 }
3676
3677 /*
3678 * Do not send error responses for requests that were received via
3679 * IP multicast. RFC7252 8.1
3680 */
3681
3682 if (coap_is_mcast(&session->addr_info.local)) {
3683 if (request->type == COAP_MESSAGE_NON &&
3684 response->type == COAP_MESSAGE_RST)
3685 return RESPONSE_DROP;
3686
3687 if ((!resource || session->context->mcast_per_resource == 0) &&
3688 COAP_RESPONSE_CLASS(response->code) > 2)
3689 return RESPONSE_DROP;
3690 }
3691
3692 /* Default behavior applies when we are not dealing with a response
3693 * (class == 0) or the request did not contain a No-Response option.
3694 */
3695 return RESPONSE_DEFAULT;
3696}
3697
3698static coap_str_const_t coap_default_uri_wellknown = {
3700 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3701};
3702
3703/* Initialized in coap_startup() */
3704static coap_resource_t resource_uri_wellknown;
3705
3706static void
3707handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3708 coap_pdu_t *orig_pdu) {
3710 coap_pdu_t *response = NULL;
3711 coap_opt_filter_t opt_filter;
3712 coap_resource_t *resource = NULL;
3713 /* The respond field indicates whether a response must be treated
3714 * specially due to a No-Response option that declares disinterest
3715 * or interest in a specific response class. DEFAULT indicates that
3716 * No-Response has not been specified. */
3717 enum respond_t respond = RESPONSE_DEFAULT;
3718 coap_opt_iterator_t opt_iter;
3719 coap_opt_t *opt;
3720 int is_proxy_uri = 0;
3721 int is_proxy_scheme = 0;
3722 int skip_hop_limit_check = 0;
3723 int resp = 0;
3724 coap_string_t *query = NULL;
3725 coap_opt_t *observe = NULL;
3726 coap_string_t *uri_path = NULL;
3727 int observe_action = COAP_OBSERVE_CANCEL;
3728 coap_block_b_t block;
3729 int added_block = 0;
3730 coap_lg_srcv_t *free_lg_srcv = NULL;
3731#if COAP_Q_BLOCK_SUPPORT
3732 int lg_xmit_ctrl = 0;
3733#endif /* COAP_Q_BLOCK_SUPPORT */
3734#if COAP_ASYNC_SUPPORT
3735 coap_async_t *async;
3736#endif /* COAP_ASYNC_SUPPORT */
3737
3738#if COAP_ASYNC_SUPPORT
3739 async = coap_find_async_lkd(session, pdu->actual_token);
3740 if (async) {
3741 coap_tick_t now;
3742
3743 coap_ticks(&now);
3744 if (async->delay == 0 || async->delay > now) {
3745 /* re-transmit missing ACK (only if CON) */
3746 coap_log_info("Retransmit async response\n");
3747 coap_send_ack_lkd(session, pdu);
3748 /* and do not pass on to the upper layers */
3749 return;
3750 }
3751 }
3752#endif /* COAP_ASYNC_SUPPORT */
3753
3754 coap_option_filter_clear(&opt_filter);
3755 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3756 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3757 if (opt) {
3758 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3759 if (!opt) {
3760 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3761 resp = 402;
3762 goto fail_response;
3763 }
3764 is_proxy_scheme = 1;
3765 }
3766
3767 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3768 if (opt)
3769 is_proxy_uri = 1;
3770 }
3771
3772 if (is_proxy_scheme || is_proxy_uri) {
3773 coap_uri_t uri;
3774
3775 if (!context->proxy_uri_resource) {
3776 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3777 coap_log_debug("Proxy-%s support not configured\n",
3778 is_proxy_scheme ? "Scheme" : "Uri");
3779 resp = 505;
3780 goto fail_response;
3781 }
3782 if (((size_t)pdu->code - 1 <
3783 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3784 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3785 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3786 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3787 is_proxy_scheme ? "Scheme" : "Uri",
3788 pdu->code/100, pdu->code%100);
3789 resp = 505;
3790 goto fail_response;
3791 }
3792
3793 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3794 if (is_proxy_uri) {
3796 coap_opt_length(opt), &uri) < 0) {
3797 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3798 coap_log_debug("Proxy-URI not decodable\n");
3799 resp = 505;
3800 goto fail_response;
3801 }
3802 } else {
3803 memset(&uri, 0, sizeof(uri));
3804 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3805 if (opt) {
3806 uri.host.length = coap_opt_length(opt);
3807 uri.host.s = coap_opt_value(opt);
3808 } else
3809 uri.host.length = 0;
3810 }
3811
3812 resource = context->proxy_uri_resource;
3813 if (uri.host.length && resource->proxy_name_count &&
3814 resource->proxy_name_list) {
3815 size_t i;
3816
3817 if (resource->proxy_name_count == 1 &&
3818 resource->proxy_name_list[0]->length == 0) {
3819 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3820 i = 0;
3821 } else {
3822 for (i = 0; i < resource->proxy_name_count; i++) {
3823 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3824 break;
3825 }
3826 }
3827 }
3828 if (i != resource->proxy_name_count) {
3829 /* This server is hosting the proxy connection endpoint */
3830 if (pdu->crit_opt) {
3831 /* Cannot handle critical option */
3832 pdu->crit_opt = 0;
3833 resp = 402;
3834 resource = NULL;
3835 goto fail_response;
3836 }
3837 is_proxy_uri = 0;
3838 is_proxy_scheme = 0;
3839 skip_hop_limit_check = 1;
3840 }
3841 }
3842 resource = NULL;
3843 }
3844 assert(resource == NULL);
3845
3846 if (!skip_hop_limit_check) {
3847 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3848 if (opt) {
3849 size_t hop_limit;
3850 uint8_t buf[4];
3851
3852 hop_limit =
3854 if (hop_limit == 1) {
3855 /* coap_send_internal() will fill in the IP address for us */
3856 resp = 508;
3857 goto fail_response;
3858 } else if (hop_limit < 1 || hop_limit > 255) {
3859 /* Need to return a 4.00 RFC8768 Section 3 */
3860 coap_log_info("Invalid Hop Limit\n");
3861 resp = 400;
3862 goto fail_response;
3863 }
3864 hop_limit--;
3866 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3867 buf);
3868 }
3869 }
3870
3871 uri_path = coap_get_uri_path(pdu);
3872 if (!uri_path) {
3873 resp = 402;
3874 goto fail_response;
3875 }
3876
3877 if (!is_proxy_uri && !is_proxy_scheme) {
3878 /* try to find the resource from the request URI */
3879 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3880 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3881 }
3882
3883 if ((resource == NULL) || (resource->is_unknown == 1) ||
3884 (resource->is_proxy_uri == 1)) {
3885 /* The resource was not found or there is an unexpected match against the
3886 * resource defined for handling unknown or proxy URIs.
3887 */
3888 if (resource != NULL)
3889 /* Close down unexpected match */
3890 resource = NULL;
3891 /*
3892 * Check if the request URI happens to be the well-known URI, or if the
3893 * unknown resource handler is defined, a PUT or optionally other methods,
3894 * if configured, for the unknown handler.
3895 *
3896 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3897 * proxy URI handler.
3898 *
3899 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3900 * set, call the unknown URI handler with any unknown URI (including
3901 * .well-known/core) if the appropriate method is defined.
3902 *
3903 * else if well-known URI generate a default response.
3904 *
3905 * else if unknown URI handler defined, call the unknown
3906 * URI handler (to allow for potential generation of resource
3907 * [RFC7272 5.8.3]) if the appropriate method is defined.
3908 *
3909 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3910 *
3911 * else return 4.04.
3912 */
3913
3914 if (is_proxy_uri || is_proxy_scheme) {
3915 resource = context->proxy_uri_resource;
3916 } else if (context->unknown_resource != NULL &&
3917 context->unknown_resource->flags & COAP_RESOURCE_HANDLE_WELLKNOWN_CORE &&
3918 ((size_t)pdu->code - 1 <
3919 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3920 (context->unknown_resource->handler[pdu->code - 1])) {
3921 resource = context->unknown_resource;
3922 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3923 /* request for .well-known/core */
3924 resource = &resource_uri_wellknown;
3925 } else if ((context->unknown_resource != NULL) &&
3926 ((size_t)pdu->code - 1 <
3927 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3928 (context->unknown_resource->handler[pdu->code - 1])) {
3929 /*
3930 * The unknown_resource can be used to handle undefined resources
3931 * for a PUT request and can support any other registered handler
3932 * defined for it
3933 * Example set up code:-
3934 * r = coap_resource_unknown_init(hnd_put_unknown);
3935 * coap_register_request_handler(r, COAP_REQUEST_POST,
3936 * hnd_post_unknown);
3937 * coap_register_request_handler(r, COAP_REQUEST_GET,
3938 * hnd_get_unknown);
3939 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3940 * hnd_delete_unknown);
3941 * coap_add_resource(ctx, r);
3942 *
3943 * Note: It is not possible to observe the unknown_resource, a separate
3944 * resource must be created (by PUT or POST) which has a GET
3945 * handler to be observed
3946 */
3947 resource = context->unknown_resource;
3948 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3949 /*
3950 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3951 */
3952 coap_log_debug("request for unknown resource '%*.*s',"
3953 " return 2.02\n",
3954 (int)uri_path->length,
3955 (int)uri_path->length,
3956 uri_path->s);
3957 resp = 202;
3958 goto fail_response;
3959 } else if (context->dyn_create_handler != NULL) {
3960 resource = coap_add_dynamic_resource(session, pdu);
3961 if (!resource) {
3962 resp = 406;
3963 goto fail_response;
3964 }
3965 } else { /* request for any another resource, return 4.04 */
3966
3967 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3968 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3969 resp = 404;
3970 goto fail_response;
3971 }
3972
3973 }
3974
3975 coap_resource_reference_lkd(resource);
3976
3977#if COAP_OSCORE_SUPPORT
3978 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3979 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3980 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3981 resp = 401;
3982 goto fail_response;
3983 }
3984#endif /* COAP_OSCORE_SUPPORT */
3985 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3986 /* Check for existing resource and If-Non-Match */
3987 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3988 if (opt) {
3989 resp = 412;
3990 goto fail_response;
3991 }
3992 }
3993
3994 /* the resource was found, check if there is a registered handler */
3995 if ((size_t)pdu->code - 1 <
3996 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3997 h = resource->handler[pdu->code - 1];
3998
3999 if (h == NULL) {
4000 resp = 405;
4001 goto fail_response;
4002 }
4003 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
4004 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) == NULL) {
4005 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
4006 if (opt == NULL) {
4007 /* RFC 8132 2.3.1 */
4008 resp = 415;
4009 goto fail_response;
4010 }
4011 }
4012 }
4013 if (context->mcast_per_resource &&
4014 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
4015 coap_is_mcast(&session->addr_info.local)) {
4016 resp = 405;
4017 goto fail_response;
4018 }
4019
4020 if (pdu->type == COAP_MESSAGE_CON) {
4021 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, pdu->mid,
4023 } else {
4026 }
4027 if (!response) {
4028 coap_log_err("could not create response PDU\n");
4029 resp = 500;
4030 goto fail_response;
4031 }
4032 response->session = session;
4033#if COAP_ASYNC_SUPPORT
4034 /* If handling a separate response, need CON, not ACK response */
4035 if (async && pdu->type == COAP_MESSAGE_CON)
4036 response->type = COAP_MESSAGE_CON;
4037#endif /* COAP_ASYNC_SUPPORT */
4038 /* A lot of the reliable code assumes type is CON */
4039 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
4040 response->type = COAP_MESSAGE_CON;
4041
4042 if (!coap_add_token(response, pdu->actual_token.length,
4043 pdu->actual_token.s)) {
4044 resp = 500;
4045 goto fail_response;
4046 }
4047
4048 query = coap_get_query(pdu);
4049
4050 /* check for Observe option RFC7641 and RFC8132 */
4051 if (resource->observable &&
4052 (pdu->code == COAP_REQUEST_CODE_GET ||
4053 pdu->code == COAP_REQUEST_CODE_FETCH)) {
4054 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
4055 }
4056
4057 /*
4058 * See if blocks need to be aggregated or next requests sent off
4059 * before invoking application request handler
4060 */
4061 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4062 uint32_t block_mode = session->block_mode;
4063
4064 if (observe ||
4065 resource->flags & COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY)
4067 if (coap_handle_request_put_block(context, session, pdu, response,
4068 resource, uri_path, observe,
4069 &added_block, &free_lg_srcv)) {
4070 session->block_mode = block_mode;
4071 goto skip_handler;
4072 }
4073 session->block_mode = block_mode;
4074
4075 if (coap_handle_request_send_block(session, pdu, response, resource,
4076 query)) {
4077#if COAP_Q_BLOCK_SUPPORT
4078 lg_xmit_ctrl = 1;
4079#endif /* COAP_Q_BLOCK_SUPPORT */
4080 goto skip_handler;
4081 }
4082 }
4083
4084 if (observe) {
4085 observe_action =
4087 coap_opt_length(observe));
4088
4089 if (observe_action == COAP_OBSERVE_ESTABLISH) {
4090 coap_subscription_t *subscription;
4091
4092 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
4093 if (block.num != 0) {
4094 response->code = COAP_RESPONSE_CODE(400);
4095 goto skip_handler;
4096 }
4097#if COAP_Q_BLOCK_SUPPORT
4098 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
4099 &block)) {
4100 if (block.num != 0) {
4101 response->code = COAP_RESPONSE_CODE(400);
4102 goto skip_handler;
4103 }
4104#endif /* COAP_Q_BLOCK_SUPPORT */
4105 }
4106 subscription = coap_add_observer(resource, session, &pdu->actual_token,
4107 pdu);
4108 if (subscription) {
4109 uint8_t buf[4];
4110
4111 coap_touch_observer(context, session, &pdu->actual_token);
4113 coap_encode_var_safe(buf, sizeof(buf),
4114 resource->observe),
4115 buf);
4116 }
4117 } else if (observe_action == COAP_OBSERVE_CANCEL) {
4118 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
4119 } else {
4120 coap_log_info("observe: unexpected action %d\n", observe_action);
4121 }
4122 }
4123
4124#if COAP_WITH_OBSERVE_PERSIST
4125 /* If we are maintaining Observe persist */
4126 if (resource == context->unknown_resource) {
4127 context->unknown_pdu = pdu;
4128 context->unknown_session = session;
4129 } else
4130 context->unknown_pdu = NULL;
4131#endif /* COAP_WITH_OBSERVE_PERSIST */
4132
4133 /*
4134 * Call the request handler with everything set up
4135 */
4136 if (resource == &resource_uri_wellknown) {
4137 /* Leave context locked */
4138 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
4139 (int)resource->uri_path->length, (int)resource->uri_path->length,
4140 resource->uri_path->s);
4141 h(resource, session, pdu, query, response);
4142 } else {
4143 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
4144 (int)resource->uri_path->length, (int)resource->uri_path->length,
4145 resource->uri_path->s);
4146 if (resource->flags & COAP_RESOURCE_SAFE_REQUEST_HANDLER) {
4147 coap_lock_callback_release(h(resource, session, pdu, query, response),
4148 /* context is being freed off */
4149 goto finish);
4150 } else {
4152 h(resource, session, pdu, query, response),
4153 /* context is being freed off */
4154 goto finish);
4155 }
4156 }
4157
4158 /* Check validity of response code */
4159 if (!coap_check_code_class(session, response)) {
4160 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
4161 COAP_RESPONSE_CLASS(response->code),
4162 response->code & 0x1f);
4163 goto drop_it_no_debug;
4164 }
4165
4166 /* Check if lg_xmit generated and update PDU code if so */
4167 coap_check_code_lg_xmit(session, pdu, response, resource, query);
4168
4169 if (free_lg_srcv) {
4170 /* Check to see if the server is doing a 4.01 + Echo response */
4171 if (response->code == COAP_RESPONSE_CODE(401) &&
4172 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
4173 /* Need to keep lg_srcv around for client's response */
4174 } else {
4175 coap_lg_srcv_t *lg_srcv;
4176 /*
4177 * Need to check free_lg_srcv still exists in case of error or timing window
4178 */
4179 LL_FOREACH(session->lg_srcv, lg_srcv) {
4180 if (lg_srcv == free_lg_srcv) {
4181#if COAP_Q_BLOCK_SUPPORT
4182 if (lg_srcv->block_option == COAP_OPTION_Q_BLOCK1) {
4183 coap_tick_t adjust;
4184
4185 /* cache the lg_srcv for 1 second */
4188 } else {
4189 adjust = 0;
4190 }
4191 coap_ticks(&free_lg_srcv->rec_blocks.last_seen);
4192 if (free_lg_srcv->rec_blocks.last_seen > adjust) {
4193 free_lg_srcv->rec_blocks.last_seen -= adjust;
4194 }
4195 free_lg_srcv->dont_timeout = 0;
4196 break;
4197 }
4198#endif /* COAP_Q_BLOCK_SUPPORT */
4199 LL_DELETE(session->lg_srcv, free_lg_srcv);
4200 coap_block_delete_lg_srcv(session, free_lg_srcv);
4201 break;
4202 }
4203 }
4204 }
4205 }
4206 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
4207 /* Just in case, as there are more to go */
4208 response->code = COAP_RESPONSE_CODE(231);
4209 }
4210
4211skip_handler:
4212 respond = no_response(pdu, response, session, resource);
4213 if (respond != RESPONSE_DROP) {
4214#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
4215 coap_mid_t mid = pdu->mid;
4216#endif
4217 if (COAP_RESPONSE_CLASS(response->code) != 2) {
4218 if (observe) {
4220 }
4221 }
4222 if (COAP_RESPONSE_CLASS(response->code) > 2) {
4223 if (observe)
4224 coap_delete_observer(resource, session, &pdu->actual_token);
4225 if (response->code != COAP_RESPONSE_CODE(413))
4227 }
4228
4229 /* If original request contained a token, and the registered
4230 * application handler made no changes to the response, then
4231 * this is an empty ACK with a token, which is a malformed
4232 * PDU */
4233 if ((response->type == COAP_MESSAGE_ACK)
4234 && (response->code == 0)) {
4235 /* Remove token from otherwise-empty acknowledgment PDU */
4236 response->actual_token.length = 0;
4237 response->e_token_length = 0;
4238 response->used_size = 0;
4239 response->data = NULL;
4240 }
4241
4242 if (!coap_is_mcast(&session->addr_info.local) ||
4243 (context->mcast_per_resource &&
4244 resource &&
4245 (resource->flags & COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS))) {
4246 /* No delays to response */
4247#if COAP_Q_BLOCK_SUPPORT
4248 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4249 !lg_xmit_ctrl && COAP_RESPONSE_CLASS(response->code) == 2 &&
4250 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4251 block.m) {
4252 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4253 response,
4254 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4255 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4256 response = NULL;
4257 goto finish;
4258 }
4259#endif /* COAP_Q_BLOCK_SUPPORT */
4260 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4261 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4262 goto finish;
4263 }
4264 } else {
4265 /* Need to delay mcast response */
4266 coap_queue_t *node = coap_new_node();
4267 uint8_t r;
4268 coap_tick_t delay;
4269
4270 if (!node) {
4271 coap_log_debug("mcast delay: insufficient memory\n");
4272 goto drop_it_no_debug;
4273 }
4274 if (!coap_pdu_encode_header(response, session->proto)) {
4276 goto drop_it_no_debug;
4277 }
4278
4279 node->id = response->mid;
4280 node->pdu = response;
4281 node->is_mcast = 1;
4282 coap_prng_lkd(&r, sizeof(r));
4283 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4284 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4285 coap_session_str(session),
4286 response->mid,
4287 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4288 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4289 1000 / COAP_TICKS_PER_SECOND));
4290 node->timeout = (unsigned int)delay;
4291 /* Use this to delay transmission */
4292 coap_wait_ack(session->context, session, node);
4293 }
4294 } else if (COAP_PDU_IS_EMPTY(response) &&
4295 (response->type == COAP_MESSAGE_NON ||
4296 COAP_PROTO_RELIABLE(session->proto))) {
4297 coap_delete_pdu_lkd(response);
4298 } else {
4299 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4300 coap_session_str(session),
4301 response->mid);
4302 coap_show_pdu(COAP_LOG_DEBUG, response);
4303drop_it_no_debug:
4304 coap_delete_pdu_lkd(response);
4305 }
4306#if COAP_Q_BLOCK_SUPPORT
4307 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4308 if (COAP_PROTO_RELIABLE(session->proto)) {
4309 if (block.m) {
4310 /* All of the sequence not in yet */
4311 goto finish;
4312 }
4313 } else if (pdu->type == COAP_MESSAGE_NON) {
4314 /* More to go and not at a payload break */
4315 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4316 goto finish;
4317 }
4318 }
4319 }
4320#endif /* COAP_Q_BLOCK_SUPPORT */
4321
4322finish:
4323 if (query)
4324 coap_delete_string(query);
4325 if (resource)
4326 coap_resource_release_lkd(resource);
4327 coap_delete_string(uri_path);
4328 return;
4329
4330fail_response:
4331 coap_delete_pdu_lkd(response);
4332 response =
4334 &opt_filter);
4335 if (response)
4336 goto skip_handler;
4337 if (resource)
4338 coap_resource_release_lkd(resource);
4339 coap_delete_string(uri_path);
4340}
4341#endif /* COAP_SERVER_SUPPORT */
4342
4343#if COAP_CLIENT_SUPPORT
4344/* Call application-specific response handler when available. */
4345void
4347 coap_pdu_t *sent, coap_pdu_t *rcvd,
4348 void *body_data) {
4349 coap_context_t *context = session->context;
4350 coap_response_t ret;
4351
4352#if COAP_PROXY_SUPPORT
4353 if (context->proxy_response_cb) {
4354 coap_proxy_entry_t *proxy_entry;
4355 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4356 rcvd,
4357 &proxy_entry);
4358
4359 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4360 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4361 proxy_entry);
4362 return;
4363 }
4364 }
4365#endif /* COAP_PROXY_SUPPORT */
4366 if (session->doing_send_recv && session->req_token &&
4367 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4368 /* processing coap_send_recv() call */
4369 session->resp_pdu = rcvd;
4371 /* Will get freed off when PDU is freed off */
4372 rcvd->data_free = body_data;
4373 coap_send_ack_lkd(session, rcvd);
4375 return;
4376 } else if (context->response_cb) {
4378 context->response_cb(session,
4379 sent,
4380 rcvd,
4381 rcvd->mid),
4382 /* context is being freed off */
4383 return);
4384 } else {
4385 ret = COAP_RESPONSE_OK;
4386 }
4387 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4388 coap_send_rst_lkd(session, rcvd);
4390 } else {
4391 coap_send_ack_lkd(session, rcvd);
4393 }
4394 coap_free_type(COAP_STRING, body_data);
4395}
4396
4397static void
4398handle_response(coap_context_t *context, coap_session_t *session,
4399 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4400
4401 /* Set in case there is a later call to coap_update_token() */
4402 rcvd->session = session;
4403
4404 /* Check for message duplication */
4405 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4406 if (rcvd->type == COAP_MESSAGE_CON) {
4407 if (rcvd->mid == session->last_resp_mid) {
4408 /* Duplicate response: send ACK/RST, but don't process */
4409 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4410 coap_send_ack_lkd(session, rcvd);
4411 else
4412 coap_send_rst_lkd(session, rcvd);
4413 return;
4414 }
4415 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4416 if (rcvd->mid == session->last_resp_mid) {
4417 /* Duplicate response */
4418 return;
4419 }
4420 }
4421 session->last_resp_mid = rcvd->mid;
4422 }
4423 /* Check to see if checking out extended token support */
4424 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4425 session->last_token) {
4426 coap_lg_crcv_t *lg_crcv;
4427
4428 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4429 rcvd->actual_token.length != session->max_token_size ||
4430 rcvd->code == COAP_RESPONSE_CODE(400) ||
4431 rcvd->code == COAP_RESPONSE_CODE(503)) {
4432 coap_log_debug("Extended Token requested size support not available\n");
4434 } else {
4435 coap_log_debug("Extended Token support available\n");
4436 }
4438 /* Need to remove lg_crcv set up for this test */
4439 lg_crcv = coap_find_lg_crcv(session, rcvd);
4440 if (lg_crcv) {
4441 LL_DELETE(session->lg_crcv, lg_crcv);
4442 coap_block_delete_lg_crcv(session, lg_crcv);
4443 }
4444 coap_send_ack_lkd(session, rcvd);
4445 coap_reset_doing_first(session);
4446 return;
4447 }
4448#if COAP_Q_BLOCK_SUPPORT
4449 /* Check to see if checking out Q-Block support */
4450 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
4451 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4452 coap_log_debug("Q-Block support not available\n");
4453 set_block_mode_drop_q(session->block_mode);
4454 } else {
4455 coap_block_b_t qblock;
4456
4457 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4458 coap_log_debug("Q-Block support available\n");
4459 set_block_mode_has_q(session->block_mode);
4460 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4461 /* Flush out any entries on session->delayqueue */
4462 coap_session_connected(session);
4463 } else {
4464 coap_log_debug("Q-Block support not available\n");
4465 set_block_mode_drop_q(session->block_mode);
4466 }
4467 }
4468 coap_send_ack_lkd(session, rcvd);
4469 coap_reset_doing_first(session);
4470 return;
4471 }
4472#endif /* COAP_Q_BLOCK_SUPPORT */
4473
4474 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4475 /* See if need to send next block to server */
4476 if (coap_handle_response_send_block(session, sent, rcvd)) {
4477 /* Next block transmitted, no need to inform app */
4478 coap_send_ack_lkd(session, rcvd);
4479 return;
4480 }
4481
4482 /* Need to see if needing to request next block */
4483 if (coap_handle_response_get_block(context, session, sent, rcvd,
4484 COAP_RECURSE_OK)) {
4485 /* Next block transmitted, ack sent no need to inform app */
4486 return;
4487 }
4488 }
4489 coap_reset_doing_first(session);
4490
4491 /* Call application-specific response handler when available. */
4492 coap_call_response_handler(session, sent, rcvd, NULL);
4493}
4494#endif /* COAP_CLIENT_SUPPORT */
4495
4496#if !COAP_DISABLE_TCP
4497static void
4499 coap_pdu_t *pdu) {
4500 coap_opt_iterator_t opt_iter;
4501 coap_opt_t *option;
4502 int set_mtu = 0;
4503
4504 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4505
4506 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4507 if (session->csm_not_seen) {
4508 coap_tick_t now;
4509
4510 coap_ticks(&now);
4511 /* CSM timeout before CSM seen */
4512 coap_log_warn("***%s: CSM received after CSM timeout\n",
4513 coap_session_str(session));
4514 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4515 coap_session_str(session),
4516 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4517 }
4518 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4520 }
4521 while ((option = coap_option_next(&opt_iter))) {
4522 unsigned max_recv;
4523
4524 switch ((coap_sig_csm_opt_t)opt_iter.number) {
4526 max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4527 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4529 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4530 coap_session_str(session), max_recv);
4531 }
4532 coap_session_set_mtu(session, max_recv);
4533 set_mtu = 1;
4534 break;
4536 session->csm_block_supported = 1;
4537 break;
4539 session->max_token_size =
4541 coap_opt_length(option));
4544 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4547 break;
4548 default:
4549 break;
4550 }
4551 }
4552 if (set_mtu) {
4553 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4554 session->csm_bert_rem_support = 1;
4555 else
4556 session->csm_bert_rem_support = 0;
4557 }
4558 if (session->state == COAP_SESSION_STATE_CSM)
4559 coap_session_connected(session);
4560 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4562 if (context->ping_cb) {
4563 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4564 }
4565 if (pong) {
4567 0, NULL);
4568 coap_send_internal(session, pong, NULL);
4569 }
4570 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4571 session->last_pong = session->last_rx_tx;
4572 session->ping_failed = 0;
4573 if (context->pong_cb) {
4574 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4575 }
4576 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4577 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4579 }
4580}
4581#endif /* !COAP_DISABLE_TCP */
4582
4583static int
4584check_token_size(coap_session_t *session, const coap_pdu_t *pdu, int is_local_mcast) {
4585 if (COAP_PDU_IS_REQUEST(pdu) &&
4586 pdu->actual_token.length >
4587 (session->type == COAP_SESSION_TYPE_CLIENT ?
4588 session->max_token_size : session->context->max_token_size)) {
4589 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4590 if (is_local_mcast)
4591 return 0;
4592 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4593 coap_opt_filter_t opt_filter;
4594 coap_pdu_t *response;
4595
4596 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4597 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4598 &opt_filter);
4599 if (!response) {
4600 coap_log_warn("coap_dispatch: cannot create error response\n");
4601 } else {
4602 /*
4603 * Note - have to leave in oversize token as per
4604 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4605 */
4606 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4607 coap_log_warn("coap_dispatch: error sending response\n");
4608 }
4609 } else {
4610 /* Indicate no extended token support */
4611 coap_send_rst_lkd(session, pdu);
4612 }
4613 return 0;
4614 }
4615 return 1;
4616}
4617
4618void
4620 coap_pdu_t *pdu) {
4621 coap_queue_t *sent = NULL;
4622 coap_pdu_t *response;
4623 coap_pdu_t *orig_pdu = NULL;
4624 coap_opt_filter_t opt_filter;
4625 int is_ping_rst;
4626 int packet_is_bad = 0;
4627#if COAP_OSCORE_SUPPORT
4628 coap_opt_iterator_t opt_iter;
4629 coap_pdu_t *dec_pdu = NULL;
4630#endif /* COAP_OSCORE_SUPPORT */
4631 int is_ext_token_rst = 0;
4632 int oscore_invalid = 0;
4633 int is_local_mcast = 0;
4634
4636 pdu->session = session;
4638
4639 if (COAP_PDU_IS_REQUEST(pdu) && coap_is_mcast(&session->addr_info.local)) {
4640 /* Need to be careful with responses to multicast requests */
4641 is_local_mcast = 1;
4642 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
4643 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
4644 return;
4645 }
4646 }
4647
4648 /* Check validity of received code */
4649 if (!coap_check_code_class(session, pdu)) {
4650 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4652 pdu->code & 0x1f);
4653 packet_is_bad = 1;
4654 if (pdu->type == COAP_MESSAGE_CON) {
4656 }
4657 /* find message id in sendqueue to stop retransmission (code is not 0.00) */
4658 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &pdu->actual_token, &sent);
4659 goto cleanup;
4660 }
4661
4662 coap_option_filter_clear(&opt_filter);
4663
4664#if COAP_SERVER_SUPPORT
4665 /* See if this a repeat request */
4666 if (COAP_PDU_IS_REQUEST(pdu) && session->last_resp_pdu &&
4667 pdu->mid == session->last_resp_pdu->mid) {
4668#if COAP_OSCORE_SUPPORT
4669 uint8_t oscore_encryption = session->oscore_encryption;
4670
4671 session->oscore_encryption = 0;
4672#endif /* COAP_OSCORE_SUPPORT */
4673 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4674 last_resp_pdu must not be removed */
4675 coap_pdu_reference_lkd(session->last_resp_pdu);
4676 coap_log_debug("Retransmit response to duplicate request\n");
4677 if (coap_send_internal(session, session->last_resp_pdu, NULL) != COAP_INVALID_MID) {
4678#if COAP_OSCORE_SUPPORT
4679 session->oscore_encryption = oscore_encryption;
4680#endif /* COAP_OSCORE_SUPPORT */
4681 goto finish;
4682 }
4683#if COAP_OSCORE_SUPPORT
4684 session->oscore_encryption = oscore_encryption;
4685#endif /* COAP_OSCORE_SUPPORT */
4686 }
4687#endif /* COAP_SERVER_SUPPORT */
4688 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4689 if (!check_token_size(session, pdu, is_local_mcast)) {
4690 goto cleanup;
4691 }
4692 }
4693#if COAP_OSCORE_SUPPORT
4694 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4695 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
4696 if (!is_local_mcast && (pdu->type == COAP_MESSAGE_CON || pdu->type == COAP_MESSAGE_NON)) {
4697 if (COAP_PDU_IS_REQUEST(pdu)) {
4698 response =
4699 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4700
4701 if (!response) {
4702 coap_log_warn("coap_dispatch: cannot create error response\n");
4703 } else {
4704 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4705 coap_log_warn("coap_dispatch: error sending response\n");
4706 }
4707 } else {
4708 coap_send_rst_lkd(session, pdu);
4709 }
4710 }
4711 goto cleanup;
4712 }
4713
4714 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4715 int decrypt = 1;
4716#if COAP_SERVER_SUPPORT
4717 coap_opt_t *opt;
4718 coap_resource_t *resource;
4719 coap_uri_t uri;
4720#endif /* COAP_SERVER_SUPPORT */
4721
4722 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4723 decrypt = 0;
4724
4725#if COAP_SERVER_SUPPORT
4726 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4727 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4728 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4729 != NULL) {
4730 /* Need to check whether this is a direct or proxy session */
4731 memset(&uri, 0, sizeof(uri));
4732 uri.host.length = coap_opt_length(opt);
4733 uri.host.s = coap_opt_value(opt);
4734 resource = context->proxy_uri_resource;
4735 if (uri.host.length && resource && resource->proxy_name_count &&
4736 resource->proxy_name_list) {
4737 size_t i;
4738 for (i = 0; i < resource->proxy_name_count; i++) {
4739 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4740 break;
4741 }
4742 }
4743 if (i == resource->proxy_name_count) {
4744 /* This server is not hosting the proxy connection endpoint */
4745 decrypt = 0;
4746 }
4747 }
4748 }
4749#endif /* COAP_SERVER_SUPPORT */
4750 if (decrypt) {
4751 /* find message id in sendqueue to stop retransmission and get sent (not empty packet) */
4752 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &pdu->actual_token, &sent);
4753 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4754 orig_pdu = pdu;
4755 coap_pdu_reference_lkd(orig_pdu);
4756 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4757 if (session->recipient_ctx == NULL ||
4758 (session->recipient_ctx->initial_state == 0 &&
4759 session->b_2_step == COAP_OSCORE_B_2_NONE)) {
4760 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4761 }
4763 coap_delete_pdu_lkd(orig_pdu);
4764 goto finish;
4765 } else {
4766 session->oscore_encryption = 1;
4767 coap_pdu_reference_lkd(dec_pdu);
4769 pdu = dec_pdu;
4770 }
4771 coap_log_debug("Decrypted PDU\n");
4773 }
4774 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4775 session->oscore_encryption &&
4776 pdu->type != COAP_MESSAGE_RST) {
4777 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4778 /* Violates RFC 8613 2 */
4779 coap_log_err("received an invalid response to the OSCORE request\n");
4780 oscore_invalid = 1;
4781 }
4782 }
4783#endif /* COAP_OSCORE_SUPPORT */
4784
4785 switch (pdu->type) {
4786 case COAP_MESSAGE_ACK:
4787 if (NULL == sent) {
4788 /* find message id in sendqueue to stop retransmission (no token if empty) */
4789 coap_remove_from_queue(&context->sendqueue, session, pdu->mid,
4790 pdu->code == 0 ? NULL : &pdu->actual_token, &sent);
4791 }
4792
4793 if (sent && session->con_active) {
4794 session->con_active--;
4795 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4796 /* Flush out any entries on session->delayqueue */
4797 coap_session_connected(session);
4798 }
4799 if (oscore_invalid ||
4800 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
4801 packet_is_bad = 1;
4802 goto cleanup;
4803 }
4804
4805#if COAP_SERVER_SUPPORT
4806 /* if sent code was >= 64 the message might have been a
4807 * notification. Then, we must flag the observer to be alive
4808 * by setting obs->fail_cnt = 0. */
4809 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4810 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4811 }
4812#endif /* COAP_SERVER_SUPPORT */
4813
4814#if COAP_Q_BLOCK_SUPPORT
4815 if (session->lg_xmit && sent && sent->pdu && sent->pdu->type == COAP_MESSAGE_CON &&
4816 !(session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK)) {
4817 int doing_q_block = 0;
4818 coap_lg_xmit_t *lg_xmit = NULL;
4819
4820 LL_FOREACH(session->lg_xmit, lg_xmit) {
4821 if ((lg_xmit->option == COAP_OPTION_Q_BLOCK1 || lg_xmit->option == COAP_OPTION_Q_BLOCK2) &&
4822 lg_xmit->last_all_sent == 0 && lg_xmit->sent_pdu->type != COAP_MESSAGE_NON) {
4823 doing_q_block = 1;
4824 break;
4825 }
4826 }
4827 if (doing_q_block && lg_xmit) {
4828 coap_block_b_t block;
4829
4830 memset(&block, 0, sizeof(block));
4831 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
4832 block.num = lg_xmit->last_block + lg_xmit->b.b1.count;
4833 } else {
4834 block.num = lg_xmit->last_block;
4835 }
4836 block.m = 1;
4837 block.szx = block.aszx = lg_xmit->blk_size;
4838 block.defined = 1;
4839 block.bert = 0;
4840 block.chunk_size = 1024;
4841
4842 coap_send_q_blocks(session, lg_xmit, block,
4843 lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
4844 }
4845 }
4846#endif /* COAP_Q_BLOCK_SUPPORT */
4847 if (pdu->code == 0) {
4848#if COAP_CLIENT_SUPPORT
4849 /*
4850 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4851 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4852 * response if the response was piggy-backed. Here, a separate response
4853 * detected and so the lg_crcv needs to be set up before the sent PDU
4854 * information is lost.
4855 *
4856 * lg_crcv was not set up if not a CoAP request.
4857 *
4858 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4859 * options.
4860 */
4861 if (sent &&
4862 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4863 COAP_PDU_IS_REQUEST(sent->pdu)) {
4864 /*
4865 * lg_crcv was not set up in coap_send(). It could have been set up
4866 * the first separate response.
4867 * See if there already is a lg_crcv set up.
4868 */
4869 coap_lg_crcv_t *lg_crcv;
4870 uint64_t token_match =
4872 sent->pdu->actual_token.length));
4873
4874 LL_FOREACH(session->lg_crcv, lg_crcv) {
4875 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4876 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4877 break;
4878 }
4879 }
4880 if (!lg_crcv) {
4881 /*
4882 * Need to set up a lg_crcv as it was not set up in coap_send()
4883 * to save time, but server has not sent back a piggy-back response.
4884 */
4885 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4886 if (lg_crcv) {
4887 LL_PREPEND(session->lg_crcv, lg_crcv);
4888 }
4889 }
4890 }
4891#endif /* COAP_CLIENT_SUPPORT */
4892 /* an empty ACK needs no further handling */
4893 goto cleanup;
4894 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4895 /* This is not legitimate - Request using ACK - ignore */
4896 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4898 pdu->code & 0x1f);
4899 packet_is_bad = 1;
4900 goto cleanup;
4901 }
4902
4903 break;
4904
4905 case COAP_MESSAGE_RST:
4906 /* We have sent something the receiver disliked, so we remove
4907 * not only the message id but also the subscriptions we might
4908 * have. */
4909 is_ping_rst = 0;
4910 if (pdu->mid == session->last_ping_mid &&
4911 session->last_ping > 0)
4912 is_ping_rst = 1;
4913
4914#if COAP_CLIENT_SUPPORT
4915#if COAP_Q_BLOCK_SUPPORT
4916 /* Check to see if checking out Q-Block support */
4917 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4918 session->remote_test_mid == pdu->mid) {
4919 coap_log_debug("Q-Block support not available\n");
4920 set_block_mode_drop_q(session->block_mode);
4921 coap_reset_doing_first(session);
4922 }
4923#endif /* COAP_Q_BLOCK_SUPPORT */
4924
4925 /* Check to see if checking out extended token support */
4926 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4927 session->remote_test_mid == pdu->mid) {
4928 coap_log_debug("Extended Token support not available\n");
4931 coap_reset_doing_first(session);
4932 is_ext_token_rst = 1;
4933 }
4934#endif /* COAP_CLIENT_SUPPORT */
4935
4936 if (!is_ping_rst && !is_ext_token_rst)
4937 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4938
4939 if (session->con_active) {
4940 session->con_active--;
4941 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4942 /* Flush out any entries on session->delayqueue */
4943 coap_session_connected(session);
4944 }
4945
4946 /* find message id in sendqueue to stop retransmission (no token as RST) */
4947 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, NULL, &sent);
4948
4949 if (sent) {
4950 if (!is_ping_rst)
4951 coap_cancel(context, sent);
4952
4953 if (!is_ping_rst && !is_ext_token_rst) {
4954 if (sent->pdu->type==COAP_MESSAGE_CON) {
4955 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4956 }
4957 } else if (is_ping_rst) {
4958 if (context->pong_cb) {
4959 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4960 }
4961 session->last_pong = session->last_rx_tx;
4962 session->ping_failed = 0;
4964 }
4965 } else {
4966#if COAP_SERVER_SUPPORT
4967 /* Need to check is there is a subscription active and delete it */
4968 RESOURCES_ITER(context->resources, r) {
4969 coap_subscription_t *obs, *tmp;
4970 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4971 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4972 /* Need to do this now as session may get de-referenced */
4974 coap_delete_observer(r, session, &obs->pdu->actual_token);
4975 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4976 coap_session_release_lkd(session);
4977 goto cleanup;
4978 }
4979 }
4980 }
4981#endif /* COAP_SERVER_SUPPORT */
4982 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4983 }
4984#if COAP_PROXY_SUPPORT
4985 if (!is_ping_rst) {
4986 /* Need to check is there is a proxy subscription active and delete it */
4987 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
4988 }
4989#endif /* COAP_PROXY_SUPPORT */
4990 goto cleanup;
4991
4992 case COAP_MESSAGE_NON:
4993 /* check for oscore issue or unknown critical options */
4994 if (oscore_invalid ||
4995 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
4996 packet_is_bad = 1;
4997 if (COAP_PDU_IS_REQUEST(pdu)) {
4998 response =
4999 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
5000
5001 if (!response) {
5002 coap_log_warn("coap_dispatch: cannot create error response\n");
5003 } else {
5004 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
5005 coap_log_warn("coap_dispatch: error sending response\n");
5006 }
5007 } else {
5008 coap_send_rst_lkd(session, pdu);
5009 }
5010 goto cleanup;
5011 }
5012 break;
5013
5014 case COAP_MESSAGE_CON:
5015 /* In a lossy context, the ACK of a separate response may have
5016 * been lost, so we need to stop retransmitting requests with the
5017 * same token. Matching on token potentially containing ext length bytes.
5018 */
5019 /* find message token in sendqueue to stop retransmission */
5020 if (pdu->code != 0)
5021 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
5022
5023 /* check for oscore issue or unknown critical options in non-signaling messages */
5024 if (oscore_invalid ||
5025 (!COAP_PDU_IS_SIGNALING(pdu) &&
5026 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0)) {
5027 packet_is_bad = 1;
5028 if (COAP_PDU_IS_REQUEST(pdu)) {
5029 response =
5030 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
5031
5032 if (!response) {
5033 coap_log_warn("coap_dispatch: cannot create error response\n");
5034 } else {
5035 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
5036 coap_log_warn("coap_dispatch: error sending response\n");
5037 }
5038 } else {
5039 coap_send_rst_lkd(session, pdu);
5040 }
5041 goto cleanup;
5042 }
5043 break;
5044 default:
5045 break;
5046 }
5047
5048 /* Pass message to upper layer if a specific handler was
5049 * registered for a request that should be handled locally. */
5050#if !COAP_DISABLE_TCP
5051 if (COAP_PDU_IS_SIGNALING(pdu))
5052 handle_signaling(context, session, pdu);
5053 else
5054#endif /* !COAP_DISABLE_TCP */
5055#if COAP_SERVER_SUPPORT
5056 if (COAP_PDU_IS_REQUEST(pdu))
5057 handle_request(context, session, pdu, orig_pdu);
5058 else
5059#endif /* COAP_SERVER_SUPPORT */
5060#if COAP_CLIENT_SUPPORT
5061 if (COAP_PDU_IS_RESPONSE(pdu))
5062 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
5063 else
5064#endif /* COAP_CLIENT_SUPPORT */
5065 {
5066 if (COAP_PDU_IS_EMPTY(pdu)) {
5067 if (context->ping_cb) {
5068 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
5069 }
5070 } else {
5071 packet_is_bad = 1;
5072 }
5073 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
5075 pdu->code & 0x1f);
5076
5077 if (!coap_is_mcast(&session->addr_info.local)) {
5078 if (COAP_PDU_IS_EMPTY(pdu)) {
5079 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
5080 coap_tick_t now;
5081 coap_ticks(&now);
5082 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
5084 session->last_tx_rst = now;
5085 }
5086 }
5087 } else {
5088 if (pdu->type == COAP_MESSAGE_CON)
5090 }
5091 }
5092 }
5093
5094cleanup:
5095 if (packet_is_bad) {
5096 if (sent) {
5097 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
5098 } else {
5100 }
5101 }
5102 coap_delete_pdu_lkd(orig_pdu);
5104#if COAP_OSCORE_SUPPORT
5105 coap_delete_pdu_lkd(dec_pdu);
5106#endif /* COAP_OSCORE_SUPPORT */
5107
5108#if COAP_SERVER_SUPPORT || COAP_OSCORE_SUPPORT
5109finish:
5110#endif /* COAP_SERVER_SUPPORT || COAP_OSCORE_SUPPORT */
5112}
5113
5114#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
5115static const char *
5117 switch (event) {
5119 return "COAP_EVENT_DTLS_CLOSED";
5121 return "COAP_EVENT_DTLS_CONNECTED";
5123 return "COAP_EVENT_DTLS_RENEGOTIATE";
5125 return "COAP_EVENT_DTLS_ERROR";
5127 return "COAP_EVENT_TCP_CONNECTED";
5129 return "COAP_EVENT_TCP_CLOSED";
5131 return "COAP_EVENT_TCP_FAILED";
5133 return "COAP_EVENT_SESSION_CONNECTED";
5135 return "COAP_EVENT_SESSION_CLOSED";
5137 return "COAP_EVENT_SESSION_FAILED";
5139 return "COAP_EVENT_PARTIAL_BLOCK";
5141 return "COAP_EVENT_XMIT_BLOCK_FAIL";
5143 return "COAP_EVENT_BLOCK_ISSUE";
5145 return "COAP_EVENT_SERVER_SESSION_NEW";
5147 return "COAP_EVENT_SERVER_SESSION_DEL";
5149 return "COAP_EVENT_SERVER_SESSION_CONNECTED";
5151 return "COAP_EVENT_BAD_PACKET";
5153 return "COAP_EVENT_MSG_RETRANSMITTED";
5155 return "COAP_EVENT_FIRST_PDU_FAIL";
5157 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
5159 return "COAP_EVENT_OSCORE_NOT_ENABLED";
5161 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
5163 return "COAP_EVENT_OSCORE_NO_SECURITY";
5165 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
5167 return "COAP_EVENT_OSCORE_DECODE_ERROR";
5169 return "COAP_EVENT_WS_PACKET_SIZE";
5171 return "COAP_EVENT_WS_CONNECTED";
5173 return "COAP_EVENT_WS_CLOSED";
5175 return "COAP_EVENT_KEEPALIVE_FAILURE";
5177 return "COAP_EVENT_RECONNECT_FAILED";
5179 return "COAP_EVENT_RECONNECT_SUCCESS";
5181 return "COAP_EVENT_RECONNECT_NO_MORE";
5183 return "COAP_EVENT_RECONNECT_STARTED";
5184 default:
5185 return "???";
5186 }
5187}
5188#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
5189
5190COAP_API int
5192 coap_session_t *session) {
5193 int ret;
5194
5195 coap_lock_lock(return 0);
5196 ret = coap_handle_event_lkd(context, event, session);
5198 return ret;
5199}
5200
5201int
5203 coap_session_t *session) {
5204 int ret = 0;
5205
5206 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
5207
5208#if COAP_PROXY_SUPPORT
5209 if (event == COAP_EVENT_SERVER_SESSION_DEL)
5210 coap_proxy_remove_association(session, 0);
5211#endif /* COAP_PROXY_SUPPORT */
5212
5213 if (context->event_cb) {
5214 coap_lock_callback_ret(ret, context->event_cb(session, event));
5215#if COAP_CLIENT_SUPPORT
5216 switch (event) {
5231 /* Those that are deemed fatal to end sending a request */
5232 session->doing_send_recv = 0;
5233 break;
5235 /* Session will now be available as well - for call-home */
5236 if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
5238 session);
5239 }
5240 break;
5246 break;
5248 /* Session will now be available as well - for call-home if not (D)TLS */
5249 if (session->type == COAP_SESSION_TYPE_SERVER &&
5250 (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
5252 session);
5253 }
5254 break;
5259 break;
5261 /* Session will now be available as well - for call-home if not (D)TLS */
5262 if (session->proto == COAP_PROTO_UDP) {
5264 session);
5265 }
5266 break;
5274 default:
5275 break;
5276 }
5277#endif /* COAP_CLIENT_SUPPORT */
5278 }
5279 return ret;
5280}
5281
5282COAP_API int
5284 int ret;
5285
5286 coap_lock_lock(return 0);
5287 ret = coap_can_exit_lkd(context);
5289 return ret;
5290}
5291
5292int
5294 coap_session_t *s, *rtmp;
5295 if (!context)
5296 return 1;
5298 if (context->sendqueue)
5299 return 0;
5300#if COAP_SERVER_SUPPORT
5301 coap_endpoint_t *ep;
5302
5303 LL_FOREACH(context->endpoint, ep) {
5304 SESSIONS_ITER(ep->sessions, s, rtmp) {
5305 if (s->delayqueue)
5306 return 0;
5307 if (s->lg_xmit)
5308 return 0;
5309 }
5310 }
5311#endif /* COAP_SERVER_SUPPORT */
5312#if COAP_CLIENT_SUPPORT
5313 SESSIONS_ITER(context->sessions, s, rtmp) {
5314 if (s->delayqueue)
5315 return 0;
5316 if (s->lg_xmit)
5317 return 0;
5318 }
5319#endif /* COAP_CLIENT_SUPPORT */
5320 return 1;
5321}
5322#if COAP_SERVER_SUPPORT
5323#if COAP_ASYNC_SUPPORT
5324/*
5325 * Return 1 if there is a future expire time, else 0.
5326 * Update tim_rem with remaining value if return is 1.
5327 */
5328int
5329coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5331 coap_async_t *async, *tmp;
5332 int ret = 0;
5333
5334 if (context->async_state_traversing)
5335 return 0;
5336 context->async_state_traversing = 1;
5337 LL_FOREACH_SAFE(context->async_state, async, tmp) {
5338 if (async->delay != 0 && !async->session->is_rate_limiting) {
5339 if (async->delay <= now) {
5340 /* Send off the request to the application */
5341 coap_log_debug("Async PDU presented to app.\n");
5342 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5343 handle_request(context, async->session, async->pdu, NULL);
5344
5345 /* Remove this async entry as it has now fired */
5346 coap_free_async_lkd(async->session, async);
5347 } else {
5348 next_due = async->delay - now;
5349 ret = 1;
5350 }
5351 }
5352 }
5353 if (tim_rem)
5354 *tim_rem = next_due;
5355 context->async_state_traversing = 0;
5356 return ret;
5357}
5358#endif /* COAP_ASYNC_SUPPORT */
5359#endif /* COAP_SERVER_SUPPORT */
5360
5362uint8_t coap_unique_id[8] = { 0 };
5363
5364#if COAP_THREAD_SAFE
5365/*
5366 * Global lock for multi-thread support
5367 */
5368coap_lock_t global_lock;
5369/*
5370 * low level protection mutex
5371 */
5372coap_mutex_t m_show_pdu;
5373coap_mutex_t m_log_impl;
5374coap_mutex_t m_io_threads;
5375#endif /* COAP_THREAD_SAFE */
5376
5377void
5379 coap_tick_t now;
5380#ifndef WITH_CONTIKI
5381 uint64_t us;
5382#endif /* !WITH_CONTIKI */
5383
5384 if (coap_started)
5385 return;
5386 coap_started = 1;
5387
5388#if COAP_THREAD_SAFE
5389 coap_lock_init(&global_lock);
5390 coap_mutex_init(&m_show_pdu);
5391 coap_mutex_init(&m_log_impl);
5392 coap_mutex_init(&m_io_threads);
5393#endif /* COAP_THREAD_SAFE */
5394
5395#if defined(HAVE_WINSOCK2_H)
5396 WORD wVersionRequested = MAKEWORD(2, 2);
5397 WSADATA wsaData;
5398 WSAStartup(wVersionRequested, &wsaData);
5399#endif
5401 coap_ticks(&now);
5402#ifndef WITH_CONTIKI
5403 us = coap_ticks_to_rt_us(now);
5404 /* Be accurate to the nearest (approx) us */
5405 coap_prng_init_lkd((unsigned int)us);
5406#else /* WITH_CONTIKI */
5407 coap_start_io_process();
5408#endif /* WITH_CONTIKI */
5411#ifdef WITH_LWIP
5412 coap_io_lwip_init();
5413#endif /* WITH_LWIP */
5414#if COAP_SERVER_SUPPORT
5415 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5416 (const uint8_t *)".well-known/core"
5417 };
5418 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5419 resource_uri_wellknown.ref = 1;
5420 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5421 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5422 resource_uri_wellknown.uri_path = &well_known;
5423#endif /* COAP_SERVER_SUPPORT */
5426}
5427
5428void
5430 if (!coap_started)
5431 return;
5432 coap_started = 0;
5433#if defined(HAVE_WINSOCK2_H)
5434 WSACleanup();
5435#elif defined(WITH_CONTIKI)
5436 coap_stop_io_process();
5437#endif
5438#ifdef WITH_LWIP
5439 coap_io_lwip_cleanup();
5440#endif /* WITH_LWIP */
5442
5447#if COAP_THREAD_SAFE
5448 coap_mutex_destroy(&m_show_pdu);
5449 coap_mutex_destroy(&m_log_impl);
5450 coap_mutex_destroy(&m_io_threads);
5451#endif /* COAP_THREAD_SAFE */
5452
5454}
5455
5456void
5458 coap_response_handler_t handler) {
5459#if COAP_CLIENT_SUPPORT
5460 context->response_cb = handler;
5461#else /* ! COAP_CLIENT_SUPPORT */
5462 (void)context;
5463 (void)handler;
5464#endif /* ! COAP_CLIENT_SUPPORT */
5465}
5466
5467void
5470#if COAP_PROXY_SUPPORT
5471 context->proxy_response_cb = handler;
5472#else /* ! COAP_PROXY_SUPPORT */
5473 (void)context;
5474 (void)handler;
5475#endif /* ! COAP_PROXY_SUPPORT */
5476}
5477
5478void
5480 coap_nack_handler_t handler) {
5481 context->nack_cb = handler;
5482}
5483
5484void
5486 coap_ping_handler_t handler) {
5487 context->ping_cb = handler;
5488}
5489
5490void
5492 coap_pong_handler_t handler) {
5493 context->pong_cb = handler;
5494}
5495
5496void
5498 coap_resource_dynamic_create_t dyn_create_handler,
5499 uint32_t dynamic_max) {
5500 context->dyn_create_handler = dyn_create_handler;
5501 context->dynamic_max = dynamic_max;
5502 return;
5503}
5504
5505COAP_API void
5511
5512void
5516
5517#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5518#if COAP_SERVER_SUPPORT
5519COAP_API int
5520coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5521 const char *ifname) {
5522 int ret;
5523
5524 coap_lock_lock(return -1);
5525 ret = coap_join_mcast_group_intf_lkd(ctx, NULL, group_name, ifname);
5527 return ret;
5528}
5529
5530int
5532 coap_endpoint_t *single_endpoint,
5533 const char *group_name,
5534 const char *ifname) {
5535#if COAP_IPV4_SUPPORT
5536 struct ip_mreq mreq4;
5537#endif /* COAP_IPV4_SUPPORT */
5538#if COAP_IPV6_SUPPORT
5539 struct ipv6_mreq mreq6;
5540#endif /* COAP_IPV6_SUPPORT */
5541 struct addrinfo *resmulti = NULL, hints, *ainfo;
5542 int result = -1;
5543 coap_endpoint_t *endpoint;
5544#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5545 coap_endpoint_t *lookup_endpoint;
5546#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5547 int mgroup_setup = 0;
5548
5549 if (single_endpoint) {
5550 if (single_endpoint->proto != COAP_PROTO_UDP)
5551 return -1;
5552#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5553 lookup_endpoint = single_endpoint;
5554#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5555 } else {
5556 /* Need to have at least one endpoint! */
5557 assert(ctx->endpoint);
5558 if (!ctx->endpoint)
5559 return -1;
5560#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5561 lookup_endpoint = ctx->endpoint;
5562#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5563 }
5564
5565 /* Default is let the kernel choose */
5566#if COAP_IPV6_SUPPORT
5567 mreq6.ipv6mr_interface = 0;
5568#endif /* COAP_IPV6_SUPPORT */
5569#if COAP_IPV4_SUPPORT
5570 mreq4.imr_interface.s_addr = INADDR_ANY;
5571#endif /* COAP_IPV4_SUPPORT */
5572
5573 memset(&hints, 0, sizeof(hints));
5574 hints.ai_socktype = SOCK_DGRAM;
5575
5576 /* resolve the multicast group address */
5577 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5578
5579 if (result != 0) {
5580 coap_log_err("coap_join_mcast_group_intf: %s: "
5581 "Cannot resolve multicast address: %s\n",
5582 group_name, gai_strerror(result));
5583 goto finish;
5584 }
5585
5586 /* Need to do a windows equivalent at some point */
5587#ifndef _WIN32
5588 if (ifname) {
5589 /* interface specified - check if we have correct IPv4/IPv6 information */
5590 int done_ip4 = 0;
5591 int done_ip6 = 0;
5592#if defined(ESPIDF_VERSION)
5593 struct netif *netif;
5594#else /* !ESPIDF_VERSION */
5595#if COAP_IPV4_SUPPORT
5596 int ip4fd;
5597#endif /* COAP_IPV4_SUPPORT */
5598 struct ifreq ifr;
5599#endif /* !ESPIDF_VERSION */
5600
5601 /* See which mcast address family types are being asked for */
5602 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5603 ainfo = ainfo->ai_next) {
5604 switch (ainfo->ai_family) {
5605#if COAP_IPV6_SUPPORT
5606 case AF_INET6:
5607 if (done_ip6)
5608 break;
5609 done_ip6 = 1;
5610#if defined(ESPIDF_VERSION)
5611 netif = netif_find(ifname);
5612 if (netif)
5613 mreq6.ipv6mr_interface = netif_get_index(netif);
5614 else
5615 coap_log_err("coap_join_mcast_group_intf: %s: "
5616 "Cannot get IPv4 address: %s\n",
5617 ifname, coap_socket_strerror());
5618#else /* !ESPIDF_VERSION */
5619 memset(&ifr, 0, sizeof(ifr));
5620 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5621 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5622
5623#ifdef HAVE_IF_NAMETOINDEX
5624 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5625 if (mreq6.ipv6mr_interface == 0) {
5626 coap_log_warn("coap_join_mcast_group_intf: "
5627 "cannot get interface index for '%s'\n",
5628 ifname);
5629 }
5630#elif defined(__QNXNTO__)
5631#else /* !HAVE_IF_NAMETOINDEX */
5632 result = ioctl(lookup_endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5633 if (result != 0) {
5634 coap_log_warn("coap_join_mcast_group_intf: "
5635 "cannot get interface index for '%s': %s\n",
5636 ifname, coap_socket_strerror());
5637 } else {
5638 /* Capture the IPv6 if_index for later */
5639 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5640 }
5641#endif /* !HAVE_IF_NAMETOINDEX */
5642#endif /* !ESPIDF_VERSION */
5643#endif /* COAP_IPV6_SUPPORT */
5644 break;
5645#if COAP_IPV4_SUPPORT
5646 case AF_INET:
5647 if (done_ip4)
5648 break;
5649 done_ip4 = 1;
5650#if defined(ESPIDF_VERSION)
5651 netif = netif_find(ifname);
5652 if (netif)
5653 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5654 else
5655 coap_log_err("coap_join_mcast_group_intf: %s: "
5656 "Cannot get IPv4 address: %s\n",
5657 ifname, coap_socket_strerror());
5658#else /* !ESPIDF_VERSION */
5659 /*
5660 * Need an AF_INET socket to do this unfortunately to stop
5661 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5662 */
5663 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5664 if (ip4fd == -1) {
5665 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5666 ifname, coap_socket_strerror());
5667 continue;
5668 }
5669 memset(&ifr, 0, sizeof(ifr));
5670 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5671 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5672 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5673 if (result != 0) {
5674 coap_log_err("coap_join_mcast_group_intf: %s: "
5675 "Cannot get IPv4 address: %s\n",
5676 ifname, coap_socket_strerror());
5677 } else {
5678 /* Capture the IPv4 address for later */
5679 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5680 }
5681 close(ip4fd);
5682#endif /* !ESPIDF_VERSION */
5683 break;
5684#endif /* COAP_IPV4_SUPPORT */
5685 default:
5686 break;
5687 }
5688 }
5689 }
5690#else /* _WIN32 */
5691 /*
5692 * On Windows this function ignores the ifname variable so we unset this
5693 * variable on this platform in any case in order to enable the interface
5694 * selection from the bind address below.
5695 */
5696 ifname = 0;
5697#endif /* _WIN32 */
5698
5699 /* Add in mcast address(es) to appropriate interface */
5700 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5701 for (endpoint = single_endpoint ? single_endpoint : ctx->endpoint;
5702 endpoint != NULL;
5703 endpoint = single_endpoint ? NULL : endpoint->next) {
5704 /* Only UDP currently supported */
5705 if (endpoint->proto == COAP_PROTO_UDP) {
5706 coap_address_t gaddr;
5707
5708 coap_address_init(&gaddr);
5709#if COAP_IPV6_SUPPORT
5710 if (ainfo->ai_family == AF_INET6) {
5711 if (!ifname) {
5712 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5713 /*
5714 * Do it on the ifindex that the server is listening on
5715 * (sin6_scope_id could still be 0)
5716 */
5717 mreq6.ipv6mr_interface =
5718 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5719 } else {
5720 mreq6.ipv6mr_interface = 0;
5721 }
5722 }
5723 gaddr.addr.sin6.sin6_family = AF_INET6;
5724 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5725 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5726 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5727 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5728 (char *)&mreq6, sizeof(mreq6));
5729 }
5730#endif /* COAP_IPV6_SUPPORT */
5731#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5732 else
5733#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5734#if COAP_IPV4_SUPPORT
5735 if (ainfo->ai_family == AF_INET) {
5736 if (!ifname) {
5737 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5738 /*
5739 * Do it on the interface that the server is listening on
5740 * (sin_addr could still be INADDR_ANY)
5741 */
5742 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5743 } else {
5744 mreq4.imr_interface.s_addr = INADDR_ANY;
5745 }
5746 }
5747 gaddr.addr.sin.sin_family = AF_INET;
5748 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5749 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5750 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5751 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5752 (char *)&mreq4, sizeof(mreq4));
5753 }
5754#endif /* COAP_IPV4_SUPPORT */
5755 else {
5756 continue;
5757 }
5758
5759 if (result == COAP_SOCKET_ERROR) {
5760 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5761 group_name, coap_socket_strerror());
5762 } else {
5763 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5764
5765 addr_str[sizeof(addr_str)-1] = '\000';
5766 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5767 sizeof(addr_str) - 1)) {
5768 if (ifname)
5769 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5770 ifname);
5771 else
5772 coap_log_debug("added mcast group %s\n", addr_str);
5773 }
5774 mgroup_setup = 1;
5775 }
5776 }
5777 }
5778 }
5779 if (!mgroup_setup) {
5780 result = -1;
5781 }
5782
5783finish:
5784 freeaddrinfo(resmulti);
5785
5786 return result;
5787}
5788
5789COAP_API int
5791 const char *group_name,
5792 const char *ifname) {
5793 int ret;
5794
5795 if (!endpoint || !endpoint->context)
5796 return -1;
5797
5798 coap_lock_lock(return -1);
5799 ret = coap_join_mcast_group_intf_lkd(endpoint->context, endpoint, group_name, ifname);
5801 return ret;
5802}
5803
5804void
5806 context->mcast_per_resource = 1;
5807}
5808
5809#endif /* ! COAP_SERVER_SUPPORT */
5810
5811#if COAP_CLIENT_SUPPORT
5812int
5813coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5814 if (session && coap_is_mcast(&session->addr_info.remote)) {
5815 switch (session->addr_info.remote.addr.sa.sa_family) {
5816#if COAP_IPV4_SUPPORT
5817 case AF_INET:
5818 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5819 (const char *)&hops, sizeof(hops)) < 0) {
5820 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5821 hops, coap_socket_strerror());
5822 return 0;
5823 }
5824 return 1;
5825#endif /* COAP_IPV4_SUPPORT */
5826#if COAP_IPV6_SUPPORT
5827 case AF_INET6:
5828 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5829 (const char *)&hops, sizeof(hops)) < 0) {
5830 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5831 hops, coap_socket_strerror());
5832 return 0;
5833 }
5834 return 1;
5835#endif /* COAP_IPV6_SUPPORT */
5836 default:
5837 break;
5838 }
5839 }
5840 return 0;
5841}
5842#endif /* COAP_CLIENT_SUPPORT */
5843
5844#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
5845COAP_API int
5847 const char *group_name COAP_UNUSED,
5848 const char *ifname COAP_UNUSED) {
5849 return -1;
5850}
5851
5852COAP_API int
5854 const char *group_name COAP_UNUSED,
5855 const char *ifname COAP_UNUSED) {
5856 return -1;
5857}
5858
5859int
5861 size_t hops COAP_UNUSED) {
5862 return 0;
5863}
5864
5865void
5867}
5868#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)
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:614
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:966
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:666
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:1248
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:947
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:3208
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu, int is_local_mcast)
Definition coap_net.c:4584
#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:5429
#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:5116
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:3535
int coap_started
Definition coap_net.c:5361
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2583
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2624
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:4498
#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:1987
void coap_startup(void)
Definition coap_net.c:5378
static unsigned int s_csm_timeout
Definition coap_net.c:523
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:5362
#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:258
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:384
int coap_dtls_context_load_pki_trust_store(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:274
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:266
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:327
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:322
#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:2992
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:1205
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:1329
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:1300
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:2922
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:2327
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:1610
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:1220
#define COAP_IO_NO_WAIT
Definition coap_net.h:857
#define COAP_IO_WAIT
Definition coap_net.h:856
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:2981
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:2915
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:70
#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:180
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:192
#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:5202
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:5513
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:1478
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:1016
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:4619
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:1358
void coap_free_context_lkd(coap_context_t *context)
CoAP stack context must be released with coap_free_context_lkd().
Definition coap_net.c:839
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:2097
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:710
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:5293
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2445
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:1545
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_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1384
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:3267
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:3097
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 id from the list given list.
Definition coap_net.c:3158
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:3306
@ 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:572
unsigned int coap_context_get_max_handshake_sessions(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:519
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:508
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:2306
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:720
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:1600
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
void coap_context_set_max_body_size(coap_context_t *context, uint32_t max_body_size)
Set the maximum supported body size.
Definition coap_net.c:482
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:1287
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:554
void coap_context_set_csm_timeout(coap_context_t *context, unsigned int csm_timeout)
Set the CSM timeout value.
Definition coap_net.c:526
void coap_send_recv_terminate(void)
Terminate any active coap_send_recv() sessions.
Definition coap_net.c:2301
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:5457
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:699
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:3339
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:513
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:612
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:5497
COAP_API void coap_set_app_data(coap_context_t *context, void *app_data)
Definition coap_net.c:816
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:830
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 Acknowedge 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:603
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:693
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:685
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:567
unsigned int coap_context_get_session_timeout(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:598
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:1210
unsigned int coap_context_get_csm_timeout_ms(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:549
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:5485
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:824
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:502
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:1318
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:1195
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:584
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:5283
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:5506
unsigned int coap_context_get_csm_timeout(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:533
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:578
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:5491
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:491
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:5191
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:5479
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:539
@ 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:149
@ 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
Triggerred 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:137
@ 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:155
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:139
@ COAP_EVENT_RECONNECT_NO_MORE
Triggered when a session failed, and retry reconnect attempts failed.
Definition coap_event.h:153
@ 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_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:151
@ 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:135
@ 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:144
@ 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:812
#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:1741
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:692
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:546
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:1431
#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:1146
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:1062
#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:640
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:791
#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:1603
#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:1579
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:1093
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:341
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:851
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition coap_pdu.c:1022
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:413
int coap_get_data(const coap_pdu_t *pdu, size_t *len, const uint8_t **data)
Retrieves the length and data pointer of specified PDU.
Definition coap_pdu.c:947
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:1569
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:916
@ 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:5468
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:2654
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:1235
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:622
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:676
int coap_ipv6_is_supported(void)
Check whether IPv6 is available.
Definition coap_net.c:649
int coap_threadsafe_is_supported(void)
Determine whether libcoap is threadsafe or not.
Definition coap_net.c:631
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:667
int coap_client_is_supported(void)
Check whether Client code is available.
Definition coap_net.c:658
int coap_ipv4_is_supported(void)
Check whether IPv4 is available.
Definition coap_net.c:640
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition coap_uri.c:1182
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:351
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:1103
void coap_delete_upa_chain(coap_upa_chain_t *chain)
Clean up a UPA chain.
Definition coap_uri.c:1271
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::@250171263277076317333044054015357360100234370325 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
Dynamc resource create handler.
uint32_t max_body_size
Max supported body size or 0 is unlimited.
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.
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 negotating 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::@222250243137322076370063262364242303040003336106 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 transmisson 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_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
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
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
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