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