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