libcoap 4.3.5-develop-c63c8f7
Loading...
Searching...
No Matches
coap_net.c
Go to the documentation of this file.
1/* coap_net.c -- CoAP context interface
2 *
3 * Copyright (C) 2010--2026 Olaf Bergmann <bergmann@tzi.org> and others
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 *
7 * This file is part of the CoAP library libcoap. Please see
8 * README for terms of use.
9 */
10
15
18
19#include <ctype.h>
20#include <stdio.h>
21#ifdef HAVE_LIMITS_H
22#include <limits.h>
23#endif
24
25#ifndef __ZEPHYR__
26#ifdef HAVE_UNISTD_H
27#include <unistd.h>
28#else
29#ifdef HAVE_SYS_UNISTD_H
30#include <sys/unistd.h>
31#endif
32#endif
33#ifdef HAVE_SYS_TYPES_H
34#include <sys/types.h>
35#endif
36#ifdef HAVE_SYS_SOCKET_H
37#include <sys/socket.h>
38#endif
39#ifdef HAVE_SYS_IOCTL_H
40#include <sys/ioctl.h>
41#endif
42#ifdef HAVE_NETINET_IN_H
43#include <netinet/in.h>
44#endif
45#ifdef HAVE_ARPA_INET_H
46#include <arpa/inet.h>
47#endif
48#ifdef HAVE_NET_IF_H
49#include <net/if.h>
50#endif
51#ifdef COAP_EPOLL_SUPPORT
52#include <sys/epoll.h>
53#include <sys/timerfd.h>
54#endif /* COAP_EPOLL_SUPPORT */
55#ifdef HAVE_WS2TCPIP_H
56#include <ws2tcpip.h>
57#endif
58
59#ifdef HAVE_NETDB_H
60#include <netdb.h>
61#endif
62#endif /* !__ZEPHYR__ */
63
64#ifdef WITH_LWIP
65#include <lwip/pbuf.h>
66#include <lwip/udp.h>
67#include <lwip/timeouts.h>
68#include <lwip/tcpip.h>
69#endif
70
71#ifndef INET6_ADDRSTRLEN
72#define INET6_ADDRSTRLEN 40
73#endif
74
75#ifndef min
76#define min(a,b) ((a) < (b) ? (a) : (b))
77#endif
78
83#define FRAC_BITS 6
84
89#define MAX_BITS 8
90
91#if FRAC_BITS > 8
92#error FRAC_BITS must be less or equal 8
93#endif
94
96#define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
97 ((1 << (frac)) * fval.fractional_part + 500)/1000))
98
100#define ACK_RANDOM_FACTOR \
101 Q(FRAC_BITS, session->ack_random_factor)
102
104#define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
105
106static int send_recv_terminate = 0;
107
112
117
118unsigned int
120 unsigned int result = 0;
122
123 if (ctx->sendqueue) {
124 /* delta < 0 means that the new time stamp is before the old. */
125 if (delta <= 0) {
126 ctx->sendqueue->t = (coap_tick_diff_t)ctx->sendqueue->t - delta;
127 } else {
128 /* This case is more complex: The time must be advanced forward,
129 * thus possibly leading to timed out elements at the queue's
130 * start. For every element that has timed out, its relative
131 * time is set to zero and the result counter is increased. */
132
133 coap_queue_t *q = ctx->sendqueue;
134 coap_tick_t t = 0;
135 while (q && (t + q->t < (coap_tick_t)delta)) {
136 t += q->t;
137 q->t = 0;
138 result++;
139 q = q->next;
140 }
141
142 /* finally adjust the first element that has not expired */
143 if (q) {
144 q->t = (coap_tick_t)delta - t;
145 }
146 }
147 }
148
149 /* adjust basetime */
151
152 return result;
153}
154
155int
157 coap_queue_t *p, *q;
158 if (!queue || !node)
159 return 0;
160
161 /* set queue head if empty */
162 if (!*queue) {
163 *queue = node;
164 return 1;
165 }
166
167 /* replace queue head if PDU's time is less than head's time */
168 q = *queue;
169 if (node->t < q->t) {
170 node->next = q;
171 *queue = node;
172 q->t -= node->t; /* make q->t relative to node->t */
173 return 1;
174 }
175
176 /* search for right place to insert */
177 do {
178 node->t -= q->t; /* make node-> relative to q->t */
179 p = q;
180 q = q->next;
181 } while (q && q->t <= node->t);
182
183 /* insert new item */
184 if (q) {
185 q->t -= node->t; /* make q->t relative to node->t */
186 }
187 node->next = q;
188 p->next = node;
189 return 1;
190}
191
192COAP_API int
194 int ret;
195
196 if (!node)
197 return 0;
198
199 coap_lock_lock(return 0);
200 ret = coap_delete_node_lkd(node);
202 return ret;
203}
204
205int
207 if (!node)
208 return 0;
209
211 if (node->session) {
212 /*
213 * Need to remove out of context->sendqueue as added in by coap_wait_ack()
214 */
215 if (node->session->context->sendqueue) {
216 LL_DELETE(node->session->context->sendqueue, node);
217 }
219 }
220 coap_free_node(node);
221
222 return 1;
223}
224
225void
227 if (!queue)
228 return;
229
230 coap_delete_all(queue->next);
232}
233
236 coap_queue_t *node;
237 node = coap_malloc_node();
238
239 if (!node) {
240 coap_log_warn("coap_new_node: malloc failed\n");
241 return NULL;
242 }
243
244 memset(node, 0, sizeof(*node));
245 return node;
246}
247
250 if (!context || !context->sendqueue)
251 return NULL;
252
253 return context->sendqueue;
254}
255
258 coap_queue_t *next;
259
260 if (!context || !context->sendqueue)
261 return NULL;
262
263 next = context->sendqueue;
264 context->sendqueue = context->sendqueue->next;
265 if (context->sendqueue) {
266 context->sendqueue->t += next->t;
267 }
268 next->next = NULL;
269 return next;
270}
271
272#if COAP_CLIENT_SUPPORT
273const coap_bin_const_t *
275
276 if (session->psk_key) {
277 return session->psk_key;
278 }
279 if (session->cpsk_setup_data.psk_info.key.length)
280 return &session->cpsk_setup_data.psk_info.key;
281
282 /* Not defined in coap_new_client_session_psk2() */
283 return NULL;
284}
285
286const coap_bin_const_t *
288
289 if (session->psk_identity) {
290 return session->psk_identity;
291 }
293 return &session->cpsk_setup_data.psk_info.identity;
294
295 /* Not defined in coap_new_client_session_psk2() */
296 return NULL;
297}
298#endif /* COAP_CLIENT_SUPPORT */
299
300#if COAP_SERVER_SUPPORT
301const coap_bin_const_t *
303
304 if (session->psk_key)
305 return session->psk_key;
306
307 if (session->context->spsk_setup_data.psk_info.key.length)
308 return &session->context->spsk_setup_data.psk_info.key;
309
310 /* Not defined in coap_context_set_psk2() */
311 return NULL;
312}
313
314const coap_bin_const_t *
316
317 if (session->psk_hint)
318 return session->psk_hint;
319
320 if (session->context->spsk_setup_data.psk_info.hint.length)
321 return &session->context->spsk_setup_data.psk_info.hint;
322
323 /* Not defined in coap_context_set_psk2() */
324 return NULL;
325}
326
327COAP_API int
329 const char *hint,
330 const uint8_t *key,
331 size_t key_len) {
332 int ret;
333
334 coap_lock_lock(return 0);
335 ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
337 return ret;
338}
339
340int
342 const char *hint,
343 const uint8_t *key,
344 size_t key_len) {
345 coap_dtls_spsk_t setup_data;
346
348 memset(&setup_data, 0, sizeof(setup_data));
349 if (hint) {
350 setup_data.psk_info.hint.s = (const uint8_t *)hint;
351 setup_data.psk_info.hint.length = strlen(hint);
352 }
353
354 if (key && key_len > 0) {
355 setup_data.psk_info.key.s = key;
356 setup_data.psk_info.key.length = key_len;
357 }
358
359 return coap_context_set_psk2_lkd(ctx, &setup_data);
360}
361
362COAP_API int
364 int ret;
365
366 coap_lock_lock(return 0);
367 ret = coap_context_set_psk2_lkd(ctx, setup_data);
369 return ret;
370}
371
372int
374 if (!setup_data)
375 return 0;
376
378 ctx->spsk_setup_data = *setup_data;
379
381 return coap_dtls_context_set_spsk(ctx, setup_data);
382 }
383 return 0;
384}
385
386COAP_API int
388 const coap_dtls_pki_t *setup_data) {
389 int ret;
390
391 coap_lock_lock(return 0);
392 ret = coap_context_set_pki_lkd(ctx, setup_data);
394 return ret;
395}
396
397int
399 const coap_dtls_pki_t *setup_data) {
401 if (!setup_data)
402 return 0;
403 if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
404 coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
405 return 0;
406 }
408 return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
409 }
410 return 0;
411}
412#endif /* ! COAP_SERVER_SUPPORT */
413
414COAP_API int
416 const char *ca_file,
417 const char *ca_dir) {
418 int ret;
419
420 coap_lock_lock(return 0);
421 ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
423 return ret;
424}
425
426int
428 const char *ca_file,
429 const char *ca_dir) {
431 return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
432 }
433 return 0;
434}
435
436COAP_API int
438 int ret;
439
440 coap_lock_lock(return 0);
443 return ret;
444}
445
446int
453
454
455void
456coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
457 context->ping_timeout = seconds;
458}
459
460int
462#if COAP_CLIENT_SUPPORT
463 return coap_dtls_set_cid_tuple_change(context, every);
464#else /* ! COAP_CLIENT_SUPPORT */
465 (void)context;
466 (void)every;
467 return 0;
468#endif /* ! COAP_CLIENT_SUPPORT */
469}
470
471void
473 uint64_t rate_limit_ppm) {
474 if (rate_limit_ppm) {
475 context->rl_ticks_per_packet = (60ULL * COAP_TICKS_PER_SECOND) / rate_limit_ppm;
476 } else {
477 context->rl_ticks_per_packet = 0;
478 }
479}
480
481void
483 size_t max_body_size) {
484 assert(max_body_size == 0 || max_body_size > 1024);
485 if (max_body_size == 0 || max_body_size > 1024) {
486 context->max_body_size = max_body_size;
487 }
488}
489
490void
492 size_t max_bodies_ram) {
493#if COAP_SERVER_SUPPORT
494 assert(max_bodies_ram == 0 || max_bodies_ram > 1024);
495 if (max_bodies_ram == 0 || max_bodies_ram > 1024) {
496 context->max_bodies_ram = max_bodies_ram;
497 }
498 /* Cannot let a single session keep failing if it is larger then max_bodies_ram */
499 if (context->max_body_size == 0)
500 context->max_body_size = max_bodies_ram;
501#else
502 (void)context;
503 (void)max_bodies_ram;
504#endif /* COAP_SERVER_SUPPORT */
505}
506
507void
509 size_t max_token_size) {
510 assert(max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
511 max_token_size <= COAP_TOKEN_EXT_MAX);
512 if (max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
513 max_token_size <= COAP_TOKEN_EXT_MAX) {
514 context->max_token_size = (uint32_t)max_token_size;
515 }
516}
517
518void
520 unsigned int max_idle_sessions) {
521 context->max_idle_sessions = max_idle_sessions;
522}
523
524unsigned int
526 return context->max_idle_sessions;
527}
528
529void
531 unsigned int max_handshake_sessions) {
532 context->max_handshake_sessions = max_handshake_sessions;
533}
534
535unsigned int
539
540static unsigned int s_csm_timeout = 30;
541
542void
544 unsigned int csm_timeout) {
545 s_csm_timeout = csm_timeout;
546 coap_context_set_csm_timeout_ms(context, csm_timeout * 1000);
547}
548
549unsigned int
551 (void)context;
552 return s_csm_timeout;
553}
554
555void
557 unsigned int csm_timeout_ms) {
558 if (csm_timeout_ms < 10)
559 csm_timeout_ms = 10;
560 if (csm_timeout_ms > 10000)
561 csm_timeout_ms = 10000;
562 context->csm_timeout_ms = csm_timeout_ms;
563}
564
565unsigned int
567 return context->csm_timeout_ms;
568}
569
570void
572 uint32_t csm_max_message_size) {
573 assert(csm_max_message_size >= 64);
574 if (csm_max_message_size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
575 csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
576 coap_log_debug("Restricting CSM Max-Message-Size size to %" PRIu32 "\n",
577 csm_max_message_size);
578 }
579
580 context->csm_max_message_size = csm_max_message_size;
581}
582
583uint32_t
587
588void
590 unsigned int session_timeout) {
591 context->session_timeout = session_timeout;
592}
593
594void
596 unsigned int reconnect_time) {
597 coap_context_set_session_reconnect_time2(context, reconnect_time, 0);
598}
599
600void
602 unsigned int reconnect_time,
603 uint8_t retry_count) {
604#if COAP_CLIENT_SUPPORT
605 context->reconnect_time = reconnect_time;
606 context->retry_count = retry_count;
607#else /* ! COAP_CLIENT_SUPPORT */
608 (void)context;
609 (void)reconnect_time;
610 (void)retry_count;
611#endif /* ! COAP_CLIENT_SUPPORT */
612}
613
614unsigned int
616 return context->session_timeout;
617}
618
619void
621#if COAP_SERVER_SUPPORT
622 context->shutdown_no_send_observe = 1;
623#else /* ! COAP_SERVER_SUPPORT */
624 (void)context;
625#endif /* ! COAP_SERVER_SUPPORT */
626}
627
628int
630#if COAP_EPOLL_SUPPORT
631 return context->epfd;
632#else /* ! COAP_EPOLL_SUPPORT */
633 (void)context;
634 return -1;
635#endif /* ! COAP_EPOLL_SUPPORT */
636}
637
638int
640#if COAP_EPOLL_SUPPORT
641 return 1;
642#else /* ! COAP_EPOLL_SUPPORT */
643 return 0;
644#endif /* ! COAP_EPOLL_SUPPORT */
645}
646
647int
649#if COAP_THREAD_SAFE
650 return 1;
651#else /* ! COAP_THREAD_SAFE */
652 return 0;
653#endif /* ! COAP_THREAD_SAFE */
654}
655
656int
658#if COAP_IPV4_SUPPORT
659 return 1;
660#else /* ! COAP_IPV4_SUPPORT */
661 return 0;
662#endif /* ! COAP_IPV4_SUPPORT */
663}
664
665int
667#if COAP_IPV6_SUPPORT
668 return 1;
669#else /* ! COAP_IPV6_SUPPORT */
670 return 0;
671#endif /* ! COAP_IPV6_SUPPORT */
672}
673
674int
676#if COAP_CLIENT_SUPPORT
677 return 1;
678#else /* ! COAP_CLIENT_SUPPORT */
679 return 0;
680#endif /* ! COAP_CLIENT_SUPPORT */
681}
682
683int
685#if COAP_SERVER_SUPPORT
686 return 1;
687#else /* ! COAP_SERVER_SUPPORT */
688 return 0;
689#endif /* ! COAP_SERVER_SUPPORT */
690}
691
692int
694#if COAP_AF_UNIX_SUPPORT
695 return 1;
696#else /* ! COAP_AF_UNIX_SUPPORT */
697 return 0;
698#endif /* ! COAP_AF_UNIX_SUPPORT */
699}
700
701COAP_API void
702coap_context_set_app_data(coap_context_t *context, void *app_data) {
703 assert(context);
704 coap_lock_lock(return);
705 coap_context_set_app_data2_lkd(context, app_data, NULL);
707}
708
709void *
711 assert(context);
712 return context->app_data;
713}
714
715COAP_API void *
718 void *old_data;
719
720 coap_lock_lock(return NULL);
721 old_data = coap_context_set_app_data2_lkd(context, app_data, callback);
723 return old_data;
724}
725
726void *
729 void *old_data = context->app_data;
730
731 context->app_data = app_data;
732 context->app_cb = app_data ? callback : NULL;
733 return old_data;
734}
735
737coap_new_context(const coap_address_t *listen_addr) {
739
740#if ! COAP_SERVER_SUPPORT
741 (void)listen_addr;
742#endif /* COAP_SERVER_SUPPORT */
743
744 if (!coap_started) {
745 coap_startup();
746 coap_log_warn("coap_startup() should be called before any other "
747 "coap_*() functions are called\n");
748 }
749
751 if (!c) {
752 coap_log_emerg("coap_init: malloc: failed\n");
753 return NULL;
754 }
755 memset(c, 0, sizeof(coap_context_t));
756
758#ifdef COAP_EPOLL_SUPPORT
759 c->epfd = epoll_create1(0);
760 if (c->epfd == -1) {
761 coap_log_err("coap_new_context: Unable to epoll_create: %s (%d)\n",
763 errno);
764 goto onerror;
765 }
766 if (c->epfd != -1) {
767 c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
768 if (c->eptimerfd == -1) {
769 coap_log_err("coap_new_context: Unable to timerfd_create: %s (%d)\n",
771 errno);
772 goto onerror;
773 } else {
774 int ret;
775 struct epoll_event event;
776
777 /* Needed if running 32bit as ptr is only 32bit */
778 memset(&event, 0, sizeof(event));
779 event.events = EPOLLIN;
780 /* We special case this event by setting to NULL */
781 event.data.ptr = NULL;
782
783 ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
784 if (ret == -1) {
785 coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
786 "coap_new_context",
787 coap_socket_strerror(), errno);
788 goto onerror;
789 }
790 }
791 }
792#endif /* COAP_EPOLL_SUPPORT */
793
796 if (!c->dtls_context) {
797 coap_log_emerg("coap_init: no DTLS context available\n");
798 goto onerror;
799 }
800 }
801
802 /* set default CSM values */
803 c->csm_timeout_ms = 1000;
805
806#if COAP_SERVER_SUPPORT
807 if (listen_addr) {
808 coap_endpoint_t *endpoint = coap_new_endpoint_lkd(c, listen_addr, COAP_PROTO_UDP);
809 if (endpoint == NULL) {
810 goto onerror;
811 }
812 }
813#endif /* COAP_SERVER_SUPPORT */
814
815 c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
816
817#if defined(WITH_LWIP)
818#if NO_SYS == 0
819 if (sys_sem_new(&c->coap_io_timeout_sem, 0) != ERR_OK)
820 coap_log_warn("coap_new_context: Failed to set up semaphore\n");
821#endif /* NO_SYS == 0 */
822#endif /* ! WITH_LWIP */
824 return c;
825
826onerror:
829 return NULL;
830}
831
832COAP_API void
833coap_set_app_data(coap_context_t *context, void *app_data) {
834 assert(context);
835 coap_lock_lock(return);
836 coap_context_set_app_data2_lkd(context, app_data, NULL);
838}
839
840void *
842 assert(ctx);
843 return ctx->app_data;
844}
845
846COAP_API void
848 if (!context)
849 return;
850 coap_lock_lock(return);
851 coap_free_context_lkd(context);
853}
854
855void
857 if (!context)
858 return;
859
861#if COAP_SERVER_SUPPORT
862 /* Removing a resource may cause a NON unsolicited observe to be sent */
863 context->context_going_away = 1;
864 if (context->shutdown_no_send_observe)
865 context->observe_no_clear = 1;
866 coap_delete_all_resources(context);
867#endif /* COAP_SERVER_SUPPORT */
868#if COAP_CLIENT_SUPPORT
869 /* Stop any attempts at reconnection */
870 context->reconnect_time = 0;
871#endif /* COAP_CLIENT_SUPPORT */
872
873 coap_delete_all(context->sendqueue);
874 context->sendqueue = NULL;
875
876#ifdef WITH_LWIP
877 if (context->timer_configured) {
878 LOCK_TCPIP_CORE();
879 sys_untimeout(coap_io_process_timeout, (void *)context);
880 UNLOCK_TCPIP_CORE();
881 context->timer_configured = 0;
882 }
883#endif /* WITH_LWIP */
884
885#if COAP_ASYNC_SUPPORT
886 coap_delete_all_async(context);
887#endif /* COAP_ASYNC_SUPPORT */
888
889#if COAP_SERVER_SUPPORT
890 coap_cache_entry_t *cp, *ctmp;
891 coap_endpoint_t *ep, *tmp;
892
893 HASH_ITER(hh, context->cache, cp, ctmp) {
894 coap_delete_cache_entry(context, cp);
895 }
896 if (context->cache_ignore_count) {
897 coap_free_type(COAP_STRING, context->cache_ignore_options);
898 }
899
900 LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
901 coap_free_endpoint_lkd(ep);
902 }
903#endif /* COAP_SERVER_SUPPORT */
904
905#if COAP_CLIENT_SUPPORT
906 coap_session_t *sp, *rtmp;
907
908 SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
910 }
911#endif /* COAP_CLIENT_SUPPORT */
912
913#if COAP_OSCORE_SUPPORT
914 coap_delete_all_oscore(context);
915#endif /* COAP_OSCORE_SUPPORT */
916
917 if (context->dtls_context)
919#ifdef COAP_EPOLL_SUPPORT
920 if (context->eptimerfd != -1) {
921 int ret;
922 struct epoll_event event;
923
924 /* Kernels prior to 2.6.9 expect non NULL event parameter */
925 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
926 if (ret == -1) {
927 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
928 "coap_free_context",
929 coap_socket_strerror(), errno);
930 }
931 close(context->eptimerfd);
932 context->eptimerfd = -1;
933 }
934 if (context->epfd != -1) {
935 close(context->epfd);
936 context->epfd = -1;
937 }
938#endif /* COAP_EPOLL_SUPPORT */
939#if COAP_SERVER_SUPPORT
940#if COAP_WITH_OBSERVE_PERSIST
941 coap_persist_cleanup(context);
942#endif /* COAP_WITH_OBSERVE_PERSIST */
943#endif /* COAP_SERVER_SUPPORT */
944#if COAP_PROXY_SUPPORT
945 coap_proxy_cleanup(context);
946#endif /* COAP_PROXY_SUPPORT */
947
948 if (context->app_cb) {
949 coap_lock_callback(context->app_cb(context->app_data));
950 }
951#if defined(WITH_LWIP)
952#if NO_SYS == 0
953 sys_sem_free(&context->coap_io_timeout_sem);
954#endif /* NO_SYS == 0 */
955#endif /* ! WITH_LWIP */
956#if COAP_THREAD_SAFE && !WITH_LWIP
958#endif /* COAP_THREAD_SAFE && !WITH_LWIP */
961}
962
963static coap_crit_type_t
965#if COAP_SERVER_SUPPORT
966 coap_opt_iterator_t t_iter;
967 coap_opt_t *proxy_uri = NULL;
968 coap_opt_t *proxy_scheme = NULL;
969
970 if (session->proxy_session) {
971 return COAP_CRIT_PROXY;
972 } else if (COAP_PDU_IS_REQUEST(pdu) && session->context->unknown_resource &&
973 session->context->unknown_resource->is_reverse_proxy) {
974 return COAP_CRIT_PROXY;
975 } else if (COAP_PDU_IS_REQUEST(pdu) && session->context->proxy_uri_resource &&
976 ((proxy_uri = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &t_iter)) ||
977 (proxy_scheme = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &t_iter)))) {
978 if (proxy_uri || proxy_scheme) {
979 coap_uri_t uri;
980
981 /* Duplicates some of the code in handle_request() */
982 if (proxy_uri) {
984 coap_opt_length(proxy_uri), &uri) < 0) {
985 return COAP_CRIT_PROXY;
986 }
987 } else {
988 coap_opt_t *opt;
989 coap_resource_t *resource;
990
991 memset(&uri, 0, sizeof(uri));
992 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &t_iter);
993 if (opt) {
994 uri.host.length = coap_opt_length(opt);
995 uri.host.s = coap_opt_value(opt);
996 } else {
997 uri.host.length = 0;
998 }
999 /* See if we are the endpoint */
1000 resource = session->context->proxy_uri_resource;
1001 if (uri.host.length && resource->proxy_name_count &&
1002 resource->proxy_name_list) {
1003 size_t i;
1004
1005 if (resource->proxy_name_count == 1 &&
1006 resource->proxy_name_list[0]->length == 0) {
1007 /* If proxy_name_list[0] is zero length, then this is the endpoint */
1008 i = 0;
1009 } else {
1010 for (i = 0; i < resource->proxy_name_count; i++) {
1011 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
1012 break;
1013 }
1014 }
1015 }
1016 if (i != resource->proxy_name_count) {
1017 return COAP_CRIT_NOT_PROXY;
1018 }
1019 }
1020 }
1021 return COAP_CRIT_PROXY;
1022 }
1023 }
1024 return COAP_CRIT_NOT_PROXY;
1025#else /* ! COAP_SERVER_SUPPORT */
1026#endif /* ! COAP_SERVER_SUPPORT */
1027 (void)session;
1028 (void)pdu;
1029 return COAP_CRIT_NOT_PROXY;
1030}
1031
1032int
1034 coap_pdu_t *pdu,
1035 coap_opt_filter_t *unknown,
1036 coap_crit_type_t is_proxy) {
1037 coap_context_t *ctx = session->context;
1038 coap_opt_iterator_t opt_iter;
1039 int ok = 1;
1040 coap_option_num_t last_number = -1;
1041
1042 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1043
1044 while (coap_option_next(&opt_iter)) {
1045 /* Check for explicitly reserved option RFC 5272 12.2 Table 7 */
1046 /* Need to check reserved options */
1047 switch (opt_iter.number) {
1048 case 0:
1049 case 128:
1050 case 132:
1051 case 136:
1052 case 140:
1053 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1054 coap_log_debug("Unknown reserved option %d\n", opt_iter.number);
1055 ok = 0;
1056
1057 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1058 * slots have been used up and no more options can be tracked.
1059 * Safe to break out of this loop as ok is already set. */
1060 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1061 goto overflow;
1062 }
1063 }
1064 break;
1065 default:
1066 break;
1067 }
1068 if (opt_iter.number & 0x01) {
1069 /* first check the known built-in critical options */
1070 switch (opt_iter.number) {
1071#if COAP_Q_BLOCK_SUPPORT
1074 if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
1075 coap_log_debug("Critical option '%s' (%d) disabled - not supported\n",
1076 coap_option_string(pdu->code, opt_iter.number), opt_iter.number);
1077 ok = 0;
1078 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1079 * slots have been used up and no more options can be tracked.
1080 * Safe to break out of this loop as ok is already set. */
1081 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1082 goto overflow;
1083 }
1084 }
1085 break;
1086#endif /* COAP_Q_BLOCK_SUPPORT */
1094 case COAP_OPTION_ACCEPT:
1095 case COAP_OPTION_BLOCK2:
1096 case COAP_OPTION_BLOCK1:
1099 break;
1100 case COAP_OPTION_OSCORE:
1101 /* Valid critical if doing OSCORE */
1102#if COAP_OSCORE_SUPPORT
1103 /* Generally configured or has coap oscore enabled helper function */
1104 if (ctx->p_osc_ctx || ctx->oscore_find_cb)
1105 break;
1106#endif /* COAP_OSCORE_SUPPORT */
1107 /* Fall Through */
1108 default:
1109 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1110#if COAP_SERVER_SUPPORT
1111 if ((opt_iter.number & 0x02) == 0) {
1112 /* Safe to forward critical? - check if proxy pdu */
1113 if (is_proxy == COAP_CRIT_UNKNOWN) {
1114 is_proxy = coap_is_session_proxy(session, pdu);
1115 }
1116 if (is_proxy == COAP_CRIT_PROXY) {
1117 pdu->crit_opt = 1;
1118 break;
1119 }
1120 }
1121#endif /* COAP_SERVER_SUPPORT */
1122 coap_log_debug("Critical option %u dropped\n", opt_iter.number);
1123 ok = 0;
1124
1125 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1126 * slots have been used up and no more options can be tracked.
1127 * Safe to break out of this loop as ok is already set. */
1128 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1129 goto overflow;
1130 }
1131 }
1132 }
1133 }
1134 if (opt_iter.number & 0x02) {
1135 /* Check for safe to forward for a proxy */
1136 if (is_proxy == COAP_CRIT_UNKNOWN) {
1137 is_proxy = coap_is_session_proxy(session, pdu);
1138 }
1139 if (is_proxy == COAP_CRIT_PROXY) {
1140 switch (opt_iter.number) {
1145 case COAP_OPTION_MAXAGE:
1148 case COAP_OPTION_BLOCK2:
1149 case COAP_OPTION_BLOCK1:
1153 break;
1154 default:
1155 coap_log_debug("Not Safe option %u cannot be forwarded - dropped\n",
1156 opt_iter.number);
1157 ok = 0;
1158
1159 /* When opt_iter.number cannot be set in unknown, all of the appropriate
1160 * slots have been used up and no more options can be tracked.
1161 * Safe to break out of this loop as ok is already set. */
1162 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1163 goto overflow;
1164 }
1165 }
1166 }
1167 }
1168 if (last_number == opt_iter.number) {
1169 /* Check for duplicated option RFC 5272 5.4.5 */
1170 if (!coap_option_check_repeatable(pdu, opt_iter.number)) {
1171 if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1172 ok = 0;
1173 if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1174 goto overflow;
1175 }
1176 }
1177 }
1178 } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
1179 COAP_PDU_IS_REQUEST(pdu)) {
1180 /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
1181 coap_block_b_t block;
1182
1183 if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
1184 if (block.m) {
1185 size_t used_size = pdu->used_size;
1186 unsigned char buf[4];
1187
1188 coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
1189 block.m = 0;
1190 coap_update_option(pdu, opt_iter.number,
1191 coap_encode_var_safe(buf, sizeof(buf),
1192 ((block.num << 4) |
1193 (block.m << 3) |
1194 block.aszx)),
1195 buf);
1196 if (used_size != pdu->used_size) {
1197 /* Unfortunately need to restart the scan */
1198 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1199 last_number = -1;
1200 continue;
1201 }
1202 }
1203 }
1204 }
1205 last_number = opt_iter.number;
1206 }
1207overflow:
1208 return ok;
1209}
1210
1212coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
1213 coap_mid_t mid;
1214
1216 mid = coap_send_rst_lkd(session, request);
1218 return mid;
1219}
1220
1223 if (request->type == COAP_MESSAGE_CON || request->type == COAP_MESSAGE_NON)
1224 return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
1225 return COAP_INVALID_MID;
1226}
1227
1229coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
1230 coap_mid_t mid;
1231
1233 mid = coap_send_ack_lkd(session, request);
1235 return mid;
1236}
1237
1240 coap_pdu_t *response;
1242
1244 if (request && request->type == COAP_MESSAGE_CON &&
1245 COAP_PROTO_NOT_RELIABLE(session->proto)) {
1246 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
1247 if (response)
1248 result = coap_send_internal(session, response, NULL);
1249 }
1250 return result;
1251}
1252
1253ssize_t
1255 ssize_t bytes_written = -1;
1256 assert(pdu->hdr_size > 0);
1257
1258 /* Caller handles partial writes */
1259 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1260 pdu->token - pdu->hdr_size,
1261 pdu->used_size + pdu->hdr_size);
1263 return bytes_written;
1264}
1265
1266static ssize_t
1268 ssize_t bytes_written;
1269
1270 if (session->state == COAP_SESSION_STATE_NONE) {
1271#if ! COAP_CLIENT_SUPPORT
1272 return -1;
1273#else /* COAP_CLIENT_SUPPORT */
1274 if (session->type != COAP_SESSION_TYPE_CLIENT)
1275 return -1;
1276#endif /* COAP_CLIENT_SUPPORT */
1277 }
1278
1279 if (pdu->type == COAP_MESSAGE_CON &&
1280 (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1281 coap_is_mcast(&session->addr_info.remote)) {
1282 /* Violates RFC72522 8.1 */
1283 coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1284 return -1;
1285 }
1286
1287 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1288 (pdu->type == COAP_MESSAGE_CON &&
1289 session->con_active >= COAP_NSTART(session))) {
1290 return coap_session_delay_pdu(session, pdu, node);
1291 }
1292
1293 if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1294 (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1295 return coap_session_delay_pdu(session, pdu, node);
1296
1297 bytes_written = coap_session_send_pdu(session, pdu);
1298 if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1300 session->con_active++;
1301
1302 return bytes_written;
1303}
1304
1307 const coap_pdu_t *request,
1308 coap_pdu_code_t code,
1309 coap_opt_filter_t *opts) {
1310 coap_mid_t mid;
1311
1313 mid = coap_send_error_lkd(session, request, code, opts);
1315 return mid;
1316}
1317
1320 const coap_pdu_t *request,
1321 coap_pdu_code_t code,
1322 coap_opt_filter_t *opts) {
1323 coap_pdu_t *response;
1325
1326 assert(request);
1327 assert(session);
1328
1329 response = coap_new_error_response(request, code, opts);
1330 if (response)
1331 result = coap_send_internal(session, response, NULL);
1332
1333 return result;
1334}
1335
1338 coap_pdu_type_t type) {
1339 coap_mid_t mid;
1340
1342 mid = coap_send_message_type_lkd(session, request, type);
1344 return mid;
1345}
1346
1349 coap_pdu_type_t type) {
1350 coap_pdu_t *response;
1352
1354 if (request && COAP_PROTO_NOT_RELIABLE(session->proto) &&
1355 !(type == COAP_MESSAGE_RST && coap_is_mcast(&session->addr_info.local))) {
1356 response = coap_pdu_init(type, 0, request->mid, 0);
1357 if (response)
1358 result = coap_send_internal(session, response, NULL);
1359 }
1360 return result;
1361}
1362
1376unsigned int
1377coap_calc_timeout(coap_session_t *session, unsigned char r) {
1378 unsigned int result;
1379
1380 /* The integer 1.0 as a Qx.FRAC_BITS */
1381#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1382
1383 /* rounds val up and right shifts by frac positions */
1384#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1385
1386 /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1387 * make the result a rounded Qx.FRAC_BITS */
1388 result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1389
1390 /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1391 * make the result a rounded Qx.FRAC_BITS */
1392 result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1393
1394 /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1395 * (yields a Qx.FRAC_BITS) and shift to get an integer */
1396 return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1397
1398#undef FP1
1399#undef SHR_FP
1400}
1401
1404 coap_queue_t *node) {
1405 coap_tick_t now;
1406
1407 node->session = coap_session_reference_lkd(session);
1408
1409 /* Set timer for pdu retransmission. If this is the first element in
1410 * the retransmission queue, the base time is set to the current
1411 * time and the retransmission time is node->timeout. If there is
1412 * already an entry in the sendqueue, we must check if this node is
1413 * to be retransmitted earlier. Therefore, node->timeout is first
1414 * normalized to the base time and then inserted into the queue with
1415 * an adjusted relative time.
1416 */
1417 coap_ticks(&now);
1418 if (context->sendqueue == NULL) {
1419 node->t = node->timeout << node->retransmit_cnt;
1420 context->sendqueue_basetime = now;
1421 } else {
1422 /* make node->t relative to context->sendqueue_basetime */
1423 node->t = (now - context->sendqueue_basetime) +
1424 (node->timeout << node->retransmit_cnt);
1425 }
1426 coap_address_copy(&node->remote, &session->addr_info.remote);
1427
1428 coap_insert_node(&context->sendqueue, node);
1429
1430 coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1431 coap_session_str(node->session), node->id,
1432 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1434
1435 coap_update_io_timer(context, node->t);
1436
1437 return node->id;
1438}
1439
1440#if COAP_CLIENT_SUPPORT
1441/*
1442 * Sent out a test PDU for Extended Token
1443 */
1444static coap_mid_t
1445coap_send_test_extended_token(coap_session_t *session) {
1446 coap_pdu_t *pdu;
1448 size_t i;
1449 coap_binary_t *token;
1450 coap_lg_crcv_t *lg_crcv;
1451
1452 coap_log_debug("Testing for Extended Token support\n");
1453 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1455 coap_new_message_id_lkd(session),
1457 if (!pdu)
1458 return COAP_INVALID_MID;
1459
1460 token = coap_new_binary(session->max_token_size);
1461 if (token == NULL) {
1463 return COAP_INVALID_MID;
1464 }
1465 for (i = 0; i < session->max_token_size; i++) {
1466 token->s[i] = (uint8_t)(i + 1);
1467 }
1468 coap_add_token(pdu, session->max_token_size, token->s);
1469 coap_delete_binary(token);
1470
1473 pdu->actual_token.length);
1474
1476
1477 session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1478
1479 /* Need to track in case OSCORE / Echo etc. comes back after non-piggy-backed ACK */
1480 lg_crcv = coap_block_new_lg_crcv(session, pdu, NULL);
1481 if (lg_crcv) {
1482 LL_PREPEND(session->lg_crcv, lg_crcv);
1483 }
1484 mid = coap_send_internal(session, pdu, NULL);
1485 if (mid == COAP_INVALID_MID)
1486 return COAP_INVALID_MID;
1487 session->remote_test_mid = mid;
1488 return mid;
1489}
1490#endif /* COAP_CLIENT_SUPPORT */
1491
1492/*
1493 * Return: 0 Something failed
1494 * 1 Success
1495 */
1496int
1498#if COAP_CLIENT_SUPPORT
1499 if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1500 int timeout_ms = 5000;
1501 coap_session_state_t current_state = session->state;
1502
1503 if (session->delay_recursive) {
1504 return 0;
1505 } else {
1506 session->delay_recursive = 1;
1507 }
1508 /*
1509 * Need to wait for first request to get out and response back before
1510 * continuing.. Response handler has to clear doing_first if not an error.
1511 */
1513 while (session->doing_first != 0) {
1514 int result = coap_io_process_lkd(session->context, 1000);
1515
1516 if (result < 0) {
1517 coap_reset_doing_first(session);
1518 session->delay_recursive = 0;
1519 coap_session_release_lkd(session);
1520 return 0;
1521 }
1522
1523 /* coap_io_process_lkd() may have updated session state */
1524 if (session->state == COAP_SESSION_STATE_CSM &&
1525 current_state != COAP_SESSION_STATE_CSM) {
1526 /* Update timeout and restart the clock for CSM timeout */
1527 current_state = COAP_SESSION_STATE_CSM;
1528 timeout_ms = session->context->csm_timeout_ms;
1529 result = 0;
1530 }
1531
1532 if (result < timeout_ms) {
1533 timeout_ms -= result;
1534 } else {
1535 if (session->doing_first == 1) {
1536 /* Timeout failure of some sort with first request */
1537 if (session->state == COAP_SESSION_STATE_CSM) {
1538 coap_log_debug("** %s: timeout waiting for CSM response\n",
1539 coap_session_str(session));
1540 session->csm_not_seen = 1;
1541 } else {
1542 coap_log_debug("** %s: timeout waiting for first response\n",
1543 coap_session_str(session));
1544 }
1545 coap_reset_doing_first(session);
1546 coap_session_connected(session);
1547 }
1548 }
1549 }
1550 session->delay_recursive = 0;
1551 coap_session_release_lkd(session);
1552 }
1553#else /* ! COAP_CLIENT_SUPPORT */
1554 (void)session;
1555#endif /* ! COAP_CLIENT_SUPPORT */
1556 return 1;
1557}
1558
1559/*
1560 * return 0 Invalid
1561 * 1 Valid
1562 */
1563int
1565
1566 /* Check validity of sending code */
1567 switch (COAP_RESPONSE_CLASS(pdu->code)) {
1568 case 0: /* Empty or request */
1569 case 2: /* Success */
1570 case 3: /* Reserved for future use */
1571 case 4: /* Client error */
1572 case 5: /* Server error */
1573 break;
1574 case 7: /* Reliable signalling */
1575 if (COAP_PROTO_RELIABLE(session->proto))
1576 break;
1577 /* Not valid if UDP */
1578 /* Fall through */
1579 case 1: /* Invalid */
1580 case 6: /* Invalid */
1581 default:
1582 return 0;
1583 }
1584 return 1;
1585}
1586
1587#if COAP_CLIENT_SUPPORT
1588/*
1589 * If type is CON and protocol is not reliable, there is no need to set up
1590 * lg_crcv if it can be built up based on sent PDU if there is a
1591 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1592 * (Q-)Block1.
1593 */
1594static int
1595coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1596 coap_opt_iterator_t opt_iter;
1597
1598 if (!COAP_PDU_IS_REQUEST(pdu))
1599 return 0;
1600
1601 if (
1602#if COAP_OSCORE_SUPPORT
1603 session->oscore_encryption ||
1604#endif /* COAP_OSCORE_SUPPORT */
1605 pdu->type == COAP_MESSAGE_NON ||
1606 COAP_PROTO_RELIABLE(session->proto) ||
1607 coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1608#if COAP_Q_BLOCK_SUPPORT
1609 coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1610#endif /* COAP_Q_BLOCK_SUPPORT */
1611 coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1612 return 1;
1613 }
1614 return 0;
1615}
1616#endif /* COAP_CLIENT_SUPPORT */
1617
1620 coap_mid_t mid;
1621
1623 mid = coap_send_lkd(session, pdu);
1625 return mid;
1626}
1627
1631#if COAP_CLIENT_SUPPORT
1632 coap_lg_crcv_t *lg_crcv = NULL;
1633 coap_opt_iterator_t opt_iter;
1634 coap_block_b_t block;
1635 int observe_action = -1;
1636 int have_block1 = 0;
1637 coap_opt_t *opt;
1638#endif /* COAP_CLIENT_SUPPORT */
1639
1640 assert(pdu);
1641
1643
1644 /* Check validity of sending code */
1645 if (!coap_check_code_class(session, pdu)) {
1646 coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1648 pdu->code & 0x1f);
1649 goto error;
1650 }
1651 pdu->session = session;
1652#if COAP_CLIENT_SUPPORT
1653 if (session->type == COAP_SESSION_TYPE_CLIENT &&
1654 !coap_netif_available(session) && !session->session_failed) {
1655 coap_log_debug("coap_send: Socket closed\n");
1656 goto error;
1657 }
1658
1659 if (session->doing_first) {
1660 LL_APPEND(session->doing_first_pdu, pdu);
1662 coap_log_debug("** %s: mid=0x%04x: queued\n",
1663 coap_session_str(session), pdu->mid);
1664 return pdu->mid;
1665 }
1666
1667 /* Indicate support for Extended Tokens if appropriate */
1668 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1670 session->type == COAP_SESSION_TYPE_CLIENT &&
1671 COAP_PDU_IS_REQUEST(pdu)) {
1672 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1673 /*
1674 * When the pass / fail response for Extended Token is received, this PDU
1675 * will get transmitted.
1676 */
1677 if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1678 goto error;
1679 }
1680 }
1681 /*
1682 * For reliable protocols, this will get cleared after CSM exchanged
1683 * in coap_session_connected() where Token size support is indicated in the CSM.
1684 */
1685 session->doing_first = 1;
1686 coap_ticks(&session->doing_first_timeout);
1687 LL_PREPEND(session->doing_first_pdu, pdu);
1688 if (session->proto != COAP_PROTO_UDP) {
1689 /* In case the next handshake / CSM is already in */
1691 }
1692 /*
1693 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1694 * will get called again.
1695 */
1697 coap_log_debug("** %s: mid=0x%04x: queued\n",
1698 coap_session_str(session), pdu->mid);
1699 return pdu->mid;
1700 }
1701#if COAP_Q_BLOCK_SUPPORT
1702 /* Indicate support for Q-Block if appropriate */
1703 if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1704 session->type == COAP_SESSION_TYPE_CLIENT &&
1705 COAP_PDU_IS_REQUEST(pdu)) {
1706 if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1707 goto error;
1708 }
1709 session->doing_first = 1;
1710 coap_ticks(&session->doing_first_timeout);
1711 LL_PREPEND(session->doing_first_pdu, pdu);
1712 if (session->proto != COAP_PROTO_UDP) {
1713 /* In case the next handshake / CSM is already in */
1715 }
1716 /*
1717 * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1718 * will get called again.
1719 */
1721 coap_log_debug("** %s: mid=0x%04x: queued\n",
1722 coap_session_str(session), pdu->mid);
1723 return pdu->mid;
1724 }
1725#endif /* COAP_Q_BLOCK_SUPPORT */
1726
1727 /*
1728 * Check validity of token length
1729 */
1730 if (COAP_PDU_IS_REQUEST(pdu) &&
1731 pdu->actual_token.length > session->max_token_size) {
1732 coap_log_warn("coap_send: PDU dropped as token too long (%" PRIuS " > %" PRIu32 ")\n",
1733 pdu->actual_token.length, session->max_token_size);
1734 goto error;
1735 }
1736
1737 /* A lot of the reliable code assumes type is CON */
1738 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1739 pdu->type = COAP_MESSAGE_CON;
1740
1741#if COAP_OSCORE_SUPPORT
1742 if (session->oscore_encryption) {
1743 if (session->recipient_ctx->initial_state == 1 &&
1744 !session->recipient_ctx->silent_server) {
1745 /*
1746 * Not sure if remote supports OSCORE, or is going to send us a
1747 * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1748 * is OK. Continue sending current pdu to test things.
1749 */
1750 session->doing_first = 1;
1751 }
1752 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1754 goto error;
1755 }
1756 }
1757#endif /* COAP_OSCORE_SUPPORT */
1758
1759 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1760 return coap_send_internal(session, pdu, NULL);
1761 }
1762
1763 if (session->no_path_abbrev) {
1764 opt = coap_check_option(pdu, COAP_OPTION_URI_PATH_ABB, &opt_iter);
1765 if (opt) {
1766 /* Server cannot handle Uri-Path-Abbrev */
1767 coap_pdu_t *new;
1768 size_t data_len;
1769 const uint8_t *data;
1770
1771 new = coap_pdu_duplicate_lkd(pdu, session, pdu->actual_token.length,
1773 if (new) {
1774 if (coap_get_data(pdu, &data_len, &data)) {
1775 coap_add_data(pdu, data_len, data);
1776 }
1777 coap_log_debug("* Retransmitting PDU with Uri-Path-Abbrev replaced (3)\n");
1779 pdu = new;
1780 }
1781 }
1782 }
1783
1784 if (COAP_PDU_IS_REQUEST(pdu)) {
1785 uint8_t buf[4];
1786
1787 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1788
1789 if (opt) {
1790 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1791 coap_opt_length(opt));
1792 }
1793
1794 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1795 (block.m == 1 || block.bert == 1)) {
1796 have_block1 = 1;
1797 }
1798#if COAP_Q_BLOCK_SUPPORT
1799 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1800 (block.m == 1 || block.bert == 1)) {
1801 if (have_block1) {
1802 coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1804 }
1805 have_block1 = 1;
1806 }
1807#endif /* COAP_Q_BLOCK_SUPPORT */
1808 if (observe_action != COAP_OBSERVE_CANCEL) {
1809 /* Warn about reuse of tokens */
1810 if (session->last_token &&
1811 coap_binary_equal(&pdu->actual_token, session->last_token)) {
1813 char scratch[24];
1814 size_t size;
1815 size_t i;
1816
1817 scratch[0] = '\000';
1818 for (i = 0; i < pdu->actual_token.length; i++) {
1819 size = strlen(scratch);
1820 snprintf(&scratch[size], sizeof(scratch)-size,
1821 "%02x", pdu->actual_token.s[i]);
1822 }
1823 coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1824 scratch);
1825 }
1826 }
1829 pdu->actual_token.length);
1830 } else {
1831 /* observe_action == COAP_OBSERVE_CANCEL */
1832 coap_binary_t tmp;
1833 int ret;
1834
1835 coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1836 /* Unfortunately need to change the ptr type to be r/w */
1837 memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1838 tmp.length = pdu->actual_token.length;
1839 ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1840 if (ret == 1) {
1841 /* Observe Cancel successfully sent */
1843 return ret;
1844 }
1845 /* Some mismatch somewhere - continue to send original packet */
1846 }
1847 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1848 (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1852 coap_encode_var_safe(buf, sizeof(buf),
1853 ++session->tx_rtag),
1854 buf);
1855 } else {
1856 memset(&block, 0, sizeof(block));
1857 }
1858
1859#if COAP_Q_BLOCK_SUPPORT
1860 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1861#endif /* COAP_Q_BLOCK_SUPPORT */
1862 {
1863 /* Need to check if we need to reset Q-Block to Block */
1864 uint8_t buf[4];
1865
1866 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1869 coap_encode_var_safe(buf, sizeof(buf),
1870 (block.num << 4) | (0 << 3) | block.szx),
1871 buf);
1872 coap_log_debug("Replaced option Q-Block2 with Block2\n");
1873 /* Need to update associated lg_xmit */
1874 coap_lg_xmit_t *lg_xmit;
1875
1876 LL_FOREACH(session->lg_xmit, lg_xmit) {
1877 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1878 lg_xmit->b.b1.app_token &&
1879 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1880 /* Update the skeletal PDU with the block1 option */
1883 coap_encode_var_safe(buf, sizeof(buf),
1884 (block.num << 4) | (0 << 3) | block.szx),
1885 buf);
1886 break;
1887 }
1888 }
1889 }
1890 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1893 coap_encode_var_safe(buf, sizeof(buf),
1894 (block.num << 4) | (block.m << 3) | block.szx),
1895 buf);
1896 coap_log_debug("Replaced option Q-Block1 with Block1\n");
1897 /* Need to update associated lg_xmit */
1898 coap_lg_xmit_t *lg_xmit;
1899
1900 LL_FOREACH(session->lg_xmit, lg_xmit) {
1901 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1902 lg_xmit->b.b1.app_token &&
1903 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1904 /* Update the skeletal PDU with the block1 option */
1907 coap_encode_var_safe(buf, sizeof(buf),
1908 (block.num << 4) |
1909 (block.m << 3) |
1910 block.szx),
1911 buf);
1912 /* Update as this is a Request */
1913 lg_xmit->option = COAP_OPTION_BLOCK1;
1914 break;
1915 }
1916 }
1917 }
1918 }
1919
1920#if COAP_Q_BLOCK_SUPPORT
1921 if (COAP_PDU_IS_REQUEST(pdu) &&
1922 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1923 if (block.num == 0 && block.m == 0) {
1924 uint8_t buf[4];
1925
1926 /* M needs to be set as asking for all the blocks */
1928 coap_encode_var_safe(buf, sizeof(buf),
1929 (0 << 4) | (1 << 3) | block.szx),
1930 buf);
1931 }
1932 }
1933#endif /* COAP_Q_BLOCK_SUPPORT */
1934
1935 /*
1936 * If type is CON and protocol is not reliable, there is no need to set up
1937 * lg_crcv here as it can be built up based on sent PDU if there is a
1938 * (Q-)Block2 in the response. However, still need it for Observe, Oscore and
1939 * (Q-)Block1.
1940 */
1941 if (coap_check_send_need_lg_crcv(session, pdu)) {
1942 coap_lg_xmit_t *lg_xmit = NULL;
1943
1944 if (!session->lg_xmit && have_block1) {
1945 coap_log_debug("PDU presented by app\n");
1947 }
1948 /* See if this token is already in use for large body responses */
1949 LL_FOREACH(session->lg_crcv, lg_crcv) {
1950 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1951 /* Need to terminate and clean up previous response setup */
1952 LL_DELETE(session->lg_crcv, lg_crcv);
1953 coap_block_delete_lg_crcv(session, lg_crcv);
1954 break;
1955 }
1956 }
1957
1958 if (have_block1 && session->lg_xmit) {
1959 LL_FOREACH(session->lg_xmit, lg_xmit) {
1960 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1961 lg_xmit->b.b1.app_token &&
1962 coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1963 break;
1964 }
1965 }
1966 }
1967 lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1968 if (lg_crcv == NULL) {
1969 goto error;
1970 }
1971 if (lg_xmit) {
1972 /* Need to update the token as set up in the session->lg_xmit */
1973 lg_xmit->b.b1.state_token = lg_crcv->state_token;
1974 }
1975 }
1976 if (session->sock.flags & COAP_SOCKET_MULTICAST)
1977 coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1978
1979#if COAP_Q_BLOCK_SUPPORT
1980 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1981 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1982 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1983 } else
1984#endif /* COAP_Q_BLOCK_SUPPORT */
1985 mid = coap_send_internal(session, pdu, NULL);
1986#else /* !COAP_CLIENT_SUPPORT */
1987 mid = coap_send_internal(session, pdu, NULL);
1988#endif /* !COAP_CLIENT_SUPPORT */
1989#if COAP_CLIENT_SUPPORT
1990 if (lg_crcv) {
1991 if (mid != COAP_INVALID_MID) {
1992 LL_PREPEND(session->lg_crcv, lg_crcv);
1993 } else {
1994 coap_block_delete_lg_crcv(session, lg_crcv);
1995 }
1996 }
1997#endif /* COAP_CLIENT_SUPPORT */
1998 return mid;
1999
2000error:
2002 return COAP_INVALID_MID;
2003}
2004
2005static int
2007 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
2008 coap_opt_t *opt;
2009 coap_opt_iterator_t opt_iter;
2010 size_t hop_limit;
2011
2012 addr_str[sizeof(addr_str)-1] = '\000';
2013 if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
2014 sizeof(addr_str) - 1)) {
2015 char *cp;
2016 size_t len;
2017
2018 if (addr_str[0] == '[') {
2019 cp = strchr(addr_str, ']');
2020 if (cp)
2021 *cp = '\000';
2022 if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
2023 /* IPv4 embedded into IPv6 */
2024 cp = &addr_str[8];
2025 } else {
2026 cp = &addr_str[1];
2027 }
2028 } else {
2029 cp = strchr(addr_str, ':');
2030 if (cp)
2031 *cp = '\000';
2032 cp = addr_str;
2033 }
2034 len = strlen(cp);
2035
2036 /* See if Hop Limit option is being used in return path */
2037 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2038 if (opt) {
2039 uint8_t buf[4];
2040
2041 hop_limit =
2043 if (hop_limit == 1) {
2044 coap_log_warn("Proxy loop detected '%s'\n",
2045 (char *)pdu->data);
2048 } else if (hop_limit < 1 || hop_limit > 255) {
2049 /* Something is bad - need to drop this pdu (TODO or delete option) */
2050 coap_log_warn("Proxy return has bad hop limit count '%" PRIuS "'\n",
2051 hop_limit);
2053 return 0;
2054 }
2055 hop_limit--;
2057 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2058 buf);
2059 }
2060
2061 /* Need to check that we are not seeing this proxy in the return loop */
2062 if (pdu->data && opt == NULL) {
2063 char *a_match;
2064 size_t data_len;
2065
2066 if (pdu->used_size + 1 > pdu->max_size) {
2067 /* No space */
2069 return 0;
2070 }
2071 if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
2072 /* Internal error */
2074 return 0;
2075 }
2076 data_len = pdu->used_size - (pdu->data - pdu->token);
2077 pdu->data[data_len] = '\000';
2078 a_match = strstr((char *)pdu->data, cp);
2079 if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
2080 ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
2081 a_match[len] == ' ')) {
2082 coap_log_warn("Proxy loop detected '%s'\n",
2083 (char *)pdu->data);
2085 return 0;
2086 }
2087 }
2088 if (pdu->used_size + len + 1 <= pdu->max_size) {
2089 size_t old_size = pdu->used_size;
2090 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
2091 if (pdu->data == NULL) {
2092 /*
2093 * Set Hop Limit to max for return path. If this libcoap is in
2094 * a proxy loop path, it will always decrement hop limit in code
2095 * above and hence timeout / drop the response as appropriate
2096 */
2097 hop_limit = 255;
2099 (uint8_t *)&hop_limit);
2100 coap_add_data(pdu, len, (uint8_t *)cp);
2101 } else {
2102 /* prepend with space separator, leaving hop limit "as is" */
2103 memmove(pdu->data + len + 1, pdu->data,
2104 old_size - (pdu->data - pdu->token));
2105 memcpy(pdu->data, cp, len);
2106 pdu->data[len] = ' ';
2107 pdu->used_size += len + 1;
2108 }
2109 }
2110 }
2111 }
2112 return 1;
2113}
2114
2117 uint8_t r;
2118 ssize_t bytes_written;
2119
2120#if ! COAP_SERVER_SUPPORT
2121 (void)request_pdu;
2122#endif /* COAP_SERVER_SUPPORT */
2123 pdu->session = session;
2124#if COAP_CLIENT_SUPPORT
2125 if (session->session_failed) {
2126 coap_session_reconnect(session);
2127 if (session->session_failed)
2128 goto error;
2129 }
2130#endif /* COAP_CLIENT_SUPPORT */
2131 if (pdu->type == COAP_MESSAGE_NON && session->rl_ticks_per_packet) {
2132 coap_tick_t now;
2133
2134 if (!session->is_rate_limiting) {
2135 coap_ticks(&now);
2136#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
2137 if (now - session->last_tx < session->rl_ticks_per_packet) {
2138 uint32_t rem = (uint32_t)(session->rl_ticks_per_packet -
2139 (now - session->last_tx)) * 1000 / COAP_TICKS_PER_SECOND;
2140 coap_log_debug("** %s: mid 0x%04x: delaying transmission (%" PRIu32 ".%03" PRIu32 "s)\n",
2141 coap_session_str(session), pdu->mid, rem / 1000, rem %1000);
2143 }
2144#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
2145 while (1) {
2146 uint32_t timeout_ms;
2147
2148 if (send_recv_terminate) {
2149 goto error;
2150 }
2151
2152 if (now - session->last_tx >= session->rl_ticks_per_packet) {
2153 break;
2154 }
2155 timeout_ms = (uint32_t)(((session->rl_ticks_per_packet - (now - session->last_tx)) *
2156 1000) / COAP_TICKS_PER_SECOND);
2157
2158 if (timeout_ms == 0) {
2159 timeout_ms = COAP_IO_NO_WAIT;
2160 }
2161
2162 session->is_rate_limiting = 1;
2163 coap_io_process_lkd(session->context, timeout_ms);
2164 session->is_rate_limiting = 0;
2165 coap_ticks(&now);
2166 }
2167 coap_log_debug("** %s: mid 0x%04x: now transmitting\n",
2168 coap_session_str(session), pdu->mid);
2169 session->last_tx = now;
2170 }
2171 }
2172#if COAP_PROXY_SUPPORT
2173 if (session->server_list) {
2174 /* Local session wanting to use proxy logic */
2175 return coap_proxy_local_write(session, pdu);
2176 }
2177#endif /* COAP_PROXY_SUPPORT */
2178 if (pdu->code == COAP_RESPONSE_CODE(508)) {
2179 /*
2180 * Need to prepend our IP identifier to the data as per
2181 * https://rfc-editor.org/rfc/rfc8768.html#section-4
2182 */
2183 if (!prepend_508_ip(session, pdu)) {
2185 }
2186 }
2187
2188 if (session->echo) {
2189 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
2190 session->echo->s))
2191 goto error;
2192 coap_delete_bin_const(session->echo);
2193 session->echo = NULL;
2194 }
2195#if COAP_OSCORE_SUPPORT
2196 if (session->oscore_encryption) {
2197 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
2199 goto error;
2200 }
2201#endif /* COAP_OSCORE_SUPPORT */
2202
2203 if (!coap_pdu_encode_header(pdu, session->proto)) {
2204 goto error;
2205 }
2206
2207#if !COAP_DISABLE_TCP
2208 if (COAP_PROTO_RELIABLE(session->proto) &&
2210 coap_opt_iterator_t opt_iter;
2211
2212 if (!session->csm_block_supported) {
2213 /*
2214 * Need to check that this instance is not sending any block options as
2215 * the remote end via CSM has not informed us that there is support
2216 * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2217 * This includes potential BERT blocks.
2218 */
2219 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2220 coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2221 }
2222 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2223 coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2224 }
2225 } else if (!session->csm_bert_rem_support) {
2226 coap_opt_t *opt;
2227
2228 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2229 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2230 coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2231 }
2232 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2233 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2234 coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2235 }
2236 }
2237 }
2238#endif /* !COAP_DISABLE_TCP */
2239
2240#if COAP_OSCORE_SUPPORT
2241 if (session->oscore_encryption &&
2242 pdu->type != COAP_MESSAGE_RST &&
2243 !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2244 !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2245 /* Refactor PDU as appropriate RFC8613 */
2246 coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2247
2248 if (osc_pdu == NULL) {
2249 coap_log_warn("OSCORE: PDU could not be encrypted\n");
2252 goto error;
2253 }
2254 bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2256 pdu = osc_pdu;
2257 } else
2258#endif /* COAP_OSCORE_SUPPORT */
2259 bytes_written = coap_send_pdu(session, pdu, NULL);
2260
2261#if COAP_SERVER_SUPPORT
2262 if (session->last_resp_pdu != pdu &&
2263 request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2264 COAP_PDU_IS_REQUEST(request_pdu) &&
2265 COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2266 coap_delete_pdu_lkd(session->last_resp_pdu);
2267 session->last_resp_pdu = pdu;
2268 coap_pdu_reference_lkd(session->last_resp_pdu);
2269 }
2270#endif /* COAP_SERVER_SUPPORT */
2271
2272 if (bytes_written == COAP_PDU_DELAYED) {
2273 /* do not free pdu as it is stored with session for later use */
2274 return pdu->mid;
2275 }
2276 if (bytes_written < 0) {
2277 if (pdu->code != 0)
2279 goto error;
2280 }
2281
2282#if !COAP_DISABLE_TCP
2283 if (COAP_PROTO_RELIABLE(session->proto) &&
2284 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2285 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2286 session->partial_write = (size_t)bytes_written;
2287 /* do not free pdu as it is stored with session for later use */
2288 return pdu->mid;
2289 } else {
2290 goto error;
2291 }
2292 }
2293#endif /* !COAP_DISABLE_TCP */
2294
2295 if (pdu->type != COAP_MESSAGE_CON
2296 || COAP_PROTO_RELIABLE(session->proto)) {
2297 coap_mid_t id = pdu->mid;
2299 return id;
2300 }
2301
2302 coap_queue_t *node = coap_new_node();
2303 if (!node) {
2304 coap_log_debug("coap_wait_ack: insufficient memory\n");
2305 goto error;
2306 }
2307
2308 node->id = pdu->mid;
2309 node->pdu = pdu;
2310 coap_prng_lkd(&r, sizeof(r));
2311 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2312 node->timeout = coap_calc_timeout(session, r);
2313 return coap_wait_ack(session->context, session, node);
2314error:
2316 return COAP_INVALID_MID;
2317}
2318
2319void
2323
2324COAP_API int
2326 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2327 int ret;
2328
2329 coap_lock_lock(return 0);
2330 ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2332 return ret;
2333}
2334
2335/*
2336 * Return 0 or +ve Time in function in ms after successful transfer
2337 * -1 Invalid timeout parameter
2338 * -2 Failed to transmit PDU
2339 * -3 Nack or Event handler invoked, cancelling request
2340 * -4 coap_io_process returned error (fail to re-lock or select())
2341 * -5 Response not received in the given time
2342 * -6 Terminated by user
2343 * -7 Client mode code not enabled
2344 */
2345int
2347 coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2348#if COAP_CLIENT_SUPPORT
2350 uint32_t rem_timeout = timeout_ms;
2351 uint32_t block_mode = session->block_mode;
2352 int ret = 0;
2353 coap_tick_t now;
2354 coap_tick_t start;
2355 coap_tick_t ticks_so_far;
2356 uint32_t time_so_far_ms;
2357
2358 coap_ticks(&start);
2359 assert(request_pdu);
2360
2362
2363 session->resp_pdu = NULL;
2364 session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2365 request_pdu->actual_token.length);
2366
2367 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2368 ret = -1;
2369 goto fail;
2370 }
2371 if (session->state == COAP_SESSION_STATE_NONE) {
2372 ret = -3;
2373 goto fail;
2374 }
2375
2377 if (coap_is_mcast(&session->addr_info.remote))
2378 block_mode = session->block_mode;
2379
2380 session->doing_send_recv = 1;
2381 /* So the user needs to delete the PDU */
2382 coap_pdu_reference_lkd(request_pdu);
2383 mid = coap_send_lkd(session, request_pdu);
2384 if (mid == COAP_INVALID_MID) {
2385 if (!session->doing_send_recv)
2386 ret = -3;
2387 else
2388 ret = -2;
2389 goto fail;
2390 }
2391
2392 /* Wait for the response to come in */
2393 while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2394 if (send_recv_terminate) {
2395 ret = -6;
2396 goto fail;
2397 }
2398 ret = coap_io_process_lkd(session->context, rem_timeout);
2399 if (ret < 0) {
2400 ret = -4;
2401 goto fail;
2402 }
2403 /* timeout_ms is for timeout between specific request and response */
2404 coap_ticks(&now);
2405 ticks_so_far = now - session->last_rx_tx;
2406 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2407 if (time_so_far_ms >= timeout_ms) {
2408 rem_timeout = 0;
2409 } else {
2410 rem_timeout = timeout_ms - time_so_far_ms;
2411 }
2412 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2413 /* To pick up on (D)TLS setup issues */
2414 coap_ticks(&now);
2415 ticks_so_far = now - start;
2416 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2417 if (time_so_far_ms >= timeout_ms) {
2418 rem_timeout = 0;
2419 } else {
2420 rem_timeout = timeout_ms - time_so_far_ms;
2421 }
2422 }
2423 }
2424
2425 if (rem_timeout) {
2426 coap_ticks(&now);
2427 ticks_so_far = now - start;
2428 time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2429 ret = time_so_far_ms;
2430 /* Give PDU to user who will be calling coap_delete_pdu() */
2431 *response_pdu = session->resp_pdu;
2432 session->resp_pdu = NULL;
2433 if (*response_pdu == NULL) {
2434 ret = -3;
2435 }
2436 } else {
2437 /* If there is a resp_pdu, it will get cleared below */
2438 ret = -5;
2439 }
2440
2441fail:
2442 session->block_mode = block_mode;
2443 session->doing_send_recv = 0;
2444 /* delete referenced copy */
2445 coap_delete_pdu_lkd(session->resp_pdu);
2446 session->resp_pdu = NULL;
2447 coap_delete_bin_const(session->req_token);
2448 session->req_token = NULL;
2449 return ret;
2450
2451#else /* !COAP_CLIENT_SUPPORT */
2452
2453 (void)session;
2454 (void)timeout_ms;
2455 (void)request_pdu;
2456 coap_log_warn("coap_send_recv: Client mode not supported\n");
2457 *response_pdu = NULL;
2458 return -7;
2459
2460#endif /* ! COAP_CLIENT_SUPPORT */
2461}
2462
2465 if (!context || !node || !node->session)
2466 return COAP_INVALID_MID;
2467
2468#if COAP_CLIENT_SUPPORT
2469 if (node->session->session_failed) {
2470 /* Force failure */
2471 node->retransmit_cnt = (unsigned char)node->session->max_retransmit;
2472 }
2473#endif /* COAP_CLIENT_SUPPORT */
2474
2475 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2476 if (node->retransmit_cnt < node->session->max_retransmit) {
2477 ssize_t bytes_written;
2478 coap_tick_t now;
2479 coap_tick_t next_delay;
2480 coap_address_t remote;
2481
2482 node->retransmit_cnt++;
2484
2485 next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2486 if (context->ping_timeout &&
2487 context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2488 uint8_t byte;
2489
2490 coap_prng_lkd(&byte, sizeof(byte));
2491 /* Don't exceed the ping timeout value */
2492 next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2493 }
2494
2495 coap_ticks(&now);
2496 if (context->sendqueue == NULL) {
2497 node->t = next_delay;
2498 context->sendqueue_basetime = now;
2499 } else {
2500 /* make node->t relative to context->sendqueue_basetime */
2501 node->t = (now - context->sendqueue_basetime) + next_delay;
2502 }
2503 coap_insert_node(&context->sendqueue, node);
2504 coap_address_copy(&remote, &node->session->addr_info.remote);
2506
2507 if (node->is_mcast) {
2508 coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2509 coap_session_str(node->session), node->id);
2510 } else {
2511 coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2512 coap_session_str(node->session), node->id,
2513 node->retransmit_cnt,
2514 (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2515 }
2516
2517 if (node->session->con_active)
2518 node->session->con_active--;
2519 bytes_written = coap_send_pdu(node->session, node->pdu, node);
2520
2521 if (bytes_written == COAP_PDU_DELAYED) {
2522 /* PDU was not retransmitted immediately because a new handshake is
2523 in progress. node was moved to the send queue of the session. */
2524 return node->id;
2525 }
2526
2527 coap_address_copy(&node->session->addr_info.remote, &remote);
2528 if (node->is_mcast) {
2531 return COAP_INVALID_MID;
2532 }
2533
2534 if (bytes_written < 0)
2535 return (int)bytes_written;
2536
2537 return node->id;
2538 }
2539
2540#if COAP_CLIENT_SUPPORT
2541 if (node->session->session_failed) {
2542 coap_log_info("** %s: mid=0x%04x: deleted due to reconnection issue\n",
2543 coap_session_str(node->session), node->id);
2544 } else {
2545#endif /* COAP_CLIENT_SUPPORT */
2546 /* no more retransmissions, remove node from system */
2547 coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2548 coap_session_str(node->session), node->id, node->retransmit_cnt);
2549#if COAP_CLIENT_SUPPORT
2550 }
2551#endif /* COAP_CLIENT_SUPPORT */
2552
2553#if COAP_SERVER_SUPPORT
2554 /* Check if subscriptions exist that should be canceled after
2555 COAP_OBS_MAX_FAIL */
2556 if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2557 (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2558 if (context->ping_timeout) {
2561 return COAP_INVALID_MID;
2562 } else {
2563 if (node->session->ref_subscriptions)
2564 coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2565#if COAP_PROXY_SUPPORT
2566 /* Need to check is there is a proxy subscription active and delete it */
2567 if (node->session->ref_proxy_subs)
2568 coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2569 0, COAP_PROXY_SUBS_TOKEN);
2570#endif /* COAP_PROXY_SUPPORT */
2571 }
2572 }
2573#endif /* COAP_SERVER_SUPPORT */
2574 if (node->session->con_active) {
2575 node->session->con_active--;
2577 /*
2578 * As there may be another CON in a different queue entry on the same
2579 * session that needs to be immediately released,
2580 * coap_session_connected() is called.
2581 * However, there is the possibility coap_wait_ack() may be called for
2582 * this node (queue) and re-added to context->sendqueue.
2583 * coap_delete_node_lkd(node) called shortly will handle this and
2584 * remove it.
2585 */
2587 }
2588 }
2589
2590 if (node->pdu->type == COAP_MESSAGE_CON) {
2592 }
2593#if COAP_CLIENT_SUPPORT
2594 node->session->doing_send_recv = 0;
2595#endif /* COAP_CLIENT_SUPPORT */
2596 /* And finally delete the node */
2598 return COAP_INVALID_MID;
2599}
2600
2601static int
2603 uint8_t *data;
2604 size_t data_len;
2605 int result = -1;
2606
2607 coap_packet_get_memmapped(packet, &data, &data_len);
2608 if (session->proto == COAP_PROTO_DTLS) {
2609#if COAP_SERVER_SUPPORT
2610 if (session->type == COAP_SESSION_TYPE_HELLO)
2611 result = coap_dtls_hello(session, data, data_len);
2612 else
2613#endif /* COAP_SERVER_SUPPORT */
2614 if (session->tls)
2615 result = coap_dtls_receive(session, data, data_len);
2616 } else if (session->proto == COAP_PROTO_UDP) {
2617 result = coap_handle_dgram(ctx, session, data, data_len);
2618 }
2619 return result;
2620}
2621
2622#if COAP_CLIENT_SUPPORT
2623void
2625#if COAP_DISABLE_TCP
2626 (void)now;
2627
2629#else /* !COAP_DISABLE_TCP */
2630 if (coap_netif_strm_connect2(session)) {
2631 session->last_rx_tx = now;
2633 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2634 } else {
2637 }
2638#endif /* !COAP_DISABLE_TCP */
2639}
2640#endif /* COAP_CLIENT_SUPPORT */
2641
2642static void
2644 coap_queue_t *q;
2645
2646 (void)ctx;
2647 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2648
2649 while ((q = coap_remove_first_from_delayq(session)) != NULL) {
2650 ssize_t bytes_written;
2651
2652 coap_address_copy(&session->addr_info.remote, &q->remote);
2653 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2654 coap_session_str(session), (int)q->id);
2655 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2656 bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2657 q->pdu->token - q->pdu->hdr_size + session->partial_write,
2658 q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2659 if (bytes_written > 0)
2660 session->last_rx_tx = now;
2661 if (bytes_written <= 0 ||
2662 (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2663 if (bytes_written > 0)
2664 session->partial_write += (size_t)bytes_written;
2665 coap_add_to_head_delayq(session, q);
2666 break;
2667 }
2668 session->partial_write = 0;
2670 }
2671}
2672
2673void
2675#if COAP_CONSTRAINED_STACK
2676 /* payload and packet can be protected by global_lock if needed */
2677 static unsigned char payload[COAP_RXBUFFER_SIZE];
2678 static coap_packet_t s_packet;
2679#else /* ! COAP_CONSTRAINED_STACK */
2680 unsigned char payload[COAP_RXBUFFER_SIZE];
2681 coap_packet_t s_packet;
2682#endif /* ! COAP_CONSTRAINED_STACK */
2683 coap_packet_t *packet = &s_packet;
2684
2686
2687 packet->length = sizeof(payload);
2688 packet->payload = payload;
2689
2690 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2691 ssize_t bytes_read;
2692 coap_address_t remote;
2693
2694 coap_address_copy(&remote, &session->addr_info.remote);
2695 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2696 bytes_read = coap_netif_dgrm_read(session, packet);
2697
2698 if (bytes_read < 0) {
2699 if (bytes_read == -2) {
2700 coap_address_copy(&session->addr_info.remote, &remote);
2701 /* Reset the session back to startup defaults */
2703 }
2704 } else if (bytes_read > 0) {
2705 session->last_rx_tx = now;
2706#if COAP_CLIENT_SUPPORT
2707 if (session->session_failed) {
2708 session->session_failed = 0;
2710 }
2711#endif /* COAP_CLIENT_SUPPORT */
2712 /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2713 coap_handle_dgram_for_proto(ctx, session, packet);
2714 } else {
2715 coap_address_copy(&session->addr_info.remote, &remote);
2716 }
2717#if !COAP_DISABLE_TCP
2718 } else if (session->proto == COAP_PROTO_WS ||
2719 session->proto == COAP_PROTO_WSS) {
2720 ssize_t bytes_read = 0;
2721
2722 /* WebSocket layer passes us the whole packet */
2723 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2724 packet->payload,
2725 packet->length);
2726 if (bytes_read < 0) {
2728 } else if (bytes_read > 2) {
2729 coap_pdu_t *pdu;
2730
2731 session->last_rx_tx = now;
2732 /* Need max space in case PDU is updated with updated token etc. */
2733 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2734 if (!pdu) {
2735 return;
2736 }
2737
2738 if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2740 coap_log_warn("discard malformed PDU\n");
2742 return;
2743 }
2744
2745 coap_dispatch(ctx, session, pdu);
2747 return;
2748 }
2749 } else {
2750 ssize_t bytes_read = 0;
2751 const uint8_t *p;
2752 int retry;
2753
2754 do {
2755 bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2756 packet->payload,
2757 packet->length);
2758 if (bytes_read > 0) {
2759 session->last_rx_tx = now;
2760 }
2761 p = packet->payload;
2762 retry = bytes_read == (ssize_t)packet->length;
2763 while (bytes_read > 0) {
2764 if (session->partial_pdu) {
2765 size_t len = session->partial_pdu->used_size
2766 + session->partial_pdu->hdr_size
2767 - session->partial_read;
2768 size_t n = min(len, (size_t)bytes_read);
2769 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2770 + session->partial_read, p, n);
2771 p += n;
2772 bytes_read -= n;
2773 if (n == len) {
2774 coap_opt_filter_t error_opts;
2775 coap_pdu_t *pdu = session->partial_pdu;
2776
2777 session->partial_pdu = NULL;
2778 session->partial_read = 0;
2779
2780 coap_option_filter_clear(&error_opts);
2781 if (coap_pdu_parse_header(pdu, session->proto)
2782 && coap_pdu_parse_opt(pdu, &error_opts)) {
2783 coap_dispatch(ctx, session, pdu);
2784 } else if (error_opts.mask) {
2785 coap_pdu_t *response =
2787 COAP_RESPONSE_CODE(402), &error_opts);
2788 if (!response) {
2789 coap_log_warn("coap_read_session: cannot create error response\n");
2790 } else {
2791 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2792 coap_log_warn("coap_read_session: error sending response\n");
2793 }
2794 }
2796 } else {
2797 session->partial_read += n;
2798 }
2799 } else if (session->partial_read > 0) {
2800 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2801 session->read_header);
2802 size_t tkl = session->read_header[0] & 0x0f;
2803 size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2804 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2805 size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2806 size_t n = min(len, (size_t)bytes_read);
2807 memcpy(session->read_header + session->partial_read, p, n);
2808 p += n;
2809 bytes_read -= n;
2810 if (n == len) {
2811 /* Header now all in */
2812 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2813 hdr_size + tok_ext_bytes);
2814 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
2815 coap_log_warn("** %s: incoming PDU length too large (%" PRIuS " > %lu)\n",
2816 coap_session_str(session),
2818 bytes_read = -1;
2819 break;
2820 }
2821 /* Need max space in case PDU is updated with updated token etc. */
2822 session->partial_pdu = coap_pdu_init(0, 0, 0,
2824 if (session->partial_pdu == NULL) {
2825 bytes_read = -1;
2826 break;
2827 }
2828 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2829 bytes_read = -1;
2830 break;
2831 }
2832 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2833 session->partial_pdu->used_size = size;
2834 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2835 session->partial_read = hdr_size + tok_ext_bytes;
2836 if (size == 0) {
2837 coap_pdu_t *pdu = session->partial_pdu;
2838
2839 session->partial_pdu = NULL;
2840 session->partial_read = 0;
2841 if (coap_pdu_parse_header(pdu, session->proto)) {
2842 coap_dispatch(ctx, session, pdu);
2843 }
2845 }
2846 } else {
2847 /* More of the header to go */
2848 session->partial_read += n;
2849 }
2850 } else {
2851 /* Get in first byte of the header */
2852 session->read_header[0] = *p++;
2853 bytes_read -= 1;
2854 if (!coap_pdu_parse_header_size(session->proto,
2855 session->read_header)) {
2856 bytes_read = -1;
2857 break;
2858 }
2859 session->partial_read = 1;
2860 }
2861 }
2862 } while (bytes_read == 0 && retry);
2863 if (bytes_read < 0)
2865#endif /* !COAP_DISABLE_TCP */
2866 }
2867}
2868
2869#if COAP_SERVER_SUPPORT
2870static int
2871coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2872 ssize_t bytes_read = -1;
2873 int result = -1; /* the value to be returned */
2874#if COAP_CONSTRAINED_STACK
2875 /* payload and e_packet can be protected by global_lock if needed */
2876 static unsigned char payload[COAP_RXBUFFER_SIZE];
2877 static coap_packet_t e_packet;
2878#else /* ! COAP_CONSTRAINED_STACK */
2879 unsigned char payload[COAP_RXBUFFER_SIZE];
2880 coap_packet_t e_packet;
2881#endif /* ! COAP_CONSTRAINED_STACK */
2882 coap_packet_t *packet = &e_packet;
2883
2884 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2885 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2886
2887 /* Need to do this as there may be holes in addr_info */
2888 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2889 packet->length = sizeof(payload);
2890 packet->payload = payload;
2892 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2893
2894 bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2895 if (bytes_read < 0) {
2896 if (errno != EAGAIN) {
2897 coap_log_warn("* %s: read failed\n", coap_endpoint_str(endpoint));
2898 }
2899 } else if (bytes_read > 0) {
2900 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2901 if (session) {
2903 coap_log_debug("* %s: netif: recv %4" PRIdS " bytes\n",
2904 coap_session_str(session), bytes_read);
2905 result = coap_handle_dgram_for_proto(ctx, session, packet);
2906 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2907 coap_session_new_dtls_session(session, now);
2908 coap_session_release_lkd(session);
2909 }
2910 }
2911 return result;
2912}
2913
2914static int
2915coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2916 (void)ctx;
2917 (void)endpoint;
2918 (void)now;
2919 return 0;
2920}
2921
2922#if !COAP_DISABLE_TCP
2923static int
2924coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2925 coap_tick_t now, void *extra) {
2926 coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2927 if (session)
2928 session->last_rx_tx = now;
2929 return session != NULL;
2930}
2931#endif /* !COAP_DISABLE_TCP */
2932#endif /* COAP_SERVER_SUPPORT */
2933
2934COAP_API void
2936 coap_lock_lock(return);
2937 coap_io_do_io_lkd(ctx, now);
2939}
2940
2941void
2943#ifdef COAP_EPOLL_SUPPORT
2944 (void)ctx;
2945 (void)now;
2946 coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2947#else /* ! COAP_EPOLL_SUPPORT */
2948 coap_session_t *s, *rtmp;
2949
2951#if COAP_SERVER_SUPPORT
2952 coap_endpoint_t *ep, *tmp;
2953 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2954 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2955 coap_read_endpoint(ctx, ep, now);
2956 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2957 coap_write_endpoint(ctx, ep, now);
2958#if !COAP_DISABLE_TCP
2959 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2960 coap_accept_endpoint(ctx, ep, now, NULL);
2961#endif /* !COAP_DISABLE_TCP */
2962 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2963 /* Make sure the session object is not deleted in one of the callbacks */
2965#if COAP_CLIENT_SUPPORT
2966 if (s->client_initiated && (s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2967 coap_connect_session(s, now);
2968 }
2969#endif /* COAP_CLIENT_SUPPORT */
2970 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2971 coap_read_session(ctx, s, now);
2972 }
2973 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2974 coap_write_session(ctx, s, now);
2975 }
2977 }
2978 }
2979#endif /* COAP_SERVER_SUPPORT */
2980
2981#if COAP_CLIENT_SUPPORT
2982 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2983 /* Make sure the session object is not deleted in one of the callbacks */
2985 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2986 coap_connect_session(s, now);
2987 }
2988 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2989 coap_read_session(ctx, s, now);
2990 }
2991 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2992 coap_write_session(ctx, s, now);
2993 }
2995 }
2996#endif /* COAP_CLIENT_SUPPORT */
2997#endif /* ! COAP_EPOLL_SUPPORT */
2998}
2999
3000COAP_API void
3001coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
3002 coap_lock_lock(return);
3003 coap_io_do_epoll_lkd(ctx, events, nevents);
3005}
3006
3007/*
3008 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
3009 * directly saves having to iterate through the endpoints / sessions.
3010 */
3011void
3012coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
3013#ifndef COAP_EPOLL_SUPPORT
3014 (void)ctx;
3015 (void)events;
3016 (void)nevents;
3017 coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
3018#else /* COAP_EPOLL_SUPPORT */
3019 coap_tick_t now;
3020 size_t j;
3021
3023 coap_ticks(&now);
3024 for (j = 0; j < nevents; j++) {
3025 coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
3026
3027 /* Ignore 'timer trigger' ptr which is NULL */
3028 if (sock) {
3029#if COAP_SERVER_SUPPORT
3030 if (sock->endpoint) {
3031 coap_endpoint_t *endpoint = sock->endpoint;
3032 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
3033 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3034 sock->flags |= COAP_SOCKET_CAN_READ;
3035 coap_read_endpoint(endpoint->context, endpoint, now);
3036 }
3037
3038 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
3039 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3040 /*
3041 * Need to update this to EPOLLIN as EPOLLOUT will normally always
3042 * be true causing epoll_wait to return early
3043 */
3044 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3046 coap_write_endpoint(endpoint->context, endpoint, now);
3047 }
3048
3049#if !COAP_DISABLE_TCP
3050 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
3051 (events[j].events & EPOLLIN)) {
3053 coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
3054 }
3055#endif /* !COAP_DISABLE_TCP */
3056
3057 } else
3058#endif /* COAP_SERVER_SUPPORT */
3059 if (sock->session) {
3060 coap_session_t *session = sock->session;
3061
3062 /* Make sure the session object is not deleted
3063 in one of the callbacks */
3065#if COAP_CLIENT_SUPPORT
3066 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
3067 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3069 coap_connect_session(session, now);
3070 if (coap_netif_available(session) &&
3071 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
3072 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3073 }
3074 }
3075#endif /* COAP_CLIENT_SUPPORT */
3076
3077 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
3078 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3079 sock->flags |= COAP_SOCKET_CAN_READ;
3080 coap_read_session(session->context, session, now);
3081 }
3082
3083 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
3084 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3085 /*
3086 * Need to update this to EPOLLIN as EPOLLOUT will normally always
3087 * be true causing epoll_wait to return early
3088 */
3089 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3091 coap_write_session(session->context, session, now);
3092 }
3093 /* Now dereference session so it can go away if needed */
3094 coap_session_release_lkd(session);
3095 }
3096 } else if (ctx->eptimerfd != -1) {
3097 /*
3098 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
3099 * it so that it does not set EPOLLIN in the next epoll_wait().
3100 */
3101 uint64_t count;
3102
3103 /* Check the result from read() to suppress the warning on
3104 * systems that declare read() with warn_unused_result. */
3105 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
3106 /* do nothing */;
3107 }
3108 }
3109 }
3110 /* And update eptimerfd as to when to next trigger */
3111 coap_ticks(&now);
3112 coap_io_prepare_epoll_lkd(ctx, now);
3113#endif /* COAP_EPOLL_SUPPORT */
3114}
3115
3116int
3118 uint8_t *msg, size_t msg_len) {
3119
3120 coap_pdu_t *pdu = NULL;
3121 coap_opt_filter_t error_opts;
3122
3123 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
3124 if (msg_len < 4) {
3125 /* Minimum size of CoAP header - ignore runt */
3126 return -1;
3127 }
3128 if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
3129 /*
3130 * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
3131 * this MUST be silently ignored.
3132 */
3133 coap_log_debug("coap_handle_dgram: UDP version not supported\n");
3134 return -1;
3135 }
3136
3137 /* Need max space in case PDU is updated with updated token etc. */
3138 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
3139 if (!pdu)
3140 goto error;
3141
3142 coap_option_filter_clear(&error_opts);
3143 if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
3145 coap_log_warn("discard malformed PDU\n");
3146 if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
3147 coap_pdu_t *response =
3149 COAP_RESPONSE_CODE(402), &error_opts);
3150 if (!response) {
3151 coap_log_warn("coap_handle_dgram: cannot create error response\n");
3152 } else {
3153 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
3154 coap_log_warn("coap_handle_dgram: error sending response\n");
3155 }
3157 return -1;
3158 } else {
3159 goto error;
3160 }
3161 }
3162
3163 if (coap_debug_recv_packet()) {
3164 coap_dispatch(ctx, session, pdu);
3165 } else {
3167 }
3169 return 0;
3170
3171error:
3172 /*
3173 * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
3174 * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
3175 */
3176 coap_send_rst_lkd(session, pdu);
3178 return -1;
3179}
3180
3183 coap_queue_t *p = NULL;
3184 coap_queue_t *q;
3185
3186 LL_FOREACH(session->delayqueue, q) {
3187 if (q->id == mid) {
3188 if (p) {
3189 p->next = q->next;
3190 } else {
3191 session->delayqueue = q->next;
3192 }
3193 if (session->delayqueue_tail == q)
3194 session->delayqueue_tail = p;
3195 q->next = NULL;
3196 return q;
3197 }
3198 p = q;
3199 }
3200 return NULL;
3201}
3202
3205 coap_queue_t *q = session->delayqueue;
3206
3207 if (q) {
3208 session->delayqueue = q->next;
3209 if (session->delayqueue == NULL)
3210 session->delayqueue_tail = NULL;
3211 q->next = NULL;
3212 }
3213 return q;
3214}
3215
3216void
3218 node->next = NULL;
3219 if (session->delayqueue_tail) {
3220 session->delayqueue_tail->next = node;
3221 } else {
3222 session->delayqueue = node;
3223 }
3224 session->delayqueue_tail = node;
3225}
3226
3227void
3229 node->next = session->delayqueue;
3230 session->delayqueue = node;
3231 if (node->next == NULL)
3232 session->delayqueue_tail = node;
3233}
3234
3235int
3237 coap_bin_const_t *token, coap_queue_t **node) {
3238 coap_queue_t *p, *q;
3239
3240 if (!queue || !*queue) {
3241 *node = NULL;
3242 return 0;
3243 }
3244
3245 /* replace queue head if PDU's time is less than head's time */
3246
3247 if (session == (*queue)->session && mid == (*queue)->id &&
3248 (!token || coap_binary_equal(token, &(*queue)->pdu->actual_token))) { /* found message id */
3249 *node = *queue;
3250 *queue = (*queue)->next;
3251 if (*queue) { /* adjust relative time of new queue head */
3252 (*queue)->t += (*node)->t;
3253 }
3254 (*node)->next = NULL;
3255 coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
3256 coap_session_str(session), mid);
3257 return 1;
3258 }
3259
3260 /* search message id in queue to remove (only first occurrence will be removed) */
3261 q = *queue;
3262 do {
3263 p = q;
3264 q = q->next;
3265 } while (q && (session != q->session || mid != q->id ||
3266 (token && ! coap_binary_equal(token, &q->pdu->actual_token))));
3267
3268 if (q) { /* found message id */
3269 p->next = q->next;
3270 if (p->next) { /* must update relative time of p->next */
3271 p->next->t += q->t;
3272 }
3273 q->next = NULL;
3274 *node = q;
3275 coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
3276 coap_session_str(session), mid);
3277 return 1;
3278 }
3279
3280 *node = NULL;
3281 return 0;
3282
3283}
3284
3285static int
3287 coap_bin_const_t *token, coap_queue_t **node) {
3288 coap_queue_t *p, *q;
3289
3290 if (!queue || !*queue)
3291 return 0;
3292
3293 /* replace queue head if PDU's time is less than head's time */
3294
3295 if (session == (*queue)->session &&
3296 (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
3297 *node = *queue;
3298 *queue = (*queue)->next;
3299 if (*queue) { /* adjust relative time of new queue head */
3300 (*queue)->t += (*node)->t;
3301 }
3302 (*node)->next = NULL;
3303 coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3304 coap_session_str(session), (*node)->id);
3305 if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3306 session->con_active--;
3307 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3308 /* Flush out any entries on session->delayqueue */
3309 coap_session_connected(session);
3310 }
3311 return 1;
3312 }
3313
3314 /* search token in queue to remove (only first occurrence will be removed) */
3315 q = *queue;
3316 do {
3317 p = q;
3318 q = q->next;
3319 } while (q && (session != q->session ||
3320 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3321
3322 if (q) { /* found token */
3323 p->next = q->next;
3324 if (p->next) { /* must update relative time of p->next */
3325 p->next->t += q->t;
3326 }
3327 q->next = NULL;
3328 *node = q;
3329 coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3330 coap_session_str(session), (*node)->id);
3331 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3332 session->con_active--;
3333 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3334 /* Flush out any entries on session->delayqueue */
3335 coap_session_connected(session);
3336 }
3337 return 1;
3338 }
3339
3340 return 0;
3341
3342}
3343
3344void
3346 coap_nack_reason_t reason) {
3347 coap_queue_t *p, *q;
3348
3349 while (context->sendqueue && context->sendqueue->session == session) {
3350 q = context->sendqueue;
3351 context->sendqueue = q->next;
3352 coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3353 coap_session_str(session), q->id);
3354 if (q->pdu->type == COAP_MESSAGE_CON) {
3355 coap_handle_nack(session, q->pdu, reason, q->id);
3356 }
3358 }
3359
3360 if (!context->sendqueue)
3361 return;
3362
3363 p = context->sendqueue;
3364 q = p->next;
3365
3366 while (q) {
3367 if (q->session == session) {
3368 p->next = q->next;
3369 coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3370 coap_session_str(session), q->id);
3371 if (q->pdu->type == COAP_MESSAGE_CON) {
3372 coap_handle_nack(session, q->pdu, reason, q->id);
3373 }
3375 q = p->next;
3376 } else {
3377 p = q;
3378 q = q->next;
3379 }
3380 }
3381}
3382
3383void
3385 coap_bin_const_t *token) {
3386 /* cancel all messages in sendqueue that belong to session
3387 * and use the specified token */
3388 coap_queue_t **p, *q;
3389
3390 if (!context->sendqueue)
3391 return;
3392
3393 p = &context->sendqueue;
3394 q = *p;
3395
3396 while (q) {
3397 if (q->session == session &&
3398 (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3399 *p = q->next;
3400 coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3401 coap_session_str(session), q->id);
3402 if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3403 session->con_active--;
3404 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3405 /* Flush out any entries on session->delayqueue */
3406 coap_session_connected(session);
3407 }
3409 } else {
3410 p = &(q->next);
3411 }
3412 q = *p;
3413 }
3414}
3415
3416coap_pdu_t *
3418 coap_opt_filter_t *opts) {
3419 coap_opt_iterator_t opt_iter;
3420 coap_pdu_t *response;
3421 unsigned char type;
3422
3423#if COAP_ERROR_PHRASE_LENGTH > 0
3424 const char *phrase;
3425 if (code != COAP_RESPONSE_CODE(508)) {
3426 phrase = coap_response_phrase(code);
3427 } else {
3428 phrase = NULL;
3429 }
3430#endif
3431
3432 assert(request);
3433
3434 if (request->type != COAP_MESSAGE_NON && request->type != COAP_MESSAGE_CON)
3435 return NULL;
3436
3437 /* cannot send ACK if original request was not confirmable */
3438 type = request->type == COAP_MESSAGE_CON ?
3440
3441 /* Now create the response and fill with options and payload data. */
3442 response = coap_pdu_init(type, code, request->mid,
3443 request->session ?
3444 coap_session_max_pdu_size_lkd(request->session) : 512);
3445 if (response) {
3446 /* copy token */
3447 if (request->actual_token.length &&
3448 !coap_add_token(response, request->actual_token.length,
3449 request->actual_token.s)) {
3450 coap_log_debug("cannot add token to error response\n");
3451 coap_delete_pdu_lkd(response);
3452 return NULL;
3453 }
3454 if (response->code == COAP_RESPONSE_CODE(402)) {
3455 char buf[128];
3456 int first = 1;
3457 int i;
3458 size_t len;
3459
3460#if COAP_ERROR_PHRASE_LENGTH > 0
3461 snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3462#else
3463 buf[0] = '\000';
3464#endif
3465 /* copy all reported options into diagnostic message */
3466 for (i = COAP_OPT_FILTER_SHORT - 1; i >= 0; i--) {
3467 if (opts->mask & (1 << (COAP_OPT_FILTER_LONG + i))) {
3468 len = strlen(buf);
3469 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",",
3470 opts->short_opts[i]);
3471 first = 0;
3472 }
3473 }
3474 for (i = COAP_OPT_FILTER_LONG - 1; i >= 0; i--) {
3475 if (opts->mask & (1 << i)) {
3476 len = strlen(buf);
3477 snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",",
3478 opts->long_opts[i]);
3479 first = 0;
3480 }
3481 }
3482 coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3483 } else if (opts && opts->mask) {
3484 coap_opt_t *option;
3485
3486 /* copy all options */
3487 coap_option_iterator_init(request, &opt_iter, opts);
3488 while ((option = coap_option_next(&opt_iter))) {
3489 coap_add_option_internal(response, opt_iter.number,
3490 coap_opt_length(option),
3491 coap_opt_value(option));
3492 }
3493#if COAP_ERROR_PHRASE_LENGTH > 0
3494 if (phrase)
3495 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3496 } else {
3497 /* note that diagnostic messages do not need a Content-Format option. */
3498 if (phrase)
3499 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3500#endif
3501 }
3502 }
3503
3504 return response;
3505}
3506
3507#if COAP_SERVER_SUPPORT
3508#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3509
3510static void
3511free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3512 coap_delete_string(app_ptr);
3513}
3514
3515/*
3516 * Caution: As this handler is in libcoap space, it is called with
3517 * context locked.
3518 */
3519static void
3520hnd_get_wellknown_lkd(coap_resource_t *resource,
3521 coap_session_t *session,
3522 const coap_pdu_t *request,
3523 const coap_string_t *query,
3524 coap_pdu_t *response) {
3525 size_t len = 0;
3526 coap_string_t *data_string = NULL;
3527 coap_print_status_t result = 0;
3528 size_t wkc_len = 0;
3529 uint8_t buf[4];
3530
3531 /*
3532 * Quick hack to determine the size of the resource descriptions for
3533 * .well-known/core.
3534 */
3535 result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3536 if (result & COAP_PRINT_STATUS_ERROR) {
3537 coap_log_warn("cannot determine length of /.well-known/core\n");
3538 goto error;
3539 }
3540
3541 if (wkc_len > 0) {
3542 data_string = coap_new_string(wkc_len);
3543 if (!data_string)
3544 goto error;
3545
3546 len = wkc_len;
3547 result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3548 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3549 coap_log_debug("coap_print_wellknown failed\n");
3550 goto error;
3551 }
3552 assert(len <= (size_t)wkc_len);
3553 data_string->length = len;
3554
3555 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3557 coap_encode_var_safe(buf, sizeof(buf),
3559 goto error;
3560 }
3561 if (response->used_size + len + 1 > response->max_size) {
3562 /*
3563 * Data does not fit into a packet and no libcoap block support
3564 * +1 for end of options marker
3565 */
3566 coap_log_debug(".well-known/core: truncating data length to %" PRIuS " from %" PRIuS "\n",
3567 len, response->max_size - response->used_size - 1);
3568 len = response->max_size - response->used_size - 1;
3569 }
3570 if (!coap_add_data(response, len, data_string->s)) {
3571 goto error;
3572 }
3573 free_wellknown_response(session, data_string);
3574 } else if (!coap_add_data_large_response_lkd(resource, session, request,
3575 response, query,
3577 -1, 0, data_string->length,
3578 data_string->s,
3579 free_wellknown_response,
3580 data_string)) {
3581 goto error_released;
3582 }
3583 } else {
3585 coap_encode_var_safe(buf, sizeof(buf),
3587 goto error;
3588 }
3589 }
3590 response->code = COAP_RESPONSE_CODE(205);
3591 return;
3592
3593error:
3594 free_wellknown_response(session, data_string);
3595error_released:
3596 if (response->code == 0) {
3597 /* set error code 5.03 and remove all options and data from response */
3598 response->code = COAP_RESPONSE_CODE(503);
3599 response->used_size = response->e_token_length;
3600 response->data = NULL;
3601 }
3602}
3603#endif /* COAP_SERVER_SUPPORT */
3604
3615static int
3617 int num_cancelled = 0; /* the number of observers cancelled */
3618
3619#ifndef COAP_SERVER_SUPPORT
3620 (void)sent;
3621#endif /* ! COAP_SERVER_SUPPORT */
3622 (void)context;
3623
3624#if COAP_SERVER_SUPPORT
3625 /* remove observer for this resource, if any
3626 * Use token from sent and try to find a matching resource. Uh!
3627 */
3628 RESOURCES_ITER(context->resources, r) {
3629 coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3630 num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3631 }
3632#endif /* COAP_SERVER_SUPPORT */
3633
3634 return num_cancelled;
3635}
3636
3637#if COAP_SERVER_SUPPORT
3642enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3643
3644/*
3645 * Checks for No-Response option in given @p request and
3646 * returns @c RESPONSE_DROP if @p response should be suppressed
3647 * according to RFC 7967.
3648 *
3649 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3650 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3651 * on retrying.
3652 *
3653 * Checks if the response code is 0.00 and if the response is confirmable,
3654 * non-confirmable, or the session is reliable, @c RESPONSE_DROP is also
3655 * returned. An Empty confirmable message is a ping, not a response.
3656 *
3657 * Multicast response checking is also carried out.
3658 *
3659 * NOTE: It is the responsibility of the application to determine whether
3660 * a delayed separate response should be sent as the original requesting packet
3661 * containing the No-Response option has long since gone.
3662 *
3663 * The value of the No-Response option is encoded as
3664 * follows:
3665 *
3666 * @verbatim
3667 * +-------+-----------------------+-----------------------------------+
3668 * | Value | Binary Representation | Description |
3669 * +-------+-----------------------+-----------------------------------+
3670 * | 0 | <empty> | Interested in all responses. |
3671 * +-------+-----------------------+-----------------------------------+
3672 * | 2 | 00000010 | Not interested in 2.xx responses. |
3673 * +-------+-----------------------+-----------------------------------+
3674 * | 8 | 00001000 | Not interested in 4.xx responses. |
3675 * +-------+-----------------------+-----------------------------------+
3676 * | 16 | 00010000 | Not interested in 5.xx responses. |
3677 * +-------+-----------------------+-----------------------------------+
3678 * @endverbatim
3679 *
3680 * @param request The CoAP request to check for the No-Response option.
3681 * This parameter must not be NULL.
3682 * @param response The response that is potentially suppressed.
3683 * This parameter must not be NULL.
3684 * @param session The session this request/response are associated with.
3685 * This parameter must not be NULL.
3686 * @return RESPONSE_DEFAULT when no special treatment is requested,
3687 * RESPONSE_DROP when the response must be discarded, or
3688 * RESPONSE_SEND when the response must be sent.
3689 */
3690static enum respond_t
3691no_response(coap_pdu_t *request, coap_pdu_t *response,
3692 coap_session_t *session, coap_resource_t *resource) {
3693 coap_opt_t *nores;
3694 coap_opt_iterator_t opt_iter;
3695 unsigned int val = 0;
3696
3697 assert(request);
3698 assert(response);
3699
3700 if (COAP_RESPONSE_CLASS(response->code) > 0) {
3701 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3702
3703 if (nores) {
3705
3706 /* The response should be dropped when the bit corresponding to
3707 * the response class is set (cf. table in function
3708 * documentation). When a No-Response option is present and the
3709 * bit is not set, the sender explicitly indicates interest in
3710 * this response. */
3711 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3712 /* Should be dropping the response */
3713 if (response->type == COAP_MESSAGE_ACK &&
3714 COAP_PROTO_NOT_RELIABLE(session->proto)) {
3715 /* Still need to ACK the request */
3716 response->code = 0;
3717 /* Remove token/data from piggybacked acknowledgment PDU */
3718 response->actual_token.length = 0;
3719 response->e_token_length = 0;
3720 response->used_size = 0;
3721 response->data = NULL;
3722 return RESPONSE_SEND;
3723 } else {
3724 return RESPONSE_DROP;
3725 }
3726 } else {
3727 /* True for mcast as well RFC7967 2.1 */
3728 return RESPONSE_SEND;
3729 }
3730 } else if (resource && session->context->mcast_per_resource &&
3731 coap_is_mcast(&session->addr_info.local)) {
3732 /* Handle any mcast suppression specifics if no NoResponse option */
3733 if ((resource->flags &
3735 COAP_RESPONSE_CLASS(response->code) == 2) {
3736 return RESPONSE_DROP;
3737 } else if ((resource->flags &
3739 response->code == COAP_RESPONSE_CODE(205)) {
3740 if (response->data == NULL)
3741 return RESPONSE_DROP;
3742 } else if ((resource->flags &
3744 COAP_RESPONSE_CLASS(response->code) == 4) {
3745 return RESPONSE_DROP;
3746 } else if ((resource->flags &
3748 COAP_RESPONSE_CLASS(response->code) == 5) {
3749 return RESPONSE_DROP;
3750 }
3751 }
3752 } else if (COAP_PDU_IS_EMPTY(response) &&
3753 (response->type == COAP_MESSAGE_NON ||
3754 response->type == COAP_MESSAGE_CON ||
3755 COAP_PROTO_RELIABLE(session->proto))) {
3756 /* Response is 0.00, and this is reliable, non-confirmable, or a separate
3757 * (confirmable) response. An Empty CON is a ping (RFC 7252 4.2), not a
3758 * response, and the PDU still has the request's token attached, which
3759 * RFC 7252 4.1 does not allow. A CON would then get retransmitted up to
3760 * MAX_RETRANSMIT times. */
3761 return RESPONSE_DROP;
3762 }
3763
3764 /*
3765 * Do not send error responses for requests that were received via
3766 * IP multicast. RFC7252 8.1
3767 */
3768
3769 if (coap_is_mcast(&session->addr_info.local)) {
3770 if (request->type == COAP_MESSAGE_NON &&
3771 response->type == COAP_MESSAGE_RST)
3772 return RESPONSE_DROP;
3773
3774 if ((!resource || session->context->mcast_per_resource == 0) &&
3775 COAP_RESPONSE_CLASS(response->code) > 2)
3776 return RESPONSE_DROP;
3777 }
3778
3779 /* Default behavior applies when we are not dealing with a response
3780 * (class == 0) or the request did not contain a No-Response option.
3781 */
3782 return RESPONSE_DEFAULT;
3783}
3784
3785static coap_str_const_t coap_default_uri_wellknown = {
3787 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3788};
3789
3790/* Initialized in coap_startup() */
3791static coap_resource_t resource_uri_wellknown;
3792
3793static void
3794handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3795 coap_pdu_t *orig_pdu) {
3797 coap_pdu_t *response = NULL;
3798 coap_opt_filter_t opt_filter;
3799 coap_resource_t *resource = NULL;
3800 /* The respond field indicates whether a response must be treated
3801 * specially due to a No-Response option that declares disinterest
3802 * or interest in a specific response class. DEFAULT indicates that
3803 * No-Response has not been specified. */
3804 enum respond_t respond = RESPONSE_DEFAULT;
3805 coap_opt_iterator_t opt_iter;
3806 coap_opt_t *opt;
3807 int is_proxy_uri = 0;
3808 int is_proxy_scheme = 0;
3809 int skip_hop_limit_check = 0;
3810 int resp = 0;
3811 coap_string_t *query = NULL;
3812 coap_opt_t *observe = NULL;
3813 coap_string_t *uri_path = NULL;
3814 int observe_action = COAP_OBSERVE_CANCEL;
3815 coap_block_b_t block;
3816 int added_block = 0;
3817 coap_lg_srcv_t *free_lg_srcv = NULL;
3818#if COAP_Q_BLOCK_SUPPORT
3819 int lg_xmit_ctrl = 0;
3820#endif /* COAP_Q_BLOCK_SUPPORT */
3821#if COAP_ASYNC_SUPPORT
3822 coap_async_t *async;
3823#endif /* COAP_ASYNC_SUPPORT */
3824
3825#if COAP_ASYNC_SUPPORT
3826 async = coap_find_async_lkd(session, pdu->actual_token);
3827 if (async) {
3828 coap_tick_t now;
3829
3830 coap_ticks(&now);
3831 if (async->delay == 0 || async->delay > now) {
3832 /* re-transmit missing ACK (only if CON) */
3833 coap_log_info("Retransmit async response\n");
3834 coap_send_ack_lkd(session, pdu);
3835 /* and do not pass on to the upper layers */
3836 return;
3837 }
3838 }
3839#endif /* COAP_ASYNC_SUPPORT */
3840
3841 coap_option_filter_clear(&opt_filter);
3842 if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3843 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3844 if (opt) {
3845 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3846 if (!opt) {
3847 coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3848 resp = 402;
3849 goto fail_response;
3850 }
3851 is_proxy_scheme = 1;
3852 }
3853
3854 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3855 if (opt)
3856 is_proxy_uri = 1;
3857 }
3858
3859 if (is_proxy_scheme || is_proxy_uri) {
3860 coap_uri_t uri;
3861
3862 if (!context->proxy_uri_resource) {
3863 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3864 coap_log_debug("Proxy-%s support not configured\n",
3865 is_proxy_scheme ? "Scheme" : "Uri");
3866 resp = 505;
3867 goto fail_response;
3868 }
3869 if (((size_t)pdu->code - 1 <
3870 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3871 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3872 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3873 coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3874 is_proxy_scheme ? "Scheme" : "Uri",
3875 pdu->code/100, pdu->code%100);
3876 resp = 505;
3877 goto fail_response;
3878 }
3879
3880 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3881 if (is_proxy_uri) {
3883 coap_opt_length(opt), &uri) < 0) {
3884 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3885 coap_log_debug("Proxy-URI not decodable\n");
3886 resp = 505;
3887 goto fail_response;
3888 }
3889 } else {
3890 memset(&uri, 0, sizeof(uri));
3891 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3892 if (opt) {
3893 uri.host.length = coap_opt_length(opt);
3894 uri.host.s = coap_opt_value(opt);
3895 } else
3896 uri.host.length = 0;
3897 }
3898
3899 resource = context->proxy_uri_resource;
3900 if (uri.host.length && resource->proxy_name_count &&
3901 resource->proxy_name_list) {
3902 size_t i;
3903
3904 if (resource->proxy_name_count == 1 &&
3905 resource->proxy_name_list[0]->length == 0) {
3906 /* If proxy_name_list[0] is zero length, then this is the endpoint */
3907 i = 0;
3908 } else {
3909 for (i = 0; i < resource->proxy_name_count; i++) {
3910 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3911 break;
3912 }
3913 }
3914 }
3915 if (i != resource->proxy_name_count) {
3916 /* This server is hosting the proxy connection endpoint */
3917 if (pdu->crit_opt) {
3918 /* Cannot handle critical option */
3919 pdu->crit_opt = 0;
3920 resp = 402;
3921 resource = NULL;
3922 goto fail_response;
3923 }
3924 is_proxy_uri = 0;
3925 is_proxy_scheme = 0;
3926 skip_hop_limit_check = 1;
3927 }
3928 }
3929 resource = NULL;
3930 }
3931 assert(resource == NULL);
3932
3933 if (!skip_hop_limit_check) {
3934 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3935 if (opt) {
3936 size_t hop_limit;
3937 uint8_t buf[4];
3938
3939 hop_limit =
3941 if (hop_limit == 1) {
3942 /* coap_send_internal() will fill in the IP address for us */
3943 resp = 508;
3944 goto fail_response;
3945 } else if (hop_limit < 1 || hop_limit > 255) {
3946 /* Need to return a 4.00 RFC8768 Section 3 */
3947 coap_log_info("Invalid Hop Limit\n");
3948 resp = 400;
3949 goto fail_response;
3950 }
3951 hop_limit--;
3953 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
3954 buf);
3955 }
3956 }
3957
3958 uri_path = coap_get_uri_path(pdu);
3959 if (!uri_path) {
3960 resp = 402;
3961 goto fail_response;
3962 }
3963
3964 if (!is_proxy_uri && !is_proxy_scheme) {
3965 /* try to find the resource from the request URI */
3966 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3967 resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3968 }
3969
3970 if ((resource == NULL) || (resource->is_unknown == 1) ||
3971 (resource->is_proxy_uri == 1)) {
3972 /* The resource was not found or there is an unexpected match against the
3973 * resource defined for handling unknown or proxy URIs.
3974 */
3975 if (resource != NULL)
3976 /* Close down unexpected match */
3977 resource = NULL;
3978 /*
3979 * Check if the request URI happens to be the well-known URI, or if the
3980 * unknown resource handler is defined, a PUT or optionally other methods,
3981 * if configured, for the unknown handler.
3982 *
3983 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
3984 * proxy URI handler.
3985 *
3986 * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
3987 * set, call the unknown URI handler with any unknown URI (including
3988 * .well-known/core) if the appropriate method is defined.
3989 *
3990 * else if well-known URI generate a default response.
3991 *
3992 * else if unknown URI handler defined, call the unknown
3993 * URI handler (to allow for potential generation of resource
3994 * [RFC7272 5.8.3]) if the appropriate method is defined.
3995 *
3996 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE).
3997 *
3998 * else return 4.04.
3999 */
4000
4001 if (is_proxy_uri || is_proxy_scheme) {
4002 resource = context->proxy_uri_resource;
4003 } else if (context->unknown_resource != NULL &&
4004 context->unknown_resource->flags & COAP_RESOURCE_HANDLE_WELLKNOWN_CORE &&
4005 ((size_t)pdu->code - 1 <
4006 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
4007 (context->unknown_resource->handler[pdu->code - 1])) {
4008 resource = context->unknown_resource;
4009 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
4010 /* request for .well-known/core */
4011 resource = &resource_uri_wellknown;
4012 } else if ((context->unknown_resource != NULL) &&
4013 ((size_t)pdu->code - 1 <
4014 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
4015 (context->unknown_resource->handler[pdu->code - 1])) {
4016 /*
4017 * The unknown_resource can be used to handle undefined resources
4018 * for a PUT request and can support any other registered handler
4019 * defined for it
4020 * Example set up code:-
4021 * r = coap_resource_unknown_init(hnd_put_unknown);
4022 * coap_register_request_handler(r, COAP_REQUEST_POST,
4023 * hnd_post_unknown);
4024 * coap_register_request_handler(r, COAP_REQUEST_GET,
4025 * hnd_get_unknown);
4026 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
4027 * hnd_delete_unknown);
4028 * coap_add_resource(ctx, r);
4029 *
4030 * Note: It is not possible to observe the unknown_resource, a separate
4031 * resource must be created (by PUT or POST) which has a GET
4032 * handler to be observed
4033 */
4034 resource = context->unknown_resource;
4035 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
4036 /*
4037 * Request for DELETE on non-existent resource (RFC7252: 5.8.4. DELETE)
4038 */
4039 coap_log_debug("request for unknown resource '%*.*s',"
4040 " return 2.02\n",
4041 (int)uri_path->length,
4042 (int)uri_path->length,
4043 uri_path->s);
4044 resp = 202;
4045 goto fail_response;
4046 } else if (context->dyn_create_handler != NULL) {
4047 resource = coap_add_dynamic_resource(session, pdu);
4048 if (!resource) {
4049 resp = 406;
4050 goto fail_response;
4051 }
4052 } else { /* request for any another resource, return 4.04 */
4053
4054 coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
4055 (int)uri_path->length, (int)uri_path->length, uri_path->s);
4056 resp = 404;
4057 goto fail_response;
4058 }
4059
4060 }
4061
4062 coap_resource_reference_lkd(resource);
4063
4064#if COAP_OSCORE_SUPPORT
4065 if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
4066 coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
4067 (int)uri_path->length, (int)uri_path->length, uri_path->s);
4068 resp = 401;
4069 goto fail_response;
4070 }
4071#endif /* COAP_OSCORE_SUPPORT */
4072 if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
4073 /* Check for existing resource and If-Non-Match */
4074 opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
4075 if (opt) {
4076 resp = 412;
4077 goto fail_response;
4078 }
4079 }
4080
4081 /* the resource was found, check if there is a registered handler */
4082 if ((size_t)pdu->code - 1 <
4083 sizeof(resource->handler) / sizeof(coap_method_handler_t))
4084 h = resource->handler[pdu->code - 1];
4085
4086 if (h == NULL) {
4087 resp = 405;
4088 goto fail_response;
4089 }
4090 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
4091 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) == NULL) {
4092 opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
4093 if (opt == NULL) {
4094 /* RFC 8132 2.3.1 */
4095 resp = 415;
4096 goto fail_response;
4097 }
4098 }
4099 }
4100 if (context->mcast_per_resource &&
4101 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
4102 coap_is_mcast(&session->addr_info.local)) {
4103 resp = 405;
4104 goto fail_response;
4105 }
4106
4107 if (pdu->type == COAP_MESSAGE_CON) {
4108 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, pdu->mid,
4110 } else {
4113 }
4114 if (!response) {
4115 coap_log_err("could not create response PDU\n");
4116 resp = 500;
4117 goto fail_response;
4118 }
4119 response->session = session;
4120#if COAP_ASYNC_SUPPORT
4121 /* If handling a separate response, need CON, not ACK response */
4122 if (async && pdu->type == COAP_MESSAGE_CON)
4123 response->type = COAP_MESSAGE_CON;
4124#endif /* COAP_ASYNC_SUPPORT */
4125 /* A lot of the reliable code assumes type is CON */
4126 if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
4127 response->type = COAP_MESSAGE_CON;
4128
4129 if (!coap_add_token(response, pdu->actual_token.length,
4130 pdu->actual_token.s)) {
4131 resp = 500;
4132 goto fail_response;
4133 }
4134
4135 /*
4136 * RFC7959 2.2: the SZX value 7 "is reserved, i.e., MUST NOT be sent and
4137 * MUST lead to a 4.00 Bad Request response code upon reception in a
4138 * request". SZX 7 is only meaningful as the BERT escape (RFC8323 6),
4139 * which needs a reliable transport with BERT negotiated in both CSMs.
4140 * Anywhere else it must be rejected here: coap_get_block_b() reports a
4141 * reserved SZX as "no Block option present", which is indistinguishable
4142 * further down from a request that never carried one.
4143 */
4144 if (COAP_PROTO_NOT_RELIABLE(session->proto) ||
4145 !(session->csm_bert_rem_support && session->csm_bert_loc_support)) {
4146 static const coap_option_num_t block_nums[] = {
4148 };
4149 size_t bn;
4150
4151 for (bn = 0; bn < sizeof(block_nums)/sizeof(block_nums[0]); bn++) {
4152 coap_opt_t *block_opt = coap_check_option(pdu, block_nums[bn], &opt_iter);
4153
4154 if (block_opt && COAP_OPT_BLOCK_SZX(block_opt) == 7) {
4155 coap_log_debug("request: reserved Block SZX 7 (RFC7959 2.2)\n");
4156 resp = 400;
4157 goto fail_response;
4158 }
4159 }
4160 }
4161
4162 query = coap_get_query(pdu);
4163
4164 /* check for Observe option RFC7641 and RFC8132 */
4165 if (resource->observable &&
4166 (pdu->code == COAP_REQUEST_CODE_GET ||
4167 pdu->code == COAP_REQUEST_CODE_FETCH)) {
4168 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
4169 }
4170
4171 /*
4172 * See if blocks need to be aggregated or next requests sent off
4173 * before invoking application request handler
4174 */
4175 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4176 uint32_t block_mode = session->block_mode;
4177
4178 if (observe ||
4179 resource->flags & COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY)
4181 if (coap_handle_request_put_block(context, session, pdu, response,
4182 resource, observe,
4183 &added_block, &free_lg_srcv)) {
4184 session->block_mode = block_mode;
4185 goto skip_handler;
4186 }
4187 session->block_mode = block_mode;
4188
4189 if (coap_handle_request_send_block(session, pdu, response, resource,
4190 query)) {
4191#if COAP_Q_BLOCK_SUPPORT
4192 lg_xmit_ctrl = 1;
4193#endif /* COAP_Q_BLOCK_SUPPORT */
4194 goto skip_handler;
4195 }
4196 }
4197
4198 if (observe) {
4199 observe_action =
4201 coap_opt_length(observe));
4202
4203 if (observe_action == COAP_OBSERVE_ESTABLISH) {
4204 coap_subscription_t *subscription;
4205
4206 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
4207 if (block.num != 0) {
4208 response->code = COAP_RESPONSE_CODE(400);
4209 goto skip_handler;
4210 }
4211#if COAP_Q_BLOCK_SUPPORT
4212 } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
4213 &block)) {
4214 if (block.num != 0) {
4215 response->code = COAP_RESPONSE_CODE(400);
4216 goto skip_handler;
4217 }
4218#endif /* COAP_Q_BLOCK_SUPPORT */
4219 }
4220 subscription = coap_add_observer(resource, session, &pdu->actual_token,
4221 pdu);
4222 if (subscription) {
4223 uint8_t buf[4];
4224
4225 coap_touch_observer(context, session, &pdu->actual_token);
4227 coap_encode_var_safe(buf, sizeof(buf),
4228 resource->observe),
4229 buf);
4230 }
4231 } else if (observe_action == COAP_OBSERVE_CANCEL) {
4232 coap_delete_observer_request(resource, session, &pdu->actual_token, pdu, free_lg_srcv != NULL);
4233 } else {
4234 coap_log_info("observe: unexpected action %d\n", observe_action);
4235 }
4236 }
4237
4238#if COAP_WITH_OBSERVE_PERSIST
4239 /* If we are maintaining Observe persist */
4240 if (resource == context->unknown_resource) {
4241 context->unknown_pdu = pdu;
4242 context->unknown_session = session;
4243 } else
4244 context->unknown_pdu = NULL;
4245#endif /* COAP_WITH_OBSERVE_PERSIST */
4246
4247 /*
4248 * Call the request handler with everything set up
4249 */
4250 if (resource == &resource_uri_wellknown) {
4251 /* Leave context locked */
4252 coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
4253 (int)resource->uri_path->length, (int)resource->uri_path->length,
4254 resource->uri_path->s);
4255 h(resource, session, pdu, query, response);
4256 if (COAP_RESPONSE_CLASS(response->code) == 2 && response->data == NULL &&
4257 coap_is_mcast(&session->addr_info.local)) {
4258 goto drop_it_debug;
4259 }
4260 } else {
4261 coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
4262 (int)resource->uri_path->length, (int)resource->uri_path->length,
4263 resource->uri_path->s);
4264 if (resource->flags & COAP_RESOURCE_SAFE_REQUEST_HANDLER) {
4265 coap_lock_callback_release(h(resource, session, pdu, query, response),
4266 /* context is being freed off */
4267 goto finish);
4268 } else {
4270 h(resource, session, pdu, query, response),
4271 /* context is being freed off */
4272 goto finish);
4273 }
4274 }
4275
4276 /* Check validity of response code */
4277 if (!coap_check_code_class(session, response)) {
4278 coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
4279 COAP_RESPONSE_CLASS(response->code),
4280 response->code & 0x1f);
4281 goto drop_it_no_debug;
4282 }
4283
4284 /* Check correct content type returned by application */
4285 if (response->code != 0 && (opt = coap_check_option(pdu, COAP_OPTION_ACCEPT, &opt_iter)) &&
4286 !(COAP_RESPONSE_CLASS(response->code) == 4 || COAP_RESPONSE_CLASS(response->code) == 5)) {
4287 coap_opt_t *ropt = coap_check_option(response, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
4288
4289 if (!ropt) {
4291 coap_opt_length(opt), coap_opt_value(opt));
4292 } else if (coap_opt_length(opt) != coap_opt_length(ropt) ||
4293 memcmp(coap_opt_value(opt), coap_opt_value(ropt), coap_opt_length(opt)) != 0) {
4294 coap_show_pdu(COAP_LOG_DEBUG, response);
4295 coap_log_debug("handle_request: response: Invalid Content-Format\n");
4296 /* Need to convert response to 4.06 as incorrect content type */
4297 response->code = COAP_RESPONSE_CODE(406);
4298 response->used_size = response->e_token_length;
4299 response->data = NULL;
4300 response->max_opt = 0;
4302 coap_opt_length(opt),
4303 coap_opt_value(opt));
4304 coap_add_data(response, sizeof("Not Acceptable")-1, (const uint8_t *)"Not Acceptable");
4305 }
4306 }
4307
4308 /* Check if lg_xmit generated and update PDU code if so */
4309 coap_check_code_lg_xmit(session, pdu, response, resource, query);
4310
4311 if (free_lg_srcv) {
4312 /* Check to see if the server is doing a 4.01 + Echo response */
4313 if (response->code == COAP_RESPONSE_CODE(401) &&
4314 coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
4315 /* Need to keep lg_srcv around for client's response */
4316 } else {
4317 coap_lg_srcv_t *lg_srcv;
4318 /*
4319 * Need to check free_lg_srcv still exists in case of error or timing window
4320 */
4321 LL_FOREACH(session->lg_srcv, lg_srcv) {
4322 if (lg_srcv == free_lg_srcv) {
4323#if COAP_Q_BLOCK_SUPPORT
4324 if (lg_srcv->block_option == COAP_OPTION_Q_BLOCK1) {
4325 coap_tick_t adjust;
4326
4327 /* cache the lg_srcv for 1 second */
4330 } else {
4331 adjust = 0;
4332 }
4333 coap_ticks(&free_lg_srcv->rec_blocks.last_seen);
4334 if (free_lg_srcv->rec_blocks.last_seen > adjust) {
4335 free_lg_srcv->rec_blocks.last_seen -= adjust;
4336 }
4337 free_lg_srcv->dont_timeout = 0;
4338 break;
4339 }
4340#endif /* COAP_Q_BLOCK_SUPPORT */
4341 LL_DELETE(session->lg_srcv, free_lg_srcv);
4342 coap_block_delete_lg_srcv(session, free_lg_srcv);
4343 break;
4344 }
4345 }
4346 }
4347 }
4348 if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
4349 /* Just in case, as there are more to go */
4350 response->code = COAP_RESPONSE_CODE(231);
4351 }
4352
4353skip_handler:
4354 respond = no_response(pdu, response, session, resource);
4355 if (respond != RESPONSE_DROP) {
4356#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
4357 coap_mid_t mid = pdu->mid;
4358#endif
4359 if (COAP_RESPONSE_CLASS(response->code) != 2) {
4360 if (observe) {
4362 }
4363 }
4364 if (COAP_RESPONSE_CLASS(response->code) > 2) {
4365 if (observe)
4366 coap_delete_observer(resource, session, &pdu->actual_token);
4367 if (response->code != COAP_RESPONSE_CODE(413))
4369 }
4370
4371 /* If original request contained a token, and the registered
4372 * application handler made no changes to the response, then
4373 * this is an empty ACK with a token, which is a malformed
4374 * PDU */
4375 if ((response->type == COAP_MESSAGE_ACK)
4376 && (response->code == 0)) {
4377 /* Remove token from otherwise-empty acknowledgment PDU */
4378 response->actual_token.length = 0;
4379 response->e_token_length = 0;
4380 response->used_size = 0;
4381 response->data = NULL;
4382 }
4383
4384 if (!coap_is_mcast(&session->addr_info.local) ||
4385 (context->mcast_per_resource &&
4386 resource &&
4387 (resource->flags & COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS))) {
4388 /* No delays to response */
4389#if COAP_Q_BLOCK_SUPPORT
4390 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4391 !lg_xmit_ctrl && COAP_RESPONSE_CLASS(response->code) == 2 &&
4392 coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4393 block.m) {
4394 if (coap_send_q_block2(session, resource, query, pdu->code, block,
4395 response,
4396 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4397 coap_log_debug("cannot send response for mid=0x%x\n", mid);
4398 response = NULL;
4399 goto finish;
4400 }
4401#endif /* COAP_Q_BLOCK_SUPPORT */
4402 if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4403 coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4404 goto finish;
4405 }
4406 } else {
4407 /* Need to delay mcast response */
4408 coap_queue_t *node = coap_new_node();
4409 uint8_t r;
4410 coap_tick_t delay;
4411
4412 if (!node) {
4413 coap_log_debug("mcast delay: insufficient memory\n");
4414 goto drop_it_no_debug;
4415 }
4416 if (!coap_pdu_encode_header(response, session->proto)) {
4418 goto drop_it_no_debug;
4419 }
4420
4421 node->id = response->mid;
4422 node->pdu = response;
4423 node->is_mcast = 1;
4424 coap_prng_lkd(&r, sizeof(r));
4425 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4426 coap_log_debug(" %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4427 coap_session_str(session),
4428 response->mid,
4429 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4430 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4431 1000 / COAP_TICKS_PER_SECOND));
4432 node->timeout = (unsigned int)delay;
4433 /* Use this to delay transmission */
4434 coap_wait_ack(session->context, session, node);
4435 }
4436 } else if (COAP_PDU_IS_EMPTY(response) &&
4437 (response->type == COAP_MESSAGE_NON ||
4438 response->type == COAP_MESSAGE_CON ||
4439 COAP_PROTO_RELIABLE(session->proto))) {
4440 coap_delete_pdu_lkd(response);
4441 } else {
4442drop_it_debug:
4443 coap_log_debug(" %s: mid=0x%04x: response dropped\n",
4444 coap_session_str(session),
4445 response->mid);
4446 coap_show_pdu(COAP_LOG_DEBUG, response);
4447drop_it_no_debug:
4448 coap_delete_pdu_lkd(response);
4449 }
4450#if COAP_Q_BLOCK_SUPPORT
4451 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4452 if (COAP_PROTO_RELIABLE(session->proto)) {
4453 if (block.m) {
4454 /* All of the sequence not in yet */
4455 goto finish;
4456 }
4457 } else if (pdu->type == COAP_MESSAGE_NON) {
4458 /* More to go and not at a payload break */
4459 if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4460 goto finish;
4461 }
4462 }
4463 }
4464#endif /* COAP_Q_BLOCK_SUPPORT */
4465
4466finish:
4467 if (query)
4468 coap_delete_string(query);
4469 if (resource)
4470 coap_resource_release_lkd(resource);
4471 coap_delete_string(uri_path);
4472 return;
4473
4474fail_response:
4475 coap_delete_pdu_lkd(response);
4476 response =
4478 &opt_filter);
4479 if (response)
4480 goto skip_handler;
4481 if (resource)
4482 coap_resource_release_lkd(resource);
4483 coap_delete_string(uri_path);
4484}
4485#endif /* COAP_SERVER_SUPPORT */
4486
4487#if COAP_CLIENT_SUPPORT
4488/* Call application-specific response handler when available. */
4489void
4491 coap_pdu_t *sent, coap_pdu_t *rcvd,
4492 void *body_data) {
4493 coap_context_t *context = session->context;
4494 coap_response_t ret;
4495
4496#if COAP_PROXY_SUPPORT
4497 if (context->proxy_response_cb) {
4498 coap_proxy_entry_t *proxy_entry;
4499 coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4500 rcvd,
4501 &proxy_entry);
4502
4503 if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4504 coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4505 proxy_entry);
4506 return;
4507 }
4508 }
4509#endif /* COAP_PROXY_SUPPORT */
4510 if (session->doing_send_recv && session->req_token &&
4511 coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4512 /* processing coap_send_recv() call */
4513 session->resp_pdu = rcvd;
4515 /* Will get freed off when PDU is freed off */
4516 rcvd->data_free = body_data;
4517 coap_send_ack_lkd(session, rcvd);
4519 return;
4520 } else if (context->response_cb) {
4522 context->response_cb(session,
4523 sent,
4524 rcvd,
4525 rcvd->mid),
4526 /* context is being freed off */
4527 return);
4528 } else {
4529 /*
4530 * RFC7252 4.2
4531 * (b) reject the message if the recipient lacks context to process the
4532 * message properly
4533 */
4534 ret = COAP_RESPONSE_FAIL;
4535 }
4536 if (ret == COAP_RESPONSE_FAIL) {
4537 coap_send_rst_lkd(session, rcvd);
4539 } else {
4540 coap_send_ack_lkd(session, rcvd);
4542 }
4543 coap_free_type(COAP_STRING, body_data);
4544}
4545
4546static void
4547handle_response(coap_context_t *context, coap_session_t *session,
4548 coap_pdu_t *sent, coap_pdu_t *rcvd) {
4549
4550 /* Set in case there is a later call to coap_update_token() */
4551 rcvd->session = session;
4552
4553 /* Check for message duplication */
4554 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4555 if (rcvd->type == COAP_MESSAGE_CON) {
4556 if (rcvd->mid == session->last_resp_mid) {
4557 /* Duplicate response: send ACK/RST, but don't process */
4558 if (session->last_con_handler_res == COAP_RESPONSE_OK)
4559 coap_send_ack_lkd(session, rcvd);
4560 else
4561 coap_send_rst_lkd(session, rcvd);
4562 return;
4563 }
4564 } else if (rcvd->type == COAP_MESSAGE_ACK) {
4565 if (rcvd->mid == session->last_resp_mid) {
4566 /* Duplicate response */
4567 return;
4568 }
4569 }
4570 session->last_resp_mid = rcvd->mid;
4571 }
4572 /* Check to see if checking out extended token support */
4573 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4574 session->last_token) {
4575 coap_lg_crcv_t *lg_crcv;
4576
4577 if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4578 rcvd->actual_token.length != session->max_token_size ||
4579 rcvd->code == COAP_RESPONSE_CODE(400) ||
4580 rcvd->code == COAP_RESPONSE_CODE(503)) {
4581 coap_log_debug("Extended Token requested size support not available\n");
4583 } else {
4584 coap_log_debug("Extended Token support available\n");
4585 }
4587 /* Need to remove lg_crcv set up for this test */
4588 lg_crcv = coap_find_lg_crcv(session, rcvd);
4589 if (lg_crcv) {
4590 LL_DELETE(session->lg_crcv, lg_crcv);
4591 coap_block_delete_lg_crcv(session, lg_crcv);
4592 }
4593 coap_send_ack_lkd(session, rcvd);
4594 coap_reset_doing_first(session);
4595 return;
4596 }
4597#if COAP_Q_BLOCK_SUPPORT
4598 /* Check to see if checking out Q-Block support */
4599 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
4600 if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4601 coap_log_debug("Q-Block support not available\n");
4602 set_block_mode_drop_q(session->block_mode);
4603 } else {
4604 coap_block_b_t qblock;
4605
4606 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4607 coap_log_debug("Q-Block support available\n");
4608 set_block_mode_has_q(session->block_mode);
4609 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4610 /* Flush out any entries on session->delayqueue */
4611 coap_session_connected(session);
4612 } else {
4613 coap_log_debug("Q-Block support not available\n");
4614 set_block_mode_drop_q(session->block_mode);
4615 }
4616 }
4617 coap_send_ack_lkd(session, rcvd);
4618 coap_reset_doing_first(session);
4619 return;
4620 }
4621#endif /* COAP_Q_BLOCK_SUPPORT */
4622
4623 /* See if the server is struggling */
4624 if (rcvd->code == COAP_RESPONSE_CODE(503) || rcvd->code == COAP_RESPONSE_CODE(429)) {
4625 if (!sent && session->lg_crcv)
4626 sent = session->lg_crcv->sent_pdu;
4627
4628 if (sent) {
4629 /* sent is not active, so safe to reuse */
4630 uint8_t buf[4];
4631 /* Need to resend request in max_age seconds */
4632 size_t max_age = 60;
4633 coap_opt_iterator_t opt_iter;
4634 coap_opt_t *option = coap_check_option(rcvd, COAP_OPTION_MAXAGE, &opt_iter);
4635 coap_queue_t *node = coap_new_node();
4636 if (option)
4637 max_age = coap_decode_var_bytes(coap_opt_value(option),
4638 coap_opt_length(option));
4639
4640 if (!node) {
4641 coap_log_debug("retransmit delay: insufficient memory\n");
4642 return;
4643 }
4644
4646 sent->mid = coap_new_message_id_lkd(session);
4647 coap_update_option(sent,
4649 coap_encode_var_safe(buf, sizeof(buf),
4650 ++session->tx_rtag),
4651 buf);
4652 coap_pdu_encode_header(sent, session->proto);
4653 node->id = sent->mid;
4654 node->pdu = sent;
4655 coap_log_debug(" %s: mid=0x%04x: re-request delayed for %u secs\n",
4656 coap_session_str(session),
4657 sent->mid,
4658 (unsigned int)max_age);
4659 node->timeout = (unsigned int)max_age * COAP_TICKS_PER_SECOND;
4660 /* Use this to delay transmission */
4661 coap_wait_ack(session->context, session, node);
4662 }
4663 return;
4664 }
4665
4666 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4667 /* See if need to send next block to server */
4668 if (coap_handle_response_send_block(session, sent, rcvd)) {
4669 /* Next block transmitted, no need to inform app */
4670 coap_send_ack_lkd(session, rcvd);
4671 return;
4672 }
4673
4674 /* Need to see if needing to request next block */
4675 if (coap_handle_response_get_block(context, session, sent, rcvd,
4676 COAP_RECURSE_OK)) {
4677 /* Next block transmitted, ack sent no need to inform app */
4678 return;
4679 }
4680 }
4681 coap_reset_doing_first(session);
4682
4683 /* Call application-specific response handler when available. */
4684 coap_call_response_handler(session, sent, rcvd, NULL);
4685}
4686#endif /* COAP_CLIENT_SUPPORT */
4687
4688#if !COAP_DISABLE_TCP
4689static void
4691 coap_pdu_t *pdu) {
4692 coap_opt_iterator_t opt_iter;
4693 coap_opt_t *option;
4694 int set_mtu = 0;
4695
4696 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4697
4698 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4699 if (session->csm_not_seen) {
4700 coap_tick_t now;
4701
4702 coap_ticks(&now);
4703 /* CSM timeout before CSM seen */
4704 coap_log_warn("***%s: CSM received after CSM timeout\n",
4705 coap_session_str(session));
4706 coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4707 coap_session_str(session),
4708 (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4709 }
4710 if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4712 }
4713 while ((option = coap_option_next(&opt_iter))) {
4714 unsigned max_recv;
4715
4716 switch ((coap_sig_csm_opt_t)opt_iter.number) {
4718 max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4719 if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4721 coap_log_debug("* %s: Restricting CSM Max-Message-Size size to %u\n",
4722 coap_session_str(session), max_recv);
4723 }
4724 coap_session_set_mtu(session, max_recv);
4725 set_mtu = 1;
4726 break;
4728 session->csm_block_supported = 1;
4729 break;
4731 session->max_token_size =
4733 coap_opt_length(option));
4736 else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4739 break;
4740 default:
4741 break;
4742 }
4743 }
4744 if (set_mtu) {
4745 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4746 session->csm_bert_rem_support = 1;
4747 else
4748 session->csm_bert_rem_support = 0;
4749 }
4750 if (session->state == COAP_SESSION_STATE_CSM)
4751 coap_session_connected(session);
4752 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4754 if (context->ping_cb) {
4755 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4756 }
4757 if (pong) {
4759 0, NULL);
4760 coap_send_internal(session, pong, NULL);
4761 }
4762 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4763 session->last_pong = session->last_rx_tx;
4764 session->ping_failed = 0;
4765 if (context->pong_cb) {
4766 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4767 }
4768 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4769 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4771 } else {
4772 coap_log_debug("PDU signaling code %u.%02u unknown\n", (pdu->code >> 5) & 0x7, pdu->code & 0x1f);
4773 }
4774}
4775#endif /* !COAP_DISABLE_TCP */
4776
4777static int
4778check_token_size(coap_session_t *session, const coap_pdu_t *pdu, int is_local_mcast) {
4779 if (COAP_PDU_IS_REQUEST(pdu) &&
4780 pdu->actual_token.length >
4781 (session->type == COAP_SESSION_TYPE_CLIENT ?
4782 session->max_token_size : session->context->max_token_size)) {
4783 /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4784 if (is_local_mcast)
4785 return 0;
4786 if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4787 coap_opt_filter_t opt_filter;
4788 coap_pdu_t *response;
4789
4790 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4791 response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4792 &opt_filter);
4793 if (!response) {
4794 coap_log_warn("coap_dispatch: cannot create error response\n");
4795 } else {
4796 /*
4797 * Note - have to leave in oversize token as per
4798 * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4799 */
4800 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4801 coap_log_warn("coap_dispatch: error sending response\n");
4802 }
4803 } else {
4804 /* Indicate no extended token support */
4805 coap_send_rst_lkd(session, pdu);
4806 }
4807 return 0;
4808 }
4809 return 1;
4810}
4811
4812void
4814 coap_pdu_t *pdu) {
4815 coap_queue_t *sent = NULL;
4816 coap_pdu_t *response;
4817 coap_pdu_t *orig_pdu = NULL;
4818 coap_opt_filter_t opt_filter;
4819 int is_ping_rst;
4820 int packet_is_bad = 0;
4821#if COAP_OSCORE_SUPPORT
4822 coap_opt_iterator_t opt_iter;
4823 coap_pdu_t *dec_pdu = NULL;
4824#endif /* COAP_OSCORE_SUPPORT */
4825 int is_ext_token_rst = 0;
4826 int oscore_invalid = 0;
4827 int is_local_mcast = 0;
4828
4830 pdu->session = session;
4832
4833 if (COAP_PDU_IS_REQUEST(pdu) && coap_is_mcast(&session->addr_info.local)) {
4834 /* Need to be careful with responses to multicast requests */
4835 is_local_mcast = 1;
4836 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
4837 coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
4838 return;
4839 }
4840 }
4841
4842 /* Check validity of received code */
4843 if (!coap_check_code_class(session, pdu)) {
4844 coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4846 pdu->code & 0x1f);
4847 packet_is_bad = 1;
4848 if (pdu->type == COAP_MESSAGE_CON) {
4850 }
4851 /* find message id in sendqueue to stop retransmission (code is not 0.00) */
4852 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &pdu->actual_token, &sent);
4853 goto cleanup;
4854 }
4855
4856 coap_option_filter_clear(&opt_filter);
4857
4858#if COAP_SERVER_SUPPORT
4859 /* See if this a repeat request */
4860 if (COAP_PDU_IS_REQUEST(pdu) && session->last_resp_pdu &&
4861 pdu->mid == session->last_resp_pdu->mid) {
4862#if COAP_OSCORE_SUPPORT
4863 uint8_t oscore_encryption = session->oscore_encryption;
4864
4865 session->oscore_encryption = 0;
4866#endif /* COAP_OSCORE_SUPPORT */
4867 /* Account for coap_send_internal() doing a coap_delete_pdu() and
4868 last_resp_pdu must not be removed */
4869 coap_pdu_reference_lkd(session->last_resp_pdu);
4870 coap_log_debug("Retransmit response to duplicate request\n");
4871 if (coap_send_internal(session, session->last_resp_pdu, NULL) != COAP_INVALID_MID) {
4872#if COAP_OSCORE_SUPPORT
4873 session->oscore_encryption = oscore_encryption;
4874#endif /* COAP_OSCORE_SUPPORT */
4875 goto finish;
4876 }
4877#if COAP_OSCORE_SUPPORT
4878 session->oscore_encryption = oscore_encryption;
4879#endif /* COAP_OSCORE_SUPPORT */
4880 }
4881#endif /* COAP_SERVER_SUPPORT */
4882 if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4883 if (!check_token_size(session, pdu, is_local_mcast)) {
4884 goto cleanup;
4885 }
4886 }
4887#if COAP_OSCORE_SUPPORT
4888 if (!COAP_PDU_IS_SIGNALING(pdu) &&
4889 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
4890 if (!is_local_mcast && (pdu->type == COAP_MESSAGE_CON || pdu->type == COAP_MESSAGE_NON)) {
4891 if (COAP_PDU_IS_REQUEST(pdu)) {
4892 response =
4893 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4894
4895 if (!response) {
4896 coap_log_warn("coap_dispatch: cannot create error response\n");
4897 } else {
4898 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4899 coap_log_warn("coap_dispatch: error sending response\n");
4900 }
4901 } else {
4902 coap_send_rst_lkd(session, pdu);
4903 }
4904 }
4905 goto cleanup;
4906 }
4907
4908 if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4909 int decrypt = 1;
4910#if COAP_SERVER_SUPPORT
4911 coap_opt_t *opt;
4912 coap_resource_t *resource;
4913 coap_uri_t uri;
4914#endif /* COAP_SERVER_SUPPORT */
4915
4916 if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4917 decrypt = 0;
4918
4919#if COAP_SERVER_SUPPORT
4920 if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4921 coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4922 (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4923 != NULL) {
4924 /* Need to check whether this is a direct or proxy session */
4925 memset(&uri, 0, sizeof(uri));
4926 uri.host.length = coap_opt_length(opt);
4927 uri.host.s = coap_opt_value(opt);
4928 resource = context->proxy_uri_resource;
4929 if (uri.host.length && resource && resource->proxy_name_count &&
4930 resource->proxy_name_list) {
4931 size_t i;
4932 for (i = 0; i < resource->proxy_name_count; i++) {
4933 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4934 break;
4935 }
4936 }
4937 if (i == resource->proxy_name_count) {
4938 /* This server is not hosting the proxy connection endpoint */
4939 decrypt = 0;
4940 }
4941 }
4942 }
4943#endif /* COAP_SERVER_SUPPORT */
4944 if (decrypt) {
4945 /* find message id in sendqueue to stop retransmission and get sent (not empty packet) */
4946 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &pdu->actual_token, &sent);
4947 /* Bump ref so pdu is not freed of, and keep a pointer to it */
4948 orig_pdu = pdu;
4949 coap_pdu_reference_lkd(orig_pdu);
4950 if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
4951 if (session->recipient_ctx == NULL ||
4952 (session->recipient_ctx->initial_state == 0 &&
4953 session->b_2_step == COAP_OSCORE_B_2_NONE)) {
4954 coap_log_warn("OSCORE: PDU could not be decrypted\n");
4955 }
4957 coap_delete_pdu_lkd(orig_pdu);
4958 goto finish;
4959 } else {
4960 session->oscore_encryption = 1;
4961 coap_pdu_reference_lkd(dec_pdu);
4963 pdu = dec_pdu;
4964 }
4965 coap_log_debug("Decrypted PDU\n");
4967 }
4968 } else if (COAP_PDU_IS_RESPONSE(pdu) &&
4969 session->oscore_encryption &&
4970 pdu->type != COAP_MESSAGE_RST) {
4971 if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
4972 /* Violates RFC 8613 2 */
4973 coap_log_err("received an invalid response to the OSCORE request\n");
4974 oscore_invalid = 1;
4975 }
4976 }
4977#endif /* COAP_OSCORE_SUPPORT */
4978
4979 switch (pdu->type) {
4980 case COAP_MESSAGE_ACK:
4981 if (NULL == sent) {
4982 /* find message id in sendqueue to stop retransmission (no token if empty) */
4983 coap_remove_from_queue(&context->sendqueue, session, pdu->mid,
4984 pdu->code == 0 ? NULL : &pdu->actual_token, &sent);
4985 }
4986
4987 if (sent && session->con_active) {
4988 session->con_active--;
4989 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4990 /* Flush out any entries on session->delayqueue */
4991 coap_session_connected(session);
4992 }
4993 if (oscore_invalid ||
4994 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
4995 packet_is_bad = 1;
4996 goto cleanup;
4997 }
4998
4999#if COAP_SERVER_SUPPORT
5000 /* if sent code was >= 64 the message might have been a
5001 * notification. Then, we must flag the observer to be alive
5002 * by setting obs->fail_cnt = 0. */
5003 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
5004 coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
5005 }
5006#endif /* COAP_SERVER_SUPPORT */
5007
5008#if COAP_Q_BLOCK_SUPPORT
5009 if (session->lg_xmit && sent && sent->pdu && sent->pdu->type == COAP_MESSAGE_CON &&
5010 !(session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK)) {
5011 int doing_q_block = 0;
5012 coap_lg_xmit_t *lg_xmit = NULL;
5013
5014 LL_FOREACH(session->lg_xmit, lg_xmit) {
5015 if ((lg_xmit->option == COAP_OPTION_Q_BLOCK1 || lg_xmit->option == COAP_OPTION_Q_BLOCK2) &&
5016 lg_xmit->last_all_sent == 0 && lg_xmit->sent_pdu->type != COAP_MESSAGE_NON) {
5017 doing_q_block = 1;
5018 break;
5019 }
5020 }
5021 if (doing_q_block && lg_xmit) {
5022 coap_block_b_t block;
5023
5024 memset(&block, 0, sizeof(block));
5025 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
5026 block.num = lg_xmit->last_block + lg_xmit->b.b1.count;
5027 } else {
5028 block.num = lg_xmit->last_block;
5029 }
5030 block.m = 1;
5031 block.szx = block.aszx = lg_xmit->blk_size;
5032 block.defined = 1;
5033 block.bert = 0;
5034 block.chunk_size = 1024;
5035
5036 coap_send_q_blocks(session, lg_xmit, block,
5037 lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
5038 }
5039 }
5040#endif /* COAP_Q_BLOCK_SUPPORT */
5041 if (pdu->code == 0) {
5042#if COAP_CLIENT_SUPPORT
5043 /*
5044 * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
5045 * reliable to save overhead as this can be set up on detection of a (Q)-Block2
5046 * response if the response was piggy-backed. Here, a separate response
5047 * detected and so the lg_crcv needs to be set up before the sent PDU
5048 * information is lost.
5049 *
5050 * lg_crcv was not set up if not a CoAP request.
5051 *
5052 * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
5053 * options.
5054 */
5055 if (sent &&
5056 !coap_check_send_need_lg_crcv(session, sent->pdu) &&
5057 COAP_PDU_IS_REQUEST(sent->pdu)) {
5058 /*
5059 * lg_crcv was not set up in coap_send(). It could have been set up
5060 * the first separate response.
5061 * See if there already is a lg_crcv set up.
5062 */
5063 coap_lg_crcv_t *lg_crcv;
5064 uint64_t token_match =
5066 sent->pdu->actual_token.length));
5067
5068 LL_FOREACH(session->lg_crcv, lg_crcv) {
5069 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
5070 coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
5071 break;
5072 }
5073 }
5074 if (!lg_crcv) {
5075 /*
5076 * Need to set up a lg_crcv as it was not set up in coap_send()
5077 * to save time, but server has not sent back a piggy-back response.
5078 */
5079 lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
5080 if (lg_crcv) {
5081 LL_PREPEND(session->lg_crcv, lg_crcv);
5082 }
5083 }
5084 }
5085#endif /* COAP_CLIENT_SUPPORT */
5086 /* an empty ACK needs no further handling */
5087 goto cleanup;
5088 } else if (COAP_PDU_IS_REQUEST(pdu)) {
5089 /* This is not legitimate - Request using ACK - ignore */
5090 coap_log_debug("dropped ACK with request code (%d.%02d)\n",
5092 pdu->code & 0x1f);
5093 packet_is_bad = 1;
5094 goto cleanup;
5095 }
5096
5097 break;
5098
5099 case COAP_MESSAGE_RST:
5100 /* We have sent something the receiver disliked, so we remove
5101 * not only the message id but also the subscriptions we might
5102 * have. */
5103 is_ping_rst = 0;
5104 if (pdu->mid == session->last_ping_mid &&
5105 session->last_ping > 0)
5106 is_ping_rst = 1;
5107
5108#if COAP_CLIENT_SUPPORT
5109#if COAP_Q_BLOCK_SUPPORT
5110 /* Check to see if checking out Q-Block support */
5111 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
5112 session->remote_test_mid == pdu->mid) {
5113 coap_log_debug("Q-Block support not available\n");
5114 set_block_mode_drop_q(session->block_mode);
5115 coap_reset_doing_first(session);
5116 }
5117#endif /* COAP_Q_BLOCK_SUPPORT */
5118
5119 /* Check to see if checking out extended token support */
5120 if (session->max_token_checked == COAP_EXT_T_CHECKING &&
5121 session->remote_test_mid == pdu->mid) {
5122 coap_log_debug("Extended Token support not available\n");
5125 coap_reset_doing_first(session);
5126 is_ext_token_rst = 1;
5127 }
5128#endif /* COAP_CLIENT_SUPPORT */
5129
5130 if (!is_ping_rst && !is_ext_token_rst)
5131 coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
5132
5133 if (session->con_active) {
5134 session->con_active--;
5135 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
5136 /* Flush out any entries on session->delayqueue */
5137 coap_session_connected(session);
5138 }
5139
5140 /* find message id in sendqueue to stop retransmission (no token as RST) */
5141 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, NULL, &sent);
5142
5143 if (sent) {
5144 if (!is_ping_rst)
5145 coap_cancel(context, sent);
5146
5147 if (!is_ping_rst && !is_ext_token_rst) {
5148 if (sent->pdu->type==COAP_MESSAGE_CON) {
5149 coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
5150 }
5151 } else if (is_ping_rst) {
5152 if (context->pong_cb) {
5153 coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
5154 }
5155 session->last_pong = session->last_rx_tx;
5156 session->ping_failed = 0;
5158 }
5159 } else {
5160#if COAP_SERVER_SUPPORT
5161 /* Need to check is there is a subscription active and delete it */
5162 RESOURCES_ITER(context->resources, r) {
5163 coap_subscription_t *obs, *tmp;
5164 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
5165 if (obs->pdu->mid == pdu->mid && obs->session == session) {
5166 /* Need to do this now as session may get de-referenced */
5168 coap_delete_observer(r, session, &obs->pdu->actual_token);
5169 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
5170 coap_session_release_lkd(session);
5171 goto cleanup;
5172 }
5173 }
5174 }
5175#endif /* COAP_SERVER_SUPPORT */
5176 coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
5177 }
5178#if COAP_PROXY_SUPPORT
5179 if (!is_ping_rst) {
5180 /* Need to check is there is a proxy subscription active and delete it */
5181 coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
5182 }
5183#endif /* COAP_PROXY_SUPPORT */
5184 goto cleanup;
5185
5186 case COAP_MESSAGE_NON:
5187 /* check for oscore issue or unknown critical options */
5188 if (oscore_invalid ||
5189 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
5190 packet_is_bad = 1;
5191 if (COAP_PDU_IS_REQUEST(pdu)) {
5192 response =
5193 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
5194
5195 if (!response) {
5196 coap_log_warn("coap_dispatch: cannot create error response\n");
5197 } else {
5198 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
5199 coap_log_warn("coap_dispatch: error sending response\n");
5200 }
5201 } else {
5202 coap_send_rst_lkd(session, pdu);
5203 }
5204 goto cleanup;
5205 }
5206 break;
5207
5208 case COAP_MESSAGE_CON:
5209 /* In a lossy context, the ACK of a separate response may have
5210 * been lost, so we need to stop retransmitting requests with the
5211 * same token. Matching on token potentially containing ext length bytes.
5212 */
5213 /* find message token in sendqueue to stop retransmission */
5214 if (pdu->code != 0)
5215 coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
5216
5217 /* check for oscore issue or unknown critical options in non-signaling messages */
5218 if (oscore_invalid ||
5219 (!COAP_PDU_IS_SIGNALING(pdu) &&
5220 coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0)) {
5221 packet_is_bad = 1;
5222 if (COAP_PDU_IS_REQUEST(pdu)) {
5223 response =
5224 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
5225
5226 if (!response) {
5227 coap_log_warn("coap_dispatch: cannot create error response\n");
5228 } else {
5229 if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
5230 coap_log_warn("coap_dispatch: error sending response\n");
5231 }
5232 } else {
5233 coap_send_rst_lkd(session, pdu);
5234 }
5235 goto cleanup;
5236 }
5237 break;
5238 default:
5239 break;
5240 }
5241
5242 /* Pass message to upper layer if a specific handler was
5243 * registered for a request that should be handled locally. */
5244#if !COAP_DISABLE_TCP
5245 if (COAP_PDU_IS_SIGNALING(pdu))
5246 handle_signaling(context, session, pdu);
5247 else
5248#endif /* !COAP_DISABLE_TCP */
5249#if COAP_SERVER_SUPPORT
5250 if (COAP_PDU_IS_REQUEST(pdu))
5251 handle_request(context, session, pdu, orig_pdu);
5252 else
5253#endif /* COAP_SERVER_SUPPORT */
5254#if COAP_CLIENT_SUPPORT
5255 if (COAP_PDU_IS_RESPONSE(pdu))
5256 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
5257 else
5258#endif /* COAP_CLIENT_SUPPORT */
5259 {
5260 if (COAP_PDU_IS_EMPTY(pdu)) {
5261 if (context->ping_cb) {
5262 coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
5263 }
5264 } else {
5265 packet_is_bad = 1;
5266 }
5267 coap_log_debug("dropped message with invalid code (%d.%02d)\n",
5269 pdu->code & 0x1f);
5270
5271 if (!coap_is_mcast(&session->addr_info.local)) {
5272 if (COAP_PDU_IS_EMPTY(pdu)) {
5273 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
5274 coap_tick_t now;
5275 coap_ticks(&now);
5276 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
5278 session->last_tx_rst = now;
5279 }
5280 }
5281 } else {
5282 if (pdu->type == COAP_MESSAGE_CON)
5284 }
5285 }
5286 }
5287
5288cleanup:
5289 if (packet_is_bad) {
5290 if (sent) {
5291 coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
5292 } else {
5294 }
5295 }
5296 coap_delete_pdu_lkd(orig_pdu);
5298#if COAP_OSCORE_SUPPORT
5299 coap_delete_pdu_lkd(dec_pdu);
5300#endif /* COAP_OSCORE_SUPPORT */
5301
5302#if COAP_SERVER_SUPPORT || COAP_OSCORE_SUPPORT
5303finish:
5304#endif /* COAP_SERVER_SUPPORT || COAP_OSCORE_SUPPORT */
5306}
5307
5308#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
5309static const char *
5311 switch (event) {
5313 return "COAP_EVENT_DTLS_CLOSED";
5315 return "COAP_EVENT_DTLS_CONNECTED";
5317 return "COAP_EVENT_DTLS_RENEGOTIATE";
5319 return "COAP_EVENT_DTLS_ERROR";
5321 return "COAP_EVENT_TCP_CONNECTED";
5323 return "COAP_EVENT_TCP_CLOSED";
5325 return "COAP_EVENT_TCP_FAILED";
5327 return "COAP_EVENT_SESSION_CONNECTED";
5329 return "COAP_EVENT_SESSION_CLOSED";
5331 return "COAP_EVENT_SESSION_FAILED";
5333 return "COAP_EVENT_PARTIAL_BLOCK";
5335 return "COAP_EVENT_XMIT_BLOCK_FAIL";
5337 return "COAP_EVENT_BLOCK_ISSUE";
5339 return "COAP_EVENT_SERVER_SESSION_NEW";
5341 return "COAP_EVENT_SERVER_SESSION_DEL";
5343 return "COAP_EVENT_SERVER_SESSION_CONNECTED";
5345 return "COAP_EVENT_BAD_PACKET";
5347 return "COAP_EVENT_MSG_RETRANSMITTED";
5349 return "COAP_EVENT_FIRST_PDU_FAIL";
5351 return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
5353 return "COAP_EVENT_OSCORE_NOT_ENABLED";
5355 return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
5357 return "COAP_EVENT_OSCORE_NO_SECURITY";
5359 return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
5361 return "COAP_EVENT_OSCORE_DECODE_ERROR";
5363 return "COAP_EVENT_WS_PACKET_SIZE";
5365 return "COAP_EVENT_WS_CONNECTED";
5367 return "COAP_EVENT_WS_CLOSED";
5369 return "COAP_EVENT_KEEPALIVE_FAILURE";
5371 return "COAP_EVENT_RECONNECT_FAILED";
5373 return "COAP_EVENT_RECONNECT_SUCCESS";
5375 return "COAP_EVENT_RECONNECT_NO_MORE";
5377 return "COAP_EVENT_RECONNECT_STARTED";
5378 default:
5379 return "???";
5380 }
5381}
5382#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
5383
5384COAP_API int
5386 coap_session_t *session) {
5387 int ret;
5388
5389 coap_lock_lock(return 0);
5390 ret = coap_handle_event_lkd(context, event, session);
5392 return ret;
5393}
5394
5395int
5397 coap_session_t *session) {
5398 int ret = 0;
5399
5400 coap_log_debug("***EVENT: %s\n", coap_event_name(event));
5401
5402#if COAP_PROXY_SUPPORT
5403 if (event == COAP_EVENT_SERVER_SESSION_DEL)
5404 coap_proxy_remove_association(session, 0);
5405#endif /* COAP_PROXY_SUPPORT */
5406
5407 if (context->event_cb) {
5408 coap_lock_callback_ret(ret, context->event_cb(session, event));
5409#if COAP_CLIENT_SUPPORT
5410 switch (event) {
5425 /* Those that are deemed fatal to end sending a request */
5426 session->doing_send_recv = 0;
5427 break;
5429 /* Session will now be available as well - for call-home */
5430 if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
5432 session);
5433 }
5434 break;
5440 break;
5442 /* Session will now be available as well - for call-home if not (D)TLS */
5443 if (session->type == COAP_SESSION_TYPE_SERVER &&
5444 (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
5446 session);
5447 }
5448 break;
5453 break;
5455 /* Session will now be available as well - for call-home if not (D)TLS */
5456 if (session->proto == COAP_PROTO_UDP) {
5458 session);
5459 }
5460 break;
5468 default:
5469 break;
5470 }
5471#endif /* COAP_CLIENT_SUPPORT */
5472 }
5473 return ret;
5474}
5475
5476COAP_API int
5478 int ret;
5479
5480 coap_lock_lock(return 0);
5481 ret = coap_can_exit_lkd(context);
5483 return ret;
5484}
5485
5486int
5488 coap_session_t *s, *rtmp;
5489 if (!context)
5490 return 1;
5492 if (context->sendqueue)
5493 return 0;
5494#if COAP_SERVER_SUPPORT
5495 coap_endpoint_t *ep;
5496
5497 LL_FOREACH(context->endpoint, ep) {
5498 SESSIONS_ITER(ep->sessions, s, rtmp) {
5499 if (s->delayqueue)
5500 return 0;
5501 if (s->lg_xmit)
5502 return 0;
5503 }
5504 }
5505#endif /* COAP_SERVER_SUPPORT */
5506#if COAP_CLIENT_SUPPORT
5507 SESSIONS_ITER(context->sessions, s, rtmp) {
5508 if (s->delayqueue)
5509 return 0;
5510 if (s->lg_xmit)
5511 return 0;
5512 }
5513#endif /* COAP_CLIENT_SUPPORT */
5514 return 1;
5515}
5516#if COAP_SERVER_SUPPORT
5517#if COAP_ASYNC_SUPPORT
5518/*
5519 * Return 1 if there is a future expire time, else 0.
5520 * Update tim_rem with remaining value if return is 1.
5521 */
5522int
5523coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5525 coap_async_t *async, *tmp;
5526 int ret = 0;
5527
5528 if (context->async_state_traversing)
5529 return 0;
5530 context->async_state_traversing = 1;
5531 LL_FOREACH_SAFE(context->async_state, async, tmp) {
5532 if (async->delay != 0 && !async->session->is_rate_limiting) {
5533 if (async->delay <= now) {
5534 /* Restore the local address the request was received on */
5535 coap_address_copy(&async->session->addr_info.local, &async->local_if);
5536 /* Send off the request to the application */
5537 coap_log_debug("Async PDU presented to app.\n");
5538 coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5539 handle_request(context, async->session, async->pdu, NULL);
5540
5541 /* Remove this async entry as it has now fired */
5542 coap_free_async_lkd(async->session, async);
5543 } else {
5544 next_due = async->delay - now;
5545 ret = 1;
5546 }
5547 }
5548 }
5549 if (tim_rem)
5550 *tim_rem = next_due;
5551 context->async_state_traversing = 0;
5552 return ret;
5553}
5554#endif /* COAP_ASYNC_SUPPORT */
5555#endif /* COAP_SERVER_SUPPORT */
5556
5558uint8_t coap_unique_id[8] = { 0 };
5559
5560#if COAP_THREAD_SAFE
5561/*
5562 * Global lock for multi-thread support
5563 */
5564coap_lock_t global_lock;
5565/*
5566 * low level protection mutex
5567 */
5568coap_mutex_t m_show_pdu;
5569coap_mutex_t m_log_impl;
5570coap_mutex_t m_io_threads;
5571#endif /* COAP_THREAD_SAFE */
5572
5573void
5575 coap_tick_t now;
5576#ifndef WITH_CONTIKI
5577 uint64_t us;
5578#endif /* !WITH_CONTIKI */
5579
5580 if (coap_started)
5581 return;
5582 coap_started = 1;
5583
5584#if COAP_THREAD_SAFE
5585 coap_lock_init(&global_lock);
5586 coap_mutex_init(&m_show_pdu);
5587 coap_mutex_init(&m_log_impl);
5588 coap_mutex_init(&m_io_threads);
5589#endif /* COAP_THREAD_SAFE */
5590
5591#if defined(HAVE_WINSOCK2_H)
5592 WORD wVersionRequested = MAKEWORD(2, 2);
5593 WSADATA wsaData;
5594 WSAStartup(wVersionRequested, &wsaData);
5595#endif
5597 coap_ticks(&now);
5598#ifndef WITH_CONTIKI
5599 us = coap_ticks_to_rt_us(now);
5600 /* Be accurate to the nearest (approx) us */
5601 coap_prng_init_lkd((unsigned int)us);
5602#else /* WITH_CONTIKI */
5603 coap_start_io_process();
5604#endif /* WITH_CONTIKI */
5607#ifdef WITH_LWIP
5608 coap_io_lwip_init();
5609#endif /* WITH_LWIP */
5610#if COAP_SERVER_SUPPORT
5611 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5612 (const uint8_t *)".well-known/core"
5613 };
5614 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5615 resource_uri_wellknown.ref = 1;
5616 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5617 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5618 resource_uri_wellknown.uri_path = &well_known;
5619#endif /* COAP_SERVER_SUPPORT */
5622}
5623
5624void
5626 if (!coap_started)
5627 return;
5628 coap_started = 0;
5629#if defined(HAVE_WINSOCK2_H)
5630 WSACleanup();
5631#elif defined(WITH_CONTIKI)
5632 coap_stop_io_process();
5633#endif
5634#ifdef WITH_LWIP
5635 coap_io_lwip_cleanup();
5636#endif /* WITH_LWIP */
5638
5643#if COAP_THREAD_SAFE
5644 coap_mutex_destroy(&m_show_pdu);
5645 coap_mutex_destroy(&m_log_impl);
5646 coap_mutex_destroy(&m_io_threads);
5647#endif /* COAP_THREAD_SAFE */
5648
5650}
5651
5652void
5654 coap_response_handler_t handler) {
5655#if COAP_CLIENT_SUPPORT
5656 context->response_cb = handler;
5657#else /* ! COAP_CLIENT_SUPPORT */
5658 (void)context;
5659 (void)handler;
5660#endif /* ! COAP_CLIENT_SUPPORT */
5661}
5662
5663void
5666#if COAP_PROXY_SUPPORT
5667 context->proxy_response_cb = handler;
5668#else /* ! COAP_PROXY_SUPPORT */
5669 (void)context;
5670 (void)handler;
5671#endif /* ! COAP_PROXY_SUPPORT */
5672}
5673
5674void
5676 coap_nack_handler_t handler) {
5677 context->nack_cb = handler;
5678}
5679
5680void
5682 coap_ping_handler_t handler) {
5683 context->ping_cb = handler;
5684}
5685
5686void
5688 coap_pong_handler_t handler) {
5689 context->pong_cb = handler;
5690}
5691
5692void
5694 coap_resource_dynamic_create_t dyn_create_handler,
5695 uint32_t dynamic_max) {
5696 context->dyn_create_handler = dyn_create_handler;
5697 context->dynamic_max = dynamic_max;
5698 return;
5699}
5700
5701COAP_API void
5707
5708void
5712
5713#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5714#if COAP_SERVER_SUPPORT
5715COAP_API int
5716coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5717 const char *ifname) {
5718 int ret;
5719
5720 coap_lock_lock(return -1);
5721 ret = coap_join_mcast_group_intf_lkd(ctx, NULL, group_name, ifname);
5723 return ret;
5724}
5725
5726int
5728 coap_endpoint_t *single_endpoint,
5729 const char *group_name,
5730 const char *ifname) {
5731#if COAP_IPV4_SUPPORT
5732 struct ip_mreq mreq4;
5733#endif /* COAP_IPV4_SUPPORT */
5734#if COAP_IPV6_SUPPORT
5735 struct ipv6_mreq mreq6;
5736#endif /* COAP_IPV6_SUPPORT */
5737 struct addrinfo *resmulti = NULL, hints, *ainfo;
5738 int result = -1;
5739 coap_endpoint_t *endpoint;
5740#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5741 coap_endpoint_t *lookup_endpoint;
5742#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5743 int mgroup_setup = 0;
5744
5745 if (single_endpoint) {
5746 if (single_endpoint->proto != COAP_PROTO_UDP)
5747 return -1;
5748#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5749 lookup_endpoint = single_endpoint;
5750#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5751 } else {
5752 /* Need to have at least one endpoint! */
5753 assert(ctx->endpoint);
5754 if (!ctx->endpoint)
5755 return -1;
5756#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5757 lookup_endpoint = ctx->endpoint;
5758#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5759 }
5760
5761 /* Default is let the kernel choose */
5762#if COAP_IPV6_SUPPORT
5763 mreq6.ipv6mr_interface = 0;
5764#endif /* COAP_IPV6_SUPPORT */
5765#if COAP_IPV4_SUPPORT
5766 mreq4.imr_interface.s_addr = INADDR_ANY;
5767#endif /* COAP_IPV4_SUPPORT */
5768
5769 memset(&hints, 0, sizeof(hints));
5770 hints.ai_socktype = SOCK_DGRAM;
5771
5772 /* resolve the multicast group address */
5773 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5774
5775 if (result != 0) {
5776 coap_log_err("coap_join_mcast_group_intf: %s: "
5777 "Cannot resolve multicast address: %s\n",
5778 group_name, gai_strerror(result));
5779 goto finish;
5780 }
5781
5782 /* Need to do a windows equivalent at some point */
5783#ifndef _WIN32
5784 if (ifname) {
5785 /* interface specified - check if we have correct IPv4/IPv6 information */
5786 int done_ip4 = 0;
5787 int done_ip6 = 0;
5788#if defined(ESPIDF_VERSION)
5789 struct netif *netif;
5790#else /* !ESPIDF_VERSION */
5791#if COAP_IPV4_SUPPORT
5792 int ip4fd;
5793#endif /* COAP_IPV4_SUPPORT */
5794 struct ifreq ifr;
5795#endif /* !ESPIDF_VERSION */
5796
5797 /* See which mcast address family types are being asked for */
5798 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5799 ainfo = ainfo->ai_next) {
5800 switch (ainfo->ai_family) {
5801#if COAP_IPV6_SUPPORT
5802 case AF_INET6:
5803 if (done_ip6)
5804 break;
5805 done_ip6 = 1;
5806#if defined(ESPIDF_VERSION)
5807 netif = netif_find(ifname);
5808 if (netif)
5809 mreq6.ipv6mr_interface = netif_get_index(netif);
5810 else
5811 coap_log_err("coap_join_mcast_group_intf: %s: "
5812 "Cannot get IPv4 address: %s\n",
5813 ifname, coap_socket_strerror());
5814#else /* !ESPIDF_VERSION */
5815 memset(&ifr, 0, sizeof(ifr));
5816 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5817 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5818
5819#ifdef HAVE_IF_NAMETOINDEX
5820 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5821 if (mreq6.ipv6mr_interface == 0) {
5822 coap_log_warn("coap_join_mcast_group_intf: "
5823 "cannot get interface index for '%s'\n",
5824 ifname);
5825 }
5826#elif defined(__QNXNTO__)
5827#else /* !HAVE_IF_NAMETOINDEX */
5828 result = ioctl(lookup_endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5829 if (result != 0) {
5830 coap_log_warn("coap_join_mcast_group_intf: "
5831 "cannot get interface index for '%s': %s\n",
5832 ifname, coap_socket_strerror());
5833 } else {
5834 /* Capture the IPv6 if_index for later */
5835 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5836 }
5837#endif /* !HAVE_IF_NAMETOINDEX */
5838#endif /* !ESPIDF_VERSION */
5839#endif /* COAP_IPV6_SUPPORT */
5840 break;
5841#if COAP_IPV4_SUPPORT
5842 case AF_INET:
5843 if (done_ip4)
5844 break;
5845 done_ip4 = 1;
5846#if defined(ESPIDF_VERSION)
5847 netif = netif_find(ifname);
5848 if (netif)
5849 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5850 else
5851 coap_log_err("coap_join_mcast_group_intf: %s: "
5852 "Cannot get IPv4 address: %s\n",
5853 ifname, coap_socket_strerror());
5854#else /* !ESPIDF_VERSION */
5855 /*
5856 * Need an AF_INET socket to do this unfortunately to stop
5857 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5858 */
5859 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5860 if (ip4fd == -1) {
5861 coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5862 ifname, coap_socket_strerror());
5863 continue;
5864 }
5865 memset(&ifr, 0, sizeof(ifr));
5866 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5867 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5868 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5869 if (result != 0) {
5870 coap_log_err("coap_join_mcast_group_intf: %s: "
5871 "Cannot get IPv4 address: %s\n",
5872 ifname, coap_socket_strerror());
5873 } else {
5874 /* Capture the IPv4 address for later */
5875 mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5876 }
5877 close(ip4fd);
5878#endif /* !ESPIDF_VERSION */
5879 break;
5880#endif /* COAP_IPV4_SUPPORT */
5881 default:
5882 break;
5883 }
5884 }
5885 }
5886#else /* _WIN32 */
5887 /*
5888 * On Windows this function ignores the ifname variable so we unset this
5889 * variable on this platform in any case in order to enable the interface
5890 * selection from the bind address below.
5891 */
5892 ifname = 0;
5893#endif /* _WIN32 */
5894
5895 /* Add in mcast address(es) to appropriate interface */
5896 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5897 for (endpoint = single_endpoint ? single_endpoint : ctx->endpoint;
5898 endpoint != NULL;
5899 endpoint = single_endpoint ? NULL : endpoint->next) {
5900 /* Only UDP currently supported */
5901 if (endpoint->proto == COAP_PROTO_UDP) {
5902 coap_address_t gaddr;
5903
5904 coap_address_init(&gaddr);
5905#if COAP_IPV6_SUPPORT
5906 if (ainfo->ai_family == AF_INET6) {
5907 if (!ifname) {
5908 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5909 /*
5910 * Do it on the ifindex that the server is listening on
5911 * (sin6_scope_id could still be 0)
5912 */
5913 mreq6.ipv6mr_interface =
5914 endpoint->bind_addr.addr.sin6.sin6_scope_id;
5915 } else {
5916 mreq6.ipv6mr_interface = 0;
5917 }
5918 }
5919 gaddr.addr.sin6.sin6_family = AF_INET6;
5920 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
5921 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
5922 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
5923 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
5924 (char *)&mreq6, sizeof(mreq6));
5925 }
5926#endif /* COAP_IPV6_SUPPORT */
5927#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
5928 else
5929#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
5930#if COAP_IPV4_SUPPORT
5931 if (ainfo->ai_family == AF_INET) {
5932 if (!ifname) {
5933 if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
5934 /*
5935 * Do it on the interface that the server is listening on
5936 * (sin_addr could still be INADDR_ANY)
5937 */
5938 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
5939 } else {
5940 mreq4.imr_interface.s_addr = INADDR_ANY;
5941 }
5942 }
5943 gaddr.addr.sin.sin_family = AF_INET;
5944 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
5945 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
5946 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
5947 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5948 (char *)&mreq4, sizeof(mreq4));
5949 }
5950#endif /* COAP_IPV4_SUPPORT */
5951 else {
5952 continue;
5953 }
5954
5955 if (result == COAP_SOCKET_ERROR) {
5956 coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
5957 group_name, coap_socket_strerror());
5958 } else {
5959 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
5960
5961 addr_str[sizeof(addr_str)-1] = '\000';
5962 if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
5963 sizeof(addr_str) - 1)) {
5964 if (ifname)
5965 coap_log_debug("added mcast group %s i/f %s\n", addr_str,
5966 ifname);
5967 else
5968 coap_log_debug("added mcast group %s\n", addr_str);
5969 }
5970 mgroup_setup = 1;
5971 }
5972 }
5973 }
5974 }
5975 if (!mgroup_setup) {
5976 result = -1;
5977 }
5978
5979finish:
5980 freeaddrinfo(resmulti);
5981
5982 return result;
5983}
5984
5985COAP_API int
5987 const char *group_name,
5988 const char *ifname) {
5989 int ret;
5990
5991 if (!endpoint || !endpoint->context)
5992 return -1;
5993
5994 coap_lock_lock(return -1);
5995 ret = coap_join_mcast_group_intf_lkd(endpoint->context, endpoint, group_name, ifname);
5997 return ret;
5998}
5999
6000void
6002 context->mcast_per_resource = 1;
6003}
6004
6005#endif /* ! COAP_SERVER_SUPPORT */
6006
6007#if COAP_CLIENT_SUPPORT
6008int
6009coap_mcast_set_hops(coap_session_t *session, size_t hops) {
6010 if (session && coap_is_mcast(&session->addr_info.remote)) {
6011 switch (session->addr_info.remote.addr.sa.sa_family) {
6012#if COAP_IPV4_SUPPORT
6013 case AF_INET:
6014 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
6015 (const char *)&hops, sizeof(hops)) < 0) {
6016 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
6017 hops, coap_socket_strerror());
6018 return 0;
6019 }
6020 return 1;
6021#endif /* COAP_IPV4_SUPPORT */
6022#if COAP_IPV6_SUPPORT
6023 case AF_INET6:
6024 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
6025 (const char *)&hops, sizeof(hops)) < 0) {
6026 coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
6027 hops, coap_socket_strerror());
6028 return 0;
6029 }
6030 return 1;
6031#endif /* COAP_IPV6_SUPPORT */
6032 default:
6033 break;
6034 }
6035 }
6036 return 0;
6037}
6038#endif /* COAP_CLIENT_SUPPORT */
6039
6040#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
6041COAP_API int
6043 const char *group_name COAP_UNUSED,
6044 const char *ifname COAP_UNUSED) {
6045 return -1;
6046}
6047
6048COAP_API int
6050 const char *group_name COAP_UNUSED,
6051 const char *ifname COAP_UNUSED) {
6052 return -1;
6053}
6054
6055int
6057 size_t hops COAP_UNUSED) {
6058 return 0;
6059}
6060
6061void
6063}
6064#endif /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
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)
int coap_debug_recv_packet(void)
Check to see whether an incoming packet should be dropped or not.
const char * coap_option_string(coap_pdu_code_t code, coap_option_num_t number)
Returns a textual description of the option name.
Definition coap_debug.c:615
void coap_debug_reset(void)
Reset all the defined logging parameters.
#define INET6_ADDRSTRLEN
Definition coap_debug.c:234
struct coap_lg_crcv_t coap_lg_crcv_t
struct coap_endpoint_t coap_endpoint_t
struct coap_async_t coap_async_t
Async Entry information.
struct coap_cache_entry_t coap_cache_entry_t
struct coap_proxy_entry_t coap_proxy_entry_t
Proxy information.
struct coap_subscription_t coap_subscription_t
struct coap_resource_t coap_resource_t
struct coap_lg_srcv_t coap_lg_srcv_t
#define PRIuS
#define PRIdS
#define PRIu32
const char * coap_socket_strerror(void)
Definition coap_io.c:958
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:203
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:70
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:31
#define COAP_SOCKET_ERROR
Definition coap_io.h:51
coap_nack_reason_t
Definition coap_io.h:64
@ COAP_NACK_NOT_DELIVERABLE
Definition coap_io.h:66
@ COAP_NACK_TOO_MANY_RETRIES
Definition coap_io.h:65
@ COAP_NACK_ICMP_ISSUE
Definition coap_io.h:69
@ COAP_NACK_RST
Definition coap_io.h:67
@ COAP_NACK_BAD_RESPONSE
Definition coap_io.h:70
#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:735
void coap_memory_init(void)
Initializes libcoap's memory management.
@ COAP_NODE
Definition coap_mem.h:37
@ COAP_CONTEXT
Definition coap_mem.h:38
@ COAP_STRING
Definition coap_mem.h:33
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:83
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition coap_net.c:1267
static int send_recv_terminate
Definition coap_net.c:106
static coap_crit_type_t coap_is_session_proxy(coap_session_t *session, coap_pdu_t *pdu)
Definition coap_net.c:964
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:3286
static int check_token_size(coap_session_t *session, const coap_pdu_t *pdu, int is_local_mcast)
Definition coap_net.c:4778
#define MAX_BITS
The maximum number of bits for fixed point integers that are used for retransmission time calculation...
Definition coap_net.c:89
void coap_cleanup(void)
Definition coap_net.c:5625
#define ACK_TIMEOUT
creates a Qx.FRAC_BITS from session's 'ack_timeout'
Definition coap_net.c:104
static const char * coap_event_name(coap_event_t event)
Definition coap_net.c:5310
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:3616
int coap_started
Definition coap_net.c:5557
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition coap_net.c:2602
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2643
COAP_STATIC_INLINE void coap_free_node(coap_queue_t *node)
Definition coap_net.c:114
#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:4690
#define min(a, b)
Definition coap_net.c:76
static int prepend_508_ip(coap_session_t *session, coap_pdu_t *pdu)
Definition coap_net.c:2006
void coap_startup(void)
Definition coap_net.c:5574
static unsigned int s_csm_timeout
Definition coap_net.c:540
COAP_STATIC_INLINE coap_queue_t * coap_malloc_node(void)
Definition coap_net.c:109
uint8_t coap_unique_id[8]
Definition coap_net.c:5558
#define FP1
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition coap_net.c:100
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:252
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:378
int coap_dtls_context_load_pki_trust_store(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:268
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:260
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:321
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:316
#define NULL
Definition coap_option.h:30
uint16_t coap_option_num_t
Definition coap_option.h:37
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
@ COAP_SIG_OPT_CUSTODY
coap_sig_csm_opt_t
@ COAP_SIG_OPT_BLOCK_WISE_TRANSFER
@ COAP_SIG_OPT_EXTENDED_TOKEN_LENGTH
@ COAP_SIG_OPT_MAX_MESSAGE_SIZE
@ COAP_OPTION_OBSERVE
Definition coap_option.h:75
@ COAP_OPTION_IF_NONE_MATCH
Definition coap_option.h:74
@ COAP_OPTION_NORESPONSE
Definition coap_option.h:98
@ COAP_OPTION_MAXAGE
Definition coap_option.h:83
@ COAP_OPTION_Q_BLOCK2
Definition coap_option.h:93
@ COAP_OPTION_PROXY_SCHEME
Definition coap_option.h:95
@ COAP_OPTION_HOP_LIMIT
Definition coap_option.h:85
@ COAP_OPTION_URI_PORT
Definition coap_option.h:76
@ COAP_OPTION_URI_HOST
Definition coap_option.h:72
@ COAP_OPTION_BLOCK2
Definition coap_option.h:90
@ COAP_OPTION_IF_MATCH
Definition coap_option.h:71
@ COAP_OPTION_ECHO
Definition coap_option.h:97
@ COAP_OPTION_RTAG
Definition coap_option.h:99
@ COAP_OPTION_BLOCK1
Definition coap_option.h:91
@ COAP_OPTION_URI_PATH
Definition coap_option.h:79
@ COAP_OPTION_Q_BLOCK1
Definition coap_option.h:87
@ COAP_OPTION_OSCORE
Definition coap_option.h:78
@ COAP_OPTION_CONTENT_FORMAT
Definition coap_option.h:80
@ COAP_OPTION_URI_QUERY
Definition coap_option.h:84
@ COAP_OPTION_PROXY_URI
Definition coap_option.h:94
@ COAP_OPTION_URI_PATH_ABB
Definition coap_option.h:81
@ COAP_OPTION_ACCEPT
Definition coap_option.h:86
#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:3012
void coap_reset_doing_first(coap_session_t *session)
Reset doing the first packet state when testing for optional functionality.
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:1222
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:1348
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:1319
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:2942
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:2346
void coap_io_process_remove_threads_lkd(coap_context_t *context)
Release the coap_io_process() worker threads.
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
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:219
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:1629
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:1239
#define COAP_IO_NO_WAIT
Definition coap_net.h:867
#define COAP_IO_WAIT
Definition coap_net.h:866
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:3001
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:2935
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...
#define STATE_TOKEN_BASE(t)
@ 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:94
#define COAP_BLOCK_TRY_Q_BLOCK
Definition coap_block.h:67
#define COAP_BLOCK_SINGLE_BODY
Definition coap_block.h:66
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:71
#define COAP_BLOCK_NO_PREEMPTIVE_RTAG
Definition coap_block.h:69
#define COAP_BLOCK_USE_LIBCOAP
Definition coap_block.h:65
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:161
void coap_clock_init(void)
Initializes the internal clock.
Definition coap_time.c:68
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:149
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:164
#define COAP_MAX_DELAY_TICKS
Definition coap_time.h:231
uint64_t coap_ticks_to_rt_us(coap_tick_t t)
Helper function that converts coap ticks to POSIX wallclock time in us.
Definition coap_time.c:128
void coap_prng_init_lkd(unsigned int seed)
Seeds the default random number generation function with the given seed.
Definition coap_prng.c:183
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:195
#define COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
Define this when invoking coap_resource_unknown_init2() if .well-known/core is to be passed to the un...
#define COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT
This resource has support for multicast requests.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_4_XX
Disable libcoap library suppressing 4.xx multicast responses (overridden by RFC7969 No-Response optio...
#define COAP_RESOURCE_SAFE_REQUEST_HANDLER
Don't lock this resource when calling app call-back handler for requests as handler will not be manip...
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS
Disable libcoap library from adding in delays to multicast requests before releasing the response bac...
void(* coap_method_handler_t)(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
Definition of message handler function.
#define COAP_RESOURCE_FLAGS_OSCORE_ONLY
Define this resource as an OSCORE enabled access only.
#define COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_5_XX
Disable libcoap library suppressing 5.xx multicast responses (overridden by RFC7969 No-Response optio...
uint32_t coap_print_status_t
Status word to encode the result of conditional print or copy operations such as coap_print_link().
#define COAP_PRINT_STATUS_ERROR
#define COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY
Force all large traffic to this resource to be presented as a single body to the request handler.
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_05
Enable libcoap library suppression of 205 multicast responses that are empty (overridden by RFC7969 N...
#define COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_XX
Enable libcoap library suppressing 2.xx multicast responses (overridden by RFC7969 No-Response option...
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:5396
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:119
int coap_delete_node_lkd(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:206
void coap_delete_all(coap_queue_t *queue)
Removes all items from given queue and frees the allocated storage.
Definition coap_net.c:226
int coap_context_set_psk2_lkd(coap_context_t *context, coap_dtls_spsk_t *setup_data)
Set the context's default PSK hint and/or key for a server.
void coap_register_option_lkd(coap_context_t *ctx, coap_option_num_t type)
Registers the option number number with the given context object context.
Definition coap_net.c:5709
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition coap_net.c:249
coap_crit_type_t
COAP_API int coap_delete_node(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:193
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:1497
coap_queue_t * coap_remove_mid_from_delayq(coap_session_t *session, coap_mid_t mid)
This function removes the node with given mid from the delayqueue.
Definition coap_net.c:3182
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.
int coap_option_check_critical(coap_session_t *session, coap_pdu_t *pdu, coap_opt_filter_t *unknown, coap_crit_type_t is_proxy)
Verifies that pdu contains no unknown critical options, duplicate options or the options defined as R...
Definition coap_net.c:1033
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:257
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:4813
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:156
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:1377
void coap_add_to_head_delayq(coap_session_t *session, coap_queue_t *node)
This function adds the node to the head of the delayqueue.
Definition coap_net.c:3228
void coap_free_context_lkd(coap_context_t *context)
CoAP stack context must be released with coap_free_context_lkd().
Definition coap_net.c:856
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:447
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:2116
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:727
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:5487
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2464
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:1564
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:427
int coap_join_mcast_group_intf_lkd(coap_context_t *ctx, coap_endpoint_t *endpoint, const char *groupname, const char *ifname)
Function interface for joining a multicast group for listening for the currently defined endpoints th...
coap_queue_t * coap_remove_first_from_delayq(coap_session_t *session)
This function removes the first node from the delayqueue.
Definition coap_net.c:3204
void coap_add_to_tail_delayq(coap_session_t *session, coap_queue_t *node)
This function adds the node to the tail of the delayqueue.
Definition coap_net.c:3217
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1403
coap_queue_t * coap_new_node(void)
Creates a new node suitable for adding to the CoAP sendqueue.
Definition coap_net.c:235
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:3345
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:3117
int coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t mid, coap_bin_const_t *token, coap_queue_t **node)
This function removes the element with given mid from the list given list.
Definition coap_net.c:3236
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:3384
@ COAP_CRIT_NOT_PROXY
@ COAP_CRIT_PROXY
@ COAP_CRIT_UNKNOWN
void coap_context_set_session_timeout(coap_context_t *context, unsigned int session_timeout)
Set the session timeout value.
Definition coap_net.c:589
unsigned int coap_context_get_max_handshake_sessions(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:536
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:103
unsigned int coap_context_get_max_idle_sessions(const coap_context_t *context)
Get the maximum idle sessions count.
Definition coap_net.c:525
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:2325
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:737
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:1619
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:67
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:1306
void coap_context_set_max_bodies_ram(coap_context_t *context, size_t max_bodies_ram)
Set the maximum supported total pending bodies that are being received.
Definition coap_net.c:491
void coap_context_rate_limit_ppm(coap_context_t *context, uint64_t rate_limit_ppm)
Set the ratelimit for packets per minute.
Definition coap_net.c:472
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:571
void coap_context_set_csm_timeout(coap_context_t *context, unsigned int csm_timeout)
Set the CSM timeout value.
Definition coap_net.c:543
void coap_send_recv_terminate(void)
Terminate any active coap_send_recv() sessions.
Definition coap_net.c:2320
coap_resource_t *(* coap_resource_dynamic_create_t)(coap_session_t *session, const coap_pdu_t *request)
Definition of resource dynamic creation handler function.
Definition coap_net.h:115
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:5653
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:716
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:3417
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:530
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:629
void coap_register_dynamic_resource_handler(coap_context_t *context, coap_resource_dynamic_create_t dyn_create_handler, uint32_t dynamic_max)
Sets up a handler for calling when an unknown resource is requested.
Definition coap_net.c:5693
COAP_API void coap_set_app_data(coap_context_t *context, void *app_data)
Definition coap_net.c:833
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:51
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:92
void coap_ticks(coap_tick_t *t)
Returns the current value of an internal tick counter.
Definition coap_time.c:90
COAP_API void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition coap_net.c:847
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 Acknowledge handler that is used as callback in coap_context_t.
Definition coap_net.h:80
void coap_context_set_shutdown_no_observe(coap_context_t *context)
Definition coap_net.c:620
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:710
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:415
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:702
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:584
unsigned int coap_context_get_session_timeout(const coap_context_t *context)
Get the session timeout value.
Definition coap_net.c:615
COAP_API int coap_endpoint_join_mcast_group_intf(coap_endpoint_t *endpoint, const char *groupname, const char *ifname)
Function interface for joining a multicast group for listening on a single UDP endpoint.
COAP_API int coap_context_set_psk(coap_context_t *context, const char *hint, const uint8_t *key, size_t key_len)
Set the context's default PSK hint and/or key for a server.
COAP_API coap_mid_t coap_send_ack(coap_session_t *session, const coap_pdu_t *request)
Sends an ACK message with code 0 for the specified request to dst.
Definition coap_net.c:1229
unsigned int coap_context_get_csm_timeout_ms(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:566
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:5681
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:841
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:461
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:519
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:1337
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:1212
void coap_context_set_session_reconnect_time2(coap_context_t *context, unsigned int reconnect_time, uint8_t retry_count)
Set the session reconnect delay time after a working client session has failed.
Definition coap_net.c:601
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds)
Set the context keepalive timer for sessions.
Definition coap_net.c:456
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:5477
COAP_API void coap_register_option(coap_context_t *ctx, coap_option_num_t type)
Registers the option number number with the given context object context.
Definition coap_net.c:5702
unsigned int coap_context_get_csm_timeout(const coap_context_t *context)
Get the CSM timeout value.
Definition coap_net.c:550
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:437
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:595
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:5687
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:508
void coap_context_set_max_body_size(coap_context_t *context, size_t max_body_size)
Set the maximum supported body size.
Definition coap_net.c:482
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:5385
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:5675
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:556
@ COAP_RESPONSE_FAIL
Response not liked - send CoAP RST packet.
Definition coap_net.h:52
@ COAP_RESPONSE_OK
Response is fine.
Definition coap_net.h:53
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:109
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_set_cid_tuple_change(coap_context_t *context, uint8_t every)
Set the Connection ID client tuple frequency change for testing CIDs.
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:113
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:312
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:50
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:71
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:81
coap_event_t
Scalar type to represent different events, e.g.
Definition coap_event.h:36
@ COAP_EVENT_OSCORE_DECODE_ERROR
Triggered when there is an OSCORE decode of OSCORE option failure.
Definition coap_event.h:130
@ COAP_EVENT_SESSION_CONNECTED
Triggered when TCP layer completes exchange of CSM information.
Definition coap_event.h:63
@ COAP_EVENT_RECONNECT_FAILED
Triggered when a session failed, and a reconnect is going to be attempted.
Definition coap_event.h:149
@ COAP_EVENT_OSCORE_INTERNAL_ERROR
Triggered when there is an OSCORE internal error i.e malloc failed.
Definition coap_event.h:128
@ COAP_EVENT_DTLS_CLOSED
Triggerrd when (D)TLS session closed.
Definition coap_event.h:41
@ COAP_EVENT_TCP_FAILED
Triggered when TCP layer fails for some reason.
Definition coap_event.h:57
@ COAP_EVENT_WS_CONNECTED
Triggered when the WebSockets layer is up.
Definition coap_event.h:137
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:43
@ COAP_EVENT_BLOCK_ISSUE
Triggered when a block transfer could not be handled.
Definition coap_event.h:77
@ COAP_EVENT_SESSION_FAILED
Triggered when TCP layer fails following exchange of CSM information.
Definition coap_event.h:67
@ COAP_EVENT_PARTIAL_BLOCK
Triggered when not all of a large body has been received.
Definition coap_event.h:73
@ COAP_EVENT_XMIT_BLOCK_FAIL
Triggered when not all of a large body has been transmitted.
Definition coap_event.h:75
@ 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:89
@ COAP_EVENT_OSCORE_NOT_ENABLED
Triggered when trying to use OSCORE to decrypt, but it is not enabled.
Definition coap_event.h:122
@ COAP_EVENT_RECONNECT_STARTED
Triggered when a session starts to reconnect.
Definition coap_event.h:155
@ COAP_EVENT_WS_CLOSED
Triggered when the WebSockets layer is closed.
Definition coap_event.h:139
@ COAP_EVENT_RECONNECT_NO_MORE
Triggered when a session failed, and retry reconnect attempts failed.
Definition coap_event.h:153
@ COAP_EVENT_SESSION_CLOSED
Triggered when TCP layer closes following exchange of CSM information.
Definition coap_event.h:65
@ COAP_EVENT_FIRST_PDU_FAIL
Triggered when the initial app PDU cannot be transmitted.
Definition coap_event.h:114
@ 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:98
@ COAP_EVENT_OSCORE_NO_SECURITY
Triggered when there is no OSCORE security definition found.
Definition coap_event.h:126
@ COAP_EVENT_DTLS_RENEGOTIATE
Triggered when (D)TLS session renegotiated.
Definition coap_event.h:45
@ COAP_EVENT_BAD_PACKET
Triggered when badly formatted packet received.
Definition coap_event.h:110
@ COAP_EVENT_SERVER_SESSION_CONNECTED
Called in the CoAP IO loop once a server session is active and (D)TLS (if any) is established.
Definition coap_event.h:104
@ COAP_EVENT_MSG_RETRANSMITTED
Triggered when a message is retransmitted.
Definition coap_event.h:112
@ COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD
Triggered when there is no OSCORE encrypted payload provided.
Definition coap_event.h:124
@ COAP_EVENT_RECONNECT_SUCCESS
Triggered when a session failed, and a reconnect is successful.
Definition coap_event.h:151
@ COAP_EVENT_TCP_CLOSED
Triggered when TCP layer is closed.
Definition coap_event.h:55
@ COAP_EVENT_WS_PACKET_SIZE
Triggered when there is an oversize WebSockets packet.
Definition coap_event.h:135
@ COAP_EVENT_TCP_CONNECTED
Triggered when TCP layer connects.
Definition coap_event.h:53
@ COAP_EVENT_OSCORE_DECRYPTION_FAILURE
Triggered when there is an OSCORE decryption failure.
Definition coap_event.h:120
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:144
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:47
#define coap_lock_specific_callback_release(lock, func, failed)
Dummy for no thread-safe code.
coap_mutex_t coap_lock_t
#define coap_lock_callback(func)
Dummy for no thread-safe code.
#define coap_lock_init(lock)
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, func)
Dummy for no thread-safe code.
#define coap_lock_callback_ret_release(r, func, failed)
Dummy for no thread-safe code.
#define coap_lock_unlock()
Dummy for no thread-safe code.
#define coap_lock_check_locked()
Dummy for no thread-safe code.
#define coap_lock_callback_release(func, failed)
Dummy for no thread-safe code.
#define coap_lock_lock(failed)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:126
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition coap_debug.c:103
#define coap_log_alert(...)
Definition coap_debug.h:90
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition coap_debug.c:813
#define coap_log_emerg(...)
Definition coap_debug.h:87
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:241
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:114
#define coap_log_warn(...)
Definition coap_debug.h:108
#define coap_log_err(...)
Definition coap_debug.h:102
@ COAP_LOG_DEBUG
Definition coap_debug.h:64
@ COAP_LOG_WARN
Definition coap_debug.h:61
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_FILTER_SHORT
The number of option types below 256 that can be stored in an option filter.
#define COAP_OPT_ALL
Pre-defined filter that includes all options.
#define COAP_OPT_FILTER_LONG
The number of option types above 255 that can be stored in an option 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:1760
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:197
#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:696
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:550
int coap_pdu_parse_opt(coap_pdu_t *pdu, coap_opt_filter_t *error_opts)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition coap_pdu.c:1450
#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:1165
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:1081
#define COAP_PDU_DELAYED
#define COAP_PDU_IS_EMPTY(pdu)
#define COAP_DEFAULT_MAX_PDU_RX_SIZE
#define COAP_PDU_IS_SIGNALING(pdu)
coap_pdu_t * coap_pdu_duplicate_lkd(const coap_pdu_t *old_pdu, coap_session_t *session, size_t token_length, const uint8_t *token, coap_opt_filter_t *drop_options, coap_bool_t expand_opt_abb)
Duplicate an existing PDU.
Definition coap_pdu.c:237
int coap_option_check_repeatable(coap_pdu_t *pdu, coap_option_num_t number)
Check whether the option is allowed to be repeated or not.
Definition coap_pdu.c:644
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:801
#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:1622
#define COAP_DEFAULT_VERSION
int coap_pdu_parse2(coap_proto_t proto, const uint8_t *data, size_t length, coap_pdu_t *pdu, coap_opt_filter_t *error_opts)
Parses data into the CoAP PDU structure given in result.
Definition coap_pdu.c:1598
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:1112
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:340
COAP_STATIC_INLINE void coap_pdu_release_lkd(coap_pdu_t *pdu)
#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:863
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition coap_pdu.c:1041
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:184
#define COAP_TOKEN_DEFAULT_MAX
Definition coap_pdu.h:58
#define COAP_TOKEN_EXT_MAX
Definition coap_pdu.h:62
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:96
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:99
coap_pdu_code_t
Set of codes available for a PDU.
Definition coap_pdu.h:248
coap_pdu_type_t
CoAP PDU message type definitions.
Definition coap_pdu.h:70
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:417
int coap_get_data(const coap_pdu_t *pdu, size_t *len, const uint8_t **data)
Retrieves the length and data pointer of specified PDU.
Definition coap_pdu.c:966
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:1588
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:104
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:187
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition coap_pdu.h:55
#define COAP_BERT_BASE
Definition coap_pdu.h:46
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition coap_pdu.h:135
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:935
@ COAP_BOOL_TRUE
Definition coap_pdu.h:296
@ COAP_REQUEST_GET
Definition coap_pdu.h:81
@ COAP_PROTO_WS
Definition coap_pdu.h:240
@ COAP_PROTO_DTLS
Definition coap_pdu.h:237
@ COAP_PROTO_UDP
Definition coap_pdu.h:236
@ COAP_PROTO_TLS
Definition coap_pdu.h:239
@ COAP_PROTO_WSS
Definition coap_pdu.h:241
@ COAP_PROTO_TCP
Definition coap_pdu.h:238
@ COAP_SIGNALING_CODE_ABORT
Definition coap_pdu.h:291
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:287
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:288
@ COAP_REQUEST_CODE_DELETE
Definition coap_pdu.h:254
@ COAP_SIGNALING_CODE_PONG
Definition coap_pdu.h:289
@ COAP_EMPTY_CODE
Definition coap_pdu.h:249
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:251
@ COAP_SIGNALING_CODE_RELEASE
Definition coap_pdu.h:290
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:255
@ COAP_MESSAGE_NON
Definition coap_pdu.h:72
@ COAP_MESSAGE_ACK
Definition coap_pdu.h:73
@ COAP_MESSAGE_CON
Definition coap_pdu.h:71
@ COAP_MESSAGE_RST
Definition coap_pdu.h:74
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:5664
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:134
#define COAP_NON_RECEIVE_TIMEOUT_TICKS(s)
The NON_RECEIVE_TIMEOUT definition for the session (s).
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.
void coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition coap_net.c:2674
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:1254
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_EXT_T_NOT_CHECKED
Not checked.
@ COAP_EXT_T_CHECKING
Token size check request sent.
@ COAP_EXT_T_CHECKED
Token size valid.
@ COAP_OSCORE_B_2_NONE
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_SERVER
server-side
@ 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:130
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:81
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:119
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:114
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:222
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:208
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:50
int coap_epoll_is_supported(void)
Determine whether epoll is supported or not.
Definition coap_net.c:639
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:693
int coap_ipv6_is_supported(void)
Check whether IPv6 is available.
Definition coap_net.c:666
int coap_threadsafe_is_supported(void)
Determine whether libcoap is threadsafe or not.
Definition coap_net.c:648
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:684
int coap_client_is_supported(void)
Check whether Client code is available.
Definition coap_net.c:675
int coap_ipv4_is_supported(void)
Check whether IPv4 is available.
Definition coap_net.c:657
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition coap_uri.c:1182
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:351
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:1103
void coap_delete_upa_chain(coap_upa_chain_t *chain)
Clean up a UPA chain.
Definition coap_uri.c:1271
coap_upa_chain_t * coap_upa_server_mapping_chain
Definition coap_uri.c:33
coap_upa_chain_t * coap_upa_client_fallback_chain
Definition coap_uri.c:32
#define COAP_UNUSED
Definition libcoap.h:74
#define COAP_STATIC_INLINE
Definition libcoap.h:57
coap_address_t remote
remote address and port
Definition coap_io.h:58
coap_address_t local
local address and port
Definition coap_io.h:59
Multi-purpose address abstraction.
struct sockaddr_in sin
struct sockaddr_in6 sin6
struct sockaddr sa
union coap_address_t::@032315241173221017152166135357032361306034330321 addr
CoAP binary data definition with const data.
Definition coap_str.h:65
size_t length
length of binary data
Definition coap_str.h:66
const uint8_t * s
read-only binary data
Definition coap_str.h:67
CoAP binary data definition.
Definition coap_str.h:57
size_t length
length of binary data
Definition coap_str.h:58
uint8_t * s
binary data
Definition coap_str.h:59
Structure of Block options with BERT support.
Definition coap_block.h:55
unsigned int num
block number
Definition coap_block.h:56
uint32_t chunk_size
Definition coap_block.h:62
unsigned int bert
Operating as BERT.
Definition coap_block.h:61
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:59
unsigned int defined
Set if block found.
Definition coap_block.h:60
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:57
unsigned int szx
block size (0-6)
Definition coap_block.h:58
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.
uint64_t rl_ticks_per_packet
If not 0, rate limit NON to ticks per packet.
coap_app_data_free_callback_t app_cb
call-back to release app_data
coap_pong_handler_t pong_cb
Called when a ping response is received.
coap_nack_handler_t nack_cb
Called when a response issue has occurred.
coap_resource_dynamic_create_t dyn_create_handler
Dynamic resource create handler.
void * app_data
application-specific data
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
uint32_t dynamic_max
Max number of dynamic resources or 0 is unlimited.
coap_event_handler_t event_cb
Callback function that is used to signal events to the application.
size_t max_body_size
Max supported body size or 0 is unlimited.
coap_opt_filter_t known_options
uint32_t csm_max_message_size
Value for CSM Max-Message-Size.
unsigned int max_handshake_sessions
Maximum number of simultaneous negotiating sessions per endpoint.
coap_ping_handler_t ping_cb
Called when a CoAP ping is received.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
uint32_t csm_timeout_ms
Timeout for waiting for a CSM from the remote side.
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
coap_bin_const_t key
Definition coap_dtls.h:389
coap_bin_const_t identity
Definition coap_dtls.h:388
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:451
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:317
uint8_t version
Definition coap_dtls.h:318
coap_bin_const_t hint
Definition coap_dtls.h:459
coap_bin_const_t key
Definition coap_dtls.h:460
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:509
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:541
uint64_t state_token
state token
uint32_t count
the number of packets sent for payload
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) transmission information.
coap_tick_t last_all_sent
Last time all data sent or 0.
uint8_t blk_size
large block transmission size
union coap_lg_xmit_t::@133113107100342355167305061112145335023127201276 b
int last_block
last acknowledged block number Block1 last transmitted Q-Block2
coap_pdu_t * sent_pdu
The sent pdu with all the data.
coap_l_block1_t b1
uint16_t option
large block transmission CoAP option
uint8_t short_opts[COAP_OPT_FILTER_SHORT]
uint16_t long_opts[COAP_OPT_FILTER_LONG]
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
uint16_t max_opt
highest option number in PDU
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
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 virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
volatile uint8_t max_token_checked
Check for max token size coap_ext_token_check_t.
uint8_t csm_not_seen
Set if timeout waiting for CSM.
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
uint8_t 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.
uint32_t ping_failed
Ping failure count.
coap_bin_const_t * psk_identity
If client, this field contains the current identity for server; When this field is NULL,...
coap_session_state_t state
current state of relationship with peer
uint8_t csm_bert_rem_support
CSM TCP BERT blocks supported (remote).
coap_mid_t last_resp_mid
The last response mid that has been been processed.
uint8_t is_rate_limiting
Currently NON rate limiting.
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
uint8_t csm_bert_loc_support
CSM TCP BERT blocks supported (local).
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_tick_t last_tx
Last time a ratelimited packet is sent.
coap_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
coap_bin_const_t * last_token
uint8_t no_path_abbrev
Set is remote does not support Uri-Path-Abbrev.
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
uint64_t rl_ticks_per_packet
If not 0, rate limit NON to ticks per packet.
coap_session_type_t type
client or server side socket
coap_context_t * context
session's context
coap_queue_t * delayqueue_tail
tail of delayqueue for O(1) append
size_t partial_write
if > 0 indicates number of bytes already written from the pdu at the head of sendqueue
coap_bin_const_t * echo
last token used to make a request
coap_layer_func_t lfunc[COAP_LAYER_LAST]
Layer functions to use.
coap_session_t * session
Used to determine session owner.
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values
CoAP string data definition with const data.
Definition coap_str.h:47
const uint8_t * s
read-only string data
Definition coap_str.h:49
size_t length
length of string
Definition coap_str.h:48
CoAP string data definition.
Definition coap_str.h:39
uint8_t * s
string data
Definition coap_str.h:41
size_t length
length of string
Definition coap_str.h:40
Representation of parsed URI.
Definition coap_uri.h:70
coap_str_const_t host
The host part of the URI.
Definition coap_uri.h:71