libcoap 4.3.5a
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--2025 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#ifdef HAVE_UNISTD_H
25#include <unistd.h>
26#else
27#ifdef HAVE_SYS_UNISTD_H
28#include <sys/unistd.h>
29#endif
30#endif
31#ifdef HAVE_SYS_TYPES_H
32#include <sys/types.h>
33#endif
34#ifdef HAVE_SYS_SOCKET_H
35#include <sys/socket.h>
36#endif
37#ifdef HAVE_SYS_IOCTL_H
38#include <sys/ioctl.h>
39#endif
40#ifdef HAVE_NETINET_IN_H
41#include <netinet/in.h>
42#endif
43#ifdef HAVE_ARPA_INET_H
44#include <arpa/inet.h>
45#endif
46#ifdef HAVE_NET_IF_H
47#include <net/if.h>
48#endif
49#ifdef COAP_EPOLL_SUPPORT
50#include <sys/epoll.h>
51#include <sys/timerfd.h>
52#endif /* COAP_EPOLL_SUPPORT */
53#ifdef HAVE_WS2TCPIP_H
54#include <ws2tcpip.h>
55#endif
56
57#ifdef HAVE_NETDB_H
58#include <netdb.h>
59#endif
60
61#ifdef WITH_LWIP
62#include <lwip/pbuf.h>
63#include <lwip/udp.h>
64#include <lwip/timeouts.h>
65#include <lwip/tcpip.h>
66#endif
67
68#ifndef INET6_ADDRSTRLEN
69#define INET6_ADDRSTRLEN 40
70#endif
71
72#ifndef min
73#define min(a,b) ((a) < (b) ? (a) : (b))
74#endif
75
80#define FRAC_BITS 6
81
86#define MAX_BITS 8
87
88#if FRAC_BITS > 8
89#error FRAC_BITS must be less or equal 8
90#endif
91
93#define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
94 ((1 << (frac)) * fval.fractional_part + 500)/1000))
95
97#define ACK_RANDOM_FACTOR \
98 Q(FRAC_BITS, session->ack_random_factor)
99
101#define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
102
103#ifndef WITH_LWIP
104
109
114#else /* !WITH_LWIP */
115
116#include <lwip/memp.h>
117
120 return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
121}
122
125 memp_free(MEMP_COAP_NODE, node);
126}
127#endif /* WITH_LWIP */
128
129unsigned int
131 unsigned int result = 0;
132 coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
133
134 if (ctx->sendqueue) {
135 /* delta < 0 means that the new time stamp is before the old. */
136 if (delta <= 0) {
137 ctx->sendqueue->t -= delta;
138 } else {
139 /* This case is more complex: The time must be advanced forward,
140 * thus possibly leading to timed out elements at the queue's
141 * start. For every element that has timed out, its relative
142 * time is set to zero and the result counter is increased. */
143
144 coap_queue_t *q = ctx->sendqueue;
145 coap_tick_t t = 0;
146 while (q && (t + q->t < (coap_tick_t)delta)) {
147 t += q->t;
148 q->t = 0;
149 result++;
150 q = q->next;
151 }
152
153 /* finally adjust the first element that has not expired */
154 if (q) {
155 q->t = (coap_tick_t)delta - t;
156 }
157 }
158 }
159
160 /* adjust basetime */
161 ctx->sendqueue_basetime += delta;
162
163 return result;
164}
165
166int
168 coap_queue_t *p, *q;
169 if (!queue || !node)
170 return 0;
171
172 /* set queue head if empty */
173 if (!*queue) {
174 *queue = node;
175 return 1;
176 }
177
178 /* replace queue head if PDU's time is less than head's time */
179 q = *queue;
180 if (node->t < q->t) {
181 node->next = q;
182 *queue = node;
183 q->t -= node->t; /* make q->t relative to node->t */
184 return 1;
185 }
186
187 /* search for right place to insert */
188 do {
189 node->t -= q->t; /* make node-> relative to q->t */
190 p = q;
191 q = q->next;
192 } while (q && q->t <= node->t);
193
194 /* insert new item */
195 if (q) {
196 q->t -= node->t; /* make q->t relative to node->t */
197 }
198 node->next = q;
199 p->next = node;
200 return 1;
201}
202
203COAP_API int
205 int ret;
206#if COAP_THREAD_SAFE
207 coap_context_t *context;
208#endif /* COAP_THREAD_SAFE */
209
210 if (!node)
211 return 0;
212 if (!node->session)
213 return coap_delete_node_lkd(node);
214
215#if COAP_THREAD_SAFE
216 /* Keep copy as node will be going away */
217 context = node->session->context;
218 (void)context;
219#endif /* COAP_THREAD_SAFE */
220 coap_lock_lock(context, return 0);
221 ret = coap_delete_node_lkd(node);
222 coap_lock_unlock(context);
223 return ret;
224}
225
226int
228 if (!node)
229 return 0;
230
231 coap_delete_pdu(node->pdu);
232 if (node->session) {
233 /*
234 * Need to remove out of context->sendqueue as added in by coap_wait_ack()
235 */
236 if (node->session->context->sendqueue) {
237 LL_DELETE(node->session->context->sendqueue, node);
238 }
240 }
241 coap_free_node(node);
242
243 return 1;
244}
245
246void
248 if (!queue)
249 return;
250
251 coap_delete_all(queue->next);
253}
254
257 coap_queue_t *node;
258 node = coap_malloc_node();
259
260 if (!node) {
261 coap_log_warn("coap_new_node: malloc failed\n");
262 return NULL;
263 }
264
265 memset(node, 0, sizeof(*node));
266 return node;
267}
268
271 if (!context || !context->sendqueue)
272 return NULL;
273
274 return context->sendqueue;
275}
276
279 coap_queue_t *next;
280
281 if (!context || !context->sendqueue)
282 return NULL;
283
284 next = context->sendqueue;
285 context->sendqueue = context->sendqueue->next;
286 if (context->sendqueue) {
287 context->sendqueue->t += next->t;
288 }
289 next->next = NULL;
290 return next;
291}
292
293#if COAP_CLIENT_SUPPORT
294const coap_bin_const_t *
296
297 if (session->psk_key) {
298 return session->psk_key;
299 }
300 if (session->cpsk_setup_data.psk_info.key.length)
301 return &session->cpsk_setup_data.psk_info.key;
302
303 /* Not defined in coap_new_client_session_psk2() */
304 return NULL;
305}
306
307const coap_bin_const_t *
309
310 if (session->psk_identity) {
311 return session->psk_identity;
312 }
314 return &session->cpsk_setup_data.psk_info.identity;
315
316 /* Not defined in coap_new_client_session_psk2() */
317 return NULL;
318}
319#endif /* COAP_CLIENT_SUPPORT */
320
321#if COAP_SERVER_SUPPORT
322const coap_bin_const_t *
324
325 if (session->psk_key)
326 return session->psk_key;
327
329 return &session->context->spsk_setup_data.psk_info.key;
330
331 /* Not defined in coap_context_set_psk2() */
332 return NULL;
333}
334
335const coap_bin_const_t *
337
338 if (session->psk_hint)
339 return session->psk_hint;
340
342 return &session->context->spsk_setup_data.psk_info.hint;
343
344 /* Not defined in coap_context_set_psk2() */
345 return NULL;
346}
347
348COAP_API int
350 const char *hint,
351 const uint8_t *key,
352 size_t key_len) {
353 int ret;
354
355 coap_lock_lock(ctx, return 0);
356 ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
357 coap_lock_unlock(ctx);
358 return ret;
359}
360
361int
363 const char *hint,
364 const uint8_t *key,
365 size_t key_len) {
366 coap_dtls_spsk_t setup_data;
367
369 memset(&setup_data, 0, sizeof(setup_data));
370 if (hint) {
371 setup_data.psk_info.hint.s = (const uint8_t *)hint;
372 setup_data.psk_info.hint.length = strlen(hint);
373 }
374
375 if (key && key_len > 0) {
376 setup_data.psk_info.key.s = key;
377 setup_data.psk_info.key.length = key_len;
378 }
379
380 return coap_context_set_psk2_lkd(ctx, &setup_data);
381}
382
383COAP_API int
385 int ret;
386
387 coap_lock_lock(ctx, return 0);
388 ret = coap_context_set_psk2_lkd(ctx, setup_data);
389 coap_lock_unlock(ctx);
390 return ret;
391}
392
393int
395 if (!setup_data)
396 return 0;
397
399 ctx->spsk_setup_data = *setup_data;
400
402 return coap_dtls_context_set_spsk(ctx, setup_data);
403 }
404 return 0;
405}
406
407COAP_API int
409 const coap_dtls_pki_t *setup_data) {
410 int ret;
411
412 coap_lock_lock(ctx, return 0);
413 ret = coap_context_set_pki_lkd(ctx, setup_data);
414 coap_lock_unlock(ctx);
415 return ret;
416}
417
418int
420 const coap_dtls_pki_t *setup_data) {
422 if (!setup_data)
423 return 0;
424 if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
425 coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
426 return 0;
427 }
429 return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
430 }
431 return 0;
432}
433#endif /* ! COAP_SERVER_SUPPORT */
434
435COAP_API int
437 const char *ca_file,
438 const char *ca_dir) {
439 int ret;
440
441 coap_lock_lock(ctx, return 0);
442 ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
443 coap_lock_unlock(ctx);
444 return ret;
445}
446
447int
449 const char *ca_file,
450 const char *ca_dir) {
452 return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
453 }
454 return 0;
455}
456
457void
458coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
459 context->ping_timeout = seconds;
460}
461
462int
464#if COAP_CLIENT_SUPPORT
465 return coap_dtls_set_cid_tuple_change(context, every);
466#else /* ! COAP_CLIENT_SUPPORT */
467 (void)context;
468 (void)every;
469 return 0;
470#endif /* ! COAP_CLIENT_SUPPORT */
471}
472
473void
475 size_t max_token_size) {
476 assert(max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
477 max_token_size <= COAP_TOKEN_EXT_MAX);
478 context->max_token_size = (uint32_t)max_token_size;
479}
480
481void
483 unsigned int max_idle_sessions) {
484 context->max_idle_sessions = max_idle_sessions;
485}
486
487unsigned int
489 return context->max_idle_sessions;
490}
491
492void
494 unsigned int max_handshake_sessions) {
495 context->max_handshake_sessions = max_handshake_sessions;
496}
497
498unsigned int
502
503static unsigned int s_csm_timeout = 30;
504
505void
507 unsigned int csm_timeout) {
508 s_csm_timeout = csm_timeout;
509 coap_context_set_csm_timeout_ms(context, csm_timeout * 1000);
510}
511
512unsigned int
514 (void)context;
515 return s_csm_timeout;
516}
517
518void
520 unsigned int csm_timeout_ms) {
521 if (csm_timeout_ms < 10)
522 csm_timeout_ms = 10;
523 if (csm_timeout_ms > 10000)
524 csm_timeout_ms = 10000;
525 context->csm_timeout_ms = csm_timeout_ms;
526}
527
528unsigned int
530 return context->csm_timeout_ms;
531}
532
533void
535 uint32_t csm_max_message_size) {
536 assert(csm_max_message_size >= 64);
537 context->csm_max_message_size = csm_max_message_size;
538}
539
540uint32_t
544
545void
547 unsigned int session_timeout) {
548 context->session_timeout = session_timeout;
549}
550
551unsigned int
553 return context->session_timeout;
554}
555
556int
558#ifdef COAP_EPOLL_SUPPORT
559 return context->epfd;
560#else /* ! COAP_EPOLL_SUPPORT */
561 (void)context;
562 return -1;
563#endif /* ! COAP_EPOLL_SUPPORT */
564}
565
566int
568#ifdef COAP_EPOLL_SUPPORT
569 return 1;
570#else /* ! COAP_EPOLL_SUPPORT */
571 return 0;
572#endif /* ! COAP_EPOLL_SUPPORT */
573}
574
575int
577#ifdef COAP_THREAD_SAFE
578 return 1;
579#else /* ! COAP_THREAD_SAFE */
580 return 0;
581#endif /* ! COAP_THREAD_SAFE */
582}
583
584int
586#ifdef COAP_IPV4_SUPPORT
587 return 1;
588#else /* ! COAP_IPV4_SUPPORT */
589 return 0;
590#endif /* ! COAP_IPV4_SUPPORT */
591}
592
593int
595#ifdef COAP_IPV6_SUPPORT
596 return 1;
597#else /* ! COAP_IPV6_SUPPORT */
598 return 0;
599#endif /* ! COAP_IPV6_SUPPORT */
600}
601
602int
604#ifdef COAP_CLIENT_SUPPORT
605 return 1;
606#else /* ! COAP_CLIENT_SUPPORT */
607 return 0;
608#endif /* ! COAP_CLIENT_SUPPORT */
609}
610
611int
613#ifdef COAP_SERVER_SUPPORT
614 return 1;
615#else /* ! COAP_SERVER_SUPPORT */
616 return 0;
617#endif /* ! COAP_SERVER_SUPPORT */
618}
619
620int
622#ifdef COAP_AF_UNIX_SUPPORT
623 return 1;
624#else /* ! COAP_AF_UNIX_SUPPORT */
625 return 0;
626#endif /* ! COAP_AF_UNIX_SUPPORT */
627}
628
629void
630coap_context_set_app_data(coap_context_t *context, void *app_data) {
631 assert(context);
632 context->app = app_data;
633}
634
635void *
637 assert(context);
638 return context->app;
639}
640
642coap_new_context(const coap_address_t *listen_addr) {
644
645#if ! COAP_SERVER_SUPPORT
646 (void)listen_addr;
647#endif /* COAP_SERVER_SUPPORT */
648
649 if (!coap_started) {
650 coap_startup();
651 coap_log_warn("coap_startup() should be called before any other "
652 "coap_*() functions are called\n");
653 }
654
656 if (!c) {
657 coap_log_emerg("coap_init: malloc: failed\n");
658 return NULL;
659 }
660 memset(c, 0, sizeof(coap_context_t));
661
662 coap_lock_lock(c, coap_free_type(COAP_CONTEXT, c); return NULL);
663#ifdef COAP_EPOLL_SUPPORT
664 c->epfd = epoll_create1(0);
665 if (c->epfd == -1) {
666 coap_log_err("coap_new_context: Unable to epoll_create: %s (%d)\n",
668 errno);
669 goto onerror;
670 }
671 if (c->epfd != -1) {
672 c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
673 if (c->eptimerfd == -1) {
674 coap_log_err("coap_new_context: Unable to timerfd_create: %s (%d)\n",
676 errno);
677 goto onerror;
678 } else {
679 int ret;
680 struct epoll_event event;
681
682 /* Needed if running 32bit as ptr is only 32bit */
683 memset(&event, 0, sizeof(event));
684 event.events = EPOLLIN;
685 /* We special case this event by setting to NULL */
686 event.data.ptr = NULL;
687
688 ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
689 if (ret == -1) {
690 coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
691 "coap_new_context",
692 coap_socket_strerror(), errno);
693 goto onerror;
694 }
695 }
696 }
697#endif /* COAP_EPOLL_SUPPORT */
698
701 if (!c->dtls_context) {
702 coap_log_emerg("coap_init: no DTLS context available\n");
704 return NULL;
705 }
706 }
707
708 /* set default CSM values */
709 c->csm_timeout_ms = 1000;
710 c->csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
711
712#if COAP_SERVER_SUPPORT
713 if (listen_addr) {
714 coap_endpoint_t *endpoint = coap_new_endpoint_lkd(c, listen_addr, COAP_PROTO_UDP);
715 if (endpoint == NULL) {
716 goto onerror;
717 }
718 }
719#endif /* COAP_SERVER_SUPPORT */
720
721 c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
722
724 return c;
725
726#if defined(COAP_EPOLL_SUPPORT) || COAP_SERVER_SUPPORT
727onerror:
729 return NULL;
730#endif /* COAP_EPOLL_SUPPORT || COAP_SERVER_SUPPORT */
731}
732
733void
734coap_set_app_data(coap_context_t *ctx, void *app_data) {
735 assert(ctx);
736 ctx->app = app_data;
737}
738
739void *
741 assert(ctx);
742 return ctx->app;
743}
744
745COAP_API void
747 if (!context)
748 return;
749 coap_lock_lock(context, return);
750 coap_free_context_lkd(context);
751 coap_lock_unlock(context);
752}
753
754void
756 if (!context)
757 return;
758
759 coap_lock_check_locked(context);
760#if COAP_SERVER_SUPPORT
761 /* Removing a resource may cause a NON unsolicited observe to be sent */
763#endif /* COAP_SERVER_SUPPORT */
764
765 coap_delete_all(context->sendqueue);
766
767#ifdef WITH_LWIP
768 context->sendqueue = NULL;
769 if (context->timer_configured) {
770 LOCK_TCPIP_CORE();
771 sys_untimeout(coap_io_process_timeout, (void *)context);
772 UNLOCK_TCPIP_CORE();
773 context->timer_configured = 0;
774 }
775#endif /* WITH_LWIP */
776
777#if COAP_ASYNC_SUPPORT
778 coap_delete_all_async(context);
779#endif /* COAP_ASYNC_SUPPORT */
780
781#if COAP_OSCORE_SUPPORT
782 coap_delete_all_oscore(context);
783#endif /* COAP_OSCORE_SUPPORT */
784
785#if COAP_SERVER_SUPPORT
786 coap_cache_entry_t *cp, *ctmp;
787
788 HASH_ITER(hh, context->cache, cp, ctmp) {
789 coap_delete_cache_entry(context, cp);
790 }
791 if (context->cache_ignore_count) {
793 }
794
795 coap_endpoint_t *ep, *tmp;
796
797 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
799 }
800#endif /* COAP_SERVER_SUPPORT */
801
802#if COAP_CLIENT_SUPPORT
803 coap_session_t *sp, *rtmp;
804
805 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
807 }
808#endif /* COAP_CLIENT_SUPPORT */
809
810 if (context->dtls_context)
812#ifdef COAP_EPOLL_SUPPORT
813 if (context->eptimerfd != -1) {
814 int ret;
815 struct epoll_event event;
816
817 /* Kernels prior to 2.6.9 expect non NULL event parameter */
818 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
819 if (ret == -1) {
820 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
821 "coap_free_context",
822 coap_socket_strerror(), errno);
823 }
824 close(context->eptimerfd);
825 context->eptimerfd = -1;
826 }
827 if (context->epfd != -1) {
828 close(context->epfd);
829 context->epfd = -1;
830 }
831#endif /* COAP_EPOLL_SUPPORT */
832#if COAP_SERVER_SUPPORT
833#if COAP_WITH_OBSERVE_PERSIST
834 coap_persist_cleanup(context);
835#endif /* COAP_WITH_OBSERVE_PERSIST */
836#endif /* COAP_SERVER_SUPPORT */
837#if COAP_PROXY_SUPPORT
838 coap_proxy_cleanup(context);
839#endif /* COAP_PROXY_SUPPORT */
840
843}
844
845int
847 coap_pdu_t *pdu,
848 coap_opt_filter_t *unknown) {
849 coap_context_t *ctx = session->context;
850 coap_opt_iterator_t opt_iter;
851 int ok = 1;
852 coap_option_num_t last_number = -1;
853
855
856 while (coap_option_next(&opt_iter)) {
857 if (opt_iter.number & 0x01) {
858 /* first check the known built-in critical options */
859 switch (opt_iter.number) {
860#if COAP_Q_BLOCK_SUPPORT
863 if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
864 coap_log_debug("disabled support for critical option %u\n",
865 opt_iter.number);
866 ok = 0;
867 coap_option_filter_set(unknown, opt_iter.number);
868 }
869 break;
870#endif /* COAP_Q_BLOCK_SUPPORT */
882 break;
884 /* Valid critical if doing OSCORE */
885#if COAP_OSCORE_SUPPORT
886 if (ctx->p_osc_ctx)
887 break;
888#endif /* COAP_OSCORE_SUPPORT */
889 /* Fall Through */
890 default:
891 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
892#if COAP_SERVER_SUPPORT
893 if ((opt_iter.number & 0x02) == 0) {
894 coap_opt_iterator_t t_iter;
895
896 /* Safe to forward - check if proxy pdu */
897 if (session->proxy_session)
898 break;
899 if (COAP_PDU_IS_REQUEST(pdu) && ctx->proxy_uri_resource &&
902 pdu->crit_opt = 1;
903 break;
904 }
905 }
906#endif /* COAP_SERVER_SUPPORT */
907 coap_log_debug("unknown critical option %d\n", opt_iter.number);
908 ok = 0;
909
910 /* When opt_iter.number cannot be set in unknown, all of the appropriate
911 * slots have been used up and no more options can be tracked.
912 * Safe to break out of this loop as ok is already set. */
913 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
914 break;
915 }
916 }
917 }
918 }
919 if (last_number == opt_iter.number) {
920 /* Check for duplicated option RFC 5272 5.4.5 */
921 if (!coap_option_check_repeatable(opt_iter.number)) {
922 ok = 0;
923 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
924 break;
925 }
926 }
927 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
928 COAP_PDU_IS_REQUEST(pdu)) {
929 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
930 coap_block_b_t block;
931
932 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
933 if (block.m) {
934 size_t used_size = pdu->used_size;
935 unsigned char buf[4];
936
937 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
938 block.m = 0;
939 coap_update_option(pdu, opt_iter.number,
940 coap_encode_var_safe(buf, sizeof(buf),
941 ((block.num << 4) |
942 (block.m << 3) |
943 block.aszx)),
944 buf);
945 if (used_size != pdu->used_size) {
946 /* Unfortunately need to restart the scan */
948 last_number = -1;
949 continue;
950 }
951 }
952 }
953 }
954 last_number = opt_iter.number;
955 }
956
957 return ok;
958}
959
961coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
962 coap_mid_t mid;
963
964 coap_lock_lock(session->context, return COAP_INVALID_MID);
965 mid = coap_send_rst_lkd(session, request);
966 coap_lock_unlock(session->context);
967 return mid;
968}
969
971coap_send_rst_lkd(coap_session_t *session, const coap_pdu_t *request) {
972 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
973}
974
976coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
977 coap_mid_t mid;
978
979 coap_lock_lock(session->context, return COAP_INVALID_MID);
980 mid = coap_send_ack_lkd(session, request);
981 coap_lock_unlock(session->context);
982 return mid;
983}
984
986coap_send_ack_lkd(coap_session_t *session, const coap_pdu_t *request) {
987 coap_pdu_t *response;
989
991 if (request && request->type == COAP_MESSAGE_CON &&
992 COAP_PROTO_NOT_RELIABLE(session->proto)) {
993 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
994 if (response)
995 result = coap_send_internal(session, response);
996 }
997 return result;
998}
999
1000ssize_t
1002 ssize_t bytes_written = -1;
1003 assert(pdu->hdr_size > 0);
1004
1005 /* Caller handles partial writes */
1006 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1007 pdu->token - pdu->hdr_size,
1008 pdu->used_size + pdu->hdr_size);
1010 return bytes_written;
1011}
1012
1013static ssize_t
1015 ssize_t bytes_written;
1016
1017 if (session->state == COAP_SESSION_STATE_NONE) {
1018#if ! COAP_CLIENT_SUPPORT
1019 return -1;
1020#else /* COAP_CLIENT_SUPPORT */
1021 if (session->type != COAP_SESSION_TYPE_CLIENT)
1022 return -1;
1023#endif /* COAP_CLIENT_SUPPORT */
1024 }
1025
1026 if (pdu->type == COAP_MESSAGE_CON &&
1027 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1028 (session->sock.flags & COAP_SOCKET_MULTICAST)) {
1029 /* Violates RFC72522 8.1 */
1030 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1031 return -1;
1032 }
1033
1034 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1035 (pdu->type == COAP_MESSAGE_CON &&
1036 session->con_active >= COAP_NSTART(session))) {
1037 return coap_session_delay_pdu(session, pdu, node);
1038 }
1039
1040 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1041 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1042 return coap_session_delay_pdu(session, pdu, node);
1043
1044 bytes_written = coap_session_send_pdu(session, pdu);
1045 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1047 session->con_active++;
1048
1049 return bytes_written;
1050}
1051
1054 const coap_pdu_t *request,
1055 coap_pdu_code_t code,
1056 coap_opt_filter_t *opts) {
1057 coap_mid_t mid;
1058
1059 coap_lock_lock(session->context, return COAP_INVALID_MID);
1060 mid = coap_send_error_lkd(session, request, code, opts);
1061 coap_lock_unlock(session->context);
1062 return mid;
1063}
1064
1067 const coap_pdu_t *request,
1068 coap_pdu_code_t code,
1069 coap_opt_filter_t *opts) {
1070 coap_pdu_t *response;
1072
1073 assert(request);
1074 assert(session);
1075
1076 response = coap_new_error_response(request, code, opts);
1077 if (response)
1078 result = coap_send_internal(session, response);
1079
1080 return result;
1081}
1082
1085 coap_pdu_type_t type) {
1086 coap_mid_t mid;
1087
1088 coap_lock_lock(session->context, return COAP_INVALID_MID);
1089 mid = coap_send_message_type_lkd(session, request, type);
1090 coap_lock_unlock(session->context);
1091 return mid;
1092}
1093
1096 coap_pdu_type_t type) {
1097 coap_pdu_t *response;
1099
1101 if (request && COAP_PROTO_NOT_RELIABLE(session->proto)) {
1102 response = coap_pdu_init(type, 0, request->mid, 0);
1103 if (response)
1104 result = coap_send_internal(session, response);
1105 }
1106 return result;
1107}
1108
1122unsigned int
1123coap_calc_timeout(coap_session_t *session, unsigned char r) {
1124 unsigned int result;
1125
1126 /* The integer 1.0 as a Qx.FRAC_BITS */
1127#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1128
1129 /* rounds val up and right shifts by frac positions */
1130#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1131
1132 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1133 * make the result a rounded Qx.FRAC_BITS */
1134 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1135
1136 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1137 * make the result a rounded Qx.FRAC_BITS */
1138 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1139
1140 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1141 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1142 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1143
1144#undef FP1
1145#undef SHR_FP
1146}
1147
1150 coap_queue_t *node) {
1151 coap_tick_t now;
1152
1153 node->session = coap_session_reference_lkd(session);
1154
1155 /* Set timer for pdu retransmission. If this is the first element in
1156 * the retransmission queue, the base time is set to the current
1157 * time and the retransmission time is node->timeout. If there is
1158 * already an entry in the sendqueue, we must check if this node is
1159 * to be retransmitted earlier. Therefore, node->timeout is first
1160 * normalized to the base time and then inserted into the queue with
1161 * an adjusted relative time.
1162 */
1163 coap_ticks(&now);
1164 if (context->sendqueue == NULL) {
1165 node->t = node->timeout << node->retransmit_cnt;
1166 context->sendqueue_basetime = now;
1167 } else {
1168 /* make node->t relative to context->sendqueue_basetime */
1169 node->t = (now - context->sendqueue_basetime) +
1170 (node->timeout << node->retransmit_cnt);
1171 }
1172
1173 coap_insert_node(&context->sendqueue, node);
1174
1175 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1176 coap_session_str(node->session), node->id,
1177 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1179
1180 coap_update_io_timer(context, node->t);
1181
1182 return node->id;
1183}
1184
1185#if COAP_CLIENT_SUPPORT
1186/*
1187 * Sent out a test PDU for Extended Token
1188 */
1189static coap_mid_t
1190coap_send_test_extended_token(coap_session_t *session) {
1191 coap_pdu_t *pdu;
1193 size_t i;
1194 coap_binary_t *token;
1195
1196 coap_log_debug("Testing for Extended Token support\n");
1197 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1199 coap_new_message_id_lkd(session),
1201 if (!pdu)
1202 return COAP_INVALID_MID;
1203
1204 token = coap_new_binary(session->max_token_size);
1205 if (token == NULL) {
1206 coap_delete_pdu(pdu);
1207 return COAP_INVALID_MID;
1208 }
1209 for (i = 0; i < session->max_token_size; i++) {
1210 token->s[i] = (uint8_t)(i + 1);
1211 }
1212 coap_add_token(pdu, session->max_token_size, token->s);
1213 coap_delete_binary(token);
1214
1216
1217 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1218 if ((mid = coap_send_internal(session, pdu)) == COAP_INVALID_MID)
1219 return COAP_INVALID_MID;
1220 session->remote_test_mid = mid;
1221 return mid;
1222}
1223#endif /* COAP_CLIENT_SUPPORT */
1224
1225int
1227#if COAP_CLIENT_SUPPORT
1228 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1229 int timeout_ms = 5000;
1230 coap_session_state_t current_state = session->state;
1231
1232 if (session->delay_recursive) {
1233 assert(0);
1234 return 1;
1235 } else {
1236 session->delay_recursive = 1;
1237 }
1238 /*
1239 * Need to wait for first request to get out and response back before
1240 * continuing.. Response handler has to clear doing_first if not an error.
1241 */
1243 while (session->doing_first != 0) {
1244 int result = coap_io_process_lkd(session->context, 1000);
1245
1246 if (result < 0) {
1247 session->doing_first = 0;
1248 session->delay_recursive = 0;
1249 coap_session_release_lkd(session);
1250 return 0;
1251 }
1252
1253 /* coap_io_process_lkd() may have updated session state */
1254 if (session->state == COAP_SESSION_STATE_CSM &&
1255 current_state != COAP_SESSION_STATE_CSM) {
1256 /* Update timeout and restart the clock for CSM timeout */
1257 current_state = COAP_SESSION_STATE_CSM;
1258 timeout_ms = session->context->csm_timeout_ms;
1259 result = 0;
1260 }
1261
1262 if (result < timeout_ms) {
1263 timeout_ms -= result;
1264 } else {
1265 if (session->doing_first == 1) {
1266 /* Timeout failure of some sort with first request */
1267 session->doing_first = 0;
1268 if (session->state == COAP_SESSION_STATE_CSM) {
1269 coap_log_debug("** %s: timeout waiting for CSM response\n",
1270 coap_session_str(session));
1271 session->csm_not_seen = 1;
1272 coap_session_connected(session);
1273 } else {
1274 coap_log_debug("** %s: timeout waiting for first response\n",
1275 coap_session_str(session));
1276 }
1277 }
1278 }
1279 }
1280 session->delay_recursive = 0;
1281 coap_session_release_lkd(session);
1282 }
1283#else /* ! COAP_CLIENT_SUPPORT */
1284 (void)session;
1285#endif /* ! COAP_CLIENT_SUPPORT */
1286 return 1;
1287}
1288
1289/*
1290 * return 0 Invalid
1291 * 1 Valid
1292 */
1293int
1295
1296 /* Check validity of sending code */
1297 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1298 case 0: /* Empty or request */
1299 case 2: /* Success */
1300 case 3: /* Reserved for future use */
1301 case 4: /* Client error */
1302 case 5: /* Server error */
1303 break;
1304 case 7: /* Reliable signalling */
1305 if (COAP_PROTO_RELIABLE(session->proto))
1306 break;
1307 /* Not valid if UDP */
1308 /* Fall through */
1309 case 1: /* Invalid */
1310 case 6: /* Invalid */
1311 default:
1312 return 0;
1313 }
1314 return 1;
1315}
1316
1317#if COAP_CLIENT_SUPPORT
1318/*
1319 * If type is CON and protocol is not reliable, there is no need to set up
1320 * lg_crcv if it can be built up based on sent PDU if there is a
1321 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1322 * (Q-)Block1.
1323 */
1324static int
1325coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1326 coap_opt_iterator_t opt_iter;
1327
1328 if (
1330 session->oscore_encryption ||
1331#endif /* COAP_OSCORE_SUPPORT */
1332 ((pdu->type == COAP_MESSAGE_NON || COAP_PROTO_RELIABLE(session->proto)) &&
1334 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1336 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1337#endif /* COAP_Q_BLOCK_SUPPORT */
1338 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1339 return 1;
1340 }
1341 return 0;
1342}
1343#endif /* COAP_CLIENT_SUPPORT */
1344
1347 coap_mid_t mid;
1348
1349 coap_lock_lock(session->context, return COAP_INVALID_MID);
1350 mid = coap_send_lkd(session, pdu);
1351 coap_lock_unlock(session->context);
1352 return mid;
1353}
1354
1358#if COAP_CLIENT_SUPPORT
1359 coap_lg_crcv_t *lg_crcv = NULL;
1360 coap_opt_iterator_t opt_iter;
1361 coap_block_b_t block;
1362 int observe_action = -1;
1363 int have_block1 = 0;
1364 coap_opt_t *opt;
1365#endif /* COAP_CLIENT_SUPPORT */
1366
1367 assert(pdu);
1368
1370
1371 /* Check validity of sending code */
1372 if (!coap_check_code_class(session, pdu)) {
1373 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1375 pdu->code & 0x1f);
1376 goto error;
1377 }
1378 pdu->session = session;
1379#if COAP_CLIENT_SUPPORT
1380 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1381 !coap_netif_available(session)) {
1382 coap_log_debug("coap_send: Socket closed\n");
1383 goto error;
1384 }
1385 /*
1386 * If this is not the first client request and are waiting for a response
1387 * to the first client request, then drop sending out this next request
1388 * until all is properly established.
1389 */
1390 if (!coap_client_delay_first(session)) {
1391 goto error;
1392 }
1393
1394 /* Indicate support for Extended Tokens if appropriate */
1395 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1397 session->type == COAP_SESSION_TYPE_CLIENT &&
1398 COAP_PDU_IS_REQUEST(pdu)) {
1399 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1400 /*
1401 * When the pass / fail response for Extended Token is received, this PDU
1402 * will get transmitted.
1403 */
1404 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1405 goto error;
1406 }
1407 }
1408 /*
1409 * For reliable protocols, this will get cleared after CSM exchanged
1410 * in coap_session_connected()
1411 */
1412 session->doing_first = 1;
1413 if (!coap_client_delay_first(session)) {
1414 goto error;
1415 }
1416 }
1417
1418 /*
1419 * Check validity of token length
1420 */
1421 if (COAP_PDU_IS_REQUEST(pdu) &&
1422 pdu->actual_token.length > session->max_token_size) {
1423 coap_log_warn("coap_send: PDU dropped as token too long (%zu > %" PRIu32 ")\n",
1424 pdu->actual_token.length, session->max_token_size);
1425 goto error;
1426 }
1427
1428 /* A lot of the reliable code assumes type is CON */
1429 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1430 pdu->type = COAP_MESSAGE_CON;
1431
1432#if COAP_OSCORE_SUPPORT
1433 if (session->oscore_encryption) {
1434 if (session->recipient_ctx->initial_state == 1) {
1435 /*
1436 * Not sure if remote supports OSCORE, or is going to send us a
1437 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1438 * is OK. Continue sending current pdu to test things.
1439 */
1440 session->doing_first = 1;
1441 }
1442 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1444 goto error;
1445 }
1446 }
1447#endif /* COAP_OSCORE_SUPPORT */
1448
1449 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1450 return coap_send_internal(session, pdu);
1451 }
1452
1453 if (COAP_PDU_IS_REQUEST(pdu)) {
1454 uint8_t buf[4];
1455
1456 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1457
1458 if (opt) {
1459 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1460 coap_opt_length(opt));
1461 }
1462
1463 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1464 (block.m == 1 || block.bert == 1)) {
1465 have_block1 = 1;
1466 }
1467#if COAP_Q_BLOCK_SUPPORT
1468 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1469 (block.m == 1 || block.bert == 1)) {
1470 if (have_block1) {
1471 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1473 }
1474 have_block1 = 1;
1475 }
1476#endif /* COAP_Q_BLOCK_SUPPORT */
1477 if (observe_action != COAP_OBSERVE_CANCEL) {
1478 /* Warn about re-use of tokens */
1479 if (session->last_token &&
1480 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1481 coap_log_debug("Token reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n");
1482 }
1485 pdu->actual_token.length);
1486 } else {
1487 /* observe_action == COAP_OBSERVE_CANCEL */
1488 coap_binary_t tmp;
1489 int ret;
1490
1491 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1492 /* Unfortunately need to change the ptr type to be r/w */
1493 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1494 tmp.length = pdu->actual_token.length;
1495 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1496 if (ret == 1) {
1497 /* Observe Cancel successfully sent */
1498 coap_delete_pdu(pdu);
1499 return ret;
1500 }
1501 /* Some mismatch somewhere - continue to send original packet */
1502 }
1503 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1504 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1508 coap_encode_var_safe(buf, sizeof(buf),
1509 ++session->tx_rtag),
1510 buf);
1511 } else {
1512 memset(&block, 0, sizeof(block));
1513 }
1514
1515#if COAP_Q_BLOCK_SUPPORT
1516 /* Indicate support for Q-Block if appropriate */
1517 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1518 session->type == COAP_SESSION_TYPE_CLIENT &&
1519 COAP_PDU_IS_REQUEST(pdu)) {
1520 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1521 goto error;
1522 }
1523 session->doing_first = 1;
1524 if (!coap_client_delay_first(session)) {
1525 /* Q-Block test Session has failed for some reason */
1526 set_block_mode_drop_q(session->block_mode);
1527 goto error;
1528 }
1529 }
1530#endif /* COAP_Q_BLOCK_SUPPORT */
1531
1532#if COAP_Q_BLOCK_SUPPORT
1533 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1534#endif /* COAP_Q_BLOCK_SUPPORT */
1535 {
1536 /* Need to check if we need to reset Q-Block to Block */
1537 uint8_t buf[4];
1538
1539 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1542 coap_encode_var_safe(buf, sizeof(buf),
1543 (block.num << 4) | (0 << 3) | block.szx),
1544 buf);
1545 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1546 /* Need to update associated lg_xmit */
1547 coap_lg_xmit_t *lg_xmit;
1548
1549 LL_FOREACH(session->lg_xmit, lg_xmit) {
1550 if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1551 lg_xmit->b.b1.app_token &&
1552 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1553 /* Update the skeletal PDU with the block1 option */
1556 coap_encode_var_safe(buf, sizeof(buf),
1557 (block.num << 4) | (0 << 3) | block.szx),
1558 buf);
1559 break;
1560 }
1561 }
1562 }
1563 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1566 coap_encode_var_safe(buf, sizeof(buf),
1567 (block.num << 4) | (block.m << 3) | block.szx),
1568 buf);
1569 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1570 /* Need to update associated lg_xmit */
1571 coap_lg_xmit_t *lg_xmit;
1572
1573 LL_FOREACH(session->lg_xmit, lg_xmit) {
1574 if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1575 lg_xmit->b.b1.app_token &&
1576 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1577 /* Update the skeletal PDU with the block1 option */
1580 coap_encode_var_safe(buf, sizeof(buf),
1581 (block.num << 4) |
1582 (block.m << 3) |
1583 block.szx),
1584 buf);
1585 /* Update as this is a Request */
1586 lg_xmit->option = COAP_OPTION_BLOCK1;
1587 break;
1588 }
1589 }
1590 }
1591 }
1592
1593#if COAP_Q_BLOCK_SUPPORT
1594 if (COAP_PDU_IS_REQUEST(pdu) &&
1595 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1596 if (block.num == 0 && block.m == 0) {
1597 uint8_t buf[4];
1598
1599 /* M needs to be set as asking for all the blocks */
1601 coap_encode_var_safe(buf, sizeof(buf),
1602 (0 << 4) | (1 << 3) | block.szx),
1603 buf);
1604 }
1605 }
1606#endif /* COAP_Q_BLOCK_SUPPORT */
1607
1608 /*
1609 * If type is CON and protocol is not reliable, there is no need to set up
1610 * lg_crcv here as it can be built up based on sent PDU if there is a
1611 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1612 * (Q-)Block1.
1613 */
1614 if (coap_check_send_need_lg_crcv(session, pdu)) {
1615 coap_lg_xmit_t *lg_xmit = NULL;
1616
1617 if (!session->lg_xmit && have_block1) {
1618 coap_log_debug("PDU presented by app\n");
1620 }
1621 /* See if this token is already in use for large body responses */
1622 LL_FOREACH(session->lg_crcv, lg_crcv) {
1623 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1624 /* Need to terminate and clean up previous response setup */
1625 LL_DELETE(session->lg_crcv, lg_crcv);
1626 coap_block_delete_lg_crcv(session, lg_crcv);
1627 break;
1628 }
1629 }
1630
1631 if (have_block1 && session->lg_xmit) {
1632 LL_FOREACH(session->lg_xmit, lg_xmit) {
1633 if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1634 lg_xmit->b.b1.app_token &&
1635 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1636 break;
1637 }
1638 }
1639 }
1640 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1641 if (lg_crcv == NULL) {
1642 goto error;
1643 }
1644 if (lg_xmit) {
1645 /* Need to update the token as set up in the session->lg_xmit */
1646 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1647 }
1648 }
1649 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1650 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1651
1652#if COAP_Q_BLOCK_SUPPORT
1653 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1654 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1655 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1656 } else
1657#endif /* COAP_Q_BLOCK_SUPPORT */
1658 mid = coap_send_internal(session, pdu);
1659#else /* !COAP_CLIENT_SUPPORT */
1660 mid = coap_send_internal(session, pdu);
1661#endif /* !COAP_CLIENT_SUPPORT */
1662#if COAP_CLIENT_SUPPORT
1663 if (lg_crcv) {
1664 if (mid != COAP_INVALID_MID) {
1665 LL_PREPEND(session->lg_crcv, lg_crcv);
1666 } else {
1667 coap_block_delete_lg_crcv(session, lg_crcv);
1668 }
1669 }
1670#endif /* COAP_CLIENT_SUPPORT */
1671 return mid;
1672
1673error:
1674 coap_delete_pdu(pdu);
1675 return COAP_INVALID_MID;
1676}
1677
1680 uint8_t r;
1681 ssize_t bytes_written;
1682 coap_opt_iterator_t opt_iter;
1683
1684 pdu->session = session;
1685 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1686 /*
1687 * Need to prepend our IP identifier to the data as per
1688 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1689 */
1690 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1691 coap_opt_t *opt;
1692 size_t hop_limit;
1693
1694 addr_str[sizeof(addr_str)-1] = '\000';
1695 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1696 sizeof(addr_str) - 1)) {
1697 char *cp;
1698 size_t len;
1699
1700 if (addr_str[0] == '[') {
1701 cp = strchr(addr_str, ']');
1702 if (cp)
1703 *cp = '\000';
1704 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1705 /* IPv4 embedded into IPv6 */
1706 cp = &addr_str[8];
1707 } else {
1708 cp = &addr_str[1];
1709 }
1710 } else {
1711 cp = strchr(addr_str, ':');
1712 if (cp)
1713 *cp = '\000';
1714 cp = addr_str;
1715 }
1716 len = strlen(cp);
1717
1718 /* See if Hop Limit option is being used in return path */
1719 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1720 if (opt) {
1721 uint8_t buf[4];
1722
1723 hop_limit =
1725 if (hop_limit == 1) {
1726 coap_log_warn("Proxy loop detected '%s'\n",
1727 (char *)pdu->data);
1728 coap_delete_pdu(pdu);
1730 } else if (hop_limit < 1 || hop_limit > 255) {
1731 /* Something is bad - need to drop this pdu (TODO or delete option) */
1732 coap_log_warn("Proxy return has bad hop limit count '%zu'\n",
1733 hop_limit);
1734 coap_delete_pdu(pdu);
1736 }
1737 hop_limit--;
1739 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1740 buf);
1741 }
1742
1743 /* Need to check that we are not seeing this proxy in the return loop */
1744 if (pdu->data && opt == NULL) {
1745 char *a_match;
1746 size_t data_len;
1747
1748 if (pdu->used_size + 1 > pdu->max_size) {
1749 /* No space */
1750 coap_delete_pdu(pdu);
1752 }
1753 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1754 /* Internal error */
1755 coap_delete_pdu(pdu);
1757 }
1758 data_len = pdu->used_size - (pdu->data - pdu->token);
1759 pdu->data[data_len] = '\000';
1760 a_match = strstr((char *)pdu->data, cp);
1761 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1762 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1763 a_match[len] == ' ')) {
1764 coap_log_warn("Proxy loop detected '%s'\n",
1765 (char *)pdu->data);
1766 coap_delete_pdu(pdu);
1768 }
1769 }
1770 if (pdu->used_size + len + 1 <= pdu->max_size) {
1771 size_t old_size = pdu->used_size;
1772 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1773 if (pdu->data == NULL) {
1774 /*
1775 * Set Hop Limit to max for return path. If this libcoap is in
1776 * a proxy loop path, it will always decrement hop limit in code
1777 * above and hence timeout / drop the response as appropriate
1778 */
1779 hop_limit = 255;
1781 (uint8_t *)&hop_limit);
1782 coap_add_data(pdu, len, (uint8_t *)cp);
1783 } else {
1784 /* prepend with space separator, leaving hop limit "as is" */
1785 memmove(pdu->data + len + 1, pdu->data,
1786 old_size - (pdu->data - pdu->token));
1787 memcpy(pdu->data, cp, len);
1788 pdu->data[len] = ' ';
1789 pdu->used_size += len + 1;
1790 }
1791 }
1792 }
1793 }
1794 }
1795
1796 if (session->echo) {
1797 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1798 session->echo->s))
1799 goto error;
1800 coap_delete_bin_const(session->echo);
1801 session->echo = NULL;
1802 }
1803#if COAP_OSCORE_SUPPORT
1804 if (session->oscore_encryption) {
1805 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1807 goto error;
1808 }
1809#endif /* COAP_OSCORE_SUPPORT */
1810
1811 if (!coap_pdu_encode_header(pdu, session->proto)) {
1812 goto error;
1813 }
1814
1815#if !COAP_DISABLE_TCP
1816 if (COAP_PROTO_RELIABLE(session->proto) &&
1818 if (!session->csm_block_supported) {
1819 /*
1820 * Need to check that this instance is not sending any block options as
1821 * the remote end via CSM has not informed us that there is support
1822 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
1823 * This includes potential BERT blocks.
1824 */
1825 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1826 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
1827 }
1828 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1829 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
1830 }
1831 } else if (!session->csm_bert_rem_support) {
1832 coap_opt_t *opt;
1833
1834 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
1835 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1836 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
1837 }
1838 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
1839 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1840 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
1841 }
1842 }
1843 }
1844#endif /* !COAP_DISABLE_TCP */
1845
1846#if COAP_OSCORE_SUPPORT
1847 if (session->oscore_encryption &&
1848 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE)) {
1849 /* Refactor PDU as appropriate RFC8613 */
1850 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL,
1851 0);
1852
1853 if (osc_pdu == NULL) {
1854 coap_log_warn("OSCORE: PDU could not be encrypted\n");
1855 goto error;
1856 }
1857 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
1858 coap_delete_pdu(pdu);
1859 pdu = osc_pdu;
1860 } else
1861#endif /* COAP_OSCORE_SUPPORT */
1862 bytes_written = coap_send_pdu(session, pdu, NULL);
1863
1864 if (bytes_written == COAP_PDU_DELAYED) {
1865 /* do not free pdu as it is stored with session for later use */
1866 return pdu->mid;
1867 }
1868 if (bytes_written < 0) {
1869 goto error;
1870 }
1871
1872#if !COAP_DISABLE_TCP
1873 if (COAP_PROTO_RELIABLE(session->proto) &&
1874 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
1875 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
1876 session->partial_write = (size_t)bytes_written;
1877 /* do not free pdu as it is stored with session for later use */
1878 return pdu->mid;
1879 } else {
1880 goto error;
1881 }
1882 }
1883#endif /* !COAP_DISABLE_TCP */
1884
1885 if (pdu->type != COAP_MESSAGE_CON
1886 || COAP_PROTO_RELIABLE(session->proto)) {
1887 coap_mid_t id = pdu->mid;
1888 coap_delete_pdu(pdu);
1889 return id;
1890 }
1891
1892 coap_queue_t *node = coap_new_node();
1893 if (!node) {
1894 coap_log_debug("coap_wait_ack: insufficient memory\n");
1895 goto error;
1896 }
1897
1898 node->id = pdu->mid;
1899 node->pdu = pdu;
1900 coap_prng_lkd(&r, sizeof(r));
1901 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
1902 node->timeout = coap_calc_timeout(session, r);
1903 return coap_wait_ack(session->context, session, node);
1904error:
1905 coap_delete_pdu(pdu);
1906 return COAP_INVALID_MID;
1907}
1908
1911 if (!context || !node)
1912 return COAP_INVALID_MID;
1913
1914 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
1915 if (node->retransmit_cnt < node->session->max_retransmit) {
1916 ssize_t bytes_written;
1917 coap_tick_t now;
1918 coap_tick_t next_delay;
1919
1920 node->retransmit_cnt++;
1922
1923 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
1924 if (context->ping_timeout &&
1925 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
1926 uint8_t byte;
1927
1928 coap_prng_lkd(&byte, sizeof(byte));
1929 /* Don't exceed the ping timeout value */
1930 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
1931 }
1932
1933 coap_ticks(&now);
1934 if (context->sendqueue == NULL) {
1935 node->t = next_delay;
1936 context->sendqueue_basetime = now;
1937 } else {
1938 /* make node->t relative to context->sendqueue_basetime */
1939 node->t = (now - context->sendqueue_basetime) + next_delay;
1940 }
1941 coap_insert_node(&context->sendqueue, node);
1942
1943 if (node->is_mcast) {
1944 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
1945 coap_session_str(node->session), node->id);
1946 } else {
1947 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
1948 coap_session_str(node->session), node->id,
1949 node->retransmit_cnt,
1950 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
1951 }
1952
1953 if (node->session->con_active)
1954 node->session->con_active--;
1955 bytes_written = coap_send_pdu(node->session, node->pdu, node);
1956
1957 if (node->is_mcast) {
1960 return COAP_INVALID_MID;
1961 }
1962 if (bytes_written == COAP_PDU_DELAYED) {
1963 /* PDU was not retransmitted immediately because a new handshake is
1964 in progress. node was moved to the send queue of the session. */
1965 return node->id;
1966 }
1967
1968 if (bytes_written < 0)
1969 return (int)bytes_written;
1970
1971 return node->id;
1972 }
1973
1974 /* no more retransmissions, remove node from system */
1975 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
1976 coap_session_str(node->session), node->id, node->retransmit_cnt);
1977
1978#if COAP_SERVER_SUPPORT
1979 /* Check if subscriptions exist that should be canceled after
1980 COAP_OBS_MAX_FAIL */
1981 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2) {
1982 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
1983 }
1984#endif /* COAP_SERVER_SUPPORT */
1985 if (node->session->con_active) {
1986 node->session->con_active--;
1988 /*
1989 * As there may be another CON in a different queue entry on the same
1990 * session that needs to be immediately released,
1991 * coap_session_connected() is called.
1992 * However, there is the possibility coap_wait_ack() may be called for
1993 * this node (queue) and re-added to context->sendqueue.
1994 * coap_delete_node_lkd(node) called shortly will handle this and
1995 * remove it.
1996 */
1998 }
1999 }
2000
2001 /* And finally delete the node */
2002 if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
2003 coap_check_update_token(node->session, node->pdu);
2004 coap_lock_callback(context,
2005 context->nack_handler(node->session, node->pdu,
2007 }
2009 return COAP_INVALID_MID;
2010}
2011
2012static int
2014 uint8_t *data;
2015 size_t data_len;
2016 int result = -1;
2017
2018 coap_packet_get_memmapped(packet, &data, &data_len);
2019 if (session->proto == COAP_PROTO_DTLS) {
2020#if COAP_SERVER_SUPPORT
2021 if (session->type == COAP_SESSION_TYPE_HELLO)
2022 result = coap_dtls_hello(session, data, data_len);
2023 else
2024#endif /* COAP_SERVER_SUPPORT */
2025 if (session->tls)
2026 result = coap_dtls_receive(session, data, data_len);
2027 } else if (session->proto == COAP_PROTO_UDP) {
2028 result = coap_handle_dgram(ctx, session, data, data_len);
2029 }
2030 return result;
2031}
2032
2033#if COAP_CLIENT_SUPPORT
2034void
2036#if COAP_DISABLE_TCP
2037 (void)now;
2038
2040#else /* !COAP_DISABLE_TCP */
2041 if (coap_netif_strm_connect2(session)) {
2042 session->last_rx_tx = now;
2044 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2045 } else {
2048 }
2049#endif /* !COAP_DISABLE_TCP */
2050}
2051#endif /* COAP_CLIENT_SUPPORT */
2052
2053static void
2055 (void)ctx;
2056 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2057
2058 while (session->delayqueue) {
2059 ssize_t bytes_written;
2060 coap_queue_t *q = session->delayqueue;
2061 coap_log_debug("** %s: mid=0x%04x: transmitted after delay\n",
2062 coap_session_str(session), (int)q->pdu->mid);
2063 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2064 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2065 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2066 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2067 if (bytes_written > 0)
2068 session->last_rx_tx = now;
2069 if (bytes_written <= 0 ||
2070 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2071 if (bytes_written > 0)
2072 session->partial_write += (size_t)bytes_written;
2073 break;
2074 }
2075 session->delayqueue = q->next;
2076 session->partial_write = 0;
2078 }
2079}
2080
2081void
2083#if COAP_CONSTRAINED_STACK
2084 /* payload and packet can be protected by global_lock if needed */
2085 static unsigned char payload[COAP_RXBUFFER_SIZE];
2086 static coap_packet_t s_packet;
2087#else /* ! COAP_CONSTRAINED_STACK */
2088 unsigned char payload[COAP_RXBUFFER_SIZE];
2089 coap_packet_t s_packet;
2090#endif /* ! COAP_CONSTRAINED_STACK */
2091 coap_packet_t *packet = &s_packet;
2092
2094
2095 packet->length = sizeof(payload);
2096 packet->payload = payload;
2097
2098 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2099 ssize_t bytes_read;
2100 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2101 bytes_read = coap_netif_dgrm_read(session, packet);
2102
2103 if (bytes_read < 0) {
2104 if (bytes_read == -2)
2105 /* Reset the session back to startup defaults */
2107 } else if (bytes_read > 0) {
2108 session->last_rx_tx = now;
2109 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2110 coap_handle_dgram_for_proto(ctx, session, packet);
2111 }
2112#if !COAP_DISABLE_TCP
2113 } else if (session->proto == COAP_PROTO_WS ||
2114 session->proto == COAP_PROTO_WSS) {
2115 ssize_t bytes_read = 0;
2116
2117 /* WebSocket layer passes us the whole packet */
2118 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2119 packet->payload,
2120 packet->length);
2121 if (bytes_read < 0) {
2123 } else if (bytes_read > 2) {
2124 coap_pdu_t *pdu;
2125
2126 session->last_rx_tx = now;
2127 /* Need max space incase PDU is updated with updated token etc. */
2128 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2129 if (!pdu) {
2130 return;
2131 }
2132
2133 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2135 coap_log_warn("discard malformed PDU\n");
2136 coap_delete_pdu(pdu);
2137 return;
2138 }
2139
2140 coap_dispatch(ctx, session, pdu);
2141 coap_delete_pdu(pdu);
2142 return;
2143 }
2144 } else {
2145 ssize_t bytes_read = 0;
2146 const uint8_t *p;
2147 int retry;
2148
2149 do {
2150 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2151 packet->payload,
2152 packet->length);
2153 if (bytes_read > 0) {
2154 session->last_rx_tx = now;
2155 }
2156 p = packet->payload;
2157 retry = bytes_read == (ssize_t)packet->length;
2158 while (bytes_read > 0) {
2159 if (session->partial_pdu) {
2160 size_t len = session->partial_pdu->used_size
2161 + session->partial_pdu->hdr_size
2162 - session->partial_read;
2163 size_t n = min(len, (size_t)bytes_read);
2164 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2165 + session->partial_read, p, n);
2166 p += n;
2167 bytes_read -= n;
2168 if (n == len) {
2169 if (coap_pdu_parse_header(session->partial_pdu, session->proto)
2170 && coap_pdu_parse_opt(session->partial_pdu)) {
2171 coap_dispatch(ctx, session, session->partial_pdu);
2172 }
2173 coap_delete_pdu(session->partial_pdu);
2174 session->partial_pdu = NULL;
2175 session->partial_read = 0;
2176 } else {
2177 session->partial_read += n;
2178 }
2179 } else if (session->partial_read > 0) {
2180 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2181 session->read_header);
2182 size_t tkl = session->read_header[0] & 0x0f;
2183 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2184 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2185 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2186 size_t n = min(len, (size_t)bytes_read);
2187 memcpy(session->read_header + session->partial_read, p, n);
2188 p += n;
2189 bytes_read -= n;
2190 if (n == len) {
2191 /* Header now all in */
2192 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2193 hdr_size + tok_ext_bytes);
2194 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2195 coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
2196 coap_session_str(session),
2197 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2198 bytes_read = -1;
2199 break;
2200 }
2201 /* Need max space incase PDU is updated with updated token etc. */
2202 session->partial_pdu = coap_pdu_init(0, 0, 0,
2204 if (session->partial_pdu == NULL) {
2205 bytes_read = -1;
2206 break;
2207 }
2208 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2209 bytes_read = -1;
2210 break;
2211 }
2212 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2213 session->partial_pdu->used_size = size;
2214 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2215 session->partial_read = hdr_size + tok_ext_bytes;
2216 if (size == 0) {
2217 if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
2218 coap_dispatch(ctx, session, session->partial_pdu);
2219 }
2220 coap_delete_pdu(session->partial_pdu);
2221 session->partial_pdu = NULL;
2222 session->partial_read = 0;
2223 }
2224 } else {
2225 /* More of the header to go */
2226 session->partial_read += n;
2227 }
2228 } else {
2229 /* Get in first byte of the header */
2230 session->read_header[0] = *p++;
2231 bytes_read -= 1;
2232 if (!coap_pdu_parse_header_size(session->proto,
2233 session->read_header)) {
2234 bytes_read = -1;
2235 break;
2236 }
2237 session->partial_read = 1;
2238 }
2239 }
2240 } while (bytes_read == 0 && retry);
2241 if (bytes_read < 0)
2243#endif /* !COAP_DISABLE_TCP */
2244 }
2245}
2246
2247#if COAP_SERVER_SUPPORT
2248static int
2249coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2250 ssize_t bytes_read = -1;
2251 int result = -1; /* the value to be returned */
2252#if COAP_CONSTRAINED_STACK
2253 /* payload and e_packet can be protected by global_lock if needed */
2254 static unsigned char payload[COAP_RXBUFFER_SIZE];
2255 static coap_packet_t e_packet;
2256#else /* ! COAP_CONSTRAINED_STACK */
2257 unsigned char payload[COAP_RXBUFFER_SIZE];
2258 coap_packet_t e_packet;
2259#endif /* ! COAP_CONSTRAINED_STACK */
2260 coap_packet_t *packet = &e_packet;
2261
2262 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2263 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2264
2265 /* Need to do this as there may be holes in addr_info */
2266 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2267 packet->length = sizeof(payload);
2268 packet->payload = payload;
2270 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2271
2272 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2273 if (bytes_read < 0) {
2274 if (errno != EAGAIN) {
2275 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2276 }
2277 } else if (bytes_read > 0) {
2278 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2279 if (session) {
2280 coap_log_debug("* %s: netif: recv %4zd bytes\n",
2281 coap_session_str(session), bytes_read);
2282 result = coap_handle_dgram_for_proto(ctx, session, packet);
2283 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2284 coap_session_new_dtls_session(session, now);
2285 }
2286 }
2287 return result;
2288}
2289
2290static int
2291coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2292 (void)ctx;
2293 (void)endpoint;
2294 (void)now;
2295 return 0;
2296}
2297
2298#if !COAP_DISABLE_TCP
2299static int
2300coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2301 coap_tick_t now, void *extra) {
2302 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2303 if (session)
2304 session->last_rx_tx = now;
2305 return session != NULL;
2306}
2307#endif /* !COAP_DISABLE_TCP */
2308#endif /* COAP_SERVER_SUPPORT */
2309
2310COAP_API void
2312 coap_lock_lock(ctx, return);
2313 coap_io_do_io_lkd(ctx, now);
2314 coap_lock_unlock(ctx);
2315}
2316
2317void
2319#ifdef COAP_EPOLL_SUPPORT
2320 (void)ctx;
2321 (void)now;
2322 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2323#else /* ! COAP_EPOLL_SUPPORT */
2324 coap_session_t *s, *rtmp;
2325
2327#if COAP_SERVER_SUPPORT
2328 coap_endpoint_t *ep, *tmp;
2329 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2330 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2331 coap_read_endpoint(ctx, ep, now);
2332 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2333 coap_write_endpoint(ctx, ep, now);
2334#if !COAP_DISABLE_TCP
2335 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2336 coap_accept_endpoint(ctx, ep, now, NULL);
2337#endif /* !COAP_DISABLE_TCP */
2338 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2339 /* Make sure the session object is not deleted in one of the callbacks */
2341 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2342 coap_read_session(ctx, s, now);
2343 }
2344 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2345 coap_write_session(ctx, s, now);
2346 }
2348 }
2349 }
2350#endif /* COAP_SERVER_SUPPORT */
2351
2352#if COAP_CLIENT_SUPPORT
2353 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2354 /* Make sure the session object is not deleted in one of the callbacks */
2356 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2357 coap_connect_session(s, now);
2358 }
2359 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2360 coap_read_session(ctx, s, now);
2361 }
2362 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2363 coap_write_session(ctx, s, now);
2364 }
2366 }
2367#endif /* COAP_CLIENT_SUPPORT */
2368#endif /* ! COAP_EPOLL_SUPPORT */
2369}
2370
2371COAP_API void
2372coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2373 coap_lock_lock(ctx, return);
2374 coap_io_do_epoll_lkd(ctx, events, nevents);
2375 coap_lock_unlock(ctx);
2376}
2377
2378/*
2379 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2380 * directly saves having to iterate through the endpoints / sessions.
2381 */
2382void
2383coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2384#ifndef COAP_EPOLL_SUPPORT
2385 (void)ctx;
2386 (void)events;
2387 (void)nevents;
2388 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2389#else /* COAP_EPOLL_SUPPORT */
2390 coap_tick_t now;
2391 size_t j;
2392
2394 coap_ticks(&now);
2395 for (j = 0; j < nevents; j++) {
2396 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2397
2398 /* Ignore 'timer trigger' ptr which is NULL */
2399 if (sock) {
2400#if COAP_SERVER_SUPPORT
2401 if (sock->endpoint) {
2402 coap_endpoint_t *endpoint = sock->endpoint;
2403 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2404 (events[j].events & EPOLLIN)) {
2405 sock->flags |= COAP_SOCKET_CAN_READ;
2406 coap_read_endpoint(endpoint->context, endpoint, now);
2407 }
2408
2409 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2410 (events[j].events & EPOLLOUT)) {
2411 /*
2412 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2413 * be true causing epoll_wait to return early
2414 */
2415 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2417 coap_write_endpoint(endpoint->context, endpoint, now);
2418 }
2419
2420#if !COAP_DISABLE_TCP
2421 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2422 (events[j].events & EPOLLIN)) {
2424 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2425 }
2426#endif /* !COAP_DISABLE_TCP */
2427
2428 } else
2429#endif /* COAP_SERVER_SUPPORT */
2430 if (sock->session) {
2431 coap_session_t *session = sock->session;
2432
2433 /* Make sure the session object is not deleted
2434 in one of the callbacks */
2436#if COAP_CLIENT_SUPPORT
2437 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2438 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2440 coap_connect_session(session, now);
2441 if (coap_netif_available(session) &&
2442 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2443 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2444 }
2445 }
2446#endif /* COAP_CLIENT_SUPPORT */
2447
2448 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2449 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2450 sock->flags |= COAP_SOCKET_CAN_READ;
2451 coap_read_session(session->context, session, now);
2452 }
2453
2454 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2455 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2456 /*
2457 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2458 * be true causing epoll_wait to return early
2459 */
2460 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2462 coap_write_session(session->context, session, now);
2463 }
2464 /* Now dereference session so it can go away if needed */
2465 coap_session_release_lkd(session);
2466 }
2467 } else if (ctx->eptimerfd != -1) {
2468 /*
2469 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2470 * it so that it does not set EPOLLIN in the next epoll_wait().
2471 */
2472 uint64_t count;
2473
2474 /* Check the result from read() to suppress the warning on
2475 * systems that declare read() with warn_unused_result. */
2476 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2477 /* do nothing */;
2478 }
2479 }
2480 }
2481 /* And update eptimerfd as to when to next trigger */
2482 coap_ticks(&now);
2483 coap_io_prepare_epoll_lkd(ctx, now);
2484#endif /* COAP_EPOLL_SUPPORT */
2485}
2486
2487int
2489 uint8_t *msg, size_t msg_len) {
2490
2491 coap_pdu_t *pdu = NULL;
2492
2493 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2494 if (msg_len < 4) {
2495 /* Minimum size of CoAP header - ignore runt */
2496 return -1;
2497 }
2498 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2499 /*
2500 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2501 * this MUST be silently ignored.
2502 */
2503 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2504 return -1;
2505 }
2506
2507 /* Need max space incase PDU is updated with updated token etc. */
2508 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2509 if (!pdu)
2510 goto error;
2511
2512 if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
2514 coap_log_warn("discard malformed PDU\n");
2515 goto error;
2516 }
2517
2518 coap_dispatch(ctx, session, pdu);
2519 coap_delete_pdu(pdu);
2520 return 0;
2521
2522error:
2523 /*
2524 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2525 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2526 */
2527 coap_send_rst_lkd(session, pdu);
2528 coap_delete_pdu(pdu);
2529 return -1;
2530}
2531
2532int
2534 coap_queue_t **node) {
2535 coap_queue_t *p, *q;
2536
2537 if (!queue || !*queue)
2538 return 0;
2539
2540 /* replace queue head if PDU's time is less than head's time */
2541
2542 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2543 *node = *queue;
2544 *queue = (*queue)->next;
2545 if (*queue) { /* adjust relative time of new queue head */
2546 (*queue)->t += (*node)->t;
2547 }
2548 (*node)->next = NULL;
2549 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2550 coap_session_str(session), id);
2551 return 1;
2552 }
2553
2554 /* search message id queue to remove (only first occurence will be removed) */
2555 q = *queue;
2556 do {
2557 p = q;
2558 q = q->next;
2559 } while (q && (session != q->session || id != q->id));
2560
2561 if (q) { /* found message id */
2562 p->next = q->next;
2563 if (p->next) { /* must update relative time of p->next */
2564 p->next->t += q->t;
2565 }
2566 q->next = NULL;
2567 *node = q;
2568 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
2569 coap_session_str(session), id);
2570 return 1;
2571 }
2572
2573 return 0;
2574
2575}
2576
2577void
2579 coap_nack_reason_t reason) {
2580 coap_queue_t *p, *q;
2581
2582 while (context->sendqueue && context->sendqueue->session == session) {
2583 q = context->sendqueue;
2584 context->sendqueue = q->next;
2585 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
2586 coap_session_str(session), q->id);
2587 if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
2588 coap_check_update_token(session, q->pdu);
2589 coap_lock_callback(context,
2590 context->nack_handler(session, q->pdu, reason, q->id));
2591 }
2593 }
2594
2595 if (!context->sendqueue)
2596 return;
2597
2598 p = context->sendqueue;
2599 q = p->next;
2600
2601 while (q) {
2602 if (q->session == session) {
2603 p->next = q->next;
2604 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
2605 coap_session_str(session), q->id);
2606 if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
2607 coap_check_update_token(session, q->pdu);
2608 coap_lock_callback(context,
2609 context->nack_handler(session, q->pdu, reason, q->id));
2610 }
2612 q = p->next;
2613 } else {
2614 p = q;
2615 q = q->next;
2616 }
2617 }
2618}
2619
2620void
2622 coap_bin_const_t *token) {
2623 /* cancel all messages in sendqueue that belong to session
2624 * and use the specified token */
2625 coap_queue_t **p, *q;
2626
2627 if (!context->sendqueue)
2628 return;
2629
2630 p = &context->sendqueue;
2631 q = *p;
2632
2633 while (q) {
2634 if (q->session == session &&
2635 coap_binary_equal(&q->pdu->actual_token, token)) {
2636 *p = q->next;
2637 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
2638 coap_session_str(session), q->id);
2639 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2640 session->con_active--;
2641 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2642 /* Flush out any entries on session->delayqueue */
2643 coap_session_connected(session);
2644 }
2646 } else {
2647 p = &(q->next);
2648 }
2649 q = *p;
2650 }
2651}
2652
2653coap_pdu_t *
2655 coap_opt_filter_t *opts) {
2656 coap_opt_iterator_t opt_iter;
2657 coap_pdu_t *response;
2658 size_t size = request->e_token_length;
2659 unsigned char type;
2660 coap_opt_t *option;
2661 coap_option_num_t opt_num = 0; /* used for calculating delta-storage */
2662
2663#if COAP_ERROR_PHRASE_LENGTH > 0
2664 const char *phrase;
2665 if (code != COAP_RESPONSE_CODE(508)) {
2666 phrase = coap_response_phrase(code);
2667
2668 /* Need some more space for the error phrase and payload start marker */
2669 if (phrase)
2670 size += strlen(phrase) + 1;
2671 } else {
2672 /*
2673 * Need space for IP for 5.08 response which is filled in in
2674 * coap_send_internal()
2675 * https://rfc-editor.org/rfc/rfc8768.html#section-4
2676 */
2677 phrase = NULL;
2678 size += INET6_ADDRSTRLEN;
2679 }
2680#endif
2681
2682 assert(request);
2683
2684 /* cannot send ACK if original request was not confirmable */
2685 type = request->type == COAP_MESSAGE_CON ?
2687
2688 /* Estimate how much space we need for options to copy from
2689 * request. We always need the Token, for 4.02 the unknown critical
2690 * options must be included as well. */
2691
2692 /* we do not want these */
2695 /* Unsafe to send this back */
2697
2698 coap_option_iterator_init(request, &opt_iter, opts);
2699
2700 /* Add size of each unknown critical option. As known critical
2701 options as well as elective options are not copied, the delta
2702 value might grow.
2703 */
2704 while ((option = coap_option_next(&opt_iter))) {
2705 uint16_t delta = opt_iter.number - opt_num;
2706 /* calculate space required to encode (opt_iter.number - opt_num) */
2707 if (delta < 13) {
2708 size++;
2709 } else if (delta < 269) {
2710 size += 2;
2711 } else {
2712 size += 3;
2713 }
2714
2715 /* add coap_opt_length(option) and the number of additional bytes
2716 * required to encode the option length */
2717
2718 size += coap_opt_length(option);
2719 switch (*option & 0x0f) {
2720 case 0x0e:
2721 size++;
2722 /* fall through */
2723 case 0x0d:
2724 size++;
2725 break;
2726 default:
2727 ;
2728 }
2729
2730 opt_num = opt_iter.number;
2731 }
2732
2733 /* Now create the response and fill with options and payload data. */
2734 response = coap_pdu_init(type, code, request->mid, size);
2735 if (response) {
2736 /* copy token */
2737 if (!coap_add_token(response, request->actual_token.length,
2738 request->actual_token.s)) {
2739 coap_log_debug("cannot add token to error response\n");
2740 coap_delete_pdu(response);
2741 return NULL;
2742 }
2743
2744 /* copy all options */
2745 coap_option_iterator_init(request, &opt_iter, opts);
2746 while ((option = coap_option_next(&opt_iter))) {
2747 coap_add_option_internal(response, opt_iter.number,
2748 coap_opt_length(option),
2749 coap_opt_value(option));
2750 }
2751
2752#if COAP_ERROR_PHRASE_LENGTH > 0
2753 /* note that diagnostic messages do not need a Content-Format option. */
2754 if (phrase)
2755 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
2756#endif
2757 }
2758
2759 return response;
2760}
2761
2762#if COAP_SERVER_SUPPORT
2763#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
2764
2765static void
2766free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
2767 coap_delete_string(app_ptr);
2768}
2769
2770/*
2771 * Caution: As this handler is in libcoap space, it is called with
2772 * context locked.
2773 */
2774static void
2775hnd_get_wellknown_lkd(coap_resource_t *resource,
2776 coap_session_t *session,
2777 const coap_pdu_t *request,
2778 const coap_string_t *query,
2779 coap_pdu_t *response) {
2780 size_t len = 0;
2781 coap_string_t *data_string = NULL;
2782 coap_print_status_t result = 0;
2783 size_t wkc_len = 0;
2784 uint8_t buf[4];
2785
2786 /*
2787 * Quick hack to determine the size of the resource descriptions for
2788 * .well-known/core.
2789 */
2790 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
2791 if (result & COAP_PRINT_STATUS_ERROR) {
2792 coap_log_warn("cannot determine length of /.well-known/core\n");
2793 goto error;
2794 }
2795
2796 if (wkc_len > 0) {
2797 data_string = coap_new_string(wkc_len);
2798 if (!data_string)
2799 goto error;
2800
2801 len = wkc_len;
2802 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
2803 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
2804 coap_log_debug("coap_print_wellknown failed\n");
2805 goto error;
2806 }
2807 assert(len <= (size_t)wkc_len);
2808 data_string->length = len;
2809
2810 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
2812 coap_encode_var_safe(buf, sizeof(buf),
2814 goto error;
2815 }
2816 if (response->used_size + len + 1 > response->max_size) {
2817 /*
2818 * Data does not fit into a packet and no libcoap block support
2819 * +1 for end of options marker
2820 */
2821 coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
2822 len, response->max_size - response->used_size - 1);
2823 len = response->max_size - response->used_size - 1;
2824 }
2825 if (!coap_add_data(response, len, data_string->s)) {
2826 goto error;
2827 }
2828 free_wellknown_response(session, data_string);
2829 } else if (!coap_add_data_large_response_lkd(resource, session, request,
2830 response, query,
2832 -1, 0, data_string->length,
2833 data_string->s,
2834 free_wellknown_response,
2835 data_string)) {
2836 goto error_released;
2837 }
2838 } else {
2840 coap_encode_var_safe(buf, sizeof(buf),
2842 goto error;
2843 }
2844 }
2845 response->code = COAP_RESPONSE_CODE(205);
2846 return;
2847
2848error:
2849 free_wellknown_response(session, data_string);
2850error_released:
2851 if (response->code == 0) {
2852 /* set error code 5.03 and remove all options and data from response */
2853 response->code = COAP_RESPONSE_CODE(503);
2854 response->used_size = response->e_token_length;
2855 response->data = NULL;
2856 }
2857}
2858#endif /* COAP_SERVER_SUPPORT */
2859
2870static int
2872 int num_cancelled = 0; /* the number of observers cancelled */
2873
2874#ifndef COAP_SERVER_SUPPORT
2875 (void)sent;
2876#endif /* ! COAP_SERVER_SUPPORT */
2877 (void)context;
2878
2879#if COAP_SERVER_SUPPORT
2880 /* remove observer for this resource, if any
2881 * Use token from sent and try to find a matching resource. Uh!
2882 */
2883 RESOURCES_ITER(context->resources, r) {
2884 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
2885 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
2886 }
2887#endif /* COAP_SERVER_SUPPORT */
2888
2889 return num_cancelled;
2890}
2891
2892#if COAP_SERVER_SUPPORT
2897enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
2898
2899/*
2900 * Checks for No-Response option in given @p request and
2901 * returns @c RESPONSE_DROP if @p response should be suppressed
2902 * according to RFC 7967.
2903 *
2904 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
2905 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
2906 * on retrying.
2907 *
2908 * Checks if the response code is 0.00 and if either the session is reliable or
2909 * non-confirmable, @c RESPONSE_DROP is also returned.
2910 *
2911 * Multicast response checking is also carried out.
2912 *
2913 * NOTE: It is the responsibility of the application to determine whether
2914 * a delayed separate response should be sent as the original requesting packet
2915 * containing the No-Response option has long since gone.
2916 *
2917 * The value of the No-Response option is encoded as
2918 * follows:
2919 *
2920 * @verbatim
2921 * +-------+-----------------------+-----------------------------------+
2922 * | Value | Binary Representation | Description |
2923 * +-------+-----------------------+-----------------------------------+
2924 * | 0 | <empty> | Interested in all responses. |
2925 * +-------+-----------------------+-----------------------------------+
2926 * | 2 | 00000010 | Not interested in 2.xx responses. |
2927 * +-------+-----------------------+-----------------------------------+
2928 * | 8 | 00001000 | Not interested in 4.xx responses. |
2929 * +-------+-----------------------+-----------------------------------+
2930 * | 16 | 00010000 | Not interested in 5.xx responses. |
2931 * +-------+-----------------------+-----------------------------------+
2932 * @endverbatim
2933 *
2934 * @param request The CoAP request to check for the No-Response option.
2935 * This parameter must not be NULL.
2936 * @param response The response that is potentially suppressed.
2937 * This parameter must not be NULL.
2938 * @param session The session this request/response are associated with.
2939 * This parameter must not be NULL.
2940 * @return RESPONSE_DEFAULT when no special treatment is requested,
2941 * RESPONSE_DROP when the response must be discarded, or
2942 * RESPONSE_SEND when the response must be sent.
2943 */
2944static enum respond_t
2945no_response(coap_pdu_t *request, coap_pdu_t *response,
2946 coap_session_t *session, coap_resource_t *resource) {
2947 coap_opt_t *nores;
2948 coap_opt_iterator_t opt_iter;
2949 unsigned int val = 0;
2950
2951 assert(request);
2952 assert(response);
2953
2954 if (COAP_RESPONSE_CLASS(response->code) > 0) {
2955 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
2956
2957 if (nores) {
2959
2960 /* The response should be dropped when the bit corresponding to
2961 * the response class is set (cf. table in function
2962 * documentation). When a No-Response option is present and the
2963 * bit is not set, the sender explicitly indicates interest in
2964 * this response. */
2965 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
2966 /* Should be dropping the response */
2967 if (response->type == COAP_MESSAGE_ACK &&
2968 COAP_PROTO_NOT_RELIABLE(session->proto)) {
2969 /* Still need to ACK the request */
2970 response->code = 0;
2971 /* Remove token/data from piggybacked acknowledgment PDU */
2972 response->actual_token.length = 0;
2973 response->e_token_length = 0;
2974 response->used_size = 0;
2975 response->data = NULL;
2976 return RESPONSE_SEND;
2977 } else {
2978 return RESPONSE_DROP;
2979 }
2980 } else {
2981 /* True for mcast as well RFC7967 2.1 */
2982 return RESPONSE_SEND;
2983 }
2984 } else if (resource && session->context->mcast_per_resource &&
2985 coap_is_mcast(&session->addr_info.local)) {
2986 /* Handle any mcast suppression specifics if no NoResponse option */
2987 if ((resource->flags &
2989 COAP_RESPONSE_CLASS(response->code) == 2) {
2990 return RESPONSE_DROP;
2991 } else if ((resource->flags &
2993 response->code == COAP_RESPONSE_CODE(205)) {
2994 if (response->data == NULL)
2995 return RESPONSE_DROP;
2996 } else if ((resource->flags &
2998 COAP_RESPONSE_CLASS(response->code) == 4) {
2999 return RESPONSE_DROP;
3000 } else if ((resource->flags &
3002 COAP_RESPONSE_CLASS(response->code) == 5) {
3003 return RESPONSE_DROP;
3004 }
3005 }
3006 } else if (COAP_PDU_IS_EMPTY(response) &&
3007 (response->type == COAP_MESSAGE_NON ||
3008 COAP_PROTO_RELIABLE(session->proto))) {
3009 /* response is 0.00, and this is reliable or non-confirmable */
3010 return RESPONSE_DROP;
3011 }
3012
3013 /*
3014 * Do not send error responses for requests that were received via
3015 * IP multicast. RFC7252 8.1
3016 */
3017
3018 if (coap_is_mcast(&session->addr_info.local)) {
3019 if (request->type == COAP_MESSAGE_NON &&
3020 response->type == COAP_MESSAGE_RST)
3021 return RESPONSE_DROP;
3022
3023 if ((!resource || session->context->mcast_per_resource == 0) &&
3024 COAP_RESPONSE_CLASS(response->code) > 2)
3025 return RESPONSE_DROP;
3026 }
3027
3028 /* Default behavior applies when we are not dealing with a response
3029 * (class == 0) or the request did not contain a No-Response option.
3030 */
3031 return RESPONSE_DEFAULT;
3032}
3033
3034static coap_str_const_t coap_default_uri_wellknown = {
3036 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3037};
3038
3039/* Initialized in coap_startup() */
3040static coap_resource_t resource_uri_wellknown;
3041
3042static void
3043handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu) {
3044 coap_method_handler_t h = NULL;
3045 coap_pdu_t *response = NULL;
3046 coap_opt_filter_t opt_filter;
3047 coap_resource_t *resource = NULL;
3048 /* The respond field indicates whether a response must be treated
3049 * specially due to a No-Response option that declares disinterest
3050 * or interest in a specific response class. DEFAULT indicates that
3051 * No-Response has not been specified. */
3052 enum respond_t respond = RESPONSE_DEFAULT;
3053 coap_opt_iterator_t opt_iter;
3054 coap_opt_t *opt;
3055 int is_proxy_uri = 0;
3056 int is_proxy_scheme = 0;
3057 int skip_hop_limit_check = 0;
3058 int resp = 0;
3059 int send_early_empty_ack = 0;
3060 coap_string_t *query = NULL;
3061 coap_opt_t *observe = NULL;
3062 coap_string_t *uri_path = NULL;
3063 int observe_action = COAP_OBSERVE_CANCEL;
3064 coap_block_b_t block;
3065 int added_block = 0;
3066 coap_lg_srcv_t *free_lg_srcv = NULL;
3067#if COAP_Q_BLOCK_SUPPORT
3068 int lg_xmit_ctrl = 0;
3069#endif /* COAP_Q_BLOCK_SUPPORT */
3070#if COAP_ASYNC_SUPPORT
3071 coap_async_t *async;
3072#endif /* COAP_ASYNC_SUPPORT */
3073
3074 if (coap_is_mcast(&session->addr_info.local)) {
3075 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3076 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3077 return;
3078 }
3079 }
3080#if COAP_ASYNC_SUPPORT
3081 async = coap_find_async_lkd(session, pdu->actual_token);
3082 if (async) {
3083 coap_tick_t now;
3084
3085 coap_ticks(&now);
3086 if (async->delay == 0 || async->delay > now) {
3087 /* re-transmit missing ACK (only if CON) */
3088 coap_log_info("Retransmit async response\n");
3089 coap_send_ack_lkd(session, pdu);
3090 /* and do not pass on to the upper layers */
3091 return;
3092 }
3093 }
3094#endif /* COAP_ASYNC_SUPPORT */
3095
3096 coap_option_filter_clear(&opt_filter);
3097 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3098 if (opt) {
3099 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3100 if (!opt) {
3101 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3102 resp = 402;
3103 goto fail_response;
3104 }
3105 is_proxy_scheme = 1;
3106 }
3107
3108 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3109 if (opt)
3110 is_proxy_uri = 1;
3111
3112 if (is_proxy_scheme || is_proxy_uri) {
3113 coap_uri_t uri;
3114
3115 if (!context->proxy_uri_resource) {
3116 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3117 coap_log_debug("Proxy-%s support not configured\n",
3118 is_proxy_scheme ? "Scheme" : "Uri");
3119 resp = 505;
3120 goto fail_response;
3121 }
3122 if (((size_t)pdu->code - 1 <
3123 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3124 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3125 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3126 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3127 is_proxy_scheme ? "Scheme" : "Uri",
3128 pdu->code/100, pdu->code%100);
3129 resp = 505;
3130 goto fail_response;
3131 }
3132
3133 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3134 if (is_proxy_uri) {
3136 coap_opt_length(opt), &uri) < 0) {
3137 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3138 coap_log_debug("Proxy-URI not decodable\n");
3139 resp = 505;
3140 goto fail_response;
3141 }
3142 } else {
3143 memset(&uri, 0, sizeof(uri));
3144 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3145 if (opt) {
3146 uri.host.length = coap_opt_length(opt);
3147 uri.host.s = coap_opt_value(opt);
3148 } else
3149 uri.host.length = 0;
3150 }
3151
3152 resource = context->proxy_uri_resource;
3153 if (uri.host.length && resource->proxy_name_count &&
3154 resource->proxy_name_list) {
3155 size_t i;
3156
3157 if (resource->proxy_name_count == 1 &&
3158 resource->proxy_name_list[0]->length == 0) {
3159 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3160 i = 0;
3161 } else {
3162 for (i = 0; i < resource->proxy_name_count; i++) {
3163 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3164 break;
3165 }
3166 }
3167 }
3168 if (i != resource->proxy_name_count) {
3169 /* This server is hosting the proxy connection endpoint */
3170 if (pdu->crit_opt) {
3171 /* Cannot handle critical option */
3172 pdu->crit_opt = 0;
3173 resp = 402;
3174 goto fail_response;
3175 }
3176 is_proxy_uri = 0;
3177 is_proxy_scheme = 0;
3178 skip_hop_limit_check = 1;
3179 }
3180 }
3181 resource = NULL;
3182 }
3183
3184 if (!skip_hop_limit_check) {
3185 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3186 if (opt) {
3187 size_t hop_limit;
3188 uint8_t buf[4];
3189
3190 hop_limit =
3192 if (hop_limit == 1) {
3193 /* coap_send_internal() will fill in the IP address for us */
3194 resp = 508;
3195 goto fail_response;
3196 } else if (hop_limit < 1 || hop_limit > 255) {
3197 /* Need to return a 4.00 RFC8768 Section 3 */
3198 coap_log_info("Invalid Hop Limit\n");
3199 resp = 400;
3200 goto fail_response;
3201 }
3202 hop_limit--;
3204 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3205 buf);
3206 }
3207 }
3208
3209 uri_path = coap_get_uri_path(pdu);
3210 if (!uri_path)
3211 return;
3212
3213 if (!is_proxy_uri && !is_proxy_scheme) {
3214 /* try to find the resource from the request URI */
3215 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3216 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3217 }
3218
3219 if ((resource == NULL) || (resource->is_unknown == 1) ||
3220 (resource->is_proxy_uri == 1)) {
3221 /* The resource was not found or there is an unexpected match against the
3222 * resource defined for handling unknown or proxy URIs.
3223 */
3224 if (resource != NULL)
3225 /* Close down unexpected match */
3226 resource = NULL;
3227 /*
3228 * Check if the request URI happens to be the well-known URI, or if the
3229 * unknown resource handler is defined, a PUT or optionally other methods,
3230 * if configured, for the unknown handler.
3231 *
3232 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3233 * proxy URI handler.
3234 *
3235 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3236 * set, call the unknown URI handler with any unknown URI (including
3237 * .well-known/core) if the appropriate method is defined.
3238 *
3239 * else if well-known URI generate a default response.
3240 *
3241 * else if unknown URI handler defined, call the unknown
3242 * URI handler (to allow for potential generation of resource
3243 * [RFC7272 5.8.3]) if the appropriate method is defined.
3244 *
3245 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3246 *
3247 * else return 4.04.
3248 */
3249
3250 if (is_proxy_uri || is_proxy_scheme) {
3251 resource = context->proxy_uri_resource;
3252 } else if (context->unknown_resource != NULL &&
3254 ((size_t)pdu->code - 1 <
3255 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3256 (context->unknown_resource->handler[pdu->code - 1])) {
3257 resource = context->unknown_resource;
3258 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3259 /* request for .well-known/core */
3260 resource = &resource_uri_wellknown;
3261 } else if ((context->unknown_resource != NULL) &&
3262 ((size_t)pdu->code - 1 <
3263 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3264 (context->unknown_resource->handler[pdu->code - 1])) {
3265 /*
3266 * The unknown_resource can be used to handle undefined resources
3267 * for a PUT request and can support any other registered handler
3268 * defined for it
3269 * Example set up code:-
3270 * r = coap_resource_unknown_init(hnd_put_unknown);
3271 * coap_register_request_handler(r, COAP_REQUEST_POST,
3272 * hnd_post_unknown);
3273 * coap_register_request_handler(r, COAP_REQUEST_GET,
3274 * hnd_get_unknown);
3275 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3276 * hnd_delete_unknown);
3277 * coap_add_resource(ctx, r);
3278 *
3279 * Note: It is not possible to observe the unknown_resource, a separate
3280 * resource must be created (by PUT or POST) which has a GET
3281 * handler to be observed
3282 */
3283 resource = context->unknown_resource;
3284 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3285 /*
3286 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3287 */
3288 coap_log_debug("request for unknown resource '%*.*s',"
3289 " return 2.02\n",
3290 (int)uri_path->length,
3291 (int)uri_path->length,
3292 uri_path->s);
3293 resp = 202;
3294 goto fail_response;
3295 } else { /* request for any another resource, return 4.04 */
3296
3297 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3298 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3299 resp = 404;
3300 goto fail_response;
3301 }
3302
3303 }
3304
3305#if COAP_OSCORE_SUPPORT
3306 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3307 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3308 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3309 resp = 401;
3310 goto fail_response;
3311 }
3312#endif /* COAP_OSCORE_SUPPORT */
3313 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3314 /* Check for existing resource and If-Non-Match */
3315 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3316 if (opt) {
3317 resp = 412;
3318 goto fail_response;
3319 }
3320 }
3321
3322 /* the resource was found, check if there is a registered handler */
3323 if ((size_t)pdu->code - 1 <
3324 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3325 h = resource->handler[pdu->code - 1];
3326
3327 if (h == NULL) {
3328 resp = 405;
3329 goto fail_response;
3330 }
3331 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3332 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3333 if (opt == NULL) {
3334 /* RFC 8132 2.3.1 */
3335 resp = 415;
3336 goto fail_response;
3337 }
3338 }
3339 if (context->mcast_per_resource &&
3340 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3341 coap_is_mcast(&session->addr_info.local)) {
3342 resp = 405;
3343 goto fail_response;
3344 }
3345
3346 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3348 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3349 if (!response) {
3350 coap_log_err("could not create response PDU\n");
3351 resp = 500;
3352 goto fail_response;
3353 }
3354 response->session = session;
3355#if COAP_ASYNC_SUPPORT
3356 /* If handling a separate response, need CON, not ACK response */
3357 if (async && pdu->type == COAP_MESSAGE_CON)
3358 response->type = COAP_MESSAGE_CON;
3359#endif /* COAP_ASYNC_SUPPORT */
3360 /* A lot of the reliable code assumes type is CON */
3361 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3362 response->type = COAP_MESSAGE_CON;
3363
3364 if (!coap_add_token(response, pdu->actual_token.length,
3365 pdu->actual_token.s)) {
3366 resp = 500;
3367 goto fail_response;
3368 }
3369
3370 query = coap_get_query(pdu);
3371
3372 /* check for Observe option RFC7641 and RFC8132 */
3373 if (resource->observable &&
3374 (pdu->code == COAP_REQUEST_CODE_GET ||
3375 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3376 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3377 }
3378
3379 /*
3380 * See if blocks need to be aggregated or next requests sent off
3381 * before invoking application request handler
3382 */
3383 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3384 uint32_t block_mode = session->block_mode;
3385
3386 if (pdu->code == COAP_REQUEST_CODE_FETCH ||
3389 if (coap_handle_request_put_block(context, session, pdu, response,
3390 resource, uri_path, observe,
3391 &added_block, &free_lg_srcv)) {
3392 session->block_mode = block_mode;
3393 goto skip_handler;
3394 }
3395 session->block_mode = block_mode;
3396
3397 if (coap_handle_request_send_block(session, pdu, response, resource,
3398 query)) {
3399#if COAP_Q_BLOCK_SUPPORT
3400 lg_xmit_ctrl = 1;
3401#endif /* COAP_Q_BLOCK_SUPPORT */
3402 goto skip_handler;
3403 }
3404 }
3405
3406 if (observe) {
3407 observe_action =
3409 coap_opt_length(observe));
3410
3411 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3412 coap_subscription_t *subscription;
3413
3414 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3415 if (block.num != 0) {
3416 response->code = COAP_RESPONSE_CODE(400);
3417 goto skip_handler;
3418 }
3419#if COAP_Q_BLOCK_SUPPORT
3420 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3421 &block)) {
3422 if (block.num != 0) {
3423 response->code = COAP_RESPONSE_CODE(400);
3424 goto skip_handler;
3425 }
3426#endif /* COAP_Q_BLOCK_SUPPORT */
3427 }
3428 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3429 pdu);
3430 if (subscription) {
3431 uint8_t buf[4];
3432
3433 coap_touch_observer(context, session, &pdu->actual_token);
3435 coap_encode_var_safe(buf, sizeof(buf),
3436 resource->observe),
3437 buf);
3438 }
3439 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3440 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3441 } else {
3442 coap_log_info("observe: unexpected action %d\n", observe_action);
3443 }
3444 }
3445
3446 /* TODO for non-proxy requests */
3447 if (resource == context->proxy_uri_resource &&
3448 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3449 pdu->type == COAP_MESSAGE_CON) {
3450 /* Make the proxy response separate and fix response later */
3451 send_early_empty_ack = 1;
3452 }
3453 if (send_early_empty_ack) {
3454 coap_send_ack_lkd(session, pdu);
3455 if (pdu->mid == session->last_con_mid) {
3456 /* request has already been processed - do not process it again */
3457 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3458 pdu->mid);
3459 goto drop_it_no_debug;
3460 }
3461 session->last_con_mid = pdu->mid;
3462 }
3463#if COAP_WITH_OBSERVE_PERSIST
3464 /* If we are maintaining Observe persist */
3465 if (resource == context->unknown_resource) {
3466 context->unknown_pdu = pdu;
3467 context->unknown_session = session;
3468 } else
3469 context->unknown_pdu = NULL;
3470#endif /* COAP_WITH_OBSERVE_PERSIST */
3471
3472 /*
3473 * Call the request handler with everything set up
3474 */
3475 if (resource == &resource_uri_wellknown) {
3476 /* Leave context locked */
3477 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3478 (int)resource->uri_path->length, (int)resource->uri_path->length,
3479 resource->uri_path->s);
3480 h(resource, session, pdu, query, response);
3481 } else {
3482 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3483 (int)resource->uri_path->length, (int)resource->uri_path->length,
3484 resource->uri_path->s);
3486 h(resource, session, pdu, query, response),
3487 /* context is being freed off */
3488 goto finish);
3489 }
3490
3491 /* Check validity of response code */
3492 if (!coap_check_code_class(session, response)) {
3493 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
3494 COAP_RESPONSE_CLASS(response->code),
3495 response->code & 0x1f);
3496 goto drop_it_no_debug;
3497 }
3498
3499 /* Check if lg_xmit generated and update PDU code if so */
3500 coap_check_code_lg_xmit(session, pdu, response, resource, query);
3501
3502 if (free_lg_srcv) {
3503 /* Check to see if the server is doing a 4.01 + Echo response */
3504 if (response->code == COAP_RESPONSE_CODE(401) &&
3505 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3506 /* Need to keep lg_srcv around for client's response */
3507 } else {
3508 LL_DELETE(session->lg_srcv, free_lg_srcv);
3509 coap_block_delete_lg_srcv(session, free_lg_srcv);
3510 }
3511 }
3512 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
3513 /* Just in case, as there are more to go */
3514 response->code = COAP_RESPONSE_CODE(231);
3515 }
3516
3517skip_handler:
3518 if (send_early_empty_ack &&
3519 response->type == COAP_MESSAGE_ACK) {
3520 /* Response is now separate - convert to CON as needed */
3521 response->type = COAP_MESSAGE_CON;
3522 /* Check for empty ACK - need to drop as already sent */
3523 if (response->code == 0) {
3524 goto drop_it_no_debug;
3525 }
3526 }
3527 respond = no_response(pdu, response, session, resource);
3528 if (respond != RESPONSE_DROP) {
3529#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
3530 coap_mid_t mid = pdu->mid;
3531#endif
3532 if (COAP_RESPONSE_CLASS(response->code) != 2) {
3533 if (observe) {
3535 }
3536 }
3537 if (COAP_RESPONSE_CLASS(response->code) > 2) {
3538 if (observe)
3539 coap_delete_observer(resource, session, &pdu->actual_token);
3540 if (response->code != COAP_RESPONSE_CODE(413))
3542 }
3543
3544 /* If original request contained a token, and the registered
3545 * application handler made no changes to the response, then
3546 * this is an empty ACK with a token, which is a malformed
3547 * PDU */
3548 if ((response->type == COAP_MESSAGE_ACK)
3549 && (response->code == 0)) {
3550 /* Remove token from otherwise-empty acknowledgment PDU */
3551 response->actual_token.length = 0;
3552 response->e_token_length = 0;
3553 response->used_size = 0;
3554 response->data = NULL;
3555 }
3556
3557 if (!coap_is_mcast(&session->addr_info.local) ||
3558 (context->mcast_per_resource &&
3559 resource &&
3561 /* No delays to response */
3562#if COAP_Q_BLOCK_SUPPORT
3563 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
3564 !lg_xmit_ctrl && response->code == COAP_RESPONSE_CODE(205) &&
3565 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
3566 block.m) {
3567 if (coap_send_q_block2(session, resource, query, pdu->code, block,
3568 response,
3569 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
3570 coap_log_debug("cannot send response for mid=0x%x\n", mid);
3571 response = NULL;
3572 if (query)
3573 coap_delete_string(query);
3574 goto finish;
3575 }
3576#endif /* COAP_Q_BLOCK_SUPPORT */
3577 if (coap_send_internal(session, response) == COAP_INVALID_MID) {
3578 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
3579 }
3580 } else {
3581 /* Need to delay mcast response */
3582 coap_queue_t *node = coap_new_node();
3583 uint8_t r;
3584 coap_tick_t delay;
3585
3586 if (!node) {
3587 coap_log_debug("mcast delay: insufficient memory\n");
3588 goto drop_it_no_debug;
3589 }
3590 if (!coap_pdu_encode_header(response, session->proto)) {
3592 goto drop_it_no_debug;
3593 }
3594
3595 node->id = response->mid;
3596 node->pdu = response;
3597 node->is_mcast = 1;
3598 coap_prng_lkd(&r, sizeof(r));
3599 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
3600 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
3601 coap_session_str(session),
3602 response->mid,
3603 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
3604 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
3605 1000 / COAP_TICKS_PER_SECOND));
3606 node->timeout = (unsigned int)delay;
3607 /* Use this to delay transmission */
3608 coap_wait_ack(session->context, session, node);
3609 }
3610 } else {
3611 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
3612 coap_session_str(session),
3613 response->mid);
3614 coap_show_pdu(COAP_LOG_DEBUG, response);
3615drop_it_no_debug:
3616 coap_delete_pdu(response);
3617 }
3618 if (query)
3619 coap_delete_string(query);
3620#if COAP_Q_BLOCK_SUPPORT
3621 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
3622 if (COAP_PROTO_RELIABLE(session->proto)) {
3623 if (block.m) {
3624 /* All of the sequence not in yet */
3625 goto finish;
3626 }
3627 } else if (pdu->type == COAP_MESSAGE_NON) {
3628 /* More to go and not at a payload break */
3629 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
3630 goto finish;
3631 }
3632 }
3633 }
3634#endif /* COAP_Q_BLOCK_SUPPORT */
3635
3636#if COAP_Q_BLOCK_SUPPORT || COAP_THREAD_SAFE
3637finish:
3638#endif /* COAP_Q_BLOCK_SUPPORT || COAP_THREAD_SAFE */
3639 coap_delete_string(uri_path);
3640 return;
3641
3642fail_response:
3643 coap_delete_pdu(response);
3644 response =
3646 &opt_filter);
3647 if (response)
3648 goto skip_handler;
3649 coap_delete_string(uri_path);
3650}
3651#endif /* COAP_SERVER_SUPPORT */
3652
3653#if COAP_CLIENT_SUPPORT
3654static void
3655handle_response(coap_context_t *context, coap_session_t *session,
3656 coap_pdu_t *sent, coap_pdu_t *rcvd) {
3657
3658 /* Set in case there is a later call to coap_update_token() */
3659 rcvd->session = session;
3660
3661 /* In a lossy context, the ACK of a separate response may have
3662 * been lost, so we need to stop retransmitting requests with the
3663 * same token. Matching on token potentially containing ext length bytes.
3664 */
3665 if (rcvd->type != COAP_MESSAGE_ACK)
3666 coap_cancel_all_messages(context, session, &rcvd->actual_token);
3667
3668 /* Check for message duplication */
3669 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
3670 if (rcvd->type == COAP_MESSAGE_CON) {
3671 if (rcvd->mid == session->last_con_mid) {
3672 /* Duplicate response: send ACK/RST, but don't process */
3673 if (session->last_con_handler_res == COAP_RESPONSE_OK)
3674 coap_send_ack_lkd(session, rcvd);
3675 else
3676 coap_send_rst_lkd(session, rcvd);
3677 return;
3678 }
3679 session->last_con_mid = rcvd->mid;
3680 } else if (rcvd->type == COAP_MESSAGE_ACK) {
3681 if (rcvd->mid == session->last_ack_mid) {
3682 /* Duplicate response */
3683 return;
3684 }
3685 session->last_ack_mid = rcvd->mid;
3686 }
3687 }
3688 /* Check to see if checking out extended token support */
3689 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
3690 session->remote_test_mid == rcvd->mid) {
3691
3692 if (rcvd->actual_token.length != session->max_token_size ||
3693 rcvd->code == COAP_RESPONSE_CODE(400) ||
3694 rcvd->code == COAP_RESPONSE_CODE(503)) {
3695 coap_log_debug("Extended Token requested size support not available\n");
3697 } else {
3698 coap_log_debug("Extended Token support available\n");
3699 }
3701 session->doing_first = 0;
3702 return;
3703 }
3704#if COAP_Q_BLOCK_SUPPORT
3705 /* Check to see if checking out Q-Block support */
3706 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
3707 session->remote_test_mid == rcvd->mid) {
3708 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
3709 coap_log_debug("Q-Block support not available\n");
3710 set_block_mode_drop_q(session->block_mode);
3711 } else {
3712 coap_block_b_t qblock;
3713
3714 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
3715 coap_log_debug("Q-Block support available\n");
3716 set_block_mode_has_q(session->block_mode);
3717 } else {
3718 coap_log_debug("Q-Block support not available\n");
3719 set_block_mode_drop_q(session->block_mode);
3720 }
3721 }
3722 session->doing_first = 0;
3723 return;
3724 }
3725#endif /* COAP_Q_BLOCK_SUPPORT */
3726
3727 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3728 /* See if need to send next block to server */
3729 if (coap_handle_response_send_block(session, sent, rcvd)) {
3730 /* Next block transmitted, no need to inform app */
3731 coap_send_ack_lkd(session, rcvd);
3732 return;
3733 }
3734
3735 /* Need to see if needing to request next block */
3736 if (coap_handle_response_get_block(context, session, sent, rcvd,
3737 COAP_RECURSE_OK)) {
3738 /* Next block transmitted, ack sent no need to inform app */
3739 return;
3740 }
3741 }
3742 if (session->doing_first)
3743 session->doing_first = 0;
3744
3745 /* Call application-specific response handler when available. */
3746 if (context->response_handler) {
3747 coap_response_t ret;
3748
3749 coap_lock_callback_ret_release(ret, context,
3750 context->response_handler(session, sent, rcvd,
3751 rcvd->mid),
3752 /* context is being freed off */
3753 return);
3754 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
3755 coap_send_rst_lkd(session, rcvd);
3757 } else {
3758 coap_send_ack_lkd(session, rcvd);
3760 }
3761 } else {
3762 coap_send_ack_lkd(session, rcvd);
3764 }
3765}
3766#endif /* COAP_CLIENT_SUPPORT */
3767
3768#if !COAP_DISABLE_TCP
3769static void
3771 coap_pdu_t *pdu) {
3772 coap_opt_iterator_t opt_iter;
3773 coap_opt_t *option;
3774 int set_mtu = 0;
3775
3776 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
3777
3778 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
3779 if (session->csm_not_seen) {
3780 coap_tick_t now;
3781
3782 coap_ticks(&now);
3783 /* CSM timeout before CSM seen */
3784 coap_log_warn("***%s: CSM received after CSM timeout\n",
3785 coap_session_str(session));
3786 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
3787 coap_session_str(session),
3788 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
3789 }
3790 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
3792 }
3793 while ((option = coap_option_next(&opt_iter))) {
3796 coap_opt_length(option)));
3797 set_mtu = 1;
3798 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
3799 session->csm_block_supported = 1;
3800 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
3801 session->max_token_size =
3803 coap_opt_length(option));
3806 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
3809 }
3810 }
3811 if (set_mtu) {
3812 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
3813 session->csm_bert_rem_support = 1;
3814 else
3815 session->csm_bert_rem_support = 0;
3816 }
3817 if (session->state == COAP_SESSION_STATE_CSM)
3818 coap_session_connected(session);
3819 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
3821 if (context->ping_handler) {
3822 coap_lock_callback(context,
3823 context->ping_handler(session, pdu, pdu->mid));
3824 }
3825 if (pong) {
3827 coap_send_internal(session, pong);
3828 }
3829 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
3830 session->last_pong = session->last_rx_tx;
3831 if (context->pong_handler) {
3832 coap_lock_callback(context,
3833 context->pong_handler(session, pdu, pdu->mid));
3834 }
3835 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
3836 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
3838 }
3839}
3840#endif /* !COAP_DISABLE_TCP */
3841
3842static int
3844 if (COAP_PDU_IS_REQUEST(pdu) &&
3845 pdu->actual_token.length >
3846 (session->type == COAP_SESSION_TYPE_CLIENT ?
3847 session->max_token_size : session->context->max_token_size)) {
3848 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
3849 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
3850 coap_opt_filter_t opt_filter;
3851 coap_pdu_t *response;
3852
3853 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
3854 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
3855 &opt_filter);
3856 if (!response) {
3857 coap_log_warn("coap_dispatch: cannot create error response\n");
3858 } else {
3859 /*
3860 * Note - have to leave in oversize token as per
3861 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
3862 */
3863 if (coap_send_internal(session, response) == COAP_INVALID_MID)
3864 coap_log_warn("coap_dispatch: error sending response\n");
3865 }
3866 } else {
3867 /* Indicate no extended token support */
3868 coap_send_rst_lkd(session, pdu);
3869 }
3870 return 0;
3871 }
3872 return 1;
3873}
3874
3875void
3877 coap_pdu_t *pdu) {
3878 coap_queue_t *sent = NULL;
3879 coap_pdu_t *response;
3880 coap_opt_filter_t opt_filter;
3881 int is_ping_rst;
3882 int packet_is_bad = 0;
3883#if COAP_OSCORE_SUPPORT
3884 coap_opt_iterator_t opt_iter;
3885 coap_pdu_t *dec_pdu = NULL;
3886#endif /* COAP_OSCORE_SUPPORT */
3887 int is_ext_token_rst;
3888
3889 pdu->session = session;
3891
3892 /* Check validity of received code */
3893 if (!coap_check_code_class(session, pdu)) {
3894 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
3896 pdu->code & 0x1f);
3897 packet_is_bad = 1;
3898 if (pdu->type == COAP_MESSAGE_CON) {
3900 }
3901 /* find message id in sendqueue to stop retransmission */
3902 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3903 goto cleanup;
3904 }
3905
3906 coap_option_filter_clear(&opt_filter);
3907
3908#if COAP_OSCORE_SUPPORT
3909 if (!COAP_PDU_IS_SIGNALING(pdu) &&
3910 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3911 if (pdu->type == COAP_MESSAGE_NON) {
3912 coap_send_rst_lkd(session, pdu);
3913 goto cleanup;
3914 } else if (pdu->type == COAP_MESSAGE_CON) {
3915 if (COAP_PDU_IS_REQUEST(pdu)) {
3916 response =
3917 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
3918
3919 if (!response) {
3920 coap_log_warn("coap_dispatch: cannot create error response\n");
3921 } else {
3922 if (coap_send_internal(session, response) == COAP_INVALID_MID)
3923 coap_log_warn("coap_dispatch: error sending response\n");
3924 }
3925 } else {
3926 coap_send_rst_lkd(session, pdu);
3927 }
3928 }
3929 goto cleanup;
3930 }
3931
3932 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
3933 int decrypt = 1;
3934#if COAP_SERVER_SUPPORT
3935 coap_opt_t *opt;
3936 coap_resource_t *resource;
3937 coap_uri_t uri;
3938#endif /* COAP_SERVER_SUPPORT */
3939
3940 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
3941 decrypt = 0;
3942
3943#if COAP_SERVER_SUPPORT
3944 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
3945 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
3946 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
3947 != NULL) {
3948 /* Need to check whether this is a direct or proxy session */
3949 memset(&uri, 0, sizeof(uri));
3950 uri.host.length = coap_opt_length(opt);
3951 uri.host.s = coap_opt_value(opt);
3952 resource = context->proxy_uri_resource;
3953 if (uri.host.length && resource && resource->proxy_name_count &&
3954 resource->proxy_name_list) {
3955 size_t i;
3956 for (i = 0; i < resource->proxy_name_count; i++) {
3957 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3958 break;
3959 }
3960 }
3961 if (i == resource->proxy_name_count) {
3962 /* This server is not hosting the proxy connection endpoint */
3963 decrypt = 0;
3964 }
3965 }
3966 }
3967#endif /* COAP_SERVER_SUPPORT */
3968 if (decrypt) {
3969 /* find message id in sendqueue to stop retransmission and get sent */
3970 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3971 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
3972 if (session->recipient_ctx == NULL ||
3973 session->recipient_ctx->initial_state == 0) {
3974 coap_log_warn("OSCORE: PDU could not be decrypted\n");
3975 }
3977 return;
3978 } else {
3979 session->oscore_encryption = 1;
3980 pdu = dec_pdu;
3981 }
3982 coap_log_debug("Decrypted PDU\n");
3984 }
3985 }
3986#endif /* COAP_OSCORE_SUPPORT */
3987
3988 switch (pdu->type) {
3989 case COAP_MESSAGE_ACK:
3990 /* find message id in sendqueue to stop retransmission */
3991 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3992
3993 if (sent && session->con_active) {
3994 session->con_active--;
3995 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3996 /* Flush out any entries on session->delayqueue */
3997 coap_session_connected(session);
3998 }
3999 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4000 packet_is_bad = 1;
4001 goto cleanup;
4002 }
4003
4004#if COAP_SERVER_SUPPORT
4005 /* if sent code was >= 64 the message might have been a
4006 * notification. Then, we must flag the observer to be alive
4007 * by setting obs->fail_cnt = 0. */
4008 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4009 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4010 }
4011#endif /* COAP_SERVER_SUPPORT */
4012
4013 if (pdu->code == 0) {
4014#if COAP_Q_BLOCK_SUPPORT
4015 if (sent) {
4016 coap_block_b_t block;
4017
4018 if (sent->pdu->type == COAP_MESSAGE_CON &&
4019 COAP_PROTO_NOT_RELIABLE(session->proto) &&
4020 coap_get_block_b(session, sent->pdu,
4021 COAP_PDU_IS_REQUEST(sent->pdu) ?
4023 &block)) {
4024 if (block.m) {
4025#if COAP_CLIENT_SUPPORT
4026 if (COAP_PDU_IS_REQUEST(sent->pdu))
4027 coap_send_q_block1(session, block, sent->pdu,
4028 COAP_SEND_SKIP_PDU);
4029#endif /* COAP_CLIENT_SUPPORT */
4030 if (COAP_PDU_IS_RESPONSE(sent->pdu))
4031 coap_send_q_blocks(session, sent->pdu->lg_xmit, block,
4032 sent->pdu, COAP_SEND_SKIP_PDU);
4033 }
4034 }
4035 }
4036#endif /* COAP_Q_BLOCK_SUPPORT */
4037#if COAP_CLIENT_SUPPORT
4038 /*
4039 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4040 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4041 * response if the response was piggy-backed. Here, a separate response
4042 * detected and so the lg_crcv needs to be set up before the sent PDU
4043 * information is lost.
4044 *
4045 * lg_crcv was not set up if not a CoAP request or if DELETE.
4046 *
4047 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4048 * options.
4049 */
4050 if (sent &&
4051 !coap_check_send_need_lg_crcv(session, pdu) &&
4052 COAP_PDU_IS_REQUEST(sent->pdu)) {
4053 /*
4054 * lg_crcv was not set up in coap_send(). It could have been set up
4055 * the first separate response.
4056 * See if there already is a lg_crcv set up.
4057 */
4058 coap_lg_crcv_t *lg_crcv;
4059 uint64_t token_match =
4061 sent->pdu->actual_token.length));
4062
4063 LL_FOREACH(session->lg_crcv, lg_crcv) {
4064 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4065 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4066 break;
4067 }
4068 }
4069 if (!lg_crcv) {
4070 /*
4071 * Need to set up a lg_crcv as it was not set up in coap_send()
4072 * to save time, but server has not sent back a piggy-back response.
4073 */
4074 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4075 if (lg_crcv) {
4076 LL_PREPEND(session->lg_crcv, lg_crcv);
4077 }
4078 }
4079 }
4080#endif /* COAP_CLIENT_SUPPORT */
4081 /* an empty ACK needs no further handling */
4082 goto cleanup;
4083 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4084 /* This is not legitimate - Request using ACK - ignore */
4085 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4087 pdu->code & 0x1f);
4088 packet_is_bad = 1;
4089 goto cleanup;
4090 }
4091
4092 break;
4093
4094 case COAP_MESSAGE_RST:
4095 /* We have sent something the receiver disliked, so we remove
4096 * not only the message id but also the subscriptions we might
4097 * have. */
4098 is_ping_rst = 0;
4099 if (pdu->mid == session->last_ping_mid &&
4100 context->ping_timeout && session->last_ping > 0)
4101 is_ping_rst = 1;
4102
4103#if COAP_Q_BLOCK_SUPPORT
4104 /* Check to see if checking out Q-Block support */
4105 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4106 session->remote_test_mid == pdu->mid) {
4107 coap_log_debug("Q-Block support not available\n");
4108 set_block_mode_drop_q(session->block_mode);
4109 }
4110#endif /* COAP_Q_BLOCK_SUPPORT */
4111
4112 /* Check to see if checking out extended token support */
4113 is_ext_token_rst = 0;
4114 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4115 session->remote_test_mid == pdu->mid) {
4116 coap_log_debug("Extended Token support not available\n");
4119 session->doing_first = 0;
4120 is_ext_token_rst = 1;
4121 }
4122
4123 if (!is_ping_rst && !is_ext_token_rst)
4124 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4125
4126 if (session->con_active) {
4127 session->con_active--;
4128 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4129 /* Flush out any entries on session->delayqueue */
4130 coap_session_connected(session);
4131 }
4132
4133 /* find message id in sendqueue to stop retransmission */
4134 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4135
4136 if (sent) {
4137 coap_cancel(context, sent);
4138
4139 if (!is_ping_rst && !is_ext_token_rst) {
4140 if (sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler) {
4141 coap_check_update_token(sent->session, sent->pdu);
4142 coap_lock_callback(context,
4143 context->nack_handler(sent->session, sent->pdu,
4144 COAP_NACK_RST, sent->id));
4145 }
4146 } else if (is_ping_rst) {
4147 if (context->pong_handler) {
4148 coap_lock_callback(context,
4149 context->pong_handler(session, pdu, pdu->mid));
4150 }
4151 session->last_pong = session->last_rx_tx;
4153 }
4154 } else {
4155#if COAP_SERVER_SUPPORT
4156 /* Need to check is there is a subscription active and delete it */
4157 RESOURCES_ITER(context->resources, r) {
4158 coap_subscription_t *obs, *tmp;
4159 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4160 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4161 /* Need to do this now as session may get de-referenced */
4163 coap_delete_observer(r, session, &obs->pdu->actual_token);
4164 if (context->nack_handler) {
4165 coap_lock_callback(context,
4166 context->nack_handler(session, NULL,
4167 COAP_NACK_RST, pdu->mid));
4168 }
4169 coap_session_release_lkd(session);
4170 goto cleanup;
4171 }
4172 }
4173 }
4174#endif /* COAP_SERVER_SUPPORT */
4175 if (context->nack_handler) {
4176 coap_lock_callback(context,
4177 context->nack_handler(session, NULL, COAP_NACK_RST, pdu->mid));
4178 }
4179 }
4180 goto cleanup;
4181
4182 case COAP_MESSAGE_NON:
4183 /* find transaction in sendqueue in case large response */
4184 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4185 /* check for unknown critical options */
4186 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4187 packet_is_bad = 1;
4188 coap_send_rst_lkd(session, pdu);
4189 goto cleanup;
4190 }
4191 if (!check_token_size(session, pdu)) {
4192 goto cleanup;
4193 }
4194 break;
4195
4196 case COAP_MESSAGE_CON: /* check for unknown critical options */
4197 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4198 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4199 packet_is_bad = 1;
4200 if (COAP_PDU_IS_REQUEST(pdu)) {
4201 response =
4202 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4203
4204 if (!response) {
4205 coap_log_warn("coap_dispatch: cannot create error response\n");
4206 } else {
4207 if (coap_send_internal(session, response) == COAP_INVALID_MID)
4208 coap_log_warn("coap_dispatch: error sending response\n");
4209 }
4210 } else {
4211 coap_send_rst_lkd(session, pdu);
4212 }
4213 goto cleanup;
4214 }
4215 if (!check_token_size(session, pdu)) {
4216 goto cleanup;
4217 }
4218 break;
4219 default:
4220 break;
4221 }
4222
4223 /* Pass message to upper layer if a specific handler was
4224 * registered for a request that should be handled locally. */
4225#if !COAP_DISABLE_TCP
4226 if (COAP_PDU_IS_SIGNALING(pdu))
4227 handle_signaling(context, session, pdu);
4228 else
4229#endif /* !COAP_DISABLE_TCP */
4230#if COAP_SERVER_SUPPORT
4231 if (COAP_PDU_IS_REQUEST(pdu))
4232 handle_request(context, session, pdu);
4233 else
4234#endif /* COAP_SERVER_SUPPORT */
4235#if COAP_CLIENT_SUPPORT
4236 if (COAP_PDU_IS_RESPONSE(pdu))
4237 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4238 else
4239#endif /* COAP_CLIENT_SUPPORT */
4240 {
4241 if (COAP_PDU_IS_EMPTY(pdu)) {
4242 if (context->ping_handler) {
4243 coap_lock_callback(context,
4244 context->ping_handler(session, pdu, pdu->mid));
4245 }
4246 } else {
4247 packet_is_bad = 1;
4248 }
4249 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4251 pdu->code & 0x1f);
4252
4253 if (!coap_is_mcast(&session->addr_info.local)) {
4254 if (COAP_PDU_IS_EMPTY(pdu)) {
4255 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4256 coap_tick_t now;
4257 coap_ticks(&now);
4258 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4260 session->last_tx_rst = now;
4261 }
4262 }
4263 } else {
4264 if (pdu->type == COAP_MESSAGE_CON)
4266 }
4267 }
4268 }
4269
4270cleanup:
4271 if (packet_is_bad) {
4272 if (sent) {
4273 if (context->nack_handler) {
4274 coap_check_update_token(session, sent->pdu);
4275 coap_lock_callback(context,
4276 context->nack_handler(session, sent->pdu,
4277 COAP_NACK_BAD_RESPONSE, sent->id));
4278 }
4279 } else {
4281 }
4282 }
4284#if COAP_OSCORE_SUPPORT
4285 coap_delete_pdu(dec_pdu);
4286#endif /* COAP_OSCORE_SUPPORT */
4287}
4288
4289#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4290static const char *
4292 switch (event) {
4294 return "COAP_EVENT_DTLS_CLOSED";
4296 return "COAP_EVENT_DTLS_CONNECTED";
4298 return "COAP_EVENT_DTLS_RENEGOTIATE";
4300 return "COAP_EVENT_DTLS_ERROR";
4302 return "COAP_EVENT_TCP_CONNECTED";
4304 return "COAP_EVENT_TCP_CLOSED";
4306 return "COAP_EVENT_TCP_FAILED";
4308 return "COAP_EVENT_SESSION_CONNECTED";
4310 return "COAP_EVENT_SESSION_CLOSED";
4312 return "COAP_EVENT_SESSION_FAILED";
4314 return "COAP_EVENT_PARTIAL_BLOCK";
4316 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4318 return "COAP_EVENT_SERVER_SESSION_NEW";
4320 return "COAP_EVENT_SERVER_SESSION_DEL";
4322 return "COAP_EVENT_BAD_PACKET";
4324 return "COAP_EVENT_MSG_RETRANSMITTED";
4326 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4328 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4330 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4332 return "COAP_EVENT_OSCORE_NO_SECURITY";
4334 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4336 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4338 return "COAP_EVENT_WS_PACKET_SIZE";
4340 return "COAP_EVENT_WS_CONNECTED";
4342 return "COAP_EVENT_WS_CLOSED";
4344 return "COAP_EVENT_KEEPALIVE_FAILURE";
4345 default:
4346 return "???";
4347 }
4348}
4349#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4350
4351COAP_API int
4353 coap_session_t *session) {
4354 int ret;
4355
4356 coap_lock_lock(context, return 0);
4357 ret = coap_handle_event_lkd(context, event, session);
4358 coap_lock_unlock(context);
4359 return ret;
4360}
4361
4362int
4364 coap_session_t *session) {
4365 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
4366
4367 if (context->handle_event) {
4368 int ret;
4369
4370 coap_lock_callback_ret(ret, context, context->handle_event(session, event));
4371#if COAP_PROXY_SUPPORT
4372 if (event == COAP_EVENT_SERVER_SESSION_DEL)
4374#endif /* COAP_PROXY_SUPPORT */
4375 return ret;
4376 }
4377 return 0;
4378}
4379
4380COAP_API int
4382 int ret;
4383
4384 coap_lock_lock(context, return 0);
4385 ret = coap_can_exit_lkd(context);
4386 coap_lock_unlock(context);
4387 return ret;
4388}
4389
4390int
4392 coap_session_t *s, *rtmp;
4393 if (!context)
4394 return 1;
4395 coap_lock_check_locked(context);
4396 if (context->sendqueue)
4397 return 0;
4398#if COAP_SERVER_SUPPORT
4399 coap_endpoint_t *ep;
4400
4401 LL_FOREACH(context->endpoint, ep) {
4402 SESSIONS_ITER(ep->sessions, s, rtmp) {
4403 if (s->delayqueue)
4404 return 0;
4405 if (s->lg_xmit)
4406 return 0;
4407 }
4408 }
4409#endif /* COAP_SERVER_SUPPORT */
4410#if COAP_CLIENT_SUPPORT
4411 SESSIONS_ITER(context->sessions, s, rtmp) {
4412 if (s->delayqueue)
4413 return 0;
4414 if (s->lg_xmit)
4415 return 0;
4416 }
4417#endif /* COAP_CLIENT_SUPPORT */
4418 return 1;
4419}
4420#if COAP_SERVER_SUPPORT
4421#if COAP_ASYNC_SUPPORT
4423coap_check_async(coap_context_t *context, coap_tick_t now) {
4424 coap_tick_t next_due = 0;
4425 coap_async_t *async, *tmp;
4426
4427 LL_FOREACH_SAFE(context->async_state, async, tmp) {
4428 if (async->delay != 0 && async->delay <= now) {
4429 /* Send off the request to the application */
4430 handle_request(context, async->session, async->pdu);
4431
4432 /* Remove this async entry as it has now fired */
4433 coap_free_async_lkd(async->session, async);
4434 } else {
4435 if (next_due == 0 || next_due > async->delay - now)
4436 next_due = async->delay - now;
4437 }
4438 }
4439 return next_due;
4440}
4441#endif /* COAP_ASYNC_SUPPORT */
4442#endif /* COAP_SERVER_SUPPORT */
4443
4445
4446#if COAP_THREAD_SAFE
4447/*
4448 * Global lock for multi-thread support
4449 */
4450coap_lock_t global_lock;
4451#endif /* COAP_THREAD_SAFE */
4452
4453void
4455 coap_tick_t now;
4456#ifndef WITH_CONTIKI
4457 uint64_t us;
4458#endif /* !WITH_CONTIKI */
4459
4460 if (coap_started)
4461 return;
4462 coap_started = 1;
4463
4464#if COAP_THREAD_SAFE
4466#endif /* COAP_THREAD_SAFE */
4467
4468#if defined(HAVE_WINSOCK2_H)
4469 WORD wVersionRequested = MAKEWORD(2, 2);
4470 WSADATA wsaData;
4471 WSAStartup(wVersionRequested, &wsaData);
4472#endif
4474 coap_ticks(&now);
4475#ifndef WITH_CONTIKI
4476 us = coap_ticks_to_rt_us(now);
4477 /* Be accurate to the nearest (approx) us */
4478 coap_prng_init_lkd((unsigned int)us);
4479#else /* WITH_CONTIKI */
4480 coap_start_io_process();
4481#endif /* WITH_CONTIKI */
4484#ifdef WITH_LWIP
4485 coap_io_lwip_init();
4486#endif /* WITH_LWIP */
4487#if COAP_SERVER_SUPPORT
4488 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
4489 (const uint8_t *)".well-known/core"
4490 };
4491 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
4492 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
4493 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
4494 resource_uri_wellknown.uri_path = &well_known;
4495#endif /* COAP_SERVER_SUPPORT */
4496}
4497
4498void
4500 if (!coap_started)
4501 return;
4502 coap_started = 0;
4503#if defined(HAVE_WINSOCK2_H)
4504 WSACleanup();
4505#elif defined(WITH_CONTIKI)
4506 coap_stop_io_process();
4507#endif
4508#ifdef WITH_LWIP
4509 coap_io_lwip_cleanup();
4510#endif /* WITH_LWIP */
4512
4514}
4515
4516void
4518 coap_response_handler_t handler) {
4519#if COAP_CLIENT_SUPPORT
4520 context->response_handler = handler;
4521#else /* ! COAP_CLIENT_SUPPORT */
4522 (void)context;
4523 (void)handler;
4524#endif /* COAP_CLIENT_SUPPORT */
4525}
4526
4527void
4529 coap_nack_handler_t handler) {
4530 context->nack_handler = handler;
4531}
4532
4533void
4535 coap_ping_handler_t handler) {
4536 context->ping_handler = handler;
4537}
4538
4539void
4541 coap_pong_handler_t handler) {
4542 context->pong_handler = handler;
4543}
4544
4545COAP_API void
4547 coap_lock_lock(ctx, return);
4548 coap_register_option_lkd(ctx, type);
4549 coap_lock_unlock(ctx);
4550}
4551
4552void
4555}
4556
4557#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
4558#if COAP_SERVER_SUPPORT
4559COAP_API int
4560coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
4561 const char *ifname) {
4562 int ret;
4563
4564 coap_lock_lock(ctx, return -1);
4565 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
4566 coap_lock_unlock(ctx);
4567 return ret;
4568}
4569
4570int
4571coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
4572 const char *ifname) {
4573#if COAP_IPV4_SUPPORT
4574 struct ip_mreq mreq4;
4575#endif /* COAP_IPV4_SUPPORT */
4576#if COAP_IPV6_SUPPORT
4577 struct ipv6_mreq mreq6;
4578#endif /* COAP_IPV6_SUPPORT */
4579 struct addrinfo *resmulti = NULL, hints, *ainfo;
4580 int result = -1;
4581 coap_endpoint_t *endpoint;
4582 int mgroup_setup = 0;
4583
4584 /* Need to have at least one endpoint! */
4585 assert(ctx->endpoint);
4586 if (!ctx->endpoint)
4587 return -1;
4588
4589 /* Default is let the kernel choose */
4590#if COAP_IPV6_SUPPORT
4591 mreq6.ipv6mr_interface = 0;
4592#endif /* COAP_IPV6_SUPPORT */
4593#if COAP_IPV4_SUPPORT
4594 mreq4.imr_interface.s_addr = INADDR_ANY;
4595#endif /* COAP_IPV4_SUPPORT */
4596
4597 memset(&hints, 0, sizeof(hints));
4598 hints.ai_socktype = SOCK_DGRAM;
4599
4600 /* resolve the multicast group address */
4601 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
4602
4603 if (result != 0) {
4604 coap_log_err("coap_join_mcast_group_intf: %s: "
4605 "Cannot resolve multicast address: %s\n",
4606 group_name, gai_strerror(result));
4607 goto finish;
4608 }
4609
4610 /* Need to do a windows equivalent at some point */
4611#ifndef _WIN32
4612 if (ifname) {
4613 /* interface specified - check if we have correct IPv4/IPv6 information */
4614 int done_ip4 = 0;
4615 int done_ip6 = 0;
4616#if defined(ESPIDF_VERSION)
4617 struct netif *netif;
4618#else /* !ESPIDF_VERSION */
4619#if COAP_IPV4_SUPPORT
4620 int ip4fd;
4621#endif /* COAP_IPV4_SUPPORT */
4622 struct ifreq ifr;
4623#endif /* !ESPIDF_VERSION */
4624
4625 /* See which mcast address family types are being asked for */
4626 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
4627 ainfo = ainfo->ai_next) {
4628 switch (ainfo->ai_family) {
4629#if COAP_IPV6_SUPPORT
4630 case AF_INET6:
4631 if (done_ip6)
4632 break;
4633 done_ip6 = 1;
4634#if defined(ESPIDF_VERSION)
4635 netif = netif_find(ifname);
4636 if (netif)
4637 mreq6.ipv6mr_interface = netif_get_index(netif);
4638 else
4639 coap_log_err("coap_join_mcast_group_intf: %s: "
4640 "Cannot get IPv4 address: %s\n",
4641 ifname, coap_socket_strerror());
4642#else /* !ESPIDF_VERSION */
4643 memset(&ifr, 0, sizeof(ifr));
4644 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
4645 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
4646
4647#ifdef HAVE_IF_NAMETOINDEX
4648 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
4649 if (mreq6.ipv6mr_interface == 0) {
4650 coap_log_warn("coap_join_mcast_group_intf: "
4651 "cannot get interface index for '%s'\n",
4652 ifname);
4653 }
4654#elif defined(__QNXNTO__)
4655#else /* !HAVE_IF_NAMETOINDEX */
4656 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
4657 if (result != 0) {
4658 coap_log_warn("coap_join_mcast_group_intf: "
4659 "cannot get interface index for '%s': %s\n",
4660 ifname, coap_socket_strerror());
4661 } else {
4662 /* Capture the IPv6 if_index for later */
4663 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
4664 }
4665#endif /* !HAVE_IF_NAMETOINDEX */
4666#endif /* !ESPIDF_VERSION */
4667#endif /* COAP_IPV6_SUPPORT */
4668 break;
4669#if COAP_IPV4_SUPPORT
4670 case AF_INET:
4671 if (done_ip4)
4672 break;
4673 done_ip4 = 1;
4674#if defined(ESPIDF_VERSION)
4675 netif = netif_find(ifname);
4676 if (netif)
4677 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
4678 else
4679 coap_log_err("coap_join_mcast_group_intf: %s: "
4680 "Cannot get IPv4 address: %s\n",
4681 ifname, coap_socket_strerror());
4682#else /* !ESPIDF_VERSION */
4683 /*
4684 * Need an AF_INET socket to do this unfortunately to stop
4685 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
4686 */
4687 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
4688 if (ip4fd == -1) {
4689 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
4690 ifname, coap_socket_strerror());
4691 continue;
4692 }
4693 memset(&ifr, 0, sizeof(ifr));
4694 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
4695 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
4696 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
4697 if (result != 0) {
4698 coap_log_err("coap_join_mcast_group_intf: %s: "
4699 "Cannot get IPv4 address: %s\n",
4700 ifname, coap_socket_strerror());
4701 } else {
4702 /* Capture the IPv4 address for later */
4703 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
4704 }
4705 close(ip4fd);
4706#endif /* !ESPIDF_VERSION */
4707 break;
4708#endif /* COAP_IPV4_SUPPORT */
4709 default:
4710 break;
4711 }
4712 }
4713 }
4714#endif /* ! _WIN32 */
4715
4716 /* Add in mcast address(es) to appropriate interface */
4717 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
4718 LL_FOREACH(ctx->endpoint, endpoint) {
4719 /* Only UDP currently supported */
4720 if (endpoint->proto == COAP_PROTO_UDP) {
4721 coap_address_t gaddr;
4722
4723 coap_address_init(&gaddr);
4724#if COAP_IPV6_SUPPORT
4725 if (ainfo->ai_family == AF_INET6) {
4726 if (!ifname) {
4727 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
4728 /*
4729 * Do it on the ifindex that the server is listening on
4730 * (sin6_scope_id could still be 0)
4731 */
4732 mreq6.ipv6mr_interface =
4733 endpoint->bind_addr.addr.sin6.sin6_scope_id;
4734 } else {
4735 mreq6.ipv6mr_interface = 0;
4736 }
4737 }
4738 gaddr.addr.sin6.sin6_family = AF_INET6;
4739 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
4740 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
4741 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
4742 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
4743 (char *)&mreq6, sizeof(mreq6));
4744 }
4745#endif /* COAP_IPV6_SUPPORT */
4746#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
4747 else
4748#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
4749#if COAP_IPV4_SUPPORT
4750 if (ainfo->ai_family == AF_INET) {
4751 if (!ifname) {
4752 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
4753 /*
4754 * Do it on the interface that the server is listening on
4755 * (sin_addr could still be INADDR_ANY)
4756 */
4757 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
4758 } else {
4759 mreq4.imr_interface.s_addr = INADDR_ANY;
4760 }
4761 }
4762 gaddr.addr.sin.sin_family = AF_INET;
4763 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
4764 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
4765 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
4766 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4767 (char *)&mreq4, sizeof(mreq4));
4768 }
4769#endif /* COAP_IPV4_SUPPORT */
4770 else {
4771 continue;
4772 }
4773
4774 if (result == COAP_SOCKET_ERROR) {
4775 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
4776 group_name, coap_socket_strerror());
4777 } else {
4778 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
4779
4780 addr_str[sizeof(addr_str)-1] = '\000';
4781 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
4782 sizeof(addr_str) - 1)) {
4783 if (ifname)
4784 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
4785 ifname);
4786 else
4787 coap_log_debug("added mcast group %s\n", addr_str);
4788 }
4789 mgroup_setup = 1;
4790 }
4791 }
4792 }
4793 }
4794 if (!mgroup_setup) {
4795 result = -1;
4796 }
4797
4798finish:
4799 freeaddrinfo(resmulti);
4800
4801 return result;
4802}
4803
4804void
4806 context->mcast_per_resource = 1;
4807}
4808
4809#endif /* ! COAP_SERVER_SUPPORT */
4810
4811#if COAP_CLIENT_SUPPORT
4812int
4813coap_mcast_set_hops(coap_session_t *session, size_t hops) {
4814 if (session && coap_is_mcast(&session->addr_info.remote)) {
4815 switch (session->addr_info.remote.addr.sa.sa_family) {
4816#if COAP_IPV4_SUPPORT
4817 case AF_INET:
4818 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
4819 (const char *)&hops, sizeof(hops)) < 0) {
4820 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
4821 hops, coap_socket_strerror());
4822 return 0;
4823 }
4824 return 1;
4825#endif /* COAP_IPV4_SUPPORT */
4826#if COAP_IPV6_SUPPORT
4827 case AF_INET6:
4828 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
4829 (const char *)&hops, sizeof(hops)) < 0) {
4830 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
4831 hops, coap_socket_strerror());
4832 return 0;
4833 }
4834 return 1;
4835#endif /* COAP_IPV6_SUPPORT */
4836 default:
4837 break;
4838 }
4839 }
4840 return 0;
4841}
4842#endif /* COAP_CLIENT_SUPPORT */
4843
4844#else /* defined WITH_CONTIKI || defined WITH_LWIP */
4845COAP_API int
4847 const char *group_name COAP_UNUSED,
4848 const char *ifname COAP_UNUSED) {
4849 return -1;
4850}
4851
4852int
4854 size_t hops COAP_UNUSED) {
4855 return 0;
4856}
4857
4858void
4860}
4861#endif /* defined WITH_CONTIKI || defined WITH_LWIP */
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)
void coap_debug_reset(void)
Reset all the defined logging parameters.
#define INET6_ADDRSTRLEN
Definition coap_debug.c:226
#define COAP_Q_BLOCK_SUPPORT
#define COAP_OSCORE_SUPPORT
struct coap_async_t coap_async_t
Async Entry information.
#define PRIu32
const char * coap_socket_strerror(void)
Definition coap_io.c:1899
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:1007
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:494
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:29
#define COAP_SOCKET_ERROR
Definition coap_io.h:49
coap_nack_reason_t
Definition coap_io.h:62
@ COAP_NACK_NOT_DELIVERABLE
Definition coap_io.h:64
@ COAP_NACK_TOO_MANY_RETRIES
Definition coap_io.h:63
@ COAP_NACK_ICMP_ISSUE
Definition coap_io.h:67
@ COAP_NACK_RST
Definition coap_io.h:65
@ COAP_NACK_BAD_RESPONSE
Definition coap_io.h:68
#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:669
void coap_memory_init(void)
Initializes libcoap's memory management.
@ COAP_NODE
Definition coap_mem.h:43
@ COAP_CONTEXT
Definition coap_mem.h:44
@ COAP_STRING
Definition coap_mem.h:39
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 FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition coap_net.c:80
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition coap_net.c:1014
#define MAX_BITS
The maximum number of bits for fixed point integers that are used for retransmission time calculation...
Definition coap_net.c:86
void coap_cleanup(void)
Definition coap_net.c:4499
#define ACK_TIMEOUT
creates a Qx.FRAC_BITS from session's 'ack_timeout'
Definition coap_net.c:101
static const char * coap_event_name(coap_event_t event)
Definition coap_net.c:4291
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:2871
int coap_started
Definition coap_net.c:4444
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2013
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2054
COAP_STATIC_INLINE void coap_free_node(coap_queue_t *node)
Definition coap_net.c:111
#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:3770
#define min(a, b)
Definition coap_net.c:73
void coap_startup(void)
Definition coap_net.c:4454
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:3843
static unsigned int s_csm_timeout
Definition coap_net.c:503
COAP_STATIC_INLINE coap_queue_t * coap_malloc_node(void)
Definition coap_net.c:106
#define FP1
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition coap_net.c:97
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:108
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:238
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:116
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:181
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:176
uint16_t coap_option_num_t
Definition coap_option.h:20
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
Definition coap_option.h:26
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define SESSIONS_ITER(e, el, rtmp)
void coap_proxy_cleanup(coap_context_t *context)
Close down proxy tracking, releasing any memory used.
void coap_proxy_remove_association(coap_session_t *session, int send_failure)
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:2383
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:971
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:1095
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:1066
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:2318
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1590
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:1251
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:1356
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:986
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:2372
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:2311
int coap_add_data_large_response_lkd(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_string_t *query, uint16_t media_type, int maxage, uint64_t etag, size_t length, const uint8_t *data, coap_release_large_data_t release_func, void *app_ptr)
Associates given data with the response pdu that is passed as fourth parameter.
void coap_block_delete_lg_srcv(coap_session_t *session, coap_lg_srcv_t *lg_srcv)
void coap_block_delete_lg_crcv(coap_session_t *session, coap_lg_crcv_t *lg_crcv)
int coap_handle_response_get_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd, coap_recurse_t recursive)
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...
int coap_handle_response_send_block(coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd)
void coap_check_update_token(coap_session_t *session, coap_pdu_t *pdu)
The function checks if the token needs to be updated before PDU is presented to the application (only...
int coap_handle_request_put_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *uri_path, coap_opt_t *observe, int *added_block, coap_lg_srcv_t **free_lg_srcv)
#define STATE_TOKEN_BASE(t)
coap_lg_crcv_t * coap_block_new_lg_crcv(coap_session_t *session, coap_pdu_t *pdu, coap_lg_xmit_t *lg_xmit)
int coap_handle_request_send_block(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *query)
@ 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:89
#define COAP_BLOCK_TRY_Q_BLOCK
Definition coap_block.h:63
#define COAP_BLOCK_SINGLE_BODY
Definition coap_block.h:62
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:54
#define COAP_BLOCK_NO_PREEMPTIVE_RTAG
Definition coap_block.h:65
#define COAP_BLOCK_USE_LIBCOAP
Definition coap_block.h:61
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:155
void coap_clock_init(void)
Initializes the internal clock.
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:143
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:158
uint64_t coap_ticks_to_rt_us(coap_tick_t t)
Helper function that converts coap ticks to POSIX wallclock time in us.
void coap_prng_init_lkd(unsigned int seed)
Seeds the default random number generation function with the given seed.
Definition coap_prng.c:166
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:178
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
coap_print_status_t coap_print_wellknown_lkd(coap_context_t *context, unsigned char *buf, size_t *buflen, size_t offset, const coap_string_t *query_filter)
Prints the names of all known resources for context to buf.
coap_resource_t * coap_get_resource_from_uri_path_lkd(coap_context_t *context, coap_str_const_t *uri_path)
Returns the resource identified by the unique string uri_path.
#define RESOURCES_ITER(r, tmp)
#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_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...
void coap_register_option_lkd(coap_context_t *ctx, uint16_t type)
Registers the option type type with the given context object ctx.
Definition coap_net.c:4553
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:4363
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:130
int coap_delete_node_lkd(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:227
void coap_delete_all(coap_queue_t *queue)
Removes all items from given queue and frees the allocated storage.
Definition coap_net.c:247
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.
int coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id, coap_queue_t **node)
This function removes the element with given id from the list given list.
Definition coap_net.c:2533
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition coap_net.c:270
COAP_API int coap_delete_node(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:204
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:1226
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.
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:278
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:3876
coap_mid_t coap_send_internal(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1679
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:167
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:1123
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:755
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:4391
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:1910
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:1294
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:448
int coap_option_check_critical(coap_session_t *session, coap_pdu_t *pdu, coap_opt_filter_t *unknown)
Verifies that pdu contains no unknown critical options.
Definition coap_net.c:846
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1149
coap_queue_t * coap_new_node(void)
Creates a new node suitable for adding to the CoAP sendqueue.
Definition coap_net.c:256
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:2578
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:2488
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:2621
void coap_context_set_session_timeout(coap_context_t *context, unsigned int session_timeout)
Set the session timeout value.
Definition coap_net.c:546
unsigned int coap_context_get_max_handshake_sessions(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:499
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:100
unsigned int coap_context_get_max_idle_sessions(const coap_context_t *context)
Get the maximum idle sessions count.
Definition coap_net.c:488
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:642
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:1346
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:64
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:1053
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:534
void coap_context_set_csm_timeout(coap_context_t *context, unsigned int csm_timeout)
Set the CSM timeout value.
Definition coap_net.c:506
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:4517
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:2654
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:493
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:557
int coap_mcast_set_hops(coap_session_t *session, size_t hops)
Function interface for defining the hop count (ttl) for sending multicast traffic.
void coap_context_set_app_data(coap_context_t *context, void *app_data)
Stores data with the given context.
Definition coap_net.c:630
coap_response_t
Definition coap_net.h:48
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:89
void coap_ticks(coap_tick_t *)
Returns the current value of an internal tick counter.
COAP_API void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition coap_net.c:746
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:77
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:636
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:436
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:541
unsigned int coap_context_get_session_timeout(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:552
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 void coap_register_option(coap_context_t *ctx, uint16_t type)
Registers the option type type with the given context object ctx.
Definition coap_net.c:4546
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:976
unsigned int coap_context_get_csm_timeout_ms(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:529
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:4534
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.
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:463
void * coap_get_app_data(const coap_context_t *ctx)
Definition coap_net.c:740
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:482
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:1084
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:961
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds)
Set the context keepalive timer for sessions.
Definition coap_net.c:458
void coap_set_app_data(coap_context_t *ctx, void *app_data)
Definition coap_net.c:734
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:4381
unsigned int coap_context_get_csm_timeout(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:513
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:4540
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:474
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:4352
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:4528
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:519
@ COAP_RESPONSE_FAIL
Response not liked - send CoAP RST packet.
Definition coap_net.h:49
@ COAP_RESPONSE_OK
Response is fine.
Definition coap_net.h:50
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:149
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_hello(coap_session_t *coap_session, const uint8_t *data, size_t data_len)
Handling client HELLO messages from a new candiate peer.
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.
int coap_dtls_context_set_spsk(coap_context_t *coap_context, coap_dtls_spsk_t *setup_data)
Set the DTLS context's default server PSK information.
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:161
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:307
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:46
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:67
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:77
coap_event_t
Scalar type to represent different events, e.g.
Definition coap_event.h:34
@ COAP_EVENT_OSCORE_DECODE_ERROR
Triggered when there is an OSCORE decode of OSCORE option failure.
Definition coap_event.h:118
@ COAP_EVENT_SESSION_CONNECTED
Triggered when TCP layer completes exchange of CSM information.
Definition coap_event.h:61
@ COAP_EVENT_OSCORE_INTERNAL_ERROR
Triggered when there is an OSCORE internal error i.e malloc failed.
Definition coap_event.h:116
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition coap_event.h:39
@ COAP_EVENT_TCP_FAILED
Triggered when TCP layer fails for some reason.
Definition coap_event.h:55
@ COAP_EVENT_WS_CONNECTED
Triggered when the WebSockets layer is up.
Definition coap_event.h:125
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:41
@ COAP_EVENT_SESSION_FAILED
Triggered when TCP layer fails following exchange of CSM information.
Definition coap_event.h:65
@ COAP_EVENT_PARTIAL_BLOCK
Triggered when not all of a large body has been received.
Definition coap_event.h:71
@ COAP_EVENT_XMIT_BLOCK_FAIL
Triggered when not all of a large body has been transmitted.
Definition coap_event.h:73
@ 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:85
@ COAP_EVENT_OSCORE_NOT_ENABLED
Triggered when trying to use OSCORE to decrypt, but it is not enabled.
Definition coap_event.h:110
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:127
@ COAP_EVENT_SESSION_CLOSED
Triggered when TCP layer closes following exchange of CSM information.
Definition coap_event.h:63
@ 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:94
@ COAP_EVENT_OSCORE_NO_SECURITY
Triggered when there is no OSCORE security definition found.
Definition coap_event.h:114
@ COAP_EVENT_DTLS_RENEGOTIATE
Triggered when (D)TLS session renegotiated.
Definition coap_event.h:43
@ COAP_EVENT_BAD_PACKET
Triggered when badly formatted packet received.
Definition coap_event.h:100
@ COAP_EVENT_MSG_RETRANSMITTED
Triggered when a message is retransmitted.
Definition coap_event.h:102
@ COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD
Triggered when there is no OSCORE encrypted payload provided.
Definition coap_event.h:112
@ COAP_EVENT_TCP_CLOSED
Triggered when TCP layer is closed.
Definition coap_event.h:53
@ COAP_EVENT_WS_PACKET_SIZE
Triggered when there is an oversize WebSockets packet.
Definition coap_event.h:123
@ COAP_EVENT_TCP_CONNECTED
Triggered when TCP layer connects.
Definition coap_event.h:51
@ COAP_EVENT_OSCORE_DECRYPTION_FAILURE
Triggered when there is an OSCORE decryption failure.
Definition coap_event.h:108
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:132
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:45
coap_mutex_t coap_lock_t
#define coap_lock_callback_ret_release(r, c, func, failed)
Dummy for no thread-safe code.
#define coap_lock_callback_release(c, func, failed)
Dummy for no thread-safe code.
#define coap_lock_unlock(c)
Dummy for no thread-safe code.
#define coap_lock_lock(c, failed)
Dummy for no thread-safe code.
#define coap_lock_callback(c, func)
Dummy for no thread-safe code.
#define coap_lock_check_locked(c)
Dummy for no thread-safe code.
#define coap_lock_init()
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, c, func)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:120
#define coap_log_alert(...)
Definition coap_debug.h:84
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition coap_debug.c:778
#define coap_log_emerg(...)
Definition coap_debug.h:81
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:233
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:108
#define coap_log_warn(...)
Definition coap_debug.h:102
#define coap_log_err(...)
Definition coap_debug.h:96
@ COAP_LOG_DEBUG
Definition coap_debug.h:58
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_ALL
Pre-defined filter that includes all options.
int coap_option_filter_unset(coap_opt_filter_t *filter, coap_option_num_t option)
Clears the corresponding entry for number in 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)
#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:610
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:473
#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:1057
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:973
#define COAP_PDU_DELAYED
#define COAP_PDU_IS_EMPTY(pdu)
#define COAP_PDU_IS_SIGNALING(pdu)
int coap_option_check_repeatable(coap_option_num_t number)
Check whether the option is allowed to be repeated or not.
Definition coap_pdu.c:567
int coap_pdu_parse_opt(coap_pdu_t *pdu)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition coap_pdu.c:1319
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:704
#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:1469
#define COAP_DEFAULT_VERSION
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:1004
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:281
#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:760
#define COAP_OPTION_HOP_LIMIT
Definition coap_pdu.h:133
#define COAP_OPTION_NORESPONSE
Definition coap_pdu.h:145
#define COAP_OPTION_URI_HOST
Definition coap_pdu.h:120
#define COAP_OPTION_IF_MATCH
Definition coap_pdu.h:119
#define COAP_OPTION_BLOCK2
Definition coap_pdu.h:137
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition coap_pdu.c:931
#define COAP_OPTION_CONTENT_FORMAT
Definition coap_pdu.h:128
#define COAP_OPTION_BLOCK1
Definition coap_pdu.h:138
#define COAP_OPTION_Q_BLOCK1
Definition coap_pdu.h:135
#define COAP_OPTION_PROXY_SCHEME
Definition coap_pdu.h:142
#define COAP_OPTION_URI_QUERY
Definition coap_pdu.h:132
void coap_delete_pdu(coap_pdu_t *pdu)
Dispose of an CoAP PDU and frees associated storage.
Definition coap_pdu.c:179
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:263
#define COAP_TOKEN_DEFAULT_MAX
Definition coap_pdu.h:56
#define COAP_OPTION_IF_NONE_MATCH
Definition coap_pdu.h:122
#define COAP_TOKEN_EXT_MAX
Definition coap_pdu.h:60
#define COAP_OPTION_URI_PATH
Definition coap_pdu.h:127
#define COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH
Definition coap_pdu.h:199
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:160
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:163
coap_pdu_code_t
Set of codes available for a PDU.
Definition coap_pdu.h:327
#define COAP_OPTION_OSCORE
Definition coap_pdu.h:126
coap_pdu_type_t
CoAP PDU message type definitions.
Definition coap_pdu.h:68
#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
Definition coap_pdu.h:198
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:340
#define COAP_OPTION_Q_BLOCK2
Definition coap_pdu.h:140
#define COAP_SIGNALING_OPTION_CUSTODY
Definition coap_pdu.h:202
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:1446
#define COAP_OPTION_RTAG
Definition coap_pdu.h:146
#define COAP_OPTION_URI_PORT
Definition coap_pdu.h:124
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:97
#define COAP_OPTION_ACCEPT
Definition coap_pdu.h:134
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:266
#define COAP_OPTION_PROXY_URI
Definition coap_pdu.h:141
#define COAP_OPTION_OBSERVE
Definition coap_pdu.h:123
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition coap_pdu.h:53
#define COAP_BERT_BASE
Definition coap_pdu.h:44
#define COAP_OPTION_ECHO
Definition coap_pdu.h:144
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition coap_pdu.h:214
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition coap_pdu.h:197
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:825
@ COAP_REQUEST_GET
Definition coap_pdu.h:79
@ COAP_PROTO_WS
Definition coap_pdu.h:319
@ COAP_PROTO_DTLS
Definition coap_pdu.h:316
@ COAP_PROTO_UDP
Definition coap_pdu.h:315
@ COAP_PROTO_WSS
Definition coap_pdu.h:320
@ COAP_SIGNALING_CODE_ABORT
Definition coap_pdu.h:370
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:366
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:367
@ COAP_REQUEST_CODE_DELETE
Definition coap_pdu.h:333
@ COAP_SIGNALING_CODE_PONG
Definition coap_pdu.h:368
@ COAP_EMPTY_CODE
Definition coap_pdu.h:328
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:330
@ COAP_SIGNALING_CODE_RELEASE
Definition coap_pdu.h:369
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:334
@ COAP_MESSAGE_NON
Definition coap_pdu.h:70
@ COAP_MESSAGE_ACK
Definition coap_pdu.h:71
@ COAP_MESSAGE_CON
Definition coap_pdu.h:69
@ COAP_MESSAGE_RST
Definition coap_pdu.h:72
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).
size_t coap_session_max_pdu_rcv_size(const coap_session_t *session)
Get maximum acceptable receive PDU size.
coap_session_t * coap_endpoint_get_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Lookup the server session for the packet received on an endpoint, or create a new one.
void coap_free_endpoint_lkd(coap_endpoint_t *endpoint)
Release an endpoint and all the structures associated with it.
void coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2082
#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:1001
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_endpoint_t * coap_new_endpoint_lkd(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto)
Create a new endpoint for communicating with peers.
coap_session_t * coap_new_server_session(coap_context_t *ctx, coap_endpoint_t *ep, void *extra)
Creates a new server session for the specified endpoint.
@ COAP_EXT_T_NOT_CHECKED
Not checked.
@ COAP_EXT_T_CHECKING
Token size check request sent.
@ COAP_EXT_T_CHECKED
Token size valid.
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)
@ COAP_SESSION_TYPE_HELLO
server-side ephemeral session for responding to a client hello
@ 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:120
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:77
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:110
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:105
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:211
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:197
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:46
int coap_delete_observer_request(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, coap_pdu_t *request)
Removes any subscription for session observer from resource and releases the allocated storage.
void coap_persist_cleanup(coap_context_t *context)
Close down persist tracking, releasing any memory used.
int coap_delete_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token)
Removes any subscription for session observer from resource and releases the allocated storage.
int coap_cancel_observe_lkd(coap_session_t *session, coap_binary_t *token, coap_pdu_type_t message_type)
Cancel an observe that is being tracked by the client large receive logic.
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Handles a failed observe notify.
coap_subscription_t * coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, const coap_pdu_t *pdu)
Adds the specified peer as observer for resource.
void coap_touch_observer(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Flags that data is ready to be sent to observers.
int coap_epoll_is_supported(void)
Determine whether epoll is supported or not.
Definition coap_net.c:567
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:621
int coap_ipv6_is_supported(void)
Check whether IPv6 is available.
Definition coap_net.c:594
int coap_threadsafe_is_supported(void)
Determine whether libcoap is threadsafe or not.
Definition coap_net.c:576
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:612
int coap_client_is_supported(void)
Check whether Client code is available.
Definition coap_net.c:603
int coap_ipv4_is_supported(void)
Check whether IPv4 is available.
Definition coap_net.c:585
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition coap_uri.c:1008
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:299
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:957
#define COAP_UNUSED
Definition libcoap.h:70
#define COAP_STATIC_INLINE
Definition libcoap.h:53
coap_address_t remote
remote address and port
Definition coap_io.h:56
coap_address_t local
local address and port
Definition coap_io.h:57
Multi-purpose address abstraction.
struct sockaddr_in sin
union coap_address_t::@212253263242104077351363007332217211060041217374 addr
struct sockaddr_in6 sin6
struct sockaddr sa
CoAP binary data definition with const data.
Definition coap_str.h:64
size_t length
length of binary data
Definition coap_str.h:65
const uint8_t * s
read-only binary data
Definition coap_str.h:66
CoAP binary data definition.
Definition coap_str.h:56
size_t length
length of binary data
Definition coap_str.h:57
uint8_t * s
binary data
Definition coap_str.h:58
Structure of Block options with BERT support.
Definition coap_block.h:51
unsigned int num
block number
Definition coap_block.h:52
unsigned int bert
Operating as BERT.
Definition coap_block.h:57
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:55
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:53
unsigned int szx
block size (0-6)
Definition coap_block.h:54
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.
coap_pong_handler_t pong_handler
Called when a ping response is received.
void * app
application-specific data
coap_session_t * sessions
client sessions
coap_nack_handler_t nack_handler
Called when a response issue has occurred.
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
coap_resource_t * resources
hash table or list of known resources
uint16_t * cache_ignore_options
CoAP options to ignore when creating a cache-key.
coap_opt_filter_t known_options
coap_ping_handler_t ping_handler
Called when a CoAP ping is received.
uint32_t csm_max_message_size
Value for CSM Max-Message-Size.
size_t cache_ignore_count
The number of CoAP options to ignore when creating a cache-key.
unsigned int max_handshake_sessions
Maximum number of simultaneous negotating sessions per endpoint.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
coap_response_handler_t response_handler
Called when a response is received.
coap_cache_entry_t * cache
CoAP cache-entry cache.
uint8_t mcast_per_resource
Mcast controlled on a per resource basis.
coap_endpoint_t * endpoint
the endpoints used for listening
uint32_t csm_timeout_ms
Timeout for waiting for a CSM from the remote side.
coap_event_handler_t handle_event
Callback function that is used to signal events to the application.
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.
coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
coap_resource_t * unknown_resource
can be used for handling unknown resources
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
coap_bin_const_t key
Definition coap_dtls.h:381
coap_bin_const_t identity
Definition coap_dtls.h:380
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:443
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:312
uint8_t version
Definition coap_dtls.h:313
coap_bin_const_t hint
Definition coap_dtls.h:451
coap_bin_const_t key
Definition coap_dtls.h:452
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:501
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:533
Abstraction of virtual endpoint that can be attached to coap_context_t.
coap_context_t * context
endpoint's context
coap_session_t * sessions
hash table or list of active sessions
coap_address_t bind_addr
local interface address
coap_socket_t sock
socket object for the interface, if any
coap_proto_t proto
protocol used on this interface
uint64_t state_token
state token
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) client receive information.
uint64_t state_token
state token
coap_binary_t * app_token
app requesting PDU token
Structure to hold large body (many blocks) server receive information.
Structure to hold large body (many blocks) transmission information.
coap_pdu_t pdu
skeletal PDU
coap_l_block1_t b1
union coap_lg_xmit_t::@162270112253176223172072213247305325323222064201 b
uint16_t option
large block transmisson CoAP option
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
coap_lg_xmit_t * lg_xmit
Holds ptr to lg_xmit if sending a set of blocks.
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.
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_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 resource that can be attached to coap_context_t.
coap_str_const_t ** proxy_name_list
Array valid names this host is known by (proxy support).
coap_str_const_t * uri_path
Request URI Path for this resource.
unsigned int observe
The next value for the Observe option.
coap_method_handler_t handler[7]
Used to store handlers for the seven coap methods GET, POST, PUT, DELETE, FETCH, PATCH and IPATCH.
unsigned int is_proxy_uri
resource created for proxy URI handler
unsigned int is_unknown
resource created for unknown handler
unsigned int observable
can be observed
size_t proxy_name_count
Count of valid names this host is known by (proxy support).
int flags
zero or more COAP_RESOURCE_FLAGS_* or'd together
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 doing_first
Set if doing client's first request.
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.
coap_bin_const_t * psk_identity
If client, this field contains the current identity for server; When this field is NULL,...
coap_session_state_t state
current state of relationship with peer
uint8_t csm_bert_rem_support
CSM TCP BERT blocks supported (remote).
coap_mid_t 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_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
coap_bin_const_t * last_token
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
coap_lg_srcv_t * lg_srcv
Server list of expected large receives.
coap_lg_crcv_t * lg_crcv
Client list of expected large receives.
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_endpoint_t * endpoint
Used by the epoll logic for a listening endpoint.
coap_address_t mcast_addr
remote address and port (multicast track)
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values
CoAP string data definition with const data.
Definition coap_str.h:46
const uint8_t * s
read-only string data
Definition coap_str.h:48
size_t length
length of string
Definition coap_str.h:47
CoAP string data definition.
Definition coap_str.h:38
uint8_t * s
string data
Definition coap_str.h:40
size_t length
length of string
Definition coap_str.h:39
Number of notifications that may be sent non-confirmable before a confirmable message is sent to dete...
struct coap_session_t * session
subscriber session
coap_pdu_t * pdu
cache_key to identify requester
Representation of parsed URI.
Definition coap_uri.h:65
coap_str_const_t host
The host part of the URI.
Definition coap_uri.h:66