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