libcoap 4.3.5
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--2024 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
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 (
1329#if COAP_OSCORE_SUPPORT
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) ||
1335#if COAP_Q_BLOCK_SUPPORT
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 */
1751 }
1752 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1753 /* Internal error */
1755 }
1756 data_len = pdu->used_size - (pdu->data - pdu->token);
1757 pdu->data[data_len] = '\000';
1758 a_match = strstr((char *)pdu->data, cp);
1759 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1760 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1761 a_match[len] == ' ')) {
1762 coap_log_warn("Proxy loop detected '%s'\n",
1763 (char *)pdu->data);
1764 coap_delete_pdu(pdu);
1766 }
1767 }
1768 if (pdu->used_size + len + 1 <= pdu->max_size) {
1769 size_t old_size = pdu->used_size;
1770 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1771 if (pdu->data == NULL) {
1772 /*
1773 * Set Hop Limit to max for return path. If this libcoap is in
1774 * a proxy loop path, it will always decrement hop limit in code
1775 * above and hence timeout / drop the response as appropriate
1776 */
1777 hop_limit = 255;
1779 (uint8_t *)&hop_limit);
1780 coap_add_data(pdu, len, (uint8_t *)cp);
1781 } else {
1782 /* prepend with space separator, leaving hop limit "as is" */
1783 memmove(pdu->data + len + 1, pdu->data,
1784 old_size - (pdu->data - pdu->token));
1785 memcpy(pdu->data, cp, len);
1786 pdu->data[len] = ' ';
1787 pdu->used_size += len + 1;
1788 }
1789 }
1790 }
1791 }
1792 }
1793
1794 if (session->echo) {
1795 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1796 session->echo->s))
1797 goto error;
1798 coap_delete_bin_const(session->echo);
1799 session->echo = NULL;
1800 }
1801#if COAP_OSCORE_SUPPORT
1802 if (session->oscore_encryption) {
1803 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1805 goto error;
1806 }
1807#endif /* COAP_OSCORE_SUPPORT */
1808
1809 if (!coap_pdu_encode_header(pdu, session->proto)) {
1810 goto error;
1811 }
1812
1813#if !COAP_DISABLE_TCP
1814 if (COAP_PROTO_RELIABLE(session->proto) &&
1816 if (!session->csm_block_supported) {
1817 /*
1818 * Need to check that this instance is not sending any block options as
1819 * the remote end via CSM has not informed us that there is support
1820 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
1821 * This includes potential BERT blocks.
1822 */
1823 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1824 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
1825 }
1826 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1827 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
1828 }
1829 } else if (!session->csm_bert_rem_support) {
1830 coap_opt_t *opt;
1831
1832 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
1833 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1834 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
1835 }
1836 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
1837 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1838 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
1839 }
1840 }
1841 }
1842#endif /* !COAP_DISABLE_TCP */
1843
1844#if COAP_OSCORE_SUPPORT
1845 if (session->oscore_encryption &&
1846 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE)) {
1847 /* Refactor PDU as appropriate RFC8613 */
1848 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL,
1849 0);
1850
1851 if (osc_pdu == NULL) {
1852 coap_log_warn("OSCORE: PDU could not be encrypted\n");
1853 goto error;
1854 }
1855 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
1856 coap_delete_pdu(pdu);
1857 pdu = osc_pdu;
1858 } else
1859#endif /* COAP_OSCORE_SUPPORT */
1860 bytes_written = coap_send_pdu(session, pdu, NULL);
1861
1862 if (bytes_written == COAP_PDU_DELAYED) {
1863 /* do not free pdu as it is stored with session for later use */
1864 return pdu->mid;
1865 }
1866 if (bytes_written < 0) {
1867 goto error;
1868 }
1869
1870#if !COAP_DISABLE_TCP
1871 if (COAP_PROTO_RELIABLE(session->proto) &&
1872 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
1873 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
1874 session->partial_write = (size_t)bytes_written;
1875 /* do not free pdu as it is stored with session for later use */
1876 return pdu->mid;
1877 } else {
1878 goto error;
1879 }
1880 }
1881#endif /* !COAP_DISABLE_TCP */
1882
1883 if (pdu->type != COAP_MESSAGE_CON
1884 || COAP_PROTO_RELIABLE(session->proto)) {
1885 coap_mid_t id = pdu->mid;
1886 coap_delete_pdu(pdu);
1887 return id;
1888 }
1889
1890 coap_queue_t *node = coap_new_node();
1891 if (!node) {
1892 coap_log_debug("coap_wait_ack: insufficient memory\n");
1893 goto error;
1894 }
1895
1896 node->id = pdu->mid;
1897 node->pdu = pdu;
1898 coap_prng_lkd(&r, sizeof(r));
1899 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
1900 node->timeout = coap_calc_timeout(session, r);
1901 return coap_wait_ack(session->context, session, node);
1902error:
1903 coap_delete_pdu(pdu);
1904 return COAP_INVALID_MID;
1905}
1906
1909 if (!context || !node)
1910 return COAP_INVALID_MID;
1911
1912 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
1913 if (node->retransmit_cnt < node->session->max_retransmit) {
1914 ssize_t bytes_written;
1915 coap_tick_t now;
1916 coap_tick_t next_delay;
1917
1918 node->retransmit_cnt++;
1920
1921 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
1922 if (context->ping_timeout &&
1923 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
1924 uint8_t byte;
1925
1926 coap_prng_lkd(&byte, sizeof(byte));
1927 /* Don't exceed the ping timeout value */
1928 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
1929 }
1930
1931 coap_ticks(&now);
1932 if (context->sendqueue == NULL) {
1933 node->t = next_delay;
1934 context->sendqueue_basetime = now;
1935 } else {
1936 /* make node->t relative to context->sendqueue_basetime */
1937 node->t = (now - context->sendqueue_basetime) + next_delay;
1938 }
1939 coap_insert_node(&context->sendqueue, node);
1940
1941 if (node->is_mcast) {
1942 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
1943 coap_session_str(node->session), node->id);
1944 } else {
1945 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
1946 coap_session_str(node->session), node->id,
1947 node->retransmit_cnt,
1948 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
1949 }
1950
1951 if (node->session->con_active)
1952 node->session->con_active--;
1953 bytes_written = coap_send_pdu(node->session, node->pdu, node);
1954
1955 if (node->is_mcast) {
1958 return COAP_INVALID_MID;
1959 }
1960 if (bytes_written == COAP_PDU_DELAYED) {
1961 /* PDU was not retransmitted immediately because a new handshake is
1962 in progress. node was moved to the send queue of the session. */
1963 return node->id;
1964 }
1965
1966 if (bytes_written < 0)
1967 return (int)bytes_written;
1968
1969 return node->id;
1970 }
1971
1972 /* no more retransmissions, remove node from system */
1973 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
1974 coap_session_str(node->session), node->id, node->retransmit_cnt);
1975
1976#if COAP_SERVER_SUPPORT
1977 /* Check if subscriptions exist that should be canceled after
1978 COAP_OBS_MAX_FAIL */
1979 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2) {
1980 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
1981 }
1982#endif /* COAP_SERVER_SUPPORT */
1983 if (node->session->con_active) {
1984 node->session->con_active--;
1986 /*
1987 * As there may be another CON in a different queue entry on the same
1988 * session that needs to be immediately released,
1989 * coap_session_connected() is called.
1990 * However, there is the possibility coap_wait_ack() may be called for
1991 * this node (queue) and re-added to context->sendqueue.
1992 * coap_delete_node_lkd(node) called shortly will handle this and
1993 * remove it.
1994 */
1996 }
1997 }
1998
1999 /* And finally delete the node */
2000 if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
2001 coap_check_update_token(node->session, node->pdu);
2002 coap_lock_callback(context,
2003 context->nack_handler(node->session, node->pdu,
2005 }
2007 return COAP_INVALID_MID;
2008}
2009
2010static int
2012 uint8_t *data;
2013 size_t data_len;
2014 int result = -1;
2015
2016 coap_packet_get_memmapped(packet, &data, &data_len);
2017 if (session->proto == COAP_PROTO_DTLS) {
2018#if COAP_SERVER_SUPPORT
2019 if (session->type == COAP_SESSION_TYPE_HELLO)
2020 result = coap_dtls_hello(session, data, data_len);
2021 else
2022#endif /* COAP_SERVER_SUPPORT */
2023 if (session->tls)
2024 result = coap_dtls_receive(session, data, data_len);
2025 } else if (session->proto == COAP_PROTO_UDP) {
2026 result = coap_handle_dgram(ctx, session, data, data_len);
2027 }
2028 return result;
2029}
2030
2031#if COAP_CLIENT_SUPPORT
2032void
2034#if COAP_DISABLE_TCP
2035 (void)now;
2036
2038#else /* !COAP_DISABLE_TCP */
2039 if (coap_netif_strm_connect2(session)) {
2040 session->last_rx_tx = now;
2042 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2043 } else {
2046 }
2047#endif /* !COAP_DISABLE_TCP */
2048}
2049#endif /* COAP_CLIENT_SUPPORT */
2050
2051static void
2053 (void)ctx;
2054 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2055
2056 while (session->delayqueue) {
2057 ssize_t bytes_written;
2058 coap_queue_t *q = session->delayqueue;
2059 coap_log_debug("** %s: mid=0x%04x: transmitted after delay\n",
2060 coap_session_str(session), (int)q->pdu->mid);
2061 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2062 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2063 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2064 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2065 if (bytes_written > 0)
2066 session->last_rx_tx = now;
2067 if (bytes_written <= 0 ||
2068 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2069 if (bytes_written > 0)
2070 session->partial_write += (size_t)bytes_written;
2071 break;
2072 }
2073 session->delayqueue = q->next;
2074 session->partial_write = 0;
2076 }
2077}
2078
2079void
2081#if COAP_CONSTRAINED_STACK
2082 /* payload and packet can be protected by global_lock if needed */
2083 static unsigned char payload[COAP_RXBUFFER_SIZE];
2084 static coap_packet_t s_packet;
2085#else /* ! COAP_CONSTRAINED_STACK */
2086 unsigned char payload[COAP_RXBUFFER_SIZE];
2087 coap_packet_t s_packet;
2088#endif /* ! COAP_CONSTRAINED_STACK */
2089 coap_packet_t *packet = &s_packet;
2090
2092
2093 packet->length = sizeof(payload);
2094 packet->payload = payload;
2095
2096 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2097 ssize_t bytes_read;
2098 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2099 bytes_read = coap_netif_dgrm_read(session, packet);
2100
2101 if (bytes_read < 0) {
2102 if (bytes_read == -2)
2103 /* Reset the session back to startup defaults */
2105 } else if (bytes_read > 0) {
2106 session->last_rx_tx = now;
2107 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2108 coap_handle_dgram_for_proto(ctx, session, packet);
2109 }
2110#if !COAP_DISABLE_TCP
2111 } else if (session->proto == COAP_PROTO_WS ||
2112 session->proto == COAP_PROTO_WSS) {
2113 ssize_t bytes_read = 0;
2114
2115 /* WebSocket layer passes us the whole packet */
2116 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2117 packet->payload,
2118 packet->length);
2119 if (bytes_read < 0) {
2121 } else if (bytes_read > 2) {
2122 coap_pdu_t *pdu;
2123
2124 session->last_rx_tx = now;
2125 /* Need max space incase PDU is updated with updated token etc. */
2126 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2127 if (!pdu) {
2128 return;
2129 }
2130
2131 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2133 coap_log_warn("discard malformed PDU\n");
2134 coap_delete_pdu(pdu);
2135 return;
2136 }
2137
2138 coap_dispatch(ctx, session, pdu);
2139 coap_delete_pdu(pdu);
2140 return;
2141 }
2142 } else {
2143 ssize_t bytes_read = 0;
2144 const uint8_t *p;
2145 int retry;
2146
2147 do {
2148 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2149 packet->payload,
2150 packet->length);
2151 if (bytes_read > 0) {
2152 session->last_rx_tx = now;
2153 }
2154 p = packet->payload;
2155 retry = bytes_read == (ssize_t)packet->length;
2156 while (bytes_read > 0) {
2157 if (session->partial_pdu) {
2158 size_t len = session->partial_pdu->used_size
2159 + session->partial_pdu->hdr_size
2160 - session->partial_read;
2161 size_t n = min(len, (size_t)bytes_read);
2162 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2163 + session->partial_read, p, n);
2164 p += n;
2165 bytes_read -= n;
2166 if (n == len) {
2167 if (coap_pdu_parse_header(session->partial_pdu, session->proto)
2168 && coap_pdu_parse_opt(session->partial_pdu)) {
2169 coap_dispatch(ctx, session, session->partial_pdu);
2170 }
2171 coap_delete_pdu(session->partial_pdu);
2172 session->partial_pdu = NULL;
2173 session->partial_read = 0;
2174 } else {
2175 session->partial_read += n;
2176 }
2177 } else if (session->partial_read > 0) {
2178 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2179 session->read_header);
2180 size_t tkl = session->read_header[0] & 0x0f;
2181 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2182 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2183 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2184 size_t n = min(len, (size_t)bytes_read);
2185 memcpy(session->read_header + session->partial_read, p, n);
2186 p += n;
2187 bytes_read -= n;
2188 if (n == len) {
2189 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2190 hdr_size + tok_ext_bytes);
2191 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2192 coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
2193 coap_session_str(session),
2194 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2195 bytes_read = -1;
2196 break;
2197 }
2198 /* Need max space incase PDU is updated with updated token etc. */
2199 session->partial_pdu = coap_pdu_init(0, 0, 0,
2201 if (session->partial_pdu == NULL) {
2202 bytes_read = -1;
2203 break;
2204 }
2205 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2206 bytes_read = -1;
2207 break;
2208 }
2209 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2210 session->partial_pdu->used_size = size;
2211 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2212 session->partial_read = hdr_size + tok_ext_bytes;
2213 if (size == 0) {
2214 if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
2215 coap_dispatch(ctx, session, session->partial_pdu);
2216 }
2217 coap_delete_pdu(session->partial_pdu);
2218 session->partial_pdu = NULL;
2219 session->partial_read = 0;
2220 }
2221 } else {
2222 session->partial_read += bytes_read;
2223 }
2224 } else {
2225 session->read_header[0] = *p++;
2226 bytes_read -= 1;
2227 if (!coap_pdu_parse_header_size(session->proto,
2228 session->read_header)) {
2229 bytes_read = -1;
2230 break;
2231 }
2232 session->partial_read = 1;
2233 }
2234 }
2235 } while (bytes_read == 0 && retry);
2236 if (bytes_read < 0)
2238#endif /* !COAP_DISABLE_TCP */
2239 }
2240}
2241
2242#if COAP_SERVER_SUPPORT
2243static int
2244coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2245 ssize_t bytes_read = -1;
2246 int result = -1; /* the value to be returned */
2247#if COAP_CONSTRAINED_STACK
2248 /* payload and e_packet can be protected by global_lock if needed */
2249 static unsigned char payload[COAP_RXBUFFER_SIZE];
2250 static coap_packet_t e_packet;
2251#else /* ! COAP_CONSTRAINED_STACK */
2252 unsigned char payload[COAP_RXBUFFER_SIZE];
2253 coap_packet_t e_packet;
2254#endif /* ! COAP_CONSTRAINED_STACK */
2255 coap_packet_t *packet = &e_packet;
2256
2257 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2258 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2259
2260 /* Need to do this as there may be holes in addr_info */
2261 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2262 packet->length = sizeof(payload);
2263 packet->payload = payload;
2265 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2266
2267 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2268 if (bytes_read < 0) {
2269 if (errno != EAGAIN) {
2270 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2271 }
2272 } else if (bytes_read > 0) {
2273 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2274 if (session) {
2275 coap_log_debug("* %s: netif: recv %4zd bytes\n",
2276 coap_session_str(session), bytes_read);
2277 result = coap_handle_dgram_for_proto(ctx, session, packet);
2278 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2279 coap_session_new_dtls_session(session, now);
2280 }
2281 }
2282 return result;
2283}
2284
2285static int
2286coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2287 (void)ctx;
2288 (void)endpoint;
2289 (void)now;
2290 return 0;
2291}
2292
2293#if !COAP_DISABLE_TCP
2294static int
2295coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2296 coap_tick_t now, void *extra) {
2297 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2298 if (session)
2299 session->last_rx_tx = now;
2300 return session != NULL;
2301}
2302#endif /* !COAP_DISABLE_TCP */
2303#endif /* COAP_SERVER_SUPPORT */
2304
2305COAP_API void
2307 coap_lock_lock(ctx, return);
2308 coap_io_do_io_lkd(ctx, now);
2309 coap_lock_unlock(ctx);
2310}
2311
2312void
2314#ifdef COAP_EPOLL_SUPPORT
2315 (void)ctx;
2316 (void)now;
2317 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2318#else /* ! COAP_EPOLL_SUPPORT */
2319 coap_session_t *s, *rtmp;
2320
2322#if COAP_SERVER_SUPPORT
2323 coap_endpoint_t *ep, *tmp;
2324 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2325 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2326 coap_read_endpoint(ctx, ep, now);
2327 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2328 coap_write_endpoint(ctx, ep, now);
2329#if !COAP_DISABLE_TCP
2330 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2331 coap_accept_endpoint(ctx, ep, now, NULL);
2332#endif /* !COAP_DISABLE_TCP */
2333 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2334 /* Make sure the session object is not deleted in one of the callbacks */
2336 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2337 coap_read_session(ctx, s, now);
2338 }
2339 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2340 coap_write_session(ctx, s, now);
2341 }
2343 }
2344 }
2345#endif /* COAP_SERVER_SUPPORT */
2346
2347#if COAP_CLIENT_SUPPORT
2348 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2349 /* Make sure the session object is not deleted in one of the callbacks */
2351 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2352 coap_connect_session(s, now);
2353 }
2354 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2355 coap_read_session(ctx, s, now);
2356 }
2357 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2358 coap_write_session(ctx, s, now);
2359 }
2361 }
2362#endif /* COAP_CLIENT_SUPPORT */
2363#endif /* ! COAP_EPOLL_SUPPORT */
2364}
2365
2366COAP_API void
2367coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2368 coap_lock_lock(ctx, return);
2369 coap_io_do_epoll_lkd(ctx, events, nevents);
2370 coap_lock_unlock(ctx);
2371}
2372
2373/*
2374 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2375 * directly saves having to iterate through the endpoints / sessions.
2376 */
2377void
2378coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2379#ifndef COAP_EPOLL_SUPPORT
2380 (void)ctx;
2381 (void)events;
2382 (void)nevents;
2383 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2384#else /* COAP_EPOLL_SUPPORT */
2385 coap_tick_t now;
2386 size_t j;
2387
2389 coap_ticks(&now);
2390 for (j = 0; j < nevents; j++) {
2391 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2392
2393 /* Ignore 'timer trigger' ptr which is NULL */
2394 if (sock) {
2395#if COAP_SERVER_SUPPORT
2396 if (sock->endpoint) {
2397 coap_endpoint_t *endpoint = sock->endpoint;
2398 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2399 (events[j].events & EPOLLIN)) {
2400 sock->flags |= COAP_SOCKET_CAN_READ;
2401 coap_read_endpoint(endpoint->context, endpoint, now);
2402 }
2403
2404 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2405 (events[j].events & EPOLLOUT)) {
2406 /*
2407 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2408 * be true causing epoll_wait to return early
2409 */
2410 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2412 coap_write_endpoint(endpoint->context, endpoint, now);
2413 }
2414
2415#if !COAP_DISABLE_TCP
2416 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2417 (events[j].events & EPOLLIN)) {
2419 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2420 }
2421#endif /* !COAP_DISABLE_TCP */
2422
2423 } else
2424#endif /* COAP_SERVER_SUPPORT */
2425 if (sock->session) {
2426 coap_session_t *session = sock->session;
2427
2428 /* Make sure the session object is not deleted
2429 in one of the callbacks */
2431#if COAP_CLIENT_SUPPORT
2432 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2433 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2435 coap_connect_session(session, now);
2436 if (coap_netif_available(session) &&
2437 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2438 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2439 }
2440 }
2441#endif /* COAP_CLIENT_SUPPORT */
2442
2443 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2444 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2445 sock->flags |= COAP_SOCKET_CAN_READ;
2446 coap_read_session(session->context, session, now);
2447 }
2448
2449 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2450 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2451 /*
2452 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2453 * be true causing epoll_wait to return early
2454 */
2455 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2457 coap_write_session(session->context, session, now);
2458 }
2459 /* Now dereference session so it can go away if needed */
2460 coap_session_release_lkd(session);
2461 }
2462 } else if (ctx->eptimerfd != -1) {
2463 /*
2464 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2465 * it so that it does not set EPOLLIN in the next epoll_wait().
2466 */
2467 uint64_t count;
2468
2469 /* Check the result from read() to suppress the warning on
2470 * systems that declare read() with warn_unused_result. */
2471 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2472 /* do nothing */;
2473 }
2474 }
2475 }
2476 /* And update eptimerfd as to when to next trigger */
2477 coap_ticks(&now);
2478 coap_io_prepare_epoll_lkd(ctx, now);
2479#endif /* COAP_EPOLL_SUPPORT */
2480}
2481
2482int
2484 uint8_t *msg, size_t msg_len) {
2485
2486 coap_pdu_t *pdu = NULL;
2487
2488 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2489 if (msg_len < 4) {
2490 /* Minimum size of CoAP header - ignore runt */
2491 return -1;
2492 }
2493 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2494 /*
2495 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2496 * this MUST be silently ignored.
2497 */
2498 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2499 return -1;
2500 }
2501
2502 /* Need max space incase PDU is updated with updated token etc. */
2503 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2504 if (!pdu)
2505 goto error;
2506
2507 if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
2509 coap_log_warn("discard malformed PDU\n");
2510 goto error;
2511 }
2512
2513 coap_dispatch(ctx, session, pdu);
2514 coap_delete_pdu(pdu);
2515 return 0;
2516
2517error:
2518 /*
2519 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2520 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2521 */
2522 coap_send_rst_lkd(session, pdu);
2523 coap_delete_pdu(pdu);
2524 return -1;
2525}
2526
2527int
2529 coap_queue_t **node) {
2530 coap_queue_t *p, *q;
2531
2532 if (!queue || !*queue)
2533 return 0;
2534
2535 /* replace queue head if PDU's time is less than head's time */
2536
2537 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2538 *node = *queue;
2539 *queue = (*queue)->next;
2540 if (*queue) { /* adjust relative time of new queue head */
2541 (*queue)->t += (*node)->t;
2542 }
2543 (*node)->next = NULL;
2544 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2545 coap_session_str(session), id);
2546 return 1;
2547 }
2548
2549 /* search message id queue to remove (only first occurence will be removed) */
2550 q = *queue;
2551 do {
2552 p = q;
2553 q = q->next;
2554 } while (q && (session != q->session || id != q->id));
2555
2556 if (q) { /* found message id */
2557 p->next = q->next;
2558 if (p->next) { /* must update relative time of p->next */
2559 p->next->t += q->t;
2560 }
2561 q->next = NULL;
2562 *node = q;
2563 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
2564 coap_session_str(session), id);
2565 return 1;
2566 }
2567
2568 return 0;
2569
2570}
2571
2572void
2574 coap_nack_reason_t reason) {
2575 coap_queue_t *p, *q;
2576
2577 while (context->sendqueue && context->sendqueue->session == session) {
2578 q = context->sendqueue;
2579 context->sendqueue = q->next;
2580 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
2581 coap_session_str(session), q->id);
2582 if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
2583 coap_check_update_token(session, q->pdu);
2584 coap_lock_callback(context,
2585 context->nack_handler(session, q->pdu, reason, q->id));
2586 }
2588 }
2589
2590 if (!context->sendqueue)
2591 return;
2592
2593 p = context->sendqueue;
2594 q = p->next;
2595
2596 while (q) {
2597 if (q->session == session) {
2598 p->next = q->next;
2599 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
2600 coap_session_str(session), q->id);
2601 if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
2602 coap_check_update_token(session, q->pdu);
2603 coap_lock_callback(context,
2604 context->nack_handler(session, q->pdu, reason, q->id));
2605 }
2607 q = p->next;
2608 } else {
2609 p = q;
2610 q = q->next;
2611 }
2612 }
2613}
2614
2615void
2617 coap_bin_const_t *token) {
2618 /* cancel all messages in sendqueue that belong to session
2619 * and use the specified token */
2620 coap_queue_t **p, *q;
2621
2622 if (!context->sendqueue)
2623 return;
2624
2625 p = &context->sendqueue;
2626 q = *p;
2627
2628 while (q) {
2629 if (q->session == session &&
2630 coap_binary_equal(&q->pdu->actual_token, token)) {
2631 *p = q->next;
2632 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
2633 coap_session_str(session), q->id);
2634 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2635 session->con_active--;
2636 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2637 /* Flush out any entries on session->delayqueue */
2638 coap_session_connected(session);
2639 }
2641 } else {
2642 p = &(q->next);
2643 }
2644 q = *p;
2645 }
2646}
2647
2648coap_pdu_t *
2650 coap_opt_filter_t *opts) {
2651 coap_opt_iterator_t opt_iter;
2652 coap_pdu_t *response;
2653 size_t size = request->e_token_length;
2654 unsigned char type;
2655 coap_opt_t *option;
2656 coap_option_num_t opt_num = 0; /* used for calculating delta-storage */
2657
2658#if COAP_ERROR_PHRASE_LENGTH > 0
2659 const char *phrase;
2660 if (code != COAP_RESPONSE_CODE(508)) {
2661 phrase = coap_response_phrase(code);
2662
2663 /* Need some more space for the error phrase and payload start marker */
2664 if (phrase)
2665 size += strlen(phrase) + 1;
2666 } else {
2667 /*
2668 * Need space for IP for 5.08 response which is filled in in
2669 * coap_send_internal()
2670 * https://rfc-editor.org/rfc/rfc8768.html#section-4
2671 */
2672 phrase = NULL;
2673 size += INET6_ADDRSTRLEN;
2674 }
2675#endif
2676
2677 assert(request);
2678
2679 /* cannot send ACK if original request was not confirmable */
2680 type = request->type == COAP_MESSAGE_CON ?
2682
2683 /* Estimate how much space we need for options to copy from
2684 * request. We always need the Token, for 4.02 the unknown critical
2685 * options must be included as well. */
2686
2687 /* we do not want these */
2690 /* Unsafe to send this back */
2692
2693 coap_option_iterator_init(request, &opt_iter, opts);
2694
2695 /* Add size of each unknown critical option. As known critical
2696 options as well as elective options are not copied, the delta
2697 value might grow.
2698 */
2699 while ((option = coap_option_next(&opt_iter))) {
2700 uint16_t delta = opt_iter.number - opt_num;
2701 /* calculate space required to encode (opt_iter.number - opt_num) */
2702 if (delta < 13) {
2703 size++;
2704 } else if (delta < 269) {
2705 size += 2;
2706 } else {
2707 size += 3;
2708 }
2709
2710 /* add coap_opt_length(option) and the number of additional bytes
2711 * required to encode the option length */
2712
2713 size += coap_opt_length(option);
2714 switch (*option & 0x0f) {
2715 case 0x0e:
2716 size++;
2717 /* fall through */
2718 case 0x0d:
2719 size++;
2720 break;
2721 default:
2722 ;
2723 }
2724
2725 opt_num = opt_iter.number;
2726 }
2727
2728 /* Now create the response and fill with options and payload data. */
2729 response = coap_pdu_init(type, code, request->mid, size);
2730 if (response) {
2731 /* copy token */
2732 if (!coap_add_token(response, request->actual_token.length,
2733 request->actual_token.s)) {
2734 coap_log_debug("cannot add token to error response\n");
2735 coap_delete_pdu(response);
2736 return NULL;
2737 }
2738
2739 /* copy all options */
2740 coap_option_iterator_init(request, &opt_iter, opts);
2741 while ((option = coap_option_next(&opt_iter))) {
2742 coap_add_option_internal(response, opt_iter.number,
2743 coap_opt_length(option),
2744 coap_opt_value(option));
2745 }
2746
2747#if COAP_ERROR_PHRASE_LENGTH > 0
2748 /* note that diagnostic messages do not need a Content-Format option. */
2749 if (phrase)
2750 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
2751#endif
2752 }
2753
2754 return response;
2755}
2756
2757#if COAP_SERVER_SUPPORT
2758#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
2759
2760static void
2761free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
2762 coap_delete_string(app_ptr);
2763}
2764
2765/*
2766 * Caution: As this handler is in libcoap space, it is called with
2767 * context locked.
2768 */
2769static void
2770hnd_get_wellknown_lkd(coap_resource_t *resource,
2771 coap_session_t *session,
2772 const coap_pdu_t *request,
2773 const coap_string_t *query,
2774 coap_pdu_t *response) {
2775 size_t len = 0;
2776 coap_string_t *data_string = NULL;
2777 coap_print_status_t result = 0;
2778 size_t wkc_len = 0;
2779 uint8_t buf[4];
2780
2781 /*
2782 * Quick hack to determine the size of the resource descriptions for
2783 * .well-known/core.
2784 */
2785 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
2786 if (result & COAP_PRINT_STATUS_ERROR) {
2787 coap_log_warn("cannot determine length of /.well-known/core\n");
2788 goto error;
2789 }
2790
2791 if (wkc_len > 0) {
2792 data_string = coap_new_string(wkc_len);
2793 if (!data_string)
2794 goto error;
2795
2796 len = wkc_len;
2797 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
2798 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
2799 coap_log_debug("coap_print_wellknown failed\n");
2800 goto error;
2801 }
2802 assert(len <= (size_t)wkc_len);
2803 data_string->length = len;
2804
2805 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
2807 coap_encode_var_safe(buf, sizeof(buf),
2809 goto error;
2810 }
2811 if (response->used_size + len + 1 > response->max_size) {
2812 /*
2813 * Data does not fit into a packet and no libcoap block support
2814 * +1 for end of options marker
2815 */
2816 coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
2817 len, response->max_size - response->used_size - 1);
2818 len = response->max_size - response->used_size - 1;
2819 }
2820 if (!coap_add_data(response, len, data_string->s)) {
2821 goto error;
2822 }
2823 free_wellknown_response(session, data_string);
2824 } else if (!coap_add_data_large_response_lkd(resource, session, request,
2825 response, query,
2827 -1, 0, data_string->length,
2828 data_string->s,
2829 free_wellknown_response,
2830 data_string)) {
2831 goto error_released;
2832 }
2833 } else {
2835 coap_encode_var_safe(buf, sizeof(buf),
2837 goto error;
2838 }
2839 }
2840 response->code = COAP_RESPONSE_CODE(205);
2841 return;
2842
2843error:
2844 free_wellknown_response(session, data_string);
2845error_released:
2846 if (response->code == 0) {
2847 /* set error code 5.03 and remove all options and data from response */
2848 response->code = COAP_RESPONSE_CODE(503);
2849 response->used_size = response->e_token_length;
2850 response->data = NULL;
2851 }
2852}
2853#endif /* COAP_SERVER_SUPPORT */
2854
2865static int
2867 int num_cancelled = 0; /* the number of observers cancelled */
2868
2869#ifndef COAP_SERVER_SUPPORT
2870 (void)sent;
2871#endif /* ! COAP_SERVER_SUPPORT */
2872 (void)context;
2873
2874#if COAP_SERVER_SUPPORT
2875 /* remove observer for this resource, if any
2876 * Use token from sent and try to find a matching resource. Uh!
2877 */
2878 RESOURCES_ITER(context->resources, r) {
2879 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
2880 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
2881 }
2882#endif /* COAP_SERVER_SUPPORT */
2883
2884 return num_cancelled;
2885}
2886
2887#if COAP_SERVER_SUPPORT
2892enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
2893
2894/*
2895 * Checks for No-Response option in given @p request and
2896 * returns @c RESPONSE_DROP if @p response should be suppressed
2897 * according to RFC 7967.
2898 *
2899 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
2900 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
2901 * on retrying.
2902 *
2903 * Checks if the response code is 0.00 and if either the session is reliable or
2904 * non-confirmable, @c RESPONSE_DROP is also returned.
2905 *
2906 * Multicast response checking is also carried out.
2907 *
2908 * NOTE: It is the responsibility of the application to determine whether
2909 * a delayed separate response should be sent as the original requesting packet
2910 * containing the No-Response option has long since gone.
2911 *
2912 * The value of the No-Response option is encoded as
2913 * follows:
2914 *
2915 * @verbatim
2916 * +-------+-----------------------+-----------------------------------+
2917 * | Value | Binary Representation | Description |
2918 * +-------+-----------------------+-----------------------------------+
2919 * | 0 | <empty> | Interested in all responses. |
2920 * +-------+-----------------------+-----------------------------------+
2921 * | 2 | 00000010 | Not interested in 2.xx responses. |
2922 * +-------+-----------------------+-----------------------------------+
2923 * | 8 | 00001000 | Not interested in 4.xx responses. |
2924 * +-------+-----------------------+-----------------------------------+
2925 * | 16 | 00010000 | Not interested in 5.xx responses. |
2926 * +-------+-----------------------+-----------------------------------+
2927 * @endverbatim
2928 *
2929 * @param request The CoAP request to check for the No-Response option.
2930 * This parameter must not be NULL.
2931 * @param response The response that is potentially suppressed.
2932 * This parameter must not be NULL.
2933 * @param session The session this request/response are associated with.
2934 * This parameter must not be NULL.
2935 * @return RESPONSE_DEFAULT when no special treatment is requested,
2936 * RESPONSE_DROP when the response must be discarded, or
2937 * RESPONSE_SEND when the response must be sent.
2938 */
2939static enum respond_t
2940no_response(coap_pdu_t *request, coap_pdu_t *response,
2941 coap_session_t *session, coap_resource_t *resource) {
2942 coap_opt_t *nores;
2943 coap_opt_iterator_t opt_iter;
2944 unsigned int val = 0;
2945
2946 assert(request);
2947 assert(response);
2948
2949 if (COAP_RESPONSE_CLASS(response->code) > 0) {
2950 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
2951
2952 if (nores) {
2954
2955 /* The response should be dropped when the bit corresponding to
2956 * the response class is set (cf. table in function
2957 * documentation). When a No-Response option is present and the
2958 * bit is not set, the sender explicitly indicates interest in
2959 * this response. */
2960 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
2961 /* Should be dropping the response */
2962 if (response->type == COAP_MESSAGE_ACK &&
2963 COAP_PROTO_NOT_RELIABLE(session->proto)) {
2964 /* Still need to ACK the request */
2965 response->code = 0;
2966 /* Remove token/data from piggybacked acknowledgment PDU */
2967 response->actual_token.length = 0;
2968 response->e_token_length = 0;
2969 response->used_size = 0;
2970 response->data = NULL;
2971 return RESPONSE_SEND;
2972 } else {
2973 return RESPONSE_DROP;
2974 }
2975 } else {
2976 /* True for mcast as well RFC7967 2.1 */
2977 return RESPONSE_SEND;
2978 }
2979 } else if (resource && session->context->mcast_per_resource &&
2980 coap_is_mcast(&session->addr_info.local)) {
2981 /* Handle any mcast suppression specifics if no NoResponse option */
2982 if ((resource->flags &
2984 COAP_RESPONSE_CLASS(response->code) == 2) {
2985 return RESPONSE_DROP;
2986 } else if ((resource->flags &
2988 response->code == COAP_RESPONSE_CODE(205)) {
2989 if (response->data == NULL)
2990 return RESPONSE_DROP;
2991 } else if ((resource->flags &
2993 COAP_RESPONSE_CLASS(response->code) == 4) {
2994 return RESPONSE_DROP;
2995 } else if ((resource->flags &
2997 COAP_RESPONSE_CLASS(response->code) == 5) {
2998 return RESPONSE_DROP;
2999 }
3000 }
3001 } else if (COAP_PDU_IS_EMPTY(response) &&
3002 (response->type == COAP_MESSAGE_NON ||
3003 COAP_PROTO_RELIABLE(session->proto))) {
3004 /* response is 0.00, and this is reliable or non-confirmable */
3005 return RESPONSE_DROP;
3006 }
3007
3008 /*
3009 * Do not send error responses for requests that were received via
3010 * IP multicast. RFC7252 8.1
3011 */
3012
3013 if (coap_is_mcast(&session->addr_info.local)) {
3014 if (request->type == COAP_MESSAGE_NON &&
3015 response->type == COAP_MESSAGE_RST)
3016 return RESPONSE_DROP;
3017
3018 if ((!resource || session->context->mcast_per_resource == 0) &&
3019 COAP_RESPONSE_CLASS(response->code) > 2)
3020 return RESPONSE_DROP;
3021 }
3022
3023 /* Default behavior applies when we are not dealing with a response
3024 * (class == 0) or the request did not contain a No-Response option.
3025 */
3026 return RESPONSE_DEFAULT;
3027}
3028
3029static coap_str_const_t coap_default_uri_wellknown = {
3031 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3032};
3033
3034/* Initialized in coap_startup() */
3035static coap_resource_t resource_uri_wellknown;
3036
3037static void
3038handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu) {
3039 coap_method_handler_t h = NULL;
3040 coap_pdu_t *response = NULL;
3041 coap_opt_filter_t opt_filter;
3042 coap_resource_t *resource = NULL;
3043 /* The respond field indicates whether a response must be treated
3044 * specially due to a No-Response option that declares disinterest
3045 * or interest in a specific response class. DEFAULT indicates that
3046 * No-Response has not been specified. */
3047 enum respond_t respond = RESPONSE_DEFAULT;
3048 coap_opt_iterator_t opt_iter;
3049 coap_opt_t *opt;
3050 int is_proxy_uri = 0;
3051 int is_proxy_scheme = 0;
3052 int skip_hop_limit_check = 0;
3053 int resp = 0;
3054 int send_early_empty_ack = 0;
3055 coap_string_t *query = NULL;
3056 coap_opt_t *observe = NULL;
3057 coap_string_t *uri_path = NULL;
3058 int observe_action = COAP_OBSERVE_CANCEL;
3059 coap_block_b_t block;
3060 int added_block = 0;
3061 coap_lg_srcv_t *free_lg_srcv = NULL;
3062#if COAP_Q_BLOCK_SUPPORT
3063 int lg_xmit_ctrl = 0;
3064#endif /* COAP_Q_BLOCK_SUPPORT */
3065#if COAP_ASYNC_SUPPORT
3066 coap_async_t *async;
3067#endif /* COAP_ASYNC_SUPPORT */
3068
3069 if (coap_is_mcast(&session->addr_info.local)) {
3070 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3071 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3072 return;
3073 }
3074 }
3075#if COAP_ASYNC_SUPPORT
3076 async = coap_find_async_lkd(session, pdu->actual_token);
3077 if (async) {
3078 coap_tick_t now;
3079
3080 coap_ticks(&now);
3081 if (async->delay == 0 || async->delay > now) {
3082 /* re-transmit missing ACK (only if CON) */
3083 coap_log_info("Retransmit async response\n");
3084 coap_send_ack_lkd(session, pdu);
3085 /* and do not pass on to the upper layers */
3086 return;
3087 }
3088 }
3089#endif /* COAP_ASYNC_SUPPORT */
3090
3091 coap_option_filter_clear(&opt_filter);
3092 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3093 if (opt) {
3094 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3095 if (!opt) {
3096 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3097 resp = 402;
3098 goto fail_response;
3099 }
3100 is_proxy_scheme = 1;
3101 }
3102
3103 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3104 if (opt)
3105 is_proxy_uri = 1;
3106
3107 if (is_proxy_scheme || is_proxy_uri) {
3108 coap_uri_t uri;
3109
3110 if (!context->proxy_uri_resource) {
3111 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3112 coap_log_debug("Proxy-%s support not configured\n",
3113 is_proxy_scheme ? "Scheme" : "Uri");
3114 resp = 505;
3115 goto fail_response;
3116 }
3117 if (((size_t)pdu->code - 1 <
3118 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3119 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3120 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3121 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3122 is_proxy_scheme ? "Scheme" : "Uri",
3123 pdu->code/100, pdu->code%100);
3124 resp = 505;
3125 goto fail_response;
3126 }
3127
3128 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3129 if (is_proxy_uri) {
3131 coap_opt_length(opt), &uri) < 0) {
3132 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3133 coap_log_debug("Proxy-URI not decodable\n");
3134 resp = 505;
3135 goto fail_response;
3136 }
3137 } else {
3138 memset(&uri, 0, sizeof(uri));
3139 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3140 if (opt) {
3141 uri.host.length = coap_opt_length(opt);
3142 uri.host.s = coap_opt_value(opt);
3143 } else
3144 uri.host.length = 0;
3145 }
3146
3147 resource = context->proxy_uri_resource;
3148 if (uri.host.length && resource->proxy_name_count &&
3149 resource->proxy_name_list) {
3150 size_t i;
3151
3152 if (resource->proxy_name_count == 1 &&
3153 resource->proxy_name_list[0]->length == 0) {
3154 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3155 i = 0;
3156 } else {
3157 for (i = 0; i < resource->proxy_name_count; i++) {
3158 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3159 break;
3160 }
3161 }
3162 }
3163 if (i != resource->proxy_name_count) {
3164 /* This server is hosting the proxy connection endpoint */
3165 if (pdu->crit_opt) {
3166 /* Cannot handle critical option */
3167 pdu->crit_opt = 0;
3168 resp = 402;
3169 goto fail_response;
3170 }
3171 is_proxy_uri = 0;
3172 is_proxy_scheme = 0;
3173 skip_hop_limit_check = 1;
3174 }
3175 }
3176 resource = NULL;
3177 }
3178
3179 if (!skip_hop_limit_check) {
3180 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3181 if (opt) {
3182 size_t hop_limit;
3183 uint8_t buf[4];
3184
3185 hop_limit =
3187 if (hop_limit == 1) {
3188 /* coap_send_internal() will fill in the IP address for us */
3189 resp = 508;
3190 goto fail_response;
3191 } else if (hop_limit < 1 || hop_limit > 255) {
3192 /* Need to return a 4.00 RFC8768 Section 3 */
3193 coap_log_info("Invalid Hop Limit\n");
3194 resp = 400;
3195 goto fail_response;
3196 }
3197 hop_limit--;
3199 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3200 buf);
3201 }
3202 }
3203
3204 uri_path = coap_get_uri_path(pdu);
3205 if (!uri_path)
3206 return;
3207
3208 if (!is_proxy_uri && !is_proxy_scheme) {
3209 /* try to find the resource from the request URI */
3210 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3211 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3212 }
3213
3214 if ((resource == NULL) || (resource->is_unknown == 1) ||
3215 (resource->is_proxy_uri == 1)) {
3216 /* The resource was not found or there is an unexpected match against the
3217 * resource defined for handling unknown or proxy URIs.
3218 */
3219 if (resource != NULL)
3220 /* Close down unexpected match */
3221 resource = NULL;
3222 /*
3223 * Check if the request URI happens to be the well-known URI, or if the
3224 * unknown resource handler is defined, a PUT or optionally other methods,
3225 * if configured, for the unknown handler.
3226 *
3227 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3228 * proxy URI handler.
3229 *
3230 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3231 * set, call the unknown URI handler with any unknown URI (including
3232 * .well-known/core) if the appropriate method is defined.
3233 *
3234 * else if well-known URI generate a default response.
3235 *
3236 * else if unknown URI handler defined, call the unknown
3237 * URI handler (to allow for potential generation of resource
3238 * [RFC7272 5.8.3]) if the appropriate method is defined.
3239 *
3240 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3241 *
3242 * else return 4.04.
3243 */
3244
3245 if (is_proxy_uri || is_proxy_scheme) {
3246 resource = context->proxy_uri_resource;
3247 } else if (context->unknown_resource != NULL &&
3249 ((size_t)pdu->code - 1 <
3250 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3251 (context->unknown_resource->handler[pdu->code - 1])) {
3252 resource = context->unknown_resource;
3253 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3254 /* request for .well-known/core */
3255 resource = &resource_uri_wellknown;
3256 } else if ((context->unknown_resource != NULL) &&
3257 ((size_t)pdu->code - 1 <
3258 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3259 (context->unknown_resource->handler[pdu->code - 1])) {
3260 /*
3261 * The unknown_resource can be used to handle undefined resources
3262 * for a PUT request and can support any other registered handler
3263 * defined for it
3264 * Example set up code:-
3265 * r = coap_resource_unknown_init(hnd_put_unknown);
3266 * coap_register_request_handler(r, COAP_REQUEST_POST,
3267 * hnd_post_unknown);
3268 * coap_register_request_handler(r, COAP_REQUEST_GET,
3269 * hnd_get_unknown);
3270 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3271 * hnd_delete_unknown);
3272 * coap_add_resource(ctx, r);
3273 *
3274 * Note: It is not possible to observe the unknown_resource, a separate
3275 * resource must be created (by PUT or POST) which has a GET
3276 * handler to be observed
3277 */
3278 resource = context->unknown_resource;
3279 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3280 /*
3281 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3282 */
3283 coap_log_debug("request for unknown resource '%*.*s',"
3284 " return 2.02\n",
3285 (int)uri_path->length,
3286 (int)uri_path->length,
3287 uri_path->s);
3288 resp = 202;
3289 goto fail_response;
3290 } else { /* request for any another resource, return 4.04 */
3291
3292 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3293 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3294 resp = 404;
3295 goto fail_response;
3296 }
3297
3298 }
3299
3300#if COAP_OSCORE_SUPPORT
3301 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3302 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3303 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3304 resp = 401;
3305 goto fail_response;
3306 }
3307#endif /* COAP_OSCORE_SUPPORT */
3308 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3309 /* Check for existing resource and If-Non-Match */
3310 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3311 if (opt) {
3312 resp = 412;
3313 goto fail_response;
3314 }
3315 }
3316
3317 /* the resource was found, check if there is a registered handler */
3318 if ((size_t)pdu->code - 1 <
3319 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3320 h = resource->handler[pdu->code - 1];
3321
3322 if (h == NULL) {
3323 resp = 405;
3324 goto fail_response;
3325 }
3326 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3327 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3328 if (opt == NULL) {
3329 /* RFC 8132 2.3.1 */
3330 resp = 415;
3331 goto fail_response;
3332 }
3333 }
3334 if (context->mcast_per_resource &&
3335 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3336 coap_is_mcast(&session->addr_info.local)) {
3337 resp = 405;
3338 goto fail_response;
3339 }
3340
3341 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3343 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3344 if (!response) {
3345 coap_log_err("could not create response PDU\n");
3346 resp = 500;
3347 goto fail_response;
3348 }
3349 response->session = session;
3350#if COAP_ASYNC_SUPPORT
3351 /* If handling a separate response, need CON, not ACK response */
3352 if (async && pdu->type == COAP_MESSAGE_CON)
3353 response->type = COAP_MESSAGE_CON;
3354#endif /* COAP_ASYNC_SUPPORT */
3355 /* A lot of the reliable code assumes type is CON */
3356 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3357 response->type = COAP_MESSAGE_CON;
3358
3359 if (!coap_add_token(response, pdu->actual_token.length,
3360 pdu->actual_token.s)) {
3361 resp = 500;
3362 goto fail_response;
3363 }
3364
3365 query = coap_get_query(pdu);
3366
3367 /* check for Observe option RFC7641 and RFC8132 */
3368 if (resource->observable &&
3369 (pdu->code == COAP_REQUEST_CODE_GET ||
3370 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3371 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3372 }
3373
3374 /*
3375 * See if blocks need to be aggregated or next requests sent off
3376 * before invoking application request handler
3377 */
3378 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3379 uint32_t block_mode = session->block_mode;
3380
3381 if (pdu->code == COAP_REQUEST_CODE_FETCH ||
3384 if (coap_handle_request_put_block(context, session, pdu, response,
3385 resource, uri_path, observe,
3386 &added_block, &free_lg_srcv)) {
3387 session->block_mode = block_mode;
3388 goto skip_handler;
3389 }
3390 session->block_mode = block_mode;
3391
3392 if (coap_handle_request_send_block(session, pdu, response, resource,
3393 query)) {
3394#if COAP_Q_BLOCK_SUPPORT
3395 lg_xmit_ctrl = 1;
3396#endif /* COAP_Q_BLOCK_SUPPORT */
3397 goto skip_handler;
3398 }
3399 }
3400
3401 if (observe) {
3402 observe_action =
3404 coap_opt_length(observe));
3405
3406 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3407 coap_subscription_t *subscription;
3408
3409 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3410 if (block.num != 0) {
3411 response->code = COAP_RESPONSE_CODE(400);
3412 goto skip_handler;
3413 }
3414#if COAP_Q_BLOCK_SUPPORT
3415 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3416 &block)) {
3417 if (block.num != 0) {
3418 response->code = COAP_RESPONSE_CODE(400);
3419 goto skip_handler;
3420 }
3421#endif /* COAP_Q_BLOCK_SUPPORT */
3422 }
3423 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3424 pdu);
3425 if (subscription) {
3426 uint8_t buf[4];
3427
3428 coap_touch_observer(context, session, &pdu->actual_token);
3430 coap_encode_var_safe(buf, sizeof(buf),
3431 resource->observe),
3432 buf);
3433 }
3434 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3435 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3436 } else {
3437 coap_log_info("observe: unexpected action %d\n", observe_action);
3438 }
3439 }
3440
3441 /* TODO for non-proxy requests */
3442 if (resource == context->proxy_uri_resource &&
3443 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3444 pdu->type == COAP_MESSAGE_CON) {
3445 /* Make the proxy response separate and fix response later */
3446 send_early_empty_ack = 1;
3447 }
3448 if (send_early_empty_ack) {
3449 coap_send_ack_lkd(session, pdu);
3450 if (pdu->mid == session->last_con_mid) {
3451 /* request has already been processed - do not process it again */
3452 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3453 pdu->mid);
3454 goto drop_it_no_debug;
3455 }
3456 session->last_con_mid = pdu->mid;
3457 }
3458#if COAP_WITH_OBSERVE_PERSIST
3459 /* If we are maintaining Observe persist */
3460 if (resource == context->unknown_resource) {
3461 context->unknown_pdu = pdu;
3462 context->unknown_session = session;
3463 } else
3464 context->unknown_pdu = NULL;
3465#endif /* COAP_WITH_OBSERVE_PERSIST */
3466
3467 /*
3468 * Call the request handler with everything set up
3469 */
3470 if (resource == &resource_uri_wellknown) {
3471 /* Leave context locked */
3472 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3473 (int)resource->uri_path->length, (int)resource->uri_path->length,
3474 resource->uri_path->s);
3475 h(resource, session, pdu, query, response);
3476 } else {
3477 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3478 (int)resource->uri_path->length, (int)resource->uri_path->length,
3479 resource->uri_path->s);
3481 h(resource, session, pdu, query, response),
3482 /* context is being freed off */
3483 goto finish);
3484 }
3485
3486 /* Check validity of response code */
3487 if (!coap_check_code_class(session, response)) {
3488 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
3489 COAP_RESPONSE_CLASS(response->code),
3490 response->code & 0x1f);
3491 goto drop_it_no_debug;
3492 }
3493
3494 /* Check if lg_xmit generated and update PDU code if so */
3495 coap_check_code_lg_xmit(session, pdu, response, resource, query);
3496
3497 if (free_lg_srcv) {
3498 /* Check to see if the server is doing a 4.01 + Echo response */
3499 if (response->code == COAP_RESPONSE_CODE(401) &&
3500 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3501 /* Need to keep lg_srcv around for client's response */
3502 } else {
3503 LL_DELETE(session->lg_srcv, free_lg_srcv);
3504 coap_block_delete_lg_srcv(session, free_lg_srcv);
3505 }
3506 }
3507 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
3508 /* Just in case, as there are more to go */
3509 response->code = COAP_RESPONSE_CODE(231);
3510 }
3511
3512skip_handler:
3513 if (send_early_empty_ack &&
3514 response->type == COAP_MESSAGE_ACK) {
3515 /* Response is now separate - convert to CON as needed */
3516 response->type = COAP_MESSAGE_CON;
3517 /* Check for empty ACK - need to drop as already sent */
3518 if (response->code == 0) {
3519 goto drop_it_no_debug;
3520 }
3521 }
3522 respond = no_response(pdu, response, session, resource);
3523 if (respond != RESPONSE_DROP) {
3524#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
3525 coap_mid_t mid = pdu->mid;
3526#endif
3527 if (COAP_RESPONSE_CLASS(response->code) != 2) {
3528 if (observe) {
3530 }
3531 }
3532 if (COAP_RESPONSE_CLASS(response->code) > 2) {
3533 if (observe)
3534 coap_delete_observer(resource, session, &pdu->actual_token);
3535 if (response->code != COAP_RESPONSE_CODE(413))
3537 }
3538
3539 /* If original request contained a token, and the registered
3540 * application handler made no changes to the response, then
3541 * this is an empty ACK with a token, which is a malformed
3542 * PDU */
3543 if ((response->type == COAP_MESSAGE_ACK)
3544 && (response->code == 0)) {
3545 /* Remove token from otherwise-empty acknowledgment PDU */
3546 response->actual_token.length = 0;
3547 response->e_token_length = 0;
3548 response->used_size = 0;
3549 response->data = NULL;
3550 }
3551
3552 if (!coap_is_mcast(&session->addr_info.local) ||
3553 (context->mcast_per_resource &&
3554 resource &&
3556 /* No delays to response */
3557#if COAP_Q_BLOCK_SUPPORT
3558 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
3559 !lg_xmit_ctrl && response->code == COAP_RESPONSE_CODE(205) &&
3560 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
3561 block.m) {
3562 if (coap_send_q_block2(session, resource, query, pdu->code, block,
3563 response,
3564 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
3565 coap_log_debug("cannot send response for mid=0x%x\n", mid);
3566 response = NULL;
3567 if (query)
3568 coap_delete_string(query);
3569 goto finish;
3570 }
3571#endif /* COAP_Q_BLOCK_SUPPORT */
3572 if (coap_send_internal(session, response) == COAP_INVALID_MID) {
3573 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
3574 }
3575 } else {
3576 /* Need to delay mcast response */
3577 coap_queue_t *node = coap_new_node();
3578 uint8_t r;
3579 coap_tick_t delay;
3580
3581 if (!node) {
3582 coap_log_debug("mcast delay: insufficient memory\n");
3583 goto drop_it_no_debug;
3584 }
3585 if (!coap_pdu_encode_header(response, session->proto)) {
3587 goto drop_it_no_debug;
3588 }
3589
3590 node->id = response->mid;
3591 node->pdu = response;
3592 node->is_mcast = 1;
3593 coap_prng_lkd(&r, sizeof(r));
3594 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
3595 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
3596 coap_session_str(session),
3597 response->mid,
3598 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
3599 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
3600 1000 / COAP_TICKS_PER_SECOND));
3601 node->timeout = (unsigned int)delay;
3602 /* Use this to delay transmission */
3603 coap_wait_ack(session->context, session, node);
3604 }
3605 } else {
3606 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
3607 coap_session_str(session),
3608 response->mid);
3609 coap_show_pdu(COAP_LOG_DEBUG, response);
3610drop_it_no_debug:
3611 coap_delete_pdu(response);
3612 }
3613 if (query)
3614 coap_delete_string(query);
3615#if COAP_Q_BLOCK_SUPPORT
3616 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
3617 if (COAP_PROTO_RELIABLE(session->proto)) {
3618 if (block.m) {
3619 /* All of the sequence not in yet */
3620 goto finish;
3621 }
3622 } else if (pdu->type == COAP_MESSAGE_NON) {
3623 /* More to go and not at a payload break */
3624 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
3625 goto finish;
3626 }
3627 }
3628 }
3629#endif /* COAP_Q_BLOCK_SUPPORT */
3630
3631#if COAP_Q_BLOCK_SUPPORT || COAP_THREAD_SAFE
3632finish:
3633#endif /* COAP_Q_BLOCK_SUPPORT || COAP_THREAD_SAFE */
3634 coap_delete_string(uri_path);
3635 return;
3636
3637fail_response:
3638 coap_delete_pdu(response);
3639 response =
3641 &opt_filter);
3642 if (response)
3643 goto skip_handler;
3644 coap_delete_string(uri_path);
3645}
3646#endif /* COAP_SERVER_SUPPORT */
3647
3648#if COAP_CLIENT_SUPPORT
3649static void
3650handle_response(coap_context_t *context, coap_session_t *session,
3651 coap_pdu_t *sent, coap_pdu_t *rcvd) {
3652
3653 /* Set in case there is a later call to coap_update_token() */
3654 rcvd->session = session;
3655
3656 /* In a lossy context, the ACK of a separate response may have
3657 * been lost, so we need to stop retransmitting requests with the
3658 * same token. Matching on token potentially containing ext length bytes.
3659 */
3660 if (rcvd->type != COAP_MESSAGE_ACK)
3661 coap_cancel_all_messages(context, session, &rcvd->actual_token);
3662
3663 /* Check for message duplication */
3664 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
3665 if (rcvd->type == COAP_MESSAGE_CON) {
3666 if (rcvd->mid == session->last_con_mid) {
3667 /* Duplicate response: send ACK/RST, but don't process */
3668 if (session->last_con_handler_res == COAP_RESPONSE_OK)
3669 coap_send_ack_lkd(session, rcvd);
3670 else
3671 coap_send_rst_lkd(session, rcvd);
3672 return;
3673 }
3674 session->last_con_mid = rcvd->mid;
3675 } else if (rcvd->type == COAP_MESSAGE_ACK) {
3676 if (rcvd->mid == session->last_ack_mid) {
3677 /* Duplicate response */
3678 return;
3679 }
3680 session->last_ack_mid = rcvd->mid;
3681 }
3682 }
3683 /* Check to see if checking out extended token support */
3684 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
3685 session->remote_test_mid == rcvd->mid) {
3686
3687 if (rcvd->actual_token.length != session->max_token_size ||
3688 rcvd->code == COAP_RESPONSE_CODE(400) ||
3689 rcvd->code == COAP_RESPONSE_CODE(503)) {
3690 coap_log_debug("Extended Token requested size support not available\n");
3692 } else {
3693 coap_log_debug("Extended Token support available\n");
3694 }
3696 session->doing_first = 0;
3697 return;
3698 }
3699#if COAP_Q_BLOCK_SUPPORT
3700 /* Check to see if checking out Q-Block support */
3701 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
3702 session->remote_test_mid == rcvd->mid) {
3703 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
3704 coap_log_debug("Q-Block support not available\n");
3705 set_block_mode_drop_q(session->block_mode);
3706 } else {
3707 coap_block_b_t qblock;
3708
3709 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
3710 coap_log_debug("Q-Block support available\n");
3711 set_block_mode_has_q(session->block_mode);
3712 } else {
3713 coap_log_debug("Q-Block support not available\n");
3714 set_block_mode_drop_q(session->block_mode);
3715 }
3716 }
3717 session->doing_first = 0;
3718 return;
3719 }
3720#endif /* COAP_Q_BLOCK_SUPPORT */
3721
3722 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3723 /* See if need to send next block to server */
3724 if (coap_handle_response_send_block(session, sent, rcvd)) {
3725 /* Next block transmitted, no need to inform app */
3726 coap_send_ack_lkd(session, rcvd);
3727 return;
3728 }
3729
3730 /* Need to see if needing to request next block */
3731 if (coap_handle_response_get_block(context, session, sent, rcvd,
3732 COAP_RECURSE_OK)) {
3733 /* Next block transmitted, ack sent no need to inform app */
3734 return;
3735 }
3736 }
3737 if (session->doing_first)
3738 session->doing_first = 0;
3739
3740 /* Call application-specific response handler when available. */
3741 if (context->response_handler) {
3742 coap_response_t ret;
3743
3744 coap_lock_callback_ret_release(ret, context,
3745 context->response_handler(session, sent, rcvd,
3746 rcvd->mid),
3747 /* context is being freed off */
3748 return);
3749 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
3750 coap_send_rst_lkd(session, rcvd);
3752 } else {
3753 coap_send_ack_lkd(session, rcvd);
3755 }
3756 } else {
3757 coap_send_ack_lkd(session, rcvd);
3759 }
3760}
3761#endif /* COAP_CLIENT_SUPPORT */
3762
3763#if !COAP_DISABLE_TCP
3764static void
3766 coap_pdu_t *pdu) {
3767 coap_opt_iterator_t opt_iter;
3768 coap_opt_t *option;
3769 int set_mtu = 0;
3770
3771 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
3772
3773 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
3774 if (session->csm_not_seen) {
3775 coap_tick_t now;
3776
3777 coap_ticks(&now);
3778 /* CSM timeout before CSM seen */
3779 coap_log_warn("***%s: CSM received after CSM timeout\n",
3780 coap_session_str(session));
3781 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
3782 coap_session_str(session),
3783 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
3784 }
3785 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
3787 }
3788 while ((option = coap_option_next(&opt_iter))) {
3791 coap_opt_length(option)));
3792 set_mtu = 1;
3793 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
3794 session->csm_block_supported = 1;
3795 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
3796 session->max_token_size =
3798 coap_opt_length(option));
3801 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
3804 }
3805 }
3806 if (set_mtu) {
3807 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
3808 session->csm_bert_rem_support = 1;
3809 else
3810 session->csm_bert_rem_support = 0;
3811 }
3812 if (session->state == COAP_SESSION_STATE_CSM)
3813 coap_session_connected(session);
3814 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
3816 if (context->ping_handler) {
3817 coap_lock_callback(context,
3818 context->ping_handler(session, pdu, pdu->mid));
3819 }
3820 if (pong) {
3822 coap_send_internal(session, pong);
3823 }
3824 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
3825 session->last_pong = session->last_rx_tx;
3826 if (context->pong_handler) {
3827 coap_lock_callback(context,
3828 context->pong_handler(session, pdu, pdu->mid));
3829 }
3830 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
3831 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
3833 }
3834}
3835#endif /* !COAP_DISABLE_TCP */
3836
3837static int
3839 if (COAP_PDU_IS_REQUEST(pdu) &&
3840 pdu->actual_token.length >
3841 (session->type == COAP_SESSION_TYPE_CLIENT ?
3842 session->max_token_size : session->context->max_token_size)) {
3843 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
3844 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
3845 coap_opt_filter_t opt_filter;
3846 coap_pdu_t *response;
3847
3848 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
3849 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
3850 &opt_filter);
3851 if (!response) {
3852 coap_log_warn("coap_dispatch: cannot create error response\n");
3853 } else {
3854 /*
3855 * Note - have to leave in oversize token as per
3856 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
3857 */
3858 if (coap_send_internal(session, response) == COAP_INVALID_MID)
3859 coap_log_warn("coap_dispatch: error sending response\n");
3860 }
3861 } else {
3862 /* Indicate no extended token support */
3863 coap_send_rst_lkd(session, pdu);
3864 }
3865 return 0;
3866 }
3867 return 1;
3868}
3869
3870void
3872 coap_pdu_t *pdu) {
3873 coap_queue_t *sent = NULL;
3874 coap_pdu_t *response;
3875 coap_opt_filter_t opt_filter;
3876 int is_ping_rst;
3877 int packet_is_bad = 0;
3878#if COAP_OSCORE_SUPPORT
3879 coap_opt_iterator_t opt_iter;
3880 coap_pdu_t *dec_pdu = NULL;
3881#endif /* COAP_OSCORE_SUPPORT */
3882 int is_ext_token_rst;
3883
3884 pdu->session = session;
3886
3887 /* Check validity of received code */
3888 if (!coap_check_code_class(session, pdu)) {
3889 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
3891 pdu->code & 0x1f);
3892 packet_is_bad = 1;
3893 if (pdu->type == COAP_MESSAGE_CON) {
3895 }
3896 /* find message id in sendqueue to stop retransmission */
3897 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3898 goto cleanup;
3899 }
3900
3901 coap_option_filter_clear(&opt_filter);
3902
3903#if COAP_OSCORE_SUPPORT
3904 if (!COAP_PDU_IS_SIGNALING(pdu) &&
3905 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3906 if (pdu->type == COAP_MESSAGE_NON) {
3907 coap_send_rst_lkd(session, pdu);
3908 goto cleanup;
3909 } else if (pdu->type == COAP_MESSAGE_CON) {
3910 if (COAP_PDU_IS_REQUEST(pdu)) {
3911 response =
3912 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
3913
3914 if (!response) {
3915 coap_log_warn("coap_dispatch: cannot create error response\n");
3916 } else {
3917 if (coap_send_internal(session, response) == COAP_INVALID_MID)
3918 coap_log_warn("coap_dispatch: error sending response\n");
3919 }
3920 } else {
3921 coap_send_rst_lkd(session, pdu);
3922 }
3923 }
3924 goto cleanup;
3925 }
3926
3927 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
3928 int decrypt = 1;
3929#if COAP_SERVER_SUPPORT
3930 coap_opt_t *opt;
3931 coap_resource_t *resource;
3932 coap_uri_t uri;
3933#endif /* COAP_SERVER_SUPPORT */
3934
3935 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
3936 decrypt = 0;
3937
3938#if COAP_SERVER_SUPPORT
3939 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
3940 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
3941 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
3942 != NULL) {
3943 /* Need to check whether this is a direct or proxy session */
3944 memset(&uri, 0, sizeof(uri));
3945 uri.host.length = coap_opt_length(opt);
3946 uri.host.s = coap_opt_value(opt);
3947 resource = context->proxy_uri_resource;
3948 if (uri.host.length && resource && resource->proxy_name_count &&
3949 resource->proxy_name_list) {
3950 size_t i;
3951 for (i = 0; i < resource->proxy_name_count; i++) {
3952 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3953 break;
3954 }
3955 }
3956 if (i == resource->proxy_name_count) {
3957 /* This server is not hosting the proxy connection endpoint */
3958 decrypt = 0;
3959 }
3960 }
3961 }
3962#endif /* COAP_SERVER_SUPPORT */
3963 if (decrypt) {
3964 /* find message id in sendqueue to stop retransmission and get sent */
3965 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3966 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
3967 if (session->recipient_ctx == NULL ||
3968 session->recipient_ctx->initial_state == 0) {
3969 coap_log_warn("OSCORE: PDU could not be decrypted\n");
3970 }
3972 return;
3973 } else {
3974 session->oscore_encryption = 1;
3975 pdu = dec_pdu;
3976 }
3977 coap_log_debug("Decrypted PDU\n");
3979 }
3980 }
3981#endif /* COAP_OSCORE_SUPPORT */
3982
3983 switch (pdu->type) {
3984 case COAP_MESSAGE_ACK:
3985 /* find message id in sendqueue to stop retransmission */
3986 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3987
3988 if (sent && session->con_active) {
3989 session->con_active--;
3990 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3991 /* Flush out any entries on session->delayqueue */
3992 coap_session_connected(session);
3993 }
3994 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3995 packet_is_bad = 1;
3996 goto cleanup;
3997 }
3998
3999#if COAP_SERVER_SUPPORT
4000 /* if sent code was >= 64 the message might have been a
4001 * notification. Then, we must flag the observer to be alive
4002 * by setting obs->fail_cnt = 0. */
4003 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4004 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4005 }
4006#endif /* COAP_SERVER_SUPPORT */
4007
4008 if (pdu->code == 0) {
4009#if COAP_Q_BLOCK_SUPPORT
4010 if (sent) {
4011 coap_block_b_t block;
4012
4013 if (sent->pdu->type == COAP_MESSAGE_CON &&
4014 COAP_PROTO_NOT_RELIABLE(session->proto) &&
4015 coap_get_block_b(session, sent->pdu,
4016 COAP_PDU_IS_REQUEST(sent->pdu) ?
4018 &block)) {
4019 if (block.m) {
4020#if COAP_CLIENT_SUPPORT
4021 if (COAP_PDU_IS_REQUEST(sent->pdu))
4022 coap_send_q_block1(session, block, sent->pdu,
4023 COAP_SEND_SKIP_PDU);
4024#endif /* COAP_CLIENT_SUPPORT */
4025 if (COAP_PDU_IS_RESPONSE(sent->pdu))
4026 coap_send_q_blocks(session, sent->pdu->lg_xmit, block,
4027 sent->pdu, COAP_SEND_SKIP_PDU);
4028 }
4029 }
4030 }
4031#endif /* COAP_Q_BLOCK_SUPPORT */
4032#if COAP_CLIENT_SUPPORT
4033 /*
4034 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4035 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4036 * response if the response was piggy-backed. Here, a separate response
4037 * detected and so the lg_crcv needs to be set up before the sent PDU
4038 * information is lost.
4039 *
4040 * lg_crcv was not set up if not a CoAP request or if DELETE.
4041 *
4042 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4043 * options.
4044 */
4045 if (sent &&
4046 !coap_check_send_need_lg_crcv(session, pdu) &&
4047 COAP_PDU_IS_REQUEST(sent->pdu)) {
4048 /*
4049 * lg_crcv was not set up in coap_send(). It could have been set up
4050 * the first separate response.
4051 * See if there already is a lg_crcv set up.
4052 */
4053 coap_lg_crcv_t *lg_crcv;
4054 uint64_t token_match =
4056 sent->pdu->actual_token.length));
4057
4058 LL_FOREACH(session->lg_crcv, lg_crcv) {
4059 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4060 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4061 break;
4062 }
4063 }
4064 if (!lg_crcv) {
4065 /*
4066 * Need to set up a lg_crcv as it was not set up in coap_send()
4067 * to save time, but server has not sent back a piggy-back response.
4068 */
4069 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4070 if (lg_crcv) {
4071 LL_PREPEND(session->lg_crcv, lg_crcv);
4072 }
4073 }
4074 }
4075#endif /* COAP_CLIENT_SUPPORT */
4076 /* an empty ACK needs no further handling */
4077 goto cleanup;
4078 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4079 /* This is not legitimate - Request using ACK - ignore */
4080 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4082 pdu->code & 0x1f);
4083 packet_is_bad = 1;
4084 goto cleanup;
4085 }
4086
4087 break;
4088
4089 case COAP_MESSAGE_RST:
4090 /* We have sent something the receiver disliked, so we remove
4091 * not only the message id but also the subscriptions we might
4092 * have. */
4093 is_ping_rst = 0;
4094 if (pdu->mid == session->last_ping_mid &&
4095 context->ping_timeout && session->last_ping > 0)
4096 is_ping_rst = 1;
4097
4098#if COAP_Q_BLOCK_SUPPORT
4099 /* Check to see if checking out Q-Block support */
4100 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4101 session->remote_test_mid == pdu->mid) {
4102 coap_log_debug("Q-Block support not available\n");
4103 set_block_mode_drop_q(session->block_mode);
4104 }
4105#endif /* COAP_Q_BLOCK_SUPPORT */
4106
4107 /* Check to see if checking out extended token support */
4108 is_ext_token_rst = 0;
4109 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4110 session->remote_test_mid == pdu->mid) {
4111 coap_log_debug("Extended Token support not available\n");
4114 session->doing_first = 0;
4115 is_ext_token_rst = 1;
4116 }
4117
4118 if (!is_ping_rst && !is_ext_token_rst)
4119 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4120
4121 if (session->con_active) {
4122 session->con_active--;
4123 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4124 /* Flush out any entries on session->delayqueue */
4125 coap_session_connected(session);
4126 }
4127
4128 /* find message id in sendqueue to stop retransmission */
4129 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4130
4131 if (sent) {
4132 coap_cancel(context, sent);
4133
4134 if (!is_ping_rst && !is_ext_token_rst) {
4135 if (sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler) {
4136 coap_check_update_token(sent->session, sent->pdu);
4137 coap_lock_callback(context,
4138 context->nack_handler(sent->session, sent->pdu,
4139 COAP_NACK_RST, sent->id));
4140 }
4141 } else if (is_ping_rst) {
4142 if (context->pong_handler) {
4143 coap_lock_callback(context,
4144 context->pong_handler(session, pdu, pdu->mid));
4145 }
4146 session->last_pong = session->last_rx_tx;
4148 }
4149 } else {
4150#if COAP_SERVER_SUPPORT
4151 /* Need to check is there is a subscription active and delete it */
4152 RESOURCES_ITER(context->resources, r) {
4153 coap_subscription_t *obs, *tmp;
4154 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4155 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4156 /* Need to do this now as session may get de-referenced */
4158 coap_delete_observer(r, session, &obs->pdu->actual_token);
4159 if (context->nack_handler) {
4160 coap_lock_callback(context,
4161 context->nack_handler(session, NULL,
4162 COAP_NACK_RST, pdu->mid));
4163 }
4164 coap_session_release_lkd(session);
4165 goto cleanup;
4166 }
4167 }
4168 }
4169#endif /* COAP_SERVER_SUPPORT */
4170 if (context->nack_handler) {
4171 coap_lock_callback(context,
4172 context->nack_handler(session, NULL, COAP_NACK_RST, pdu->mid));
4173 }
4174 }
4175 goto cleanup;
4176
4177 case COAP_MESSAGE_NON:
4178 /* find transaction in sendqueue in case large response */
4179 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4180 /* check for unknown critical options */
4181 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4182 packet_is_bad = 1;
4183 coap_send_rst_lkd(session, pdu);
4184 goto cleanup;
4185 }
4186 if (!check_token_size(session, pdu)) {
4187 goto cleanup;
4188 }
4189 break;
4190
4191 case COAP_MESSAGE_CON: /* check for unknown critical options */
4192 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4193 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4194 packet_is_bad = 1;
4195 if (COAP_PDU_IS_REQUEST(pdu)) {
4196 response =
4197 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4198
4199 if (!response) {
4200 coap_log_warn("coap_dispatch: cannot create error response\n");
4201 } else {
4202 if (coap_send_internal(session, response) == COAP_INVALID_MID)
4203 coap_log_warn("coap_dispatch: error sending response\n");
4204 }
4205 } else {
4206 coap_send_rst_lkd(session, pdu);
4207 }
4208 goto cleanup;
4209 }
4210 if (!check_token_size(session, pdu)) {
4211 goto cleanup;
4212 }
4213 break;
4214 default:
4215 break;
4216 }
4217
4218 /* Pass message to upper layer if a specific handler was
4219 * registered for a request that should be handled locally. */
4220#if !COAP_DISABLE_TCP
4221 if (COAP_PDU_IS_SIGNALING(pdu))
4222 handle_signaling(context, session, pdu);
4223 else
4224#endif /* !COAP_DISABLE_TCP */
4225#if COAP_SERVER_SUPPORT
4226 if (COAP_PDU_IS_REQUEST(pdu))
4227 handle_request(context, session, pdu);
4228 else
4229#endif /* COAP_SERVER_SUPPORT */
4230#if COAP_CLIENT_SUPPORT
4231 if (COAP_PDU_IS_RESPONSE(pdu))
4232 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4233 else
4234#endif /* COAP_CLIENT_SUPPORT */
4235 {
4236 if (COAP_PDU_IS_EMPTY(pdu)) {
4237 if (context->ping_handler) {
4238 coap_lock_callback(context,
4239 context->ping_handler(session, pdu, pdu->mid));
4240 }
4241 } else {
4242 packet_is_bad = 1;
4243 }
4244 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4246 pdu->code & 0x1f);
4247
4248 if (!coap_is_mcast(&session->addr_info.local)) {
4249 if (COAP_PDU_IS_EMPTY(pdu)) {
4250 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4251 coap_tick_t now;
4252 coap_ticks(&now);
4253 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4255 session->last_tx_rst = now;
4256 }
4257 }
4258 } else {
4259 if (pdu->type == COAP_MESSAGE_CON)
4261 }
4262 }
4263 }
4264
4265cleanup:
4266 if (packet_is_bad) {
4267 if (sent) {
4268 if (context->nack_handler) {
4269 coap_check_update_token(session, sent->pdu);
4270 coap_lock_callback(context,
4271 context->nack_handler(session, sent->pdu,
4272 COAP_NACK_BAD_RESPONSE, sent->id));
4273 }
4274 } else {
4276 }
4277 }
4279#if COAP_OSCORE_SUPPORT
4280 coap_delete_pdu(dec_pdu);
4281#endif /* COAP_OSCORE_SUPPORT */
4282}
4283
4284#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4285static const char *
4287 switch (event) {
4289 return "COAP_EVENT_DTLS_CLOSED";
4291 return "COAP_EVENT_DTLS_CONNECTED";
4293 return "COAP_EVENT_DTLS_RENEGOTIATE";
4295 return "COAP_EVENT_DTLS_ERROR";
4297 return "COAP_EVENT_TCP_CONNECTED";
4299 return "COAP_EVENT_TCP_CLOSED";
4301 return "COAP_EVENT_TCP_FAILED";
4303 return "COAP_EVENT_SESSION_CONNECTED";
4305 return "COAP_EVENT_SESSION_CLOSED";
4307 return "COAP_EVENT_SESSION_FAILED";
4309 return "COAP_EVENT_PARTIAL_BLOCK";
4311 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4313 return "COAP_EVENT_SERVER_SESSION_NEW";
4315 return "COAP_EVENT_SERVER_SESSION_DEL";
4317 return "COAP_EVENT_BAD_PACKET";
4319 return "COAP_EVENT_MSG_RETRANSMITTED";
4321 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4323 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4325 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4327 return "COAP_EVENT_OSCORE_NO_SECURITY";
4329 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4331 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4333 return "COAP_EVENT_WS_PACKET_SIZE";
4335 return "COAP_EVENT_WS_CONNECTED";
4337 return "COAP_EVENT_WS_CLOSED";
4339 return "COAP_EVENT_KEEPALIVE_FAILURE";
4340 default:
4341 return "???";
4342 }
4343}
4344#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4345
4346COAP_API int
4348 coap_session_t *session) {
4349 int ret;
4350
4351 coap_lock_lock(context, return 0);
4352 ret = coap_handle_event_lkd(context, event, session);
4353 coap_lock_unlock(context);
4354 return ret;
4355}
4356
4357int
4359 coap_session_t *session) {
4360 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
4361
4362 if (context->handle_event) {
4363 int ret;
4364
4365 coap_lock_callback_ret(ret, context, context->handle_event(session, event));
4366#if COAP_PROXY_SUPPORT
4367 if (event == COAP_EVENT_SERVER_SESSION_DEL)
4369#endif /* COAP_PROXY_SUPPORT */
4370 return ret;
4371 }
4372 return 0;
4373}
4374
4375COAP_API int
4377 int ret;
4378
4379 coap_lock_lock(context, return 0);
4380 ret = coap_can_exit_lkd(context);
4381 coap_lock_unlock(context);
4382 return ret;
4383}
4384
4385int
4387 coap_session_t *s, *rtmp;
4388 if (!context)
4389 return 1;
4390 coap_lock_check_locked(context);
4391 if (context->sendqueue)
4392 return 0;
4393#if COAP_SERVER_SUPPORT
4394 coap_endpoint_t *ep;
4395
4396 LL_FOREACH(context->endpoint, ep) {
4397 SESSIONS_ITER(ep->sessions, s, rtmp) {
4398 if (s->delayqueue)
4399 return 0;
4400 if (s->lg_xmit)
4401 return 0;
4402 }
4403 }
4404#endif /* COAP_SERVER_SUPPORT */
4405#if COAP_CLIENT_SUPPORT
4406 SESSIONS_ITER(context->sessions, s, rtmp) {
4407 if (s->delayqueue)
4408 return 0;
4409 if (s->lg_xmit)
4410 return 0;
4411 }
4412#endif /* COAP_CLIENT_SUPPORT */
4413 return 1;
4414}
4415#if COAP_SERVER_SUPPORT
4416#if COAP_ASYNC_SUPPORT
4418coap_check_async(coap_context_t *context, coap_tick_t now) {
4419 coap_tick_t next_due = 0;
4420 coap_async_t *async, *tmp;
4421
4422 LL_FOREACH_SAFE(context->async_state, async, tmp) {
4423 if (async->delay != 0 && async->delay <= now) {
4424 /* Send off the request to the application */
4425 handle_request(context, async->session, async->pdu);
4426
4427 /* Remove this async entry as it has now fired */
4428 coap_free_async_lkd(async->session, async);
4429 } else {
4430 if (next_due == 0 || next_due > async->delay - now)
4431 next_due = async->delay - now;
4432 }
4433 }
4434 return next_due;
4435}
4436#endif /* COAP_ASYNC_SUPPORT */
4437#endif /* COAP_SERVER_SUPPORT */
4438
4440
4441#if COAP_THREAD_SAFE
4442/*
4443 * Global lock for multi-thread support
4444 */
4445coap_lock_t global_lock;
4446#endif /* COAP_THREAD_SAFE */
4447
4448void
4450 coap_tick_t now;
4451#ifndef WITH_CONTIKI
4452 uint64_t us;
4453#endif /* !WITH_CONTIKI */
4454
4455 if (coap_started)
4456 return;
4457 coap_started = 1;
4458
4459#if COAP_THREAD_SAFE
4461#endif /* COAP_THREAD_SAFE */
4462
4463#if defined(HAVE_WINSOCK2_H)
4464 WORD wVersionRequested = MAKEWORD(2, 2);
4465 WSADATA wsaData;
4466 WSAStartup(wVersionRequested, &wsaData);
4467#endif
4469 coap_ticks(&now);
4470#ifndef WITH_CONTIKI
4471 us = coap_ticks_to_rt_us(now);
4472 /* Be accurate to the nearest (approx) us */
4473 coap_prng_init_lkd((unsigned int)us);
4474#else /* WITH_CONTIKI */
4475 coap_start_io_process();
4476#endif /* WITH_CONTIKI */
4479#ifdef WITH_LWIP
4480 coap_io_lwip_init();
4481#endif /* WITH_LWIP */
4482#if COAP_SERVER_SUPPORT
4483 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
4484 (const uint8_t *)".well-known/core"
4485 };
4486 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
4487 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
4488 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
4489 resource_uri_wellknown.uri_path = &well_known;
4490#endif /* COAP_SERVER_SUPPORT */
4491}
4492
4493void
4495 if (!coap_started)
4496 return;
4497 coap_started = 0;
4498#if defined(HAVE_WINSOCK2_H)
4499 WSACleanup();
4500#elif defined(WITH_CONTIKI)
4501 coap_stop_io_process();
4502#endif
4503#ifdef WITH_LWIP
4504 coap_io_lwip_cleanup();
4505#endif /* WITH_LWIP */
4507
4509}
4510
4511void
4513 coap_response_handler_t handler) {
4514#if COAP_CLIENT_SUPPORT
4515 context->response_handler = handler;
4516#else /* ! COAP_CLIENT_SUPPORT */
4517 (void)context;
4518 (void)handler;
4519#endif /* COAP_CLIENT_SUPPORT */
4520}
4521
4522void
4524 coap_nack_handler_t handler) {
4525 context->nack_handler = handler;
4526}
4527
4528void
4530 coap_ping_handler_t handler) {
4531 context->ping_handler = handler;
4532}
4533
4534void
4536 coap_pong_handler_t handler) {
4537 context->pong_handler = handler;
4538}
4539
4540COAP_API void
4542 coap_lock_lock(ctx, return);
4543 coap_register_option_lkd(ctx, type);
4544 coap_lock_unlock(ctx);
4545}
4546
4547void
4550}
4551
4552#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
4553#if COAP_SERVER_SUPPORT
4554COAP_API int
4555coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
4556 const char *ifname) {
4557 int ret;
4558
4559 coap_lock_lock(ctx, return -1);
4560 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
4561 coap_lock_unlock(ctx);
4562 return ret;
4563}
4564
4565int
4566coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
4567 const char *ifname) {
4568#if COAP_IPV4_SUPPORT
4569 struct ip_mreq mreq4;
4570#endif /* COAP_IPV4_SUPPORT */
4571#if COAP_IPV6_SUPPORT
4572 struct ipv6_mreq mreq6;
4573#endif /* COAP_IPV6_SUPPORT */
4574 struct addrinfo *resmulti = NULL, hints, *ainfo;
4575 int result = -1;
4576 coap_endpoint_t *endpoint;
4577 int mgroup_setup = 0;
4578
4579 /* Need to have at least one endpoint! */
4580 assert(ctx->endpoint);
4581 if (!ctx->endpoint)
4582 return -1;
4583
4584 /* Default is let the kernel choose */
4585#if COAP_IPV6_SUPPORT
4586 mreq6.ipv6mr_interface = 0;
4587#endif /* COAP_IPV6_SUPPORT */
4588#if COAP_IPV4_SUPPORT
4589 mreq4.imr_interface.s_addr = INADDR_ANY;
4590#endif /* COAP_IPV4_SUPPORT */
4591
4592 memset(&hints, 0, sizeof(hints));
4593 hints.ai_socktype = SOCK_DGRAM;
4594
4595 /* resolve the multicast group address */
4596 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
4597
4598 if (result != 0) {
4599 coap_log_err("coap_join_mcast_group_intf: %s: "
4600 "Cannot resolve multicast address: %s\n",
4601 group_name, gai_strerror(result));
4602 goto finish;
4603 }
4604
4605 /* Need to do a windows equivalent at some point */
4606#ifndef _WIN32
4607 if (ifname) {
4608 /* interface specified - check if we have correct IPv4/IPv6 information */
4609 int done_ip4 = 0;
4610 int done_ip6 = 0;
4611#if defined(ESPIDF_VERSION)
4612 struct netif *netif;
4613#else /* !ESPIDF_VERSION */
4614#if COAP_IPV4_SUPPORT
4615 int ip4fd;
4616#endif /* COAP_IPV4_SUPPORT */
4617 struct ifreq ifr;
4618#endif /* !ESPIDF_VERSION */
4619
4620 /* See which mcast address family types are being asked for */
4621 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
4622 ainfo = ainfo->ai_next) {
4623 switch (ainfo->ai_family) {
4624#if COAP_IPV6_SUPPORT
4625 case AF_INET6:
4626 if (done_ip6)
4627 break;
4628 done_ip6 = 1;
4629#if defined(ESPIDF_VERSION)
4630 netif = netif_find(ifname);
4631 if (netif)
4632 mreq6.ipv6mr_interface = netif_get_index(netif);
4633 else
4634 coap_log_err("coap_join_mcast_group_intf: %s: "
4635 "Cannot get IPv4 address: %s\n",
4636 ifname, coap_socket_strerror());
4637#else /* !ESPIDF_VERSION */
4638 memset(&ifr, 0, sizeof(ifr));
4639 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
4640 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
4641
4642#ifdef HAVE_IF_NAMETOINDEX
4643 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
4644 if (mreq6.ipv6mr_interface == 0) {
4645 coap_log_warn("coap_join_mcast_group_intf: "
4646 "cannot get interface index for '%s'\n",
4647 ifname);
4648 }
4649#elif defined(__QNXNTO__)
4650#else /* !HAVE_IF_NAMETOINDEX */
4651 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
4652 if (result != 0) {
4653 coap_log_warn("coap_join_mcast_group_intf: "
4654 "cannot get interface index for '%s': %s\n",
4655 ifname, coap_socket_strerror());
4656 } else {
4657 /* Capture the IPv6 if_index for later */
4658 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
4659 }
4660#endif /* !HAVE_IF_NAMETOINDEX */
4661#endif /* !ESPIDF_VERSION */
4662#endif /* COAP_IPV6_SUPPORT */
4663 break;
4664#if COAP_IPV4_SUPPORT
4665 case AF_INET:
4666 if (done_ip4)
4667 break;
4668 done_ip4 = 1;
4669#if defined(ESPIDF_VERSION)
4670 netif = netif_find(ifname);
4671 if (netif)
4672 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
4673 else
4674 coap_log_err("coap_join_mcast_group_intf: %s: "
4675 "Cannot get IPv4 address: %s\n",
4676 ifname, coap_socket_strerror());
4677#else /* !ESPIDF_VERSION */
4678 /*
4679 * Need an AF_INET socket to do this unfortunately to stop
4680 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
4681 */
4682 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
4683 if (ip4fd == -1) {
4684 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
4685 ifname, coap_socket_strerror());
4686 continue;
4687 }
4688 memset(&ifr, 0, sizeof(ifr));
4689 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
4690 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
4691 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
4692 if (result != 0) {
4693 coap_log_err("coap_join_mcast_group_intf: %s: "
4694 "Cannot get IPv4 address: %s\n",
4695 ifname, coap_socket_strerror());
4696 } else {
4697 /* Capture the IPv4 address for later */
4698 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
4699 }
4700 close(ip4fd);
4701#endif /* !ESPIDF_VERSION */
4702 break;
4703#endif /* COAP_IPV4_SUPPORT */
4704 default:
4705 break;
4706 }
4707 }
4708 }
4709#endif /* ! _WIN32 */
4710
4711 /* Add in mcast address(es) to appropriate interface */
4712 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
4713 LL_FOREACH(ctx->endpoint, endpoint) {
4714 /* Only UDP currently supported */
4715 if (endpoint->proto == COAP_PROTO_UDP) {
4716 coap_address_t gaddr;
4717
4718 coap_address_init(&gaddr);
4719#if COAP_IPV6_SUPPORT
4720 if (ainfo->ai_family == AF_INET6) {
4721 if (!ifname) {
4722 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
4723 /*
4724 * Do it on the ifindex that the server is listening on
4725 * (sin6_scope_id could still be 0)
4726 */
4727 mreq6.ipv6mr_interface =
4728 endpoint->bind_addr.addr.sin6.sin6_scope_id;
4729 } else {
4730 mreq6.ipv6mr_interface = 0;
4731 }
4732 }
4733 gaddr.addr.sin6.sin6_family = AF_INET6;
4734 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
4735 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
4736 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
4737 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
4738 (char *)&mreq6, sizeof(mreq6));
4739 }
4740#endif /* COAP_IPV6_SUPPORT */
4741#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
4742 else
4743#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
4744#if COAP_IPV4_SUPPORT
4745 if (ainfo->ai_family == AF_INET) {
4746 if (!ifname) {
4747 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
4748 /*
4749 * Do it on the interface that the server is listening on
4750 * (sin_addr could still be INADDR_ANY)
4751 */
4752 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
4753 } else {
4754 mreq4.imr_interface.s_addr = INADDR_ANY;
4755 }
4756 }
4757 gaddr.addr.sin.sin_family = AF_INET;
4758 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
4759 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
4760 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
4761 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4762 (char *)&mreq4, sizeof(mreq4));
4763 }
4764#endif /* COAP_IPV4_SUPPORT */
4765 else {
4766 continue;
4767 }
4768
4769 if (result == COAP_SOCKET_ERROR) {
4770 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
4771 group_name, coap_socket_strerror());
4772 } else {
4773 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
4774
4775 addr_str[sizeof(addr_str)-1] = '\000';
4776 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
4777 sizeof(addr_str) - 1)) {
4778 if (ifname)
4779 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
4780 ifname);
4781 else
4782 coap_log_debug("added mcast group %s\n", addr_str);
4783 }
4784 mgroup_setup = 1;
4785 }
4786 }
4787 }
4788 }
4789 if (!mgroup_setup) {
4790 result = -1;
4791 }
4792
4793finish:
4794 freeaddrinfo(resmulti);
4795
4796 return result;
4797}
4798
4799void
4801 context->mcast_per_resource = 1;
4802}
4803
4804#endif /* ! COAP_SERVER_SUPPORT */
4805
4806#if COAP_CLIENT_SUPPORT
4807int
4808coap_mcast_set_hops(coap_session_t *session, size_t hops) {
4809 if (session && coap_is_mcast(&session->addr_info.remote)) {
4810 switch (session->addr_info.remote.addr.sa.sa_family) {
4811#if COAP_IPV4_SUPPORT
4812 case AF_INET:
4813 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
4814 (const char *)&hops, sizeof(hops)) < 0) {
4815 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
4816 hops, coap_socket_strerror());
4817 return 0;
4818 }
4819 return 1;
4820#endif /* COAP_IPV4_SUPPORT */
4821#if COAP_IPV6_SUPPORT
4822 case AF_INET6:
4823 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
4824 (const char *)&hops, sizeof(hops)) < 0) {
4825 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
4826 hops, coap_socket_strerror());
4827 return 0;
4828 }
4829 return 1;
4830#endif /* COAP_IPV6_SUPPORT */
4831 default:
4832 break;
4833 }
4834 }
4835 return 0;
4836}
4837#endif /* COAP_CLIENT_SUPPORT */
4838
4839#else /* defined WITH_CONTIKI || defined WITH_LWIP */
4840COAP_API int
4842 const char *group_name COAP_UNUSED,
4843 const char *ifname COAP_UNUSED) {
4844 return -1;
4845}
4846
4847int
4849 size_t hops COAP_UNUSED) {
4850 return 0;
4851}
4852
4853void
4855}
4856#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.
struct coap_async_t coap_async_t
Async Entry information.
#define PRIu32
const char * coap_socket_strerror(void)
Definition coap_io.c:1900
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:1008
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:504
#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:4494
#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:4286
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:2866
int coap_started
Definition coap_net.c:4439
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2011
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2052
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:3765
#define min(a, b)
Definition coap_net.c:73
void coap_startup(void)
Definition coap_net.c:4449
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:3838
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
#define INET6_ADDRSTRLEN
Definition coap_net.c:69
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:2378
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:2313
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1591
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:1252
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:2367
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:2306
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:4548
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:4358
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:2528
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:3871
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:4386
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:1908
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:2573
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:2483
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:2616
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:4512
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:2649
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:4541
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:4529
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:4376
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:4535
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:4347
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:4523
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:326
#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:318
@ COAP_PROTO_DTLS
Definition coap_pdu.h:315
@ COAP_PROTO_UDP
Definition coap_pdu.h:314
@ COAP_PROTO_WSS
Definition coap_pdu.h:319
@ COAP_SIGNALING_CODE_ABORT
Definition coap_pdu.h:369
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:365
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:366
@ COAP_REQUEST_CODE_DELETE
Definition coap_pdu.h:332
@ COAP_SIGNALING_CODE_PONG
Definition coap_pdu.h:367
@ COAP_EMPTY_CODE
Definition coap_pdu.h:327
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:329
@ COAP_SIGNALING_CODE_RELEASE
Definition coap_pdu.h:368
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:333
@ 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:2080
#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:985
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:276
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:934
#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
struct sockaddr_in6 sin6
struct sockaddr sa
union coap_address_t::@0 addr
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.
union coap_lg_xmit_t::@1 b
coap_pdu_t pdu
skeletal PDU
coap_l_block1_t b1
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