libcoap 4.3.5-develop-60e9f08
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(context, return 0);
221 ret = coap_delete_node_lkd(node);
222 coap_lock_unlock(context);
223 return ret;
224}
225
226int
228 if (!node)
229 return 0;
230
232 if (node->session) {
233 /*
234 * Need to remove out of context->sendqueue as added in by coap_wait_ack()
235 */
236 if (node->session->context->sendqueue) {
237 LL_DELETE(node->session->context->sendqueue, node);
238 }
240 }
241 coap_free_node(node);
242
243 return 1;
244}
245
246void
248 if (!queue)
249 return;
250
251 coap_delete_all(queue->next);
253}
254
257 coap_queue_t *node;
258 node = coap_malloc_node();
259
260 if (!node) {
261 coap_log_warn("coap_new_node: malloc failed\n");
262 return NULL;
263 }
264
265 memset(node, 0, sizeof(*node));
266 return node;
267}
268
271 if (!context || !context->sendqueue)
272 return NULL;
273
274 return context->sendqueue;
275}
276
279 coap_queue_t *next;
280
281 if (!context || !context->sendqueue)
282 return NULL;
283
284 next = context->sendqueue;
285 context->sendqueue = context->sendqueue->next;
286 if (context->sendqueue) {
287 context->sendqueue->t += next->t;
288 }
289 next->next = NULL;
290 return next;
291}
292
293#if COAP_CLIENT_SUPPORT
294const coap_bin_const_t *
296
297 if (session->psk_key) {
298 return session->psk_key;
299 }
300 if (session->cpsk_setup_data.psk_info.key.length)
301 return &session->cpsk_setup_data.psk_info.key;
302
303 /* Not defined in coap_new_client_session_psk2() */
304 return NULL;
305}
306
307const coap_bin_const_t *
309
310 if (session->psk_identity) {
311 return session->psk_identity;
312 }
314 return &session->cpsk_setup_data.psk_info.identity;
315
316 /* Not defined in coap_new_client_session_psk2() */
317 return NULL;
318}
319#endif /* COAP_CLIENT_SUPPORT */
320
321#if COAP_SERVER_SUPPORT
322const coap_bin_const_t *
324
325 if (session->psk_key)
326 return session->psk_key;
327
329 return &session->context->spsk_setup_data.psk_info.key;
330
331 /* Not defined in coap_context_set_psk2() */
332 return NULL;
333}
334
335const coap_bin_const_t *
337
338 if (session->psk_hint)
339 return session->psk_hint;
340
342 return &session->context->spsk_setup_data.psk_info.hint;
343
344 /* Not defined in coap_context_set_psk2() */
345 return NULL;
346}
347
348COAP_API int
350 const char *hint,
351 const uint8_t *key,
352 size_t key_len) {
353 int ret;
354
355 coap_lock_lock(ctx, return 0);
356 ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
357 coap_lock_unlock(ctx);
358 return ret;
359}
360
361int
363 const char *hint,
364 const uint8_t *key,
365 size_t key_len) {
366 coap_dtls_spsk_t setup_data;
367
369 memset(&setup_data, 0, sizeof(setup_data));
370 if (hint) {
371 setup_data.psk_info.hint.s = (const uint8_t *)hint;
372 setup_data.psk_info.hint.length = strlen(hint);
373 }
374
375 if (key && key_len > 0) {
376 setup_data.psk_info.key.s = key;
377 setup_data.psk_info.key.length = key_len;
378 }
379
380 return coap_context_set_psk2_lkd(ctx, &setup_data);
381}
382
383COAP_API int
385 int ret;
386
387 coap_lock_lock(ctx, return 0);
388 ret = coap_context_set_psk2_lkd(ctx, setup_data);
389 coap_lock_unlock(ctx);
390 return ret;
391}
392
393int
395 if (!setup_data)
396 return 0;
397
399 ctx->spsk_setup_data = *setup_data;
400
402 return coap_dtls_context_set_spsk(ctx, setup_data);
403 }
404 return 0;
405}
406
407COAP_API int
409 const coap_dtls_pki_t *setup_data) {
410 int ret;
411
412 coap_lock_lock(ctx, return 0);
413 ret = coap_context_set_pki_lkd(ctx, setup_data);
414 coap_lock_unlock(ctx);
415 return ret;
416}
417
418int
420 const coap_dtls_pki_t *setup_data) {
422 if (!setup_data)
423 return 0;
424 if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
425 coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
426 return 0;
427 }
429 return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
430 }
431 return 0;
432}
433#endif /* ! COAP_SERVER_SUPPORT */
434
435COAP_API int
437 const char *ca_file,
438 const char *ca_dir) {
439 int ret;
440
441 coap_lock_lock(ctx, return 0);
442 ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
443 coap_lock_unlock(ctx);
444 return ret;
445}
446
447int
449 const char *ca_file,
450 const char *ca_dir) {
452 return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
453 }
454 return 0;
455}
456
457COAP_API int
459 int ret;
460
461 coap_lock_lock(ctx, return 0);
463 coap_lock_unlock(ctx);
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(context, return);
672 coap_context_set_app_data2_lkd(context, app_data, NULL);
673 coap_lock_unlock(context);
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(context, return NULL);
688 old_data = coap_context_set_app_data2_lkd(context, app_data, callback);
689 coap_lock_unlock(context);
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
724 coap_lock_lock(c, coap_free_type(COAP_CONTEXT, c); return NULL);
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(context, return);
799 coap_context_set_app_data2_lkd(context, app_data, NULL);
800 coap_lock_unlock(context);
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(context, return);
814 coap_free_context_lkd(context);
815 coap_lock_unlock(context);
816}
817
818void
820 if (!context)
821 return;
822
823 coap_lock_check_locked(context);
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
1063 coap_lock_lock(session->context, return COAP_INVALID_MID);
1064 mid = coap_send_rst_lkd(session, request);
1065 coap_lock_unlock(session->context);
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
1078 coap_lock_lock(session->context, return COAP_INVALID_MID);
1079 mid = coap_send_ack_lkd(session, request);
1080 coap_lock_unlock(session->context);
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
1158 coap_lock_lock(session->context, return COAP_INVALID_MID);
1159 mid = coap_send_error_lkd(session, request, code, opts);
1160 coap_lock_unlock(session->context);
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
1187 coap_lock_lock(session->context, return COAP_INVALID_MID);
1188 mid = coap_send_message_type_lkd(session, request, type);
1189 coap_lock_unlock(session->context);
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
1296 coap_log_debug("Testing for Extended Token support\n");
1297 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1299 coap_new_message_id_lkd(session),
1301 if (!pdu)
1302 return COAP_INVALID_MID;
1303
1304 token = coap_new_binary(session->max_token_size);
1305 if (token == NULL) {
1307 return COAP_INVALID_MID;
1308 }
1309 for (i = 0; i < session->max_token_size; i++) {
1310 token->s[i] = (uint8_t)(i + 1);
1311 }
1312 coap_add_token(pdu, session->max_token_size, token->s);
1313 coap_delete_binary(token);
1314
1316
1317 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1318 if ((mid = coap_send_internal(session, pdu, NULL)) == COAP_INVALID_MID)
1319 return COAP_INVALID_MID;
1320 session->remote_test_mid = mid;
1321 return mid;
1322}
1323#endif /* COAP_CLIENT_SUPPORT */
1324
1325int
1327#if COAP_CLIENT_SUPPORT
1328 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1329 int timeout_ms = 5000;
1330 coap_session_state_t current_state = session->state;
1331
1332 if (session->delay_recursive) {
1333 return 0;
1334 } else {
1335 session->delay_recursive = 1;
1336 }
1337 /*
1338 * Need to wait for first request to get out and response back before
1339 * continuing.. Response handler has to clear doing_first if not an error.
1340 */
1342 while (session->doing_first != 0) {
1343 int result = coap_io_process_lkd(session->context, 1000);
1344
1345 if (result < 0) {
1346 session->doing_first = 0;
1347 session->delay_recursive = 0;
1348 coap_session_release_lkd(session);
1349 return 0;
1350 }
1351
1352 /* coap_io_process_lkd() may have updated session state */
1353 if (session->state == COAP_SESSION_STATE_CSM &&
1354 current_state != COAP_SESSION_STATE_CSM) {
1355 /* Update timeout and restart the clock for CSM timeout */
1356 current_state = COAP_SESSION_STATE_CSM;
1357 timeout_ms = session->context->csm_timeout_ms;
1358 result = 0;
1359 }
1360
1361 if (result < timeout_ms) {
1362 timeout_ms -= result;
1363 } else {
1364 if (session->doing_first == 1) {
1365 /* Timeout failure of some sort with first request */
1366 session->doing_first = 0;
1367 if (session->state == COAP_SESSION_STATE_CSM) {
1368 coap_log_debug("** %s: timeout waiting for CSM response\n",
1369 coap_session_str(session));
1370 session->csm_not_seen = 1;
1371 coap_session_connected(session);
1372 } else {
1373 coap_log_debug("** %s: timeout waiting for first response\n",
1374 coap_session_str(session));
1375 }
1376 }
1377 }
1378 }
1379 session->delay_recursive = 0;
1380 coap_session_release_lkd(session);
1381 }
1382#else /* ! COAP_CLIENT_SUPPORT */
1383 (void)session;
1384#endif /* ! COAP_CLIENT_SUPPORT */
1385 return 1;
1386}
1387
1388/*
1389 * return 0 Invalid
1390 * 1 Valid
1391 */
1392int
1394
1395 /* Check validity of sending code */
1396 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1397 case 0: /* Empty or request */
1398 case 2: /* Success */
1399 case 3: /* Reserved for future use */
1400 case 4: /* Client error */
1401 case 5: /* Server error */
1402 break;
1403 case 7: /* Reliable signalling */
1404 if (COAP_PROTO_RELIABLE(session->proto))
1405 break;
1406 /* Not valid if UDP */
1407 /* Fall through */
1408 case 1: /* Invalid */
1409 case 6: /* Invalid */
1410 default:
1411 return 0;
1412 }
1413 return 1;
1414}
1415
1416#if COAP_CLIENT_SUPPORT
1417/*
1418 * If type is CON and protocol is not reliable, there is no need to set up
1419 * lg_crcv if it can be built up based on sent PDU if there is a
1420 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1421 * (Q-)Block1.
1422 */
1423static int
1424coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1425 coap_opt_iterator_t opt_iter;
1426
1427 if (!COAP_PDU_IS_REQUEST(pdu))
1428 return 0;
1429
1430 if (
1431#if COAP_OSCORE_SUPPORT
1432 session->oscore_encryption ||
1433#endif /* COAP_OSCORE_SUPPORT */
1434 pdu->type == COAP_MESSAGE_NON ||
1435 COAP_PROTO_RELIABLE(session->proto) ||
1436 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1437#if COAP_Q_BLOCK_SUPPORT
1438 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1439#endif /* COAP_Q_BLOCK_SUPPORT */
1440 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1441 return 1;
1442 }
1443 return 0;
1444}
1445#endif /* COAP_CLIENT_SUPPORT */
1446
1449 coap_mid_t mid;
1450
1451 coap_lock_lock(session->context, return COAP_INVALID_MID);
1452 mid = coap_send_lkd(session, pdu);
1453 coap_lock_unlock(session->context);
1454 return mid;
1455}
1456
1460#if COAP_CLIENT_SUPPORT
1461 coap_lg_crcv_t *lg_crcv = NULL;
1462 coap_opt_iterator_t opt_iter;
1463 coap_block_b_t block;
1464 int observe_action = -1;
1465 int have_block1 = 0;
1466 coap_opt_t *opt;
1467#endif /* COAP_CLIENT_SUPPORT */
1468
1469 assert(pdu);
1470
1472
1473 /* Check validity of sending code */
1474 if (!coap_check_code_class(session, pdu)) {
1475 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1477 pdu->code & 0x1f);
1478 goto error;
1479 }
1480 pdu->session = session;
1481#if COAP_CLIENT_SUPPORT
1482 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1483 !coap_netif_available(session) && !session->session_failed) {
1484 coap_log_debug("coap_send: Socket closed\n");
1485 goto error;
1486 }
1487 /*
1488 * If this is not the first client request and are waiting for a response
1489 * to the first client request, then drop sending out this next request
1490 * until all is properly established.
1491 */
1492 if (!coap_client_delay_first(session)) {
1493 goto error;
1494 }
1495
1496 /* Indicate support for Extended Tokens if appropriate */
1497 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1499 session->type == COAP_SESSION_TYPE_CLIENT &&
1500 COAP_PDU_IS_REQUEST(pdu)) {
1501 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1502 /*
1503 * When the pass / fail response for Extended Token is received, this PDU
1504 * will get transmitted.
1505 */
1506 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1507 goto error;
1508 }
1509 }
1510 /*
1511 * For reliable protocols, this will get cleared after CSM exchanged
1512 * in coap_session_connected()
1513 */
1514 session->doing_first = 1;
1515 if (!coap_client_delay_first(session)) {
1516 goto error;
1517 }
1518 }
1519
1520 /*
1521 * Check validity of token length
1522 */
1523 if (COAP_PDU_IS_REQUEST(pdu) &&
1524 pdu->actual_token.length > session->max_token_size) {
1525 coap_log_warn("coap_send: PDU dropped as token too long (%zu > %" PRIu32 ")\n",
1526 pdu->actual_token.length, session->max_token_size);
1527 goto error;
1528 }
1529
1530 /* A lot of the reliable code assumes type is CON */
1531 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1532 pdu->type = COAP_MESSAGE_CON;
1533
1534#if COAP_OSCORE_SUPPORT
1535 if (session->oscore_encryption) {
1536 if (session->recipient_ctx->initial_state == 1) {
1537 /*
1538 * Not sure if remote supports OSCORE, or is going to send us a
1539 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1540 * is OK. Continue sending current pdu to test things.
1541 */
1542 session->doing_first = 1;
1543 }
1544 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1546 goto error;
1547 }
1548 }
1549#endif /* COAP_OSCORE_SUPPORT */
1550
1551 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1552 return coap_send_internal(session, pdu, NULL);
1553 }
1554
1555 if (COAP_PDU_IS_REQUEST(pdu)) {
1556 uint8_t buf[4];
1557
1558 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1559
1560 if (opt) {
1561 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1562 coap_opt_length(opt));
1563 }
1564
1565 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1566 (block.m == 1 || block.bert == 1)) {
1567 have_block1 = 1;
1568 }
1569#if COAP_Q_BLOCK_SUPPORT
1570 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1571 (block.m == 1 || block.bert == 1)) {
1572 if (have_block1) {
1573 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1575 }
1576 have_block1 = 1;
1577 }
1578#endif /* COAP_Q_BLOCK_SUPPORT */
1579 if (observe_action != COAP_OBSERVE_CANCEL) {
1580 /* Warn about re-use of tokens */
1581 if (session->last_token &&
1582 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1583 coap_log_debug("Token reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n");
1584 }
1587 pdu->actual_token.length);
1588 } else {
1589 /* observe_action == COAP_OBSERVE_CANCEL */
1590 coap_binary_t tmp;
1591 int ret;
1592
1593 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1594 /* Unfortunately need to change the ptr type to be r/w */
1595 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1596 tmp.length = pdu->actual_token.length;
1597 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1598 if (ret == 1) {
1599 /* Observe Cancel successfully sent */
1601 return ret;
1602 }
1603 /* Some mismatch somewhere - continue to send original packet */
1604 }
1605 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1606 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1610 coap_encode_var_safe(buf, sizeof(buf),
1611 ++session->tx_rtag),
1612 buf);
1613 } else {
1614 memset(&block, 0, sizeof(block));
1615 }
1616
1617#if COAP_Q_BLOCK_SUPPORT
1618 /* Indicate support for Q-Block if appropriate */
1619 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1620 session->type == COAP_SESSION_TYPE_CLIENT &&
1621 COAP_PDU_IS_REQUEST(pdu)) {
1622 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1623 goto error;
1624 }
1625 session->doing_first = 1;
1626 if (!coap_client_delay_first(session)) {
1627 /* Q-Block test Session has failed for some reason */
1628 set_block_mode_drop_q(session->block_mode);
1629 goto error;
1630 }
1631 }
1632#endif /* COAP_Q_BLOCK_SUPPORT */
1633
1634#if COAP_Q_BLOCK_SUPPORT
1635 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1636#endif /* COAP_Q_BLOCK_SUPPORT */
1637 {
1638 /* Need to check if we need to reset Q-Block to Block */
1639 uint8_t buf[4];
1640
1641 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1644 coap_encode_var_safe(buf, sizeof(buf),
1645 (block.num << 4) | (0 << 3) | block.szx),
1646 buf);
1647 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1648 /* Need to update associated lg_xmit */
1649 coap_lg_xmit_t *lg_xmit;
1650
1651 LL_FOREACH(session->lg_xmit, lg_xmit) {
1652 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1653 lg_xmit->b.b1.app_token &&
1654 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1655 /* Update the skeletal PDU with the block1 option */
1658 coap_encode_var_safe(buf, sizeof(buf),
1659 (block.num << 4) | (0 << 3) | block.szx),
1660 buf);
1661 break;
1662 }
1663 }
1664 }
1665 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1668 coap_encode_var_safe(buf, sizeof(buf),
1669 (block.num << 4) | (block.m << 3) | block.szx),
1670 buf);
1671 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1672 /* Need to update associated lg_xmit */
1673 coap_lg_xmit_t *lg_xmit;
1674
1675 LL_FOREACH(session->lg_xmit, lg_xmit) {
1676 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1677 lg_xmit->b.b1.app_token &&
1678 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1679 /* Update the skeletal PDU with the block1 option */
1682 coap_encode_var_safe(buf, sizeof(buf),
1683 (block.num << 4) |
1684 (block.m << 3) |
1685 block.szx),
1686 buf);
1687 /* Update as this is a Request */
1688 lg_xmit->option = COAP_OPTION_BLOCK1;
1689 break;
1690 }
1691 }
1692 }
1693 }
1694
1695#if COAP_Q_BLOCK_SUPPORT
1696 if (COAP_PDU_IS_REQUEST(pdu) &&
1697 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1698 if (block.num == 0 && block.m == 0) {
1699 uint8_t buf[4];
1700
1701 /* M needs to be set as asking for all the blocks */
1703 coap_encode_var_safe(buf, sizeof(buf),
1704 (0 << 4) | (1 << 3) | block.szx),
1705 buf);
1706 }
1707 }
1708#endif /* COAP_Q_BLOCK_SUPPORT */
1709
1710 /*
1711 * If type is CON and protocol is not reliable, there is no need to set up
1712 * lg_crcv here as it can be built up based on sent PDU if there is a
1713 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1714 * (Q-)Block1.
1715 */
1716 if (coap_check_send_need_lg_crcv(session, pdu)) {
1717 coap_lg_xmit_t *lg_xmit = NULL;
1718
1719 if (!session->lg_xmit && have_block1) {
1720 coap_log_debug("PDU presented by app\n");
1722 }
1723 /* See if this token is already in use for large body responses */
1724 LL_FOREACH(session->lg_crcv, lg_crcv) {
1725 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1726 /* Need to terminate and clean up previous response setup */
1727 LL_DELETE(session->lg_crcv, lg_crcv);
1728 coap_block_delete_lg_crcv(session, lg_crcv);
1729 break;
1730 }
1731 }
1732
1733 if (have_block1 && session->lg_xmit) {
1734 LL_FOREACH(session->lg_xmit, lg_xmit) {
1735 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1736 lg_xmit->b.b1.app_token &&
1737 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1738 break;
1739 }
1740 }
1741 }
1742 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1743 if (lg_crcv == NULL) {
1744 goto error;
1745 }
1746 if (lg_xmit) {
1747 /* Need to update the token as set up in the session->lg_xmit */
1748 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1749 }
1750 }
1751 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1752 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1753
1754#if COAP_Q_BLOCK_SUPPORT
1755 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1756 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1757 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1758 } else
1759#endif /* COAP_Q_BLOCK_SUPPORT */
1760 mid = coap_send_internal(session, pdu, NULL);
1761#else /* !COAP_CLIENT_SUPPORT */
1762 mid = coap_send_internal(session, pdu, NULL);
1763#endif /* !COAP_CLIENT_SUPPORT */
1764#if COAP_CLIENT_SUPPORT
1765 if (lg_crcv) {
1766 if (mid != COAP_INVALID_MID) {
1767 LL_PREPEND(session->lg_crcv, lg_crcv);
1768 } else {
1769 coap_block_delete_lg_crcv(session, lg_crcv);
1770 }
1771 }
1772#endif /* COAP_CLIENT_SUPPORT */
1773 return mid;
1774
1775error:
1777 return COAP_INVALID_MID;
1778}
1779
1780#if COAP_SERVER_SUPPORT
1781static int
1782coap_pdu_cksum(const coap_pdu_t *pdu, coap_digest_t *digest_buffer) {
1783 coap_digest_ctx_t *digest_ctx = coap_digest_setup();
1784
1785 if (!digest_ctx || !pdu) {
1786 goto fail;
1787 }
1788 if (pdu->used_size && pdu->token) {
1789 if (!coap_digest_update(digest_ctx, pdu->token, pdu->used_size)) {
1790 goto fail;
1791 }
1792 }
1793 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->type, sizeof(pdu->type))) {
1794 goto fail;
1795 }
1796 if (!coap_digest_update(digest_ctx, (const uint8_t *)&pdu->code, sizeof(pdu->code))) {
1797 goto fail;
1798 }
1799 if (!coap_digest_final(digest_ctx, digest_buffer))
1800 return 0;
1801
1802 return 1;
1803
1804fail:
1805 coap_digest_free(digest_ctx);
1806 return 0;
1807}
1808#endif /* COAP_SERVER_SUPPORT */
1809
1812 uint8_t r;
1813 ssize_t bytes_written;
1814 coap_opt_iterator_t opt_iter;
1815
1816#if ! COAP_SERVER_SUPPORT
1817 (void)request_pdu;
1818#endif /* COAP_SERVER_SUPPORT */
1819 pdu->session = session;
1820#if COAP_CLIENT_SUPPORT
1821 if (session->session_failed) {
1822 coap_session_reconnect(session);
1823 if (session->session_failed)
1824 goto error;
1825 }
1826#endif /* COAP_CLIENT_SUPPORT */
1827#if COAP_PROXY_SUPPORT
1828 if (session->server_list) {
1829 /* Local session wanting to use proxy logic */
1830 return coap_proxy_local_write(session, pdu);
1831 }
1832#endif /* COAP_PROXY_SUPPORT */
1833 if (pdu->code == COAP_RESPONSE_CODE(508)) {
1834 /*
1835 * Need to prepend our IP identifier to the data as per
1836 * https://rfc-editor.org/rfc/rfc8768.html#section-4
1837 */
1838 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1839 coap_opt_t *opt;
1840 size_t hop_limit;
1841
1842 addr_str[sizeof(addr_str)-1] = '\000';
1843 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1844 sizeof(addr_str) - 1)) {
1845 char *cp;
1846 size_t len;
1847
1848 if (addr_str[0] == '[') {
1849 cp = strchr(addr_str, ']');
1850 if (cp)
1851 *cp = '\000';
1852 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1853 /* IPv4 embedded into IPv6 */
1854 cp = &addr_str[8];
1855 } else {
1856 cp = &addr_str[1];
1857 }
1858 } else {
1859 cp = strchr(addr_str, ':');
1860 if (cp)
1861 *cp = '\000';
1862 cp = addr_str;
1863 }
1864 len = strlen(cp);
1865
1866 /* See if Hop Limit option is being used in return path */
1867 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1868 if (opt) {
1869 uint8_t buf[4];
1870
1871 hop_limit =
1873 if (hop_limit == 1) {
1874 coap_log_warn("Proxy loop detected '%s'\n",
1875 (char *)pdu->data);
1878 } else if (hop_limit < 1 || hop_limit > 255) {
1879 /* Something is bad - need to drop this pdu (TODO or delete option) */
1880 coap_log_warn("Proxy return has bad hop limit count '%zu'\n",
1881 hop_limit);
1884 }
1885 hop_limit--;
1887 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1888 buf);
1889 }
1890
1891 /* Need to check that we are not seeing this proxy in the return loop */
1892 if (pdu->data && opt == NULL) {
1893 char *a_match;
1894 size_t data_len;
1895
1896 if (pdu->used_size + 1 > pdu->max_size) {
1897 /* No space */
1899 }
1900 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1901 /* Internal error */
1903 }
1904 data_len = pdu->used_size - (pdu->data - pdu->token);
1905 pdu->data[data_len] = '\000';
1906 a_match = strstr((char *)pdu->data, cp);
1907 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1908 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1909 a_match[len] == ' ')) {
1910 coap_log_warn("Proxy loop detected '%s'\n",
1911 (char *)pdu->data);
1914 }
1915 }
1916 if (pdu->used_size + len + 1 <= pdu->max_size) {
1917 size_t old_size = pdu->used_size;
1918 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1919 if (pdu->data == NULL) {
1920 /*
1921 * Set Hop Limit to max for return path. If this libcoap is in
1922 * a proxy loop path, it will always decrement hop limit in code
1923 * above and hence timeout / drop the response as appropriate
1924 */
1925 hop_limit = 255;
1927 (uint8_t *)&hop_limit);
1928 coap_add_data(pdu, len, (uint8_t *)cp);
1929 } else {
1930 /* prepend with space separator, leaving hop limit "as is" */
1931 memmove(pdu->data + len + 1, pdu->data,
1932 old_size - (pdu->data - pdu->token));
1933 memcpy(pdu->data, cp, len);
1934 pdu->data[len] = ' ';
1935 pdu->used_size += len + 1;
1936 }
1937 }
1938 }
1939 }
1940 }
1941
1942 if (session->echo) {
1943 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1944 session->echo->s))
1945 goto error;
1946 coap_delete_bin_const(session->echo);
1947 session->echo = NULL;
1948 }
1949#if COAP_OSCORE_SUPPORT
1950 if (session->oscore_encryption) {
1951 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1953 goto error;
1954 }
1955#endif /* COAP_OSCORE_SUPPORT */
1956
1957 if (!coap_pdu_encode_header(pdu, session->proto)) {
1958 goto error;
1959 }
1960
1961#if !COAP_DISABLE_TCP
1962 if (COAP_PROTO_RELIABLE(session->proto) &&
1964 if (!session->csm_block_supported) {
1965 /*
1966 * Need to check that this instance is not sending any block options as
1967 * the remote end via CSM has not informed us that there is support
1968 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
1969 * This includes potential BERT blocks.
1970 */
1971 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1972 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
1973 }
1974 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1975 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
1976 }
1977 } else if (!session->csm_bert_rem_support) {
1978 coap_opt_t *opt;
1979
1980 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
1981 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1982 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
1983 }
1984 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
1985 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1986 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
1987 }
1988 }
1989 }
1990#endif /* !COAP_DISABLE_TCP */
1991
1992#if COAP_OSCORE_SUPPORT
1993 if (session->oscore_encryption &&
1994 pdu->type != COAP_MESSAGE_RST &&
1995 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
1996 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
1997 /* Refactor PDU as appropriate RFC8613 */
1998 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
1999
2000 if (osc_pdu == NULL) {
2001 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2004 goto error;
2005 }
2006 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2008 pdu = osc_pdu;
2009 } else
2010#endif /* COAP_OSCORE_SUPPORT */
2011 bytes_written = coap_send_pdu(session, pdu, NULL);
2012
2013#if COAP_SERVER_SUPPORT
2014 if ((session->block_mode & COAP_BLOCK_CACHE_RESPONSE) &&
2015 session->cached_pdu != pdu &&
2016 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2017 COAP_PDU_IS_REQUEST(request_pdu) &&
2018 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2020 session->cached_pdu = pdu;
2022 coap_pdu_cksum(request_pdu, &session->cached_pdu_cksum);
2023 }
2024#endif /* COAP_SERVER_SUPPORT */
2025
2026 if (bytes_written == COAP_PDU_DELAYED) {
2027 /* do not free pdu as it is stored with session for later use */
2028 return pdu->mid;
2029 }
2030 if (bytes_written < 0) {
2032 goto error;
2033 }
2034
2035#if !COAP_DISABLE_TCP
2036 if (COAP_PROTO_RELIABLE(session->proto) &&
2037 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2038 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2039 session->partial_write = (size_t)bytes_written;
2040 /* do not free pdu as it is stored with session for later use */
2041 return pdu->mid;
2042 } else {
2043 goto error;
2044 }
2045 }
2046#endif /* !COAP_DISABLE_TCP */
2047
2048 if (pdu->type != COAP_MESSAGE_CON
2049 || COAP_PROTO_RELIABLE(session->proto)) {
2050 coap_mid_t id = pdu->mid;
2052 return id;
2053 }
2054
2055 coap_queue_t *node = coap_new_node();
2056 if (!node) {
2057 coap_log_debug("coap_wait_ack: insufficient memory\n");
2058 goto error;
2059 }
2060
2061 node->id = pdu->mid;
2062 node->pdu = pdu;
2063 coap_prng_lkd(&r, sizeof(r));
2064 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2065 node->timeout = coap_calc_timeout(session, r);
2066 return coap_wait_ack(session->context, session, node);
2067error:
2069 return COAP_INVALID_MID;
2070}
2071
2072static int send_recv_terminate = 0;
2073
2074void
2078
2079COAP_API int
2081 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2082 int ret;
2083
2084 coap_lock_lock(session->context, return 0);
2085 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2086 coap_lock_unlock(session->context);
2087 return ret;
2088}
2089
2090/*
2091 * Return 0 or +ve Time in function in ms after successful transfer
2092 * -1 Invalid timeout parameter
2093 * -2 Failed to transmit PDU
2094 * -3 Nack or Event handler invoked, cancelling request
2095 * -4 coap_io_process returned error (fail to re-lock or select())
2096 * -5 Response not received in the given time
2097 * -6 Terminated by user
2098 * -7 Client mode code not enabled
2099 */
2100int
2102 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2103#if COAP_CLIENT_SUPPORT
2105 uint32_t rem_timeout = timeout_ms;
2106 uint32_t block_mode = session->block_mode;
2107 int ret = 0;
2108 coap_tick_t now;
2109 coap_tick_t start;
2110 coap_tick_t ticks_so_far;
2111 uint32_t time_so_far_ms;
2112
2113 coap_ticks(&start);
2114 assert(request_pdu);
2115
2117
2118 session->resp_pdu = NULL;
2119 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2120 request_pdu->actual_token.length);
2121
2122 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2123 ret = -1;
2124 goto fail;
2125 }
2126 if (session->state == COAP_SESSION_STATE_NONE) {
2127 ret = -3;
2128 goto fail;
2129 }
2130
2132 if (coap_is_mcast(&session->addr_info.remote))
2133 block_mode = session->block_mode;
2134
2135 session->doing_send_recv = 1;
2136 /* So the user needs to delete the PDU */
2137 coap_pdu_reference_lkd(request_pdu);
2138 mid = coap_send_lkd(session, request_pdu);
2139 if (mid == COAP_INVALID_MID) {
2140 if (!session->doing_send_recv)
2141 ret = -3;
2142 else
2143 ret = -2;
2144 goto fail;
2145 }
2146
2147 /* Wait for the response to come in */
2148 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2149 if (send_recv_terminate) {
2150 ret = -6;
2151 goto fail;
2152 }
2153 ret = coap_io_process_lkd(session->context, rem_timeout);
2154 if (ret < 0) {
2155 ret = -4;
2156 goto fail;
2157 }
2158 /* timeout_ms is for timeout between specific request and response */
2159 coap_ticks(&now);
2160 ticks_so_far = now - session->last_rx_tx;
2161 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2162 if (time_so_far_ms >= timeout_ms) {
2163 rem_timeout = 0;
2164 } else {
2165 rem_timeout = timeout_ms - time_so_far_ms;
2166 }
2167 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2168 /* To pick up on (D)TLS setup issues */
2169 coap_ticks(&now);
2170 ticks_so_far = now - start;
2171 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2172 if (time_so_far_ms >= timeout_ms) {
2173 rem_timeout = 0;
2174 } else {
2175 rem_timeout = timeout_ms - time_so_far_ms;
2176 }
2177 }
2178 }
2179
2180 if (rem_timeout) {
2181 coap_ticks(&now);
2182 ticks_so_far = now - start;
2183 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2184 ret = time_so_far_ms;
2185 /* Give PDU to user who will be calling coap_delete_pdu() */
2186 *response_pdu = session->resp_pdu;
2187 session->resp_pdu = NULL;
2188 if (*response_pdu == NULL) {
2189 ret = -3;
2190 }
2191 } else {
2192 /* If there is a resp_pdu, it will get cleared below */
2193 ret = -5;
2194 }
2195
2196fail:
2197 session->block_mode = block_mode;
2198 session->doing_send_recv = 0;
2199 /* delete referenced copy */
2200 coap_delete_pdu_lkd(session->resp_pdu);
2201 session->resp_pdu = NULL;
2203 session->req_token = NULL;
2204 return ret;
2205
2206#else /* !COAP_CLIENT_SUPPORT */
2207
2208 (void)session;
2209 (void)timeout_ms;
2210 (void)request_pdu;
2211 coap_log_warn("coap_send_recv: Client mode not supported\n");
2212 *response_pdu = NULL;
2213 return -7;
2214
2215#endif /* ! COAP_CLIENT_SUPPORT */
2216}
2217
2220 if (!context || !node || !node->session)
2221 return COAP_INVALID_MID;
2222
2223 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2224 if (node->retransmit_cnt < node->session->max_retransmit) {
2225 ssize_t bytes_written;
2226 coap_tick_t now;
2227 coap_tick_t next_delay;
2228 coap_address_t remote;
2229
2230 node->retransmit_cnt++;
2232
2233 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2234 if (context->ping_timeout &&
2235 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2236 uint8_t byte;
2237
2238 coap_prng_lkd(&byte, sizeof(byte));
2239 /* Don't exceed the ping timeout value */
2240 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2241 }
2242
2243 coap_ticks(&now);
2244 if (context->sendqueue == NULL) {
2245 node->t = next_delay;
2246 context->sendqueue_basetime = now;
2247 } else {
2248 /* make node->t relative to context->sendqueue_basetime */
2249 node->t = (now - context->sendqueue_basetime) + next_delay;
2250 }
2251 coap_insert_node(&context->sendqueue, node);
2252 coap_address_copy(&remote, &node->session->addr_info.remote);
2254
2255 if (node->is_mcast) {
2256 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2257 coap_session_str(node->session), node->id);
2258 } else {
2259 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2260 coap_session_str(node->session), node->id,
2261 node->retransmit_cnt,
2262 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2263 }
2264
2265 if (node->session->con_active)
2266 node->session->con_active--;
2267 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2268
2269 if (bytes_written == COAP_PDU_DELAYED) {
2270 /* PDU was not retransmitted immediately because a new handshake is
2271 in progress. node was moved to the send queue of the session. */
2272 return node->id;
2273 }
2274
2275 coap_address_copy(&node->session->addr_info.remote, &remote);
2276 if (node->is_mcast) {
2279 return COAP_INVALID_MID;
2280 }
2281
2282 if (bytes_written < 0)
2283 return (int)bytes_written;
2284
2285 return node->id;
2286 }
2287
2288 /* no more retransmissions, remove node from system */
2289 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2290 coap_session_str(node->session), node->id, node->retransmit_cnt);
2291
2292#if COAP_SERVER_SUPPORT
2293 /* Check if subscriptions exist that should be canceled after
2294 COAP_OBS_MAX_FAIL */
2295 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 && node->session->ref_subscriptions) {
2296 if (context->ping_timeout) {
2299 return COAP_INVALID_MID;
2300 } else {
2301 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2302 }
2303 }
2304#endif /* COAP_SERVER_SUPPORT */
2305 if (node->session->con_active) {
2306 node->session->con_active--;
2308 /*
2309 * As there may be another CON in a different queue entry on the same
2310 * session that needs to be immediately released,
2311 * coap_session_connected() is called.
2312 * However, there is the possibility coap_wait_ack() may be called for
2313 * this node (queue) and re-added to context->sendqueue.
2314 * coap_delete_node_lkd(node) called shortly will handle this and
2315 * remove it.
2316 */
2318 }
2319 }
2320
2321 if (node->pdu->type == COAP_MESSAGE_CON) {
2323 }
2324#if COAP_CLIENT_SUPPORT
2325 node->session->doing_send_recv = 0;
2326#endif /* COAP_CLIENT_SUPPORT */
2327 /* And finally delete the node */
2329 return COAP_INVALID_MID;
2330}
2331
2332static int
2334 uint8_t *data;
2335 size_t data_len;
2336 int result = -1;
2337
2338 coap_packet_get_memmapped(packet, &data, &data_len);
2339 if (session->proto == COAP_PROTO_DTLS) {
2340#if COAP_SERVER_SUPPORT
2341 if (session->type == COAP_SESSION_TYPE_HELLO)
2342 result = coap_dtls_hello(session, data, data_len);
2343 else
2344#endif /* COAP_SERVER_SUPPORT */
2345 if (session->tls)
2346 result = coap_dtls_receive(session, data, data_len);
2347 } else if (session->proto == COAP_PROTO_UDP) {
2348 result = coap_handle_dgram(ctx, session, data, data_len);
2349 }
2350 return result;
2351}
2352
2353#if COAP_CLIENT_SUPPORT
2354void
2356#if COAP_DISABLE_TCP
2357 (void)now;
2358
2360#else /* !COAP_DISABLE_TCP */
2361 if (coap_netif_strm_connect2(session)) {
2362 session->last_rx_tx = now;
2364 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2365 } else {
2368 }
2369#endif /* !COAP_DISABLE_TCP */
2370}
2371#endif /* COAP_CLIENT_SUPPORT */
2372
2373static void
2375 (void)ctx;
2376 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2377
2378 while (session->delayqueue) {
2379 ssize_t bytes_written;
2380 coap_queue_t *q = session->delayqueue;
2381
2382 coap_address_copy(&session->addr_info.remote, &q->remote);
2383 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2384 coap_session_str(session), (int)q->pdu->mid);
2385 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2386 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2387 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2388 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2389 if (bytes_written > 0)
2390 session->last_rx_tx = now;
2391 if (bytes_written <= 0 ||
2392 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2393 if (bytes_written > 0)
2394 session->partial_write += (size_t)bytes_written;
2395 break;
2396 }
2397 session->delayqueue = q->next;
2398 session->partial_write = 0;
2400 }
2401}
2402
2403void
2405#if COAP_CONSTRAINED_STACK
2406 /* payload and packet can be protected by global_lock if needed */
2407 static unsigned char payload[COAP_RXBUFFER_SIZE];
2408 static coap_packet_t s_packet;
2409#else /* ! COAP_CONSTRAINED_STACK */
2410 unsigned char payload[COAP_RXBUFFER_SIZE];
2411 coap_packet_t s_packet;
2412#endif /* ! COAP_CONSTRAINED_STACK */
2413 coap_packet_t *packet = &s_packet;
2414
2416
2417 packet->length = sizeof(payload);
2418 packet->payload = payload;
2419
2420 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2421 ssize_t bytes_read;
2422 coap_address_t remote;
2423
2424 coap_address_copy(&remote, &session->addr_info.remote);
2425 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2426 bytes_read = coap_netif_dgrm_read(session, packet);
2427
2428 if (bytes_read < 0) {
2429 if (bytes_read == -2) {
2430 coap_address_copy(&session->addr_info.remote, &remote);
2431 /* Reset the session back to startup defaults */
2433 }
2434 } else if (bytes_read > 0) {
2435 session->last_rx_tx = now;
2436#if COAP_CLIENT_SUPPORT
2437 if (session->session_failed)
2438 session->session_failed = 0;
2439#endif /* COAP_CLIENT_SUPPORT */
2440 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2441 coap_handle_dgram_for_proto(ctx, session, packet);
2442 } else {
2443 coap_address_copy(&session->addr_info.remote, &remote);
2444 }
2445#if !COAP_DISABLE_TCP
2446 } else if (session->proto == COAP_PROTO_WS ||
2447 session->proto == COAP_PROTO_WSS) {
2448 ssize_t bytes_read = 0;
2449
2450 /* WebSocket layer passes us the whole packet */
2451 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2452 packet->payload,
2453 packet->length);
2454 if (bytes_read < 0) {
2456 } else if (bytes_read > 2) {
2457 coap_pdu_t *pdu;
2458
2459 session->last_rx_tx = now;
2460 /* Need max space incase PDU is updated with updated token etc. */
2461 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2462 if (!pdu) {
2463 return;
2464 }
2465
2466 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2468 coap_log_warn("discard malformed PDU\n");
2470 return;
2471 }
2472
2473 coap_dispatch(ctx, session, pdu);
2475 return;
2476 }
2477 } else {
2478 ssize_t bytes_read = 0;
2479 const uint8_t *p;
2480 int retry;
2481
2482 do {
2483 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2484 packet->payload,
2485 packet->length);
2486 if (bytes_read > 0) {
2487 session->last_rx_tx = now;
2488 }
2489 p = packet->payload;
2490 retry = bytes_read == (ssize_t)packet->length;
2491 while (bytes_read > 0) {
2492 if (session->partial_pdu) {
2493 size_t len = session->partial_pdu->used_size
2494 + session->partial_pdu->hdr_size
2495 - session->partial_read;
2496 size_t n = min(len, (size_t)bytes_read);
2497 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2498 + session->partial_read, p, n);
2499 p += n;
2500 bytes_read -= n;
2501 if (n == len) {
2502 coap_opt_filter_t error_opts;
2503
2504 coap_option_filter_clear(&error_opts);
2505 if (coap_pdu_parse_header(session->partial_pdu, session->proto)
2506 && coap_pdu_parse_opt(session->partial_pdu, &error_opts)) {
2507 coap_dispatch(ctx, session, session->partial_pdu);
2508 } else if (error_opts.mask) {
2509 coap_pdu_t *response =
2511 COAP_RESPONSE_CODE(402), &error_opts);
2512 if (!response) {
2513 coap_log_warn("coap_read_session: cannot create error response\n");
2514 } else {
2515 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2516 coap_log_warn("coap_read_session: error sending response\n");
2517 }
2518 }
2520 session->partial_pdu = NULL;
2521 session->partial_read = 0;
2522 } else {
2523 session->partial_read += n;
2524 }
2525 } else if (session->partial_read > 0) {
2526 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2527 session->read_header);
2528 size_t tkl = session->read_header[0] & 0x0f;
2529 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2530 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2531 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2532 size_t n = min(len, (size_t)bytes_read);
2533 memcpy(session->read_header + session->partial_read, p, n);
2534 p += n;
2535 bytes_read -= n;
2536 if (n == len) {
2537 /* Header now all in */
2538 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2539 hdr_size + tok_ext_bytes);
2540 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2541 coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
2542 coap_session_str(session),
2543 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
2544 bytes_read = -1;
2545 break;
2546 }
2547 /* Need max space incase PDU is updated with updated token etc. */
2548 session->partial_pdu = coap_pdu_init(0, 0, 0,
2550 if (session->partial_pdu == NULL) {
2551 bytes_read = -1;
2552 break;
2553 }
2554 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2555 bytes_read = -1;
2556 break;
2557 }
2558 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2559 session->partial_pdu->used_size = size;
2560 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2561 session->partial_read = hdr_size + tok_ext_bytes;
2562 if (size == 0) {
2563 if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
2564 coap_dispatch(ctx, session, session->partial_pdu);
2565 }
2567 session->partial_pdu = NULL;
2568 session->partial_read = 0;
2569 }
2570 } else {
2571 /* More of the header to go */
2572 session->partial_read += n;
2573 }
2574 } else {
2575 /* Get in first byte of the header */
2576 session->read_header[0] = *p++;
2577 bytes_read -= 1;
2578 if (!coap_pdu_parse_header_size(session->proto,
2579 session->read_header)) {
2580 bytes_read = -1;
2581 break;
2582 }
2583 session->partial_read = 1;
2584 }
2585 }
2586 } while (bytes_read == 0 && retry);
2587 if (bytes_read < 0)
2589#endif /* !COAP_DISABLE_TCP */
2590 }
2591}
2592
2593#if COAP_SERVER_SUPPORT
2594static int
2595coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2596 ssize_t bytes_read = -1;
2597 int result = -1; /* the value to be returned */
2598#if COAP_CONSTRAINED_STACK
2599 /* payload and e_packet can be protected by global_lock if needed */
2600 static unsigned char payload[COAP_RXBUFFER_SIZE];
2601 static coap_packet_t e_packet;
2602#else /* ! COAP_CONSTRAINED_STACK */
2603 unsigned char payload[COAP_RXBUFFER_SIZE];
2604 coap_packet_t e_packet;
2605#endif /* ! COAP_CONSTRAINED_STACK */
2606 coap_packet_t *packet = &e_packet;
2607
2608 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2609 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2610
2611 /* Need to do this as there may be holes in addr_info */
2612 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2613 packet->length = sizeof(payload);
2614 packet->payload = payload;
2616 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2617
2618 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2619 if (bytes_read < 0) {
2620 if (errno != EAGAIN) {
2621 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2622 }
2623 } else if (bytes_read > 0) {
2624 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2625 if (session) {
2627 coap_log_debug("* %s: netif: recv %4zd bytes\n",
2628 coap_session_str(session), bytes_read);
2629 result = coap_handle_dgram_for_proto(ctx, session, packet);
2630 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2631 coap_session_new_dtls_session(session, now);
2632 coap_session_release_lkd(session);
2633 }
2634 }
2635 return result;
2636}
2637
2638static int
2639coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2640 (void)ctx;
2641 (void)endpoint;
2642 (void)now;
2643 return 0;
2644}
2645
2646#if !COAP_DISABLE_TCP
2647static int
2648coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2649 coap_tick_t now, void *extra) {
2650 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2651 if (session)
2652 session->last_rx_tx = now;
2653 return session != NULL;
2654}
2655#endif /* !COAP_DISABLE_TCP */
2656#endif /* COAP_SERVER_SUPPORT */
2657
2658COAP_API void
2660 coap_lock_lock(ctx, return);
2661 coap_io_do_io_lkd(ctx, now);
2662 coap_lock_unlock(ctx);
2663}
2664
2665void
2667#ifdef COAP_EPOLL_SUPPORT
2668 (void)ctx;
2669 (void)now;
2670 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2671#else /* ! COAP_EPOLL_SUPPORT */
2672 coap_session_t *s, *rtmp;
2673
2675#if COAP_SERVER_SUPPORT
2676 coap_endpoint_t *ep, *tmp;
2677 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2678 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2679 coap_read_endpoint(ctx, ep, now);
2680 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2681 coap_write_endpoint(ctx, ep, now);
2682#if !COAP_DISABLE_TCP
2683 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2684 coap_accept_endpoint(ctx, ep, now, NULL);
2685#endif /* !COAP_DISABLE_TCP */
2686 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2687 /* Make sure the session object is not deleted in one of the callbacks */
2689 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2690 coap_read_session(ctx, s, now);
2691 }
2692 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2693 coap_write_session(ctx, s, now);
2694 }
2696 }
2697 }
2698#endif /* COAP_SERVER_SUPPORT */
2699
2700#if COAP_CLIENT_SUPPORT
2701 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2702 /* Make sure the session object is not deleted in one of the callbacks */
2704 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2705 coap_connect_session(s, now);
2706 }
2707 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2708 coap_read_session(ctx, s, now);
2709 }
2710 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2711 coap_write_session(ctx, s, now);
2712 }
2714 }
2715#endif /* COAP_CLIENT_SUPPORT */
2716#endif /* ! COAP_EPOLL_SUPPORT */
2717}
2718
2719COAP_API void
2720coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2721 coap_lock_lock(ctx, return);
2722 coap_io_do_epoll_lkd(ctx, events, nevents);
2723 coap_lock_unlock(ctx);
2724}
2725
2726/*
2727 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
2728 * directly saves having to iterate through the endpoints / sessions.
2729 */
2730void
2731coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2732#ifndef COAP_EPOLL_SUPPORT
2733 (void)ctx;
2734 (void)events;
2735 (void)nevents;
2736 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2737#else /* COAP_EPOLL_SUPPORT */
2738 coap_tick_t now;
2739 size_t j;
2740
2742 coap_ticks(&now);
2743 for (j = 0; j < nevents; j++) {
2744 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2745
2746 /* Ignore 'timer trigger' ptr which is NULL */
2747 if (sock) {
2748#if COAP_SERVER_SUPPORT
2749 if (sock->endpoint) {
2750 coap_endpoint_t *endpoint = sock->endpoint;
2751 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2752 (events[j].events & EPOLLIN)) {
2753 sock->flags |= COAP_SOCKET_CAN_READ;
2754 coap_read_endpoint(endpoint->context, endpoint, now);
2755 }
2756
2757 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2758 (events[j].events & EPOLLOUT)) {
2759 /*
2760 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2761 * be true causing epoll_wait to return early
2762 */
2763 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2765 coap_write_endpoint(endpoint->context, endpoint, now);
2766 }
2767
2768#if !COAP_DISABLE_TCP
2769 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2770 (events[j].events & EPOLLIN)) {
2772 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
2773 }
2774#endif /* !COAP_DISABLE_TCP */
2775
2776 } else
2777#endif /* COAP_SERVER_SUPPORT */
2778 if (sock->session) {
2779 coap_session_t *session = sock->session;
2780
2781 /* Make sure the session object is not deleted
2782 in one of the callbacks */
2784#if COAP_CLIENT_SUPPORT
2785 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2786 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2788 coap_connect_session(session, now);
2789 if (coap_netif_available(session) &&
2790 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2791 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2792 }
2793 }
2794#endif /* COAP_CLIENT_SUPPORT */
2795
2796 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2797 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2798 sock->flags |= COAP_SOCKET_CAN_READ;
2799 coap_read_session(session->context, session, now);
2800 }
2801
2802 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2803 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2804 /*
2805 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2806 * be true causing epoll_wait to return early
2807 */
2808 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2810 coap_write_session(session->context, session, now);
2811 }
2812 /* Now dereference session so it can go away if needed */
2813 coap_session_release_lkd(session);
2814 }
2815 } else if (ctx->eptimerfd != -1) {
2816 /*
2817 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2818 * it so that it does not set EPOLLIN in the next epoll_wait().
2819 */
2820 uint64_t count;
2821
2822 /* Check the result from read() to suppress the warning on
2823 * systems that declare read() with warn_unused_result. */
2824 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2825 /* do nothing */;
2826 }
2827 }
2828 }
2829 /* And update eptimerfd as to when to next trigger */
2830 coap_ticks(&now);
2831 coap_io_prepare_epoll_lkd(ctx, now);
2832#endif /* COAP_EPOLL_SUPPORT */
2833}
2834
2835int
2837 uint8_t *msg, size_t msg_len) {
2838
2839 coap_pdu_t *pdu = NULL;
2840 coap_opt_filter_t error_opts;
2841
2842 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2843 if (msg_len < 4) {
2844 /* Minimum size of CoAP header - ignore runt */
2845 return -1;
2846 }
2847 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
2848 /*
2849 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
2850 * this MUST be silently ignored.
2851 */
2852 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
2853 return -1;
2854 }
2855
2856 /* Need max space incase PDU is updated with updated token etc. */
2857 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2858 if (!pdu)
2859 goto error;
2860
2861 coap_option_filter_clear(&error_opts);
2862 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
2864 coap_log_warn("discard malformed PDU\n");
2865 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
2866 coap_pdu_t *response =
2868 COAP_RESPONSE_CODE(402), &error_opts);
2869 if (!response) {
2870 coap_log_warn("coap_handle_dgram: cannot create error response\n");
2871 } else {
2872 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2873 coap_log_warn("coap_handle_dgram: error sending response\n");
2874 }
2876 return -1;
2877 } else {
2878 goto error;
2879 }
2880 }
2881
2882 coap_dispatch(ctx, session, pdu);
2884 return 0;
2885
2886error:
2887 /*
2888 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2889 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2890 */
2891 coap_send_rst_lkd(session, pdu);
2893 return -1;
2894}
2895
2896int
2898 coap_queue_t **node) {
2899 coap_queue_t *p, *q;
2900
2901 if (!queue || !*queue)
2902 return 0;
2903
2904 /* replace queue head if PDU's time is less than head's time */
2905
2906 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2907 *node = *queue;
2908 *queue = (*queue)->next;
2909 if (*queue) { /* adjust relative time of new queue head */
2910 (*queue)->t += (*node)->t;
2911 }
2912 (*node)->next = NULL;
2913 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2914 coap_session_str(session), id);
2915 return 1;
2916 }
2917
2918 /* search message id in queue to remove (only first occurence will be removed) */
2919 q = *queue;
2920 do {
2921 p = q;
2922 q = q->next;
2923 } while (q && (session != q->session || id != q->id));
2924
2925 if (q) { /* found message id */
2926 p->next = q->next;
2927 if (p->next) { /* must update relative time of p->next */
2928 p->next->t += q->t;
2929 }
2930 q->next = NULL;
2931 *node = q;
2932 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
2933 coap_session_str(session), id);
2934 return 1;
2935 }
2936
2937 return 0;
2938
2939}
2940
2941static int
2943 coap_bin_const_t *token, coap_queue_t **node) {
2944 coap_queue_t *p, *q;
2945
2946 if (!queue || !*queue)
2947 return 0;
2948
2949 /* replace queue head if PDU's time is less than head's time */
2950
2951 if (session == (*queue)->session &&
2952 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
2953 *node = *queue;
2954 *queue = (*queue)->next;
2955 if (*queue) { /* adjust relative time of new queue head */
2956 (*queue)->t += (*node)->t;
2957 }
2958 (*node)->next = NULL;
2959 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
2960 coap_session_str(session), (*node)->id);
2961 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2962 session->con_active--;
2963 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2964 /* Flush out any entries on session->delayqueue */
2965 coap_session_connected(session);
2966 }
2967 return 1;
2968 }
2969
2970 /* search token in queue to remove (only first occurence will be removed) */
2971 q = *queue;
2972 do {
2973 p = q;
2974 q = q->next;
2975 } while (q && (session != q->session ||
2976 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
2977
2978 if (q) { /* found token */
2979 p->next = q->next;
2980 if (p->next) { /* must update relative time of p->next */
2981 p->next->t += q->t;
2982 }
2983 q->next = NULL;
2984 *node = q;
2985 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
2986 coap_session_str(session), (*node)->id);
2987 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2988 session->con_active--;
2989 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2990 /* Flush out any entries on session->delayqueue */
2991 coap_session_connected(session);
2992 }
2993 return 1;
2994 }
2995
2996 return 0;
2997
2998}
2999
3000void
3002 coap_nack_reason_t reason) {
3003 coap_queue_t *p, *q;
3004
3005 while (context->sendqueue && context->sendqueue->session == session) {
3006 q = context->sendqueue;
3007 context->sendqueue = q->next;
3008 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3009 coap_session_str(session), q->id);
3010 if (q->pdu->type == COAP_MESSAGE_CON) {
3011 coap_handle_nack(session, q->pdu, reason, q->id);
3012 }
3014 }
3015
3016 if (!context->sendqueue)
3017 return;
3018
3019 p = context->sendqueue;
3020 q = p->next;
3021
3022 while (q) {
3023 if (q->session == session) {
3024 p->next = q->next;
3025 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3026 coap_session_str(session), q->id);
3027 if (q->pdu->type == COAP_MESSAGE_CON) {
3028 coap_handle_nack(session, q->pdu, reason, q->id);
3029 }
3031 q = p->next;
3032 } else {
3033 p = q;
3034 q = q->next;
3035 }
3036 }
3037}
3038
3039void
3041 coap_bin_const_t *token) {
3042 /* cancel all messages in sendqueue that belong to session
3043 * and use the specified token */
3044 coap_queue_t **p, *q;
3045
3046 if (!context->sendqueue)
3047 return;
3048
3049 p = &context->sendqueue;
3050 q = *p;
3051
3052 while (q) {
3053 if (q->session == session &&
3054 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3055 *p = q->next;
3056 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3057 coap_session_str(session), q->id);
3058 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3059 session->con_active--;
3060 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3061 /* Flush out any entries on session->delayqueue */
3062 coap_session_connected(session);
3063 }
3065 } else {
3066 p = &(q->next);
3067 }
3068 q = *p;
3069 }
3070}
3071
3072coap_pdu_t *
3074 coap_opt_filter_t *opts) {
3075 coap_opt_iterator_t opt_iter;
3076 coap_pdu_t *response;
3077 unsigned char type;
3078
3079#if COAP_ERROR_PHRASE_LENGTH > 0
3080 const char *phrase;
3081 if (code != COAP_RESPONSE_CODE(508)) {
3082 phrase = coap_response_phrase(code);
3083 } else {
3084 phrase = NULL;
3085 }
3086#endif
3087
3088 assert(request);
3089
3090 /* cannot send ACK if original request was not confirmable */
3091 type = request->type == COAP_MESSAGE_CON ?
3093
3094 /* Now create the response and fill with options and payload data. */
3095 response = coap_pdu_init(type, code, request->mid,
3096 request->session ?
3097 coap_session_max_pdu_size_lkd(request->session) : 512);
3098 if (response) {
3099 /* copy token */
3100 if (!coap_add_token(response, request->actual_token.length,
3101 request->actual_token.s)) {
3102 coap_log_debug("cannot add token to error response\n");
3103 coap_delete_pdu_lkd(response);
3104 return NULL;
3105 }
3106 if (response->code == COAP_RESPONSE_CODE(402)) {
3107 char buf[128];
3108 int first = 1;
3109
3110#if COAP_ERROR_PHRASE_LENGTH > 0
3111 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3112#else
3113 buf[0] = '\000';
3114#endif
3115 /* copy all options into diagnostic message */
3116 coap_option_iterator_init(request, &opt_iter, opts);
3117 while (coap_option_next(&opt_iter)) {
3118 size_t len = strlen(buf);
3119
3120 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",", opt_iter.number);
3121 first = 0;
3122 }
3123 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3124 } else if (opts && opts->mask) {
3125 coap_opt_t *option;
3126
3127 /* copy all options */
3128 coap_option_iterator_init(request, &opt_iter, opts);
3129 while ((option = coap_option_next(&opt_iter))) {
3130 coap_add_option_internal(response, opt_iter.number,
3131 coap_opt_length(option),
3132 coap_opt_value(option));
3133 }
3134#if COAP_ERROR_PHRASE_LENGTH > 0
3135 if (phrase)
3136 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3137 } else {
3138 /* note that diagnostic messages do not need a Content-Format option. */
3139 if (phrase)
3140 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3141#endif
3142 }
3143 }
3144
3145 return response;
3146}
3147
3148#if COAP_SERVER_SUPPORT
3149#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3150
3151static void
3152free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3153 coap_delete_string(app_ptr);
3154}
3155
3156/*
3157 * Caution: As this handler is in libcoap space, it is called with
3158 * context locked.
3159 */
3160static void
3161hnd_get_wellknown_lkd(coap_resource_t *resource,
3162 coap_session_t *session,
3163 const coap_pdu_t *request,
3164 const coap_string_t *query,
3165 coap_pdu_t *response) {
3166 size_t len = 0;
3167 coap_string_t *data_string = NULL;
3168 coap_print_status_t result = 0;
3169 size_t wkc_len = 0;
3170 uint8_t buf[4];
3171
3172 /*
3173 * Quick hack to determine the size of the resource descriptions for
3174 * .well-known/core.
3175 */
3176 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3177 if (result & COAP_PRINT_STATUS_ERROR) {
3178 coap_log_warn("cannot determine length of /.well-known/core\n");
3179 goto error;
3180 }
3181
3182 if (wkc_len > 0) {
3183 data_string = coap_new_string(wkc_len);
3184 if (!data_string)
3185 goto error;
3186
3187 len = wkc_len;
3188 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3189 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3190 coap_log_debug("coap_print_wellknown failed\n");
3191 goto error;
3192 }
3193 assert(len <= (size_t)wkc_len);
3194 data_string->length = len;
3195
3196 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3198 coap_encode_var_safe(buf, sizeof(buf),
3200 goto error;
3201 }
3202 if (response->used_size + len + 1 > response->max_size) {
3203 /*
3204 * Data does not fit into a packet and no libcoap block support
3205 * +1 for end of options marker
3206 */
3207 coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
3208 len, response->max_size - response->used_size - 1);
3209 len = response->max_size - response->used_size - 1;
3210 }
3211 if (!coap_add_data(response, len, data_string->s)) {
3212 goto error;
3213 }
3214 free_wellknown_response(session, data_string);
3215 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3216 response, query,
3218 -1, 0, data_string->length,
3219 data_string->s,
3220 free_wellknown_response,
3221 data_string)) {
3222 goto error_released;
3223 }
3224 } else {
3226 coap_encode_var_safe(buf, sizeof(buf),
3228 goto error;
3229 }
3230 }
3231 response->code = COAP_RESPONSE_CODE(205);
3232 return;
3233
3234error:
3235 free_wellknown_response(session, data_string);
3236error_released:
3237 if (response->code == 0) {
3238 /* set error code 5.03 and remove all options and data from response */
3239 response->code = COAP_RESPONSE_CODE(503);
3240 response->used_size = response->e_token_length;
3241 response->data = NULL;
3242 }
3243}
3244#endif /* COAP_SERVER_SUPPORT */
3245
3256static int
3258 int num_cancelled = 0; /* the number of observers cancelled */
3259
3260#ifndef COAP_SERVER_SUPPORT
3261 (void)sent;
3262#endif /* ! COAP_SERVER_SUPPORT */
3263 (void)context;
3264
3265#if COAP_SERVER_SUPPORT
3266 /* remove observer for this resource, if any
3267 * Use token from sent and try to find a matching resource. Uh!
3268 */
3269 RESOURCES_ITER(context->resources, r) {
3270 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3271 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3272 }
3273#endif /* COAP_SERVER_SUPPORT */
3274
3275 return num_cancelled;
3276}
3277
3278#if COAP_SERVER_SUPPORT
3283enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3284
3285/*
3286 * Checks for No-Response option in given @p request and
3287 * returns @c RESPONSE_DROP if @p response should be suppressed
3288 * according to RFC 7967.
3289 *
3290 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3291 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3292 * on retrying.
3293 *
3294 * Checks if the response code is 0.00 and if either the session is reliable or
3295 * non-confirmable, @c RESPONSE_DROP is also returned.
3296 *
3297 * Multicast response checking is also carried out.
3298 *
3299 * NOTE: It is the responsibility of the application to determine whether
3300 * a delayed separate response should be sent as the original requesting packet
3301 * containing the No-Response option has long since gone.
3302 *
3303 * The value of the No-Response option is encoded as
3304 * follows:
3305 *
3306 * @verbatim
3307 * +-------+-----------------------+-----------------------------------+
3308 * | Value | Binary Representation | Description |
3309 * +-------+-----------------------+-----------------------------------+
3310 * | 0 | <empty> | Interested in all responses. |
3311 * +-------+-----------------------+-----------------------------------+
3312 * | 2 | 00000010 | Not interested in 2.xx responses. |
3313 * +-------+-----------------------+-----------------------------------+
3314 * | 8 | 00001000 | Not interested in 4.xx responses. |
3315 * +-------+-----------------------+-----------------------------------+
3316 * | 16 | 00010000 | Not interested in 5.xx responses. |
3317 * +-------+-----------------------+-----------------------------------+
3318 * @endverbatim
3319 *
3320 * @param request The CoAP request to check for the No-Response option.
3321 * This parameter must not be NULL.
3322 * @param response The response that is potentially suppressed.
3323 * This parameter must not be NULL.
3324 * @param session The session this request/response are associated with.
3325 * This parameter must not be NULL.
3326 * @return RESPONSE_DEFAULT when no special treatment is requested,
3327 * RESPONSE_DROP when the response must be discarded, or
3328 * RESPONSE_SEND when the response must be sent.
3329 */
3330static enum respond_t
3331no_response(coap_pdu_t *request, coap_pdu_t *response,
3332 coap_session_t *session, coap_resource_t *resource) {
3333 coap_opt_t *nores;
3334 coap_opt_iterator_t opt_iter;
3335 unsigned int val = 0;
3336
3337 assert(request);
3338 assert(response);
3339
3340 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3341 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3342
3343 if (nores) {
3345
3346 /* The response should be dropped when the bit corresponding to
3347 * the response class is set (cf. table in function
3348 * documentation). When a No-Response option is present and the
3349 * bit is not set, the sender explicitly indicates interest in
3350 * this response. */
3351 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3352 /* Should be dropping the response */
3353 if (response->type == COAP_MESSAGE_ACK &&
3354 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3355 /* Still need to ACK the request */
3356 response->code = 0;
3357 /* Remove token/data from piggybacked acknowledgment PDU */
3358 response->actual_token.length = 0;
3359 response->e_token_length = 0;
3360 response->used_size = 0;
3361 response->data = NULL;
3362 return RESPONSE_SEND;
3363 } else {
3364 return RESPONSE_DROP;
3365 }
3366 } else {
3367 /* True for mcast as well RFC7967 2.1 */
3368 return RESPONSE_SEND;
3369 }
3370 } else if (resource && session->context->mcast_per_resource &&
3371 coap_is_mcast(&session->addr_info.local)) {
3372 /* Handle any mcast suppression specifics if no NoResponse option */
3373 if ((resource->flags &
3375 COAP_RESPONSE_CLASS(response->code) == 2) {
3376 return RESPONSE_DROP;
3377 } else if ((resource->flags &
3379 response->code == COAP_RESPONSE_CODE(205)) {
3380 if (response->data == NULL)
3381 return RESPONSE_DROP;
3382 } else if ((resource->flags &
3384 COAP_RESPONSE_CLASS(response->code) == 4) {
3385 return RESPONSE_DROP;
3386 } else if ((resource->flags &
3388 COAP_RESPONSE_CLASS(response->code) == 5) {
3389 return RESPONSE_DROP;
3390 }
3391 }
3392 } else if (COAP_PDU_IS_EMPTY(response) &&
3393 (response->type == COAP_MESSAGE_NON ||
3394 COAP_PROTO_RELIABLE(session->proto))) {
3395 /* response is 0.00, and this is reliable or non-confirmable */
3396 return RESPONSE_DROP;
3397 }
3398
3399 /*
3400 * Do not send error responses for requests that were received via
3401 * IP multicast. RFC7252 8.1
3402 */
3403
3404 if (coap_is_mcast(&session->addr_info.local)) {
3405 if (request->type == COAP_MESSAGE_NON &&
3406 response->type == COAP_MESSAGE_RST)
3407 return RESPONSE_DROP;
3408
3409 if ((!resource || session->context->mcast_per_resource == 0) &&
3410 COAP_RESPONSE_CLASS(response->code) > 2)
3411 return RESPONSE_DROP;
3412 }
3413
3414 /* Default behavior applies when we are not dealing with a response
3415 * (class == 0) or the request did not contain a No-Response option.
3416 */
3417 return RESPONSE_DEFAULT;
3418}
3419
3420static coap_str_const_t coap_default_uri_wellknown = {
3422 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3423};
3424
3425/* Initialized in coap_startup() */
3426static coap_resource_t resource_uri_wellknown;
3427
3428static void
3429handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3430 coap_pdu_t *orig_pdu) {
3431 coap_method_handler_t h = NULL;
3432 coap_pdu_t *response = NULL;
3433 coap_opt_filter_t opt_filter;
3434 coap_resource_t *resource = NULL;
3435 /* The respond field indicates whether a response must be treated
3436 * specially due to a No-Response option that declares disinterest
3437 * or interest in a specific response class. DEFAULT indicates that
3438 * No-Response has not been specified. */
3439 enum respond_t respond = RESPONSE_DEFAULT;
3440 coap_opt_iterator_t opt_iter;
3441 coap_opt_t *opt;
3442 int is_proxy_uri = 0;
3443 int is_proxy_scheme = 0;
3444 int skip_hop_limit_check = 0;
3445 int resp = 0;
3446 int send_early_empty_ack = 0;
3447 coap_string_t *query = NULL;
3448 coap_opt_t *observe = NULL;
3449 coap_string_t *uri_path = NULL;
3450 int observe_action = COAP_OBSERVE_CANCEL;
3451 coap_block_b_t block;
3452 int added_block = 0;
3453 coap_lg_srcv_t *free_lg_srcv = NULL;
3454#if COAP_Q_BLOCK_SUPPORT
3455 int lg_xmit_ctrl = 0;
3456#endif /* COAP_Q_BLOCK_SUPPORT */
3457#if COAP_ASYNC_SUPPORT
3458 coap_async_t *async;
3459#endif /* COAP_ASYNC_SUPPORT */
3460
3461 if (coap_is_mcast(&session->addr_info.local)) {
3462 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
3463 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
3464 return;
3465 }
3466 }
3467#if COAP_ASYNC_SUPPORT
3468 async = coap_find_async_lkd(session, pdu->actual_token);
3469 if (async) {
3470 coap_tick_t now;
3471
3472 coap_ticks(&now);
3473 if (async->delay == 0 || async->delay > now) {
3474 /* re-transmit missing ACK (only if CON) */
3475 coap_log_info("Retransmit async response\n");
3476 coap_send_ack_lkd(session, pdu);
3477 /* and do not pass on to the upper layers */
3478 return;
3479 }
3480 }
3481#endif /* COAP_ASYNC_SUPPORT */
3482
3483 coap_option_filter_clear(&opt_filter);
3484 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3485 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3486 if (opt) {
3487 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3488 if (!opt) {
3489 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3490 resp = 402;
3491 goto fail_response;
3492 }
3493 is_proxy_scheme = 1;
3494 }
3495
3496 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3497 if (opt)
3498 is_proxy_uri = 1;
3499 }
3500
3501 if (is_proxy_scheme || is_proxy_uri) {
3502 coap_uri_t uri;
3503
3504 if (!context->proxy_uri_resource) {
3505 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3506 coap_log_debug("Proxy-%s support not configured\n",
3507 is_proxy_scheme ? "Scheme" : "Uri");
3508 resp = 505;
3509 goto fail_response;
3510 }
3511 if (((size_t)pdu->code - 1 <
3512 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3513 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3514 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3515 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3516 is_proxy_scheme ? "Scheme" : "Uri",
3517 pdu->code/100, pdu->code%100);
3518 resp = 505;
3519 goto fail_response;
3520 }
3521
3522 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3523 if (is_proxy_uri) {
3525 coap_opt_length(opt), &uri) < 0) {
3526 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3527 coap_log_debug("Proxy-URI not decodable\n");
3528 resp = 505;
3529 goto fail_response;
3530 }
3531 } else {
3532 memset(&uri, 0, sizeof(uri));
3533 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3534 if (opt) {
3535 uri.host.length = coap_opt_length(opt);
3536 uri.host.s = coap_opt_value(opt);
3537 } else
3538 uri.host.length = 0;
3539 }
3540
3541 resource = context->proxy_uri_resource;
3542 if (uri.host.length && resource->proxy_name_count &&
3543 resource->proxy_name_list) {
3544 size_t i;
3545
3546 if (resource->proxy_name_count == 1 &&
3547 resource->proxy_name_list[0]->length == 0) {
3548 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3549 i = 0;
3550 } else {
3551 for (i = 0; i < resource->proxy_name_count; i++) {
3552 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3553 break;
3554 }
3555 }
3556 }
3557 if (i != resource->proxy_name_count) {
3558 /* This server is hosting the proxy connection endpoint */
3559 if (pdu->crit_opt) {
3560 /* Cannot handle critical option */
3561 pdu->crit_opt = 0;
3562 resp = 402;
3563 goto fail_response;
3564 }
3565 is_proxy_uri = 0;
3566 is_proxy_scheme = 0;
3567 skip_hop_limit_check = 1;
3568 }
3569 }
3570 resource = NULL;
3571 }
3572
3573 if (!skip_hop_limit_check) {
3574 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3575 if (opt) {
3576 size_t hop_limit;
3577 uint8_t buf[4];
3578
3579 hop_limit =
3581 if (hop_limit == 1) {
3582 /* coap_send_internal() will fill in the IP address for us */
3583 resp = 508;
3584 goto fail_response;
3585 } else if (hop_limit < 1 || hop_limit > 255) {
3586 /* Need to return a 4.00 RFC8768 Section 3 */
3587 coap_log_info("Invalid Hop Limit\n");
3588 resp = 400;
3589 goto fail_response;
3590 }
3591 hop_limit--;
3593 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3594 buf);
3595 }
3596 }
3597
3598 uri_path = coap_get_uri_path(pdu);
3599 if (!uri_path)
3600 return;
3601
3602 if (!is_proxy_uri && !is_proxy_scheme) {
3603 /* try to find the resource from the request URI */
3604 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3605 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3606 }
3607
3608 if ((resource == NULL) || (resource->is_unknown == 1) ||
3609 (resource->is_proxy_uri == 1)) {
3610 /* The resource was not found or there is an unexpected match against the
3611 * resource defined for handling unknown or proxy URIs.
3612 */
3613 if (resource != NULL)
3614 /* Close down unexpected match */
3615 resource = NULL;
3616 /*
3617 * Check if the request URI happens to be the well-known URI, or if the
3618 * unknown resource handler is defined, a PUT or optionally other methods,
3619 * if configured, for the unknown handler.
3620 *
3621 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3622 * proxy URI handler.
3623 *
3624 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3625 * set, call the unknown URI handler with any unknown URI (including
3626 * .well-known/core) if the appropriate method is defined.
3627 *
3628 * else if well-known URI generate a default response.
3629 *
3630 * else if unknown URI handler defined, call the unknown
3631 * URI handler (to allow for potential generation of resource
3632 * [RFC7272 5.8.3]) if the appropriate method is defined.
3633 *
3634 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3635 *
3636 * else return 4.04.
3637 */
3638
3639 if (is_proxy_uri || is_proxy_scheme) {
3640 resource = context->proxy_uri_resource;
3641 } else if (context->unknown_resource != NULL &&
3643 ((size_t)pdu->code - 1 <
3644 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3645 (context->unknown_resource->handler[pdu->code - 1])) {
3646 resource = context->unknown_resource;
3647 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
3648 /* request for .well-known/core */
3649 resource = &resource_uri_wellknown;
3650 } else if ((context->unknown_resource != NULL) &&
3651 ((size_t)pdu->code - 1 <
3652 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
3653 (context->unknown_resource->handler[pdu->code - 1])) {
3654 /*
3655 * The unknown_resource can be used to handle undefined resources
3656 * for a PUT request and can support any other registered handler
3657 * defined for it
3658 * Example set up code:-
3659 * r = coap_resource_unknown_init(hnd_put_unknown);
3660 * coap_register_request_handler(r, COAP_REQUEST_POST,
3661 * hnd_post_unknown);
3662 * coap_register_request_handler(r, COAP_REQUEST_GET,
3663 * hnd_get_unknown);
3664 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
3665 * hnd_delete_unknown);
3666 * coap_add_resource(ctx, r);
3667 *
3668 * Note: It is not possible to observe the unknown_resource, a separate
3669 * resource must be created (by PUT or POST) which has a GET
3670 * handler to be observed
3671 */
3672 resource = context->unknown_resource;
3673 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
3674 /*
3675 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
3676 */
3677 coap_log_debug("request for unknown resource '%*.*s',"
3678 " return 2.02\n",
3679 (int)uri_path->length,
3680 (int)uri_path->length,
3681 uri_path->s);
3682 resp = 202;
3683 goto fail_response;
3684 } else { /* request for any another resource, return 4.04 */
3685
3686 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3687 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3688 resp = 404;
3689 goto fail_response;
3690 }
3691
3692 }
3693
3694#if COAP_OSCORE_SUPPORT
3695 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3696 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3697 (int)uri_path->length, (int)uri_path->length, uri_path->s);
3698 resp = 401;
3699 goto fail_response;
3700 }
3701#endif /* COAP_OSCORE_SUPPORT */
3702 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3703 /* Check for existing resource and If-Non-Match */
3704 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3705 if (opt) {
3706 resp = 412;
3707 goto fail_response;
3708 }
3709 }
3710
3711 /* the resource was found, check if there is a registered handler */
3712 if ((size_t)pdu->code - 1 <
3713 sizeof(resource->handler) / sizeof(coap_method_handler_t))
3714 h = resource->handler[pdu->code - 1];
3715
3716 if (h == NULL) {
3717 resp = 405;
3718 goto fail_response;
3719 }
3720 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3721 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3722 if (opt == NULL) {
3723 /* RFC 8132 2.3.1 */
3724 resp = 415;
3725 goto fail_response;
3726 }
3727 }
3728 if (context->mcast_per_resource &&
3729 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3730 coap_is_mcast(&session->addr_info.local)) {
3731 resp = 405;
3732 goto fail_response;
3733 }
3734
3735 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3737 0, pdu->mid, coap_session_max_pdu_size_lkd(session));
3738 if (!response) {
3739 coap_log_err("could not create response PDU\n");
3740 resp = 500;
3741 goto fail_response;
3742 }
3743 response->session = session;
3744#if COAP_ASYNC_SUPPORT
3745 /* If handling a separate response, need CON, not ACK response */
3746 if (async && pdu->type == COAP_MESSAGE_CON)
3747 response->type = COAP_MESSAGE_CON;
3748#endif /* COAP_ASYNC_SUPPORT */
3749 /* A lot of the reliable code assumes type is CON */
3750 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
3751 response->type = COAP_MESSAGE_CON;
3752
3753 if (!coap_add_token(response, pdu->actual_token.length,
3754 pdu->actual_token.s)) {
3755 resp = 500;
3756 goto fail_response;
3757 }
3758
3759 query = coap_get_query(pdu);
3760
3761 /* check for Observe option RFC7641 and RFC8132 */
3762 if (resource->observable &&
3763 (pdu->code == COAP_REQUEST_CODE_GET ||
3764 pdu->code == COAP_REQUEST_CODE_FETCH)) {
3765 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3766 }
3767
3768 /*
3769 * See if blocks need to be aggregated or next requests sent off
3770 * before invoking application request handler
3771 */
3772 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3773 uint32_t block_mode = session->block_mode;
3774
3775 if (observe ||
3778 if (coap_handle_request_put_block(context, session, pdu, response,
3779 resource, uri_path, observe,
3780 &added_block, &free_lg_srcv)) {
3781 session->block_mode = block_mode;
3782 goto skip_handler;
3783 }
3784 session->block_mode = block_mode;
3785
3786 if (coap_handle_request_send_block(session, pdu, response, resource,
3787 query)) {
3788#if COAP_Q_BLOCK_SUPPORT
3789 lg_xmit_ctrl = 1;
3790#endif /* COAP_Q_BLOCK_SUPPORT */
3791 goto skip_handler;
3792 }
3793 }
3794
3795 if (observe) {
3796 observe_action =
3798 coap_opt_length(observe));
3799
3800 if (observe_action == COAP_OBSERVE_ESTABLISH) {
3801 coap_subscription_t *subscription;
3802
3803 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3804 if (block.num != 0) {
3805 response->code = COAP_RESPONSE_CODE(400);
3806 goto skip_handler;
3807 }
3808#if COAP_Q_BLOCK_SUPPORT
3809 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3810 &block)) {
3811 if (block.num != 0) {
3812 response->code = COAP_RESPONSE_CODE(400);
3813 goto skip_handler;
3814 }
3815#endif /* COAP_Q_BLOCK_SUPPORT */
3816 }
3817 subscription = coap_add_observer(resource, session, &pdu->actual_token,
3818 pdu);
3819 if (subscription) {
3820 uint8_t buf[4];
3821
3822 coap_touch_observer(context, session, &pdu->actual_token);
3824 coap_encode_var_safe(buf, sizeof(buf),
3825 resource->observe),
3826 buf);
3827 }
3828 } else if (observe_action == COAP_OBSERVE_CANCEL) {
3829 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu);
3830 } else {
3831 coap_log_info("observe: unexpected action %d\n", observe_action);
3832 }
3833 }
3834
3835 if ((resource == context->proxy_uri_resource ||
3836 (resource == context->unknown_resource &&
3837 context->unknown_resource->is_reverse_proxy)) &&
3838 COAP_PROTO_NOT_RELIABLE(session->proto) &&
3839 pdu->type == COAP_MESSAGE_CON &&
3840 !(session->block_mode & COAP_BLOCK_CACHE_RESPONSE)) {
3841 /* Make the proxy response separate and fix response later */
3842 send_early_empty_ack = 1;
3843 }
3844 if (send_early_empty_ack) {
3845 coap_send_ack_lkd(session, pdu);
3846 if (pdu->mid == session->last_con_mid) {
3847 /* request has already been processed - do not process it again */
3848 coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3849 pdu->mid);
3850 goto drop_it_no_debug;
3851 }
3852 session->last_con_mid = pdu->mid;
3853 }
3854#if COAP_WITH_OBSERVE_PERSIST
3855 /* If we are maintaining Observe persist */
3856 if (resource == context->unknown_resource) {
3857 context->unknown_pdu = pdu;
3858 context->unknown_session = session;
3859 } else
3860 context->unknown_pdu = NULL;
3861#endif /* COAP_WITH_OBSERVE_PERSIST */
3862
3863 /*
3864 * Call the request handler with everything set up
3865 */
3866 if (resource == &resource_uri_wellknown) {
3867 /* Leave context locked */
3868 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
3869 (int)resource->uri_path->length, (int)resource->uri_path->length,
3870 resource->uri_path->s);
3871 h(resource, session, pdu, query, response);
3872 } else {
3873 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3874 (int)resource->uri_path->length, (int)resource->uri_path->length,
3875 resource->uri_path->s);
3877 h(resource, session, pdu, query, response),
3878 /* context is being freed off */
3879 coap_delete_string(query); goto finish);
3880 }
3881
3882 /* Check validity of response code */
3883 if (!coap_check_code_class(session, response)) {
3884 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
3885 COAP_RESPONSE_CLASS(response->code),
3886 response->code & 0x1f);
3887 goto drop_it_no_debug;
3888 }
3889
3890 /* Check if lg_xmit generated and update PDU code if so */
3891 coap_check_code_lg_xmit(session, pdu, response, resource, query);
3892
3893 if (free_lg_srcv) {
3894 /* Check to see if the server is doing a 4.01 + Echo response */
3895 if (response->code == COAP_RESPONSE_CODE(401) &&
3896 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3897 /* Need to keep lg_srcv around for client's response */
3898 } else {
3899 LL_DELETE(session->lg_srcv, free_lg_srcv);
3900 coap_block_delete_lg_srcv(session, free_lg_srcv);
3901 }
3902 }
3903 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
3904 /* Just in case, as there are more to go */
3905 response->code = COAP_RESPONSE_CODE(231);
3906 }
3907
3908skip_handler:
3909 if (send_early_empty_ack &&
3910 response->type == COAP_MESSAGE_ACK) {
3911 /* Response is now separate - convert to CON as needed */
3912 response->type = COAP_MESSAGE_CON;
3913 /* Check for empty ACK - need to drop as already sent */
3914 if (response->code == 0) {
3915 goto drop_it_no_debug;
3916 }
3917 }
3918 respond = no_response(pdu, response, session, resource);
3919 if (respond != RESPONSE_DROP) {
3920#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
3921 coap_mid_t mid = pdu->mid;
3922#endif
3923 if (COAP_RESPONSE_CLASS(response->code) != 2) {
3924 if (observe) {
3926 }
3927 }
3928 if (COAP_RESPONSE_CLASS(response->code) > 2) {
3929 if (observe)
3930 coap_delete_observer(resource, session, &pdu->actual_token);
3931 if (response->code != COAP_RESPONSE_CODE(413))
3933 }
3934
3935 /* If original request contained a token, and the registered
3936 * application handler made no changes to the response, then
3937 * this is an empty ACK with a token, which is a malformed
3938 * PDU */
3939 if ((response->type == COAP_MESSAGE_ACK)
3940 && (response->code == 0)) {
3941 /* Remove token from otherwise-empty acknowledgment PDU */
3942 response->actual_token.length = 0;
3943 response->e_token_length = 0;
3944 response->used_size = 0;
3945 response->data = NULL;
3946 }
3947
3948 if (!coap_is_mcast(&session->addr_info.local) ||
3949 (context->mcast_per_resource &&
3950 resource &&
3952 /* No delays to response */
3953#if COAP_Q_BLOCK_SUPPORT
3954 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
3955 !lg_xmit_ctrl && response->code == COAP_RESPONSE_CODE(205) &&
3956 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
3957 block.m) {
3958 if (coap_send_q_block2(session, resource, query, pdu->code, block,
3959 response,
3960 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
3961 coap_log_debug("cannot send response for mid=0x%x\n", mid);
3962 response = NULL;
3963 if (query)
3964 coap_delete_string(query);
3965 goto finish;
3966 }
3967#endif /* COAP_Q_BLOCK_SUPPORT */
3968 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
3969 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
3970 if (query)
3971 coap_delete_string(query);
3972 goto finish;
3973 }
3974 } else {
3975 /* Need to delay mcast response */
3976 coap_queue_t *node = coap_new_node();
3977 uint8_t r;
3978 coap_tick_t delay;
3979
3980 if (!node) {
3981 coap_log_debug("mcast delay: insufficient memory\n");
3982 goto drop_it_no_debug;
3983 }
3984 if (!coap_pdu_encode_header(response, session->proto)) {
3986 goto drop_it_no_debug;
3987 }
3988
3989 node->id = response->mid;
3990 node->pdu = response;
3991 node->is_mcast = 1;
3992 coap_prng_lkd(&r, sizeof(r));
3993 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
3994 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
3995 coap_session_str(session),
3996 response->mid,
3997 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
3998 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
3999 1000 / COAP_TICKS_PER_SECOND));
4000 node->timeout = (unsigned int)delay;
4001 /* Use this to delay transmission */
4002 coap_wait_ack(session->context, session, node);
4003 }
4004 } else {
4005 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4006 coap_session_str(session),
4007 response->mid);
4008 coap_show_pdu(COAP_LOG_DEBUG, response);
4009drop_it_no_debug:
4010 coap_delete_pdu_lkd(response);
4011 }
4012 if (query)
4013 coap_delete_string(query);
4014#if COAP_Q_BLOCK_SUPPORT
4015 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4016 if (COAP_PROTO_RELIABLE(session->proto)) {
4017 if (block.m) {
4018 /* All of the sequence not in yet */
4019 goto finish;
4020 }
4021 } else if (pdu->type == COAP_MESSAGE_NON) {
4022 /* More to go and not at a payload break */
4023 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4024 goto finish;
4025 }
4026 }
4027 }
4028#endif /* COAP_Q_BLOCK_SUPPORT */
4029
4030finish:
4031 coap_delete_string(uri_path);
4032 return;
4033
4034fail_response:
4035 coap_delete_pdu_lkd(response);
4036 response =
4038 &opt_filter);
4039 if (response)
4040 goto skip_handler;
4041 coap_delete_string(uri_path);
4042}
4043#endif /* COAP_SERVER_SUPPORT */
4044
4045#if COAP_CLIENT_SUPPORT
4046/* Call application-specific response handler when available. */
4047void
4049 coap_pdu_t *sent, coap_pdu_t *rcvd,
4050 void *body_data) {
4051 coap_context_t *context = session->context;
4052 coap_response_t ret;
4053
4054#if COAP_PROXY_SUPPORT
4055 if (context->proxy_response_handler) {
4056 coap_proxy_list_t *proxy_entry;
4057 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4058 rcvd,
4059 &proxy_entry);
4060
4061 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4062 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4063 proxy_entry);
4064 return;
4065 }
4066 }
4067#endif /* COAP_PROXY_SUPPORT */
4068 if (session->doing_send_recv && session->req_token &&
4069 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4070 /* processing coap_send_recv() call */
4071 session->resp_pdu = rcvd;
4073 /* Will get freed off when PDU is freed off */
4074 rcvd->data_free = body_data;
4075 coap_send_ack_lkd(session, rcvd);
4077 return;
4078 } else if (context->response_handler) {
4079 coap_lock_callback_ret_release(ret, context,
4080 context->response_handler(session,
4081 sent,
4082 rcvd,
4083 rcvd->mid),
4084 /* context is being freed off */
4085 return);
4086 } else {
4087 ret = COAP_RESPONSE_OK;
4088 }
4089 if (ret == COAP_RESPONSE_FAIL && rcvd->type != COAP_MESSAGE_ACK) {
4090 coap_send_rst_lkd(session, rcvd);
4092 } else {
4093 coap_send_ack_lkd(session, rcvd);
4095 }
4096 coap_free_type(COAP_STRING, body_data);
4097}
4098
4099static void
4100handle_response(coap_context_t *context, coap_session_t *session,
4101 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4102
4103 /* Set in case there is a later call to coap_update_token() */
4104 rcvd->session = session;
4105
4106 /* Check for message duplication */
4107 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4108 if (rcvd->type == COAP_MESSAGE_CON) {
4109 if (rcvd->mid == session->last_con_mid) {
4110 /* Duplicate response: send ACK/RST, but don't process */
4111 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4112 coap_send_ack_lkd(session, rcvd);
4113 else
4114 coap_send_rst_lkd(session, rcvd);
4115 return;
4116 }
4117 session->last_con_mid = rcvd->mid;
4118 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4119 if (rcvd->mid == session->last_ack_mid) {
4120 /* Duplicate response */
4121 return;
4122 }
4123 session->last_ack_mid = rcvd->mid;
4124 }
4125 }
4126 /* Check to see if checking out extended token support */
4127 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4128 session->remote_test_mid == rcvd->mid) {
4129
4130 if (rcvd->actual_token.length != session->max_token_size ||
4131 rcvd->code == COAP_RESPONSE_CODE(400) ||
4132 rcvd->code == COAP_RESPONSE_CODE(503)) {
4133 coap_log_debug("Extended Token requested size support not available\n");
4135 } else {
4136 coap_log_debug("Extended Token support available\n");
4137 }
4139 session->doing_first = 0;
4140 return;
4141 }
4142#if COAP_Q_BLOCK_SUPPORT
4143 /* Check to see if checking out Q-Block support */
4144 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4145 session->remote_test_mid == rcvd->mid) {
4146 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4147 coap_log_debug("Q-Block support not available\n");
4148 set_block_mode_drop_q(session->block_mode);
4149 } else {
4150 coap_block_b_t qblock;
4151
4152 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4153 coap_log_debug("Q-Block support available\n");
4154 set_block_mode_has_q(session->block_mode);
4155 } else {
4156 coap_log_debug("Q-Block support not available\n");
4157 set_block_mode_drop_q(session->block_mode);
4158 }
4159 }
4160 session->doing_first = 0;
4161 return;
4162 }
4163#endif /* COAP_Q_BLOCK_SUPPORT */
4164
4165 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4166 /* See if need to send next block to server */
4167 if (coap_handle_response_send_block(session, sent, rcvd)) {
4168 /* Next block transmitted, no need to inform app */
4169 coap_send_ack_lkd(session, rcvd);
4170 return;
4171 }
4172
4173 /* Need to see if needing to request next block */
4174 if (coap_handle_response_get_block(context, session, sent, rcvd,
4175 COAP_RECURSE_OK)) {
4176 /* Next block transmitted, ack sent no need to inform app */
4177 return;
4178 }
4179 }
4180 if (session->doing_first)
4181 session->doing_first = 0;
4182
4183 /* Call application-specific response handler when available. */
4184 coap_call_response_handler(session, sent, rcvd, NULL);
4185}
4186#endif /* COAP_CLIENT_SUPPORT */
4187
4188#if !COAP_DISABLE_TCP
4189static void
4191 coap_pdu_t *pdu) {
4192 coap_opt_iterator_t opt_iter;
4193 coap_opt_t *option;
4194 int set_mtu = 0;
4195
4196 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4197
4198 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4199 if (session->csm_not_seen) {
4200 coap_tick_t now;
4201
4202 coap_ticks(&now);
4203 /* CSM timeout before CSM seen */
4204 coap_log_warn("***%s: CSM received after CSM timeout\n",
4205 coap_session_str(session));
4206 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4207 coap_session_str(session),
4208 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4209 }
4210 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4212 }
4213 while ((option = coap_option_next(&opt_iter))) {
4216 coap_opt_length(option)));
4217 set_mtu = 1;
4218 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
4219 session->csm_block_supported = 1;
4220 } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
4221 session->max_token_size =
4223 coap_opt_length(option));
4226 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4229 }
4230 }
4231 if (set_mtu) {
4232 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4233 session->csm_bert_rem_support = 1;
4234 else
4235 session->csm_bert_rem_support = 0;
4236 }
4237 if (session->state == COAP_SESSION_STATE_CSM)
4238 coap_session_connected(session);
4239 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4241 if (context->ping_handler) {
4242 coap_lock_callback(context,
4243 context->ping_handler(session, pdu, pdu->mid));
4244 }
4245 if (pong) {
4247 coap_send_internal(session, pong, NULL);
4248 }
4249 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4250 session->last_pong = session->last_rx_tx;
4251 if (context->pong_handler) {
4252 coap_lock_callback(context,
4253 context->pong_handler(session, pdu, pdu->mid));
4254 }
4255 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4256 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4258 }
4259}
4260#endif /* !COAP_DISABLE_TCP */
4261
4262static int
4264 if (COAP_PDU_IS_REQUEST(pdu) &&
4265 pdu->actual_token.length >
4266 (session->type == COAP_SESSION_TYPE_CLIENT ?
4267 session->max_token_size : session->context->max_token_size)) {
4268 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4269 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4270 coap_opt_filter_t opt_filter;
4271 coap_pdu_t *response;
4272
4273 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4274 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4275 &opt_filter);
4276 if (!response) {
4277 coap_log_warn("coap_dispatch: cannot create error response\n");
4278 } else {
4279 /*
4280 * Note - have to leave in oversize token as per
4281 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4282 */
4283 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4284 coap_log_warn("coap_dispatch: error sending response\n");
4285 }
4286 } else {
4287 /* Indicate no extended token support */
4288 coap_send_rst_lkd(session, pdu);
4289 }
4290 return 0;
4291 }
4292 return 1;
4293}
4294
4295void
4297 coap_pdu_t *pdu) {
4298 coap_queue_t *sent = NULL;
4299 coap_pdu_t *response;
4300 coap_pdu_t *orig_pdu = NULL;
4301 coap_opt_filter_t opt_filter;
4302 int is_ping_rst;
4303 int packet_is_bad = 0;
4304#if COAP_OSCORE_SUPPORT
4305 coap_opt_iterator_t opt_iter;
4306 coap_pdu_t *dec_pdu = NULL;
4307#endif /* COAP_OSCORE_SUPPORT */
4308 int is_ext_token_rst;
4309
4310 pdu->session = session;
4312
4313 /* Check validity of received code */
4314 if (!coap_check_code_class(session, pdu)) {
4315 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4317 pdu->code & 0x1f);
4318 packet_is_bad = 1;
4319 if (pdu->type == COAP_MESSAGE_CON) {
4321 }
4322 /* find message id in sendqueue to stop retransmission */
4323 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4324 goto cleanup;
4325 }
4326
4327 coap_option_filter_clear(&opt_filter);
4328
4329#if COAP_SERVER_SUPPORT
4330 /* See if this a repeat request */
4331 if (COAP_PDU_IS_REQUEST(pdu) && session->cached_pdu &&
4333 coap_digest_t digest;
4334
4335 coap_pdu_cksum(pdu, &digest);
4336 if (memcmp(&digest, &session->cached_pdu_cksum, sizeof(digest)) == 0) {
4337#if COAP_OSCORE_SUPPORT
4338 uint8_t oscore_encryption = session->oscore_encryption;
4339
4340 session->oscore_encryption = 0;
4341#endif /* COAP_OSCORE_SUPPORT */
4342 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4343 cached_pdu must not be removed */
4345 coap_log_debug("Retransmit response to duplicate request\n");
4346 if (coap_send_internal(session, session->cached_pdu, NULL) != COAP_INVALID_MID) {
4347#if COAP_OSCORE_SUPPORT
4348 session->oscore_encryption = oscore_encryption;
4349#endif /* COAP_OSCORE_SUPPORT */
4350 return;
4351 }
4352#if COAP_OSCORE_SUPPORT
4353 session->oscore_encryption = oscore_encryption;
4354#endif /* COAP_OSCORE_SUPPORT */
4355 }
4356 }
4357#endif /* COAP_SERVER_SUPPORT */
4358#if COAP_OSCORE_SUPPORT
4359 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4360 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4361 if (pdu->type == COAP_MESSAGE_NON) {
4362 coap_send_rst_lkd(session, pdu);
4363 goto cleanup;
4364 } else if (pdu->type == COAP_MESSAGE_CON) {
4365 if (COAP_PDU_IS_REQUEST(pdu)) {
4366 response =
4367 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4368
4369 if (!response) {
4370 coap_log_warn("coap_dispatch: cannot create error response\n");
4371 } else {
4372 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4373 coap_log_warn("coap_dispatch: error sending response\n");
4374 }
4375 } else {
4376 coap_send_rst_lkd(session, pdu);
4377 }
4378 }
4379 goto cleanup;
4380 }
4381
4382 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4383 int decrypt = 1;
4384#if COAP_SERVER_SUPPORT
4385 coap_opt_t *opt;
4386 coap_resource_t *resource;
4387 coap_uri_t uri;
4388#endif /* COAP_SERVER_SUPPORT */
4389
4390 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4391 decrypt = 0;
4392
4393#if COAP_SERVER_SUPPORT
4394 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4395 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4396 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4397 != NULL) {
4398 /* Need to check whether this is a direct or proxy session */
4399 memset(&uri, 0, sizeof(uri));
4400 uri.host.length = coap_opt_length(opt);
4401 uri.host.s = coap_opt_value(opt);
4402 resource = context->proxy_uri_resource;
4403 if (uri.host.length && resource && resource->proxy_name_count &&
4404 resource->proxy_name_list) {
4405 size_t i;
4406 for (i = 0; i < resource->proxy_name_count; i++) {
4407 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4408 break;
4409 }
4410 }
4411 if (i == resource->proxy_name_count) {
4412 /* This server is not hosting the proxy connection endpoint */
4413 decrypt = 0;
4414 }
4415 }
4416 }
4417#endif /* COAP_SERVER_SUPPORT */
4418 if (decrypt) {
4419 /* find message id in sendqueue to stop retransmission and get sent */
4420 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4421 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4422 orig_pdu = pdu;
4423 coap_pdu_reference_lkd(orig_pdu);
4424 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4425 if (session->recipient_ctx == NULL ||
4426 session->recipient_ctx->initial_state == 0) {
4427 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4428 }
4430 coap_delete_pdu_lkd(orig_pdu);
4431 return;
4432 } else {
4433 session->oscore_encryption = 1;
4434 pdu = dec_pdu;
4435 }
4436 coap_log_debug("Decrypted PDU\n");
4438 }
4439 }
4440#endif /* COAP_OSCORE_SUPPORT */
4441
4442 switch (pdu->type) {
4443 case COAP_MESSAGE_ACK:
4444 /* find message id in sendqueue to stop retransmission */
4445 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4446
4447 if (sent && session->con_active) {
4448 session->con_active--;
4449 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4450 /* Flush out any entries on session->delayqueue */
4451 coap_session_connected(session);
4452 }
4453 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4454 packet_is_bad = 1;
4455 goto cleanup;
4456 }
4457
4458#if COAP_SERVER_SUPPORT
4459 /* if sent code was >= 64 the message might have been a
4460 * notification. Then, we must flag the observer to be alive
4461 * by setting obs->fail_cnt = 0. */
4462 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
4463 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
4464 }
4465#endif /* COAP_SERVER_SUPPORT */
4466
4467 if (pdu->code == 0) {
4468#if COAP_Q_BLOCK_SUPPORT
4469 if (sent) {
4470 coap_block_b_t block;
4471
4472 if (sent->pdu->type == COAP_MESSAGE_CON &&
4473 COAP_PROTO_NOT_RELIABLE(session->proto) &&
4474 coap_get_block_b(session, sent->pdu,
4475 COAP_PDU_IS_REQUEST(sent->pdu) ?
4477 &block)) {
4478 if (block.m) {
4479#if COAP_CLIENT_SUPPORT
4480 if (COAP_PDU_IS_REQUEST(sent->pdu))
4481 coap_send_q_block1(session, block, sent->pdu,
4482 COAP_SEND_SKIP_PDU);
4483#endif /* COAP_CLIENT_SUPPORT */
4484 if (COAP_PDU_IS_RESPONSE(sent->pdu))
4485 coap_send_q_blocks(session, sent->pdu->lg_xmit, block,
4486 sent->pdu, COAP_SEND_SKIP_PDU);
4487 }
4488 }
4489 }
4490#endif /* COAP_Q_BLOCK_SUPPORT */
4491#if COAP_CLIENT_SUPPORT
4492 /*
4493 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
4494 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
4495 * response if the response was piggy-backed. Here, a separate response
4496 * detected and so the lg_crcv needs to be set up before the sent PDU
4497 * information is lost.
4498 *
4499 * lg_crcv was not set up if not a CoAP request.
4500 *
4501 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
4502 * options.
4503 */
4504 if (sent &&
4505 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
4506 COAP_PDU_IS_REQUEST(sent->pdu)) {
4507 /*
4508 * lg_crcv was not set up in coap_send(). It could have been set up
4509 * the first separate response.
4510 * See if there already is a lg_crcv set up.
4511 */
4512 coap_lg_crcv_t *lg_crcv;
4513 uint64_t token_match =
4515 sent->pdu->actual_token.length));
4516
4517 LL_FOREACH(session->lg_crcv, lg_crcv) {
4518 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
4519 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
4520 break;
4521 }
4522 }
4523 if (!lg_crcv) {
4524 /*
4525 * Need to set up a lg_crcv as it was not set up in coap_send()
4526 * to save time, but server has not sent back a piggy-back response.
4527 */
4528 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
4529 if (lg_crcv) {
4530 LL_PREPEND(session->lg_crcv, lg_crcv);
4531 }
4532 }
4533 }
4534#endif /* COAP_CLIENT_SUPPORT */
4535 /* an empty ACK needs no further handling */
4536 goto cleanup;
4537 } else if (COAP_PDU_IS_REQUEST(pdu)) {
4538 /* This is not legitimate - Request using ACK - ignore */
4539 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
4541 pdu->code & 0x1f);
4542 packet_is_bad = 1;
4543 goto cleanup;
4544 }
4545
4546 break;
4547
4548 case COAP_MESSAGE_RST:
4549 /* We have sent something the receiver disliked, so we remove
4550 * not only the message id but also the subscriptions we might
4551 * have. */
4552 is_ping_rst = 0;
4553 if (pdu->mid == session->last_ping_mid &&
4554 context->ping_timeout && session->last_ping > 0)
4555 is_ping_rst = 1;
4556
4557#if COAP_Q_BLOCK_SUPPORT
4558 /* Check to see if checking out Q-Block support */
4559 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
4560 session->remote_test_mid == pdu->mid) {
4561 coap_log_debug("Q-Block support not available\n");
4562 set_block_mode_drop_q(session->block_mode);
4563 }
4564#endif /* COAP_Q_BLOCK_SUPPORT */
4565
4566 /* Check to see if checking out extended token support */
4567 is_ext_token_rst = 0;
4568 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4569 session->remote_test_mid == pdu->mid) {
4570 coap_log_debug("Extended Token support not available\n");
4573 session->doing_first = 0;
4574 is_ext_token_rst = 1;
4575 }
4576
4577 if (!is_ping_rst && !is_ext_token_rst)
4578 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
4579
4580 if (session->con_active) {
4581 session->con_active--;
4582 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4583 /* Flush out any entries on session->delayqueue */
4584 coap_session_connected(session);
4585 }
4586
4587 /* find message id in sendqueue to stop retransmission */
4588 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
4589
4590 if (sent) {
4591 if (!is_ping_rst)
4592 coap_cancel(context, sent);
4593
4594 if (!is_ping_rst && !is_ext_token_rst) {
4595 if (sent->pdu->type==COAP_MESSAGE_CON) {
4596 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
4597 }
4598 } else if (is_ping_rst) {
4599 if (context->pong_handler) {
4600 coap_lock_callback(context,
4601 context->pong_handler(session, pdu, pdu->mid));
4602 }
4603 session->last_pong = session->last_rx_tx;
4605 }
4606 } else {
4607#if COAP_SERVER_SUPPORT
4608 /* Need to check is there is a subscription active and delete it */
4609 RESOURCES_ITER(context->resources, r) {
4610 coap_subscription_t *obs, *tmp;
4611 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
4612 if (obs->pdu->mid == pdu->mid && obs->session == session) {
4613 /* Need to do this now as session may get de-referenced */
4615 coap_delete_observer(r, session, &obs->pdu->actual_token);
4616 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4617 coap_session_release_lkd(session);
4618 goto cleanup;
4619 }
4620 }
4621 }
4622#endif /* COAP_SERVER_SUPPORT */
4623 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
4624 }
4625 goto cleanup;
4626
4627 case COAP_MESSAGE_NON:
4628 /* check for unknown critical options */
4629 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4630 packet_is_bad = 1;
4631 coap_send_rst_lkd(session, pdu);
4632 goto cleanup;
4633 }
4634 if (!check_token_size(session, pdu)) {
4635 goto cleanup;
4636 }
4637 break;
4638
4639 case COAP_MESSAGE_CON: /* check for unknown critical options */
4640 /* In a lossy context, the ACK of a separate response may have
4641 * been lost, so we need to stop retransmitting requests with the
4642 * same token. Matching on token potentially containing ext length bytes.
4643 */
4644 /* find message token in sendqueue to stop retransmission */
4645 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
4646
4647 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4648 coap_option_check_critical(session, pdu, &opt_filter) == 0) {
4649 packet_is_bad = 1;
4650 if (COAP_PDU_IS_REQUEST(pdu)) {
4651 response =
4652 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4653
4654 if (!response) {
4655 coap_log_warn("coap_dispatch: cannot create error response\n");
4656 } else {
4657 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4658 coap_log_warn("coap_dispatch: error sending response\n");
4659 }
4660 } else {
4661 coap_send_rst_lkd(session, pdu);
4662 }
4663 goto cleanup;
4664 }
4665 if (!check_token_size(session, pdu)) {
4666 goto cleanup;
4667 }
4668 break;
4669 default:
4670 break;
4671 }
4672
4673 /* Pass message to upper layer if a specific handler was
4674 * registered for a request that should be handled locally. */
4675#if !COAP_DISABLE_TCP
4676 if (COAP_PDU_IS_SIGNALING(pdu))
4677 handle_signaling(context, session, pdu);
4678 else
4679#endif /* !COAP_DISABLE_TCP */
4680#if COAP_SERVER_SUPPORT
4681 if (COAP_PDU_IS_REQUEST(pdu))
4682 handle_request(context, session, pdu, orig_pdu);
4683 else
4684#endif /* COAP_SERVER_SUPPORT */
4685#if COAP_CLIENT_SUPPORT
4686 if (COAP_PDU_IS_RESPONSE(pdu))
4687 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
4688 else
4689#endif /* COAP_CLIENT_SUPPORT */
4690 {
4691 if (COAP_PDU_IS_EMPTY(pdu)) {
4692 if (context->ping_handler) {
4693 coap_lock_callback(context,
4694 context->ping_handler(session, pdu, pdu->mid));
4695 }
4696 } else {
4697 packet_is_bad = 1;
4698 }
4699 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
4701 pdu->code & 0x1f);
4702
4703 if (!coap_is_mcast(&session->addr_info.local)) {
4704 if (COAP_PDU_IS_EMPTY(pdu)) {
4705 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4706 coap_tick_t now;
4707 coap_ticks(&now);
4708 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
4710 session->last_tx_rst = now;
4711 }
4712 }
4713 } else {
4714 if (pdu->type == COAP_MESSAGE_CON)
4716 }
4717 }
4718 }
4719
4720cleanup:
4721 if (packet_is_bad) {
4722 if (sent) {
4723 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
4724 } else {
4726 }
4727 }
4728 coap_delete_pdu_lkd(orig_pdu);
4730#if COAP_OSCORE_SUPPORT
4731 coap_delete_pdu_lkd(dec_pdu);
4732#endif /* COAP_OSCORE_SUPPORT */
4733}
4734
4735#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
4736static const char *
4738 switch (event) {
4740 return "COAP_EVENT_DTLS_CLOSED";
4742 return "COAP_EVENT_DTLS_CONNECTED";
4744 return "COAP_EVENT_DTLS_RENEGOTIATE";
4746 return "COAP_EVENT_DTLS_ERROR";
4748 return "COAP_EVENT_TCP_CONNECTED";
4750 return "COAP_EVENT_TCP_CLOSED";
4752 return "COAP_EVENT_TCP_FAILED";
4754 return "COAP_EVENT_SESSION_CONNECTED";
4756 return "COAP_EVENT_SESSION_CLOSED";
4758 return "COAP_EVENT_SESSION_FAILED";
4760 return "COAP_EVENT_PARTIAL_BLOCK";
4762 return "COAP_EVENT_XMIT_BLOCK_FAIL";
4764 return "COAP_EVENT_SERVER_SESSION_NEW";
4766 return "COAP_EVENT_SERVER_SESSION_DEL";
4768 return "COAP_EVENT_BAD_PACKET";
4770 return "COAP_EVENT_MSG_RETRANSMITTED";
4772 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
4774 return "COAP_EVENT_OSCORE_NOT_ENABLED";
4776 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
4778 return "COAP_EVENT_OSCORE_NO_SECURITY";
4780 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
4782 return "COAP_EVENT_OSCORE_DECODE_ERROR";
4784 return "COAP_EVENT_WS_PACKET_SIZE";
4786 return "COAP_EVENT_WS_CONNECTED";
4788 return "COAP_EVENT_WS_CLOSED";
4790 return "COAP_EVENT_KEEPALIVE_FAILURE";
4791 default:
4792 return "???";
4793 }
4794}
4795#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
4796
4797COAP_API int
4799 coap_session_t *session) {
4800 int ret;
4801
4802 coap_lock_lock(context, return 0);
4803 ret = coap_handle_event_lkd(context, event, session);
4804 coap_lock_unlock(context);
4805 return ret;
4806}
4807
4808int
4810 coap_session_t *session) {
4811 int ret = 0;
4812
4813 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
4814
4815 if (context->handle_event) {
4816 coap_lock_callback_ret(ret, context, context->handle_event(session, event));
4817#if COAP_PROXY_SUPPORT
4818 if (event == COAP_EVENT_SERVER_SESSION_DEL)
4819 coap_proxy_remove_association(session, 0);
4820#endif /* COAP_PROXY_SUPPORT */
4821#if COAP_CLIENT_SUPPORT
4822 switch (event) {
4835 /* Those that are deemed fatal to end sending a request */
4836 session->doing_send_recv = 0;
4837 break;
4852 default:
4853 break;
4854 }
4855#endif /* COAP_CLIENT_SUPPORT */
4856 }
4857 return ret;
4858}
4859
4860COAP_API int
4862 int ret;
4863
4864 coap_lock_lock(context, return 0);
4865 ret = coap_can_exit_lkd(context);
4866 coap_lock_unlock(context);
4867 return ret;
4868}
4869
4870int
4872 coap_session_t *s, *rtmp;
4873 if (!context)
4874 return 1;
4875 coap_lock_check_locked(context);
4876 if (context->sendqueue)
4877 return 0;
4878#if COAP_SERVER_SUPPORT
4879 coap_endpoint_t *ep;
4880
4881 LL_FOREACH(context->endpoint, ep) {
4882 SESSIONS_ITER(ep->sessions, s, rtmp) {
4883 if (s->delayqueue)
4884 return 0;
4885 if (s->lg_xmit)
4886 return 0;
4887 }
4888 }
4889#endif /* COAP_SERVER_SUPPORT */
4890#if COAP_CLIENT_SUPPORT
4891 SESSIONS_ITER(context->sessions, s, rtmp) {
4892 if (s->delayqueue)
4893 return 0;
4894 if (s->lg_xmit)
4895 return 0;
4896 }
4897#endif /* COAP_CLIENT_SUPPORT */
4898 return 1;
4899}
4900#if COAP_SERVER_SUPPORT
4901#if COAP_ASYNC_SUPPORT
4902/*
4903 * Return 1 if there is a future expire time, else 0.
4904 * Update tim_rem with remaining value if return is 1.
4905 */
4906int
4907coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
4909 coap_async_t *async, *tmp;
4910 int ret = 0;
4911
4912 LL_FOREACH_SAFE(context->async_state, async, tmp) {
4913 if (async->delay != 0) {
4914 if (async->delay <= now) {
4915 /* Send off the request to the application */
4916 coap_log_debug("Async PDU presented to app.\n");
4917 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
4918 handle_request(context, async->session, async->pdu, NULL);
4919
4920 /* Remove this async entry as it has now fired */
4921 coap_free_async_lkd(async->session, async);
4922 } else {
4923 next_due = async->delay - now;
4924 ret = 1;
4925 }
4926 }
4927 }
4928 if (tim_rem)
4929 *tim_rem = next_due;
4930 return ret;
4931}
4932#endif /* COAP_ASYNC_SUPPORT */
4933#endif /* COAP_SERVER_SUPPORT */
4934
4936
4937#if COAP_THREAD_SAFE
4938/*
4939 * Global lock for multi-thread support
4940 */
4941coap_lock_t global_lock;
4942/*
4943 * low level protection mutex
4944 */
4945coap_mutex_t m_show_pdu;
4946coap_mutex_t m_log_impl;
4947coap_mutex_t m_io_threads;
4948#endif /* COAP_THREAD_SAFE */
4949
4950void
4952 coap_tick_t now;
4953#ifndef WITH_CONTIKI
4954 uint64_t us;
4955#endif /* !WITH_CONTIKI */
4956
4957 if (coap_started)
4958 return;
4959 coap_started = 1;
4960
4961#if COAP_THREAD_SAFE
4963 coap_mutex_init(&m_show_pdu);
4964 coap_mutex_init(&m_log_impl);
4965 coap_mutex_init(&m_io_threads);
4966#endif /* COAP_THREAD_SAFE */
4967
4968#if defined(HAVE_WINSOCK2_H)
4969 WORD wVersionRequested = MAKEWORD(2, 2);
4970 WSADATA wsaData;
4971 WSAStartup(wVersionRequested, &wsaData);
4972#endif
4974 coap_ticks(&now);
4975#ifndef WITH_CONTIKI
4976 us = coap_ticks_to_rt_us(now);
4977 /* Be accurate to the nearest (approx) us */
4978 coap_prng_init_lkd((unsigned int)us);
4979#else /* WITH_CONTIKI */
4980 coap_start_io_process();
4981#endif /* WITH_CONTIKI */
4984#ifdef WITH_LWIP
4985 coap_io_lwip_init();
4986#endif /* WITH_LWIP */
4987#if COAP_SERVER_SUPPORT
4988 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
4989 (const uint8_t *)".well-known/core"
4990 };
4991 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
4992 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
4993 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
4994 resource_uri_wellknown.uri_path = &well_known;
4995#endif /* COAP_SERVER_SUPPORT */
4997}
4998
4999void
5001 if (!coap_started)
5002 return;
5003 coap_started = 0;
5004#if defined(HAVE_WINSOCK2_H)
5005 WSACleanup();
5006#elif defined(WITH_CONTIKI)
5007 coap_stop_io_process();
5008#endif
5009#ifdef WITH_LWIP
5010 coap_io_lwip_cleanup();
5011#endif /* WITH_LWIP */
5013
5014#if COAP_THREAD_SAFE
5015 coap_mutex_destroy(&m_show_pdu);
5016 coap_mutex_destroy(&m_log_impl);
5017 coap_mutex_destroy(&m_io_threads);
5018#endif /* COAP_THREAD_SAFE */
5019
5021}
5022
5023void
5025 coap_response_handler_t handler) {
5026#if COAP_CLIENT_SUPPORT
5027 context->response_handler = handler;
5028#else /* ! COAP_CLIENT_SUPPORT */
5029 (void)context;
5030 (void)handler;
5031#endif /* ! COAP_CLIENT_SUPPORT */
5032}
5033
5034void
5037#if COAP_PROXY_SUPPORT
5038 context->proxy_response_handler = handler;
5039#else /* ! COAP_PROXY_SUPPORT */
5040 (void)context;
5041 (void)handler;
5042#endif /* ! COAP_PROXY_SUPPORT */
5043}
5044
5045void
5047 coap_nack_handler_t handler) {
5048 context->nack_handler = handler;
5049}
5050
5051void
5053 coap_ping_handler_t handler) {
5054 context->ping_handler = handler;
5055}
5056
5057void
5059 coap_pong_handler_t handler) {
5060 context->pong_handler = handler;
5061}
5062
5063COAP_API void
5065 coap_lock_lock(ctx, return);
5066 coap_register_option_lkd(ctx, type);
5067 coap_lock_unlock(ctx);
5068}
5069
5070void
5073}
5074
5075#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
5076#if COAP_SERVER_SUPPORT
5077COAP_API int
5078coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5079 const char *ifname) {
5080 int ret;
5081
5082 coap_lock_lock(ctx, return -1);
5083 ret = coap_join_mcast_group_intf_lkd(ctx, group_name, ifname);
5084 coap_lock_unlock(ctx);
5085 return ret;
5086}
5087
5088int
5089coap_join_mcast_group_intf_lkd(coap_context_t *ctx, const char *group_name,
5090 const char *ifname) {
5091#if COAP_IPV4_SUPPORT
5092 struct ip_mreq mreq4;
5093#endif /* COAP_IPV4_SUPPORT */
5094#if COAP_IPV6_SUPPORT
5095 struct ipv6_mreq mreq6;
5096#endif /* COAP_IPV6_SUPPORT */
5097 struct addrinfo *resmulti = NULL, hints, *ainfo;
5098 int result = -1;
5099 coap_endpoint_t *endpoint;
5100 int mgroup_setup = 0;
5101
5102 /* Need to have at least one endpoint! */
5103 assert(ctx->endpoint);
5104 if (!ctx->endpoint)
5105 return -1;
5106
5107 /* Default is let the kernel choose */
5108#if COAP_IPV6_SUPPORT
5109 mreq6.ipv6mr_interface = 0;
5110#endif /* COAP_IPV6_SUPPORT */
5111#if COAP_IPV4_SUPPORT
5112 mreq4.imr_interface.s_addr = INADDR_ANY;
5113#endif /* COAP_IPV4_SUPPORT */
5114
5115 memset(&hints, 0, sizeof(hints));
5116 hints.ai_socktype = SOCK_DGRAM;
5117
5118 /* resolve the multicast group address */
5119 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5120
5121 if (result != 0) {
5122 coap_log_err("coap_join_mcast_group_intf: %s: "
5123 "Cannot resolve multicast address: %s\n",
5124 group_name, gai_strerror(result));
5125 goto finish;
5126 }
5127
5128 /* Need to do a windows equivalent at some point */
5129#ifndef _WIN32
5130 if (ifname) {
5131 /* interface specified - check if we have correct IPv4/IPv6 information */
5132 int done_ip4 = 0;
5133 int done_ip6 = 0;
5134#if defined(ESPIDF_VERSION)
5135 struct netif *netif;
5136#else /* !ESPIDF_VERSION */
5137#if COAP_IPV4_SUPPORT
5138 int ip4fd;
5139#endif /* COAP_IPV4_SUPPORT */
5140 struct ifreq ifr;
5141#endif /* !ESPIDF_VERSION */
5142
5143 /* See which mcast address family types are being asked for */
5144 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5145 ainfo = ainfo->ai_next) {
5146 switch (ainfo->ai_family) {
5147#if COAP_IPV6_SUPPORT
5148 case AF_INET6:
5149 if (done_ip6)
5150 break;
5151 done_ip6 = 1;
5152#if defined(ESPIDF_VERSION)
5153 netif = netif_find(ifname);
5154 if (netif)
5155 mreq6.ipv6mr_interface = netif_get_index(netif);
5156 else
5157 coap_log_err("coap_join_mcast_group_intf: %s: "
5158 "Cannot get IPv4 address: %s\n",
5159 ifname, coap_socket_strerror());
5160#else /* !ESPIDF_VERSION */
5161 memset(&ifr, 0, sizeof(ifr));
5162 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5163 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5164
5165#ifdef HAVE_IF_NAMETOINDEX
5166 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5167 if (mreq6.ipv6mr_interface == 0) {
5168 coap_log_warn("coap_join_mcast_group_intf: "
5169 "cannot get interface index for '%s'\n",
5170 ifname);
5171 }
5172#elif defined(__QNXNTO__)
5173#else /* !HAVE_IF_NAMETOINDEX */
5174 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5175 if (result != 0) {
5176 coap_log_warn("coap_join_mcast_group_intf: "
5177 "cannot get interface index for '%s': %s\n",
5178 ifname, coap_socket_strerror());
5179 } else {
5180 /* Capture the IPv6 if_index for later */
5181 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5182 }
5183#endif /* !HAVE_IF_NAMETOINDEX */
5184#endif /* !ESPIDF_VERSION */
5185#endif /* COAP_IPV6_SUPPORT */
5186 break;
5187#if COAP_IPV4_SUPPORT
5188 case AF_INET:
5189 if (done_ip4)
5190 break;
5191 done_ip4 = 1;
5192#if defined(ESPIDF_VERSION)
5193 netif = netif_find(ifname);
5194 if (netif)
5195 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5196 else
5197 coap_log_err("coap_join_mcast_group_intf: %s: "
5198 "Cannot get IPv4 address: %s\n",
5199 ifname, coap_socket_strerror());
5200#else /* !ESPIDF_VERSION */
5201 /*
5202 * Need an AF_INET socket to do this unfortunately to stop
5203 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5204 */
5205 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5206 if (ip4fd == -1) {
5207 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5208 ifname, coap_socket_strerror());
5209 continue;
5210 }
5211 memset(&ifr, 0, sizeof(ifr));
5212 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5213 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5214 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5215 if (result != 0) {
5216 coap_log_err("coap_join_mcast_group_intf: %s: "
5217 "Cannot get IPv4 address: %s\n",
5218 ifname, coap_socket_strerror());
5219 } else {
5220 /* Capture the IPv4 address for later */
5221 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5222 }
5223 close(ip4fd);
5224#endif /* !ESPIDF_VERSION */
5225 break;
5226#endif /* COAP_IPV4_SUPPORT */
5227 default:
5228 break;
5229 }
5230 }
5231 }
5232#else /* _WIN32 */
5233 /*
5234 * On Windows this function ignores the ifname variable so we unset this
5235 * variable on this platform in any case in order to enable the interface
5236 * selection from the bind address below.
5237 */
5238 ifname = 0;
5239#endif /* _WIN32 */
5240
5241 /* Add in mcast address(es) to appropriate interface */
5242 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5243 LL_FOREACH(ctx->endpoint, endpoint) {
5244 /* Only UDP currently supported */
5245 if (endpoint->proto == COAP_PROTO_UDP) {
5246 coap_address_t gaddr;
5247
5248 coap_address_init(&gaddr);
5249#if COAP_IPV6_SUPPORT
5250 if (ainfo->ai_family == AF_INET6) {
5251 if (!ifname) {
5252 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5253 /*
5254 * Do it on the ifindex that the server is listening on
5255 * (sin6_scope_id could still be 0)
5256 */
5257 mreq6.ipv6mr_interface =
5258 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5259 } else {
5260 mreq6.ipv6mr_interface = 0;
5261 }
5262 }
5263 gaddr.addr.sin6.sin6_family = AF_INET6;
5264 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5265 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5266 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5267 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5268 (char *)&mreq6, sizeof(mreq6));
5269 }
5270#endif /* COAP_IPV6_SUPPORT */
5271#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5272 else
5273#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5274#if COAP_IPV4_SUPPORT
5275 if (ainfo->ai_family == AF_INET) {
5276 if (!ifname) {
5277 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5278 /*
5279 * Do it on the interface that the server is listening on
5280 * (sin_addr could still be INADDR_ANY)
5281 */
5282 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5283 } else {
5284 mreq4.imr_interface.s_addr = INADDR_ANY;
5285 }
5286 }
5287 gaddr.addr.sin.sin_family = AF_INET;
5288 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5289 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5290 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5291 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5292 (char *)&mreq4, sizeof(mreq4));
5293 }
5294#endif /* COAP_IPV4_SUPPORT */
5295 else {
5296 continue;
5297 }
5298
5299 if (result == COAP_SOCKET_ERROR) {
5300 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5301 group_name, coap_socket_strerror());
5302 } else {
5303 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5304
5305 addr_str[sizeof(addr_str)-1] = '\000';
5306 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5307 sizeof(addr_str) - 1)) {
5308 if (ifname)
5309 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5310 ifname);
5311 else
5312 coap_log_debug("added mcast group %s\n", addr_str);
5313 }
5314 mgroup_setup = 1;
5315 }
5316 }
5317 }
5318 }
5319 if (!mgroup_setup) {
5320 result = -1;
5321 }
5322
5323finish:
5324 freeaddrinfo(resmulti);
5325
5326 return result;
5327}
5328
5329void
5331 context->mcast_per_resource = 1;
5332}
5333
5334#endif /* ! COAP_SERVER_SUPPORT */
5335
5336#if COAP_CLIENT_SUPPORT
5337int
5338coap_mcast_set_hops(coap_session_t *session, size_t hops) {
5339 if (session && coap_is_mcast(&session->addr_info.remote)) {
5340 switch (session->addr_info.remote.addr.sa.sa_family) {
5341#if COAP_IPV4_SUPPORT
5342 case AF_INET:
5343 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
5344 (const char *)&hops, sizeof(hops)) < 0) {
5345 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5346 hops, coap_socket_strerror());
5347 return 0;
5348 }
5349 return 1;
5350#endif /* COAP_IPV4_SUPPORT */
5351#if COAP_IPV6_SUPPORT
5352 case AF_INET6:
5353 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
5354 (const char *)&hops, sizeof(hops)) < 0) {
5355 coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
5356 hops, coap_socket_strerror());
5357 return 0;
5358 }
5359 return 1;
5360#endif /* COAP_IPV6_SUPPORT */
5361 default:
5362 break;
5363 }
5364 }
5365 return 0;
5366}
5367#endif /* COAP_CLIENT_SUPPORT */
5368
5369#else /* defined WITH_CONTIKI || defined WITH_LWIP */
5370COAP_API int
5372 const char *group_name COAP_UNUSED,
5373 const char *ifname COAP_UNUSED) {
5374 return -1;
5375}
5376
5377int
5379 size_t hops COAP_UNUSED) {
5380 return 0;
5381}
5382
5383void
5385}
5386#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:2336
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:1029
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:517
#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:2072
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:2942
#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:5000
#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:4737
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:3257
int coap_started
Definition coap_net.c:4935
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2333
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2374
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:4190
#define min(a, b)
Definition coap_net.c:73
void coap_startup(void)
Definition coap_net.c:4951
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu)
Definition coap_net.c:4263
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:2731
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:2666
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:2101
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1814
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:1273
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:1458
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:2720
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:2659
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)
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:4809
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:5071
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:2897
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:1326
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:4296
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:1811
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:4871
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2219
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:1393
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:3001
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:2836
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:3040
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:2080
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:1448
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:2075
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:5024
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:3073
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:5052
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:4861
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:5064
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:5058
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:4798
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:5046
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_ret_release(r, c, func, failed)
Dummy for no thread-safe code.
#define coap_lock_callback_release(c, func, failed)
Dummy for no thread-safe code.
#define coap_lock_unlock(c)
Dummy for no thread-safe code.
#define coap_lock_lock(c, failed)
Dummy for no thread-safe code.
#define coap_lock_callback(c, func)
Dummy for no thread-safe code.
#define coap_lock_check_locked(c)
Dummy for no thread-safe code.
#define coap_lock_init()
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, c, func)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:120
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:5035
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:2404
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
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