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