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