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