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