libcoap 4.3.2rc2

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