libcoap 4.3.5-develop-17c3fee
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
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(return 0);
221 ret = coap_delete_node_lkd(node);
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(return 0);
356 ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
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(return 0);
388 ret = coap_context_set_psk2_lkd(ctx, setup_data);
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(return 0);
413 ret = coap_context_set_pki_lkd(ctx, setup_data);
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(return 0);
442 ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
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
457COAP_API int
459 int ret;
460
461 coap_lock_lock(return 0);
464 return ret;
465}
466
467int
474
475
476void
477coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
478 context->ping_timeout = seconds;
479}
480
481int
483#if COAP_CLIENT_SUPPORT
484 return coap_dtls_set_cid_tuple_change(context, every);
485#else /* ! COAP_CLIENT_SUPPORT */
486 (void)context;
487 (void)every;
488 return 0;
489#endif /* ! COAP_CLIENT_SUPPORT */
490}
491
492void
494 size_t max_token_size) {
495 assert(max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
496 max_token_size <= COAP_TOKEN_EXT_MAX);
497 context->max_token_size = (uint32_t)max_token_size;
498}
499
500void
502 unsigned int max_idle_sessions) {
503 context->max_idle_sessions = max_idle_sessions;
504}
505
506unsigned int
508 return context->max_idle_sessions;
509}
510
511void
513 unsigned int max_handshake_sessions) {
514 context->max_handshake_sessions = max_handshake_sessions;
515}
516
517unsigned int
521
522static unsigned int s_csm_timeout = 30;
523
524void
526 unsigned int csm_timeout) {
527 s_csm_timeout = csm_timeout;
528 coap_context_set_csm_timeout_ms(context, csm_timeout * 1000);
529}
530
531unsigned int
533 (void)context;
534 return s_csm_timeout;
535}
536
537void
539 unsigned int csm_timeout_ms) {
540 if (csm_timeout_ms < 10)
541 csm_timeout_ms = 10;
542 if (csm_timeout_ms > 10000)
543 csm_timeout_ms = 10000;
544 context->csm_timeout_ms = csm_timeout_ms;
545}
546
547unsigned int
549 return context->csm_timeout_ms;
550}
551
552void
554 uint32_t csm_max_message_size) {
555 assert(csm_max_message_size >= 64);
556 context->csm_max_message_size = csm_max_message_size;
557}
558
559uint32_t
563
564void
566 unsigned int session_timeout) {
567 context->session_timeout = session_timeout;
568}
569
570void
572 unsigned int reconnect_time) {
573#if COAP_CLIENT_SUPPORT
574 context->reconnect_time = reconnect_time;
575#else /* ! COAP_CLIENT_SUPPORT */
576 (void)context;
577 (void)reconnect_time;
578#endif /* ! COAP_CLIENT_SUPPORT */
579}
580
581unsigned int
583 return context->session_timeout;
584}
585
586void
588#if COAP_SERVER_SUPPORT
589 context->shutdown_no_send_observe = 1;
590#else /* ! COAP_SERVER_SUPPORT */
591 (void)context;
592#endif /* ! COAP_SERVER_SUPPORT */
593}
594
595int
597#ifdef COAP_EPOLL_SUPPORT
598 return context->epfd;
599#else /* ! COAP_EPOLL_SUPPORT */
600 (void)context;
601 return -1;
602#endif /* ! COAP_EPOLL_SUPPORT */
603}
604
605int
607#ifdef COAP_EPOLL_SUPPORT
608 return 1;
609#else /* ! COAP_EPOLL_SUPPORT */
610 return 0;
611#endif /* ! COAP_EPOLL_SUPPORT */
612}
613
614int
616#ifdef COAP_THREAD_SAFE
617 return 1;
618#else /* ! COAP_THREAD_SAFE */
619 return 0;
620#endif /* ! COAP_THREAD_SAFE */
621}
622
623int
625#ifdef COAP_IPV4_SUPPORT
626 return 1;
627#else /* ! COAP_IPV4_SUPPORT */
628 return 0;
629#endif /* ! COAP_IPV4_SUPPORT */
630}
631
632int
634#ifdef COAP_IPV6_SUPPORT
635 return 1;
636#else /* ! COAP_IPV6_SUPPORT */
637 return 0;
638#endif /* ! COAP_IPV6_SUPPORT */
639}
640
641int
643#ifdef COAP_CLIENT_SUPPORT
644 return 1;
645#else /* ! COAP_CLIENT_SUPPORT */
646 return 0;
647#endif /* ! COAP_CLIENT_SUPPORT */
648}
649
650int
652#ifdef COAP_SERVER_SUPPORT
653 return 1;
654#else /* ! COAP_SERVER_SUPPORT */
655 return 0;
656#endif /* ! COAP_SERVER_SUPPORT */
657}
658
659int
661#ifdef COAP_AF_UNIX_SUPPORT
662 return 1;
663#else /* ! COAP_AF_UNIX_SUPPORT */
664 return 0;
665#endif /* ! COAP_AF_UNIX_SUPPORT */
666}
667
668COAP_API void
669coap_context_set_app_data(coap_context_t *context, void *app_data) {
670 assert(context);
671 coap_lock_lock(return);
672 coap_context_set_app_data2_lkd(context, app_data, NULL);
674}
675
676void *
678 assert(context);
679 return context->app_data;
680}
681
682COAP_API void *
685 void *old_data;
686
687 coap_lock_lock(return NULL);
688 old_data = coap_context_set_app_data2_lkd(context, app_data, callback);
690 return old_data;
691}
692
693void *
696 void *old_data = context->app_data;
697
698 context->app_data = app_data;
699 context->app_cb = app_data ? callback : NULL;
700 return old_data;
701}
702
704coap_new_context(const coap_address_t *listen_addr) {
706
707#if ! COAP_SERVER_SUPPORT
708 (void)listen_addr;
709#endif /* COAP_SERVER_SUPPORT */
710
711 if (!coap_started) {
712 coap_startup();
713 coap_log_warn("coap_startup() should be called before any other "
714 "coap_*() functions are called\n");
715 }
716
718 if (!c) {
719 coap_log_emerg("coap_init: malloc: failed\n");
720 return NULL;
721 }
722 memset(c, 0, sizeof(coap_context_t));
723
725#ifdef COAP_EPOLL_SUPPORT
726 c->epfd = epoll_create1(0);
727 if (c->epfd == -1) {
728 coap_log_err("coap_new_context: Unable to epoll_create: %s (%d)\n",
730 errno);
731 goto onerror;
732 }
733 if (c->epfd != -1) {
734 c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
735 if (c->eptimerfd == -1) {
736 coap_log_err("coap_new_context: Unable to timerfd_create: %s (%d)\n",
738 errno);
739 goto onerror;
740 } else {
741 int ret;
742 struct epoll_event event;
743
744 /* Needed if running 32bit as ptr is only 32bit */
745 memset(&event, 0, sizeof(event));
746 event.events = EPOLLIN;
747 /* We special case this event by setting to NULL */
748 event.data.ptr = NULL;
749
750 ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
751 if (ret == -1) {
752 coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
753 "coap_new_context",
754 coap_socket_strerror(), errno);
755 goto onerror;
756 }
757 }
758 }
759#endif /* COAP_EPOLL_SUPPORT */
760
763 if (!c->dtls_context) {
764 coap_log_emerg("coap_init: no DTLS context available\n");
766 return NULL;
767 }
768 }
769
770 /* set default CSM values */
771 c->csm_timeout_ms = 1000;
772 c->csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
773
774#if COAP_SERVER_SUPPORT
775 if (listen_addr) {
776 coap_endpoint_t *endpoint = coap_new_endpoint_lkd(c, listen_addr, COAP_PROTO_UDP);
777 if (endpoint == NULL) {
778 goto onerror;
779 }
780 }
781#endif /* COAP_SERVER_SUPPORT */
782
783 c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
784
786 return c;
787
788#if defined(COAP_EPOLL_SUPPORT) || COAP_SERVER_SUPPORT
789onerror:
791 return NULL;
792#endif /* COAP_EPOLL_SUPPORT || COAP_SERVER_SUPPORT */
793}
794
795COAP_API void
796coap_set_app_data(coap_context_t *context, void *app_data) {
797 assert(context);
798 coap_lock_lock(return);
799 coap_context_set_app_data2_lkd(context, app_data, NULL);
801}
802
803void *
805 assert(ctx);
806 return ctx->app_data;
807}
808
809COAP_API void
811 if (!context)
812 return;
813 coap_lock_lock(return);
814 coap_free_context_lkd(context);
816}
817
818void
820 if (!context)
821 return;
822
824#if COAP_SERVER_SUPPORT
825 /* Removing a resource may cause a NON unsolicited observe to be sent */
826 if (context->shutdown_no_send_observe)
827 context->observe_no_clear = 1;
829#endif /* COAP_SERVER_SUPPORT */
830
831 coap_delete_all(context->sendqueue);
832 context->sendqueue = NULL;
833
834#ifdef WITH_LWIP
835 if (context->timer_configured) {
836 LOCK_TCPIP_CORE();
837 sys_untimeout(coap_io_process_timeout, (void *)context);
838 UNLOCK_TCPIP_CORE();
839 context->timer_configured = 0;
840 }
841#endif /* WITH_LWIP */
842
843#if COAP_ASYNC_SUPPORT
844 coap_delete_all_async(context);
845#endif /* COAP_ASYNC_SUPPORT */
846
847#if COAP_OSCORE_SUPPORT
848 coap_delete_all_oscore(context);
849#endif /* COAP_OSCORE_SUPPORT */
850
851#if COAP_SERVER_SUPPORT
852 coap_cache_entry_t *cp, *ctmp;
853
854 HASH_ITER(hh, context->cache, cp, ctmp) {
855 coap_delete_cache_entry(context, cp);
856 }
857 if (context->cache_ignore_count) {
859 }
860
861 coap_endpoint_t *ep, *tmp;
862
863 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
865 }
866#endif /* COAP_SERVER_SUPPORT */
867
868#if COAP_CLIENT_SUPPORT
869 coap_session_t *sp, *rtmp;
870
871 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
873 }
874#endif /* COAP_CLIENT_SUPPORT */
875
876 if (context->dtls_context)
878#ifdef COAP_EPOLL_SUPPORT
879 if (context->eptimerfd != -1) {
880 int ret;
881 struct epoll_event event;
882
883 /* Kernels prior to 2.6.9 expect non NULL event parameter */
884 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
885 if (ret == -1) {
886 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
887 "coap_free_context",
888 coap_socket_strerror(), errno);
889 }
890 close(context->eptimerfd);
891 context->eptimerfd = -1;
892 }
893 if (context->epfd != -1) {
894 close(context->epfd);
895 context->epfd = -1;
896 }
897#endif /* COAP_EPOLL_SUPPORT */
898#if COAP_SERVER_SUPPORT
899#if COAP_WITH_OBSERVE_PERSIST
900 coap_persist_cleanup(context);
901#endif /* COAP_WITH_OBSERVE_PERSIST */
902#endif /* COAP_SERVER_SUPPORT */
903#if COAP_PROXY_SUPPORT
904 coap_proxy_cleanup(context);
905#endif /* COAP_PROXY_SUPPORT */
906
907 if (context->app_cb) {
908 context->app_cb(context->app_data);
909 }
912}
913
914int
916 coap_pdu_t *pdu,
917 coap_opt_filter_t *unknown) {
918 coap_context_t *ctx = session->context;
919 coap_opt_iterator_t opt_iter;
920 int ok = 1;
921 coap_option_num_t last_number = -1;
922
924
925 while (coap_option_next(&opt_iter)) {
926 /* Check for explicitely reserved option RFC 5272 12.2 Table 7 */
927 /* Need to check reserved options */
928 switch (opt_iter.number) {
929 case 0:
930 case 128:
931 case 132:
932 case 136:
933 case 140:
934 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
935 coap_log_debug("unknown reserved option %d\n", opt_iter.number);
936 ok = 0;
937
938 /* When opt_iter.number cannot be set in unknown, all of the appropriate
939 * slots have been used up and no more options can be tracked.
940 * Safe to break out of this loop as ok is already set. */
941 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
942 goto overflow;
943 }
944 }
945 break;
946 default:
947 break;
948 }
949 if (opt_iter.number & 0x01) {
950 /* first check the known built-in critical options */
951 switch (opt_iter.number) {
952#if COAP_Q_BLOCK_SUPPORT
955 if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
956 coap_log_debug("disabled support for critical option %u\n",
957 opt_iter.number);
958 ok = 0;
959 /* When opt_iter.number cannot be set in unknown, all of the appropriate
960 * slots have been used up and no more options can be tracked.
961 * Safe to break out of this loop as ok is already set. */
962 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
963 goto overflow;
964 }
965 }
966 break;
967#endif /* COAP_Q_BLOCK_SUPPORT */
979 break;
981 /* Valid critical if doing OSCORE */
982#if COAP_OSCORE_SUPPORT
983 if (ctx->p_osc_ctx)
984 break;
985#endif /* COAP_OSCORE_SUPPORT */
986 /* Fall Through */
987 default:
988 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
989#if COAP_SERVER_SUPPORT
990 if ((opt_iter.number & 0x02) == 0) {
991 coap_opt_iterator_t t_iter;
992
993 /* Safe to forward - check if proxy pdu */
994 if (session->proxy_session)
995 break;
996 if (COAP_PDU_IS_REQUEST(pdu) && ctx->proxy_uri_resource &&
999 pdu->crit_opt = 1;
1000 break;
1001 }
1002 }
1003#endif /* COAP_SERVER_SUPPORT */
1004 coap_log_debug("unknown critical option %d\n", opt_iter.number);
1005 ok = 0;
1006
1007 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1008 * slots have been used up and no more options can be tracked.
1009 * Safe to break out of this loop as ok is already set. */
1010 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1011 goto overflow;
1012 }
1013 }
1014 }
1015 }
1016 if (last_number == opt_iter.number) {
1017 /* Check for duplicated option RFC 5272 5.4.5 */
1018 if (!coap_option_check_repeatable(opt_iter.number)) {
1019 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1020 ok = 0;
1021 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1022 goto overflow;
1023 }
1024 }
1025 }
1026 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
1027 COAP_PDU_IS_REQUEST(pdu)) {
1028 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
1029 coap_block_b_t block;
1030
1031 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
1032 if (block.m) {
1033 size_t used_size = pdu->used_size;
1034 unsigned char buf[4];
1035
1036 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
1037 block.m = 0;
1038 coap_update_option(pdu, opt_iter.number,
1039 coap_encode_var_safe(buf, sizeof(buf),
1040 ((block.num << 4) |
1041 (block.m << 3) |
1042 block.aszx)),
1043 buf);
1044 if (used_size != pdu->used_size) {
1045 /* Unfortunately need to restart the scan */
1046 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1047 last_number = -1;
1048 continue;
1049 }
1050 }
1051 }
1052 }
1053 last_number = opt_iter.number;
1054 }
1055overflow:
1056 return ok;
1057}
1058
1060coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
1061 coap_mid_t mid;
1062
1064 mid = coap_send_rst_lkd(session, request);
1066 return mid;
1067}
1068
1071 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
1072}
1073
1075coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
1076 coap_mid_t mid;
1077
1079 mid = coap_send_ack_lkd(session, request);
1081 return mid;
1082}
1083
1086 coap_pdu_t *response;
1088
1090 if (request && request->type == COAP_MESSAGE_CON &&
1091 COAP_PROTO_NOT_RELIABLE(session->proto)) {
1092 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
1093 if (response)
1094 result = coap_send_internal(session, response, NULL);
1095 }
1096 return result;
1097}
1098
1099ssize_t
1101 ssize_t bytes_written = -1;
1102 assert(pdu->hdr_size > 0);
1103
1104 /* Caller handles partial writes */
1105 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1106 pdu->token - pdu->hdr_size,
1107 pdu->used_size + pdu->hdr_size);
1109 return bytes_written;
1110}
1111
1112static ssize_t
1114 ssize_t bytes_written;
1115
1116 if (session->state == COAP_SESSION_STATE_NONE) {
1117#if ! COAP_CLIENT_SUPPORT
1118 return -1;
1119#else /* COAP_CLIENT_SUPPORT */
1120 if (session->type != COAP_SESSION_TYPE_CLIENT)
1121 return -1;
1122#endif /* COAP_CLIENT_SUPPORT */
1123 }
1124
1125 if (pdu->type == COAP_MESSAGE_CON &&
1126 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1127 coap_is_mcast(&session->addr_info.remote)) {
1128 /* Violates RFC72522 8.1 */
1129 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1130 return -1;
1131 }
1132
1133 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1134 (pdu->type == COAP_MESSAGE_CON &&
1135 session->con_active >= COAP_NSTART(session))) {
1136 return coap_session_delay_pdu(session, pdu, node);
1137 }
1138
1139 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1140 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1141 return coap_session_delay_pdu(session, pdu, node);
1142
1143 bytes_written = coap_session_send_pdu(session, pdu);
1144 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1146 session->con_active++;
1147
1148 return bytes_written;
1149}
1150
1153 const coap_pdu_t *request,
1154 coap_pdu_code_t code,
1155 coap_opt_filter_t *opts) {
1156 coap_mid_t mid;
1157
1159 mid = coap_send_error_lkd(session, request, code, opts);
1161 return mid;
1162}
1163
1166 const coap_pdu_t *request,
1167 coap_pdu_code_t code,
1168 coap_opt_filter_t *opts) {
1169 coap_pdu_t *response;
1171
1172 assert(request);
1173 assert(session);
1174
1175 response = coap_new_error_response(request, code, opts);
1176 if (response)
1177 result = coap_send_internal(session, response, NULL);
1178
1179 return result;
1180}
1181
1184 coap_pdu_type_t type) {
1185 coap_mid_t mid;
1186
1188 mid = coap_send_message_type_lkd(session, request, type);
1190 return mid;
1191}
1192
1195 coap_pdu_type_t type) {
1196 coap_pdu_t *response;
1198
1200 if (request && COAP_PROTO_NOT_RELIABLE(session->proto)) {
1201 response = coap_pdu_init(type, 0, request->mid, 0);
1202 if (response)
1203 result = coap_send_internal(session, response, NULL);
1204 }
1205 return result;
1206}
1207
1221unsigned int
1222coap_calc_timeout(coap_session_t *session, unsigned char r) {
1223 unsigned int result;
1224
1225 /* The integer 1.0 as a Qx.FRAC_BITS */
1226#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1227
1228 /* rounds val up and right shifts by frac positions */
1229#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1230
1231 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1232 * make the result a rounded Qx.FRAC_BITS */
1233 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1234
1235 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1236 * make the result a rounded Qx.FRAC_BITS */
1237 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1238
1239 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1240 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1241 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1242
1243#undef FP1
1244#undef SHR_FP
1245}
1246
1249 coap_queue_t *node) {
1250 coap_tick_t now;
1251
1252 node->session = coap_session_reference_lkd(session);
1253
1254 /* Set timer for pdu retransmission. If this is the first element in
1255 * the retransmission queue, the base time is set to the current
1256 * time and the retransmission time is node->timeout. If there is
1257 * already an entry in the sendqueue, we must check if this node is
1258 * to be retransmitted earlier. Therefore, node->timeout is first
1259 * normalized to the base time and then inserted into the queue with
1260 * an adjusted relative time.
1261 */
1262 coap_ticks(&now);
1263 if (context->sendqueue == NULL) {
1264 node->t = node->timeout << node->retransmit_cnt;
1265 context->sendqueue_basetime = now;
1266 } else {
1267 /* make node->t relative to context->sendqueue_basetime */
1268 node->t = (now - context->sendqueue_basetime) +
1269 (node->timeout << node->retransmit_cnt);
1270 }
1271 coap_address_copy(&node->remote, &session->addr_info.remote);
1272
1273 coap_insert_node(&context->sendqueue, node);
1274
1275 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1276 coap_session_str(node->session), node->id,
1277 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1279
1280 coap_update_io_timer(context, node->t);
1281
1282 return node->id;
1283}
1284
1285#if COAP_CLIENT_SUPPORT
1286/*
1287 * Sent out a test PDU for Extended Token
1288 */
1289static coap_mid_t
1290coap_send_test_extended_token(coap_session_t *session) {
1291 coap_pdu_t *pdu;
1293 size_t i;
1294 coap_binary_t *token;
1295 coap_lg_crcv_t *lg_crcv;
1296
1297 coap_log_debug("Testing for Extended Token support\n");
1298 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1300 coap_new_message_id_lkd(session),
1302 if (!pdu)
1303 return COAP_INVALID_MID;
1304
1305 token = coap_new_binary(session->max_token_size);
1306 if (token == NULL) {
1308 return COAP_INVALID_MID;
1309 }
1310 for (i = 0; i < session->max_token_size; i++) {
1311 token->s[i] = (uint8_t)(i + 1);
1312 }
1313 coap_add_token(pdu, session->max_token_size, token->s);
1314 coap_delete_binary(token);
1315
1318 pdu->actual_token.length);
1319
1321
1322 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1323
1324 /* Need to track incase OSCORE / Echo etc. comes back after non-piggy-backed ACK */
1325 lg_crcv = coap_block_new_lg_crcv(session, pdu, NULL);
1326 if (lg_crcv) {
1327 LL_PREPEND(session->lg_crcv, lg_crcv);
1328 }
1329 mid = coap_send_internal(session, pdu, NULL);
1330 if (mid == COAP_INVALID_MID)
1331 return COAP_INVALID_MID;
1332 session->remote_test_mid = mid;
1333 return mid;
1334}
1335#endif /* COAP_CLIENT_SUPPORT */
1336
1337int
1339#if COAP_CLIENT_SUPPORT
1340 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1341 int timeout_ms = 5000;
1342 coap_session_state_t current_state = session->state;
1343
1344 if (session->delay_recursive) {
1345 return 0;
1346 } else {
1347 session->delay_recursive = 1;
1348 }
1349 /*
1350 * Need to wait for first request to get out and response back before
1351 * continuing.. Response handler has to clear doing_first if not an error.
1352 */
1354 while (session->doing_first != 0) {
1355 int result = coap_io_process_lkd(session->context, 1000);
1356
1357 if (result < 0) {
1358 session->doing_first = 0;
1359 session->delay_recursive = 0;
1360 coap_session_release_lkd(session);
1361 return 0;
1362 }
1363
1364 /* coap_io_process_lkd() may have updated session state */
1365 if (session->state == COAP_SESSION_STATE_CSM &&
1366 current_state != COAP_SESSION_STATE_CSM) {
1367 /* Update timeout and restart the clock for CSM timeout */
1368 current_state = COAP_SESSION_STATE_CSM;
1369 timeout_ms = session->context->csm_timeout_ms;
1370 result = 0;
1371 }
1372
1373 if (result < timeout_ms) {
1374 timeout_ms -= result;
1375 } else {
1376 if (session->doing_first == 1) {
1377 /* Timeout failure of some sort with first request */
1378 session->doing_first = 0;
1379 if (session->state == COAP_SESSION_STATE_CSM) {
1380 coap_log_debug("** %s: timeout waiting for CSM response\n",
1381 coap_session_str(session));
1382 session->csm_not_seen = 1;
1383 coap_session_connected(session);
1384 } else {
1385 coap_log_debug("** %s: timeout waiting for first response\n",
1386 coap_session_str(session));
1387 }
1388 }
1389 }
1390 }
1391 session->delay_recursive = 0;
1392 coap_session_release_lkd(session);
1393 }
1394#else /* ! COAP_CLIENT_SUPPORT */
1395 (void)session;
1396#endif /* ! COAP_CLIENT_SUPPORT */
1397 return 1;
1398}
1399
1400/*
1401 * return 0 Invalid
1402 * 1 Valid
1403 */
1404int
1406
1407 /* Check validity of sending code */
1408 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1409 case 0: /* Empty or request */
1410 case 2: /* Success */
1411 case 3: /* Reserved for future use */
1412 case 4: /* Client error */
1413 case 5: /* Server error */
1414 break;
1415 case 7: /* Reliable signalling */
1416 if (COAP_PROTO_RELIABLE(session->proto))
1417 break;
1418 /* Not valid if UDP */
1419 /* Fall through */
1420 case 1: /* Invalid */
1421 case 6: /* Invalid */
1422 default:
1423 return 0;
1424 }
1425 return 1;
1426}
1427
1428#if COAP_CLIENT_SUPPORT
1429/*
1430 * If type is CON and protocol is not reliable, there is no need to set up
1431 * lg_crcv if it can be built up based on sent PDU if there is a
1432 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1433 * (Q-)Block1.
1434 */
1435static int
1436coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1437 coap_opt_iterator_t opt_iter;
1438
1439 if (!COAP_PDU_IS_REQUEST(pdu))
1440 return 0;
1441
1442 if (
1443#if COAP_OSCORE_SUPPORT
1444 session->oscore_encryption ||
1445#endif /* COAP_OSCORE_SUPPORT */
1446 pdu->type == COAP_MESSAGE_NON ||
1447 COAP_PROTO_RELIABLE(session->proto) ||
1448 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1449#if COAP_Q_BLOCK_SUPPORT
1450 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1451#endif /* COAP_Q_BLOCK_SUPPORT */
1452 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1453 return 1;
1454 }
1455 return 0;
1456}
1457#endif /* COAP_CLIENT_SUPPORT */
1458
1461 coap_mid_t mid;
1462
1464 mid = coap_send_lkd(session, pdu);
1466 return mid;
1467}
1468
1472#if COAP_CLIENT_SUPPORT
1473 coap_lg_crcv_t *lg_crcv = NULL;
1474 coap_opt_iterator_t opt_iter;
1475 coap_block_b_t block;
1476 int observe_action = -1;
1477 int have_block1 = 0;
1478 coap_opt_t *opt;
1479#endif /* COAP_CLIENT_SUPPORT */
1480
1481 assert(pdu);
1482
1484
1485 /* Check validity of sending code */
1486 if (!coap_check_code_class(session, pdu)) {
1487 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1489 pdu->code & 0x1f);
1490 goto error;
1491 }
1492 pdu->session = session;
1493#if COAP_CLIENT_SUPPORT
1494 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1495 !coap_netif_available(session) && !session->session_failed) {
1496 coap_log_debug("coap_send: Socket closed\n");
1497 goto error;
1498 }
1499 /*
1500 * If this is not the first client request and are waiting for a response
1501 * to the first client request, then drop sending out this next request
1502 * until all is properly established.
1503 */
1504 if (!coap_client_delay_first(session)) {
1505 goto error;
1506 }
1507
1508 /* Indicate support for Extended Tokens if appropriate */
1509 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1511 session->type == COAP_SESSION_TYPE_CLIENT &&
1512 COAP_PDU_IS_REQUEST(pdu)) {
1513 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1514 /*
1515 * When the pass / fail response for Extended Token is received, this PDU
1516 * will get transmitted.
1517 */
1518 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1519 goto error;
1520 }
1521 }
1522 /*
1523 * For reliable protocols, this will get cleared after CSM exchanged
1524 * in coap_session_connected()
1525 */
1526 session->doing_first = 1;
1527 if (!coap_client_delay_first(session)) {
1528 goto error;
1529 }
1530 }
1531
1532 /*
1533 * Check validity of token length
1534 */
1535 if (COAP_PDU_IS_REQUEST(pdu) &&
1536 pdu->actual_token.length > session->max_token_size) {
1537 coap_log_warn("coap_send: PDU dropped as token too long (%zu > %" PRIu32 ")\n",
1538 pdu->actual_token.length, session->max_token_size);
1539 goto error;
1540 }
1541
1542 /* A lot of the reliable code assumes type is CON */
1543 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1544 pdu->type = COAP_MESSAGE_CON;
1545
1546#if COAP_OSCORE_SUPPORT
1547 if (session->oscore_encryption) {
1548 if (session->recipient_ctx->initial_state == 1) {
1549 /*
1550 * Not sure if remote supports OSCORE, or is going to send us a
1551 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1552 * is OK. Continue sending current pdu to test things.
1553 */
1554 session->doing_first = 1;
1555 }
1556 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1558 goto error;
1559 }
1560 }
1561#endif /* COAP_OSCORE_SUPPORT */
1562
1563 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1564 return coap_send_internal(session, pdu, NULL);
1565 }
1566
1567 if (COAP_PDU_IS_REQUEST(pdu)) {
1568 uint8_t buf[4];
1569
1570 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1571
1572 if (opt) {
1573 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1574 coap_opt_length(opt));
1575 }
1576
1577 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1578 (block.m == 1 || block.bert == 1)) {
1579 have_block1 = 1;
1580 }
1581#if COAP_Q_BLOCK_SUPPORT
1582 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1583 (block.m == 1 || block.bert == 1)) {
1584 if (have_block1) {
1585 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1587 }
1588 have_block1 = 1;
1589 }
1590#endif /* COAP_Q_BLOCK_SUPPORT */
1591 if (observe_action != COAP_OBSERVE_CANCEL) {
1592 /* Warn about re-use of tokens */
1593 if (session->last_token &&
1594 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1596 char scratch[24];
1597 size_t size;
1598 size_t i;
1599
1600 scratch[0] = '\000';
1601 for (i = 0; i < pdu->actual_token.length; i++) {
1602 size = strlen(scratch);
1603 snprintf(&scratch[size], sizeof(scratch)-size,
1604 "%02x", pdu->actual_token.s[i]);
1605 }
1606 coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1607 scratch);
1608 }
1609 }
1612 pdu->actual_token.length);
1613 } else {
1614 /* observe_action == COAP_OBSERVE_CANCEL */
1615 coap_binary_t tmp;
1616 int ret;
1617
1618 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1619 /* Unfortunately need to change the ptr type to be r/w */
1620 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1621 tmp.length = pdu->actual_token.length;
1622 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1623 if (ret == 1) {
1624 /* Observe Cancel successfully sent */
1626 return ret;
1627 }
1628 /* Some mismatch somewhere - continue to send original packet */
1629 }
1630 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1631 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1635 coap_encode_var_safe(buf, sizeof(buf),
1636 ++session->tx_rtag),
1637 buf);
1638 } else {
1639 memset(&block, 0, sizeof(block));
1640 }
1641
1642#if COAP_Q_BLOCK_SUPPORT
1643 /* Indicate support for Q-Block if appropriate */
1644 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1645 session->type == COAP_SESSION_TYPE_CLIENT &&
1646 COAP_PDU_IS_REQUEST(pdu)) {
1647 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1648 goto error;
1649 }
1650 session->doing_first = 1;
1651 if (!coap_client_delay_first(session)) {
1652 /* Q-Block test Session has failed for some reason */
1653 set_block_mode_drop_q(session->block_mode);
1654 goto error;
1655 }
1656 }
1657#endif /* COAP_Q_BLOCK_SUPPORT */
1658
1659#if COAP_Q_BLOCK_SUPPORT
1660 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1661#endif /* COAP_Q_BLOCK_SUPPORT */
1662 {
1663 /* Need to check if we need to reset Q-Block to Block */
1664 uint8_t buf[4];
1665
1666 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1669 coap_encode_var_safe(buf, sizeof(buf),
1670 (block.num << 4) | (0 << 3) | block.szx),
1671 buf);
1672 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1673 /* Need to update associated lg_xmit */
1674 coap_lg_xmit_t *lg_xmit;
1675
1676 LL_FOREACH(session->lg_xmit, lg_xmit) {
1677 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1678 lg_xmit->b.b1.app_token &&
1679 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1680 /* Update the skeletal PDU with the block1 option */
1683 coap_encode_var_safe(buf, sizeof(buf),
1684 (block.num << 4) | (0 << 3) | block.szx),
1685 buf);
1686 break;
1687 }
1688 }
1689 }
1690 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1693 coap_encode_var_safe(buf, sizeof(buf),
1694 (block.num << 4) | (block.m << 3) | block.szx),
1695 buf);
1696 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1697 /* Need to update associated lg_xmit */
1698 coap_lg_xmit_t *lg_xmit;
1699
1700 LL_FOREACH(session->lg_xmit, lg_xmit) {
1701 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1702 lg_xmit->b.b1.app_token &&
1703 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1704 /* Update the skeletal PDU with the block1 option */
1707 coap_encode_var_safe(buf, sizeof(buf),
1708 (block.num << 4) |
1709 (block.m << 3) |
1710 block.szx),
1711 buf);
1712 /* Update as this is a Request */
1713 lg_xmit->option = COAP_OPTION_BLOCK1;
1714 break;
1715 }
1716 }
1717 }
1718 }
1719
1720#if COAP_Q_BLOCK_SUPPORT
1721 if (COAP_PDU_IS_REQUEST(pdu) &&
1722 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1723 if (block.num == 0 && block.m == 0) {
1724 uint8_t buf[4];
1725
1726 /* M needs to be set as asking for all the blocks */
1728 coap_encode_var_safe(buf, sizeof(buf),
1729 (0 << 4) | (1 << 3) | block.szx),
1730 buf);
1731 }
1732 }
1733#endif /* COAP_Q_BLOCK_SUPPORT */
1734
1735 /*
1736 * If type is CON and protocol is not reliable, there is no need to set up
1737 * lg_crcv here as it can be built up based on sent PDU if there is a
1738 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1739 * (Q-)Block1.
1740 */
1741 if (coap_check_send_need_lg_crcv(session, pdu)) {
1742 coap_lg_xmit_t *lg_xmit = NULL;
1743
1744 if (!session->lg_xmit && have_block1) {
1745 coap_log_debug("PDU presented by app\n");
1747 }
1748 /* See if this token is already in use for large body responses */
1749 LL_FOREACH(session->lg_crcv, lg_crcv) {
1750 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1751 /* Need to terminate and clean up previous response setup */
1752 LL_DELETE(session->lg_crcv, lg_crcv);
1753 coap_block_delete_lg_crcv(session, lg_crcv);
1754 break;
1755 }
1756 }
1757
1758 if (have_block1 && session->lg_xmit) {
1759 LL_FOREACH(session->lg_xmit, lg_xmit) {
1760 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1761 lg_xmit->b.b1.app_token &&
1762 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1763 break;
1764 }
1765 }
1766 }
1767 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1768 if (lg_crcv == NULL) {
1769 goto error;
1770 }
1771 if (lg_xmit) {
1772 /* Need to update the token as set up in the session->lg_xmit */
1773 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1774 }
1775 }
1776 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1777 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1778
1779#if COAP_Q_BLOCK_SUPPORT
1780 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1781 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1782 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1783 } else
1784#endif /* COAP_Q_BLOCK_SUPPORT */
1785 mid = coap_send_internal(session, pdu, NULL);
1786#else /* !COAP_CLIENT_SUPPORT */
1787 mid = coap_send_internal(session, pdu, NULL);
1788#endif /* !COAP_CLIENT_SUPPORT */
1789#if COAP_CLIENT_SUPPORT
1790 if (lg_crcv) {
1791 if (mid != COAP_INVALID_MID) {
1792 LL_PREPEND(session->lg_crcv, lg_crcv);
1793 } else {
1794 coap_block_delete_lg_crcv(session, lg_crcv);
1795 }
1796 }
1797#endif /* COAP_CLIENT_SUPPORT */
1798 return mid;
1799
1800error:
1802 return COAP_INVALID_MID;
1803}
1804
1805#if COAP_SERVER_SUPPORT
1806static int
1807coap_pdu_cksum(const coap_pdu_t *pdu, coap_digest_t *digest_buffer) {
1808 coap_digest_ctx_t *digest_ctx = coap_digest_setup();
1809
1810 if (!digest_ctx || !pdu) {
1811 goto fail;
1812 }
1813 if (pdu->used_size && pdu->token) {
1814 if (!coap_digest_update(digest_ctx, pdu->token, pdu->used_size)) {
1815 goto fail;
1816 }
1817 }
1818 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->type, sizeof(pdu->type))) {
1819 goto fail;
1820 }
1821 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->code, sizeof(pdu->code))) {
1822 goto fail;
1823 }
1824 if (!coap_digest_final(digest_ctx, digest_buffer))
1825 return 0;
1826
1827 return 1;
1828
1829fail:
1830 coap_digest_free(digest_ctx);
1831 return 0;
1832}
1833#endif /* COAP_SERVER_SUPPORT */
1834
1837 uint8_t r;
1838 ssize_t bytes_written;
1839 coap_opt_iterator_t opt_iter;
1840
1841#if ! COAP_SERVER_SUPPORT
1842 (void)request_pdu;
1843#endif /* COAP_SERVER_SUPPORT */
1844 pdu->session = session;
1845#if COAP_CLIENT_SUPPORT
1846 if (session->session_failed) {
1847 coap_session_reconnect(session);
1848 if (session->session_failed)
1849 goto error;
1850 }
1851#endif /* COAP_CLIENT_SUPPORT */
1852#if COAP_PROXY_SUPPORT
1853 if (session->server_list) {
1854 /* Local session wanting to use proxy logic */
1855 return coap_proxy_local_write(session, pdu);
1856 }
1857#endif /* COAP_PROXY_SUPPORT */
1858 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1859 /*
1860 * Need to prepend our IP identifier to the data as per
1861 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1862 */
1863 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1864 coap_opt_t *opt;
1865 size_t hop_limit;
1866
1867 addr_str[sizeof(addr_str)-1] = '\000';
1868 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1869 sizeof(addr_str) - 1)) {
1870 char *cp;
1871 size_t len;
1872
1873 if (addr_str[0] == '[') {
1874 cp = strchr(addr_str, ']');
1875 if (cp)
1876 *cp = '\000';
1877 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1878 /* IPv4 embedded into IPv6 */
1879 cp = &addr_str[8];
1880 } else {
1881 cp = &addr_str[1];
1882 }
1883 } else {
1884 cp = strchr(addr_str, ':');
1885 if (cp)
1886 *cp = '\000';
1887 cp = addr_str;
1888 }
1889 len = strlen(cp);
1890
1891 /* See if Hop Limit option is being used in return path */
1892 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1893 if (opt) {
1894 uint8_t buf[4];
1895
1896 hop_limit =
1898 if (hop_limit == 1) {
1899 coap_log_warn("Proxy loop detected '%s'\n",
1900 (char *)pdu->data);
1903 } else if (hop_limit < 1 || hop_limit > 255) {
1904 /* Something is bad - need to drop this pdu (TODO or delete option) */
1905 coap_log_warn("Proxy return has bad hop limit count '%zu'\n",
1906 hop_limit);
1909 }
1910 hop_limit--;
1912 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1913 buf);
1914 }
1915
1916 /* Need to check that we are not seeing this proxy in the return loop */
1917 if (pdu->data && opt == NULL) {
1918 char *a_match;
1919 size_t data_len;
1920
1921 if (pdu->used_size + 1 > pdu->max_size) {
1922 /* No space */
1924 }
1925 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1926 /* Internal error */
1928 }
1929 data_len = pdu->used_size - (pdu->data - pdu->token);
1930 pdu->data[data_len] = '\000';
1931 a_match = strstr((char *)pdu->data, cp);
1932 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1933 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1934 a_match[len] == ' ')) {
1935 coap_log_warn("Proxy loop detected '%s'\n",
1936 (char *)pdu->data);
1939 }
1940 }
1941 if (pdu->used_size + len + 1 <= pdu->max_size) {
1942 size_t old_size = pdu->used_size;
1943 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1944 if (pdu->data == NULL) {
1945 /*
1946 * Set Hop Limit to max for return path. If this libcoap is in
1947 * a proxy loop path, it will always decrement hop limit in code
1948 * above and hence timeout / drop the response as appropriate
1949 */
1950 hop_limit = 255;
1952 (uint8_t *)&hop_limit);
1953 coap_add_data(pdu, len, (uint8_t *)cp);
1954 } else {
1955 /* prepend with space separator, leaving hop limit "as is" */
1956 memmove(pdu->data + len + 1, pdu->data,
1957 old_size - (pdu->data - pdu->token));
1958 memcpy(pdu->data, cp, len);
1959 pdu->data[len] = ' ';
1960 pdu->used_size += len + 1;
1961 }
1962 }
1963 }
1964 }
1965 }
1966
1967 if (session->echo) {
1968 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1969 session->echo->s))
1970 goto error;
1971 coap_delete_bin_const(session->echo);
1972 session->echo = NULL;
1973 }
1974#if COAP_OSCORE_SUPPORT
1975 if (session->oscore_encryption) {
1976 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1978 goto error;
1979 }
1980#endif /* COAP_OSCORE_SUPPORT */
1981
1982 if (!coap_pdu_encode_header(pdu, session->proto)) {
1983 goto error;
1984 }
1985
1986#if !COAP_DISABLE_TCP
1987 if (COAP_PROTO_RELIABLE(session->proto) &&
1989 if (!session->csm_block_supported) {
1990 /*
1991 * Need to check that this instance is not sending any block options as
1992 * the remote end via CSM has not informed us that there is support
1993 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
1994 * This includes potential BERT blocks.
1995 */
1996 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1997 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
1998 }
1999 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2000 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2001 }
2002 } else if (!session->csm_bert_rem_support) {
2003 coap_opt_t *opt;
2004
2005 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2006 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2007 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2008 }
2009 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2010 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2011 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2012 }
2013 }
2014 }
2015#endif /* !COAP_DISABLE_TCP */
2016
2017#if COAP_OSCORE_SUPPORT
2018 if (session->oscore_encryption &&
2019 pdu->type != COAP_MESSAGE_RST &&
2020 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2021 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2022 /* Refactor PDU as appropriate RFC8613 */
2023 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2024
2025 if (osc_pdu == NULL) {
2026 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2029 goto error;
2030 }
2031 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2033 pdu = osc_pdu;
2034 } else
2035#endif /* COAP_OSCORE_SUPPORT */
2036 bytes_written = coap_send_pdu(session, pdu, NULL);
2037
2038#if COAP_SERVER_SUPPORT
2039 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
2040 session->cached_pdu != pdu &&
2041 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2042 COAP_PDU_IS_REQUEST(request_pdu) &&
2043 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2045 session->cached_pdu = pdu;
2047 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
2048 }
2049#endif /* COAP_SERVER_SUPPORT */
2050
2051 if (bytes_written == COAP_PDU_DELAYED) {
2052 /* do not free pdu as it is stored with session for later use */
2053 return pdu->mid;
2054 }
2055 if (bytes_written < 0) {
2057 goto error;
2058 }
2059
2060#if !COAP_DISABLE_TCP
2061 if (COAP_PROTO_RELIABLE(session->proto) &&
2062 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2063 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2064 session->partial_write = (size_t)bytes_written;
2065 /* do not free pdu as it is stored with session for later use */
2066 return pdu->mid;
2067 } else {
2068 goto error;
2069 }
2070 }
2071#endif /* !COAP_DISABLE_TCP */
2072
2073 if (pdu->type != COAP_MESSAGE_CON
2074 || COAP_PROTO_RELIABLE(session->proto)) {
2075 coap_mid_t id = pdu->mid;
2077 return id;
2078 }
2079
2080 coap_queue_t *node = coap_new_node();
2081 if (!node) {
2082 coap_log_debug("coap_wait_ack: insufficient memory\n");
2083 goto error;
2084 }
2085
2086 node->id = pdu->mid;
2087 node->pdu = pdu;
2088 coap_prng_lkd(&r, sizeof(r));
2089 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2090 node->timeout = coap_calc_timeout(session, r);
2091 return coap_wait_ack(session->context, session, node);
2092error:
2094 return COAP_INVALID_MID;
2095}
2096
2097static int send_recv_terminate = 0;
2098
2099void
2103
2104COAP_API int
2106 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2107 int ret;
2108
2109 coap_lock_lock(return 0);
2110 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2112 return ret;
2113}
2114
2115/*
2116 * Return 0 or +ve Time in function in ms after successful transfer
2117 * -1 Invalid timeout parameter
2118 * -2 Failed to transmit PDU
2119 * -3 Nack or Event handler invoked, cancelling request
2120 * -4 coap_io_process returned error (fail to re-lock or select())
2121 * -5 Response not received in the given time
2122 * -6 Terminated by user
2123 * -7 Client mode code not enabled
2124 */
2125int
2127 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2128#if COAP_CLIENT_SUPPORT
2130 uint32_t rem_timeout = timeout_ms;
2131 uint32_t block_mode = session->block_mode;
2132 int ret = 0;
2133 coap_tick_t now;
2134 coap_tick_t start;
2135 coap_tick_t ticks_so_far;
2136 uint32_t time_so_far_ms;
2137
2138 coap_ticks(&start);
2139 assert(request_pdu);
2140
2142
2143 session->resp_pdu = NULL;
2144 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2145 request_pdu->actual_token.length);
2146
2147 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2148 ret = -1;
2149 goto fail;
2150 }
2151 if (session->state == COAP_SESSION_STATE_NONE) {
2152 ret = -3;
2153 goto fail;
2154 }
2155
2157 if (coap_is_mcast(&session->addr_info.remote))
2158 block_mode = session->block_mode;
2159
2160 session->doing_send_recv = 1;
2161 /* So the user needs to delete the PDU */
2162 coap_pdu_reference_lkd(request_pdu);
2163 mid = coap_send_lkd(session, request_pdu);
2164 if (mid == COAP_INVALID_MID) {
2165 if (!session->doing_send_recv)
2166 ret = -3;
2167 else
2168 ret = -2;
2169 goto fail;
2170 }
2171
2172 /* Wait for the response to come in */
2173 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2174 if (send_recv_terminate) {
2175 ret = -6;
2176 goto fail;
2177 }
2178 ret = coap_io_process_lkd(session->context, rem_timeout);
2179 if (ret < 0) {
2180 ret = -4;
2181 goto fail;
2182 }
2183 /* timeout_ms is for timeout between specific request and response */
2184 coap_ticks(&now);
2185 ticks_so_far = now - session->last_rx_tx;
2186 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2187 if (time_so_far_ms >= timeout_ms) {
2188 rem_timeout = 0;
2189 } else {
2190 rem_timeout = timeout_ms - time_so_far_ms;
2191 }
2192 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2193 /* To pick up on (D)TLS setup issues */
2194 coap_ticks(&now);
2195 ticks_so_far = now - start;
2196 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2197 if (time_so_far_ms >= timeout_ms) {
2198 rem_timeout = 0;
2199 } else {
2200 rem_timeout = timeout_ms - time_so_far_ms;
2201 }
2202 }
2203 }
2204
2205 if (rem_timeout) {
2206 coap_ticks(&now);
2207 ticks_so_far = now - start;
2208 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2209 ret = time_so_far_ms;
2210 /* Give PDU to user who will be calling coap_delete_pdu() */
2211 *response_pdu = session->resp_pdu;
2212 session->resp_pdu = NULL;
2213 if (*response_pdu == NULL) {
2214 ret = -3;
2215 }
2216 } else {
2217 /* If there is a resp_pdu, it will get cleared below */
2218 ret = -5;
2219 }
2220
2221fail:
2222 session->block_mode = block_mode;
2223 session->doing_send_recv = 0;
2224 /* delete referenced copy */
2225 coap_delete_pdu_lkd(session->resp_pdu);
2226 session->resp_pdu = NULL;
2228 session->req_token = NULL;
2229 return ret;
2230
2231#else /* !COAP_CLIENT_SUPPORT */
2232
2233 (void)session;
2234 (void)timeout_ms;
2235 (void)request_pdu;
2236 coap_log_warn("coap_send_recv: Client mode not supported\n");
2237 *response_pdu = NULL;
2238 return -7;
2239
2240#endif /* ! COAP_CLIENT_SUPPORT */
2241}
2242
2245 if (!context || !node || !node->session)
2246 return COAP_INVALID_MID;
2247
2248 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2249 if (node->retransmit_cnt < node->session->max_retransmit) {
2250 ssize_t bytes_written;
2251 coap_tick_t now;
2252 coap_tick_t next_delay;
2253 coap_address_t remote;
2254
2255 node->retransmit_cnt++;
2257
2258 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2259 if (context->ping_timeout &&
2260 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2261 uint8_t byte;
2262
2263 coap_prng_lkd(&byte, sizeof(byte));
2264 /* Don't exceed the ping timeout value */
2265 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2266 }
2267
2268 coap_ticks(&now);
2269 if (context->sendqueue == NULL) {
2270 node->t = next_delay;
2271 context->sendqueue_basetime = now;
2272 } else {
2273 /* make node->t relative to context->sendqueue_basetime */
2274 node->t = (now - context->sendqueue_basetime) + next_delay;
2275 }
2276 coap_insert_node(&context->sendqueue, node);
2277 coap_address_copy(&remote, &node->session->addr_info.remote);
2279
2280 if (node->is_mcast) {
2281 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2282 coap_session_str(node->session), node->id);
2283 } else {
2284 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2285 coap_session_str(node->session), node->id,
2286 node->retransmit_cnt,
2287 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2288 }
2289
2290 if (node->session->con_active)
2291 node->session->con_active--;
2292 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2293
2294 if (bytes_written == COAP_PDU_DELAYED) {
2295 /* PDU was not retransmitted immediately because a new handshake is
2296 in progress. node was moved to the send queue of the session. */
2297 return node->id;
2298 }
2299
2300 coap_address_copy(&node->session->addr_info.remote, &remote);
2301 if (node->is_mcast) {
2304 return COAP_INVALID_MID;
2305 }
2306
2307 if (bytes_written < 0)
2308 return (int)bytes_written;
2309
2310 return node->id;
2311 }
2312
2313 /* no more retransmissions, remove node from system */
2314 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2315 coap_session_str(node->session), node->id, node->retransmit_cnt);
2316
2317#if COAP_SERVER_SUPPORT
2318 /* Check if subscriptions exist that should be canceled after
2319 COAP_OBS_MAX_FAIL */
2320 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2321 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2322 if (context->ping_timeout) {
2325 return COAP_INVALID_MID;
2326 } else {
2327 if (node->session->ref_subscriptions)
2328 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2329#if COAP_PROXY_SUPPORT
2330 /* Need to check is there is a proxy subscription active and delete it */
2331 if (node->session->ref_proxy_subs)
2332 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2333 0, COAP_PROXY_SUBS_TOKEN);
2334#endif /* COAP_PROXY_SUPPORT */
2335 }
2336 }
2337#endif /* COAP_SERVER_SUPPORT */
2338 if (node->session->con_active) {
2339 node->session->con_active--;
2341 /*
2342 * As there may be another CON in a different queue entry on the same
2343 * session that needs to be immediately released,
2344 * coap_session_connected() is called.
2345 * However, there is the possibility coap_wait_ack() may be called for
2346 * this node (queue) and re-added to context->sendqueue.
2347 * coap_delete_node_lkd(node) called shortly will handle this and
2348 * remove it.
2349 */
2351 }
2352 }
2353
2354 if (node->pdu->type == COAP_MESSAGE_CON) {
2356 }
2357#if COAP_CLIENT_SUPPORT
2358 node->session->doing_send_recv = 0;
2359#endif /* COAP_CLIENT_SUPPORT */
2360 /* And finally delete the node */
2362 return COAP_INVALID_MID;
2363}
2364
2365static int
2367 uint8_t *data;
2368 size_t data_len;
2369 int result = -1;
2370
2371 coap_packet_get_memmapped(packet, &data, &data_len);
2372 if (session->proto == COAP_PROTO_DTLS) {
2373#if COAP_SERVER_SUPPORT
2374 if (session->type == COAP_SESSION_TYPE_HELLO)
2375 result = coap_dtls_hello(session, data, data_len);
2376 else
2377#endif /* COAP_SERVER_SUPPORT */
2378 if (session->tls)
2379 result = coap_dtls_receive(session, data, data_len);
2380 } else if (session->proto == COAP_PROTO_UDP) {
2381 result = coap_handle_dgram(ctx, session, data, data_len);
2382 }
2383 return result;
2384}
2385
2386#if COAP_CLIENT_SUPPORT
2387void
2389#if COAP_DISABLE_TCP
2390 (void)now;
2391
2393#else /* !COAP_DISABLE_TCP */
2394 if (coap_netif_strm_connect2(session)) {
2395 session->last_rx_tx = now;
2397 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2398 } else {
2401 }
2402#endif /* !COAP_DISABLE_TCP */
2403}
2404#endif /* COAP_CLIENT_SUPPORT */
2405
2406static void
2408 (void)ctx;
2409 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2410
2411 while (session->delayqueue) {
2412 ssize_t bytes_written;
2413 coap_queue_t *q = session->delayqueue;
2414
2415 coap_address_copy(&session->addr_info.remote, &q->remote);
2416 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2417 coap_session_str(session), (int)q->pdu->mid);
2418 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2419 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2420 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2421 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2422 if (bytes_written > 0)
2423 session->last_rx_tx = now;
2424 if (bytes_written <= 0 ||
2425 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2426 if (bytes_written > 0)
2427 session->partial_write += (size_t)bytes_written;
2428 break;
2429 }
2430 session->delayqueue = q->next;
2431 session->partial_write = 0;
2433 }
2434}
2435
2436void
2438#if COAP_CONSTRAINED_STACK
2439 /* payload and packet can be protected by global_lock if needed */
2440 static unsigned char payload[COAP_RXBUFFER_SIZE];
2441 static coap_packet_t s_packet;
2442#else /* ! COAP_CONSTRAINED_STACK */
2443 unsigned char payload[COAP_RXBUFFER_SIZE];
2444 coap_packet_t s_packet;
2445#endif /* ! COAP_CONSTRAINED_STACK */
2446 coap_packet_t *packet = &s_packet;
2447
2449
2450 packet->length = sizeof(payload);
2451 packet->payload = payload;
2452
2453 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2454 ssize_t bytes_read;
2455 coap_address_t remote;
2456
2457 coap_address_copy(&remote, &session->addr_info.remote);
2458 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2459 bytes_read = coap_netif_dgrm_read(session, packet);
2460
2461 if (bytes_read < 0) {
2462 if (bytes_read == -2) {
2463 coap_address_copy(&session->addr_info.remote, &remote);
2464 /* Reset the session back to startup defaults */
2466 }
2467 } else if (bytes_read > 0) {
2468 session->last_rx_tx = now;
2469#if COAP_CLIENT_SUPPORT
2470 if (session->session_failed)
2471 session->session_failed = 0;
2472#endif /* COAP_CLIENT_SUPPORT */
2473 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2474 coap_handle_dgram_for_proto(ctx, session, packet);
2475 } else {
2476 coap_address_copy(&session->addr_info.remote, &remote);
2477 }
2478#if !COAP_DISABLE_TCP
2479 } else if (session->proto == COAP_PROTO_WS ||
2480 session->proto == COAP_PROTO_WSS) {
2481 ssize_t bytes_read = 0;
2482
2483 /* WebSocket layer passes us the whole packet */
2484 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2485 packet->payload,
2486 packet->length);
2487 if (bytes_read < 0) {
2489 } else if (bytes_read > 2) {
2490 coap_pdu_t *pdu;
2491
2492 session->last_rx_tx = now;
2493 /* Need max space incase PDU is updated with updated token etc. */
2494 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2495 if (!pdu) {
2496 return;
2497 }
2498
2499 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2501 coap_log_warn("discard malformed PDU\n");
2503 return;
2504 }
2505
2506 coap_dispatch(ctx, session, pdu);
2508 return;
2509 }
2510 } else {
2511 ssize_t bytes_read = 0;
2512 const uint8_t *p;
2513 int retry;
2514
2515 do {
2516 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2517 packet->payload,
2518 packet->length);
2519 if (bytes_read > 0) {
2520 session->last_rx_tx = now;
2521 }
2522 p = packet->payload;
2523 retry = bytes_read == (ssize_t)packet->length;
2524 while (bytes_read > 0) {
2525 if (session->partial_pdu) {
2526 size_t len = session->partial_pdu->used_size
2527 + session->partial_pdu->hdr_size
2528 - session->partial_read;
2529 size_t n = min(len, (size_t)bytes_read);
2530 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2531 + session->partial_read, p, n);
2532 p += n;
2533 bytes_read -= n;
2534 if (n == len) {
2535 coap_opt_filter_t error_opts;
2536 coap_pdu_t *pdu = session->partial_pdu;
2537
2538 session->partial_pdu = NULL;
2539 session->partial_read = 0;
2540
2541 coap_option_filter_clear(&error_opts);
2542 if (coap_pdu_parse_header(pdu, session->proto)
2543 && coap_pdu_parse_opt(pdu, &error_opts)) {
2544 coap_dispatch(ctx, session, pdu);
2545 } else if (error_opts.mask) {
2546 coap_pdu_t *response =
2548 COAP_RESPONSE_CODE(402), &error_opts);
2549 if (!response) {
2550 coap_log_warn("coap_read_session: cannot create error response\n");
2551 } else {
2552 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2553 coap_log_warn("coap_read_session: error sending response\n");
2554 }
2555 }
2557 } else {
2558 session->partial_read += n;
2559 }
2560 } else if (session->partial_read > 0) {
2561 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2562 session->read_header);
2563 size_t tkl = session->read_header[0] & 0x0f;
2564 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2565 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2566 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2567 size_t n = min(len, (size_t)bytes_read);
2568 memcpy(session->read_header + session->partial_read, p, n);
2569 p += n;
2570 bytes_read -= n;
2571 if (n == len) {
2572 /* Header now all in */
2573 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2574 hdr_size + tok_ext_bytes);
2575 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2576 coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
2577 coap_session_str(session),
2578 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2579 bytes_read = -1;
2580 break;
2581 }
2582 /* Need max space incase PDU is updated with updated token etc. */
2583 session->partial_pdu = coap_pdu_init(0, 0, 0,
2585 if (session->partial_pdu == NULL) {
2586 bytes_read = -1;
2587 break;
2588 }
2589 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2590 bytes_read = -1;
2591 break;
2592 }
2593 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2594 session->partial_pdu->used_size = size;
2595 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2596 session->partial_read = hdr_size + tok_ext_bytes;
2597 if (size == 0) {
2598 coap_pdu_t *pdu = session->partial_pdu;
2599
2600 session->partial_pdu = NULL;
2601 session->partial_read = 0;
2602 if (coap_pdu_parse_header(pdu, session->proto)) {
2603 coap_dispatch(ctx, session, pdu);
2604 }
2606 }
2607 } else {
2608 /* More of the header to go */
2609 session->partial_read += n;
2610 }
2611 } else {
2612 /* Get in first byte of the header */
2613 session->read_header[0] = *p++;
2614 bytes_read -= 1;
2615 if (!coap_pdu_parse_header_size(session->proto,
2616 session->read_header)) {
2617 bytes_read = -1;
2618 break;
2619 }
2620 session->partial_read = 1;
2621 }
2622 }
2623 } while (bytes_read == 0 && retry);
2624 if (bytes_read < 0)
2626#endif /* !COAP_DISABLE_TCP */
2627 }
2628}
2629
2630#if COAP_SERVER_SUPPORT
2631static int
2632coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2633 ssize_t bytes_read = -1;
2634 int result = -1; /* the value to be returned */
2635#if COAP_CONSTRAINED_STACK
2636 /* payload and e_packet can be protected by global_lock if needed */
2637 static unsigned char payload[COAP_RXBUFFER_SIZE];
2638 static coap_packet_t e_packet;
2639#else /* ! COAP_CONSTRAINED_STACK */
2640 unsigned char payload[COAP_RXBUFFER_SIZE];
2641 coap_packet_t e_packet;
2642#endif /* ! COAP_CONSTRAINED_STACK */
2643 coap_packet_t *packet = &e_packet;
2644
2645 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2646 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2647
2648 /* Need to do this as there may be holes in addr_info */
2649 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2650 packet->length = sizeof(payload);
2651 packet->payload = payload;
2653 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2654
2655 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2656 if (bytes_read < 0) {
2657 if (errno != EAGAIN) {
2658 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2659 }
2660 } else if (bytes_read > 0) {
2661 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2662 if (session) {
2664 coap_log_debug("* %s: netif: recv %4zd bytes\n",
2665 coap_session_str(session), bytes_read);
2666 result = coap_handle_dgram_for_proto(ctx, session, packet);
2667 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2668 coap_session_new_dtls_session(session, now);
2669 coap_session_release_lkd(session);
2670 }
2671 }
2672 return result;
2673}
2674
2675static int
2676coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2677 (void)ctx;
2678 (void)endpoint;
2679 (void)now;
2680 return 0;
2681}
2682
2683#if !COAP_DISABLE_TCP
2684static int
2685coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2686 coap_tick_t now, void *extra) {
2687 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2688 if (session)
2689 session->last_rx_tx = now;
2690 return session != NULL;
2691}
2692#endif /* !COAP_DISABLE_TCP */
2693#endif /* COAP_SERVER_SUPPORT */
2694
2695COAP_API void
2697 coap_lock_lock(return);
2698 coap_io_do_io_lkd(ctx, now);
2700}
2701
2702void
2704#ifdef COAP_EPOLL_SUPPORT
2705 (void)ctx;
2706 (void)now;
2707 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2708#else /* ! COAP_EPOLL_SUPPORT */
2709 coap_session_t *s, *rtmp;
2710
2712#if COAP_SERVER_SUPPORT
2713 coap_endpoint_t *ep, *tmp;
2714 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2715 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2716 coap_read_endpoint(ctx, ep, now);
2717 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2718 coap_write_endpoint(ctx, ep, now);
2719#if !COAP_DISABLE_TCP
2720 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2721 coap_accept_endpoint(ctx, ep, now, NULL);
2722#endif /* !COAP_DISABLE_TCP */
2723 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2724 /* Make sure the session object is not deleted in one of the callbacks */
2726 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2727 coap_read_session(ctx, s, now);
2728 }
2729 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2730 coap_write_session(ctx, s, now);
2731 }
2733 }
2734 }
2735#endif /* COAP_SERVER_SUPPORT */
2736
2737#if COAP_CLIENT_SUPPORT
2738 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2739 /* Make sure the session object is not deleted in one of the callbacks */
2741 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2742 coap_connect_session(s, now);
2743 }
2744 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2745 coap_read_session(ctx, s, now);
2746 }
2747 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2748 coap_write_session(ctx, s, now);
2749 }
2751 }
2752#endif /* COAP_CLIENT_SUPPORT */
2753#endif /* ! COAP_EPOLL_SUPPORT */
2754}
2755
2756COAP_API void
2757coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2758 coap_lock_lock(return);
2759 coap_io_do_epoll_lkd(ctx, events, nevents);
2761}
2762
2763/*
2764 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2765 * directly saves having to iterate through the endpoints / sessions.
2766 */
2767void
2768coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2769#ifndef COAP_EPOLL_SUPPORT
2770 (void)ctx;
2771 (void)events;
2772 (void)nevents;
2773 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2774#else /* COAP_EPOLL_SUPPORT */
2775 coap_tick_t now;
2776 size_t j;
2777
2779 coap_ticks(&now);
2780 for (j = 0; j < nevents; j++) {
2781 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2782
2783 /* Ignore 'timer trigger' ptr which is NULL */
2784 if (sock) {
2785#if COAP_SERVER_SUPPORT
2786 if (sock->endpoint) {
2787 coap_endpoint_t *endpoint = sock->endpoint;
2788 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2789 (events[j].events & EPOLLIN)) {
2790 sock->flags |= COAP_SOCKET_CAN_READ;
2791 coap_read_endpoint(endpoint->context, endpoint, now);
2792 }
2793
2794 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2795 (events[j].events & EPOLLOUT)) {
2796 /*
2797 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2798 * be true causing epoll_wait to return early
2799 */
2800 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2802 coap_write_endpoint(endpoint->context, endpoint, now);
2803 }
2804
2805#if !COAP_DISABLE_TCP
2806 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2807 (events[j].events & EPOLLIN)) {
2809 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2810 }
2811#endif /* !COAP_DISABLE_TCP */
2812
2813 } else
2814#endif /* COAP_SERVER_SUPPORT */
2815 if (sock->session) {
2816 coap_session_t *session = sock->session;
2817
2818 /* Make sure the session object is not deleted
2819 in one of the callbacks */
2821#if COAP_CLIENT_SUPPORT
2822 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2823 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2825 coap_connect_session(session, now);
2826 if (coap_netif_available(session) &&
2827 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2828 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2829 }
2830 }
2831#endif /* COAP_CLIENT_SUPPORT */
2832
2833 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2834 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2835 sock->flags |= COAP_SOCKET_CAN_READ;
2836 coap_read_session(session->context, session, now);
2837 }
2838
2839 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2840 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2841 /*
2842 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2843 * be true causing epoll_wait to return early
2844 */
2845 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2847 coap_write_session(session->context, session, now);
2848 }
2849 /* Now dereference session so it can go away if needed */
2850 coap_session_release_lkd(session);
2851 }
2852 } else if (ctx->eptimerfd != -1) {
2853 /*
2854 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2855 * it so that it does not set EPOLLIN in the next epoll_wait().
2856 */
2857 uint64_t count;
2858
2859 /* Check the result from read() to suppress the warning on
2860 * systems that declare read() with warn_unused_result. */
2861 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2862 /* do nothing */;
2863 }
2864 }
2865 }
2866 /* And update eptimerfd as to when to next trigger */
2867 coap_ticks(&now);
2868 coap_io_prepare_epoll_lkd(ctx, now);
2869#endif /* COAP_EPOLL_SUPPORT */
2870}
2871
2872int
2874 uint8_t *msg, size_t msg_len) {
2875
2876 coap_pdu_t *pdu = NULL;
2877 coap_opt_filter_t error_opts;
2878
2879 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2880 if (msg_len < 4) {
2881 /* Minimum size of CoAP header - ignore runt */
2882 return -1;
2883 }
2884 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2885 /*
2886 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2887 * this MUST be silently ignored.
2888 */
2889 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2890 return -1;
2891 }
2892
2893 /* Need max space incase PDU is updated with updated token etc. */
2894 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2895 if (!pdu)
2896 goto error;
2897
2898 coap_option_filter_clear(&error_opts);
2899 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
2901 coap_log_warn("discard malformed PDU\n");
2902 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
2903 coap_pdu_t *response =
2905 COAP_RESPONSE_CODE(402), &error_opts);
2906 if (!response) {
2907 coap_log_warn("coap_handle_dgram: cannot create error response\n");
2908 } else {
2909 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2910 coap_log_warn("coap_handle_dgram: error sending response\n");
2911 }
2913 return -1;
2914 } else {
2915 goto error;
2916 }
2917 }
2918
2919 coap_dispatch(ctx, session, pdu);
2921 return 0;
2922
2923error:
2924 /*
2925 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2926 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2927 */
2928 coap_send_rst_lkd(session, pdu);
2930 return -1;
2931}
2932
2933int
2935 coap_queue_t **node) {
2936 coap_queue_t *p, *q;
2937
2938 if (!queue || !*queue)
2939 return 0;
2940
2941 /* replace queue head if PDU's time is less than head's time */
2942
2943 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2944 *node = *queue;
2945 *queue = (*queue)->next;
2946 if (*queue) { /* adjust relative time of new queue head */
2947 (*queue)->t += (*node)->t;
2948 }
2949 (*node)->next = NULL;
2950 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2951 coap_session_str(session), id);
2952 return 1;
2953 }
2954
2955 /* search message id in queue to remove (only first occurence will be removed) */
2956 q = *queue;
2957 do {
2958 p = q;
2959 q = q->next;
2960 } while (q && (session != q->session || id != q->id));
2961
2962 if (q) { /* found message id */
2963 p->next = q->next;
2964 if (p->next) { /* must update relative time of p->next */
2965 p->next->t += q->t;
2966 }
2967 q->next = NULL;
2968 *node = q;
2969 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
2970 coap_session_str(session), id);
2971 return 1;
2972 }
2973
2974 return 0;
2975
2976}
2977
2978static int
2980 coap_bin_const_t *token, coap_queue_t **node) {
2981 coap_queue_t *p, *q;
2982
2983 if (!queue || !*queue)
2984 return 0;
2985
2986 /* replace queue head if PDU's time is less than head's time */
2987
2988 if (session == (*queue)->session &&
2989 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
2990 *node = *queue;
2991 *queue = (*queue)->next;
2992 if (*queue) { /* adjust relative time of new queue head */
2993 (*queue)->t += (*node)->t;
2994 }
2995 (*node)->next = NULL;
2996 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
2997 coap_session_str(session), (*node)->id);
2998 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2999 session->con_active--;
3000 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3001 /* Flush out any entries on session->delayqueue */
3002 coap_session_connected(session);
3003 }
3004 return 1;
3005 }
3006
3007 /* search token in queue to remove (only first occurence will be removed) */
3008 q = *queue;
3009 do {
3010 p = q;
3011 q = q->next;
3012 } while (q && (session != q->session ||
3013 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3014
3015 if (q) { /* found token */
3016 p->next = q->next;
3017 if (p->next) { /* must update relative time of p->next */
3018 p->next->t += q->t;
3019 }
3020 q->next = NULL;
3021 *node = q;
3022 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3023 coap_session_str(session), (*node)->id);
3024 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3025 session->con_active--;
3026 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3027 /* Flush out any entries on session->delayqueue */
3028 coap_session_connected(session);
3029 }
3030 return 1;
3031 }
3032
3033 return 0;
3034
3035}
3036
3037void
3039 coap_nack_reason_t reason) {
3040 coap_queue_t *p, *q;
3041
3042 while (context->sendqueue && context->sendqueue->session == session) {
3043 q = context->sendqueue;
3044 context->sendqueue = q->next;
3045 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3046 coap_session_str(session), q->id);
3047 if (q->pdu->type == COAP_MESSAGE_CON) {
3048 coap_handle_nack(session, q->pdu, reason, q->id);
3049 }
3051 }
3052
3053 if (!context->sendqueue)
3054 return;
3055
3056 p = context->sendqueue;
3057 q = p->next;
3058
3059 while (q) {
3060 if (q->session == session) {
3061 p->next = q->next;
3062 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3063 coap_session_str(session), q->id);
3064 if (q->pdu->type == COAP_MESSAGE_CON) {
3065 coap_handle_nack(session, q->pdu, reason, q->id);
3066 }
3068 q = p->next;
3069 } else {
3070 p = q;
3071 q = q->next;
3072 }
3073 }
3074}
3075
3076void
3078 coap_bin_const_t *token) {
3079 /* cancel all messages in sendqueue that belong to session
3080 * and use the specified token */
3081 coap_queue_t **p, *q;
3082
3083 if (!context->sendqueue)
3084 return;
3085
3086 p = &context->sendqueue;
3087 q = *p;
3088
3089 while (q) {
3090 if (q->session == session &&
3091 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3092 *p = q->next;
3093 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3094 coap_session_str(session), q->id);
3095 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3096 session->con_active--;
3097 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3098 /* Flush out any entries on session->delayqueue */
3099 coap_session_connected(session);
3100 }
3102 } else {
3103 p = &(q->next);
3104 }
3105 q = *p;
3106 }
3107}
3108
3109coap_pdu_t *
3111 coap_opt_filter_t *opts) {
3112 coap_opt_iterator_t opt_iter;
3113 coap_pdu_t *response;
3114 unsigned char type;
3115
3116#if COAP_ERROR_PHRASE_LENGTH > 0
3117 const char *phrase;
3118 if (code != COAP_RESPONSE_CODE(508)) {
3119 phrase = coap_response_phrase(code);
3120 } else {
3121 phrase = NULL;
3122 }
3123#endif
3124
3125 assert(request);
3126
3127 /* cannot send ACK if original request was not confirmable */
3128 type = request->type == COAP_MESSAGE_CON ?
3130
3131 /* Now create the response and fill with options and payload data. */
3132 response = coap_pdu_init(type, code, request->mid,
3133 request->session ?
3134 coap_session_max_pdu_size_lkd(request->session) : 512);
3135 if (response) {
3136 /* copy token */
3137 if (!coap_add_token(response, request->actual_token.length,
3138 request->actual_token.s)) {
3139 coap_log_debug("cannot add token to error response\n");
3140 coap_delete_pdu_lkd(response);
3141 return NULL;
3142 }
3143 if (response->code == COAP_RESPONSE_CODE(402)) {
3144 char buf[128];
3145 int first = 1;
3146
3147#if COAP_ERROR_PHRASE_LENGTH > 0
3148 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3149#else
3150 buf[0] = '\000';
3151#endif
3152 /* copy all options into diagnostic message */
3153 coap_option_iterator_init(request, &opt_iter, opts);
3154 while (coap_option_next(&opt_iter)) {
3155 size_t len = strlen(buf);
3156
3157 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",", opt_iter.number);
3158 first = 0;
3159 }
3160 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3161 } else if (opts && opts->mask) {
3162 coap_opt_t *option;
3163
3164 /* copy all options */
3165 coap_option_iterator_init(request, &opt_iter, opts);
3166 while ((option = coap_option_next(&opt_iter))) {
3167 coap_add_option_internal(response, opt_iter.number,
3168 coap_opt_length(option),
3169 coap_opt_value(option));
3170 }
3171#if COAP_ERROR_PHRASE_LENGTH > 0
3172 if (phrase)
3173 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3174 } else {
3175 /* note that diagnostic messages do not need a Content-Format option. */
3176 if (phrase)
3177 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3178#endif
3179 }
3180 }
3181
3182 return response;
3183}
3184
3185#if COAP_SERVER_SUPPORT
3186#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3187
3188static void
3189free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3190 coap_delete_string(app_ptr);
3191}
3192
3193/*
3194 * Caution: As this handler is in libcoap space, it is called with
3195 * context locked.
3196 */
3197static void
3198hnd_get_wellknown_lkd(coap_resource_t *resource,
3199 coap_session_t *session,
3200 const coap_pdu_t *request,
3201 const coap_string_t *query,
3202 coap_pdu_t *response) {
3203 size_t len = 0;
3204 coap_string_t *data_string = NULL;
3205 coap_print_status_t result = 0;
3206 size_t wkc_len = 0;
3207 uint8_t buf[4];
3208
3209 /*
3210 * Quick hack to determine the size of the resource descriptions for
3211 * .well-known/core.
3212 */
3213 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3214 if (result & COAP_PRINT_STATUS_ERROR) {
3215 coap_log_warn("cannot determine length of /.well-known/core\n");
3216 goto error;
3217 }
3218
3219 if (wkc_len > 0) {
3220 data_string = coap_new_string(wkc_len);
3221 if (!data_string)
3222 goto error;
3223
3224 len = wkc_len;
3225 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3226 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3227 coap_log_debug("coap_print_wellknown failed\n");
3228 goto error;
3229 }
3230 assert(len <= (size_t)wkc_len);
3231 data_string->length = len;
3232
3233 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3235 coap_encode_var_safe(buf, sizeof(buf),
3237 goto error;
3238 }
3239 if (response->used_size + len + 1 > response->max_size) {
3240 /*
3241 * Data does not fit into a packet and no libcoap block support
3242 * +1 for end of options marker
3243 */
3244 coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
3245 len, response->max_size - response->used_size - 1);
3246 len = response->max_size - response->used_size - 1;
3247 }
3248 if (!coap_add_data(response, len, data_string->s)) {
3249 goto error;
3250 }
3251 free_wellknown_response(session, data_string);
3252 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3253 response, query,
3255 -1, 0, data_string->length,
3256 data_string->s,
3257 free_wellknown_response,
3258 data_string)) {
3259 goto error_released;
3260 }
3261 } else {
3263 coap_encode_var_safe(buf, sizeof(buf),
3265 goto error;
3266 }
3267 }
3268 response->code = COAP_RESPONSE_CODE(205);
3269 return;
3270
3271error:
3272 free_wellknown_response(session, data_string);
3273error_released:
3274 if (response->code == 0) {
3275 /* set error code 5.03 and remove all options and data from response */
3276 response->code = COAP_RESPONSE_CODE(503);
3277 response->used_size = response->e_token_length;
3278 response->data = NULL;
3279 }
3280}
3281#endif /* COAP_SERVER_SUPPORT */
3282
3293static int
3295 int num_cancelled = 0; /* the number of observers cancelled */
3296
3297#ifndef COAP_SERVER_SUPPORT
3298 (void)sent;
3299#endif /* ! COAP_SERVER_SUPPORT */
3300 (void)context;
3301
3302#if COAP_SERVER_SUPPORT
3303 /* remove observer for this resource, if any
3304 * Use token from sent and try to find a matching resource. Uh!
3305 */
3306 RESOURCES_ITER(context->resources, r) {
3307 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3308 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3309 }
3310#endif /* COAP_SERVER_SUPPORT */
3311
3312 return num_cancelled;
3313}
3314
3315#if COAP_SERVER_SUPPORT
3320enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3321
3322/*
3323 * Checks for No-Response option in given @p request and
3324 * returns @c RESPONSE_DROP if @p response should be suppressed
3325 * according to RFC 7967.
3326 *
3327 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3328 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3329 * on retrying.
3330 *
3331 * Checks if the response code is 0.00 and if either the session is reliable or
3332 * non-confirmable, @c RESPONSE_DROP is also returned.
3333 *
3334 * Multicast response checking is also carried out.
3335 *
3336 * NOTE: It is the responsibility of the application to determine whether
3337 * a delayed separate response should be sent as the original requesting packet
3338 * containing the No-Response option has long since gone.
3339 *
3340 * The value of the No-Response option is encoded as
3341 * follows:
3342 *
3343 * @verbatim
3344 * +-------+-----------------------+-----------------------------------+
3345 * | Value | Binary Representation | Description |
3346 * +-------+-----------------------+-----------------------------------+
3347 * | 0 | <empty> | Interested in all responses. |
3348 * +-------+-----------------------+-----------------------------------+
3349 * | 2 | 00000010 | Not interested in 2.xx responses. |
3350 * +-------+-----------------------+-----------------------------------+
3351 * | 8 | 00001000 | Not interested in 4.xx responses. |
3352 * +-------+-----------------------+-----------------------------------+
3353 * | 16 | 00010000 | Not interested in 5.xx responses. |
3354 * +-------+-----------------------+-----------------------------------+
3355 * @endverbatim
3356 *
3357 * @param request The CoAP request to check for the No-Response option.
3358 * This parameter must not be NULL.
3359 * @param response The response that is potentially suppressed.
3360 * This parameter must not be NULL.
3361 * @param session The session this request/response are associated with.
3362 * This parameter must not be NULL.
3363 * @return RESPONSE_DEFAULT when no special treatment is requested,
3364 * RESPONSE_DROP when the response must be discarded, or
3365 * RESPONSE_SEND when the response must be sent.
3366 */
3367static enum respond_t
3368no_response(coap_pdu_t *request, coap_pdu_t *response,
3369 coap_session_t *session, coap_resource_t *resource) {
3370 coap_opt_t *nores;
3371 coap_opt_iterator_t opt_iter;
3372 unsigned int val = 0;
3373
3374 assert(request);
3375 assert(response);
3376
3377 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3378 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3379
3380 if (nores) {
3382
3383 /* The response should be dropped when the bit corresponding to
3384 * the response class is set (cf. table in function
3385 * documentation). When a No-Response option is present and the
3386 * bit is not set, the sender explicitly indicates interest in
3387 * this response. */
3388 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3389 /* Should be dropping the response */
3390 if (response->type == COAP_MESSAGE_ACK &&
3391 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3392 /* Still need to ACK the request */
3393 response->code = 0;
3394 /* Remove token/data from piggybacked acknowledgment PDU */
3395 response->actual_token.length = 0;
3396 response->e_token_length = 0;
3397 response->used_size = 0;
3398 response->data = NULL;
3399 return RESPONSE_SEND;
3400 } else {
3401 return RESPONSE_DROP;
3402 }
3403 } else {
3404 /* True for mcast as well RFC7967 2.1 */
3405 return RESPONSE_SEND;
3406 }
3407 } else if (resource && session->context->mcast_per_resource &&
3408 coap_is_mcast(&session->addr_info.local)) {
3409 /* Handle any mcast suppression specifics if no NoResponse option */
3410 if ((resource->flags &
3412 COAP_RESPONSE_CLASS(response->code) == 2) {
3413 return RESPONSE_DROP;
3414 } else if ((resource->flags &
3416 response->code == COAP_RESPONSE_CODE(205)) {
3417 if (response->data == NULL)
3418 return RESPONSE_DROP;
3419 } else if ((resource->flags &
3421 COAP_RESPONSE_CLASS(response->code) == 4) {
3422 return RESPONSE_DROP;
3423 } else if ((resource->flags &
3425 COAP_RESPONSE_CLASS(response->code) == 5) {
3426 return RESPONSE_DROP;
3427 }
3428 }
3429 } else if (COAP_PDU_IS_EMPTY(response) &&
3430 (response->type == COAP_MESSAGE_NON ||
3431 COAP_PROTO_RELIABLE(session->proto))) {
3432 /* response is 0.00, and this is reliable or non-confirmable */
3433 return RESPONSE_DROP;
3434 }
3435
3436 /*
3437 * Do not send error responses for requests that were received via
3438 * IP multicast. RFC7252 8.1
3439 */
3440
3441 if (coap_is_mcast(&session->addr_info.local)) {
3442 if (request->type == COAP_MESSAGE_NON &&
3443 response->type == COAP_MESSAGE_RST)
3444 return RESPONSE_DROP;
3445
3446 if ((!resource || session->context->mcast_per_resource == 0) &&
3447 COAP_RESPONSE_CLASS(response->code) > 2)
3448 return RESPONSE_DROP;
3449 }
3450
3451 /* Default behavior applies when we are not dealing with a response
3452 * (class == 0) or the request did not contain a No-Response option.
3453 */
3454 return RESPONSE_DEFAULT;
3455}
3456
3457static coap_str_const_t coap_default_uri_wellknown = {
3459 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3460};
3461
3462/* Initialized in coap_startup() */
3463static coap_resource_t resource_uri_wellknown;
3464
3465static void
3466handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3467 coap_pdu_t *orig_pdu) {
3468 coap_method_handler_t h = NULL;
3469 coap_pdu_t *response = NULL;
3470 coap_opt_filter_t opt_filter;
3471 coap_resource_t *resource = NULL;
3472 /* The respond field indicates whether a response must be treated
3473 * specially due to a No-Response option that declares disinterest
3474 * or interest in a specific response class. DEFAULT indicates that
3475 * No-Response has not been specified. */
3476 enum respond_t respond = RESPONSE_DEFAULT;
3477 coap_opt_iterator_t opt_iter;
3478 coap_opt_t *opt;
3479 int is_proxy_uri = 0;
3480 int is_proxy_scheme = 0;
3481 int skip_hop_limit_check = 0;
3482 int resp = 0;
3483 int send_early_empty_ack = 0;
3484 coap_string_t *query = NULL;
3485 coap_opt_t *observe = NULL;
3486 coap_string_t *uri_path = NULL;
3487 int observe_action = COAP_OBSERVE_CANCEL;
3488 coap_block_b_t block;
3489 int added_block = 0;
3490 coap_lg_srcv_t *free_lg_srcv = NULL;
3491#if COAP_Q_BLOCK_SUPPORT
3492 int lg_xmit_ctrl = 0;
3493#endif /* COAP_Q_BLOCK_SUPPORT */
3494#if COAP_ASYNC_SUPPORT
3495 coap_async_t *async;
3496#endif /* COAP_ASYNC_SUPPORT */
3497
3498 if (coap_is_mcast(&session->addr_info.local)) {
3499 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3500 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3501 return;
3502 }
3503 }
3504#if COAP_ASYNC_SUPPORT
3505 async = coap_find_async_lkd(session, pdu->actual_token);
3506 if (async) {
3507 coap_tick_t now;
3508
3509 coap_ticks(&now);
3510 if (async->delay == 0 || async->delay > now) {
3511 /* re-transmit missing ACK (only if CON) */
3512 coap_log_info("Retransmit async response\n");
3513 coap_send_ack_lkd(session, pdu);
3514 /* and do not pass on to the upper layers */
3515 return;
3516 }
3517 }
3518#endif /* COAP_ASYNC_SUPPORT */
3519
3520 coap_option_filter_clear(&opt_filter);
3521 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3522 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3523 if (opt) {
3524 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3525 if (!opt) {
3526 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3527 resp = 402;
3528 goto fail_response;
3529 }
3530 is_proxy_scheme = 1;
3531 }
3532
3533 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3534 if (opt)
3535 is_proxy_uri = 1;
3536 }
3537
3538 if (is_proxy_scheme || is_proxy_uri) {
3539 coap_uri_t uri;
3540
3541 if (!context->proxy_uri_resource) {
3542 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3543 coap_log_debug("Proxy-%s support not configured\n",
3544 is_proxy_scheme ? "Scheme" : "Uri");
3545 resp = 505;
3546 goto fail_response;
3547 }
3548 if (((size_t)pdu->code - 1 <
3549 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3550 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3551 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3552 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3553 is_proxy_scheme ? "Scheme" : "Uri",
3554 pdu->code/100, pdu->code%100);
3555 resp = 505;
3556 goto fail_response;
3557 }
3558
3559 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3560 if (is_proxy_uri) {
3562 coap_opt_length(opt), &uri) < 0) {
3563 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3564 coap_log_debug("Proxy-URI not decodable\n");
3565 resp = 505;
3566 goto fail_response;
3567 }
3568 } else {
3569 memset(&uri, 0, sizeof(uri));
3570 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3571 if (opt) {
3572 uri.host.length = coap_opt_length(opt);
3573 uri.host.s = coap_opt_value(opt);
3574 } else
3575 uri.host.length = 0;
3576 }
3577
3578 resource = context->proxy_uri_resource;
3579 if (uri.host.length && resource->proxy_name_count &&
3580 resource->proxy_name_list) {
3581 size_t i;
3582
3583 if (resource->proxy_name_count == 1 &&
3584 resource->proxy_name_list[0]->length == 0) {
3585 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3586 i = 0;
3587 } else {
3588 for (i = 0; i < resource->proxy_name_count; i++) {
3589 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3590 break;
3591 }
3592 }
3593 }
3594 if (i != resource->proxy_name_count) {
3595 /* This server is hosting the proxy connection endpoint */
3596 if (pdu->crit_opt) {
3597 /* Cannot handle critical option */
3598 pdu->crit_opt = 0;
3599 resp = 402;
3600 goto fail_response;
3601 }
3602 is_proxy_uri = 0;
3603 is_proxy_scheme = 0;
3604 skip_hop_limit_check = 1;
3605 }
3606 }
3607 resource = NULL;
3608 }
3609
3610 if (!skip_hop_limit_check) {
3611 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3612 if (opt) {
3613 size_t hop_limit;
3614 uint8_t buf[4];
3615
3616 hop_limit =
3618 if (hop_limit == 1) {
3619 /* coap_send_internal() will fill in the IP address for us */
3620 resp = 508;
3621 goto fail_response;
3622 } else if (hop_limit < 1 || hop_limit > 255) {
3623 /* Need to return a 4.00 RFC8768 Section 3 */
3624 coap_log_info("Invalid Hop Limit\n");
3625 resp = 400;
3626 goto fail_response;
3627 }
3628 hop_limit--;
3630 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3631 buf);
3632 }
3633 }
3634
3635 uri_path = coap_get_uri_path(pdu);
3636 if (!uri_path)
3637 return;
3638
3639 if (!is_proxy_uri && !is_proxy_scheme) {
3640 /* try to find the resource from the request URI */
3641 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3642 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3643 }
3644
3645 if ((resource == NULL) || (resource->is_unknown == 1) ||
3646 (resource->is_proxy_uri == 1)) {
3647 /* The resource was not found or there is an unexpected match against the
3648 * resource defined for handling unknown or proxy URIs.
3649 */
3650 if (resource != NULL)
3651 /* Close down unexpected match */
3652 resource = NULL;
3653 /*
3654 * Check if the request URI happens to be the well-known URI, or if the
3655 * unknown resource handler is defined, a PUT or optionally other methods,
3656 * if configured, for the unknown handler.
3657 *
3658 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3659 * proxy URI handler.
3660 *
3661 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3662 * set, call the unknown URI handler with any unknown URI (including
3663 * .well-known/core) if the appropriate method is defined.
3664 *
3665 * else if well-known URI generate a default response.
3666 *
3667 * else if unknown URI handler defined, call the unknown
3668 * URI handler (to allow for potential generation of resource
3669 * [RFC7272 5.8.3]) if the appropriate method is defined.
3670 *
3671 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3672 *
3673 * else return 4.04.
3674 */
3675
3676 if (is_proxy_uri || is_proxy_scheme) {
3677 resource = context->proxy_uri_resource;
3678 } else if (context->unknown_resource != NULL &&
3680 ((size_t)pdu->code - 1 <
3681 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3682 (context->unknown_resource->handler[pdu->code - 1])) {
3683 resource = context->unknown_resource;
3684 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3685 /* request for .well-known/core */
3686 resource = &resource_uri_wellknown;
3687 } else if ((context->unknown_resource != NULL) &&
3688 ((size_t)pdu->code - 1 <
3689 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3690 (context->unknown_resource->handler[pdu->code - 1])) {
3691 /*
3692 * The unknown_resource can be used to handle undefined resources
3693 * for a PUT request and can support any other registered handler
3694 * defined for it
3695 * Example set up code:-
3696 * r = coap_resource_unknown_init(hnd_put_unknown);
3697 * coap_register_request_handler(r, COAP_REQUEST_POST,
3698 * hnd_post_unknown);
3699 * coap_register_request_handler(r, COAP_REQUEST_GET,
3700 * hnd_get_unknown);
3701 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3702 * hnd_delete_unknown);
3703 * coap_add_resource(ctx, r);
3704 *
3705 * Note: It is not possible to observe the unknown_resource, a separate
3706 * resource must be created (by PUT or POST) which has a GET
3707 * handler to be observed
3708 */
3709 resource = context->unknown_resource;
3710 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3711 /*
3712 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3713 */
3714 coap_log_debug("request for unknown resource '%*.*s',"
3715 " return 2.02\n",
3716 (int)uri_path->length,
3717 (int)uri_path->length,
3718 uri_path->s);
3719 resp = 202;
3720 goto fail_response;
3721 } else { /* request for any another resource, return 4.04 */
3722
3723 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3724 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3725 resp = 404;
3726 goto fail_response;
3727 }
3728
3729 }
3730
3731#if COAP_OSCORE_SUPPORT
3732 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3733 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3734 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3735 resp = 401;
3736 goto fail_response;
3737 }
3738#endif /* COAP_OSCORE_SUPPORT */
3739 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3740 /* Check for existing resource and If-Non-Match */
3741 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3742 if (opt) {
3743 resp = 412;
3744 goto fail_response;
3745 }
3746 }
3747
3748 /* the resource was found, check if there is a registered handler */
3749 if ((size_t)pdu->code - 1 <
3750 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3751 h = resource->handler[pdu->code - 1];
3752
3753 if (h == NULL) {
3754 resp = 405;
3755 goto fail_response;
3756 }
3757 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3758 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3759 if (opt == NULL) {
3760 /* RFC 8132 2.3.1 */
3761 resp = 415;
3762 goto fail_response;
3763 }
3764 }
3765 if (context->mcast_per_resource &&
3766 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3767 coap_is_mcast(&session->addr_info.local)) {
3768 resp = 405;
3769 goto fail_response;
3770 }
3771
3772 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3774 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3775 if (!response) {
3776 coap_log_err("could not create response PDU\n");
3777 resp = 500;
3778 goto fail_response;
3779 }
3780 response->session = session;
3781#if COAP_ASYNC_SUPPORT
3782 /* If handling a separate response, need CON, not ACK response */
3783 if (async && pdu->type == COAP_MESSAGE_CON)
3784 response->type = COAP_MESSAGE_CON;
3785#endif /* COAP_ASYNC_SUPPORT */
3786 /* A lot of the reliable code assumes type is CON */
3787 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3788 response->type = COAP_MESSAGE_CON;
3789
3790 if (!coap_add_token(response, pdu->actual_token.length,
3791 pdu->actual_token.s)) {
3792 resp = 500;
3793 goto fail_response;
3794 }
3795
3796 query = coap_get_query(pdu);
3797
3798 /* check for Observe option RFC7641 and RFC8132 */
3799 if (resource->observable &&
3800 (pdu->code == COAP_REQUEST_CODE_GET ||
3801 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3802 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3803 }
3804
3805 /*
3806 * See if blocks need to be aggregated or next requests sent off
3807 * before invoking application request handler
3808 */
3809 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3810 uint32_t block_mode = session->block_mode;
3811
3812 if (observe ||
3815 if (coap_handle_request_put_block(context, session, pdu, response,
3816 resource, uri_path, observe,
3817 &added_block, &free_lg_srcv)) {
3818 session->block_mode = block_mode;
3819 goto skip_handler;
3820 }
3821 session->block_mode = block_mode;
3822
3823 if (coap_handle_request_send_block(session, pdu, response, resource,
3824 query)) {
3825#if COAP_Q_BLOCK_SUPPORT
3826 lg_xmit_ctrl = 1;
3827#endif /* COAP_Q_BLOCK_SUPPORT */
3828 goto skip_handler;
3829 }
3830 }
3831
3832 if (observe) {
3833 observe_action =
3835 coap_opt_length(observe));
3836
3837 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3838 coap_subscription_t *subscription;
3839
3840 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3841 if (block.num != 0) {
3842 response->code = COAP_RESPONSE_CODE(400);
3843 goto skip_handler;
3844 }
3845#if COAP_Q_BLOCK_SUPPORT
3846 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3847 &block)) {
3848 if (block.num != 0) {
3849 response->code = COAP_RESPONSE_CODE(400);
3850 goto skip_handler;
3851 }
3852#endif /* COAP_Q_BLOCK_SUPPORT */
3853 }
3854 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3855 pdu);
3856 if (subscription) {
3857 uint8_t buf[4];
3858
3859 coap_touch_observer(context, session, &pdu->actual_token);
3861 coap_encode_var_safe(buf, sizeof(buf),
3862 resource->observe),
3863 buf);
3864 }
3865 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3866 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3867 } else {
3868 coap_log_info("observe: unexpected action %d\n", observe_action);
3869 }
3870 }
3871
3872 if ((resource == context->proxy_uri_resource ||
3873 (resource == context->unknown_resource &&
3874 context->unknown_resource->is_reverse_proxy)) &&
3875 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3876 pdu->type == COAP_MESSAGE_CON &&
3877 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
3878 /* Make the proxy response separate and fix response later */
3879 send_early_empty_ack = 1;
3880 }
3881 if (send_early_empty_ack) {
3882 coap_send_ack_lkd(session, pdu);
3883 if (pdu->mid == session->last_con_mid) {
3884 /* request has already been processed - do not process it again */
3885 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3886 pdu->mid);
3887 goto drop_it_no_debug;
3888 }
3889 session->last_con_mid = pdu->mid;
3890 }
3891#if COAP_WITH_OBSERVE_PERSIST
3892 /* If we are maintaining Observe persist */
3893 if (resource == context->unknown_resource) {
3894 context->unknown_pdu = pdu;
3895 context->unknown_session = session;
3896 } else
3897 context->unknown_pdu = NULL;
3898#endif /* COAP_WITH_OBSERVE_PERSIST */
3899
3900 /*
3901 * Call the request handler with everything set up
3902 */
3903 if (resource == &resource_uri_wellknown) {
3904 /* Leave context locked */
3905 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3906 (int)resource->uri_path->length, (int)resource->uri_path->length,
3907 resource->uri_path->s);
3908 h(resource, session, pdu, query, response);
3909 } else {
3910 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3911 (int)resource->uri_path->length, (int)resource->uri_path->length,
3912 resource->uri_path->s);
3913 coap_lock_callback_release(h(resource, session, pdu, query, response),
3914 /* context is being freed off */
3915 coap_delete_string(query); goto finish);
3916 }
3917
3918 /* Check validity of response code */
3919 if (!coap_check_code_class(session, response)) {
3920 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
3921 COAP_RESPONSE_CLASS(response->code),
3922 response->code & 0x1f);
3923 goto drop_it_no_debug;
3924 }
3925
3926 /* Check if lg_xmit generated and update PDU code if so */
3927 coap_check_code_lg_xmit(session, pdu, response, resource, query);
3928
3929 if (free_lg_srcv) {
3930 /* Check to see if the server is doing a 4.01 + Echo response */
3931 if (response->code == COAP_RESPONSE_CODE(401) &&
3932 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3933 /* Need to keep lg_srcv around for client's response */
3934 } else {
3935 LL_DELETE(session->lg_srcv, free_lg_srcv);
3936 coap_block_delete_lg_srcv(session, free_lg_srcv);
3937 }
3938 }
3939 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
3940 /* Just in case, as there are more to go */
3941 response->code = COAP_RESPONSE_CODE(231);
3942 }
3943
3944skip_handler:
3945 if (send_early_empty_ack &&
3946 response->type == COAP_MESSAGE_ACK) {
3947 /* Response is now separate - convert to CON as needed */
3948 response->type = COAP_MESSAGE_CON;
3949 /* Check for empty ACK - need to drop as already sent */
3950 if (response->code == 0) {
3951 goto drop_it_no_debug;
3952 }
3953 }
3954 respond = no_response(pdu, response, session, resource);
3955 if (respond != RESPONSE_DROP) {
3956#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
3957 coap_mid_t mid = pdu->mid;
3958#endif
3959 if (COAP_RESPONSE_CLASS(response->code) != 2) {
3960 if (observe) {
3962 }
3963 }
3964 if (COAP_RESPONSE_CLASS(response->code) > 2) {
3965 if (observe)
3966 coap_delete_observer(resource, session, &pdu->actual_token);
3967 if (response->code != COAP_RESPONSE_CODE(413))
3969 }
3970
3971 /* If original request contained a token, and the registered
3972 * application handler made no changes to the response, then
3973 * this is an empty ACK with a token, which is a malformed
3974 * PDU */
3975 if ((response->type == COAP_MESSAGE_ACK)
3976 && (response->code == 0)) {
3977 /* Remove token from otherwise-empty acknowledgment PDU */
3978 response->actual_token.length = 0;
3979 response->e_token_length = 0;
3980 response->used_size = 0;
3981 response->data = NULL;
3982 }
3983
3984 if (!coap_is_mcast(&session->addr_info.local) ||
3985 (context->mcast_per_resource &&
3986 resource &&
3988 /* No delays to response */
3989#if COAP_Q_BLOCK_SUPPORT
3990 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
3991 !lg_xmit_ctrl && response->code == COAP_RESPONSE_CODE(205) &&
3992 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
3993 block.m) {
3994 if (coap_send_q_block2(session, resource, query, pdu->code, block,
3995 response,
3996 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
3997 coap_log_debug("cannot send response for mid=0x%x\n", mid);
3998 response = NULL;
3999 if (query)
4000 coap_delete_string(query);
4001 goto finish;
4002 }
4003#endif /* COAP_Q_BLOCK_SUPPORT */
4004 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4005 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4006 if (query)
4007 coap_delete_string(query);
4008 goto finish;
4009 }
4010 } else {
4011 /* Need to delay mcast response */
4012 coap_queue_t *node = coap_new_node();
4013 uint8_t r;
4014 coap_tick_t delay;
4015
4016 if (!node) {
4017 coap_log_debug("mcast delay: insufficient memory\n");
4018 goto drop_it_no_debug;
4019 }
4020 if (!coap_pdu_encode_header(response, session->proto)) {
4022 goto drop_it_no_debug;
4023 }
4024
4025 node->id = response->mid;
4026 node->pdu = response;
4027 node->is_mcast = 1;
4028 coap_prng_lkd(&r, sizeof(r));
4029 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4030 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4031 coap_session_str(session),
4032 response->mid,
4033 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4034 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4035 1000 / COAP_TICKS_PER_SECOND));
4036 node->timeout = (unsigned int)delay;
4037 /* Use this to delay transmission */
4038 coap_wait_ack(session->context, session, node);
4039 }
4040 } else {
4041 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4042 coap_session_str(session),
4043 response->mid);
4044 coap_show_pdu(COAP_LOG_DEBUG, response);
4045drop_it_no_debug:
4046 coap_delete_pdu_lkd(response);
4047 }
4048 if (query)
4049 coap_delete_string(query);
4050#if COAP_Q_BLOCK_SUPPORT
4051 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4052 if (COAP_PROTO_RELIABLE(session->proto)) {
4053 if (block.m) {
4054 /* All of the sequence not in yet */
4055 goto finish;
4056 }
4057 } else if (pdu->type == COAP_MESSAGE_NON) {
4058 /* More to go and not at a payload break */
4059 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4060 goto finish;
4061 }
4062 }
4063 }
4064#endif /* COAP_Q_BLOCK_SUPPORT */
4065
4066finish:
4067 coap_delete_string(uri_path);
4068 return;
4069
4070fail_response:
4071 coap_delete_pdu_lkd(response);
4072 response =
4074 &opt_filter);
4075 if (response)
4076 goto skip_handler;
4077 coap_delete_string(uri_path);
4078}
4079#endif /* COAP_SERVER_SUPPORT */
4080
4081#if COAP_CLIENT_SUPPORT
4082/* Call application-specific response handler when available. */
4083void
4085 coap_pdu_t *sent, coap_pdu_t *rcvd,
4086 void *body_data) {
4087 coap_context_t *context = session->context;
4088 coap_response_t ret;
4089
4090#if COAP_PROXY_SUPPORT
4091 if (context->proxy_response_handler) {
4092 coap_proxy_list_t *proxy_entry;
4093 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4094 rcvd,
4095 &proxy_entry);
4096
4097 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4098 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4099 proxy_entry);
4100 return;
4101 }
4102 }
4103#endif /* COAP_PROXY_SUPPORT */
4104 if (session->doing_send_recv && session->req_token &&
4105 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4106 /* processing coap_send_recv() call */
4107 session->resp_pdu = rcvd;
4109 /* Will get freed off when PDU is freed off */
4110 rcvd->data_free = body_data;
4111 coap_send_ack_lkd(session, rcvd);
4113 return;
4114 } else if (context->response_handler) {
4116 context->response_handler(session,
4117 sent,
4118 rcvd,
4119 rcvd->mid),
4120 /* context is being freed off */
4121 return);
4122 } else {
4123 ret = COAP_RESPONSE_OK;
4124 }
4125 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4126 coap_send_rst_lkd(session, rcvd);
4128 } else {
4129 coap_send_ack_lkd(session, rcvd);
4131 }
4132 coap_free_type(COAP_STRING, body_data);
4133}
4134
4135static void
4136handle_response(coap_context_t *context, coap_session_t *session,
4137 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4138
4139 /* Set in case there is a later call to coap_update_token() */
4140 rcvd->session = session;
4141
4142 /* Check for message duplication */
4143 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4144 if (rcvd->type == COAP_MESSAGE_CON) {
4145 if (rcvd->mid == session->last_con_mid) {
4146 /* Duplicate response: send ACK/RST, but don't process */
4147 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4148 coap_send_ack_lkd(session, rcvd);
4149 else
4150 coap_send_rst_lkd(session, rcvd);
4151 return;
4152 }
4153 session->last_con_mid = rcvd->mid;
4154 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4155 if (rcvd->mid == session->last_ack_mid) {
4156 /* Duplicate response */
4157 return;
4158 }
4159 session->last_ack_mid = rcvd->mid;
4160 }
4161 }
4162 /* Check to see if checking out extended token support */
4163 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4164 session->last_token) {
4165 coap_lg_crcv_t *lg_crcv;
4166
4167 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4168 rcvd->actual_token.length != session->max_token_size ||
4169 rcvd->code == COAP_RESPONSE_CODE(400) ||
4170 rcvd->code == COAP_RESPONSE_CODE(503)) {
4171 coap_log_debug("Extended Token requested size support not available\n");
4173 } else {
4174 coap_log_debug("Extended Token support available\n");
4175 }
4177 /* Need to remove lg_crcv set up for this test */
4178 lg_crcv = coap_find_lg_crcv(session, rcvd);
4179 if (lg_crcv) {
4180 LL_DELETE(session->lg_crcv, lg_crcv);
4181 coap_block_delete_lg_crcv(session, lg_crcv);
4182 }
4183 coap_send_ack_lkd(session, rcvd);
4184 session->doing_first = 0;
4185 return;
4186 }
4187#if COAP_Q_BLOCK_SUPPORT
4188 /* Check to see if checking out Q-Block support */
4189 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4190 session->remote_test_mid == rcvd->mid) {
4191 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4192 coap_log_debug("Q-Block support not available\n");
4193 set_block_mode_drop_q(session->block_mode);
4194 } else {
4195 coap_block_b_t qblock;
4196
4197 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4198 coap_log_debug("Q-Block support available\n");
4199 set_block_mode_has_q(session->block_mode);
4200 } else {
4201 coap_log_debug("Q-Block support not available\n");
4202 set_block_mode_drop_q(session->block_mode);
4203 }
4204 }
4205 session->doing_first = 0;
4206 return;
4207 }
4208#endif /* COAP_Q_BLOCK_SUPPORT */
4209
4210 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4211 /* See if need to send next block to server */
4212 if (coap_handle_response_send_block(session, sent, rcvd)) {
4213 /* Next block transmitted, no need to inform app */
4214 coap_send_ack_lkd(session, rcvd);
4215 return;
4216 }
4217
4218 /* Need to see if needing to request next block */
4219 if (coap_handle_response_get_block(context, session, sent, rcvd,
4220 COAP_RECURSE_OK)) {
4221 /* Next block transmitted, ack sent no need to inform app */
4222 return;
4223 }
4224 }
4225 if (session->doing_first)
4226 session->doing_first = 0;
4227
4228 /* Call application-specific response handler when available. */
4229 coap_call_response_handler(session, sent, rcvd, NULL);
4230}
4231#endif /* COAP_CLIENT_SUPPORT */
4232
4233#if !COAP_DISABLE_TCP
4234static void
4236 coap_pdu_t *pdu) {
4237 coap_opt_iterator_t opt_iter;
4238 coap_opt_t *option;
4239 int set_mtu = 0;
4240
4241 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4242
4243 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4244 if (session->csm_not_seen) {
4245 coap_tick_t now;
4246
4247 coap_ticks(&now);
4248 /* CSM timeout before CSM seen */
4249 coap_log_warn("***%s: CSM received after CSM timeout\n",
4250 coap_session_str(session));
4251 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4252 coap_session_str(session),
4253 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4254 }
4255 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4257 }
4258 while ((option = coap_option_next(&opt_iter))) {
4261 coap_opt_length(option)));
4262 set_mtu = 1;
4263 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4264 session->csm_block_supported = 1;
4265 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4266 session->max_token_size =
4268 coap_opt_length(option));
4271 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4274 }
4275 }
4276 if (set_mtu) {
4277 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4278 session->csm_bert_rem_support = 1;
4279 else
4280 session->csm_bert_rem_support = 0;
4281 }
4282 if (session->state == COAP_SESSION_STATE_CSM)
4283 coap_session_connected(session);
4284 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4286 if (context->ping_handler) {
4287 coap_lock_callback(context->ping_handler(session, pdu, pdu->mid));
4288 }
4289 if (pong) {
4291 coap_send_internal(session, pong, NULL);
4292 }
4293 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4294 session->last_pong = session->last_rx_tx;
4295 if (context->pong_handler) {
4296 coap_lock_callback(context->pong_handler(session, pdu, pdu->mid));
4297 }
4298 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4299 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4301 }
4302}
4303#endif /* !COAP_DISABLE_TCP */
4304
4305static int
4307 if (COAP_PDU_IS_REQUEST(pdu) &&
4308 pdu->actual_token.length >
4309 (session->type == COAP_SESSION_TYPE_CLIENT ?
4310 session->max_token_size : session->context->max_token_size)) {
4311 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4312 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4313 coap_opt_filter_t opt_filter;
4314 coap_pdu_t *response;
4315
4316 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4317 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4318 &opt_filter);
4319 if (!response) {
4320 coap_log_warn("coap_dispatch: cannot create error response\n");
4321 } else {
4322 /*
4323 * Note - have to leave in oversize token as per
4324 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4325 */
4326 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4327 coap_log_warn("coap_dispatch: error sending response\n");
4328 }
4329 } else {
4330 /* Indicate no extended token support */
4331 coap_send_rst_lkd(session, pdu);
4332 }
4333 return 0;
4334 }
4335 return 1;
4336}
4337
4338void
4340 coap_pdu_t *pdu) {
4341 coap_queue_t *sent = NULL;
4342 coap_pdu_t *response;
4343 coap_pdu_t *orig_pdu = NULL;
4344 coap_opt_filter_t opt_filter;
4345 int is_ping_rst;
4346 int packet_is_bad = 0;
4347#if COAP_OSCORE_SUPPORT
4348 coap_opt_iterator_t opt_iter;
4349 coap_pdu_t *dec_pdu = NULL;
4350#endif /* COAP_OSCORE_SUPPORT */
4351 int is_ext_token_rst;
4352 int oscore_invalid = 0;
4353
4354 pdu->session = session;
4356
4357 /* Check validity of received code */
4358 if (!coap_check_code_class(session, pdu)) {
4359 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4361 pdu->code & 0x1f);
4362 packet_is_bad = 1;
4363 if (pdu->type == COAP_MESSAGE_CON) {
4365 }
4366 /* find message id in sendqueue to stop retransmission */
4367 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4368 goto cleanup;
4369 }
4370
4371 coap_option_filter_clear(&opt_filter);
4372
4373#if COAP_SERVER_SUPPORT
4374 /* See if this a repeat request */
4375 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4377 coap_digest_t digest;
4378
4379 coap_pdu_cksum(pdu, &digest);
4380 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4381#if COAP_OSCORE_SUPPORT
4382 uint8_t oscore_encryption = session->oscore_encryption;
4383
4384 session->oscore_encryption = 0;
4385#endif /* COAP_OSCORE_SUPPORT */
4386 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4387 cached_pdu must not be removed */
4389 coap_log_debug("Retransmit response to duplicate request\n");
4390 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4391#if COAP_OSCORE_SUPPORT
4392 session->oscore_encryption = oscore_encryption;
4393#endif /* COAP_OSCORE_SUPPORT */
4394 return;
4395 }
4396#if COAP_OSCORE_SUPPORT
4397 session->oscore_encryption = oscore_encryption;
4398#endif /* COAP_OSCORE_SUPPORT */
4399 }
4400 }
4401#endif /* COAP_SERVER_SUPPORT */
4402 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4403 if (!check_token_size(session, pdu)) {
4404 goto cleanup;
4405 }
4406 }
4407#if COAP_OSCORE_SUPPORT
4408 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4409 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4410 if (pdu->type == COAP_MESSAGE_NON) {
4411 coap_send_rst_lkd(session, pdu);
4412 goto cleanup;
4413 } else if (pdu->type == COAP_MESSAGE_CON) {
4414 if (COAP_PDU_IS_REQUEST(pdu)) {
4415 response =
4416 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4417
4418 if (!response) {
4419 coap_log_warn("coap_dispatch: cannot create error response\n");
4420 } else {
4421 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4422 coap_log_warn("coap_dispatch: error sending response\n");
4423 }
4424 } else {
4425 coap_send_rst_lkd(session, pdu);
4426 }
4427 }
4428 goto cleanup;
4429 }
4430
4431 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4432 int decrypt = 1;
4433#if COAP_SERVER_SUPPORT
4434 coap_opt_t *opt;
4435 coap_resource_t *resource;
4436 coap_uri_t uri;
4437#endif /* COAP_SERVER_SUPPORT */
4438
4439 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4440 decrypt = 0;
4441
4442#if COAP_SERVER_SUPPORT
4443 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4444 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4445 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4446 != NULL) {
4447 /* Need to check whether this is a direct or proxy session */
4448 memset(&uri, 0, sizeof(uri));
4449 uri.host.length = coap_opt_length(opt);
4450 uri.host.s = coap_opt_value(opt);
4451 resource = context->proxy_uri_resource;
4452 if (uri.host.length && resource && resource->proxy_name_count &&
4453 resource->proxy_name_list) {
4454 size_t i;
4455 for (i = 0; i < resource->proxy_name_count; i++) {
4456 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4457 break;
4458 }
4459 }
4460 if (i == resource->proxy_name_count) {
4461 /* This server is not hosting the proxy connection endpoint */
4462 decrypt = 0;
4463 }
4464 }
4465 }
4466#endif /* COAP_SERVER_SUPPORT */
4467 if (decrypt) {
4468 /* find message id in sendqueue to stop retransmission and get sent */
4469 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4470 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4471 orig_pdu = pdu;
4472 coap_pdu_reference_lkd(orig_pdu);
4473 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4474 if (session->recipient_ctx == NULL ||
4475 session->recipient_ctx->initial_state == 0) {
4476 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4477 }
4479 coap_delete_pdu_lkd(orig_pdu);
4480 return;
4481 } else {
4482 session->oscore_encryption = 1;
4483 pdu = dec_pdu;
4484 }
4485 coap_log_debug("Decrypted PDU\n");
4487 }
4488 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4489 session->oscore_encryption &&
4490 pdu->type != COAP_MESSAGE_RST) {
4491 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4492 /* Violates RFC 8613 2 */
4493 coap_log_err("received an invalid response to the OSCORE request\n");
4494 oscore_invalid = 1;
4495 }
4496 }
4497#endif /* COAP_OSCORE_SUPPORT */
4498
4499 switch (pdu->type) {
4500 case COAP_MESSAGE_ACK:
4501 /* find message id in sendqueue to stop retransmission */
4502 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4503
4504 if (sent && session->con_active) {
4505 session->con_active--;
4506 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4507 /* Flush out any entries on session->delayqueue */
4508 coap_session_connected(session);
4509 }
4510 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4511 packet_is_bad = 1;
4512 goto cleanup;
4513 }
4514
4515#if COAP_SERVER_SUPPORT
4516 /* if sent code was >= 64 the message might have been a
4517 * notification. Then, we must flag the observer to be alive
4518 * by setting obs->fail_cnt = 0. */
4519 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4520 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4521 }
4522#endif /* COAP_SERVER_SUPPORT */
4523
4524 if (pdu->code == 0) {
4525#if COAP_Q_BLOCK_SUPPORT
4526 if (sent) {
4527 coap_block_b_t block;
4528
4529 if (sent->pdu->type == COAP_MESSAGE_CON &&
4530 COAP_PROTO_NOT_RELIABLE(session->proto) &&
4531 coap_get_block_b(session, sent->pdu,
4532 COAP_PDU_IS_REQUEST(sent->pdu) ?
4534 &block)) {
4535 if (block.m) {
4536#if COAP_CLIENT_SUPPORT
4537 if (COAP_PDU_IS_REQUEST(sent->pdu))
4538 coap_send_q_block1(session, block, sent->pdu,
4539 COAP_SEND_SKIP_PDU);
4540#endif /* COAP_CLIENT_SUPPORT */
4541 if (COAP_PDU_IS_RESPONSE(sent->pdu))
4542 coap_send_q_blocks(session, sent->pdu->lg_xmit, block,
4543 sent->pdu, COAP_SEND_SKIP_PDU);
4544 }
4545 }
4546 }
4547#endif /* COAP_Q_BLOCK_SUPPORT */
4548#if COAP_CLIENT_SUPPORT
4549 /*
4550 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4551 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4552 * response if the response was piggy-backed. Here, a separate response
4553 * detected and so the lg_crcv needs to be set up before the sent PDU
4554 * information is lost.
4555 *
4556 * lg_crcv was not set up if not a CoAP request.
4557 *
4558 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4559 * options.
4560 */
4561 if (sent &&
4562 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4563 COAP_PDU_IS_REQUEST(sent->pdu)) {
4564 /*
4565 * lg_crcv was not set up in coap_send(). It could have been set up
4566 * the first separate response.
4567 * See if there already is a lg_crcv set up.
4568 */
4569 coap_lg_crcv_t *lg_crcv;
4570 uint64_t token_match =
4572 sent->pdu->actual_token.length));
4573
4574 LL_FOREACH(session->lg_crcv, lg_crcv) {
4575 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4576 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4577 break;
4578 }
4579 }
4580 if (!lg_crcv) {
4581 /*
4582 * Need to set up a lg_crcv as it was not set up in coap_send()
4583 * to save time, but server has not sent back a piggy-back response.
4584 */
4585 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4586 if (lg_crcv) {
4587 LL_PREPEND(session->lg_crcv, lg_crcv);
4588 }
4589 }
4590 }
4591#endif /* COAP_CLIENT_SUPPORT */
4592 /* an empty ACK needs no further handling */
4593 goto cleanup;
4594 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4595 /* This is not legitimate - Request using ACK - ignore */
4596 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4598 pdu->code & 0x1f);
4599 packet_is_bad = 1;
4600 goto cleanup;
4601 }
4602
4603 break;
4604
4605 case COAP_MESSAGE_RST:
4606 /* We have sent something the receiver disliked, so we remove
4607 * not only the message id but also the subscriptions we might
4608 * have. */
4609 is_ping_rst = 0;
4610 if (pdu->mid == session->last_ping_mid &&
4611 context->ping_timeout && session->last_ping > 0)
4612 is_ping_rst = 1;
4613
4614#if COAP_Q_BLOCK_SUPPORT
4615 /* Check to see if checking out Q-Block support */
4616 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4617 session->remote_test_mid == pdu->mid) {
4618 coap_log_debug("Q-Block support not available\n");
4619 set_block_mode_drop_q(session->block_mode);
4620 }
4621#endif /* COAP_Q_BLOCK_SUPPORT */
4622
4623 /* Check to see if checking out extended token support */
4624 is_ext_token_rst = 0;
4625 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4626 session->remote_test_mid == pdu->mid) {
4627 coap_log_debug("Extended Token support not available\n");
4630 session->doing_first = 0;
4631 is_ext_token_rst = 1;
4632 }
4633
4634 if (!is_ping_rst && !is_ext_token_rst)
4635 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4636
4637 if (session->con_active) {
4638 session->con_active--;
4639 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4640 /* Flush out any entries on session->delayqueue */
4641 coap_session_connected(session);
4642 }
4643
4644 /* find message id in sendqueue to stop retransmission */
4645 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4646
4647 if (sent) {
4648 if (!is_ping_rst)
4649 coap_cancel(context, sent);
4650
4651 if (!is_ping_rst && !is_ext_token_rst) {
4652 if (sent->pdu->type==COAP_MESSAGE_CON) {
4653 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4654 }
4655 } else if (is_ping_rst) {
4656 if (context->pong_handler) {
4657 coap_lock_callback(context->pong_handler(session, pdu, pdu->mid));
4658 }
4659 session->last_pong = session->last_rx_tx;
4661 }
4662 } else {
4663#if COAP_SERVER_SUPPORT
4664 /* Need to check is there is a subscription active and delete it */
4665 RESOURCES_ITER(context->resources, r) {
4666 coap_subscription_t *obs, *tmp;
4667 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4668 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4669 /* Need to do this now as session may get de-referenced */
4671 coap_delete_observer(r, session, &obs->pdu->actual_token);
4672 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4673 coap_session_release_lkd(session);
4674 goto cleanup;
4675 }
4676 }
4677 }
4678#endif /* COAP_SERVER_SUPPORT */
4679 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4680 }
4681#if COAP_PROXY_SUPPORT
4682 if (!is_ping_rst) {
4683 /* Need to check is there is a proxy subscription active and delete it */
4684 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
4685 }
4686#endif /* COAP_PROXY_SUPPORT */
4687 goto cleanup;
4688
4689 case COAP_MESSAGE_NON:
4690 /* check for oscore issue or unknown critical options */
4691 if (oscore_invalid || coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4692 packet_is_bad = 1;
4693 coap_send_rst_lkd(session, pdu);
4694 goto cleanup;
4695 }
4696 break;
4697
4698 case COAP_MESSAGE_CON:
4699 /* In a lossy context, the ACK of a separate response may have
4700 * been lost, so we need to stop retransmitting requests with the
4701 * same token. Matching on token potentially containing ext length bytes.
4702 */
4703 /* find message token in sendqueue to stop retransmission */
4704 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4705
4706 /* check for oscore issue or unknown critical options in non-signaling messages */
4707 if (oscore_invalid ||
4708 (!COAP_PDU_IS_SIGNALING(pdu) && coap_option_check_critical(session, pdu, &opt_filter) == 0)) {
4709 packet_is_bad = 1;
4710 if (COAP_PDU_IS_REQUEST(pdu)) {
4711 response =
4712 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4713
4714 if (!response) {
4715 coap_log_warn("coap_dispatch: cannot create error response\n");
4716 } else {
4717 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4718 coap_log_warn("coap_dispatch: error sending response\n");
4719 }
4720 } else {
4721 coap_send_rst_lkd(session, pdu);
4722 }
4723 goto cleanup;
4724 }
4725 break;
4726 default:
4727 break;
4728 }
4729
4730 /* Pass message to upper layer if a specific handler was
4731 * registered for a request that should be handled locally. */
4732#if !COAP_DISABLE_TCP
4733 if (COAP_PDU_IS_SIGNALING(pdu))
4734 handle_signaling(context, session, pdu);
4735 else
4736#endif /* !COAP_DISABLE_TCP */
4737#if COAP_SERVER_SUPPORT
4738 if (COAP_PDU_IS_REQUEST(pdu))
4739 handle_request(context, session, pdu, orig_pdu);
4740 else
4741#endif /* COAP_SERVER_SUPPORT */
4742#if COAP_CLIENT_SUPPORT
4743 if (COAP_PDU_IS_RESPONSE(pdu))
4744 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4745 else
4746#endif /* COAP_CLIENT_SUPPORT */
4747 {
4748 if (COAP_PDU_IS_EMPTY(pdu)) {
4749 if (context->ping_handler) {
4750 coap_lock_callback(context->ping_handler(session, pdu, pdu->mid));
4751 }
4752 } else {
4753 packet_is_bad = 1;
4754 }
4755 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4757 pdu->code & 0x1f);
4758
4759 if (!coap_is_mcast(&session->addr_info.local)) {
4760 if (COAP_PDU_IS_EMPTY(pdu)) {
4761 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4762 coap_tick_t now;
4763 coap_ticks(&now);
4764 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4766 session->last_tx_rst = now;
4767 }
4768 }
4769 } else {
4770 if (pdu->type == COAP_MESSAGE_CON)
4772 }
4773 }
4774 }
4775
4776cleanup:
4777 if (packet_is_bad) {
4778 if (sent) {
4779 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
4780 } else {
4782 }
4783 }
4784 coap_delete_pdu_lkd(orig_pdu);
4786#if COAP_OSCORE_SUPPORT
4787 coap_delete_pdu_lkd(dec_pdu);
4788#endif /* COAP_OSCORE_SUPPORT */
4789}
4790
4791#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4792static const char *
4794 switch (event) {
4796 return "COAP_EVENT_DTLS_CLOSED";
4798 return "COAP_EVENT_DTLS_CONNECTED";
4800 return "COAP_EVENT_DTLS_RENEGOTIATE";
4802 return "COAP_EVENT_DTLS_ERROR";
4804 return "COAP_EVENT_TCP_CONNECTED";
4806 return "COAP_EVENT_TCP_CLOSED";
4808 return "COAP_EVENT_TCP_FAILED";
4810 return "COAP_EVENT_SESSION_CONNECTED";
4812 return "COAP_EVENT_SESSION_CLOSED";
4814 return "COAP_EVENT_SESSION_FAILED";
4816 return "COAP_EVENT_PARTIAL_BLOCK";
4818 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4820 return "COAP_EVENT_SERVER_SESSION_NEW";
4822 return "COAP_EVENT_SERVER_SESSION_DEL";
4824 return "COAP_EVENT_BAD_PACKET";
4826 return "COAP_EVENT_MSG_RETRANSMITTED";
4828 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4830 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4832 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4834 return "COAP_EVENT_OSCORE_NO_SECURITY";
4836 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4838 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4840 return "COAP_EVENT_WS_PACKET_SIZE";
4842 return "COAP_EVENT_WS_CONNECTED";
4844 return "COAP_EVENT_WS_CLOSED";
4846 return "COAP_EVENT_KEEPALIVE_FAILURE";
4847 default:
4848 return "???";
4849 }
4850}
4851#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4852
4853COAP_API int
4855 coap_session_t *session) {
4856 int ret;
4857
4858 coap_lock_lock(return 0);
4859 ret = coap_handle_event_lkd(context, event, session);
4861 return ret;
4862}
4863
4864int
4866 coap_session_t *session) {
4867 int ret = 0;
4868
4869 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
4870
4871 if (context->handle_event) {
4872 coap_lock_callback_ret(ret, context->handle_event(session, event));
4873#if COAP_PROXY_SUPPORT
4874 if (event == COAP_EVENT_SERVER_SESSION_DEL)
4875 coap_proxy_remove_association(session, 0);
4876#endif /* COAP_PROXY_SUPPORT */
4877#if COAP_CLIENT_SUPPORT
4878 switch (event) {
4891 /* Those that are deemed fatal to end sending a request */
4892 session->doing_send_recv = 0;
4893 break;
4908 default:
4909 break;
4910 }
4911#endif /* COAP_CLIENT_SUPPORT */
4912 }
4913 return ret;
4914}
4915
4916COAP_API int
4918 int ret;
4919
4920 coap_lock_lock(return 0);
4921 ret = coap_can_exit_lkd(context);
4923 return ret;
4924}
4925
4926int
4928 coap_session_t *s, *rtmp;
4929 if (!context)
4930 return 1;
4932 if (context->sendqueue)
4933 return 0;
4934#if COAP_SERVER_SUPPORT
4935 coap_endpoint_t *ep;
4936
4937 LL_FOREACH(context->endpoint, ep) {
4938 SESSIONS_ITER(ep->sessions, s, rtmp) {
4939 if (s->delayqueue)
4940 return 0;
4941 if (s->lg_xmit)
4942 return 0;
4943 }
4944 }
4945#endif /* COAP_SERVER_SUPPORT */
4946#if COAP_CLIENT_SUPPORT
4947 SESSIONS_ITER(context->sessions, s, rtmp) {
4948 if (s->delayqueue)
4949 return 0;
4950 if (s->lg_xmit)
4951 return 0;
4952 }
4953#endif /* COAP_CLIENT_SUPPORT */
4954 return 1;
4955}
4956#if COAP_SERVER_SUPPORT
4957#if COAP_ASYNC_SUPPORT
4958/*
4959 * Return 1 if there is a future expire time, else 0.
4960 * Update tim_rem with remaining value if return is 1.
4961 */
4962int
4963coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
4965 coap_async_t *async, *tmp;
4966 int ret = 0;
4967
4968 LL_FOREACH_SAFE(context->async_state, async, tmp) {
4969 if (async->delay != 0) {
4970 if (async->delay <= now) {
4971 /* Send off the request to the application */
4972 coap_log_debug("Async PDU presented to app.\n");
4973 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
4974 handle_request(context, async->session, async->pdu, NULL);
4975
4976 /* Remove this async entry as it has now fired */
4977 coap_free_async_lkd(async->session, async);
4978 } else {
4979 next_due = async->delay - now;
4980 ret = 1;
4981 }
4982 }
4983 }
4984 if (tim_rem)
4985 *tim_rem = next_due;
4986 return ret;
4987}
4988#endif /* COAP_ASYNC_SUPPORT */
4989#endif /* COAP_SERVER_SUPPORT */
4990
4992
4993#if COAP_THREAD_SAFE
4994/*
4995 * Global lock for multi-thread support
4996 */
4997coap_lock_t global_lock;
4998/*
4999 * low level protection mutex
5000 */
5001coap_mutex_t m_show_pdu;
5002coap_mutex_t m_log_impl;
5003coap_mutex_t m_io_threads;
5004#endif /* COAP_THREAD_SAFE */
5005
5006void
5008 coap_tick_t now;
5009#ifndef WITH_CONTIKI
5010 uint64_t us;
5011#endif /* !WITH_CONTIKI */
5012
5013 if (coap_started)
5014 return;
5015 coap_started = 1;
5016
5017#if COAP_THREAD_SAFE
5019 coap_mutex_init(&m_show_pdu);
5020 coap_mutex_init(&m_log_impl);
5021 coap_mutex_init(&m_io_threads);
5022#endif /* COAP_THREAD_SAFE */
5023
5024#if defined(HAVE_WINSOCK2_H)
5025 WORD wVersionRequested = MAKEWORD(2, 2);
5026 WSADATA wsaData;
5027 WSAStartup(wVersionRequested, &wsaData);
5028#endif
5030 coap_ticks(&now);
5031#ifndef WITH_CONTIKI
5032 us = coap_ticks_to_rt_us(now);
5033 /* Be accurate to the nearest (approx) us */
5034 coap_prng_init_lkd((unsigned int)us);
5035#else /* WITH_CONTIKI */
5036 coap_start_io_process();
5037#endif /* WITH_CONTIKI */
5040#ifdef WITH_LWIP
5041 coap_io_lwip_init();
5042#endif /* WITH_LWIP */
5043#if COAP_SERVER_SUPPORT
5044 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5045 (const uint8_t *)".well-known/core"
5046 };
5047 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5048 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5049 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5050 resource_uri_wellknown.uri_path = &well_known;
5051#endif /* COAP_SERVER_SUPPORT */
5053}
5054
5055void
5057 if (!coap_started)
5058 return;
5059 coap_started = 0;
5060#if defined(HAVE_WINSOCK2_H)
5061 WSACleanup();
5062#elif defined(WITH_CONTIKI)
5063 coap_stop_io_process();
5064#endif
5065#ifdef WITH_LWIP
5066 coap_io_lwip_cleanup();
5067#endif /* WITH_LWIP */
5069
5070#if COAP_THREAD_SAFE
5071 coap_mutex_destroy(&m_show_pdu);
5072 coap_mutex_destroy(&m_log_impl);
5073 coap_mutex_destroy(&m_io_threads);
5074#endif /* COAP_THREAD_SAFE */
5075
5077}
5078
5079void
5081 coap_response_handler_t handler) {
5082#if COAP_CLIENT_SUPPORT
5083 context->response_handler = handler;
5084#else /* ! COAP_CLIENT_SUPPORT */
5085 (void)context;
5086 (void)handler;
5087#endif /* ! COAP_CLIENT_SUPPORT */
5088}
5089
5090void
5093#if COAP_PROXY_SUPPORT
5094 context->proxy_response_handler = handler;
5095#else /* ! COAP_PROXY_SUPPORT */
5096 (void)context;
5097 (void)handler;
5098#endif /* ! COAP_PROXY_SUPPORT */
5099}
5100
5101void
5103 coap_nack_handler_t handler) {
5104 context->nack_handler = handler;
5105}
5106
5107void
5109 coap_ping_handler_t handler) {
5110 context->ping_handler = handler;
5111}
5112
5113void
5115 coap_pong_handler_t handler) {
5116 context->pong_handler = handler;
5117}
5118
5119COAP_API void
5121 coap_lock_lock(return);
5122 coap_register_option_lkd(ctx, type);
5124}
5125
5126void
5129}
5130
5131#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
5132#if COAP_SERVER_SUPPORT
5133COAP_API int
5134coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5135 const char *ifname) {
5136 int ret;
5137
5138 coap_lock_lock(return -1);
5139 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
5141 return ret;
5142}
5143
5144int
5145coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
5146 const char *ifname) {
5147#if COAP_IPV4_SUPPORT
5148 struct ip_mreq mreq4;
5149#endif /* COAP_IPV4_SUPPORT */
5150#if COAP_IPV6_SUPPORT
5151 struct ipv6_mreq mreq6;
5152#endif /* COAP_IPV6_SUPPORT */
5153 struct addrinfo *resmulti = NULL, hints, *ainfo;
5154 int result = -1;
5155 coap_endpoint_t *endpoint;
5156 int mgroup_setup = 0;
5157
5158 /* Need to have at least one endpoint! */
5159 assert(ctx->endpoint);
5160 if (!ctx->endpoint)
5161 return -1;
5162
5163 /* Default is let the kernel choose */
5164#if COAP_IPV6_SUPPORT
5165 mreq6.ipv6mr_interface = 0;
5166#endif /* COAP_IPV6_SUPPORT */
5167#if COAP_IPV4_SUPPORT
5168 mreq4.imr_interface.s_addr = INADDR_ANY;
5169#endif /* COAP_IPV4_SUPPORT */
5170
5171 memset(&hints, 0, sizeof(hints));
5172 hints.ai_socktype = SOCK_DGRAM;
5173
5174 /* resolve the multicast group address */
5175 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5176
5177 if (result != 0) {
5178 coap_log_err("coap_join_mcast_group_intf: %s: "
5179 "Cannot resolve multicast address: %s\n",
5180 group_name, gai_strerror(result));
5181 goto finish;
5182 }
5183
5184 /* Need to do a windows equivalent at some point */
5185#ifndef _WIN32
5186 if (ifname) {
5187 /* interface specified - check if we have correct IPv4/IPv6 information */
5188 int done_ip4 = 0;
5189 int done_ip6 = 0;
5190#if defined(ESPIDF_VERSION)
5191 struct netif *netif;
5192#else /* !ESPIDF_VERSION */
5193#if COAP_IPV4_SUPPORT
5194 int ip4fd;
5195#endif /* COAP_IPV4_SUPPORT */
5196 struct ifreq ifr;
5197#endif /* !ESPIDF_VERSION */
5198
5199 /* See which mcast address family types are being asked for */
5200 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5201 ainfo = ainfo->ai_next) {
5202 switch (ainfo->ai_family) {
5203#if COAP_IPV6_SUPPORT
5204 case AF_INET6:
5205 if (done_ip6)
5206 break;
5207 done_ip6 = 1;
5208#if defined(ESPIDF_VERSION)
5209 netif = netif_find(ifname);
5210 if (netif)
5211 mreq6.ipv6mr_interface = netif_get_index(netif);
5212 else
5213 coap_log_err("coap_join_mcast_group_intf: %s: "
5214 "Cannot get IPv4 address: %s\n",
5215 ifname, coap_socket_strerror());
5216#else /* !ESPIDF_VERSION */
5217 memset(&ifr, 0, sizeof(ifr));
5218 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5219 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5220
5221#ifdef HAVE_IF_NAMETOINDEX
5222 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5223 if (mreq6.ipv6mr_interface == 0) {
5224 coap_log_warn("coap_join_mcast_group_intf: "
5225 "cannot get interface index for '%s'\n",
5226 ifname);
5227 }
5228#elif defined(__QNXNTO__)
5229#else /* !HAVE_IF_NAMETOINDEX */
5230 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5231 if (result != 0) {
5232 coap_log_warn("coap_join_mcast_group_intf: "
5233 "cannot get interface index for '%s': %s\n",
5234 ifname, coap_socket_strerror());
5235 } else {
5236 /* Capture the IPv6 if_index for later */
5237 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5238 }
5239#endif /* !HAVE_IF_NAMETOINDEX */
5240#endif /* !ESPIDF_VERSION */
5241#endif /* COAP_IPV6_SUPPORT */
5242 break;
5243#if COAP_IPV4_SUPPORT
5244 case AF_INET:
5245 if (done_ip4)
5246 break;
5247 done_ip4 = 1;
5248#if defined(ESPIDF_VERSION)
5249 netif = netif_find(ifname);
5250 if (netif)
5251 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5252 else
5253 coap_log_err("coap_join_mcast_group_intf: %s: "
5254 "Cannot get IPv4 address: %s\n",
5255 ifname, coap_socket_strerror());
5256#else /* !ESPIDF_VERSION */
5257 /*
5258 * Need an AF_INET socket to do this unfortunately to stop
5259 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5260 */
5261 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5262 if (ip4fd == -1) {
5263 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5264 ifname, coap_socket_strerror());
5265 continue;
5266 }
5267 memset(&ifr, 0, sizeof(ifr));
5268 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5269 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5270 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5271 if (result != 0) {
5272 coap_log_err("coap_join_mcast_group_intf: %s: "
5273 "Cannot get IPv4 address: %s\n",
5274 ifname, coap_socket_strerror());
5275 } else {
5276 /* Capture the IPv4 address for later */
5277 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5278 }
5279 close(ip4fd);
5280#endif /* !ESPIDF_VERSION */
5281 break;
5282#endif /* COAP_IPV4_SUPPORT */
5283 default:
5284 break;
5285 }
5286 }
5287 }
5288#else /* _WIN32 */
5289 /*
5290 * On Windows this function ignores the ifname variable so we unset this
5291 * variable on this platform in any case in order to enable the interface
5292 * selection from the bind address below.
5293 */
5294 ifname = 0;
5295#endif /* _WIN32 */
5296
5297 /* Add in mcast address(es) to appropriate interface */
5298 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5299 LL_FOREACH(ctx->endpoint, endpoint) {
5300 /* Only UDP currently supported */
5301 if (endpoint->proto == COAP_PROTO_UDP) {
5302 coap_address_t gaddr;
5303
5304 coap_address_init(&gaddr);
5305#if COAP_IPV6_SUPPORT
5306 if (ainfo->ai_family == AF_INET6) {
5307 if (!ifname) {
5308 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5309 /*
5310 * Do it on the ifindex that the server is listening on
5311 * (sin6_scope_id could still be 0)
5312 */
5313 mreq6.ipv6mr_interface =
5314 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5315 } else {
5316 mreq6.ipv6mr_interface = 0;
5317 }
5318 }
5319 gaddr.addr.sin6.sin6_family = AF_INET6;
5320 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5321 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5322 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5323 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5324 (char *)&mreq6, sizeof(mreq6));
5325 }
5326#endif /* COAP_IPV6_SUPPORT */
5327#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5328 else
5329#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5330#if COAP_IPV4_SUPPORT
5331 if (ainfo->ai_family == AF_INET) {
5332 if (!ifname) {
5333 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5334 /*
5335 * Do it on the interface that the server is listening on
5336 * (sin_addr could still be INADDR_ANY)
5337 */
5338 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5339 } else {
5340 mreq4.imr_interface.s_addr = INADDR_ANY;
5341 }
5342 }
5343 gaddr.addr.sin.sin_family = AF_INET;
5344 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5345 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5346 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5347 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5348 (char *)&mreq4, sizeof(mreq4));
5349 }
5350#endif /* COAP_IPV4_SUPPORT */
5351 else {
5352 continue;
5353 }
5354
5355 if (result == COAP_SOCKET_ERROR) {
5356 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5357 group_name, coap_socket_strerror());
5358 } else {
5359 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5360
5361 addr_str[sizeof(addr_str)-1] = '\000';
5362 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5363 sizeof(addr_str) - 1)) {
5364 if (ifname)
5365 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5366 ifname);
5367 else
5368 coap_log_debug("added mcast group %s\n", addr_str);
5369 }
5370 mgroup_setup = 1;
5371 }
5372 }
5373 }
5374 }
5375 if (!mgroup_setup) {
5376 result = -1;
5377 }
5378
5379finish:
5380 freeaddrinfo(resmulti);
5381
5382 return result;
5383}
5384
5385void
5387 context->mcast_per_resource = 1;
5388}
5389
5390#endif /* ! COAP_SERVER_SUPPORT */
5391
5392#if COAP_CLIENT_SUPPORT
5393int
5394coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5395 if (session && coap_is_mcast(&session->addr_info.remote)) {
5396 switch (session->addr_info.remote.addr.sa.sa_family) {
5397#if COAP_IPV4_SUPPORT
5398 case AF_INET:
5399 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5400 (const char *)&hops, sizeof(hops)) < 0) {
5401 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5402 hops, coap_socket_strerror());
5403 return 0;
5404 }
5405 return 1;
5406#endif /* COAP_IPV4_SUPPORT */
5407#if COAP_IPV6_SUPPORT
5408 case AF_INET6:
5409 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5410 (const char *)&hops, sizeof(hops)) < 0) {
5411 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5412 hops, coap_socket_strerror());
5413 return 0;
5414 }
5415 return 1;
5416#endif /* COAP_IPV6_SUPPORT */
5417 default:
5418 break;
5419 }
5420 }
5421 return 0;
5422}
5423#endif /* COAP_CLIENT_SUPPORT */
5424
5425#else /* defined WITH_CONTIKI || defined WITH_LWIP */
5426COAP_API int
5428 const char *group_name COAP_UNUSED,
5429 const char *ifname COAP_UNUSED) {
5430 return -1;
5431}
5432
5433int
5435 size_t hops COAP_UNUSED) {
5436 return 0;
5437}
5438
5439void
5441}
5442#endif /* defined WITH_CONTIKI || defined WITH_LWIP */
void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
int coap_is_mcast(const coap_address_t *a)
Checks if given address a denotes a multicast address.
void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
void coap_debug_reset(void)
Reset all the defined logging parameters.
struct coap_proxy_list_t coap_proxy_list_t
Proxy information.
struct coap_async_t coap_async_t
Async Entry information.
#define PRIu32
const char * coap_socket_strerror(void)
Definition coap_io.c:2338
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:1031
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:519
#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:670
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 coap_mutex_init(a)
int coap_mutex_t
#define coap_mutex_destroy(a)
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition coap_net.c:80
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition coap_net.c:1113
static int send_recv_terminate
Definition coap_net.c:2097
static int coap_remove_from_queue_token(coap_queue_t **queue, coap_session_t *session, coap_bin_const_t *token, coap_queue_t **node)
Definition coap_net.c:2979
#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:5056
#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:4793
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:3294
int coap_started
Definition coap_net.c:4991
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2366
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2407
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:4235
#define min(a, b)
Definition coap_net.c:73
void coap_startup(void)
Definition coap_net.c:5007
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4306
static unsigned int s_csm_timeout
Definition coap_net.c:522
COAP_STATIC_INLINE coap_queue_t * coap_malloc_node(void)
Definition coap_net.c:106
#define FP1
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition coap_net.c:97
#define INET6_ADDRSTRLEN
Definition coap_net.c:69
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c: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:243
int coap_dtls_context_load_pki_trust_store(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:124
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:186
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:181
uint16_t coap_option_num_t
Definition coap_option.h:20
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
Definition coap_option.h:26
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define SESSIONS_ITER(e, el, rtmp)
void coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition coap_net.c:2768
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:1070
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:1194
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:1165
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:2703
int coap_send_recv_lkd(coap_session_t *session, coap_pdu_t *request_pdu, coap_pdu_t **response_pdu, uint32_t timeout_ms)
Definition coap_net.c:2126
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1816
void coap_call_response_handler(coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd, void *body_free)
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:1275
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:1470
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:1085
#define COAP_IO_NO_WAIT
Definition coap_net.h:728
#define COAP_IO_WAIT
Definition coap_net.h:727
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:2757
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:2696
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)
coap_lg_crcv_t * coap_find_lg_crcv(coap_session_t *session, coap_pdu_t *pdu)
Find the current lg_crcv for the session that matches the pdu.
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:90
#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:62
#define COAP_BLOCK_NO_PREEMPTIVE_RTAG
Definition coap_block.h:65
#define COAP_BLOCK_CACHE_RESPONSE
Definition coap_block.h:69
#define COAP_BLOCK_USE_LIBCOAP
Definition coap_block.h:61
void coap_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
int coap_digest_final(coap_digest_ctx_t *digest_ctx, coap_digest_t *digest_buffer)
Finalize the coap_digest information into the provided digest_buffer.
int coap_digest_update(coap_digest_ctx_t *digest_ctx, const uint8_t *data, size_t data_len)
Update the coap_digest information with the next chunk of data.
void coap_digest_ctx_t
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
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
#define COAP_MAX_DELAY_TICKS
Definition coap_time.h:221
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
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
coap_print_status_t coap_print_wellknown_lkd(coap_context_t *context, unsigned char *buf, size_t *buflen, size_t offset, const coap_string_t *query_filter)
Prints the names of all known resources for context to buf.
coap_resource_t * coap_get_resource_from_uri_path_lkd(coap_context_t *context, coap_str_const_t *uri_path)
Returns the resource identified by the unique string uri_path.
#define RESOURCES_ITER(r, tmp)
#define COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
Define this when invoking coap_resource_unknown_init2() if .well-known/core is to be passed to the un...
#define COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT
This resource has support for multicast requests.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_4_XX
Disable libcoap library suppressing 4.xx multicast responses (overridden by RFC7969 No-Response optio...
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS
Disable libcoap library from adding in delays to multicast requests before releasing the response bac...
void(* coap_method_handler_t)(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
Definition of message handler function.
#define COAP_RESOURCE_FLAGS_OSCORE_ONLY
Define this resource as an OSCORE enabled access only.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_5_XX
Disable libcoap library suppressing 5.xx multicast responses (overridden by RFC7969 No-Response optio...
uint32_t coap_print_status_t
Status word to encode the result of conditional print or copy operations such as coap_print_link().
#define COAP_PRINT_STATUS_ERROR
#define COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY
Force all large traffic to this resource to be presented as a single body to the request handler.
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_05
Enable libcoap library suppression of 205 multicast responses that are empty (overridden by RFC7969 N...
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_XX
Enable libcoap library suppressing 2.xx multicast responses (overridden by RFC7969 No-Response option...
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:4865
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.
void coap_register_option_lkd(coap_context_t *ctx, uint16_t type)
Registers the option number number with the given context object context.
Definition coap_net.c:5127
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:2934
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:1338
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:4339
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:1222
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:819
int coap_context_load_pki_trust_store_lkd(coap_context_t *ctx)
Load the context's default trusted CAs for a client or server.
Definition coap_net.c:468
coap_mid_t coap_send_internal(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *request_pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1836
void * coap_context_set_app_data2_lkd(coap_context_t *context, void *app_data, coap_app_data_free_callback_t callback)
Stores data with the given context, returning the previously stored value or NULL.
Definition coap_net.c:694
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:4927
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2244
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:1405
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, duplicate options or the options defined as R...
Definition coap_net.c:915
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1248
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:3038
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:2873
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:3077
void coap_context_set_session_timeout(coap_context_t *context, unsigned int session_timeout)
Set the session timeout value.
Definition coap_net.c:565
unsigned int coap_context_get_max_handshake_sessions(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:518
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:507
COAP_API int coap_send_recv(coap_session_t *session, coap_pdu_t *request_pdu, coap_pdu_t **response_pdu, uint32_t timeout_ms)
Definition coap_net.c:2105
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:704
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:1460
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:1152
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:553
void coap_context_set_csm_timeout(coap_context_t *context, unsigned int csm_timeout)
Set the CSM timeout value.
Definition coap_net.c:525
void coap_send_recv_terminate(void)
Terminate any active coap_send_recv() sessions.
Definition coap_net.c:2100
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:5080
COAP_API void * coap_context_set_app_data2(coap_context_t *context, void *app_data, coap_app_data_free_callback_t callback)
Stores data with the given context, returning the previously stored value or NULL.
Definition coap_net.c:683
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:3110
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:512
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:596
COAP_API void coap_set_app_data(coap_context_t *context, void *app_data)
Definition coap_net.c:796
int coap_mcast_set_hops(coap_session_t *session, size_t hops)
Function interface for defining the hop count (ttl) for sending multicast traffic.
coap_response_t
Definition coap_net.h:48
void(* coap_ping_handler_t)(coap_session_t *session, const coap_pdu_t *received, const coap_mid_t mid)
Received Ping handler that is used as callback in coap_context_t.
Definition coap_net.h:89
void coap_ticks(coap_tick_t *)
Returns the current value of an internal tick counter.
COAP_API void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition coap_net.c:810
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_set_shutdown_no_observe(coap_context_t *context)
Definition coap_net.c:587
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:677
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
COAP_API void coap_context_set_app_data(coap_context_t *context, void *app_data)
Stores data with the given context.
Definition coap_net.c:669
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:560
unsigned int coap_context_get_session_timeout(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:582
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 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:1075
unsigned int coap_context_get_csm_timeout_ms(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:548
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:5108
COAP_API int coap_context_set_psk2(coap_context_t *context, coap_dtls_spsk_t *setup_data)
Set the context's default PSK hint and/or key for a server.
void * coap_get_app_data(const coap_context_t *ctx)
Definition coap_net.c:804
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:482
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:501
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:1183
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:1060
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds)
Set the context keepalive timer for sessions.
Definition coap_net.c:477
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:4917
COAP_API void coap_register_option(coap_context_t *ctx, uint16_t type)
Registers the option number number with the given context object context.
Definition coap_net.c:5120
unsigned int coap_context_get_csm_timeout(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:532
COAP_API int coap_context_load_pki_trust_store(coap_context_t *ctx)
Load the hosts's default trusted CAs for a client or server.
Definition coap_net.c:458
void coap_context_set_session_reconnect_time(coap_context_t *context, unsigned int reconnect_time)
Set the session reconnect delay time after a working client session has failed.
Definition coap_net.c:571
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:5114
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:493
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:4854
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:5102
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:538
@ 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:154
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:166
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
coap_mutex_t coap_lock_t
#define coap_lock_callback(func)
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, func)
Dummy for no thread-safe code.
#define coap_lock_callback_ret_release(r, func, failed)
Dummy for no thread-safe code.
#define coap_lock_unlock()
Dummy for no thread-safe code.
#define coap_lock_check_locked()
Dummy for no thread-safe code.
#define coap_lock_callback_release(func, failed)
Dummy for no thread-safe code.
#define coap_lock_lock(failed)
Dummy for no thread-safe code.
#define coap_lock_init()
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:120
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition coap_debug.c:101
#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:784
#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:239
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
@ COAP_LOG_WARN
Definition coap_debug.h:55
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.
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:1651
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:190
#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:629
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
int coap_pdu_parse_opt(coap_pdu_t *pdu, coap_opt_filter_t *error_opts)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition coap_pdu.c:1348
#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:1074
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:990
#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
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:723
#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:1513
#define COAP_DEFAULT_VERSION
int coap_pdu_parse2(coap_proto_t proto, const uint8_t *data, size_t length, coap_pdu_t *pdu, coap_opt_filter_t *error_opts)
Parses data into the CoAP PDU structure given in result.
Definition coap_pdu.c:1489
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:1021
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:297
#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:779
#define COAP_OPTION_HOP_LIMIT
Definition coap_pdu.h:133
#define COAP_OPTION_NORESPONSE
Definition coap_pdu.h:146
#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:138
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition coap_pdu.c:950
#define COAP_OPTION_CONTENT_FORMAT
Definition coap_pdu.h:128
#define COAP_OPTION_BLOCK1
Definition coap_pdu.h:139
#define COAP_OPTION_Q_BLOCK1
Definition coap_pdu.h:135
#define COAP_OPTION_PROXY_SCHEME
Definition coap_pdu.h:143
#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:264
#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:200
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:161
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:164
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:199
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:141
#define COAP_SIGNALING_OPTION_CUSTODY
Definition coap_pdu.h:203
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:1479
#define COAP_OPTION_RTAG
Definition coap_pdu.h:147
#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:267
#define COAP_OPTION_PROXY_URI
Definition coap_pdu.h:142
#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:145
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition coap_pdu.h:215
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition coap_pdu.h:198
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:844
@ 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_register_proxy_response_handler(coap_context_t *context, coap_proxy_response_handler_t handler)
Registers a new message handler that is called whenever a response is received by the proxy logic.
Definition coap_net.c:5091
coap_pdu_t *(* coap_proxy_response_handler_t)(coap_session_t *session, const coap_pdu_t *sent, coap_pdu_t *received, coap_cache_key_t *cache_key)
Proxy response handler that is used as callback held in coap_context_t.
Definition coap_proxy.h:85
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).
void coap_handle_nack(coap_session_t *session, coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
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:2437
int coap_session_reconnect(coap_session_t *session)
Close the current session (if not already closed) and reconnect to server (client session only).
void coap_session_server_keepalive_failed(coap_session_t *session)
Clear down a session following a keepalive failure.
#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:1100
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)
void(* coap_app_data_free_callback_t)(void *data)
Callback to free off the app data when the entry is being deleted / freed off.
@ COAP_SESSION_TYPE_HELLO
server-side ephemeral session for responding to a client hello
@ COAP_SESSION_TYPE_CLIENT
client-side
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_ESTABLISHED
@ COAP_SESSION_STATE_NONE
void coap_delete_bin_const(coap_bin_const_t *s)
Deletes the given const binary data and releases any memory allocated.
Definition coap_str.c:120
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:77
coap_bin_const_t * coap_new_bin_const(const uint8_t *data, size_t size)
Take the specified byte array (text) and create a coap_bin_const_t * Returns a new const binary objec...
Definition coap_str.c:110
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:105
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:211
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:197
coap_string_t * coap_new_string(size_t size)
Returns a new string object with at least size+1 bytes storage allocated.
Definition coap_str.c:21
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition coap_str.c:46
int coap_delete_observer_request(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, coap_pdu_t *request)
Removes any subscription for session observer from resource and releases the allocated storage.
void coap_persist_cleanup(coap_context_t *context)
Close down persist tracking, releasing any memory used.
int coap_delete_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token)
Removes any subscription for session observer from resource and releases the allocated storage.
int coap_cancel_observe_lkd(coap_session_t *session, coap_binary_t *token, coap_pdu_type_t message_type)
Cancel an observe that is being tracked by the client large receive logic.
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Handles a failed observe notify.
coap_subscription_t * coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token, const coap_pdu_t *pdu)
Adds the specified peer as observer for resource.
void coap_touch_observer(coap_context_t *context, coap_session_t *session, const coap_bin_const_t *token)
Flags that data is ready to be sent to observers.
int coap_epoll_is_supported(void)
Determine whether epoll is supported or not.
Definition coap_net.c:606
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:660
int coap_ipv6_is_supported(void)
Check whether IPv6 is available.
Definition coap_net.c:633
int coap_threadsafe_is_supported(void)
Determine whether libcoap is threadsafe or not.
Definition coap_net.c:615
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:651
int coap_client_is_supported(void)
Check whether Client code is available.
Definition coap_net.c:642
int coap_ipv4_is_supported(void)
Check whether IPv4 is available.
Definition coap_net.c:624
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition coap_uri.c:990
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:281
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:939
#define COAP_UNUSED
Definition libcoap.h:70
#define COAP_STATIC_INLINE
Definition libcoap.h:53
coap_address_t remote
remote address and port
Definition coap_io.h:56
coap_address_t local
local address and port
Definition coap_io.h:57
Multi-purpose address abstraction.
struct sockaddr_in sin
struct sockaddr_in6 sin6
struct sockaddr sa
union coap_address_t::@0 addr
CoAP binary data definition with const data.
Definition coap_str.h:64
size_t length
length of binary data
Definition coap_str.h:65
const uint8_t * s
read-only binary data
Definition coap_str.h:66
CoAP binary data definition.
Definition coap_str.h:56
size_t length
length of binary data
Definition coap_str.h:57
uint8_t * s
binary data
Definition coap_str.h:58
Structure of Block options with BERT support.
Definition coap_block.h:51
unsigned int num
block number
Definition coap_block.h:52
unsigned int bert
Operating as BERT.
Definition coap_block.h:57
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:55
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:53
unsigned int szx
block size (0-6)
Definition coap_block.h:54
The CoAP stack's global state is stored in a coap_context_t object.
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
coap_pong_handler_t pong_handler
Called when a ping response is received.
coap_app_data_free_callback_t app_cb
call-back to release app_data
unsigned int reconnect_time
Time to wait before reconnecting a failed client session.
uint8_t shutdown_no_send_observe
Do not send out unsolicited observe when coap_free_context() is called.
coap_session_t * sessions
client sessions
coap_nack_handler_t nack_handler
Called when a response issue has occurred.
void * app_data
application-specific data
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.
uint8_t observe_no_clear
Observe 4.04 not to be sent on deleting resource.
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.
union coap_lg_xmit_t::@1 b
coap_pdu_t * sent_pdu
The sent pdu with all the data.
coap_l_block1_t b1
uint16_t option
large block transmisson CoAP option
Iterator to run through PDU options.
coap_option_num_t number
decoded option number
size_t length
length of payload
coap_addr_tuple_t addr_info
local and remote addresses
unsigned char * payload
payload
structure for CoAP PDUs
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
coap_lg_xmit_t * lg_xmit
Holds ptr to lg_xmit if sending a set of blocks.
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
coap_pdu_code_t code
request method (value 1–31) or response code (value 64-255)
uint8_t hdr_size
actual size used for protocol-specific header (0 until header is encoded)
coap_bin_const_t actual_token
Actual token in pdu.
uint8_t * data
first byte of payload, if any
coap_mid_t mid
message id, if any, in regular host byte order
uint32_t e_token_length
length of Token space (includes leading extended bytes
size_t used_size
used bytes of storage for token, options and payload
uint8_t crit_opt
Set if unknown critical option for proxy.
coap_binary_t * data_free
Data to be freed off by coap_delete_pdu()
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_address_t remote
For re-transmission - where the node is going.
coap_session_t * session
the CoAP session
coap_pdu_t * pdu
the CoAP PDU to send
unsigned int timeout
the randomized timeout value
uint8_t is_mcast
Set if this is a queued mcast response.
struct coap_queue_t * next
coap_mid_t id
CoAP message id.
coap_tick_t t
when to send PDU for the next time
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Abstraction of resource that can be attached to coap_context_t.
coap_str_const_t ** proxy_name_list
Array valid names this host is known by (proxy support)
coap_str_const_t * uri_path
Request URI Path for this resource.
unsigned int observe
The next value for the Observe option.
coap_method_handler_t handler[7]
Used to store handlers for the seven coap methods GET, POST, PUT, DELETE, FETCH, PATCH and IPATCH.
unsigned int is_proxy_uri
resource created for proxy URI handler
unsigned int is_unknown
resource created for unknown handler
unsigned int is_reverse_proxy
resource created for reverse proxy URI handler
unsigned int observable
can be observed
size_t proxy_name_count
Count of valid names this host is known by (proxy support)
int flags
zero or more COAP_RESOURCE_FLAGS_* or'd together
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
volatile uint8_t max_token_checked
Check for max token size coap_ext_token_check_t.
uint8_t csm_not_seen
Set if timeout waiting for CSM.
unsigned ref_subscriptions
reference count of current subscriptions
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_digest_t cached_pdu_cksum
Checksum of last CON request PDU.
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
unsigned ref_proxy_subs
reference count of current proxy subscriptions
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
uint8_t doing_send_recv
Set if coap_send_recv() active.
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_bin_const_t * req_token
Token in request pdu of coap_send_recv()
coap_pdu_t * resp_pdu
PDU returned in coap_send_recv() call.
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
uint8_t session_failed
Set if session failed and can try re-connect.
size_t partial_write
if > 0 indicates number of bytes already written from the pdu at the head of sendqueue
coap_pdu_t * cached_pdu
Cached copy of last ACK response PDU.
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:68
coap_str_const_t host
The host part of the URI.
Definition coap_uri.h:69