libcoap 4.3.5-develop-9d407dd
Loading...
Searching...
No Matches
coap_net.c
Go to the documentation of this file.
1/* coap_net.c -- CoAP context interface
2 *
3 * Copyright (C) 2010--2026 Olaf Bergmann <bergmann@tzi.org> and others
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 *
7 * This file is part of the CoAP library libcoap. Please see
8 * README for terms of use.
9 */
10
15
18
19#include <ctype.h>
20#include <stdio.h>
21#ifdef HAVE_LIMITS_H
22#include <limits.h>
23#endif
24
25#ifndef __ZEPHYR__
26#ifdef HAVE_UNISTD_H
27#include <unistd.h>
28#else
29#ifdef HAVE_SYS_UNISTD_H
30#include <sys/unistd.h>
31#endif
32#endif
33#ifdef HAVE_SYS_TYPES_H
34#include <sys/types.h>
35#endif
36#ifdef HAVE_SYS_SOCKET_H
37#include <sys/socket.h>
38#endif
39#ifdef HAVE_SYS_IOCTL_H
40#include <sys/ioctl.h>
41#endif
42#ifdef HAVE_NETINET_IN_H
43#include <netinet/in.h>
44#endif
45#ifdef HAVE_ARPA_INET_H
46#include <arpa/inet.h>
47#endif
48#ifdef HAVE_NET_IF_H
49#include <net/if.h>
50#endif
51#ifdef COAP_EPOLL_SUPPORT
52#include <sys/epoll.h>
53#include <sys/timerfd.h>
54#endif /* COAP_EPOLL_SUPPORT */
55#ifdef HAVE_WS2TCPIP_H
56#include <ws2tcpip.h>
57#endif
58
59#ifdef HAVE_NETDB_H
60#include <netdb.h>
61#endif
62#endif /* !__ZEPHYR__ */
63
64#ifdef WITH_LWIP
65#include <lwip/pbuf.h>
66#include <lwip/udp.h>
67#include <lwip/timeouts.h>
68#include <lwip/tcpip.h>
69#endif
70
71#ifndef INET6_ADDRSTRLEN
72#define INET6_ADDRSTRLEN 40
73#endif
74
75#ifndef min
76#define min(a,b) ((a) < (b) ? (a) : (b))
77#endif
78
83#define FRAC_BITS 6
84
89#define MAX_BITS 8
90
91#if FRAC_BITS > 8
92#error FRAC_BITS must be less or equal 8
93#endif
94
96#define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
97 ((1 << (frac)) * fval.fractional_part + 500)/1000))
98
100#define ACK_RANDOM_FACTOR \
101 Q(FRAC_BITS, session->ack_random_factor)
102
104#define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
105
106static int send_recv_terminate = 0;
107
112
117
118unsigned int
120 unsigned int result = 0;
122
123 if (ctx->sendqueue) {
124 /* delta < 0 means that the new time stamp is before the old. */
125 if (delta <= 0) {
126 ctx->sendqueue->t = (coap_tick_diff_t)ctx->sendqueue->t - delta;
127 } else {
128 /* This case is more complex: The time must be advanced forward,
129 * thus possibly leading to timed out elements at the queue's
130 * start. For every element that has timed out, its relative
131 * time is set to zero and the result counter is increased. */
132
133 coap_queue_t *q = ctx->sendqueue;
134 coap_tick_t t = 0;
135 while (q && (t + q->t < (coap_tick_t)delta)) {
136 t += q->t;
137 q->t = 0;
138 result++;
139 q = q->next;
140 }
141
142 /* finally adjust the first element that has not expired */
143 if (q) {
144 q->t = (coap_tick_t)delta - t;
145 }
146 }
147 }
148
149 /* adjust basetime */
151
152 return result;
153}
154
155int
157 coap_queue_t *p, *q;
158 if (!queue || !node)
159 return 0;
160
161 /* set queue head if empty */
162 if (!*queue) {
163 *queue = node;
164 return 1;
165 }
166
167 /* replace queue head if PDU's time is less than head's time */
168 q = *queue;
169 if (node->t < q->t) {
170 node->next = q;
171 *queue = node;
172 q->t -= node->t; /* make q->t relative to node->t */
173 return 1;
174 }
175
176 /* search for right place to insert */
177 do {
178 node->t -= q->t; /* make node-> relative to q->t */
179 p = q;
180 q = q->next;
181 } while (q && q->t <= node->t);
182
183 /* insert new item */
184 if (q) {
185 q->t -= node->t; /* make q->t relative to node->t */
186 }
187 node->next = q;
188 p->next = node;
189 return 1;
190}
191
192COAP_API int
194 int ret;
195
196 if (!node)
197 return 0;
198
199 coap_lock_lock(return 0);
200 ret = coap_delete_node_lkd(node);
202 return ret;
203}
204
205int
207 if (!node)
208 return 0;
209
211 if (node->session) {
212 /*
213 * Need to remove out of context->sendqueue as added in by coap_wait_ack()
214 */
215 if (node->session->context->sendqueue) {
216 LL_DELETE(node->session->context->sendqueue, node);
217 }
219 }
220 coap_free_node(node);
221
222 return 1;
223}
224
225void
227 if (!queue)
228 return;
229
230 coap_delete_all(queue->next);
232}
233
236 coap_queue_t *node;
237 node = coap_malloc_node();
238
239 if (!node) {
240 coap_log_warn("coap_new_node: malloc failed\n");
241 return NULL;
242 }
243
244 memset(node, 0, sizeof(*node));
245 return node;
246}
247
250 if (!context || !context->sendqueue)
251 return NULL;
252
253 return context->sendqueue;
254}
255
258 coap_queue_t *next;
259
260 if (!context || !context->sendqueue)
261 return NULL;
262
263 next = context->sendqueue;
264 context->sendqueue = context->sendqueue->next;
265 if (context->sendqueue) {
266 context->sendqueue->t += next->t;
267 }
268 next->next = NULL;
269 return next;
270}
271
272#if COAP_CLIENT_SUPPORT
273const coap_bin_const_t *
275
276 if (session->psk_key) {
277 return session->psk_key;
278 }
279 if (session->cpsk_setup_data.psk_info.key.length)
280 return &session->cpsk_setup_data.psk_info.key;
281
282 /* Not defined in coap_new_client_session_psk2() */
283 return NULL;
284}
285
286const coap_bin_const_t *
288
289 if (session->psk_identity) {
290 return session->psk_identity;
291 }
293 return &session->cpsk_setup_data.psk_info.identity;
294
295 /* Not defined in coap_new_client_session_psk2() */
296 return NULL;
297}
298#endif /* COAP_CLIENT_SUPPORT */
299
300#if COAP_SERVER_SUPPORT
301const coap_bin_const_t *
303
304 if (session->psk_key)
305 return session->psk_key;
306
307 if (session->context->spsk_setup_data.psk_info.key.length)
308 return &session->context->spsk_setup_data.psk_info.key;
309
310 /* Not defined in coap_context_set_psk2() */
311 return NULL;
312}
313
314const coap_bin_const_t *
316
317 if (session->psk_hint)
318 return session->psk_hint;
319
320 if (session->context->spsk_setup_data.psk_info.hint.length)
321 return &session->context->spsk_setup_data.psk_info.hint;
322
323 /* Not defined in coap_context_set_psk2() */
324 return NULL;
325}
326
327COAP_API int
329 const char *hint,
330 const uint8_t *key,
331 size_t key_len) {
332 int ret;
333
334 coap_lock_lock(return 0);
335 ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
337 return ret;
338}
339
340int
342 const char *hint,
343 const uint8_t *key,
344 size_t key_len) {
345 coap_dtls_spsk_t setup_data;
346
348 memset(&setup_data, 0, sizeof(setup_data));
349 if (hint) {
350 setup_data.psk_info.hint.s = (const uint8_t *)hint;
351 setup_data.psk_info.hint.length = strlen(hint);
352 }
353
354 if (key && key_len > 0) {
355 setup_data.psk_info.key.s = key;
356 setup_data.psk_info.key.length = key_len;
357 }
358
359 return coap_context_set_psk2_lkd(ctx, &setup_data);
360}
361
362COAP_API int
364 int ret;
365
366 coap_lock_lock(return 0);
367 ret = coap_context_set_psk2_lkd(ctx, setup_data);
369 return ret;
370}
371
372int
374 if (!setup_data)
375 return 0;
376
378 ctx->spsk_setup_data = *setup_data;
379
381 return coap_dtls_context_set_spsk(ctx, setup_data);
382 }
383 return 0;
384}
385
386COAP_API int
388 const coap_dtls_pki_t *setup_data) {
389 int ret;
390
391 coap_lock_lock(return 0);
392 ret = coap_context_set_pki_lkd(ctx, setup_data);
394 return ret;
395}
396
397int
399 const coap_dtls_pki_t *setup_data) {
401 if (!setup_data)
402 return 0;
403 if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
404 coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
405 return 0;
406 }
408 return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
409 }
410 return 0;
411}
412#endif /* ! COAP_SERVER_SUPPORT */
413
414COAP_API int
416 const char *ca_file,
417 const char *ca_dir) {
418 int ret;
419
420 coap_lock_lock(return 0);
421 ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
423 return ret;
424}
425
426int
428 const char *ca_file,
429 const char *ca_dir) {
431 return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
432 }
433 return 0;
434}
435
436COAP_API int
438 int ret;
439
440 coap_lock_lock(return 0);
443 return ret;
444}
445
446int
453
454
455void
456coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
457 context->ping_timeout = seconds;
458}
459
460int
462#if COAP_CLIENT_SUPPORT
463 return coap_dtls_set_cid_tuple_change(context, every);
464#else /* ! COAP_CLIENT_SUPPORT */
465 (void)context;
466 (void)every;
467 return 0;
468#endif /* ! COAP_CLIENT_SUPPORT */
469}
470
471void
473 uint64_t rate_limit_ppm) {
474 if (rate_limit_ppm) {
475 context->rl_ticks_per_packet = (60ULL * COAP_TICKS_PER_SECOND) / rate_limit_ppm;
476 } else {
477 context->rl_ticks_per_packet = 0;
478 }
479}
480
481void
483 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 explicitly 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 in case 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 reuse 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 (%" PRIu32 ".%03" PRIu32 "s)\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 1000) / COAP_TICKS_PER_SECOND);
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 in case 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 in case 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 in case 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 if (coap_debug_recv_packet()) {
3144 coap_dispatch(ctx, session, pdu);
3145 } else {
3147 }
3149 return 0;
3150
3151error:
3152 /*
3153 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
3154 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
3155 */
3156 coap_send_rst_lkd(session, pdu);
3158 return -1;
3159}
3160
3161int
3163 coap_bin_const_t *token, coap_queue_t **node) {
3164 coap_queue_t *p, *q;
3165
3166 if (!queue || !*queue) {
3167 *node = NULL;
3168 return 0;
3169 }
3170
3171 /* replace queue head if PDU's time is less than head's time */
3172
3173 if (session == (*queue)->session && mid == (*queue)->id &&
3174 (!token || coap_binary_equal(token, &(*queue)->pdu->actual_token))) { /* found message id */
3175 *node = *queue;
3176 *queue = (*queue)->next;
3177 if (*queue) { /* adjust relative time of new queue head */
3178 (*queue)->t += (*node)->t;
3179 }
3180 (*node)->next = NULL;
3181 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
3182 coap_session_str(session), mid);
3183 return 1;
3184 }
3185
3186 /* search message id in queue to remove (only first occurrence will be removed) */
3187 q = *queue;
3188 do {
3189 p = q;
3190 q = q->next;
3191 } while (q && (session != q->session || mid != q->id ||
3192 (token && ! coap_binary_equal(token, &q->pdu->actual_token))));
3193
3194 if (q) { /* found message id */
3195 p->next = q->next;
3196 if (p->next) { /* must update relative time of p->next */
3197 p->next->t += q->t;
3198 }
3199 q->next = NULL;
3200 *node = q;
3201 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
3202 coap_session_str(session), mid);
3203 return 1;
3204 }
3205
3206 *node = NULL;
3207 return 0;
3208
3209}
3210
3211static int
3213 coap_bin_const_t *token, coap_queue_t **node) {
3214 coap_queue_t *p, *q;
3215
3216 if (!queue || !*queue)
3217 return 0;
3218
3219 /* replace queue head if PDU's time is less than head's time */
3220
3221 if (session == (*queue)->session &&
3222 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
3223 *node = *queue;
3224 *queue = (*queue)->next;
3225 if (*queue) { /* adjust relative time of new queue head */
3226 (*queue)->t += (*node)->t;
3227 }
3228 (*node)->next = NULL;
3229 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3230 coap_session_str(session), (*node)->id);
3231 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3232 session->con_active--;
3233 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3234 /* Flush out any entries on session->delayqueue */
3235 coap_session_connected(session);
3236 }
3237 return 1;
3238 }
3239
3240 /* search token in queue to remove (only first occurrence will be removed) */
3241 q = *queue;
3242 do {
3243 p = q;
3244 q = q->next;
3245 } while (q && (session != q->session ||
3246 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3247
3248 if (q) { /* found token */
3249 p->next = q->next;
3250 if (p->next) { /* must update relative time of p->next */
3251 p->next->t += q->t;
3252 }
3253 q->next = NULL;
3254 *node = q;
3255 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3256 coap_session_str(session), (*node)->id);
3257 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3258 session->con_active--;
3259 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3260 /* Flush out any entries on session->delayqueue */
3261 coap_session_connected(session);
3262 }
3263 return 1;
3264 }
3265
3266 return 0;
3267
3268}
3269
3270void
3272 coap_nack_reason_t reason) {
3273 coap_queue_t *p, *q;
3274
3275 while (context->sendqueue && context->sendqueue->session == session) {
3276 q = context->sendqueue;
3277 context->sendqueue = q->next;
3278 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3279 coap_session_str(session), q->id);
3280 if (q->pdu->type == COAP_MESSAGE_CON) {
3281 coap_handle_nack(session, q->pdu, reason, q->id);
3282 }
3284 }
3285
3286 if (!context->sendqueue)
3287 return;
3288
3289 p = context->sendqueue;
3290 q = p->next;
3291
3292 while (q) {
3293 if (q->session == session) {
3294 p->next = q->next;
3295 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3296 coap_session_str(session), q->id);
3297 if (q->pdu->type == COAP_MESSAGE_CON) {
3298 coap_handle_nack(session, q->pdu, reason, q->id);
3299 }
3301 q = p->next;
3302 } else {
3303 p = q;
3304 q = q->next;
3305 }
3306 }
3307}
3308
3309void
3311 coap_bin_const_t *token) {
3312 /* cancel all messages in sendqueue that belong to session
3313 * and use the specified token */
3314 coap_queue_t **p, *q;
3315
3316 if (!context->sendqueue)
3317 return;
3318
3319 p = &context->sendqueue;
3320 q = *p;
3321
3322 while (q) {
3323 if (q->session == session &&
3324 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3325 *p = q->next;
3326 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3327 coap_session_str(session), q->id);
3328 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3329 session->con_active--;
3330 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3331 /* Flush out any entries on session->delayqueue */
3332 coap_session_connected(session);
3333 }
3335 } else {
3336 p = &(q->next);
3337 }
3338 q = *p;
3339 }
3340}
3341
3342coap_pdu_t *
3344 coap_opt_filter_t *opts) {
3345 coap_opt_iterator_t opt_iter;
3346 coap_pdu_t *response;
3347 unsigned char type;
3348
3349#if COAP_ERROR_PHRASE_LENGTH > 0
3350 const char *phrase;
3351 if (code != COAP_RESPONSE_CODE(508)) {
3352 phrase = coap_response_phrase(code);
3353 } else {
3354 phrase = NULL;
3355 }
3356#endif
3357
3358 assert(request);
3359
3360 /* cannot send ACK if original request was not confirmable */
3361 type = request->type == COAP_MESSAGE_CON ?
3363
3364 /* Now create the response and fill with options and payload data. */
3365 response = coap_pdu_init(type, code, request->mid,
3366 request->session ?
3367 coap_session_max_pdu_size_lkd(request->session) : 512);
3368 if (response) {
3369 /* copy token */
3370 if (request->actual_token.length &&
3371 !coap_add_token(response, request->actual_token.length,
3372 request->actual_token.s)) {
3373 coap_log_debug("cannot add token to error response\n");
3374 coap_delete_pdu_lkd(response);
3375 return NULL;
3376 }
3377 if (response->code == COAP_RESPONSE_CODE(402)) {
3378 char buf[128];
3379 int first = 1;
3380 int i;
3381 size_t len;
3382
3383#if COAP_ERROR_PHRASE_LENGTH > 0
3384 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3385#else
3386 buf[0] = '\000';
3387#endif
3388 /* copy all reported options into diagnostic message */
3389 for (i = COAP_OPT_FILTER_SHORT - 1; i >= 0; i--) {
3390 if (opts->mask & (1 << (COAP_OPT_FILTER_LONG + i))) {
3391 len = strlen(buf);
3392 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",",
3393 opts->short_opts[i]);
3394 first = 0;
3395 }
3396 }
3397 for (i = COAP_OPT_FILTER_LONG - 1; i >= 0; i--) {
3398 if (opts->mask & (1 << i)) {
3399 len = strlen(buf);
3400 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",",
3401 opts->long_opts[i]);
3402 first = 0;
3403 }
3404 }
3405 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3406 } else if (opts && opts->mask) {
3407 coap_opt_t *option;
3408
3409 /* copy all options */
3410 coap_option_iterator_init(request, &opt_iter, opts);
3411 while ((option = coap_option_next(&opt_iter))) {
3412 coap_add_option_internal(response, opt_iter.number,
3413 coap_opt_length(option),
3414 coap_opt_value(option));
3415 }
3416#if COAP_ERROR_PHRASE_LENGTH > 0
3417 if (phrase)
3418 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3419 } else {
3420 /* note that diagnostic messages do not need a Content-Format option. */
3421 if (phrase)
3422 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3423#endif
3424 }
3425 }
3426
3427 return response;
3428}
3429
3430#if COAP_SERVER_SUPPORT
3431#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3432
3433static void
3434free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3435 coap_delete_string(app_ptr);
3436}
3437
3438/*
3439 * Caution: As this handler is in libcoap space, it is called with
3440 * context locked.
3441 */
3442static void
3443hnd_get_wellknown_lkd(coap_resource_t *resource,
3444 coap_session_t *session,
3445 const coap_pdu_t *request,
3446 const coap_string_t *query,
3447 coap_pdu_t *response) {
3448 size_t len = 0;
3449 coap_string_t *data_string = NULL;
3450 coap_print_status_t result = 0;
3451 size_t wkc_len = 0;
3452 uint8_t buf[4];
3453
3454 /*
3455 * Quick hack to determine the size of the resource descriptions for
3456 * .well-known/core.
3457 */
3458 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3459 if (result & COAP_PRINT_STATUS_ERROR) {
3460 coap_log_warn("cannot determine length of /.well-known/core\n");
3461 goto error;
3462 }
3463
3464 if (wkc_len > 0) {
3465 data_string = coap_new_string(wkc_len);
3466 if (!data_string)
3467 goto error;
3468
3469 len = wkc_len;
3470 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3471 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3472 coap_log_debug("coap_print_wellknown failed\n");
3473 goto error;
3474 }
3475 assert(len <= (size_t)wkc_len);
3476 data_string->length = len;
3477
3478 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3480 coap_encode_var_safe(buf, sizeof(buf),
3482 goto error;
3483 }
3484 if (response->used_size + len + 1 > response->max_size) {
3485 /*
3486 * Data does not fit into a packet and no libcoap block support
3487 * +1 for end of options marker
3488 */
3489 coap_log_debug(".well-known/core: truncating data length to %" PRIuS " from %" PRIuS "\n",
3490 len, response->max_size - response->used_size - 1);
3491 len = response->max_size - response->used_size - 1;
3492 }
3493 if (!coap_add_data(response, len, data_string->s)) {
3494 goto error;
3495 }
3496 free_wellknown_response(session, data_string);
3497 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3498 response, query,
3500 -1, 0, data_string->length,
3501 data_string->s,
3502 free_wellknown_response,
3503 data_string)) {
3504 goto error_released;
3505 }
3506 } else {
3508 coap_encode_var_safe(buf, sizeof(buf),
3510 goto error;
3511 }
3512 }
3513 response->code = COAP_RESPONSE_CODE(205);
3514 return;
3515
3516error:
3517 free_wellknown_response(session, data_string);
3518error_released:
3519 if (response->code == 0) {
3520 /* set error code 5.03 and remove all options and data from response */
3521 response->code = COAP_RESPONSE_CODE(503);
3522 response->used_size = response->e_token_length;
3523 response->data = NULL;
3524 }
3525}
3526#endif /* COAP_SERVER_SUPPORT */
3527
3538static int
3540 int num_cancelled = 0; /* the number of observers cancelled */
3541
3542#ifndef COAP_SERVER_SUPPORT
3543 (void)sent;
3544#endif /* ! COAP_SERVER_SUPPORT */
3545 (void)context;
3546
3547#if COAP_SERVER_SUPPORT
3548 /* remove observer for this resource, if any
3549 * Use token from sent and try to find a matching resource. Uh!
3550 */
3551 RESOURCES_ITER(context->resources, r) {
3552 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3553 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3554 }
3555#endif /* COAP_SERVER_SUPPORT */
3556
3557 return num_cancelled;
3558}
3559
3560#if COAP_SERVER_SUPPORT
3565enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3566
3567/*
3568 * Checks for No-Response option in given @p request and
3569 * returns @c RESPONSE_DROP if @p response should be suppressed
3570 * according to RFC 7967.
3571 *
3572 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3573 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3574 * on retrying.
3575 *
3576 * Checks if the response code is 0.00 and if either the session is reliable or
3577 * non-confirmable, @c RESPONSE_DROP is also returned.
3578 *
3579 * Multicast response checking is also carried out.
3580 *
3581 * NOTE: It is the responsibility of the application to determine whether
3582 * a delayed separate response should be sent as the original requesting packet
3583 * containing the No-Response option has long since gone.
3584 *
3585 * The value of the No-Response option is encoded as
3586 * follows:
3587 *
3588 * @verbatim
3589 * +-------+-----------------------+-----------------------------------+
3590 * | Value | Binary Representation | Description |
3591 * +-------+-----------------------+-----------------------------------+
3592 * | 0 | <empty> | Interested in all responses. |
3593 * +-------+-----------------------+-----------------------------------+
3594 * | 2 | 00000010 | Not interested in 2.xx responses. |
3595 * +-------+-----------------------+-----------------------------------+
3596 * | 8 | 00001000 | Not interested in 4.xx responses. |
3597 * +-------+-----------------------+-----------------------------------+
3598 * | 16 | 00010000 | Not interested in 5.xx responses. |
3599 * +-------+-----------------------+-----------------------------------+
3600 * @endverbatim
3601 *
3602 * @param request The CoAP request to check for the No-Response option.
3603 * This parameter must not be NULL.
3604 * @param response The response that is potentially suppressed.
3605 * This parameter must not be NULL.
3606 * @param session The session this request/response are associated with.
3607 * This parameter must not be NULL.
3608 * @return RESPONSE_DEFAULT when no special treatment is requested,
3609 * RESPONSE_DROP when the response must be discarded, or
3610 * RESPONSE_SEND when the response must be sent.
3611 */
3612static enum respond_t
3613no_response(coap_pdu_t *request, coap_pdu_t *response,
3614 coap_session_t *session, coap_resource_t *resource) {
3615 coap_opt_t *nores;
3616 coap_opt_iterator_t opt_iter;
3617 unsigned int val = 0;
3618
3619 assert(request);
3620 assert(response);
3621
3622 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3623 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3624
3625 if (nores) {
3627
3628 /* The response should be dropped when the bit corresponding to
3629 * the response class is set (cf. table in function
3630 * documentation). When a No-Response option is present and the
3631 * bit is not set, the sender explicitly indicates interest in
3632 * this response. */
3633 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3634 /* Should be dropping the response */
3635 if (response->type == COAP_MESSAGE_ACK &&
3636 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3637 /* Still need to ACK the request */
3638 response->code = 0;
3639 /* Remove token/data from piggybacked acknowledgment PDU */
3640 response->actual_token.length = 0;
3641 response->e_token_length = 0;
3642 response->used_size = 0;
3643 response->data = NULL;
3644 return RESPONSE_SEND;
3645 } else {
3646 return RESPONSE_DROP;
3647 }
3648 } else {
3649 /* True for mcast as well RFC7967 2.1 */
3650 return RESPONSE_SEND;
3651 }
3652 } else if (resource && session->context->mcast_per_resource &&
3653 coap_is_mcast(&session->addr_info.local)) {
3654 /* Handle any mcast suppression specifics if no NoResponse option */
3655 if ((resource->flags &
3657 COAP_RESPONSE_CLASS(response->code) == 2) {
3658 return RESPONSE_DROP;
3659 } else if ((resource->flags &
3661 response->code == COAP_RESPONSE_CODE(205)) {
3662 if (response->data == NULL)
3663 return RESPONSE_DROP;
3664 } else if ((resource->flags &
3666 COAP_RESPONSE_CLASS(response->code) == 4) {
3667 return RESPONSE_DROP;
3668 } else if ((resource->flags &
3670 COAP_RESPONSE_CLASS(response->code) == 5) {
3671 return RESPONSE_DROP;
3672 }
3673 }
3674 } else if (COAP_PDU_IS_EMPTY(response) &&
3675 (response->type == COAP_MESSAGE_NON ||
3676 COAP_PROTO_RELIABLE(session->proto))) {
3677 /* response is 0.00, and this is reliable or non-confirmable */
3678 return RESPONSE_DROP;
3679 }
3680
3681 /*
3682 * Do not send error responses for requests that were received via
3683 * IP multicast. RFC7252 8.1
3684 */
3685
3686 if (coap_is_mcast(&session->addr_info.local)) {
3687 if (request->type == COAP_MESSAGE_NON &&
3688 response->type == COAP_MESSAGE_RST)
3689 return RESPONSE_DROP;
3690
3691 if ((!resource || session->context->mcast_per_resource == 0) &&
3692 COAP_RESPONSE_CLASS(response->code) > 2)
3693 return RESPONSE_DROP;
3694 }
3695
3696 /* Default behavior applies when we are not dealing with a response
3697 * (class == 0) or the request did not contain a No-Response option.
3698 */
3699 return RESPONSE_DEFAULT;
3700}
3701
3702static coap_str_const_t coap_default_uri_wellknown = {
3704 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3705};
3706
3707/* Initialized in coap_startup() */
3708static coap_resource_t resource_uri_wellknown;
3709
3710static void
3711handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3712 coap_pdu_t *orig_pdu) {
3714 coap_pdu_t *response = NULL;
3715 coap_opt_filter_t opt_filter;
3716 coap_resource_t *resource = NULL;
3717 /* The respond field indicates whether a response must be treated
3718 * specially due to a No-Response option that declares disinterest
3719 * or interest in a specific response class. DEFAULT indicates that
3720 * No-Response has not been specified. */
3721 enum respond_t respond = RESPONSE_DEFAULT;
3722 coap_opt_iterator_t opt_iter;
3723 coap_opt_t *opt;
3724 int is_proxy_uri = 0;
3725 int is_proxy_scheme = 0;
3726 int skip_hop_limit_check = 0;
3727 int resp = 0;
3728 coap_string_t *query = NULL;
3729 coap_opt_t *observe = NULL;
3730 coap_string_t *uri_path = NULL;
3731 int observe_action = COAP_OBSERVE_CANCEL;
3732 coap_block_b_t block;
3733 int added_block = 0;
3734 coap_lg_srcv_t *free_lg_srcv = NULL;
3735#if COAP_Q_BLOCK_SUPPORT
3736 int lg_xmit_ctrl = 0;
3737#endif /* COAP_Q_BLOCK_SUPPORT */
3738#if COAP_ASYNC_SUPPORT
3739 coap_async_t *async;
3740#endif /* COAP_ASYNC_SUPPORT */
3741
3742#if COAP_ASYNC_SUPPORT
3743 async = coap_find_async_lkd(session, pdu->actual_token);
3744 if (async) {
3745 coap_tick_t now;
3746
3747 coap_ticks(&now);
3748 if (async->delay == 0 || async->delay > now) {
3749 /* re-transmit missing ACK (only if CON) */
3750 coap_log_info("Retransmit async response\n");
3751 coap_send_ack_lkd(session, pdu);
3752 /* and do not pass on to the upper layers */
3753 return;
3754 }
3755 }
3756#endif /* COAP_ASYNC_SUPPORT */
3757
3758 coap_option_filter_clear(&opt_filter);
3759 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3760 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3761 if (opt) {
3762 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3763 if (!opt) {
3764 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3765 resp = 402;
3766 goto fail_response;
3767 }
3768 is_proxy_scheme = 1;
3769 }
3770
3771 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3772 if (opt)
3773 is_proxy_uri = 1;
3774 }
3775
3776 if (is_proxy_scheme || is_proxy_uri) {
3777 coap_uri_t uri;
3778
3779 if (!context->proxy_uri_resource) {
3780 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3781 coap_log_debug("Proxy-%s support not configured\n",
3782 is_proxy_scheme ? "Scheme" : "Uri");
3783 resp = 505;
3784 goto fail_response;
3785 }
3786 if (((size_t)pdu->code - 1 <
3787 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3788 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3789 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3790 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3791 is_proxy_scheme ? "Scheme" : "Uri",
3792 pdu->code/100, pdu->code%100);
3793 resp = 505;
3794 goto fail_response;
3795 }
3796
3797 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3798 if (is_proxy_uri) {
3800 coap_opt_length(opt), &uri) < 0) {
3801 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3802 coap_log_debug("Proxy-URI not decodable\n");
3803 resp = 505;
3804 goto fail_response;
3805 }
3806 } else {
3807 memset(&uri, 0, sizeof(uri));
3808 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3809 if (opt) {
3810 uri.host.length = coap_opt_length(opt);
3811 uri.host.s = coap_opt_value(opt);
3812 } else
3813 uri.host.length = 0;
3814 }
3815
3816 resource = context->proxy_uri_resource;
3817 if (uri.host.length && resource->proxy_name_count &&
3818 resource->proxy_name_list) {
3819 size_t i;
3820
3821 if (resource->proxy_name_count == 1 &&
3822 resource->proxy_name_list[0]->length == 0) {
3823 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3824 i = 0;
3825 } else {
3826 for (i = 0; i < resource->proxy_name_count; i++) {
3827 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3828 break;
3829 }
3830 }
3831 }
3832 if (i != resource->proxy_name_count) {
3833 /* This server is hosting the proxy connection endpoint */
3834 if (pdu->crit_opt) {
3835 /* Cannot handle critical option */
3836 pdu->crit_opt = 0;
3837 resp = 402;
3838 resource = NULL;
3839 goto fail_response;
3840 }
3841 is_proxy_uri = 0;
3842 is_proxy_scheme = 0;
3843 skip_hop_limit_check = 1;
3844 }
3845 }
3846 resource = NULL;
3847 }
3848 assert(resource == NULL);
3849
3850 if (!skip_hop_limit_check) {
3851 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3852 if (opt) {
3853 size_t hop_limit;
3854 uint8_t buf[4];
3855
3856 hop_limit =
3858 if (hop_limit == 1) {
3859 /* coap_send_internal() will fill in the IP address for us */
3860 resp = 508;
3861 goto fail_response;
3862 } else if (hop_limit < 1 || hop_limit > 255) {
3863 /* Need to return a 4.00 RFC8768 Section 3 */
3864 coap_log_info("Invalid Hop Limit\n");
3865 resp = 400;
3866 goto fail_response;
3867 }
3868 hop_limit--;
3870 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3871 buf);
3872 }
3873 }
3874
3875 uri_path = coap_get_uri_path(pdu);
3876 if (!uri_path) {
3877 resp = 402;
3878 goto fail_response;
3879 }
3880
3881 if (!is_proxy_uri && !is_proxy_scheme) {
3882 /* try to find the resource from the request URI */
3883 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3884 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3885 }
3886
3887 if ((resource == NULL) || (resource->is_unknown == 1) ||
3888 (resource->is_proxy_uri == 1)) {
3889 /* The resource was not found or there is an unexpected match against the
3890 * resource defined for handling unknown or proxy URIs.
3891 */
3892 if (resource != NULL)
3893 /* Close down unexpected match */
3894 resource = NULL;
3895 /*
3896 * Check if the request URI happens to be the well-known URI, or if the
3897 * unknown resource handler is defined, a PUT or optionally other methods,
3898 * if configured, for the unknown handler.
3899 *
3900 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3901 * proxy URI handler.
3902 *
3903 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3904 * set, call the unknown URI handler with any unknown URI (including
3905 * .well-known/core) if the appropriate method is defined.
3906 *
3907 * else if well-known URI generate a default response.
3908 *
3909 * else if unknown URI handler defined, call the unknown
3910 * URI handler (to allow for potential generation of resource
3911 * [RFC7272 5.8.3]) if the appropriate method is defined.
3912 *
3913 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3914 *
3915 * else return 4.04.
3916 */
3917
3918 if (is_proxy_uri || is_proxy_scheme) {
3919 resource = context->proxy_uri_resource;
3920 } else if (context->unknown_resource != NULL &&
3921 context->unknown_resource->flags & COAP_RESOURCE_HANDLE_WELLKNOWN_CORE &&
3922 ((size_t)pdu->code - 1 <
3923 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3924 (context->unknown_resource->handler[pdu->code - 1])) {
3925 resource = context->unknown_resource;
3926 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3927 /* request for .well-known/core */
3928 resource = &resource_uri_wellknown;
3929 } else if ((context->unknown_resource != NULL) &&
3930 ((size_t)pdu->code - 1 <
3931 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3932 (context->unknown_resource->handler[pdu->code - 1])) {
3933 /*
3934 * The unknown_resource can be used to handle undefined resources
3935 * for a PUT request and can support any other registered handler
3936 * defined for it
3937 * Example set up code:-
3938 * r = coap_resource_unknown_init(hnd_put_unknown);
3939 * coap_register_request_handler(r, COAP_REQUEST_POST,
3940 * hnd_post_unknown);
3941 * coap_register_request_handler(r, COAP_REQUEST_GET,
3942 * hnd_get_unknown);
3943 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3944 * hnd_delete_unknown);
3945 * coap_add_resource(ctx, r);
3946 *
3947 * Note: It is not possible to observe the unknown_resource, a separate
3948 * resource must be created (by PUT or POST) which has a GET
3949 * handler to be observed
3950 */
3951 resource = context->unknown_resource;
3952 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3953 /*
3954 * Request for DELETE on non-existent resource (RFC7252: 5.8.4. DELETE)
3955 */
3956 coap_log_debug("request for unknown resource '%*.*s',"
3957 " return 2.02\n",
3958 (int)uri_path->length,
3959 (int)uri_path->length,
3960 uri_path->s);
3961 resp = 202;
3962 goto fail_response;
3963 } else if (context->dyn_create_handler != NULL) {
3964 resource = coap_add_dynamic_resource(session, pdu);
3965 if (!resource) {
3966 resp = 406;
3967 goto fail_response;
3968 }
3969 } else { /* request for any another resource, return 4.04 */
3970
3971 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3972 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3973 resp = 404;
3974 goto fail_response;
3975 }
3976
3977 }
3978
3979 coap_resource_reference_lkd(resource);
3980
3981#if COAP_OSCORE_SUPPORT
3982 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3983 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3984 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3985 resp = 401;
3986 goto fail_response;
3987 }
3988#endif /* COAP_OSCORE_SUPPORT */
3989 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3990 /* Check for existing resource and If-Non-Match */
3991 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3992 if (opt) {
3993 resp = 412;
3994 goto fail_response;
3995 }
3996 }
3997
3998 /* the resource was found, check if there is a registered handler */
3999 if ((size_t)pdu->code - 1 <
4000 sizeof(resource->handler) / sizeof(coap_method_handler_t))
4001 h = resource->handler[pdu->code - 1];
4002
4003 if (h == NULL) {
4004 resp = 405;
4005 goto fail_response;
4006 }
4007 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
4008 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) == NULL) {
4009 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
4010 if (opt == NULL) {
4011 /* RFC 8132 2.3.1 */
4012 resp = 415;
4013 goto fail_response;
4014 }
4015 }
4016 }
4017 if (context->mcast_per_resource &&
4018 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
4019 coap_is_mcast(&session->addr_info.local)) {
4020 resp = 405;
4021 goto fail_response;
4022 }
4023
4024 if (pdu->type == COAP_MESSAGE_CON) {
4025 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, pdu->mid,
4027 } else {
4030 }
4031 if (!response) {
4032 coap_log_err("could not create response PDU\n");
4033 resp = 500;
4034 goto fail_response;
4035 }
4036 response->session = session;
4037#if COAP_ASYNC_SUPPORT
4038 /* If handling a separate response, need CON, not ACK response */
4039 if (async && pdu->type == COAP_MESSAGE_CON)
4040 response->type = COAP_MESSAGE_CON;
4041#endif /* COAP_ASYNC_SUPPORT */
4042 /* A lot of the reliable code assumes type is CON */
4043 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
4044 response->type = COAP_MESSAGE_CON;
4045
4046 if (!coap_add_token(response, pdu->actual_token.length,
4047 pdu->actual_token.s)) {
4048 resp = 500;
4049 goto fail_response;
4050 }
4051
4052 /*
4053 * RFC7959 2.2: the SZX value 7 "is reserved, i.e., MUST NOT be sent and
4054 * MUST lead to a 4.00 Bad Request response code upon reception in a
4055 * request". SZX 7 is only meaningful as the BERT escape (RFC8323 6),
4056 * which needs a reliable transport with BERT negotiated in both CSMs.
4057 * Anywhere else it must be rejected here: coap_get_block_b() reports a
4058 * reserved SZX as "no Block option present", which is indistinguishable
4059 * further down from a request that never carried one.
4060 */
4061 if (COAP_PROTO_NOT_RELIABLE(session->proto) ||
4062 !(session->csm_bert_rem_support && session->csm_bert_loc_support)) {
4063 static const coap_option_num_t block_nums[] = {
4065 };
4066 size_t bn;
4067
4068 for (bn = 0; bn < sizeof(block_nums)/sizeof(block_nums[0]); bn++) {
4069 coap_opt_t *block_opt = coap_check_option(pdu, block_nums[bn], &opt_iter);
4070
4071 if (block_opt && COAP_OPT_BLOCK_SZX(block_opt) == 7) {
4072 coap_log_debug("request: reserved Block SZX 7 (RFC7959 2.2)\n");
4073 resp = 400;
4074 goto fail_response;
4075 }
4076 }
4077 }
4078
4079 query = coap_get_query(pdu);
4080
4081 /* check for Observe option RFC7641 and RFC8132 */
4082 if (resource->observable &&
4083 (pdu->code == COAP_REQUEST_CODE_GET ||
4084 pdu->code == COAP_REQUEST_CODE_FETCH)) {
4085 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
4086 }
4087
4088 /*
4089 * See if blocks need to be aggregated or next requests sent off
4090 * before invoking application request handler
4091 */
4092 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4093 uint32_t block_mode = session->block_mode;
4094
4095 if (observe ||
4096 resource->flags & COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY)
4098 if (coap_handle_request_put_block(context, session, pdu, response,
4099 resource, uri_path, observe,
4100 &added_block, &free_lg_srcv)) {
4101 session->block_mode = block_mode;
4102 goto skip_handler;
4103 }
4104 session->block_mode = block_mode;
4105
4106 if (coap_handle_request_send_block(session, pdu, response, resource,
4107 query)) {
4108#if COAP_Q_BLOCK_SUPPORT
4109 lg_xmit_ctrl = 1;
4110#endif /* COAP_Q_BLOCK_SUPPORT */
4111 goto skip_handler;
4112 }
4113 }
4114
4115 if (observe) {
4116 observe_action =
4118 coap_opt_length(observe));
4119
4120 if (observe_action == COAP_OBSERVE_ESTABLISH) {
4121 coap_subscription_t *subscription;
4122
4123 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
4124 if (block.num != 0) {
4125 response->code = COAP_RESPONSE_CODE(400);
4126 goto skip_handler;
4127 }
4128#if COAP_Q_BLOCK_SUPPORT
4129 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
4130 &block)) {
4131 if (block.num != 0) {
4132 response->code = COAP_RESPONSE_CODE(400);
4133 goto skip_handler;
4134 }
4135#endif /* COAP_Q_BLOCK_SUPPORT */
4136 }
4137 subscription = coap_add_observer(resource, session, &pdu->actual_token,
4138 pdu);
4139 if (subscription) {
4140 uint8_t buf[4];
4141
4142 coap_touch_observer(context, session, &pdu->actual_token);
4144 coap_encode_var_safe(buf, sizeof(buf),
4145 resource->observe),
4146 buf);
4147 }
4148 } else if (observe_action == COAP_OBSERVE_CANCEL) {
4149 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu, free_lg_srcv != NULL);
4150 } else {
4151 coap_log_info("observe: unexpected action %d\n", observe_action);
4152 }
4153 }
4154
4155#if COAP_WITH_OBSERVE_PERSIST
4156 /* If we are maintaining Observe persist */
4157 if (resource == context->unknown_resource) {
4158 context->unknown_pdu = pdu;
4159 context->unknown_session = session;
4160 } else
4161 context->unknown_pdu = NULL;
4162#endif /* COAP_WITH_OBSERVE_PERSIST */
4163
4164 /*
4165 * Call the request handler with everything set up
4166 */
4167 if (resource == &resource_uri_wellknown) {
4168 /* Leave context locked */
4169 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
4170 (int)resource->uri_path->length, (int)resource->uri_path->length,
4171 resource->uri_path->s);
4172 h(resource, session, pdu, query, response);
4173 if (COAP_RESPONSE_CLASS(response->code) == 2 && response->data == NULL &&
4174 coap_is_mcast(&session->addr_info.local)) {
4175 goto drop_it_debug;
4176 }
4177 } else {
4178 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
4179 (int)resource->uri_path->length, (int)resource->uri_path->length,
4180 resource->uri_path->s);
4181 if (resource->flags & COAP_RESOURCE_SAFE_REQUEST_HANDLER) {
4182 coap_lock_callback_release(h(resource, session, pdu, query, response),
4183 /* context is being freed off */
4184 goto finish);
4185 } else {
4187 h(resource, session, pdu, query, response),
4188 /* context is being freed off */
4189 goto finish);
4190 }
4191 }
4192
4193 /* Check validity of response code */
4194 if (!coap_check_code_class(session, response)) {
4195 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
4196 COAP_RESPONSE_CLASS(response->code),
4197 response->code & 0x1f);
4198 goto drop_it_no_debug;
4199 }
4200
4201 /* Check correct content type returned by application */
4202 if (response->code != 0 && (opt = coap_check_option(pdu, COAP_OPTION_ACCEPT, &opt_iter)) &&
4203 !(COAP_RESPONSE_CLASS(response->code) == 4 || COAP_RESPONSE_CLASS(response->code) == 5)) {
4204 coap_opt_t *ropt = coap_check_option(response, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
4205
4206 if (!ropt) {
4208 coap_opt_length(opt), coap_opt_value(opt));
4209 } else if (coap_opt_length(opt) != coap_opt_length(ropt) ||
4210 memcmp(coap_opt_value(opt), coap_opt_value(ropt), coap_opt_length(opt)) != 0) {
4211 coap_show_pdu(COAP_LOG_DEBUG, response);
4212 coap_log_debug("handle_request: response: Invalid Content-Format\n");
4213 /* Need to convert response to 4.06 as incorrect content type */
4214 response->code = COAP_RESPONSE_CODE(406);
4215 response->used_size = response->e_token_length;
4216 response->data = NULL;
4217 response->max_opt = 0;
4219 coap_opt_length(opt),
4220 coap_opt_value(opt));
4221 coap_add_data(response, sizeof("Not Acceptable")-1, (const uint8_t *)"Not Acceptable");
4222 }
4223 }
4224
4225 /* Check if lg_xmit generated and update PDU code if so */
4226 coap_check_code_lg_xmit(session, pdu, response, resource, query);
4227
4228 if (free_lg_srcv) {
4229 /* Check to see if the server is doing a 4.01 + Echo response */
4230 if (response->code == COAP_RESPONSE_CODE(401) &&
4231 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
4232 /* Need to keep lg_srcv around for client's response */
4233 } else {
4234 coap_lg_srcv_t *lg_srcv;
4235 /*
4236 * Need to check free_lg_srcv still exists in case of error or timing window
4237 */
4238 LL_FOREACH(session->lg_srcv, lg_srcv) {
4239 if (lg_srcv == free_lg_srcv) {
4240#if COAP_Q_BLOCK_SUPPORT
4241 if (lg_srcv->block_option == COAP_OPTION_Q_BLOCK1) {
4242 coap_tick_t adjust;
4243
4244 /* cache the lg_srcv for 1 second */
4247 } else {
4248 adjust = 0;
4249 }
4250 coap_ticks(&free_lg_srcv->rec_blocks.last_seen);
4251 if (free_lg_srcv->rec_blocks.last_seen > adjust) {
4252 free_lg_srcv->rec_blocks.last_seen -= adjust;
4253 }
4254 free_lg_srcv->dont_timeout = 0;
4255 break;
4256 }
4257#endif /* COAP_Q_BLOCK_SUPPORT */
4258 LL_DELETE(session->lg_srcv, free_lg_srcv);
4259 coap_block_delete_lg_srcv(session, free_lg_srcv);
4260 break;
4261 }
4262 }
4263 }
4264 }
4265 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
4266 /* Just in case, as there are more to go */
4267 response->code = COAP_RESPONSE_CODE(231);
4268 }
4269
4270skip_handler:
4271 respond = no_response(pdu, response, session, resource);
4272 if (respond != RESPONSE_DROP) {
4273#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
4274 coap_mid_t mid = pdu->mid;
4275#endif
4276 if (COAP_RESPONSE_CLASS(response->code) != 2) {
4277 if (observe) {
4279 }
4280 }
4281 if (COAP_RESPONSE_CLASS(response->code) > 2) {
4282 if (observe)
4283 coap_delete_observer(resource, session, &pdu->actual_token);
4284 if (response->code != COAP_RESPONSE_CODE(413))
4286 }
4287
4288 /* If original request contained a token, and the registered
4289 * application handler made no changes to the response, then
4290 * this is an empty ACK with a token, which is a malformed
4291 * PDU */
4292 if ((response->type == COAP_MESSAGE_ACK)
4293 && (response->code == 0)) {
4294 /* Remove token from otherwise-empty acknowledgment PDU */
4295 response->actual_token.length = 0;
4296 response->e_token_length = 0;
4297 response->used_size = 0;
4298 response->data = NULL;
4299 }
4300
4301 if (!coap_is_mcast(&session->addr_info.local) ||
4302 (context->mcast_per_resource &&
4303 resource &&
4304 (resource->flags & COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS))) {
4305 /* No delays to response */
4306#if COAP_Q_BLOCK_SUPPORT
4307 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4308 !lg_xmit_ctrl && COAP_RESPONSE_CLASS(response->code) == 2 &&
4309 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4310 block.m) {
4311 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4312 response,
4313 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4314 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4315 response = NULL;
4316 goto finish;
4317 }
4318#endif /* COAP_Q_BLOCK_SUPPORT */
4319 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4320 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4321 goto finish;
4322 }
4323 } else {
4324 /* Need to delay mcast response */
4325 coap_queue_t *node = coap_new_node();
4326 uint8_t r;
4327 coap_tick_t delay;
4328
4329 if (!node) {
4330 coap_log_debug("mcast delay: insufficient memory\n");
4331 goto drop_it_no_debug;
4332 }
4333 if (!coap_pdu_encode_header(response, session->proto)) {
4335 goto drop_it_no_debug;
4336 }
4337
4338 node->id = response->mid;
4339 node->pdu = response;
4340 node->is_mcast = 1;
4341 coap_prng_lkd(&r, sizeof(r));
4342 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4343 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4344 coap_session_str(session),
4345 response->mid,
4346 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4347 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4348 1000 / COAP_TICKS_PER_SECOND));
4349 node->timeout = (unsigned int)delay;
4350 /* Use this to delay transmission */
4351 coap_wait_ack(session->context, session, node);
4352 }
4353 } else if (COAP_PDU_IS_EMPTY(response) &&
4354 (response->type == COAP_MESSAGE_NON ||
4355 COAP_PROTO_RELIABLE(session->proto))) {
4356 coap_delete_pdu_lkd(response);
4357 } else {
4358drop_it_debug:
4359 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4360 coap_session_str(session),
4361 response->mid);
4362 coap_show_pdu(COAP_LOG_DEBUG, response);
4363drop_it_no_debug:
4364 coap_delete_pdu_lkd(response);
4365 }
4366#if COAP_Q_BLOCK_SUPPORT
4367 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4368 if (COAP_PROTO_RELIABLE(session->proto)) {
4369 if (block.m) {
4370 /* All of the sequence not in yet */
4371 goto finish;
4372 }
4373 } else if (pdu->type == COAP_MESSAGE_NON) {
4374 /* More to go and not at a payload break */
4375 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4376 goto finish;
4377 }
4378 }
4379 }
4380#endif /* COAP_Q_BLOCK_SUPPORT */
4381
4382finish:
4383 if (query)
4384 coap_delete_string(query);
4385 if (resource)
4386 coap_resource_release_lkd(resource);
4387 coap_delete_string(uri_path);
4388 return;
4389
4390fail_response:
4391 coap_delete_pdu_lkd(response);
4392 response =
4394 &opt_filter);
4395 if (response)
4396 goto skip_handler;
4397 if (resource)
4398 coap_resource_release_lkd(resource);
4399 coap_delete_string(uri_path);
4400}
4401#endif /* COAP_SERVER_SUPPORT */
4402
4403#if COAP_CLIENT_SUPPORT
4404/* Call application-specific response handler when available. */
4405void
4407 coap_pdu_t *sent, coap_pdu_t *rcvd,
4408 void *body_data) {
4409 coap_context_t *context = session->context;
4410 coap_response_t ret;
4411
4412#if COAP_PROXY_SUPPORT
4413 if (context->proxy_response_cb) {
4414 coap_proxy_entry_t *proxy_entry;
4415 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4416 rcvd,
4417 &proxy_entry);
4418
4419 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4420 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4421 proxy_entry);
4422 return;
4423 }
4424 }
4425#endif /* COAP_PROXY_SUPPORT */
4426 if (session->doing_send_recv && session->req_token &&
4427 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4428 /* processing coap_send_recv() call */
4429 session->resp_pdu = rcvd;
4431 /* Will get freed off when PDU is freed off */
4432 rcvd->data_free = body_data;
4433 coap_send_ack_lkd(session, rcvd);
4435 return;
4436 } else if (context->response_cb) {
4438 context->response_cb(session,
4439 sent,
4440 rcvd,
4441 rcvd->mid),
4442 /* context is being freed off */
4443 return);
4444 } else {
4445 ret = COAP_RESPONSE_OK;
4446 }
4447 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4448 coap_send_rst_lkd(session, rcvd);
4450 } else {
4451 coap_send_ack_lkd(session, rcvd);
4453 }
4454 coap_free_type(COAP_STRING, body_data);
4455}
4456
4457static void
4458handle_response(coap_context_t *context, coap_session_t *session,
4459 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4460
4461 /* Set in case there is a later call to coap_update_token() */
4462 rcvd->session = session;
4463
4464 /* Check for message duplication */
4465 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4466 if (rcvd->type == COAP_MESSAGE_CON) {
4467 if (rcvd->mid == session->last_resp_mid) {
4468 /* Duplicate response: send ACK/RST, but don't process */
4469 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4470 coap_send_ack_lkd(session, rcvd);
4471 else
4472 coap_send_rst_lkd(session, rcvd);
4473 return;
4474 }
4475 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4476 if (rcvd->mid == session->last_resp_mid) {
4477 /* Duplicate response */
4478 return;
4479 }
4480 }
4481 session->last_resp_mid = rcvd->mid;
4482 }
4483 /* Check to see if checking out extended token support */
4484 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4485 session->last_token) {
4486 coap_lg_crcv_t *lg_crcv;
4487
4488 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4489 rcvd->actual_token.length != session->max_token_size ||
4490 rcvd->code == COAP_RESPONSE_CODE(400) ||
4491 rcvd->code == COAP_RESPONSE_CODE(503)) {
4492 coap_log_debug("Extended Token requested size support not available\n");
4494 } else {
4495 coap_log_debug("Extended Token support available\n");
4496 }
4498 /* Need to remove lg_crcv set up for this test */
4499 lg_crcv = coap_find_lg_crcv(session, rcvd);
4500 if (lg_crcv) {
4501 LL_DELETE(session->lg_crcv, lg_crcv);
4502 coap_block_delete_lg_crcv(session, lg_crcv);
4503 }
4504 coap_send_ack_lkd(session, rcvd);
4505 coap_reset_doing_first(session);
4506 return;
4507 }
4508#if COAP_Q_BLOCK_SUPPORT
4509 /* Check to see if checking out Q-Block support */
4510 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
4511 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4512 coap_log_debug("Q-Block support not available\n");
4513 set_block_mode_drop_q(session->block_mode);
4514 } else {
4515 coap_block_b_t qblock;
4516
4517 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4518 coap_log_debug("Q-Block support available\n");
4519 set_block_mode_has_q(session->block_mode);
4520 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4521 /* Flush out any entries on session->delayqueue */
4522 coap_session_connected(session);
4523 } else {
4524 coap_log_debug("Q-Block support not available\n");
4525 set_block_mode_drop_q(session->block_mode);
4526 }
4527 }
4528 coap_send_ack_lkd(session, rcvd);
4529 coap_reset_doing_first(session);
4530 return;
4531 }
4532#endif /* COAP_Q_BLOCK_SUPPORT */
4533
4534 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4535 /* See if need to send next block to server */
4536 if (coap_handle_response_send_block(session, sent, rcvd)) {
4537 /* Next block transmitted, no need to inform app */
4538 coap_send_ack_lkd(session, rcvd);
4539 return;
4540 }
4541
4542 /* Need to see if needing to request next block */
4543 if (coap_handle_response_get_block(context, session, sent, rcvd,
4544 COAP_RECURSE_OK)) {
4545 /* Next block transmitted, ack sent no need to inform app */
4546 return;
4547 }
4548 }
4549 coap_reset_doing_first(session);
4550
4551 /* Call application-specific response handler when available. */
4552 coap_call_response_handler(session, sent, rcvd, NULL);
4553}
4554#endif /* COAP_CLIENT_SUPPORT */
4555
4556#if !COAP_DISABLE_TCP
4557static void
4559 coap_pdu_t *pdu) {
4560 coap_opt_iterator_t opt_iter;
4561 coap_opt_t *option;
4562 int set_mtu = 0;
4563
4564 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4565
4566 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4567 if (session->csm_not_seen) {
4568 coap_tick_t now;
4569
4570 coap_ticks(&now);
4571 /* CSM timeout before CSM seen */
4572 coap_log_warn("***%s: CSM received after CSM timeout\n",
4573 coap_session_str(session));
4574 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4575 coap_session_str(session),
4576 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4577 }
4578 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4580 }
4581 while ((option = coap_option_next(&opt_iter))) {
4582 unsigned max_recv;
4583
4584 switch ((coap_sig_csm_opt_t)opt_iter.number) {
4586 max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4587 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4589 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4590 coap_session_str(session), max_recv);
4591 }
4592 coap_session_set_mtu(session, max_recv);
4593 set_mtu = 1;
4594 break;
4596 session->csm_block_supported = 1;
4597 break;
4599 session->max_token_size =
4601 coap_opt_length(option));
4604 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4607 break;
4608 default:
4609 break;
4610 }
4611 }
4612 if (set_mtu) {
4613 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4614 session->csm_bert_rem_support = 1;
4615 else
4616 session->csm_bert_rem_support = 0;
4617 }
4618 if (session->state == COAP_SESSION_STATE_CSM)
4619 coap_session_connected(session);
4620 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4622 if (context->ping_cb) {
4623 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4624 }
4625 if (pong) {
4627 0, NULL);
4628 coap_send_internal(session, pong, NULL);
4629 }
4630 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4631 session->last_pong = session->last_rx_tx;
4632 session->ping_failed = 0;
4633 if (context->pong_cb) {
4634 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4635 }
4636 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4637 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4639 }
4640}
4641#endif /* !COAP_DISABLE_TCP */
4642
4643static int
4644check_token_size(coap_session_t *session, const coap_pdu_t *pdu, int is_local_mcast) {
4645 if (COAP_PDU_IS_REQUEST(pdu) &&
4646 pdu->actual_token.length >
4647 (session->type == COAP_SESSION_TYPE_CLIENT ?
4648 session->max_token_size : session->context->max_token_size)) {
4649 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4650 if (is_local_mcast)
4651 return 0;
4652 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4653 coap_opt_filter_t opt_filter;
4654 coap_pdu_t *response;
4655
4656 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4657 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4658 &opt_filter);
4659 if (!response) {
4660 coap_log_warn("coap_dispatch: cannot create error response\n");
4661 } else {
4662 /*
4663 * Note - have to leave in oversize token as per
4664 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4665 */
4666 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4667 coap_log_warn("coap_dispatch: error sending response\n");
4668 }
4669 } else {
4670 /* Indicate no extended token support */
4671 coap_send_rst_lkd(session, pdu);
4672 }
4673 return 0;
4674 }
4675 return 1;
4676}
4677
4678void
4680 coap_pdu_t *pdu) {
4681 coap_queue_t *sent = NULL;
4682 coap_pdu_t *response;
4683 coap_pdu_t *orig_pdu = NULL;
4684 coap_opt_filter_t opt_filter;
4685 int is_ping_rst;
4686 int packet_is_bad = 0;
4687#if COAP_OSCORE_SUPPORT
4688 coap_opt_iterator_t opt_iter;
4689 coap_pdu_t *dec_pdu = NULL;
4690#endif /* COAP_OSCORE_SUPPORT */
4691 int is_ext_token_rst = 0;
4692 int oscore_invalid = 0;
4693 int is_local_mcast = 0;
4694
4696 pdu->session = session;
4698
4699 if (COAP_PDU_IS_REQUEST(pdu) && coap_is_mcast(&session->addr_info.local)) {
4700 /* Need to be careful with responses to multicast requests */
4701 is_local_mcast = 1;
4702 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
4703 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
4704 return;
4705 }
4706 }
4707
4708 /* Check validity of received code */
4709 if (!coap_check_code_class(session, pdu)) {
4710 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4712 pdu->code & 0x1f);
4713 packet_is_bad = 1;
4714 if (pdu->type == COAP_MESSAGE_CON) {
4716 }
4717 /* find message id in sendqueue to stop retransmission (code is not 0.00) */
4718 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &pdu->actual_token, &sent);
4719 goto cleanup;
4720 }
4721
4722 coap_option_filter_clear(&opt_filter);
4723
4724#if COAP_SERVER_SUPPORT
4725 /* See if this a repeat request */
4726 if (COAP_PDU_IS_REQUEST(pdu) && session->last_resp_pdu &&
4727 pdu->mid == session->last_resp_pdu->mid) {
4728#if COAP_OSCORE_SUPPORT
4729 uint8_t oscore_encryption = session->oscore_encryption;
4730
4731 session->oscore_encryption = 0;
4732#endif /* COAP_OSCORE_SUPPORT */
4733 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4734 last_resp_pdu must not be removed */
4735 coap_pdu_reference_lkd(session->last_resp_pdu);
4736 coap_log_debug("Retransmit response to duplicate request\n");
4737 if (coap_send_internal(session, session->last_resp_pdu, NULL) != COAP_INVALID_MID) {
4738#if COAP_OSCORE_SUPPORT
4739 session->oscore_encryption = oscore_encryption;
4740#endif /* COAP_OSCORE_SUPPORT */
4741 goto finish;
4742 }
4743#if COAP_OSCORE_SUPPORT
4744 session->oscore_encryption = oscore_encryption;
4745#endif /* COAP_OSCORE_SUPPORT */
4746 }
4747#endif /* COAP_SERVER_SUPPORT */
4748 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4749 if (!check_token_size(session, pdu, is_local_mcast)) {
4750 goto cleanup;
4751 }
4752 }
4753#if COAP_OSCORE_SUPPORT
4754 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4755 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
4756 if (!is_local_mcast && (pdu->type == COAP_MESSAGE_CON || pdu->type == COAP_MESSAGE_NON)) {
4757 if (COAP_PDU_IS_REQUEST(pdu)) {
4758 response =
4759 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4760
4761 if (!response) {
4762 coap_log_warn("coap_dispatch: cannot create error response\n");
4763 } else {
4764 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4765 coap_log_warn("coap_dispatch: error sending response\n");
4766 }
4767 } else {
4768 coap_send_rst_lkd(session, pdu);
4769 }
4770 }
4771 goto cleanup;
4772 }
4773
4774 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4775 int decrypt = 1;
4776#if COAP_SERVER_SUPPORT
4777 coap_opt_t *opt;
4778 coap_resource_t *resource;
4779 coap_uri_t uri;
4780#endif /* COAP_SERVER_SUPPORT */
4781
4782 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4783 decrypt = 0;
4784
4785#if COAP_SERVER_SUPPORT
4786 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4787 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4788 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4789 != NULL) {
4790 /* Need to check whether this is a direct or proxy session */
4791 memset(&uri, 0, sizeof(uri));
4792 uri.host.length = coap_opt_length(opt);
4793 uri.host.s = coap_opt_value(opt);
4794 resource = context->proxy_uri_resource;
4795 if (uri.host.length && resource && resource->proxy_name_count &&
4796 resource->proxy_name_list) {
4797 size_t i;
4798 for (i = 0; i < resource->proxy_name_count; i++) {
4799 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4800 break;
4801 }
4802 }
4803 if (i == resource->proxy_name_count) {
4804 /* This server is not hosting the proxy connection endpoint */
4805 decrypt = 0;
4806 }
4807 }
4808 }
4809#endif /* COAP_SERVER_SUPPORT */
4810 if (decrypt) {
4811 /* find message id in sendqueue to stop retransmission and get sent (not empty packet) */
4812 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &pdu->actual_token, &sent);
4813 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4814 orig_pdu = pdu;
4815 coap_pdu_reference_lkd(orig_pdu);
4816 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4817 if (session->recipient_ctx == NULL ||
4818 (session->recipient_ctx->initial_state == 0 &&
4819 session->b_2_step == COAP_OSCORE_B_2_NONE)) {
4820 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4821 }
4823 coap_delete_pdu_lkd(orig_pdu);
4824 goto finish;
4825 } else {
4826 session->oscore_encryption = 1;
4827 coap_pdu_reference_lkd(dec_pdu);
4829 pdu = dec_pdu;
4830 }
4831 coap_log_debug("Decrypted PDU\n");
4833 }
4834 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4835 session->oscore_encryption &&
4836 pdu->type != COAP_MESSAGE_RST) {
4837 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4838 /* Violates RFC 8613 2 */
4839 coap_log_err("received an invalid response to the OSCORE request\n");
4840 oscore_invalid = 1;
4841 }
4842 }
4843#endif /* COAP_OSCORE_SUPPORT */
4844
4845 switch (pdu->type) {
4846 case COAP_MESSAGE_ACK:
4847 if (NULL == sent) {
4848 /* find message id in sendqueue to stop retransmission (no token if empty) */
4849 coap_remove_from_queue(&context->sendqueue, session, pdu->mid,
4850 pdu->code == 0 ? NULL : &pdu->actual_token, &sent);
4851 }
4852
4853 if (sent && session->con_active) {
4854 session->con_active--;
4855 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4856 /* Flush out any entries on session->delayqueue */
4857 coap_session_connected(session);
4858 }
4859 if (oscore_invalid ||
4860 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
4861 packet_is_bad = 1;
4862 goto cleanup;
4863 }
4864
4865#if COAP_SERVER_SUPPORT
4866 /* if sent code was >= 64 the message might have been a
4867 * notification. Then, we must flag the observer to be alive
4868 * by setting obs->fail_cnt = 0. */
4869 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4870 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4871 }
4872#endif /* COAP_SERVER_SUPPORT */
4873
4874#if COAP_Q_BLOCK_SUPPORT
4875 if (session->lg_xmit && sent && sent->pdu && sent->pdu->type == COAP_MESSAGE_CON &&
4876 !(session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK)) {
4877 int doing_q_block = 0;
4878 coap_lg_xmit_t *lg_xmit = NULL;
4879
4880 LL_FOREACH(session->lg_xmit, lg_xmit) {
4881 if ((lg_xmit->option == COAP_OPTION_Q_BLOCK1 || lg_xmit->option == COAP_OPTION_Q_BLOCK2) &&
4882 lg_xmit->last_all_sent == 0 && lg_xmit->sent_pdu->type != COAP_MESSAGE_NON) {
4883 doing_q_block = 1;
4884 break;
4885 }
4886 }
4887 if (doing_q_block && lg_xmit) {
4888 coap_block_b_t block;
4889
4890 memset(&block, 0, sizeof(block));
4891 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
4892 block.num = lg_xmit->last_block + lg_xmit->b.b1.count;
4893 } else {
4894 block.num = lg_xmit->last_block;
4895 }
4896 block.m = 1;
4897 block.szx = block.aszx = lg_xmit->blk_size;
4898 block.defined = 1;
4899 block.bert = 0;
4900 block.chunk_size = 1024;
4901
4902 coap_send_q_blocks(session, lg_xmit, block,
4903 lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
4904 }
4905 }
4906#endif /* COAP_Q_BLOCK_SUPPORT */
4907 if (pdu->code == 0) {
4908#if COAP_CLIENT_SUPPORT
4909 /*
4910 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4911 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4912 * response if the response was piggy-backed. Here, a separate response
4913 * detected and so the lg_crcv needs to be set up before the sent PDU
4914 * information is lost.
4915 *
4916 * lg_crcv was not set up if not a CoAP request.
4917 *
4918 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4919 * options.
4920 */
4921 if (sent &&
4922 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4923 COAP_PDU_IS_REQUEST(sent->pdu)) {
4924 /*
4925 * lg_crcv was not set up in coap_send(). It could have been set up
4926 * the first separate response.
4927 * See if there already is a lg_crcv set up.
4928 */
4929 coap_lg_crcv_t *lg_crcv;
4930 uint64_t token_match =
4932 sent->pdu->actual_token.length));
4933
4934 LL_FOREACH(session->lg_crcv, lg_crcv) {
4935 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4936 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4937 break;
4938 }
4939 }
4940 if (!lg_crcv) {
4941 /*
4942 * Need to set up a lg_crcv as it was not set up in coap_send()
4943 * to save time, but server has not sent back a piggy-back response.
4944 */
4945 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4946 if (lg_crcv) {
4947 LL_PREPEND(session->lg_crcv, lg_crcv);
4948 }
4949 }
4950 }
4951#endif /* COAP_CLIENT_SUPPORT */
4952 /* an empty ACK needs no further handling */
4953 goto cleanup;
4954 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4955 /* This is not legitimate - Request using ACK - ignore */
4956 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4958 pdu->code & 0x1f);
4959 packet_is_bad = 1;
4960 goto cleanup;
4961 }
4962
4963 break;
4964
4965 case COAP_MESSAGE_RST:
4966 /* We have sent something the receiver disliked, so we remove
4967 * not only the message id but also the subscriptions we might
4968 * have. */
4969 is_ping_rst = 0;
4970 if (pdu->mid == session->last_ping_mid &&
4971 session->last_ping > 0)
4972 is_ping_rst = 1;
4973
4974#if COAP_CLIENT_SUPPORT
4975#if COAP_Q_BLOCK_SUPPORT
4976 /* Check to see if checking out Q-Block support */
4977 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4978 session->remote_test_mid == pdu->mid) {
4979 coap_log_debug("Q-Block support not available\n");
4980 set_block_mode_drop_q(session->block_mode);
4981 coap_reset_doing_first(session);
4982 }
4983#endif /* COAP_Q_BLOCK_SUPPORT */
4984
4985 /* Check to see if checking out extended token support */
4986 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4987 session->remote_test_mid == pdu->mid) {
4988 coap_log_debug("Extended Token support not available\n");
4991 coap_reset_doing_first(session);
4992 is_ext_token_rst = 1;
4993 }
4994#endif /* COAP_CLIENT_SUPPORT */
4995
4996 if (!is_ping_rst && !is_ext_token_rst)
4997 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4998
4999 if (session->con_active) {
5000 session->con_active--;
5001 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
5002 /* Flush out any entries on session->delayqueue */
5003 coap_session_connected(session);
5004 }
5005
5006 /* find message id in sendqueue to stop retransmission (no token as RST) */
5007 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, NULL, &sent);
5008
5009 if (sent) {
5010 if (!is_ping_rst)
5011 coap_cancel(context, sent);
5012
5013 if (!is_ping_rst && !is_ext_token_rst) {
5014 if (sent->pdu->type==COAP_MESSAGE_CON) {
5015 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
5016 }
5017 } else if (is_ping_rst) {
5018 if (context->pong_cb) {
5019 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
5020 }
5021 session->last_pong = session->last_rx_tx;
5022 session->ping_failed = 0;
5024 }
5025 } else {
5026#if COAP_SERVER_SUPPORT
5027 /* Need to check is there is a subscription active and delete it */
5028 RESOURCES_ITER(context->resources, r) {
5029 coap_subscription_t *obs, *tmp;
5030 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
5031 if (obs->pdu->mid == pdu->mid && obs->session == session) {
5032 /* Need to do this now as session may get de-referenced */
5034 coap_delete_observer(r, session, &obs->pdu->actual_token);
5035 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
5036 coap_session_release_lkd(session);
5037 goto cleanup;
5038 }
5039 }
5040 }
5041#endif /* COAP_SERVER_SUPPORT */
5042 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
5043 }
5044#if COAP_PROXY_SUPPORT
5045 if (!is_ping_rst) {
5046 /* Need to check is there is a proxy subscription active and delete it */
5047 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
5048 }
5049#endif /* COAP_PROXY_SUPPORT */
5050 goto cleanup;
5051
5052 case COAP_MESSAGE_NON:
5053 /* check for oscore issue or unknown critical options */
5054 if (oscore_invalid ||
5055 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
5056 packet_is_bad = 1;
5057 if (COAP_PDU_IS_REQUEST(pdu)) {
5058 response =
5059 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
5060
5061 if (!response) {
5062 coap_log_warn("coap_dispatch: cannot create error response\n");
5063 } else {
5064 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
5065 coap_log_warn("coap_dispatch: error sending response\n");
5066 }
5067 } else {
5068 coap_send_rst_lkd(session, pdu);
5069 }
5070 goto cleanup;
5071 }
5072 break;
5073
5074 case COAP_MESSAGE_CON:
5075 /* In a lossy context, the ACK of a separate response may have
5076 * been lost, so we need to stop retransmitting requests with the
5077 * same token. Matching on token potentially containing ext length bytes.
5078 */
5079 /* find message token in sendqueue to stop retransmission */
5080 if (pdu->code != 0)
5081 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
5082
5083 /* check for oscore issue or unknown critical options in non-signaling messages */
5084 if (oscore_invalid ||
5085 (!COAP_PDU_IS_SIGNALING(pdu) &&
5086 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0)) {
5087 packet_is_bad = 1;
5088 if (COAP_PDU_IS_REQUEST(pdu)) {
5089 response =
5090 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
5091
5092 if (!response) {
5093 coap_log_warn("coap_dispatch: cannot create error response\n");
5094 } else {
5095 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
5096 coap_log_warn("coap_dispatch: error sending response\n");
5097 }
5098 } else {
5099 coap_send_rst_lkd(session, pdu);
5100 }
5101 goto cleanup;
5102 }
5103 break;
5104 default:
5105 break;
5106 }
5107
5108 /* Pass message to upper layer if a specific handler was
5109 * registered for a request that should be handled locally. */
5110#if !COAP_DISABLE_TCP
5111 if (COAP_PDU_IS_SIGNALING(pdu))
5112 handle_signaling(context, session, pdu);
5113 else
5114#endif /* !COAP_DISABLE_TCP */
5115#if COAP_SERVER_SUPPORT
5116 if (COAP_PDU_IS_REQUEST(pdu))
5117 handle_request(context, session, pdu, orig_pdu);
5118 else
5119#endif /* COAP_SERVER_SUPPORT */
5120#if COAP_CLIENT_SUPPORT
5121 if (COAP_PDU_IS_RESPONSE(pdu))
5122 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
5123 else
5124#endif /* COAP_CLIENT_SUPPORT */
5125 {
5126 if (COAP_PDU_IS_EMPTY(pdu)) {
5127 if (context->ping_cb) {
5128 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
5129 }
5130 } else {
5131 packet_is_bad = 1;
5132 }
5133 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
5135 pdu->code & 0x1f);
5136
5137 if (!coap_is_mcast(&session->addr_info.local)) {
5138 if (COAP_PDU_IS_EMPTY(pdu)) {
5139 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
5140 coap_tick_t now;
5141 coap_ticks(&now);
5142 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
5144 session->last_tx_rst = now;
5145 }
5146 }
5147 } else {
5148 if (pdu->type == COAP_MESSAGE_CON)
5150 }
5151 }
5152 }
5153
5154cleanup:
5155 if (packet_is_bad) {
5156 if (sent) {
5157 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
5158 } else {
5160 }
5161 }
5162 coap_delete_pdu_lkd(orig_pdu);
5164#if COAP_OSCORE_SUPPORT
5165 coap_delete_pdu_lkd(dec_pdu);
5166#endif /* COAP_OSCORE_SUPPORT */
5167
5168#if COAP_SERVER_SUPPORT || COAP_OSCORE_SUPPORT
5169finish:
5170#endif /* COAP_SERVER_SUPPORT || COAP_OSCORE_SUPPORT */
5172}
5173
5174#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
5175static const char *
5177 switch (event) {
5179 return "COAP_EVENT_DTLS_CLOSED";
5181 return "COAP_EVENT_DTLS_CONNECTED";
5183 return "COAP_EVENT_DTLS_RENEGOTIATE";
5185 return "COAP_EVENT_DTLS_ERROR";
5187 return "COAP_EVENT_TCP_CONNECTED";
5189 return "COAP_EVENT_TCP_CLOSED";
5191 return "COAP_EVENT_TCP_FAILED";
5193 return "COAP_EVENT_SESSION_CONNECTED";
5195 return "COAP_EVENT_SESSION_CLOSED";
5197 return "COAP_EVENT_SESSION_FAILED";
5199 return "COAP_EVENT_PARTIAL_BLOCK";
5201 return "COAP_EVENT_XMIT_BLOCK_FAIL";
5203 return "COAP_EVENT_BLOCK_ISSUE";
5205 return "COAP_EVENT_SERVER_SESSION_NEW";
5207 return "COAP_EVENT_SERVER_SESSION_DEL";
5209 return "COAP_EVENT_SERVER_SESSION_CONNECTED";
5211 return "COAP_EVENT_BAD_PACKET";
5213 return "COAP_EVENT_MSG_RETRANSMITTED";
5215 return "COAP_EVENT_FIRST_PDU_FAIL";
5217 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
5219 return "COAP_EVENT_OSCORE_NOT_ENABLED";
5221 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
5223 return "COAP_EVENT_OSCORE_NO_SECURITY";
5225 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
5227 return "COAP_EVENT_OSCORE_DECODE_ERROR";
5229 return "COAP_EVENT_WS_PACKET_SIZE";
5231 return "COAP_EVENT_WS_CONNECTED";
5233 return "COAP_EVENT_WS_CLOSED";
5235 return "COAP_EVENT_KEEPALIVE_FAILURE";
5237 return "COAP_EVENT_RECONNECT_FAILED";
5239 return "COAP_EVENT_RECONNECT_SUCCESS";
5241 return "COAP_EVENT_RECONNECT_NO_MORE";
5243 return "COAP_EVENT_RECONNECT_STARTED";
5244 default:
5245 return "???";
5246 }
5247}
5248#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
5249
5250COAP_API int
5252 coap_session_t *session) {
5253 int ret;
5254
5255 coap_lock_lock(return 0);
5256 ret = coap_handle_event_lkd(context, event, session);
5258 return ret;
5259}
5260
5261int
5263 coap_session_t *session) {
5264 int ret = 0;
5265
5266 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
5267
5268#if COAP_PROXY_SUPPORT
5269 if (event == COAP_EVENT_SERVER_SESSION_DEL)
5270 coap_proxy_remove_association(session, 0);
5271#endif /* COAP_PROXY_SUPPORT */
5272
5273 if (context->event_cb) {
5274 coap_lock_callback_ret(ret, context->event_cb(session, event));
5275#if COAP_CLIENT_SUPPORT
5276 switch (event) {
5291 /* Those that are deemed fatal to end sending a request */
5292 session->doing_send_recv = 0;
5293 break;
5295 /* Session will now be available as well - for call-home */
5296 if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
5298 session);
5299 }
5300 break;
5306 break;
5308 /* Session will now be available as well - for call-home if not (D)TLS */
5309 if (session->type == COAP_SESSION_TYPE_SERVER &&
5310 (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
5312 session);
5313 }
5314 break;
5319 break;
5321 /* Session will now be available as well - for call-home if not (D)TLS */
5322 if (session->proto == COAP_PROTO_UDP) {
5324 session);
5325 }
5326 break;
5334 default:
5335 break;
5336 }
5337#endif /* COAP_CLIENT_SUPPORT */
5338 }
5339 return ret;
5340}
5341
5342COAP_API int
5344 int ret;
5345
5346 coap_lock_lock(return 0);
5347 ret = coap_can_exit_lkd(context);
5349 return ret;
5350}
5351
5352int
5354 coap_session_t *s, *rtmp;
5355 if (!context)
5356 return 1;
5358 if (context->sendqueue)
5359 return 0;
5360#if COAP_SERVER_SUPPORT
5361 coap_endpoint_t *ep;
5362
5363 LL_FOREACH(context->endpoint, ep) {
5364 SESSIONS_ITER(ep->sessions, s, rtmp) {
5365 if (s->delayqueue)
5366 return 0;
5367 if (s->lg_xmit)
5368 return 0;
5369 }
5370 }
5371#endif /* COAP_SERVER_SUPPORT */
5372#if COAP_CLIENT_SUPPORT
5373 SESSIONS_ITER(context->sessions, s, rtmp) {
5374 if (s->delayqueue)
5375 return 0;
5376 if (s->lg_xmit)
5377 return 0;
5378 }
5379#endif /* COAP_CLIENT_SUPPORT */
5380 return 1;
5381}
5382#if COAP_SERVER_SUPPORT
5383#if COAP_ASYNC_SUPPORT
5384/*
5385 * Return 1 if there is a future expire time, else 0.
5386 * Update tim_rem with remaining value if return is 1.
5387 */
5388int
5389coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5391 coap_async_t *async, *tmp;
5392 int ret = 0;
5393
5394 if (context->async_state_traversing)
5395 return 0;
5396 context->async_state_traversing = 1;
5397 LL_FOREACH_SAFE(context->async_state, async, tmp) {
5398 if (async->delay != 0 && !async->session->is_rate_limiting) {
5399 if (async->delay <= now) {
5400 /* Send off the request to the application */
5401 coap_log_debug("Async PDU presented to app.\n");
5402 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5403 handle_request(context, async->session, async->pdu, NULL);
5404
5405 /* Remove this async entry as it has now fired */
5406 coap_free_async_lkd(async->session, async);
5407 } else {
5408 next_due = async->delay - now;
5409 ret = 1;
5410 }
5411 }
5412 }
5413 if (tim_rem)
5414 *tim_rem = next_due;
5415 context->async_state_traversing = 0;
5416 return ret;
5417}
5418#endif /* COAP_ASYNC_SUPPORT */
5419#endif /* COAP_SERVER_SUPPORT */
5420
5422uint8_t coap_unique_id[8] = { 0 };
5423
5424#if COAP_THREAD_SAFE
5425/*
5426 * Global lock for multi-thread support
5427 */
5428coap_lock_t global_lock;
5429/*
5430 * low level protection mutex
5431 */
5432coap_mutex_t m_show_pdu;
5433coap_mutex_t m_log_impl;
5434coap_mutex_t m_io_threads;
5435#endif /* COAP_THREAD_SAFE */
5436
5437void
5439 coap_tick_t now;
5440#ifndef WITH_CONTIKI
5441 uint64_t us;
5442#endif /* !WITH_CONTIKI */
5443
5444 if (coap_started)
5445 return;
5446 coap_started = 1;
5447
5448#if COAP_THREAD_SAFE
5449 coap_lock_init(&global_lock);
5450 coap_mutex_init(&m_show_pdu);
5451 coap_mutex_init(&m_log_impl);
5452 coap_mutex_init(&m_io_threads);
5453#endif /* COAP_THREAD_SAFE */
5454
5455#if defined(HAVE_WINSOCK2_H)
5456 WORD wVersionRequested = MAKEWORD(2, 2);
5457 WSADATA wsaData;
5458 WSAStartup(wVersionRequested, &wsaData);
5459#endif
5461 coap_ticks(&now);
5462#ifndef WITH_CONTIKI
5463 us = coap_ticks_to_rt_us(now);
5464 /* Be accurate to the nearest (approx) us */
5465 coap_prng_init_lkd((unsigned int)us);
5466#else /* WITH_CONTIKI */
5467 coap_start_io_process();
5468#endif /* WITH_CONTIKI */
5471#ifdef WITH_LWIP
5472 coap_io_lwip_init();
5473#endif /* WITH_LWIP */
5474#if COAP_SERVER_SUPPORT
5475 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5476 (const uint8_t *)".well-known/core"
5477 };
5478 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5479 resource_uri_wellknown.ref = 1;
5480 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5481 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5482 resource_uri_wellknown.uri_path = &well_known;
5483#endif /* COAP_SERVER_SUPPORT */
5486}
5487
5488void
5490 if (!coap_started)
5491 return;
5492 coap_started = 0;
5493#if defined(HAVE_WINSOCK2_H)
5494 WSACleanup();
5495#elif defined(WITH_CONTIKI)
5496 coap_stop_io_process();
5497#endif
5498#ifdef WITH_LWIP
5499 coap_io_lwip_cleanup();
5500#endif /* WITH_LWIP */
5502
5507#if COAP_THREAD_SAFE
5508 coap_mutex_destroy(&m_show_pdu);
5509 coap_mutex_destroy(&m_log_impl);
5510 coap_mutex_destroy(&m_io_threads);
5511#endif /* COAP_THREAD_SAFE */
5512
5514}
5515
5516void
5518 coap_response_handler_t handler) {
5519#if COAP_CLIENT_SUPPORT
5520 context->response_cb = handler;
5521#else /* ! COAP_CLIENT_SUPPORT */
5522 (void)context;
5523 (void)handler;
5524#endif /* ! COAP_CLIENT_SUPPORT */
5525}
5526
5527void
5530#if COAP_PROXY_SUPPORT
5531 context->proxy_response_cb = handler;
5532#else /* ! COAP_PROXY_SUPPORT */
5533 (void)context;
5534 (void)handler;
5535#endif /* ! COAP_PROXY_SUPPORT */
5536}
5537
5538void
5540 coap_nack_handler_t handler) {
5541 context->nack_cb = handler;
5542}
5543
5544void
5546 coap_ping_handler_t handler) {
5547 context->ping_cb = handler;
5548}
5549
5550void
5552 coap_pong_handler_t handler) {
5553 context->pong_cb = handler;
5554}
5555
5556void
5558 coap_resource_dynamic_create_t dyn_create_handler,
5559 uint32_t dynamic_max) {
5560 context->dyn_create_handler = dyn_create_handler;
5561 context->dynamic_max = dynamic_max;
5562 return;
5563}
5564
5565COAP_API void
5571
5572void
5576
5577#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5578#if COAP_SERVER_SUPPORT
5579COAP_API int
5580coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5581 const char *ifname) {
5582 int ret;
5583
5584 coap_lock_lock(return -1);
5585 ret = coap_join_mcast_group_intf_lkd(ctx, NULL, group_name, ifname);
5587 return ret;
5588}
5589
5590int
5592 coap_endpoint_t *single_endpoint,
5593 const char *group_name,
5594 const char *ifname) {
5595#if COAP_IPV4_SUPPORT
5596 struct ip_mreq mreq4;
5597#endif /* COAP_IPV4_SUPPORT */
5598#if COAP_IPV6_SUPPORT
5599 struct ipv6_mreq mreq6;
5600#endif /* COAP_IPV6_SUPPORT */
5601 struct addrinfo *resmulti = NULL, hints, *ainfo;
5602 int result = -1;
5603 coap_endpoint_t *endpoint;
5604#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5605 coap_endpoint_t *lookup_endpoint;
5606#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5607 int mgroup_setup = 0;
5608
5609 if (single_endpoint) {
5610 if (single_endpoint->proto != COAP_PROTO_UDP)
5611 return -1;
5612#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5613 lookup_endpoint = single_endpoint;
5614#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5615 } else {
5616 /* Need to have at least one endpoint! */
5617 assert(ctx->endpoint);
5618 if (!ctx->endpoint)
5619 return -1;
5620#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5621 lookup_endpoint = ctx->endpoint;
5622#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5623 }
5624
5625 /* Default is let the kernel choose */
5626#if COAP_IPV6_SUPPORT
5627 mreq6.ipv6mr_interface = 0;
5628#endif /* COAP_IPV6_SUPPORT */
5629#if COAP_IPV4_SUPPORT
5630 mreq4.imr_interface.s_addr = INADDR_ANY;
5631#endif /* COAP_IPV4_SUPPORT */
5632
5633 memset(&hints, 0, sizeof(hints));
5634 hints.ai_socktype = SOCK_DGRAM;
5635
5636 /* resolve the multicast group address */
5637 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5638
5639 if (result != 0) {
5640 coap_log_err("coap_join_mcast_group_intf: %s: "
5641 "Cannot resolve multicast address: %s\n",
5642 group_name, gai_strerror(result));
5643 goto finish;
5644 }
5645
5646 /* Need to do a windows equivalent at some point */
5647#ifndef _WIN32
5648 if (ifname) {
5649 /* interface specified - check if we have correct IPv4/IPv6 information */
5650 int done_ip4 = 0;
5651 int done_ip6 = 0;
5652#if defined(ESPIDF_VERSION)
5653 struct netif *netif;
5654#else /* !ESPIDF_VERSION */
5655#if COAP_IPV4_SUPPORT
5656 int ip4fd;
5657#endif /* COAP_IPV4_SUPPORT */
5658 struct ifreq ifr;
5659#endif /* !ESPIDF_VERSION */
5660
5661 /* See which mcast address family types are being asked for */
5662 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5663 ainfo = ainfo->ai_next) {
5664 switch (ainfo->ai_family) {
5665#if COAP_IPV6_SUPPORT
5666 case AF_INET6:
5667 if (done_ip6)
5668 break;
5669 done_ip6 = 1;
5670#if defined(ESPIDF_VERSION)
5671 netif = netif_find(ifname);
5672 if (netif)
5673 mreq6.ipv6mr_interface = netif_get_index(netif);
5674 else
5675 coap_log_err("coap_join_mcast_group_intf: %s: "
5676 "Cannot get IPv4 address: %s\n",
5677 ifname, coap_socket_strerror());
5678#else /* !ESPIDF_VERSION */
5679 memset(&ifr, 0, sizeof(ifr));
5680 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5681 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5682
5683#ifdef HAVE_IF_NAMETOINDEX
5684 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5685 if (mreq6.ipv6mr_interface == 0) {
5686 coap_log_warn("coap_join_mcast_group_intf: "
5687 "cannot get interface index for '%s'\n",
5688 ifname);
5689 }
5690#elif defined(__QNXNTO__)
5691#else /* !HAVE_IF_NAMETOINDEX */
5692 result = ioctl(lookup_endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5693 if (result != 0) {
5694 coap_log_warn("coap_join_mcast_group_intf: "
5695 "cannot get interface index for '%s': %s\n",
5696 ifname, coap_socket_strerror());
5697 } else {
5698 /* Capture the IPv6 if_index for later */
5699 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5700 }
5701#endif /* !HAVE_IF_NAMETOINDEX */
5702#endif /* !ESPIDF_VERSION */
5703#endif /* COAP_IPV6_SUPPORT */
5704 break;
5705#if COAP_IPV4_SUPPORT
5706 case AF_INET:
5707 if (done_ip4)
5708 break;
5709 done_ip4 = 1;
5710#if defined(ESPIDF_VERSION)
5711 netif = netif_find(ifname);
5712 if (netif)
5713 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5714 else
5715 coap_log_err("coap_join_mcast_group_intf: %s: "
5716 "Cannot get IPv4 address: %s\n",
5717 ifname, coap_socket_strerror());
5718#else /* !ESPIDF_VERSION */
5719 /*
5720 * Need an AF_INET socket to do this unfortunately to stop
5721 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5722 */
5723 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5724 if (ip4fd == -1) {
5725 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5726 ifname, coap_socket_strerror());
5727 continue;
5728 }
5729 memset(&ifr, 0, sizeof(ifr));
5730 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5731 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5732 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5733 if (result != 0) {
5734 coap_log_err("coap_join_mcast_group_intf: %s: "
5735 "Cannot get IPv4 address: %s\n",
5736 ifname, coap_socket_strerror());
5737 } else {
5738 /* Capture the IPv4 address for later */
5739 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5740 }
5741 close(ip4fd);
5742#endif /* !ESPIDF_VERSION */
5743 break;
5744#endif /* COAP_IPV4_SUPPORT */
5745 default:
5746 break;
5747 }
5748 }
5749 }
5750#else /* _WIN32 */
5751 /*
5752 * On Windows this function ignores the ifname variable so we unset this
5753 * variable on this platform in any case in order to enable the interface
5754 * selection from the bind address below.
5755 */
5756 ifname = 0;
5757#endif /* _WIN32 */
5758
5759 /* Add in mcast address(es) to appropriate interface */
5760 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5761 for (endpoint = single_endpoint ? single_endpoint : ctx->endpoint;
5762 endpoint != NULL;
5763 endpoint = single_endpoint ? NULL : endpoint->next) {
5764 /* Only UDP currently supported */
5765 if (endpoint->proto == COAP_PROTO_UDP) {
5766 coap_address_t gaddr;
5767
5768 coap_address_init(&gaddr);
5769#if COAP_IPV6_SUPPORT
5770 if (ainfo->ai_family == AF_INET6) {
5771 if (!ifname) {
5772 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5773 /*
5774 * Do it on the ifindex that the server is listening on
5775 * (sin6_scope_id could still be 0)
5776 */
5777 mreq6.ipv6mr_interface =
5778 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5779 } else {
5780 mreq6.ipv6mr_interface = 0;
5781 }
5782 }
5783 gaddr.addr.sin6.sin6_family = AF_INET6;
5784 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5785 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5786 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5787 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5788 (char *)&mreq6, sizeof(mreq6));
5789 }
5790#endif /* COAP_IPV6_SUPPORT */
5791#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5792 else
5793#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5794#if COAP_IPV4_SUPPORT
5795 if (ainfo->ai_family == AF_INET) {
5796 if (!ifname) {
5797 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5798 /*
5799 * Do it on the interface that the server is listening on
5800 * (sin_addr could still be INADDR_ANY)
5801 */
5802 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5803 } else {
5804 mreq4.imr_interface.s_addr = INADDR_ANY;
5805 }
5806 }
5807 gaddr.addr.sin.sin_family = AF_INET;
5808 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5809 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5810 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5811 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5812 (char *)&mreq4, sizeof(mreq4));
5813 }
5814#endif /* COAP_IPV4_SUPPORT */
5815 else {
5816 continue;
5817 }
5818
5819 if (result == COAP_SOCKET_ERROR) {
5820 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5821 group_name, coap_socket_strerror());
5822 } else {
5823 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5824
5825 addr_str[sizeof(addr_str)-1] = '\000';
5826 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5827 sizeof(addr_str) - 1)) {
5828 if (ifname)
5829 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5830 ifname);
5831 else
5832 coap_log_debug("added mcast group %s\n", addr_str);
5833 }
5834 mgroup_setup = 1;
5835 }
5836 }
5837 }
5838 }
5839 if (!mgroup_setup) {
5840 result = -1;
5841 }
5842
5843finish:
5844 freeaddrinfo(resmulti);
5845
5846 return result;
5847}
5848
5849COAP_API int
5851 const char *group_name,
5852 const char *ifname) {
5853 int ret;
5854
5855 if (!endpoint || !endpoint->context)
5856 return -1;
5857
5858 coap_lock_lock(return -1);
5859 ret = coap_join_mcast_group_intf_lkd(endpoint->context, endpoint, group_name, ifname);
5861 return ret;
5862}
5863
5864void
5866 context->mcast_per_resource = 1;
5867}
5868
5869#endif /* ! COAP_SERVER_SUPPORT */
5870
5871#if COAP_CLIENT_SUPPORT
5872int
5873coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5874 if (session && coap_is_mcast(&session->addr_info.remote)) {
5875 switch (session->addr_info.remote.addr.sa.sa_family) {
5876#if COAP_IPV4_SUPPORT
5877 case AF_INET:
5878 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5879 (const char *)&hops, sizeof(hops)) < 0) {
5880 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5881 hops, coap_socket_strerror());
5882 return 0;
5883 }
5884 return 1;
5885#endif /* COAP_IPV4_SUPPORT */
5886#if COAP_IPV6_SUPPORT
5887 case AF_INET6:
5888 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5889 (const char *)&hops, sizeof(hops)) < 0) {
5890 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
5891 hops, coap_socket_strerror());
5892 return 0;
5893 }
5894 return 1;
5895#endif /* COAP_IPV6_SUPPORT */
5896 default:
5897 break;
5898 }
5899 }
5900 return 0;
5901}
5902#endif /* COAP_CLIENT_SUPPORT */
5903
5904#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
5905COAP_API int
5907 const char *group_name COAP_UNUSED,
5908 const char *ifname COAP_UNUSED) {
5909 return -1;
5910}
5911
5912COAP_API int
5914 const char *group_name COAP_UNUSED,
5915 const char *ifname COAP_UNUSED) {
5916 return -1;
5917}
5918
5919int
5921 size_t hops COAP_UNUSED) {
5922 return 0;
5923}
5924
5925void
5927}
5928#endif /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
int coap_is_mcast(const coap_address_t *a)
Checks if given address a denotes a multicast address.
void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
int coap_debug_recv_packet(void)
Check to see whether an incoming packet should be dropped or not.
const char * coap_option_string(coap_pdu_code_t code, coap_option_num_t number)
Returns a textual description of the option name.
Definition coap_debug.c: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:735
void coap_memory_init(void)
Initializes libcoap's memory management.
@ COAP_NODE
Definition coap_mem.h:37
@ COAP_CONTEXT
Definition coap_mem.h:38
@ COAP_STRING
Definition coap_mem.h:33
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
CoAP mutex mechanism wrapper.
#define coap_mutex_init(a)
int coap_mutex_t
#define coap_mutex_destroy(a)
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition coap_net.c:83
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition coap_net.c: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:3212
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu, int is_local_mcast)
Definition coap_net.c:4644
#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:5489
#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:5176
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:3539
int coap_started
Definition coap_net.c:5421
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:4558
#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:5438
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:5422
#define FP1
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition coap_net.c:100
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c:252
int coap_dtls_receive(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:378
int coap_dtls_context_load_pki_trust_store(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:268
int coap_dtls_context_set_pki_root_cas(coap_context_t *ctx COAP_UNUSED, const char *ca_file COAP_UNUSED, const char *ca_path COAP_UNUSED)
Definition coap_notls.c:260
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:321
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:316
#define NULL
Definition coap_option.h:30
uint16_t coap_option_num_t
Definition coap_option.h:37
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
@ COAP_SIG_OPT_CUSTODY
coap_sig_csm_opt_t
@ COAP_SIG_OPT_BLOCK_WISE_TRANSFER
@ COAP_SIG_OPT_EXTENDED_TOKEN_LENGTH
@ COAP_SIG_OPT_MAX_MESSAGE_SIZE
@ COAP_OPTION_OBSERVE
Definition coap_option.h:75
@ COAP_OPTION_IF_NONE_MATCH
Definition coap_option.h:74
@ COAP_OPTION_NORESPONSE
Definition coap_option.h:98
@ COAP_OPTION_MAXAGE
Definition coap_option.h:83
@ COAP_OPTION_Q_BLOCK2
Definition coap_option.h:93
@ COAP_OPTION_PROXY_SCHEME
Definition coap_option.h:95
@ COAP_OPTION_HOP_LIMIT
Definition coap_option.h:85
@ COAP_OPTION_URI_PORT
Definition coap_option.h:76
@ COAP_OPTION_URI_HOST
Definition coap_option.h:72
@ COAP_OPTION_BLOCK2
Definition coap_option.h:90
@ COAP_OPTION_IF_MATCH
Definition coap_option.h:71
@ COAP_OPTION_ECHO
Definition coap_option.h:97
@ COAP_OPTION_RTAG
Definition coap_option.h:99
@ COAP_OPTION_BLOCK1
Definition coap_option.h:91
@ COAP_OPTION_URI_PATH
Definition coap_option.h:79
@ COAP_OPTION_Q_BLOCK1
Definition coap_option.h:87
@ COAP_OPTION_OSCORE
Definition coap_option.h:78
@ COAP_OPTION_CONTENT_FORMAT
Definition coap_option.h:80
@ COAP_OPTION_URI_QUERY
Definition coap_option.h:84
@ COAP_OPTION_PROXY_URI
Definition coap_option.h:94
@ COAP_OPTION_URI_PATH_ABB
Definition coap_option.h:81
@ COAP_OPTION_ACCEPT
Definition coap_option.h:86
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define SESSIONS_ITER(e, el, rtmp)
void coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition coap_net.c: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:5262
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:5573
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:4679
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:5353
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:3271
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:3162
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:3310
@ 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:5517
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:3343
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:5557
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 Acknowledge handler that is used as callback in coap_context_t.
Definition coap_net.h:80
void coap_context_set_shutdown_no_observe(coap_context_t *context)
Definition coap_net.c: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:5545
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:5343
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:5566
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:5551
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:5251
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:5539
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
Triggerrd when (D)TLS session closed.
Definition coap_event.h:41
@ COAP_EVENT_TCP_FAILED
Triggered when TCP layer fails for some reason.
Definition coap_event.h:57
@ COAP_EVENT_WS_CONNECTED
Triggered when the WebSockets layer is up.
Definition coap_event.h: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:5528
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::@044177361107056137161161332060137052154267075253 addr
CoAP binary data definition with const data.
Definition coap_str.h:65
size_t length
length of binary data
Definition coap_str.h:66
const uint8_t * s
read-only binary data
Definition coap_str.h:67
CoAP binary data definition.
Definition coap_str.h:57
size_t length
length of binary data
Definition coap_str.h:58
uint8_t * s
binary data
Definition coap_str.h:59
Structure of Block options with BERT support.
Definition coap_block.h:55
unsigned int num
block number
Definition coap_block.h:56
uint32_t chunk_size
Definition coap_block.h:62
unsigned int bert
Operating as BERT.
Definition coap_block.h:61
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:59
unsigned int defined
Set if block found.
Definition coap_block.h:60
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:57
unsigned int szx
block size (0-6)
Definition coap_block.h:58
The CoAP stack's global state is stored in a coap_context_t object.
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
uint64_t rl_ticks_per_packet
If not 0, rate limit NON to ticks per packet.
coap_app_data_free_callback_t app_cb
call-back to release app_data
coap_pong_handler_t pong_cb
Called when a ping response is received.
coap_nack_handler_t nack_cb
Called when a response issue has occurred.
coap_resource_dynamic_create_t dyn_create_handler
Dynamic resource create handler.
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 negotiating sessions per endpoint.
coap_ping_handler_t ping_cb
Called when a CoAP ping is received.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
uint32_t csm_timeout_ms
Timeout for waiting for a CSM from the remote side.
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
coap_bin_const_t key
Definition coap_dtls.h:389
coap_bin_const_t identity
Definition coap_dtls.h:388
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:451
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:317
uint8_t version
Definition coap_dtls.h:318
coap_bin_const_t hint
Definition coap_dtls.h:459
coap_bin_const_t key
Definition coap_dtls.h:460
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:509
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:541
uint64_t state_token
state token
uint32_t count
the number of packets sent for payload
coap_binary_t * app_token
original PDU token
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
Structure to hold large body (many blocks) transmission information.
coap_tick_t last_all_sent
Last time all data sent or 0.
uint8_t blk_size
large block transmission size
int last_block
last acknowledged block number Block1 last transmitted Q-Block2
union coap_lg_xmit_t::@203075012364233124260125111050261235054056026301 b
coap_pdu_t * sent_pdu
The sent pdu with all the data.
coap_l_block1_t b1
uint16_t option
large block transmission CoAP option
uint8_t short_opts[COAP_OPT_FILTER_SHORT]
uint16_t long_opts[COAP_OPT_FILTER_LONG]
Iterator to run through PDU options.
coap_option_num_t number
decoded option number
size_t length
length of payload
coap_addr_tuple_t addr_info
local and remote addresses
unsigned char * payload
payload
structure for CoAP PDUs
uint16_t max_opt
highest option number in PDU
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
coap_pdu_code_t code
request method (value 1–31) or response code (value 64-255)
uint8_t hdr_size
actual size used for protocol-specific header (0 until header is encoded)
coap_bin_const_t actual_token
Actual token in pdu.
uint8_t * data
first byte of payload, if any
coap_mid_t mid
message id, if any, in regular host byte order
uint32_t e_token_length
length of Token space (includes leading extended bytes
size_t used_size
used bytes of storage for token, options and payload
uint8_t crit_opt
Set if unknown critical option for proxy.
coap_binary_t * data_free
Data to be freed off by coap_delete_pdu().
size_t alloc_size
allocated storage for token, options and payload
coap_session_t * session
Session responsible for PDU or NULL.
coap_pdu_type_t type
message type
Queue entry.
coap_address_t remote
For re-transmission - where the node is going.
coap_session_t * session
the CoAP session
coap_pdu_t * pdu
the CoAP PDU to send
unsigned int timeout
the randomized timeout value
uint8_t is_mcast
Set if this is a queued mcast response.
struct coap_queue_t * next
coap_mid_t id
CoAP message id.
coap_tick_t t
when to send PDU for the next time
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
volatile uint8_t max_token_checked
Check for max token size coap_ext_token_check_t.
uint8_t csm_not_seen
Set if timeout waiting for CSM.
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
uint8_t delay_recursive
Set if in coap_client_delay_first().
coap_socket_t sock
socket object for the session, if any
coap_pdu_t * partial_pdu
incomplete incoming pdu
uint32_t max_token_size
Largest token size supported RFC8974.
uint32_t ping_failed
Ping failure count.
coap_bin_const_t * psk_identity
If client, this field contains the current identity for server; When this field is NULL,...
coap_session_state_t state
current state of relationship with peer
uint8_t csm_bert_rem_support
CSM TCP BERT blocks supported (remote).
coap_mid_t last_resp_mid
The last response mid that has been been processed.
uint8_t is_rate_limiting
Currently NON rate limiting.
coap_mid_t remote_test_mid
mid used for checking remote support
uint8_t read_header[8]
storage space for header of incoming message header
uint8_t csm_bert_loc_support
CSM TCP BERT blocks supported (local).
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
unsigned ref
reference count from queues
coap_response_t last_con_handler_res
The result of calling the response handler of the last CON.
coap_tick_t last_tx
Last time a ratelimited packet is sent.
coap_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
coap_bin_const_t * last_token
uint8_t no_path_abbrev
Set is remote does not support Uri-Path-Abbrev.
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
size_t partial_read
if > 0 indicates number of bytes already read for an incoming message
void * tls
security parameters
uint16_t max_retransmit
maximum re-transmit count (default 4)
uint8_t csm_block_supported
CSM TCP blocks supported.
uint8_t proxy_session
Set if this is an ongoing proxy session.
uint8_t con_active
Active CON request sent.
coap_queue_t * delayqueue
list of delayed messages waiting to be sent
uint32_t tx_rtag
Next Request-Tag number to use.
coap_mid_t last_ping_mid
the last keepalive message id that was used in this session
uint64_t rl_ticks_per_packet
If not 0, rate limit NON to ticks per packet.
coap_session_type_t type
client or server side socket
coap_context_t * context
session's context
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