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