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