libcoap 4.3.5-develop-daa4e05
Loading...
Searching...
No Matches
coap_session.c
Go to the documentation of this file.
1/* coap_session.c -- Session management for libcoap
2 *
3 * Copyright (C) 2017 Jean-Claue Michelou <jcm@spinetix.com>
4 * Copyright (C) 2022-2025 Jon Shallow <supjps-libcoap@jpshallow.com>
5 *
6 * SPDX-License-Identifier: BSD-2-Clause
7 *
8 * This file is part of the CoAP library libcoap. Please see
9 * README for terms of use.
10 */
11
18
19#ifndef COAP_SESSION_C_
20#define COAP_SESSION_C_
21
22#include <stdio.h>
23
24#ifdef COAP_EPOLL_SUPPORT
25#include <sys/epoll.h>
26#include <sys/timerfd.h>
27#endif /* COAP_EPOLL_SUPPORT */
28
32 uint32_t fr = fp1.fractional_part * fp2.fractional_part;
33
34 res.integer_part = fp1.integer_part * fp2.integer_part + fr/1000;
35 res.fractional_part = fr % 1000;
36 return res;
37}
38
42 uint32_t fr = fp1.fractional_part * u2;
43
44 res.integer_part = fp1.integer_part * u2 + fr/1000;
45 res.fractional_part = fr % 1000;
46 return res;
47}
48
52 uint32_t fr = fp1.fractional_part + fp2.fractional_part;
53
54 res.integer_part = fp1.integer_part + fp2.integer_part + fr/1000;
55 res.fractional_part = fr % 1000;
56 return res;
57}
58
61 coap_fixed_point_t res = fp1;
62
63 res.integer_part += u2;
64 return res;
65}
66
69 coap_fixed_point_t res = fp1;
70
71 res.integer_part -= u2;
72 return res;
73}
74
78 uint32_t num = (fp1.integer_part * 1000 + fp1.fractional_part) / u2;
79
80 res.integer_part = num / 1000;
81 res.fractional_part = num % 1000;
82 return res;
83}
84
85#if COAP_Q_BLOCK_SUPPORT
89 uint8_t ran;
90
91 coap_prng_lkd(&ran, sizeof(ran));
93 res = coap_multi_fixed_uint(res, ran);
94 res = coap_div_fixed_uint(res, 0xff);
95 res = coap_add_fixed_fixed(COAP_NON_TIMEOUT(session), res);
96 return res;
97}
98
104
105 return ticks;
106}
107
108/*
109 * Save away derived Congestion Control parameters for speed of access.
110 * They will get updated whenever a component variable is updated.
111 */
112
113/*
114 * NON_PROBING_WAIT = NON_TIMEOUT * ((2 ** NON_MAX_RETRANSMIT) - 1) *
115 * ACK_RANDOM_FACTOR + (2 * MAX_LATENCY) + NON_TIMEOUT_RANDOM
116 *
117 * Do not include NON_TIMEOUT_RANDOM as that changes
118 */
119static void
120coap_session_fix_non_probing_wait_base(coap_session_t *s) {
122
124 ((1 << (COAP_NON_MAX_RETRANSMIT(s) + 1)) -1));
128}
129
130/*
131 * NON_PARTIAL_TIMEOUT = NON_TIMEOUT * ((2 ** NON_MAX_RETRANSMIT) - 1) *
132 * ACK_RANDOM_FACTOR + (2 * MAX_LATENCY) + NON_TIMEOUT
133 */
134static void
135coap_session_fix_non_partial_timeout(coap_session_t *s) {
137
139 ((1 << (COAP_NON_MAX_RETRANSMIT(s) + 1)) -1));
144}
145#endif /* COAP_Q_BLOCK_SUPPORT */
146
147void
149 if (value.integer_part > 0 && value.fractional_part < 1000) {
150 session->ack_timeout = value;
151 coap_log_debug("***%s: session ack_timeout set to %u.%03u\n",
152 coap_session_str(session), session->ack_timeout.integer_part,
154 }
155}
156
157void
159 coap_fixed_point_t value) {
160 if (value.integer_part > 0 && value.fractional_part < 1000) {
161 session->ack_random_factor = value;
162 coap_log_debug("***%s: session ack_random_factor set to %u.%03u\n",
165#if COAP_Q_BLOCK_SUPPORT
166 coap_session_fix_non_probing_wait_base(session);
167 coap_session_fix_non_partial_timeout(session);
168#endif /* COAP_Q_BLOCK_SUPPORT */
169 }
170 return;
171}
172
173void
175 if (value > 0) {
176 session->max_retransmit = value;
177 coap_log_debug("***%s: session max_retransmit set to %u\n",
178 coap_session_str(session), session->max_retransmit);
179 }
180}
181
182void
183coap_session_set_nstart(coap_session_t *session, uint16_t value) {
184 if (value > 0) {
185 session->nstart = value;
186 coap_log_debug("***%s: session nstart set to %u\n",
187 coap_session_str(session), session->nstart);
188 }
189}
190
191void
193 coap_fixed_point_t value) {
194 if (value.integer_part > 0 && value.fractional_part < 1000) {
195 session->default_leisure = value;
196 coap_log_debug("***%s: session default_leisure set to %u.%03u\n",
199 }
200}
201
202void
204 if (value > 0) {
205 session->probing_rate = value;
206 coap_log_debug("***%s: session probing_rate set to %" PRIu32 "\n",
207 coap_session_str(session), session->probing_rate);
208 }
209}
210
211void
213#if COAP_Q_BLOCK_SUPPORT
214 if (value > 0) {
215 session->max_payloads = value;
216 coap_log_debug("***%s: session max_payloads set to %u\n",
217 coap_session_str(session), session->max_payloads);
218 coap_session_fix_non_probing_wait_base(session);
219 coap_session_fix_non_partial_timeout(session);
220 }
221#else /* ! COAP_Q_BLOCK_SUPPORT */
222 (void)session;
223 (void)value;
224#endif /* ! COAP_Q_BLOCK_SUPPORT */
225}
226
227void
229#if COAP_Q_BLOCK_SUPPORT
230 if (value > 0) {
231 session->non_max_retransmit = value;
232 coap_log_debug("***%s: session non_max_retransmit set to %u\n",
233 coap_session_str(session), session->non_max_retransmit);
234 coap_session_fix_non_probing_wait_base(session);
235 coap_session_fix_non_partial_timeout(session);
236 }
237#else /* ! COAP_Q_BLOCK_SUPPORT */
238 (void)session;
239 (void)value;
240#endif /* ! COAP_Q_BLOCK_SUPPORT */
241}
242
243void
245 coap_fixed_point_t value) {
246#if COAP_Q_BLOCK_SUPPORT
247 if (value.integer_part > 0 && value.fractional_part < 1000) {
248 session->non_timeout = value;
249 coap_log_debug("***%s: session non_timeout set to %u.%03u\n",
250 coap_session_str(session), session->non_timeout.integer_part,
251 session->non_timeout.fractional_part);
252 coap_session_fix_non_probing_wait_base(session);
253 coap_session_fix_non_partial_timeout(session);
254 }
255#else /* ! COAP_Q_BLOCK_SUPPORT */
256 (void)session;
257 (void)value;
258#endif /* ! COAP_Q_BLOCK_SUPPORT */
259}
260
261void
263 coap_fixed_point_t value) {
264#if COAP_Q_BLOCK_SUPPORT
265 if (value.integer_part > 0 && value.fractional_part < 1000)
266 session->non_receive_timeout = value;
267 coap_log_debug("***%s: session non_receive_timeout set to %u.%03u\n",
268 coap_session_str(session),
269 session->non_receive_timeout.integer_part,
270 session->non_receive_timeout.fractional_part);
271#else /* ! COAP_Q_BLOCK_SUPPORT */
272 (void)session;
273 (void)value;
274#endif /* ! COAP_Q_BLOCK_SUPPORT */
275}
276
279 return session->ack_timeout;
280}
281
284 return session->ack_random_factor;
285}
286
287uint16_t
289 return session->max_retransmit;
290}
291
292uint16_t
294 return session->nstart;
295}
296
299 return session->default_leisure;
300}
301
302uint32_t
304 return session->probing_rate;
305}
306
307uint16_t
309#if COAP_Q_BLOCK_SUPPORT
310 return session->max_payloads;
311#else /* ! COAP_Q_BLOCK_SUPPORT */
312 (void)session;
314#endif /* ! COAP_Q_BLOCK_SUPPORT */
315}
316
317uint16_t
319#if COAP_Q_BLOCK_SUPPORT
320 return session->non_max_retransmit;
321#else /* ! COAP_Q_BLOCK_SUPPORT */
322 (void)session;
324#endif /* ! COAP_Q_BLOCK_SUPPORT */
325}
326
329#if COAP_Q_BLOCK_SUPPORT
330 return session->non_timeout;
331#else /* ! COAP_Q_BLOCK_SUPPORT */
332 (void)session;
334#endif /* ! COAP_Q_BLOCK_SUPPORT */
335}
336
339#if COAP_Q_BLOCK_SUPPORT
340 return session->non_receive_timeout;
341#else /* ! COAP_Q_BLOCK_SUPPORT */
342 (void)session;
344#endif /* ! COAP_Q_BLOCK_SUPPORT */
345}
346
349 coap_lock_lock(session->context, return NULL);
351 coap_lock_unlock(session->context);
352 return session;
353}
354
357 ++session->ref;
358 return session;
359}
360
361COAP_API void
363 if (session) {
364#if COAP_THREAD_SAFE
365 coap_context_t *context = session->context;
366 (void)context;
367#endif /* COAP_THREAD_SAFE */
368
369 coap_lock_lock(context, return);
371 coap_lock_unlock(context);
372 }
373}
374
375void
377 if (session) {
379#ifndef __COVERITY__
380 assert(session->ref > 0);
381 if (session->ref > 0)
382 --session->ref;
383 if (session->ref == 0 && session->type == COAP_SESSION_TYPE_CLIENT)
384 coap_session_free(session);
385#else /* __COVERITY__ */
386 /* Coverity scan is fooled by the reference counter leading to
387 * false positives for USE_AFTER_FREE. */
388 --session->ref;
389 __coverity_negative_sink__(session->ref);
390 /* Indicate that resources are released properly. */
391 if (session->ref == 0 && session->type == COAP_SESSION_TYPE_CLIENT) {
392 __coverity_free__(session);
393 }
394#endif /* __COVERITY__ */
395 }
396}
397
398COAP_API void
399coap_session_set_app_data(coap_session_t *session, void *app_data) {
400 assert(session);
401 coap_lock_lock(session->context, return);
402 coap_session_set_app_data2_lkd(session, app_data, NULL);
403 coap_lock_unlock(session->context);
404}
405
406void *
408 assert(session);
409 return session->app_data;
410}
411
412COAP_API void *
415 void *old_data;
416
417 coap_lock_lock(session->context, return NULL);
418 old_data = coap_session_set_app_data2_lkd(session, app_data, callback);
419 coap_lock_unlock(session->context);
420 return old_data;
421}
422
423void *
426 void *old_data = session->app_data;
427
428 session->app_data = app_data;
429 session->app_cb = app_data ? callback : NULL;
430 return old_data;
431}
432
433static coap_session_t *
435 const coap_addr_hash_t *addr_hash,
436 const coap_address_t *local_addr,
437 const coap_address_t *remote_addr, int ifindex,
438 coap_context_t *context, coap_endpoint_t *endpoint) {
440 sizeof(coap_session_t));
441#if ! COAP_SERVER_SUPPORT
442 (void)endpoint;
443#endif /* ! COAP_SERVER_SUPPORT */
444 if (!session)
445 return NULL;
446 memset(session, 0, sizeof(*session));
447 session->proto = proto;
448 session->type = type;
449 if (addr_hash)
450 memcpy(&session->addr_hash, addr_hash, sizeof(session->addr_hash));
451 else
452 memset(&session->addr_hash, 0, sizeof(session->addr_hash));
453 if (local_addr) {
454 coap_address_copy(&session->addr_info.local, local_addr);
455#if COAP_CLIENT_SUPPORT
456 coap_address_copy(&session->local_reconnect, local_addr);
457#endif /* COAP_CLIENT_SUPPORT */
458 } else {
460#if COAP_CLIENT_SUPPORT
462#endif /* COAP_CLIENT_SUPPORT */
463 }
464 if (remote_addr)
465 coap_address_copy(&session->addr_info.remote, remote_addr);
466 else
468 session->ifindex = ifindex;
469 session->context = context;
470#if COAP_SERVER_SUPPORT
471 session->endpoint = endpoint;
472 if (endpoint)
473 session->mtu = endpoint->default_mtu;
474 else
475#endif /* COAP_SERVER_SUPPORT */
477 session->block_mode = context->block_mode;
478 if (proto == COAP_PROTO_DTLS) {
479 session->tls_overhead = 29;
480 if (session->tls_overhead >= session->mtu) {
481 session->tls_overhead = session->mtu;
482 coap_log_err("DTLS overhead exceeds MTU\n");
483 }
484 }
488 session->nstart = COAP_DEFAULT_NSTART;
491#if COAP_Q_BLOCK_SUPPORT
492 session->max_payloads = COAP_DEFAULT_MAX_PAYLOADS;
493 session->non_max_retransmit = COAP_DEFAULT_NON_MAX_RETRANSMIT;
494 session->non_timeout = COAP_DEFAULT_NON_TIMEOUT;
495 session->non_receive_timeout = COAP_DEFAULT_NON_RECEIVE_TIMEOUT;
496 coap_session_fix_non_probing_wait_base(session);
497 coap_session_fix_non_partial_timeout(session);
498#endif /* COAP_Q_BLOCK_SUPPORT */
499 session->dtls_event = -1;
504 session->max_token_size = context->max_token_size; /* RFC8974 */
505 if (session->type != COAP_SESSION_TYPE_CLIENT)
507
508 /* Randomly initialize */
509 /* TCP/TLS have no notion of mid */
510 if (COAP_PROTO_NOT_RELIABLE(session->proto))
511 coap_prng_lkd((unsigned char *)&session->tx_mid, sizeof(session->tx_mid));
512 coap_prng_lkd((unsigned char *)&session->tx_rtag, sizeof(session->tx_rtag));
513
514 return session;
515}
516
517void
519 coap_queue_t *q, *tmp;
520 coap_lg_xmit_t *lq, *ltmp;
521
522#if COAP_CLIENT_SUPPORT
523 coap_lg_crcv_t *lg_crcv, *etmp;
524
525 /* Need to do this before (D)TLS and socket is closed down */
526 LL_FOREACH_SAFE(session->lg_crcv, lg_crcv, etmp) {
527 if (lg_crcv->observe_set && session->no_observe_cancel == 0) {
528 /* Need to close down observe */
529 if (coap_cancel_observe_lkd(session, lg_crcv->app_token, COAP_MESSAGE_NON)) {
530 /* Need to delete node we set up for NON */
531 coap_queue_t *queue = session->context->sendqueue;
532
533 while (queue) {
534 if (queue->session == session) {
536 break;
537 }
538 queue = queue->next;
539 }
540 }
541 }
542 LL_DELETE(session->lg_crcv, lg_crcv);
543 coap_block_delete_lg_crcv(session, lg_crcv);
544 }
545#endif /* COAP_CLIENT_SUPPORT */
546
547 if (session->partial_pdu)
549 if (session->sock.lfunc[COAP_LAYER_SESSION].l_close)
550 session->sock.lfunc[COAP_LAYER_SESSION].l_close(session);
551 if (session->psk_identity)
553 if (session->psk_key)
555 if (session->psk_hint)
557
558#if COAP_SERVER_SUPPORT
559 coap_cache_entry_t *cp, *ctmp;
560 HASH_ITER(hh, session->context->cache, cp, ctmp) {
561 /* cp->session is NULL if not session based */
562 if (cp->session == session) {
563 coap_delete_cache_entry(session->context, cp);
564 }
565 }
566#endif /* COAP_SERVER_SUPPORT */
567 LL_FOREACH_SAFE(session->delayqueue, q, tmp) {
568 if (q->pdu->type==COAP_MESSAGE_CON) {
569 coap_handle_nack(session, q->pdu,
570 session->proto == COAP_PROTO_DTLS ?
572 q->id);
573 }
575 }
576 LL_FOREACH_SAFE(session->lg_xmit, lq, ltmp) {
577 LL_DELETE(session->lg_xmit, lq);
578 coap_block_delete_lg_xmit(session, lq);
579 }
580#if COAP_SERVER_SUPPORT
581 coap_lg_srcv_t *sq, *stmp;
582
583 LL_FOREACH_SAFE(session->lg_srcv, sq, stmp) {
584 LL_DELETE(session->lg_srcv, sq);
585 coap_block_delete_lg_srcv(session, sq);
586 }
587#endif /* COAP_SERVER_SUPPORT */
588#if COAP_OSCORE_SUPPORT
590#endif /* COAP_OSCORE_SUPPORT */
591#if COAP_WS_SUPPORT
592 coap_free_type(COAP_STRING, session->ws);
593 coap_delete_str_const(session->ws_host);
594#endif /* COAP_WS_SUPPORT */
595}
596
597void
599 if (!session)
600 return;
602 assert(session->ref == 0);
603 if (session->ref)
604 return;
605 /* Make sure nothing gets deleted under our feet */
607 coap_session_mfree(session);
608#if COAP_SERVER_SUPPORT
610 if (session->endpoint) {
611 if (session->endpoint->sessions)
612 SESSIONS_DELETE(session->endpoint->sessions, session);
613 } else
614#endif /* COAP_SERVER_SUPPORT */
615#if COAP_CLIENT_SUPPORT
616 if (session->context) {
617 if (session->context->sessions)
618 SESSIONS_DELETE(session->context->sessions, session);
619 }
621#endif /* COAP_CLIENT_SUPPORT */
623 coap_delete_bin_const(session->echo);
624#if COAP_SERVER_SUPPORT
626#endif /* COAP_SERVER_SUPPORT */
627 coap_log_debug("***%s: session %p: closed\n", coap_session_str(session),
628 (void *)session);
629
630 if (session->app_cb) {
631 session->app_cb(session->app_data);
632 }
633 assert(session->ref == 1);
635}
636
637#if COAP_SERVER_SUPPORT
638void
640 int i;
641
644 coap_cancel_all_messages(session->context, session, NULL);
645 RESOURCES_ITER(session->context->resources, r) {
646 /* In case code is broken somewhere */
647 for (i = 0; i < 1000; i++) {
648 if (!coap_delete_observer(r, session, NULL))
649 break;
650 }
651 }
652 if (session->context->unknown_resource) {
653 /* In case code is broken somewhere */
654 for (i = 0; i < 1000; i++) {
655 if (!coap_delete_observer(session->context->unknown_resource, session, NULL))
656 break;
657 }
658 }
659 if (session->context->proxy_uri_resource) {
660 /* In case code is broken somewhere */
661 for (i = 0; i < 1000; i++) {
662 if (!coap_delete_observer(session->context->proxy_uri_resource, session, NULL))
663 break;
664 }
665 }
666 while (session->delayqueue) {
667 coap_queue_t *q = session->delayqueue;
668
669 session->delayqueue = q->next;
671 }
672 /* Force session to go away */
675
677}
678#endif /* COAP_SERVER_SUPPORT */
679
680static size_t
682 size_t max_with_header) {
683#if COAP_DISABLE_TCP
684 (void)session;
685 return max_with_header > COAP_PDU_MAX_UDP_HEADER_SIZE
686 ? max_with_header - COAP_PDU_MAX_UDP_HEADER_SIZE
687 : 0;
688#else /* !COAP_DISABLE_TCP */
689 if (COAP_PROTO_NOT_RELIABLE(session->proto))
690 return max_with_header > COAP_PDU_MAX_UDP_HEADER_SIZE
691 ? max_with_header - COAP_PDU_MAX_UDP_HEADER_SIZE
692 : 0;
693 /* we must assume there is no token to be on the safe side */
694 if (max_with_header <= 2)
695 return 0;
696 else if (max_with_header <= COAP_MAX_MESSAGE_SIZE_TCP0 + 2)
697 return max_with_header - 2;
698 else if (max_with_header <= COAP_MAX_MESSAGE_SIZE_TCP8 + 3)
699 return max_with_header - 3;
700 else if (max_with_header <= COAP_MAX_MESSAGE_SIZE_TCP16 + 4)
701 return max_with_header - 4;
702 else
703 return max_with_header - COAP_PDU_MAX_TCP_HEADER_SIZE;
704#endif /* !COAP_DISABLE_TCP */
705}
706
707size_t
709 if (session->csm_rcv_mtu)
711 (size_t)(session->csm_rcv_mtu));
712
714 (size_t)(session->mtu - session->tls_overhead));
715}
716
717COAP_API size_t
719 size_t size;
720 coap_session_t *session_rw;
721
722 /*
723 * Need to do this to not get a compiler warning about const parameters
724 * but need to maintain source code backward compatibility
725 */
726 memcpy(&session_rw, &session, sizeof(session_rw));
727 coap_lock_lock(session_rw->context, return 0);
728 size = coap_session_max_pdu_size_lkd(session_rw);
729 coap_lock_unlock(session_rw->context);
730 return size;
731}
732
733size_t
735 size_t max_with_header;
736
738#if COAP_CLIENT_SUPPORT
739 /*
740 * Delay if session->doing_first is set.
741 * E.g. Reliable and CSM not in yet for checking block support
742 */
743 coap_session_t *session_rw;
744
745 /*
746 * Need to do this to not get a compiler warning about const parameters
747 * but need to maintain source code backward compatibility
748 */
749 memcpy(&session_rw, &session, sizeof(session_rw));
750 if (coap_client_delay_first(session_rw) == 0) {
751 coap_log_debug("coap_client_delay_first: timeout\n");
752 /* Have to go with the defaults */
753 }
754#endif /* COAP_CLIENT_SUPPORT */
755
756 max_with_header = (size_t)(session->mtu - session->tls_overhead);
757
758 return coap_session_max_pdu_size_internal(session, max_with_header);
759}
760
761void
762coap_session_set_mtu(coap_session_t *session, unsigned mtu) {
763#if defined(WITH_CONTIKI) || defined(WITH_LWIP)
764 if (mtu > COAP_DEFAULT_MAX_PDU_RX_SIZE)
765 mtu = COAP_DEFAULT_MAX_PDU_RX_SIZE;
766#endif
767 if (mtu < 64)
768 mtu = 64;
769 session->mtu = mtu;
770 if (session->tls_overhead >= session->mtu) {
771 session->tls_overhead = session->mtu;
772 coap_log_err("DTLS overhead exceeds MTU\n");
773 }
774}
775
776ssize_t
778 coap_queue_t *node) {
779 if (node) {
780 coap_queue_t *removed = NULL;
781 coap_remove_from_queue(&session->context->sendqueue, session, node->id, &removed);
782 assert(removed == node);
784 node->session = NULL;
785 node->t = 0;
786 } else {
787 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
788 coap_queue_t *q = NULL;
789 /* Check same mid is not getting re-used in violation of RFC7252 */
790 LL_FOREACH(session->delayqueue, q) {
791 if (q->id == pdu->mid) {
792 coap_log_err("** %s: mid=0x%04x: already in-use - dropped\n",
793 coap_session_str(session), pdu->mid);
794 return COAP_INVALID_MID;
795 }
796 }
797 }
798 node = coap_new_node();
799 if (node == NULL)
800 return COAP_INVALID_MID;
801 node->id = pdu->mid;
802 node->pdu = pdu;
803 if (pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) {
804 uint8_t r;
805 coap_prng_lkd(&r, sizeof(r));
806 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
807 node->timeout = coap_calc_timeout(session, r);
808 }
809 coap_address_copy(&node->remote, &session->addr_info.remote);
810 }
811 LL_APPEND(session->delayqueue, node);
812 coap_log_debug("** %s: mid=0x%04x: delayed\n",
813 coap_session_str(session), node->id);
814 return COAP_PDU_DELAYED;
815}
816
817#if !COAP_DISABLE_TCP
818void
820 coap_pdu_t *pdu;
821 uint8_t buf[4];
822 assert(COAP_PROTO_RELIABLE(session->proto));
823 coap_log_debug("***%s: sending CSM\n", coap_session_str(session));
824 session->state = COAP_SESSION_STATE_CSM;
825 session->partial_write = 0;
826 if (session->mtu == 0)
827 coap_session_set_mtu(session, COAP_DEFAULT_MTU); /* base value */
829 if (pdu == NULL
831 coap_encode_var_safe(buf, sizeof(buf),
832 session->context->csm_max_message_size), buf) == 0
834 coap_encode_var_safe(buf, sizeof(buf),
835 0), buf) == 0
836 || (session->max_token_size > COAP_TOKEN_DEFAULT_MAX &&
839 coap_encode_var_safe(buf, sizeof(buf),
840 session->max_token_size),
841 buf) == 0)
842 || coap_pdu_encode_header(pdu, session->proto) == 0
843 ) {
845 } else {
846 ssize_t bytes_written;
847
848 pdu->session = session;
849 bytes_written = coap_session_send_pdu(session, pdu);
850 if (bytes_written != (ssize_t)pdu->used_size + pdu->hdr_size) {
852 } else {
853 session->csm_rcv_mtu = session->context->csm_max_message_size;
854 if (session->csm_rcv_mtu > COAP_BERT_BASE)
855 session->csm_bert_loc_support = 1;
856 else
857 session->csm_bert_loc_support = 0;
858 }
859 }
860 if (pdu)
862}
863#endif /* !COAP_DISABLE_TCP */
864
867 coap_mid_t mid;
868
869 coap_lock_lock(session->context, return COAP_INVALID_MID);
870 mid = coap_session_send_ping_lkd(session);
871 coap_lock_unlock(session->context);
872 return mid;
873}
874
877 coap_pdu_t *ping = NULL;
878
880 if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
881 session->con_active)
882 return COAP_INVALID_MID;
883 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
884 uint16_t mid = coap_new_message_id_lkd(session);
885 ping = coap_pdu_init(COAP_MESSAGE_CON, 0, mid, 0);
886 }
887#if !COAP_DISABLE_TCP
888 else {
890 }
891#endif /* !COAP_DISABLE_TCP */
892 if (!ping)
893 return COAP_INVALID_MID;
894 return coap_send_internal(session, ping, NULL);
895}
896
897void
899 if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
900 coap_log_debug("***%s: session connected\n",
901 coap_session_str(session));
902 if (session->state == COAP_SESSION_STATE_CSM) {
904#if COAP_CLIENT_SUPPORT
906#endif /* COAP_CLIENT_SUPPORT */
907 if (session->doing_first)
908 session->doing_first = 0;
909 }
910 }
911
913 session->partial_write = 0;
914
915 if (session->proto==COAP_PROTO_DTLS) {
916 session->tls_overhead = coap_dtls_get_overhead(session);
917 if (session->tls_overhead >= session->mtu) {
918 session->tls_overhead = session->mtu;
919 coap_log_err("DTLS overhead exceeds MTU\n");
920 }
921 }
922
923 while (session->delayqueue && session->state == COAP_SESSION_STATE_ESTABLISHED) {
924 ssize_t bytes_written;
925 coap_queue_t *q = session->delayqueue;
926 coap_address_t remote;
927
928 if (q->pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) {
929 if (session->con_active >= COAP_NSTART(session))
930 break;
931 session->con_active++;
932 }
933 /* Take entry off the queue */
934 session->delayqueue = q->next;
935 q->next = NULL;
936
937 coap_address_copy(&remote, &session->addr_info.remote);
939 coap_log_debug("** %s: mid=0x%04x: transmitted after delay (2)\n",
940 coap_session_str(session), (int)q->pdu->mid);
941 bytes_written = coap_session_send_pdu(session, q->pdu);
942 if (q->pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) {
943 if (coap_wait_ack(session->context, session, q) >= 0)
944 q = NULL;
945 }
946 coap_address_copy(&session->addr_info.remote, &remote);
947 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
948 if (q)
950 if (bytes_written < 0)
951 break;
952 } else if (q) {
953 if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size) {
954 q->next = session->delayqueue;
955 session->delayqueue = q;
956 if (bytes_written > 0)
957 session->partial_write = (size_t)bytes_written;
958 break;
959 } else {
961 }
962 }
963 }
964}
965
966#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
967static const char *
969 switch (reason) {
971 return "COAP_NACK_TOO_MANY_RETRIES";
973 return "COAP_NACK_NOT_DELIVERABLE";
974 case COAP_NACK_RST:
975 return "COAP_NACK_RST";
977 return "COAP_NACK_TLS_FAILED";
979 return "COAP_NACK_ICMP_ISSUE";
981 return "COAP_NACK_BAD_RESPONSE";
983 return "COAP_NACK_TLS_LAYER_FAILED";
985 return "COAP_NACK_WS_LAYER_FAILED";
987 return "COAP_NACK_WS_FAILED";
988 default:
989 return "???";
990 }
991}
992#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
993
994void
996 coap_pdu_t *sent,
997 const coap_nack_reason_t reason,
998 const coap_mid_t mid) {
999 if (session->context->nack_handler) {
1000 coap_bin_const_t token = {0, NULL};
1001
1002 if (sent) {
1003 coap_check_update_token(session, sent);
1004 token = sent->actual_token;
1005 }
1006 coap_lock_callback(session->context,
1007 session->context->nack_handler(session, sent, reason, mid));
1008 if (sent) {
1009 coap_update_token(sent, token.length, token.s);
1010 }
1011 }
1012#if COAP_CLIENT_SUPPORT
1013 if (reason != COAP_NACK_ICMP_ISSUE) {
1014 session->doing_send_recv = 0;
1015 }
1016#endif /* COAP_CLIENT_SUPPORT */
1017}
1018
1019COAP_API void
1021 coap_lock_lock(session->context, return);
1022 coap_session_disconnected_lkd(session, reason);
1023 coap_lock_unlock(session->context);
1024}
1025
1026void
1028#if !COAP_DISABLE_TCP
1029 coap_session_state_t state = session->state;
1030#endif /* !COAP_DISABLE_TCP */
1031 coap_lg_xmit_t *lq, *ltmp;
1032#if COAP_SERVER_SUPPORT
1033 coap_lg_srcv_t *sq, *stmp;
1034#endif /* COAP_SERVER_SUPPORT */
1035#if COAP_CLIENT_SUPPORT
1036 coap_lg_crcv_t *cq, *etmp;
1037#endif /* COAP_CLIENT_SUPPORT */
1038 int sent_nack = 0;
1039 coap_queue_t *q;
1040
1042#if COAP_CLIENT_SUPPORT
1043 coap_session_failed(session);
1044#endif /* COAP_CLIENT_SUPPORT */
1045
1046 q = session->context->sendqueue;
1047 while (q) {
1048 if (q->session == session) {
1049 /* Take the first one */
1050 coap_handle_nack(session, q->pdu, reason, q->id);
1051 sent_nack = 1;
1052 break;
1053 }
1054 q = q->next;
1055 }
1056
1057 if (reason != COAP_NACK_ICMP_ISSUE) {
1058 while (session->delayqueue) {
1059 q = session->delayqueue;
1060 session->delayqueue = q->next;
1061 q->next = NULL;
1062 coap_log_debug("** %s: mid=0x%04x: not transmitted after disconnect\n",
1063 coap_session_str(session), q->id);
1064 if (q->pdu->type == COAP_MESSAGE_CON) {
1065 coap_handle_nack(session, q->pdu, reason, q->id);
1066 sent_nack = 1;
1067 }
1068
1069#if COAP_CLIENT_SUPPORT
1070 session->doing_send_recv = 0;
1071#endif /* COAP_CLIENT_SUPPORT */
1073 }
1074 }
1075#if COAP_CLIENT_SUPPORT
1076 if (!sent_nack && session->lg_crcv) {
1077 /* Take the first one */
1078 coap_handle_nack(session, session->lg_crcv->sent_pdu, reason,
1079 session->lg_crcv->sent_pdu->mid);
1080 sent_nack = 1;
1081 }
1082#endif /* COAP_CLIENT_SUPPORT */
1083 if (!sent_nack) {
1084 /* Unable to determine which request disconnection was for */
1085 coap_handle_nack(session, NULL, reason, 0);
1086 }
1087 if (reason == COAP_NACK_ICMP_ISSUE) {
1088 coap_log_debug("***%s: session ICMP issue (%s)\n",
1089 coap_session_str(session), coap_nack_name(reason));
1090 return;
1091 }
1092 coap_log_debug("***%s: session disconnected (%s)\n",
1093 coap_session_str(session), coap_nack_name(reason));
1094#if COAP_SERVER_SUPPORT
1095 coap_delete_observers(session->context, session);
1096#endif /* COAP_SERVER_SUPPORT */
1097
1098 if (session->proto == COAP_PROTO_UDP)
1100 else
1101 session->state = COAP_SESSION_STATE_NONE;
1102
1103 session->con_active = 0;
1104
1105 if (session->partial_pdu) {
1107 session->partial_pdu = NULL;
1108 }
1109 session->partial_read = 0;
1110
1111 /* Not done if nack handler called above */
1112 while (session->delayqueue) {
1113 q = session->delayqueue;
1114 session->delayqueue = q->next;
1115 q->next = NULL;
1116 coap_log_debug("** %s: mid=0x%04x: not transmitted after disconnect\n",
1117 coap_session_str(session), q->id);
1118#if COAP_CLIENT_SUPPORT
1119 session->doing_send_recv = 0;
1120#endif /* COAP_CLIENT_SUPPORT */
1122 }
1123
1124#if COAP_CLIENT_SUPPORT
1125 if (!session->session_failed) {
1126 /* Need to do this before (D)TLS and socket is closed down */
1127 LL_FOREACH_SAFE(session->lg_crcv, cq, etmp) {
1128 LL_DELETE(session->lg_crcv, cq);
1129 coap_block_delete_lg_crcv(session, cq);
1130 }
1131 }
1132#endif /* COAP_CLIENT_SUPPORT */
1133 LL_FOREACH_SAFE(session->lg_xmit, lq, ltmp) {
1134 LL_DELETE(session->lg_xmit, lq);
1135 coap_block_delete_lg_xmit(session, lq);
1136 }
1137#if COAP_SERVER_SUPPORT
1138 LL_FOREACH_SAFE(session->lg_srcv, sq, stmp) {
1139 LL_DELETE(session->lg_srcv, sq);
1140 coap_block_delete_lg_srcv(session, sq);
1141 }
1142#endif /* COAP_SERVER_SUPPORT */
1143 coap_cancel_session_messages(session->context, session, reason);
1144
1145#if !COAP_DISABLE_TCP
1146 if (COAP_PROTO_RELIABLE(session->proto)) {
1147 if (coap_netif_available(session)) {
1151 }
1152#if COAP_CLIENT_SUPPORT
1153 if (state != COAP_SESSION_STATE_NONE && !session->session_failed) {
1157 }
1158#endif /* COAP_CLIENT_SUPPORT */
1159 if (session->doing_first)
1160 session->doing_first = 0;
1161 }
1162#endif /* !COAP_DISABLE_TCP */
1163 if (session->sock.lfunc[COAP_LAYER_SESSION].l_close)
1164 session->sock.lfunc[COAP_LAYER_SESSION].l_close(session);
1165}
1166
1167#if COAP_CLIENT_SUPPORT
1168void
1170 if (session->context->reconnect_time &&
1172 session->type == COAP_SESSION_TYPE_CLIENT) {
1173 if (session->sock.lfunc[COAP_LAYER_SESSION].l_close)
1174 session->sock.lfunc[COAP_LAYER_SESSION].l_close(session);
1175 session->session_failed = 1;
1176 coap_ticks(&session->last_rx_tx);
1177 }
1178}
1179#endif /* COAP_CLIENT_SUPPORT */
1180
1181#if COAP_SERVER_SUPPORT
1182static void
1183coap_make_addr_hash(coap_addr_hash_t *addr_hash, coap_proto_t proto,
1184 const coap_addr_tuple_t *addr_info) {
1185 memset(addr_hash, 0, sizeof(coap_addr_hash_t));
1186 coap_address_copy(&addr_hash->remote, &addr_info->remote);
1187 addr_hash->lport = coap_address_get_port(&addr_info->local);
1188 addr_hash->proto = proto;
1189}
1190
1193 const coap_packet_t *packet, coap_tick_t now) {
1194 coap_session_t *session;
1195 coap_session_t *rtmp;
1196 unsigned int num_idle = 0;
1197 unsigned int num_hs = 0;
1198 coap_session_t *oldest = NULL;
1199 coap_session_t *oldest_hs = NULL;
1200 coap_addr_hash_t addr_hash;
1201
1202 coap_make_addr_hash(&addr_hash, endpoint->proto, &packet->addr_info);
1203 SESSIONS_FIND(endpoint->sessions, addr_hash, session);
1204 if (session) {
1205 /* Maybe mcast or unicast IP address which is not in the hash */
1206 coap_address_copy(&session->addr_info.local, &packet->addr_info.local);
1207 session->ifindex = packet->ifindex;
1208 session->last_rx_tx = now;
1209 return session;
1210 }
1211
1212#if COAP_CLIENT_SUPPORT
1213 if (coap_is_mcast(&packet->addr_info.local)) {
1214 /* Check if this a proxy client packet we sent on another socket */
1215 SESSIONS_ITER(endpoint->context->sessions, session, rtmp) {
1216 if (coap_address_equals(&session->addr_info.remote, &packet->addr_info.local) &&
1219 /* Drop looped back packet to stop recursion / confusion */
1220 return NULL;
1221 }
1222 }
1223 }
1224#endif /* COAP_CLIENT_SUPPORT */
1225 SESSIONS_ITER(endpoint->sessions, session, rtmp) {
1226 if (session->ref == 0 && session->delayqueue == NULL) {
1227 if (session->type == COAP_SESSION_TYPE_SERVER) {
1228 ++num_idle;
1229 if (oldest==NULL || session->last_rx_tx < oldest->last_rx_tx)
1230 oldest = session;
1231
1232 if (session->state == COAP_SESSION_STATE_HANDSHAKE) {
1233 ++num_hs;
1234 /* See if this is a partial (D)TLS session set up
1235 which needs to be cleared down to prevent DOS */
1236 if ((session->last_rx_tx + COAP_PARTIAL_SESSION_TIMEOUT_TICKS) < now) {
1237 if (oldest_hs == NULL ||
1238 session->last_rx_tx < oldest_hs->last_rx_tx)
1239 oldest_hs = session;
1240 }
1241 }
1242 } else if (session->type == COAP_SESSION_TYPE_HELLO) {
1243 ++num_hs;
1244 /* See if this is a partial (D)TLS session set up for Client Hello
1245 which needs to be cleared down to prevent DOS */
1246 if ((session->last_rx_tx + COAP_PARTIAL_SESSION_TIMEOUT_TICKS) < now) {
1247 if (oldest_hs == NULL ||
1248 session->last_rx_tx < oldest_hs->last_rx_tx)
1249 oldest_hs = session;
1250 }
1251 }
1252 }
1253 }
1254
1255 if (endpoint->context->max_idle_sessions > 0 &&
1256 num_idle >= endpoint->context->max_idle_sessions) {
1258 coap_session_free(oldest);
1259 } else if (oldest_hs) {
1260 coap_log_warn("***%s: Incomplete session timed out\n",
1261 coap_session_str(oldest_hs));
1263 coap_session_free(oldest_hs);
1264 }
1265
1266 if (num_hs > (endpoint->context->max_handshake_sessions ?
1267 endpoint->context->max_handshake_sessions :
1269 /* Maxed out on number of sessions in (D)TLS negotiation state */
1270 coap_log_debug("Oustanding sessions in COAP_SESSION_STATE_HANDSHAKE too "
1271 "large. New request ignored\n");
1272 return NULL;
1273 }
1274
1275 if (endpoint->proto == COAP_PROTO_DTLS) {
1276 /*
1277 * Need to check that this actually is a Client Hello before wasting
1278 * time allocating and then freeing off session.
1279 */
1280
1281 /*
1282 * Generic header structure of the DTLS record layer.
1283 * typedef struct __attribute__((__packed__)) {
1284 * uint8_t content_type; content type of the included message
1285 * uint16_t version; Protocol version
1286 * uint16_t epoch; counter for cipher state changes
1287 * uint8_t sequence_number[6]; sequence number
1288 * uint16_t length; length of the following fragment
1289 * uint8_t handshake; If content_type == DTLS_CT_HANDSHAKE
1290 * } dtls_record_handshake_t;
1291 */
1292#define OFF_CONTENT_TYPE 0 /* offset of content_type in dtls_record_handshake_t */
1293#define DTLS_CT_ALERT 21 /* Content Type Alert */
1294#define DTLS_CT_HANDSHAKE 22 /* Content Type Handshake */
1295#define OFF_HANDSHAKE_TYPE 13 /* offset of handshake in dtls_record_handshake_t */
1296#define DTLS_HT_CLIENT_HELLO 1 /* Client Hello handshake type */
1297#define DTLS_CT_CID 25 /* Content Type Connection ID */
1298#define OFF_CID 11 /* offset of CID in dtls_record_handshake_t */
1299#define OFF_CID_DTLS13 1 /* offset of CID in DTLS1.3 Unified Header */
1300
1301 const uint8_t *payload = (const uint8_t *)packet->payload;
1302 size_t length = packet->length;
1303 if (length < (OFF_HANDSHAKE_TYPE + 1)) {
1304 coap_log_debug("coap_dtls_hello: ContentType %d Short Packet (%zu < %d) dropped\n",
1305 payload[OFF_CONTENT_TYPE], length,
1306 OFF_HANDSHAKE_TYPE + 1);
1307 return NULL;
1308 }
1309 if ((payload[OFF_CONTENT_TYPE] & 0x30) == 0x30 ||
1310 payload[OFF_CONTENT_TYPE] == DTLS_CT_CID) {
1311 /* Client may have changed its IP address */
1312 int changed = 0;
1313
1314 SESSIONS_ITER(endpoint->sessions, session, rtmp) {
1315 if (session->client_cid) {
1316 if ((session->is_dtls13 && (payload[OFF_CONTENT_TYPE] & 0x30) == 0x30 &&
1317 memcmp(session->client_cid->s, &payload[OFF_CID_DTLS13],
1318 session->client_cid->length) == 0) ||
1319 (!session->is_dtls13 && payload[OFF_CONTENT_TYPE] == DTLS_CT_CID &&
1320 memcmp(session->client_cid->s, &payload[OFF_CID],
1321 session->client_cid->length) == 0)) {
1322 /* Updating IP address */
1323 coap_log_info("***%s: CID: Old Client Session\n", coap_session_str(session));
1324 SESSIONS_DELETE(endpoint->sessions, session);
1325 session->addr_info = packet->addr_info;
1326 memcpy(&session->addr_hash, &addr_hash, sizeof(session->addr_hash));
1327 SESSIONS_ADD(endpoint->sessions, session);
1328 coap_log_info("***%s: CID: New Client Session\n", coap_session_str(session));
1329 return session;
1330 }
1331 }
1332 }
1333 if (!changed) {
1334 coap_log_debug("coap_dtls_hello: ContentType Connection-IS dropped\n");
1335 return NULL;
1336 }
1337 } else if (payload[OFF_CONTENT_TYPE] != DTLS_CT_HANDSHAKE ||
1338 payload[OFF_HANDSHAKE_TYPE] != DTLS_HT_CLIENT_HELLO) {
1339 /* only log if not a late alert */
1340 if (payload[OFF_CONTENT_TYPE] != DTLS_CT_ALERT)
1341 coap_log_debug("coap_dtls_hello: ContentType %d Handshake %d dropped\n",
1342 payload[OFF_CONTENT_TYPE],
1343 payload[OFF_HANDSHAKE_TYPE]);
1344 return NULL;
1345 }
1346 }
1347
1349 &addr_hash, &packet->addr_info.local,
1350 &packet->addr_info.remote,
1351 packet->ifindex, endpoint->context, endpoint);
1352 if (session) {
1353 session->last_rx_tx = now;
1354 memcpy(session->sock.lfunc, endpoint->sock.lfunc,
1355 sizeof(session->sock.lfunc));
1356 if (endpoint->proto == COAP_PROTO_UDP)
1358 else if (endpoint->proto == COAP_PROTO_DTLS) {
1359 session->type = COAP_SESSION_TYPE_HELLO;
1360 }
1361 SESSIONS_ADD(endpoint->sessions, session);
1362 coap_log_debug("***%s: session %p: new incoming session\n",
1363 coap_session_str(session), (void *)session);
1365 }
1366 return session;
1367}
1368
1371 coap_tick_t now) {
1372 if (session) {
1373 session->last_rx_tx = now;
1374 session->type = COAP_SESSION_TYPE_SERVER;
1375 coap_dtls_establish(session);
1376 }
1377 return session;
1378}
1379#endif /* COAP_SERVER_SUPPORT */
1380
1381#if COAP_CLIENT_SUPPORT
1382static coap_session_t *
1383coap_session_create_client(coap_context_t *ctx,
1384 const coap_address_t *local_if,
1385 const coap_address_t *server,
1386 coap_proto_t proto) {
1387 coap_session_t *session = NULL;
1388 int default_port = COAP_DEFAULT_PORT;
1389
1390 assert(server);
1391
1392 switch (proto) {
1393 case COAP_PROTO_UDP:
1394 default_port = COAP_DEFAULT_PORT;
1395 break;
1396 case COAP_PROTO_DTLS:
1397 if (!coap_dtls_is_supported()) {
1398 coap_log_crit("coap_new_client_session*: DTLS not supported\n");
1399 return NULL;
1400 }
1401 default_port = COAPS_DEFAULT_PORT;
1402 break;
1403 case COAP_PROTO_TCP:
1404 if (!coap_tcp_is_supported()) {
1405 coap_log_crit("coap_new_client_session*: TCP not supported\n");
1406 return NULL;
1407 }
1408 default_port = COAP_DEFAULT_PORT;
1409 break;
1410 case COAP_PROTO_TLS:
1411 if (!coap_tls_is_supported()) {
1412 coap_log_crit("coap_new_client_session*: TLS not supported\n");
1413 return NULL;
1414 }
1415 default_port = COAPS_DEFAULT_PORT;
1416 break;
1417 case COAP_PROTO_WS:
1418 if (!coap_ws_is_supported()) {
1419 coap_log_crit("coap_new_client_session*: WS not supported\n");
1420 return NULL;
1421 }
1422 default_port = 80;
1423 break;
1424 case COAP_PROTO_WSS:
1425 if (!coap_wss_is_supported()) {
1426 coap_log_crit("coap_new_client_session*: WSS not supported\n");
1427 return NULL;
1428 }
1429 default_port = 443;
1430 break;
1431 case COAP_PROTO_NONE:
1432 case COAP_PROTO_LAST:
1433 default:
1434 assert(0);
1435 return NULL;
1436 }
1437 session = coap_make_session(proto, COAP_SESSION_TYPE_CLIENT, NULL,
1438 local_if, server, 0, ctx, NULL);
1439 if (!session)
1440 goto error;
1441
1443 session->sock.session = session;
1444 memcpy(&session->sock.lfunc, coap_layers_coap[proto],
1445 sizeof(session->sock.lfunc));
1446
1447 if (COAP_PROTO_NOT_RELIABLE(proto)) {
1448 coap_session_t *s, *rtmp;
1449 if (!coap_netif_dgrm_connect(session, local_if, server, default_port)) {
1450 goto error;
1451 }
1452 /* Check that this is not a duplicate 4-tuple */
1453 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1456 &s->addr_info.local) &&
1458 &s->addr_info.remote)) {
1459 coap_log_warn("***%s: session %p: duplicate - already exists\n",
1460 coap_session_str(session), (void *)session);
1461 goto error;
1462 }
1463 }
1464#ifdef WITH_CONTIKI
1465 session->sock.context = ctx;
1466#endif /* WITH_CONTIKI */
1467#if !COAP_DISABLE_TCP
1468 } else if (COAP_PROTO_RELIABLE(proto)) {
1469 if (!coap_netif_strm_connect1(session, local_if, server, default_port)) {
1470 goto error;
1471 }
1472#endif /* !COAP_DISABLE_TCP */
1473 }
1474
1475 session->sock.session = session;
1476#ifdef COAP_EPOLL_SUPPORT
1477 coap_epoll_ctl_add(&session->sock,
1478 EPOLLIN |
1479 ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ?
1480 EPOLLOUT : 0),
1481 __func__);
1482#endif /* COAP_EPOLL_SUPPORT */
1483
1485 if (local_if)
1486 session->sock.flags |= COAP_SOCKET_BOUND;
1487#if COAP_SERVER_SUPPORT
1488 if (ctx->proxy_uri_resource)
1489 session->proxy_session = 1;
1490#endif /* COAP_SERVER_SUPPORT */
1491 SESSIONS_ADD(ctx->sessions, session);
1492 return session;
1493
1494error:
1495 /*
1496 * Need to add in the session as coap_session_release_lkd()
1497 * will call SESSIONS_DELETE in coap_session_free().
1498 */
1499 if (session)
1500 SESSIONS_ADD(ctx->sessions, session);
1501 coap_session_release_lkd(session);
1502 return NULL;
1503}
1504
1505static void
1506coap_session_check_connect(coap_session_t *session) {
1507 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1508 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
1509 }
1510#if !COAP_DISABLE_TCP
1511 if (COAP_PROTO_RELIABLE(session->proto)) {
1512 if (session->sock.flags & COAP_SOCKET_WANT_CONNECT) {
1514 if (session->type == COAP_SESSION_TYPE_CLIENT) {
1515 session->doing_first = 1;
1516 }
1517 } else {
1518 /* Initial connect worked immediately */
1519 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
1520 }
1521 }
1522#endif /* !COAP_DISABLE_TCP */
1523 coap_ticks(&session->last_rx_tx);
1524}
1525#endif /* COAP_CLIENT_SUPPORT */
1526
1527void
1529 if (COAP_PROTO_NOT_RELIABLE(session->proto))
1530 coap_session_connected(session);
1531#if !COAP_DISABLE_TCP
1532 if (COAP_PROTO_RELIABLE(session->proto))
1533 coap_session_send_csm(session);
1534#endif /* !COAP_DISABLE_TCP */
1535}
1536
1537#if COAP_CLIENT_SUPPORT
1538int
1540 int default_port = COAP_DEFAULT_PORT;
1541
1542 if (session->sock.lfunc[COAP_LAYER_SESSION].l_close && !session->session_failed)
1543 session->sock.lfunc[COAP_LAYER_SESSION].l_close(session);
1544
1545 switch (session->proto) {
1546 case COAP_PROTO_UDP:
1547 default_port = COAP_DEFAULT_PORT;
1548 break;
1549 case COAP_PROTO_DTLS:
1550 default_port = COAPS_DEFAULT_PORT;
1551 break;
1552 case COAP_PROTO_TCP:
1553 default_port = COAP_DEFAULT_PORT;
1554 break;
1555 case COAP_PROTO_TLS:
1556 default_port = COAPS_DEFAULT_PORT;
1557 break;
1558 case COAP_PROTO_WS:
1559 default_port = 80;
1560 break;
1561 case COAP_PROTO_WSS:
1562 default_port = 443;
1563 break;
1564 case COAP_PROTO_NONE:
1565 case COAP_PROTO_LAST:
1566 default:
1567 assert(0);
1568 return 0;
1569 }
1570 session->sock.session = session;
1571 coap_log_debug("***%s: trying to reconnect\n", coap_session_str(session));
1572 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1573 session->state = COAP_SESSION_STATE_NONE;
1574 if (!coap_netif_dgrm_connect(session, &session->local_reconnect, &session->addr_info.remote,
1575 default_port)) {
1576 goto error;
1577 }
1579#ifdef WITH_CONTIKI
1580 session->sock.context = session->context;
1581#endif /* WITH_CONTIKI */
1582#if !COAP_DISABLE_TCP
1583 } else if (COAP_PROTO_RELIABLE(session->proto)) {
1584 if (!coap_netif_strm_connect1(session, &session->local_reconnect, &session->addr_info.remote,
1585 default_port)) {
1586 goto error;
1587 }
1588#endif /* !COAP_DISABLE_TCP */
1589 } else {
1590 goto error;
1591 }
1592#ifdef COAP_EPOLL_SUPPORT
1593 coap_epoll_ctl_add(&session->sock,
1594 EPOLLIN |
1595 ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ?
1596 EPOLLOUT : 0),
1597 __func__);
1598#endif /* COAP_EPOLL_SUPPORT */
1599
1601 session->sock.flags |= COAP_SOCKET_BOUND;
1602 coap_session_check_connect(session);
1603 return 1;
1604error:
1605 return 0;
1606}
1607
1608void
1610 coap_lg_crcv_t *lg_crcv, *etmp;
1611
1612 if (!session->session_failed)
1613 return;
1614 coap_log_debug("***%s: session re-established\n",
1615 coap_session_str(session));
1616 session->session_failed = 0;
1617 LL_FOREACH_SAFE(session->lg_crcv, lg_crcv, etmp) {
1619 coap_send_internal(session, lg_crcv->sent_pdu, NULL);
1620 }
1621}
1622
1625 const coap_address_t *local_if,
1626 const coap_address_t *server,
1627 coap_proto_t proto) {
1628 coap_session_t *session;
1629
1630 coap_lock_lock(ctx, return NULL);
1631 session = coap_new_client_session_lkd(ctx, local_if, server, proto);
1632 coap_lock_unlock(ctx);
1633 return session;
1634}
1635
1638 const coap_address_t *local_if,
1639 const coap_address_t *server,
1640 coap_proto_t proto) {
1641 coap_session_t *session;
1642
1644 session = coap_session_create_client(ctx, local_if, server,
1645 proto);
1646 if (session) {
1647 coap_log_debug("***%s: session %p: created outgoing session\n",
1648 coap_session_str(session), (void *)session);
1649 coap_session_check_connect(session);
1650 }
1651 return session;
1652}
1653
1656 const coap_address_t *local_if,
1657 const coap_address_t *server,
1658 coap_proto_t proto, const char *identity,
1659 const uint8_t *key, unsigned key_len) {
1660 coap_session_t *session;
1661
1662 coap_lock_lock(ctx, return NULL);
1663 session = coap_new_client_session_psk_lkd(ctx, local_if, server, proto, identity, key, key_len);
1664 coap_lock_unlock(ctx);
1665 return session;
1666}
1667
1670 const coap_address_t *local_if,
1671 const coap_address_t *server,
1672 coap_proto_t proto, const char *identity,
1673 const uint8_t *key, unsigned key_len) {
1674 coap_dtls_cpsk_t setup_data;
1675
1677 memset(&setup_data, 0, sizeof(setup_data));
1679
1680 if (identity) {
1681 setup_data.psk_info.identity.s = (const uint8_t *)identity;
1682 setup_data.psk_info.identity.length = strlen(identity);
1683 }
1684
1685 if (key && key_len > 0) {
1686 setup_data.psk_info.key.s = key;
1687 setup_data.psk_info.key.length = key_len;
1688 }
1689
1690 return coap_new_client_session_psk2_lkd(ctx, local_if, server,
1691 proto, &setup_data);
1692}
1693
1694/*
1695 * Check the validity of the SNI to send to the server.
1696 *
1697 * https://datatracker.ietf.org/doc/html/rfc6066#section-3
1698 * Literal IPv4 and IPv6 addresses are not permitted in "HostName".
1699 */
1700static void
1701coap_sanitize_client_sni(char **client_sni) {
1702 char *cp;
1703
1704 if (*client_sni == NULL)
1705 return;
1706
1707 cp = *client_sni;
1708 switch (*cp) {
1709 case '0':
1710 case '1':
1711 case '2':
1712 case '3':
1713 case '4':
1714 case '5':
1715 case '6':
1716 case '7':
1717 case '8':
1718 case '9':
1719 case 'a':
1720 case 'b':
1721 case 'c':
1722 case 'd':
1723 case 'e':
1724 case 'f':
1725 case 'A':
1726 case 'B':
1727 case 'C':
1728 case 'D':
1729 case 'E':
1730 case 'F':
1731 case ':':
1732 break;
1733 case '\000':
1734 /* Empty entry invalid */
1735 *client_sni = NULL;
1736 return;
1737 default:
1738 /* Does not start with a hex digit or : - not literal IP. */
1739 return;
1740 }
1741 /* Check for IPv4 */
1742 while (*cp) {
1743 switch (*cp) {
1744 case '0':
1745 case '1':
1746 case '2':
1747 case '3':
1748 case '4':
1749 case '5':
1750 case '6':
1751 case '7':
1752 case '8':
1753 case '9':
1754 case '.':
1755 break;
1756 default:
1757 /* Not of format nnn.nnn.nnn.nnn. Could be IPv6 */
1758 goto check_ipv6;
1759 }
1760 cp++;
1761 }
1762 /* IPv4 address - not allowed. */
1763 *client_sni = NULL;
1764 return;
1765
1766check_ipv6:
1767 /* Check for IPv6 */
1768 cp = *client_sni;
1769 while (*cp) {
1770 switch (*cp) {
1771 case '0':
1772 case '1':
1773 case '2':
1774 case '3':
1775 case '4':
1776 case '5':
1777 case '6':
1778 case '7':
1779 case '8':
1780 case '9':
1781 case 'a':
1782 case 'b':
1783 case 'c':
1784 case 'd':
1785 case 'e':
1786 case 'f':
1787 case 'A':
1788 case 'B':
1789 case 'C':
1790 case 'D':
1791 case 'E':
1792 case 'F':
1793 case ':':
1794 break;
1795 case '%':
1796 /* Start of i/f specification, Previous is IPv6 */
1797 *client_sni = NULL;
1798 return;
1799 default:
1800 /* Not of format xx:xx::xx. */
1801 return;
1802 }
1803 cp++;
1804 }
1805 *client_sni = NULL;
1806 return;
1807}
1808
1811 const coap_address_t *local_if,
1812 const coap_address_t *server,
1813 coap_proto_t proto,
1814 coap_dtls_cpsk_t *setup_data) {
1815 coap_session_t *session;
1816
1817 coap_lock_lock(ctx, return NULL);
1818 session = coap_new_client_session_psk2_lkd(ctx, local_if, server, proto, setup_data);
1819 coap_lock_unlock(ctx);
1820 return session;
1821}
1822
1825 const coap_address_t *local_if,
1826 const coap_address_t *server,
1827 coap_proto_t proto,
1828 coap_dtls_cpsk_t *setup_data) {
1829 coap_session_t *session;
1830
1832 session = coap_session_create_client(ctx, local_if, server, proto);
1833
1834 if (!session || !setup_data)
1835 return NULL;
1836
1837 session->cpsk_setup_data = *setup_data;
1838 if (setup_data->psk_info.identity.s) {
1839 session->psk_identity =
1841 setup_data->psk_info.identity.length);
1842 if (!session->psk_identity) {
1843 coap_log_warn("Cannot store session Identity (PSK)\n");
1844 coap_session_release_lkd(session);
1845 return NULL;
1846 }
1848 coap_log_warn("Identity (PSK) not defined\n");
1849 coap_session_release_lkd(session);
1850 return NULL;
1851 }
1852
1853 if (setup_data->psk_info.key.s && setup_data->psk_info.key.length > 0) {
1854 session->psk_key = coap_new_bin_const(setup_data->psk_info.key.s,
1855 setup_data->psk_info.key.length);
1856 if (!session->psk_key) {
1857 coap_log_warn("Cannot store session pre-shared key (PSK)\n");
1858 coap_session_release_lkd(session);
1859 return NULL;
1860 }
1862 coap_log_warn("Pre-shared key (PSK) not defined\n");
1863 coap_session_release_lkd(session);
1864 return NULL;
1865 }
1866
1867 coap_sanitize_client_sni(&session->cpsk_setup_data.client_sni);
1868
1870 if (!coap_dtls_context_set_cpsk(ctx, &session->cpsk_setup_data)) {
1871 coap_session_release_lkd(session);
1872 return NULL;
1873 }
1874 }
1875 coap_log_debug("***%s: new outgoing session\n",
1876 coap_session_str(session));
1877 coap_session_check_connect(session);
1878 return session;
1879}
1880#endif /* COAP_CLIENT_SUPPORT */
1881
1882int
1884 const coap_bin_const_t *psk_hint
1885 ) {
1886 /* We may be refreshing the hint with the same hint */
1887 coap_bin_const_t *old_psk_hint = session->psk_hint;
1888
1889 if (psk_hint && psk_hint->s) {
1890 if (session->psk_hint) {
1891 if (coap_binary_equal(session->psk_hint, psk_hint))
1892 return 1;
1893 }
1894 session->psk_hint = coap_new_bin_const(psk_hint->s,
1895 psk_hint->length);
1896 if (!session->psk_hint) {
1897 coap_log_err("No memory to store identity hint (PSK)\n");
1898 if (old_psk_hint)
1899 coap_delete_bin_const(old_psk_hint);
1900 return 0;
1901 }
1902 } else {
1903 session->psk_hint = NULL;
1904 }
1905 if (old_psk_hint)
1906 coap_delete_bin_const(old_psk_hint);
1907
1908 return 1;
1909}
1910
1911int
1913 const coap_bin_const_t *psk_key
1914 ) {
1915 /* We may be refreshing the key with the same key */
1916 coap_bin_const_t *old_psk_key = session->psk_key;
1917
1918 if (psk_key && psk_key->s) {
1919 if (session->psk_key) {
1920 if (coap_binary_equal(session->psk_key, psk_key))
1921 return 1;
1922 }
1923 session->psk_key = coap_new_bin_const(psk_key->s, psk_key->length);
1924 if (!session->psk_key) {
1925 coap_log_err("No memory to store pre-shared key (PSK)\n");
1926 if (old_psk_key)
1927 coap_delete_bin_const(old_psk_key);
1928 return 0;
1929 }
1930 } else {
1931 session->psk_key = NULL;
1932 }
1933 if (old_psk_key)
1934 coap_delete_bin_const(old_psk_key);
1935
1936 return 1;
1937}
1938
1939int
1941 const coap_bin_const_t *psk_identity
1942 ) {
1943 /* We may be refreshing the identity with the same identity */
1944 coap_bin_const_t *old_psk_identity = session->psk_identity;
1945
1946 if (psk_identity && psk_identity->s) {
1947 if (session->psk_identity) {
1948 if (coap_binary_equal(session->psk_identity, psk_identity))
1949 return 1;
1950 }
1951 session->psk_identity = coap_new_bin_const(psk_identity->s,
1952 psk_identity->length);
1953 if (!session->psk_identity) {
1954 coap_log_err("No memory to store pre-shared key identity (PSK)\n");
1955 if (old_psk_identity)
1956 coap_delete_bin_const(old_psk_identity);
1957 return 0;
1958 }
1959 } else {
1960 session->psk_identity = NULL;
1961 }
1962 if (old_psk_identity)
1963 coap_delete_bin_const(old_psk_identity);
1964
1965 return 1;
1966}
1967
1968#if COAP_SERVER_SUPPORT
1969const coap_bin_const_t *
1971 if (session)
1972 return session->psk_hint;
1973 return NULL;
1974}
1975#endif /* COAP_SERVER_SUPPORT */
1976
1977const coap_bin_const_t *
1979 const coap_bin_const_t *psk_identity = NULL;
1980 if (session) {
1981 psk_identity = session->psk_identity;
1982 if (psk_identity == NULL) {
1983 psk_identity = &session->cpsk_setup_data.psk_info.identity;
1984 }
1985 }
1986 return psk_identity;
1987}
1988
1989const coap_bin_const_t *
1991 if (session)
1992 return session->psk_key;
1993 return NULL;
1994}
1995
1996#if COAP_CLIENT_SUPPORT
1999 const coap_address_t *local_if,
2000 const coap_address_t *server,
2001 coap_proto_t proto,
2002 coap_dtls_pki_t *setup_data) {
2003 coap_session_t *session;
2004
2005 coap_lock_lock(ctx, return NULL);
2006 session = coap_new_client_session_pki_lkd(ctx, local_if, server, proto, setup_data);
2007 coap_lock_unlock(ctx);
2008 return session;
2009}
2010
2013 const coap_address_t *local_if,
2014 const coap_address_t *server,
2015 coap_proto_t proto,
2016 coap_dtls_pki_t *setup_data) {
2017 coap_session_t *session;
2018 coap_dtls_pki_t l_setup_data;
2019
2020 if (!setup_data)
2021 return NULL;
2022 if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
2023 coap_log_err("coap_new_client_session_pki: Wrong version of setup_data\n");
2024 return NULL;
2025 }
2026
2028 l_setup_data = *setup_data;
2029 coap_sanitize_client_sni(&l_setup_data.client_sni);
2030
2031 session = coap_session_create_client(ctx, local_if, server, proto);
2032
2033 if (!session) {
2034 return NULL;
2035 }
2036
2038 /* we know that setup_data is not NULL */
2039 if (!coap_dtls_context_set_pki(ctx, &l_setup_data, COAP_DTLS_ROLE_CLIENT)) {
2040 coap_session_release_lkd(session);
2041 return NULL;
2042 }
2043 }
2044 coap_log_debug("***%s: new outgoing session\n",
2045 coap_session_str(session));
2046 coap_session_check_connect(session);
2047 return session;
2048}
2049#endif /* ! COAP_CLIENT_SUPPORT */
2050
2051#if COAP_SERVER_SUPPORT
2052#if !COAP_DISABLE_TCP
2055 coap_session_t *session;
2057 NULL, NULL, NULL, 0, ctx, ep);
2058 if (!session)
2059 goto error;
2060
2061 memcpy(session->sock.lfunc, ep->sock.lfunc, sizeof(session->sock.lfunc));
2062 if (!coap_netif_strm_accept(ep, session, extra))
2063 goto error;
2064
2065 coap_make_addr_hash(&session->addr_hash, session->proto, &session->addr_info);
2066
2067#ifdef COAP_EPOLL_SUPPORT
2068 session->sock.session = session;
2069 coap_epoll_ctl_add(&session->sock,
2070 EPOLLIN,
2071 __func__);
2072#endif /* COAP_EPOLL_SUPPORT */
2073 SESSIONS_ADD(ep->sessions, session);
2074 if (session) {
2075 coap_log_debug("***%s: session %p: new incoming session\n",
2076 coap_session_str(session), (void *)session);
2080 session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2081 }
2082 return session;
2083
2084error:
2085 /*
2086 * Need to add in the session as coap_session_release_lkd()
2087 * will call SESSIONS_DELETE in coap_session_free().
2088 */
2089 if (session) {
2090 SESSIONS_ADD(ep->sessions, session);
2091 coap_session_free(session);
2092 }
2093 return NULL;
2094}
2095#endif /* !COAP_DISABLE_TCP */
2096#endif /* COAP_SERVER_SUPPORT */
2097
2098void
2100 const uint8_t *data) {
2101 session->tx_token = coap_decode_var_bytes8(data, len);
2102 /*
2103 * Decrement as when first used by coap_session_new_token() it will
2104 * get incremented
2105 */
2106 session->tx_token--;
2107}
2108
2109void
2111 uint8_t *data) {
2112 *len = coap_encode_var_safe8(data,
2113 sizeof(session->tx_token), ++session->tx_token);
2114}
2115
2116COAP_API uint16_t
2118 uint16_t mid;
2119
2120 coap_lock_lock(session->context, return 0);
2121 mid = coap_new_message_id_lkd(session);
2122 coap_lock_unlock(session->context);
2123 return mid;
2124}
2125
2126uint16_t
2129 if (COAP_PROTO_NOT_RELIABLE(session->proto))
2130 return ++session->tx_mid;
2131 /* TCP/TLS have no notion of mid */
2132 return 0;
2133}
2134
2135const coap_address_t *
2137 if (session)
2138 return &session->addr_info.remote;
2139 return NULL;
2140}
2141
2142const coap_address_t *
2144 if (session)
2145 return &session->addr_info.local;
2146 return NULL;
2147}
2148
2149const coap_address_t *
2151#if COAP_CLIENT_SUPPORT
2152 if (session && session->type == COAP_SESSION_TYPE_CLIENT &&
2153 session->sock.flags & COAP_SOCKET_MULTICAST)
2154 return &session->sock.mcast_addr;
2155#else /* ! COAP_CLIENT_SUPPORT */
2156 (void)session;
2157#endif /* ! COAP_CLIENT_SUPPORT */
2158 return NULL;
2159}
2160
2163 if (session)
2164 return session->context;
2165 return NULL;
2166}
2167
2170 if (session)
2171 return session->proto;
2172 return 0;
2173}
2174
2177 if (session)
2178 return session->type;
2179 return 0;
2180}
2181
2182COAP_API int
2184 int ret;
2185
2186 coap_lock_lock(session->context, return 0);
2187 ret = coap_session_set_type_client_lkd(session);
2188 coap_lock_unlock(session->context);
2189 return ret;
2190}
2191
2192int
2194#if COAP_SERVER_SUPPORT
2195 if (session && session->type == COAP_SESSION_TYPE_SERVER) {
2197 session->type = COAP_SESSION_TYPE_CLIENT;
2198 return 1;
2199 }
2200#else /* ! COAP_SERVER_SUPPORT */
2201 (void)session;
2202#endif /* ! COAP_SERVER_SUPPORT */
2203 return 0;
2204}
2205
2208 if (session)
2209 return session->state;
2210 return 0;
2211}
2212
2213int
2215 if (session)
2216 return session->ifindex;
2217 return -1;
2218}
2219
2220void *
2222 coap_tls_library_t *tls_lib) {
2223 if (session)
2224 return coap_dtls_get_tls(session, tls_lib);
2225 return NULL;
2226}
2227
2228static const char *
2230 switch (proto) {
2231 case COAP_PROTO_UDP:
2232 return "UDP ";
2233 case COAP_PROTO_DTLS:
2234 return "DTLS";
2235 case COAP_PROTO_TCP:
2236 return "TCP ";
2237 case COAP_PROTO_TLS:
2238 return "TLS ";
2239 case COAP_PROTO_WS:
2240 return "WS ";
2241 case COAP_PROTO_WSS:
2242 return "WSS ";
2243 case COAP_PROTO_NONE:
2244 case COAP_PROTO_LAST:
2245 default:
2246 return "????" ;
2247 break;
2248 }
2249 return NULL;
2250}
2251
2252#if COAP_SERVER_SUPPORT
2254coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto) {
2255 coap_endpoint_t *endpoint;
2256
2257 coap_lock_lock(context, return NULL);
2258 endpoint = coap_new_endpoint_lkd(context, listen_addr, proto);
2259 coap_lock_unlock(context);
2260 return endpoint;
2261}
2262
2264coap_new_endpoint_lkd(coap_context_t *context, const coap_address_t *listen_addr,
2265 coap_proto_t proto) {
2266 coap_endpoint_t *ep = NULL;
2267
2268 if (!context || !listen_addr) {
2269 coap_log_debug("coap_new_endpoint: Both context and listen_addr need to be defined\n");
2270 return NULL;
2271 }
2272
2273 coap_lock_check_locked(context);
2274
2275 switch (proto) {
2276 case COAP_PROTO_UDP:
2277 break;
2278 case COAP_PROTO_DTLS:
2279 if (!coap_dtls_is_supported()) {
2280 coap_log_warn("coap_new_endpoint: DTLS not supported\n");
2281 return NULL;
2282 }
2283 break;
2284 case COAP_PROTO_TLS:
2285 if (!coap_tls_is_supported()) {
2286 coap_log_warn("coap_new_endpoint: TLS not supported\n");
2287 return NULL;
2288 }
2289 break;
2290 case COAP_PROTO_TCP:
2291 if (!coap_tcp_is_supported()) {
2292 coap_log_warn("coap_new_endpoint: TCP not supported\n");
2293 return NULL;
2294 }
2295 break;
2296 case COAP_PROTO_WS:
2297 if (!coap_ws_is_supported()) {
2298 coap_log_warn("coap_new_endpoint: WS not supported\n");
2299 return NULL;
2300 }
2301 break;
2302 case COAP_PROTO_WSS:
2303 if (!coap_wss_is_supported()) {
2304 coap_log_warn("coap_new_endpoint: WSS not supported\n");
2305 return NULL;
2306 }
2307 break;
2308 case COAP_PROTO_NONE:
2309 case COAP_PROTO_LAST:
2310 default:
2311 coap_log_crit("coap_new_endpoint: Unsupported protocol %d\n", proto);
2312 return NULL;
2313 }
2314
2315 if (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS ||
2316 proto == COAP_PROTO_WSS) {
2318 coap_log_info("coap_new_endpoint: one of coap_context_set_psk() or "
2319 "coap_context_set_pki() not called\n");
2320 return NULL;
2321 }
2322 }
2323 ep = coap_malloc_endpoint();
2324 if (!ep) {
2325 coap_log_warn("coap_new_endpoint: malloc");
2326 return NULL;
2327 }
2328
2329 memset(ep, 0, sizeof(coap_endpoint_t));
2330 ep->context = context;
2331 ep->proto = proto;
2332 ep->sock.endpoint = ep;
2333 memcpy(&ep->sock.lfunc, coap_layers_coap[proto], sizeof(ep->sock.lfunc));
2334
2335 if (COAP_PROTO_NOT_RELIABLE(proto)) {
2336 if (!coap_netif_dgrm_listen(ep, listen_addr))
2337 goto error;
2338#ifdef WITH_CONTIKI
2339 ep->sock.context = context;
2340#endif /* WITH_CONTIKI */
2341#if !COAP_DISABLE_TCP
2342 } else if (COAP_PROTO_RELIABLE(proto)) {
2343 if (!coap_netif_strm_listen(ep, listen_addr))
2344 goto error;
2345#endif /* !COAP_DISABLE_TCP */
2346 } else {
2347 coap_log_crit("coap_new_endpoint: Protocol type not supported %d\n", proto);
2348 goto error;
2349 }
2350
2352#ifndef INET6_ADDRSTRLEN
2353#define INET6_ADDRSTRLEN 40
2354#endif
2355 unsigned char addr_str[INET6_ADDRSTRLEN + 8];
2356
2357 if (coap_print_addr(&ep->bind_addr, addr_str, INET6_ADDRSTRLEN + 8)) {
2358 coap_log_debug("created %s endpoint %s\n", coap_proto_name(ep->proto),
2359 addr_str);
2360 }
2361 }
2362
2364
2365#ifdef COAP_EPOLL_SUPPORT
2366 ep->sock.endpoint = ep;
2368 EPOLLIN,
2369 __func__);
2370#endif /* COAP_EPOLL_SUPPORT */
2371
2372 LL_PREPEND(context->endpoint, ep);
2373 return ep;
2374
2375error:
2377 return NULL;
2378}
2379
2380void
2382 ep->default_mtu = (uint16_t)mtu;
2383}
2384
2385COAP_API void
2387 if (ep) {
2388 coap_context_t *context = ep->context;
2389 if (context) {
2390 coap_lock_lock(context, return);
2391 }
2393 if (context) {
2394 coap_lock_unlock(context);
2395 }
2396 }
2397}
2398
2399void
2401 if (ep) {
2402 coap_session_t *session, *rtmp;
2403
2404 if (ep->context) {
2405 /* If fully allocated and inserted */
2407 SESSIONS_ITER_SAFE(ep->sessions, session, rtmp) {
2408 assert(session->ref == 0);
2409 if (session->ref == 0) {
2411 coap_session_free(session);
2412 }
2413 }
2414 if (coap_netif_available_ep(ep)) {
2415 /*
2416 * ep->sock.endpoint is set in coap_new_endpoint().
2417 * ep->sock.session is never set.
2418 *
2419 * session->sock.session is set for both clients and servers (when a
2420 * new session is accepted), but does not affect the endpoint.
2421 *
2422 * So, it is safe to call coap_netif_close_ep() after all the sessions
2423 * have been freed above as we are only working with the endpoint sock.
2424 */
2425#ifdef COAP_EPOLL_SUPPORT
2426 assert(ep->sock.session == NULL);
2427#endif /* COAP_EPOLL_SUPPORT */
2429 }
2430
2431 if (ep->context->endpoint) {
2432 LL_DELETE(ep->context->endpoint, ep);
2433 }
2434 }
2436 }
2437}
2438#endif /* COAP_SERVER_SUPPORT */
2439
2442 const coap_address_t *remote_addr,
2443 int ifindex) {
2444 coap_session_t *s, *rtmp;
2445#if COAP_CLIENT_SUPPORT
2446 SESSIONS_ITER(ctx->sessions, s, rtmp) {
2447 if (s->ifindex == ifindex) {
2448 if (s->sock.flags & COAP_SOCKET_MULTICAST) {
2449 if (coap_address_equals(&s->sock.mcast_addr, remote_addr))
2450 return s;
2451 } else if (coap_address_equals(&s->addr_info.remote, remote_addr))
2452 return s;
2453 }
2454 }
2455#endif /* COAP_CLIENT_SUPPORT */
2456#if COAP_SERVER_SUPPORT
2457 coap_endpoint_t *ep;
2458
2459 LL_FOREACH(ctx->endpoint, ep) {
2460 SESSIONS_ITER(ep->sessions, s, rtmp) {
2461 if (s->ifindex == ifindex && coap_address_equals(&s->addr_info.remote,
2462 remote_addr))
2463 return s;
2464 }
2465 }
2466#endif /* COAP_SERVER_SUPPORT */
2467 return NULL;
2468}
2469
2470#ifndef INET6_ADDRSTRLEN
2471#define INET6_ADDRSTRLEN 46
2472#endif
2473const char *
2475 static char szSession[2 * (INET6_ADDRSTRLEN + 8) + 24];
2476 char *p = szSession, *end = szSession + sizeof(szSession);
2477 if (coap_print_addr(&session->addr_info.local,
2478 (unsigned char *)p, end - p) > 0)
2479 p += strlen(p);
2480 if (p + 6 < end) {
2481 strcpy(p, " <-> ");
2482 p += 5;
2483 }
2484 if (p + 1 < end) {
2485 if (coap_print_addr(&session->addr_info.remote,
2486 (unsigned char *)p, end - p) > 0)
2487 p += strlen(p);
2488 }
2489 if (session->ifindex > 0 && p + 1 < end)
2490 p += snprintf(p, end - p, " (if%d)", session->ifindex);
2491 if (p + 6 < end) {
2492 strcpy(p, " ");
2493 p++;
2494 strcpy(p, coap_proto_name(session->proto));
2495 }
2496
2497 return szSession;
2498}
2499
2500#if COAP_SERVER_SUPPORT
2501const char *
2502coap_endpoint_str(const coap_endpoint_t *endpoint) {
2503 static char szEndpoint[128];
2504 char *p = szEndpoint, *end = szEndpoint + sizeof(szEndpoint);
2505 if (coap_print_addr(&endpoint->bind_addr, (unsigned char *)p, end - p) > 0)
2506 p += strlen(p);
2507 if (p + 6 < end) {
2508 if (endpoint->proto == COAP_PROTO_UDP) {
2509 strcpy(p, " UDP");
2510 } else if (endpoint->proto == COAP_PROTO_DTLS) {
2511 strcpy(p, " DTLS");
2512 } else {
2513 strcpy(p, " NONE");
2514 }
2515 }
2516
2517 return szEndpoint;
2518}
2519#endif /* COAP_SERVER_SUPPORT */
2520#if COAP_CLIENT_SUPPORT
2521void
2523 session->no_observe_cancel = 1;
2524}
2525#endif /* COAP_CLIENT_SUPPORT */
2526#endif /* COAP_SESSION_C_ */
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.
uint16_t coap_address_get_port(const coap_address_t *addr)
Returns the port from addr in host byte order.
void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
int coap_address_equals(const coap_address_t *a, const coap_address_t *b)
Compares given address objects a and b.
#define PRIu32
coap_nack_reason_t
Definition coap_io.h:62
@ COAP_NACK_NOT_DELIVERABLE
Definition coap_io.h:64
@ COAP_NACK_WS_FAILED
Definition coap_io.h:71
@ COAP_NACK_TOO_MANY_RETRIES
Definition coap_io.h:63
@ COAP_NACK_TLS_FAILED
Definition coap_io.h:66
@ COAP_NACK_TLS_LAYER_FAILED
Definition coap_io.h:69
@ COAP_NACK_ICMP_ISSUE
Definition coap_io.h:67
@ COAP_NACK_WS_LAYER_FAILED
Definition coap_io.h:70
@ COAP_NACK_RST
Definition coap_io.h:65
@ COAP_NACK_BAD_RESPONSE
Definition coap_io.h:68
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
void coap_epoll_ctl_add(coap_socket_t *sock, uint32_t events, const char *func)
Epoll specific function to add the state of events that epoll is to track for the appropriate file de...
#define COAP_SOCKET_NOT_EMPTY
the socket is not empty
#define COAP_SOCKET_BOUND
the socket is bound
#define COAP_SOCKET_WANT_READ
non blocking socket is waiting for reading
coap_endpoint_t * coap_malloc_endpoint(void)
#define COAP_SOCKET_WANT_CONNECT
non blocking client socket is waiting for connect
void coap_mfree_endpoint(coap_endpoint_t *ep)
coap_layer_func_t coap_layers_coap[COAP_PROTO_LAST][COAP_LAYER_LAST]
Definition coap_layers.c:39
@ COAP_LAYER_SESSION
Library specific build wrapper for coap_internal.h.
#define COAP_API
@ COAP_SESSION
Definition coap_mem.h:51
@ COAP_STRING
Definition coap_mem.h:39
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c:108
void * coap_dtls_get_tls(const coap_session_t *c_session COAP_UNUSED, coap_tls_library_t *tls_lib)
Definition coap_notls.c:158
unsigned int coap_dtls_get_overhead(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:261
int coap_dtls_context_check_keys_enabled(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:147
static const char * coap_proto_name(coap_proto_t proto)
COAP_API coap_mid_t coap_session_send_ping(coap_session_t *session)
Send a ping message for the session.
static const char * coap_nack_name(coap_nack_reason_t reason)
static coap_session_t * coap_make_session(coap_proto_t proto, coap_session_type_t type, const coap_addr_hash_t *addr_hash, const coap_address_t *local_addr, const coap_address_t *remote_addr, int ifindex, coap_context_t *context, coap_endpoint_t *endpoint)
static size_t coap_session_max_pdu_size_internal(const coap_session_t *session, size_t max_with_header)
#define INET6_ADDRSTRLEN
void coap_session_set_no_observe_cancel(coap_session_t *session)
Disable client automatically sending observe cancel on session close.
#define SESSIONS_ADD(e, obj)
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define COAP_PARTIAL_SESSION_TIMEOUT_TICKS
#define SESSIONS_DELETE(e, obj)
#define COAP_DEFAULT_MAX_HANDSHAKE_SESSIONS
#define SESSIONS_ITER(e, el, rtmp)
#define SESSIONS_FIND(e, k, res)
void coap_block_delete_lg_srcv(coap_session_t *session, coap_lg_srcv_t *lg_srcv)
void coap_block_delete_lg_crcv(coap_session_t *session, coap_lg_crcv_t *lg_crcv)
void coap_check_update_token(coap_session_t *session, coap_pdu_t *pdu)
The function checks if the token needs to be updated before PDU is presented to the application (only...
void coap_block_delete_lg_xmit(coap_session_t *session, coap_lg_xmit_t *lg_xmit)
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...
#define COAP_DEFAULT_NON_MAX_RETRANSMIT
The number of times for requests for re-transmission of missing Q-Block1 when no response has been re...
uint16_t coap_session_get_non_max_retransmit(const coap_session_t *session)
Get the CoAP NON maximum retransmit count of missing Q-Block1 or Q-Block2 requested before there is a...
coap_fixed_point_t coap_session_get_default_leisure(const coap_session_t *session)
Get the CoAP default leisure time RFC7252 DEFAULT_LEISURE.
void coap_session_set_max_retransmit(coap_session_t *session, uint16_t value)
Set the CoAP maximum retransmit count before failure.
#define COAP_DEFAULT_NON_TIMEOUT
The delay (+ ACK_RANDOM_FACTOR) to introduce once NON MAX_PAYLOADS Q-Block1 or Q-Block2 have been sen...
coap_fixed_point_t coap_session_get_non_timeout(const coap_session_t *session)
Get the CoAP MAX_PAYLOADS limit delay timeout.
void coap_session_set_ack_random_factor(coap_session_t *session, coap_fixed_point_t value)
Set the CoAP ack randomize factor.
#define COAP_DEFAULT_MAX_LATENCY
The MAX_LATENCY definition.
coap_fixed_point_t coap_session_get_ack_random_factor(const coap_session_t *session)
Get the CoAP ack randomize factor.
#define COAP_DEFAULT_ACK_RANDOM_FACTOR
A factor that is used to randomize the wait time before a message is retransmitted to prevent synchro...
uint16_t coap_session_get_max_retransmit(const coap_session_t *session)
Get the CoAP maximum retransmit before failure.
void coap_session_set_max_payloads(coap_session_t *session, uint16_t value)
Set the CoAP maximum payloads count of Q-Block1 or Q-Block2 before delay is introduced RFC9177 MAX_PA...
#define COAP_DEFAULT_MAX_RETRANSMIT
Number of message retransmissions before message sending is stopped.
uint32_t coap_session_get_probing_rate(const coap_session_t *session)
Get the CoAP probing rate when there is no response RFC7252 PROBING_RATE.
#define COAP_DEFAULT_ACK_TIMEOUT
Number of seconds when to expect an ACK or a response to an outstanding CON message.
#define COAP_DEFAULT_DEFAULT_LEISURE
The number of seconds to use as bounds for multicast traffic RFC 7252, Section 4.8 Default value of D...
void coap_session_set_ack_timeout(coap_session_t *session, coap_fixed_point_t value)
Set the CoAP initial ack response timeout before the next re-transmit.
#define COAP_DEFAULT_NSTART
The number of simultaneous outstanding interactions that a client maintains to a given server.
void coap_session_set_non_receive_timeout(coap_session_t *session, coap_fixed_point_t value)
Set the CoAP non receive timeout delay timeout.
void coap_session_set_nstart(coap_session_t *session, uint16_t value)
Set the CoAP maximum concurrent transmission count of Confirmable messages RFC7252 NSTART.
#define COAP_DEFAULT_PROBING_RATE
The number of bytes/second allowed when there is no response RFC 7252, Section 4.8 Default value of P...
void coap_session_set_non_max_retransmit(coap_session_t *session, uint16_t value)
Set the CoAP NON maximum retransmit count of missing Q-Block1 or Q-Block2 requested before there is a...
uint16_t coap_session_get_max_payloads(const coap_session_t *session)
Get the CoAP maximum payloads count of Q-Block1 or Q-Block2 before delay is introduced RFC9177 MAX_PA...
#define COAP_DEFAULT_NON_RECEIVE_TIMEOUT
The time to wait for any missing Q-Block1 or Q-Block2 packets before requesting re-transmission of mi...
void coap_session_set_probing_rate(coap_session_t *session, uint32_t value)
Set the CoAP probing rate when there is no response RFC7252 PROBING_RATE.
void coap_session_set_default_leisure(coap_session_t *session, coap_fixed_point_t value)
Set the CoAP default leisure time (for multicast) RFC7252 DEFAULT_LEISURE.
coap_fixed_point_t coap_session_get_non_receive_timeout(const coap_session_t *session)
Get the CoAP non receive timeout delay timeout.
uint16_t coap_session_get_nstart(const coap_session_t *session)
Get the CoAP maximum concurrent transmission count of Confirmable messages RFC7252 NSTART.
#define COAP_DEFAULT_MAX_PAYLOADS
Number of Q-Block1 or Q-Block2 payloads that can be sent in a burst before a delay has to kick in.
coap_fixed_point_t coap_session_get_ack_timeout(const coap_session_t *session)
Get the CoAP initial ack response timeout before the next re-transmit.
void coap_session_set_non_timeout(coap_session_t *session, coap_fixed_point_t value)
Set the CoAP non timeout delay timeout.
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:143
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:158
int coap_prng_lkd(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition coap_prng.c:178
#define RESOURCES_ITER(r, tmp)
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4783
uint16_t coap_new_message_id_lkd(coap_session_t *session)
Returns a new message id and updates session->tx_mid accordingly.
int coap_delete_node_lkd(coap_queue_t *node)
Destroys specified node.
Definition coap_net.c:227
int coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id, coap_queue_t **node)
This function removes the element with given id from the list given list.
Definition coap_net.c:2838
int coap_client_delay_first(coap_session_t *session)
Delay the sending of the first client request until some other negotiation has completed.
Definition coap_net.c:1296
unsigned int coap_calc_timeout(coap_session_t *session, unsigned char r)
Calculates the initial timeout based on the session CoAP transmission parameters 'ack_timeout',...
Definition coap_net.c:1192
coap_mid_t coap_send_internal(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *request_pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:1781
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition coap_net.c:1218
coap_queue_t * coap_new_node(void)
Creates a new node suitable for adding to the CoAP sendqueue.
Definition coap_net.c:256
void coap_cancel_session_messages(coap_context_t *context, coap_session_t *session, coap_nack_reason_t reason)
Cancels all outstanding messages for session session.
Definition coap_net.c:2942
void coap_cancel_all_messages(coap_context_t *context, coap_session_t *session, coap_bin_const_t *token)
Cancels all outstanding messages for session session that have the specified token.
Definition coap_net.c:2981
void coap_ticks(coap_tick_t *)
Returns the current value of an internal tick counter.
COAP_API uint16_t coap_new_message_id(coap_session_t *session)
Returns a new message id and updates session->tx_mid accordingly.
@ COAP_RESPONSE_OK
Response is fine.
Definition coap_net.h:50
void coap_dtls_establish(coap_session_t *session)
Layer function interface for layer below DTLS connect being established.
Definition coap_dtls.c:266
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_context_set_cpsk(coap_context_t *coap_context, coap_dtls_cpsk_t *setup_data)
Set the DTLS context's default client PSK information.
#define COAP_DTLS_PKI_SETUP_VERSION
Latest PKI setup version.
Definition coap_dtls.h:307
#define COAP_DTLS_CPSK_SETUP_VERSION
Latest CPSK setup version.
Definition coap_dtls.h:405
coap_tls_library_t
Definition coap_dtls.h:70
@ COAP_DTLS_ROLE_CLIENT
Internal function invoked for client.
Definition coap_dtls.h:45
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
uint64_t coap_decode_var_bytes8(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:67
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:77
@ COAP_EVENT_SESSION_CONNECTED
Triggered when TCP layer completes exchange of CSM information.
Definition coap_event.h:61
@ COAP_EVENT_TCP_FAILED
Triggered when TCP layer fails for some reason.
Definition coap_event.h:55
@ COAP_EVENT_SESSION_FAILED
Triggered when TCP layer fails following exchange of CSM information.
Definition coap_event.h:65
@ COAP_EVENT_SERVER_SESSION_NEW
Called in the CoAP IO loop if a new server-side session is created due to an incoming connection.
Definition coap_event.h:85
@ COAP_EVENT_SESSION_CLOSED
Triggered when TCP layer closes following exchange of CSM information.
Definition coap_event.h:63
@ COAP_EVENT_SERVER_SESSION_DEL
Called in the CoAP IO loop if a server session is deleted (e.g., due to inactivity or because the max...
Definition coap_event.h:94
@ COAP_EVENT_TCP_CLOSED
Triggered when TCP layer is closed.
Definition coap_event.h:53
@ COAP_EVENT_TCP_CONNECTED
Triggered when TCP layer connects.
Definition coap_event.h:51
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:132
#define coap_lock_unlock(c)
Dummy for no thread-safe code.
#define coap_lock_lock(c, failed)
Dummy for no thread-safe code.
#define coap_lock_callback(c, func)
Dummy for no thread-safe code.
#define coap_lock_check_locked(c)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:120
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition coap_debug.c:101
size_t coap_print_addr(const coap_address_t *addr, unsigned char *buf, size_t len)
Print the address into the defined buffer.
Definition coap_debug.c:239
const char * coap_endpoint_str(const coap_endpoint_t *endpoint)
Get endpoint description.
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:108
#define coap_log_warn(...)
Definition coap_debug.h:102
#define coap_log_err(...)
Definition coap_debug.h:96
#define coap_log_crit(...)
Definition coap_debug.h:90
@ COAP_LOG_DEBUG
Definition coap_debug.h:58
int coap_netif_dgrm_listen(coap_endpoint_t *endpoint, const coap_address_t *listen_addr)
Layer function interface for Netif datagram listem (udp).
void coap_netif_close_ep(coap_endpoint_t *endpoint)
Layer function interface for Netif close for a endpoint.
int coap_netif_strm_connect1(coap_session_t *session, const coap_address_t *local_if, const coap_address_t *server, int default_port)
Layer function interface for Netif stream connect (tcp).
int coap_netif_strm_accept(coap_endpoint_t *endpoint, coap_session_t *session, void *extra)
Layer function interface for Netif stream accept.
int coap_netif_strm_listen(coap_endpoint_t *endpoint, const coap_address_t *listen_addr)
Layer function interface for Netif stream listem (tcp).
int coap_netif_dgrm_connect(coap_session_t *session, const coap_address_t *local_if, const coap_address_t *server, int default_port)
Layer function interface for Netif datagram connect (udp).
int coap_netif_available(coap_session_t *session)
Function interface to check whether netif for session is still available.
Definition coap_netif.c:25
int coap_netif_available_ep(coap_endpoint_t *endpoint)
Function interface to check whether netif for endpoint is still available.
void coap_delete_oscore_associations(coap_session_t *session)
Cleanup all allocated OSCORE association information.
coap_pdu_t * coap_pdu_reference_lkd(coap_pdu_t *pdu)
Increment reference counter on a pdu to stop it prematurely getting freed off when coap_delete_pdu() ...
Definition coap_pdu.c:1623
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:190
int coap_update_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Updates token in pdu with length len and data.
Definition coap_pdu.c:413
#define COAP_PDU_MAX_UDP_HEADER_SIZE
#define COAP_PDU_DELAYED
#define COAP_PDU_MAX_TCP_HEADER_SIZE
#define COAP_MAX_MESSAGE_SIZE_TCP8
#define COAP_MAX_MESSAGE_SIZE_TCP0
size_t coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto)
Compose the protocol specific header for the specified PDU.
Definition coap_pdu.c:1485
#define COAP_MAX_MESSAGE_SIZE_TCP16
size_t coap_add_option_internal(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Adds option of given number to pdu that is passed as first parameter.
Definition coap_pdu.c:776
#define COAP_DEFAULT_PORT
Definition coap_pdu.h:37
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:263
#define COAP_TOKEN_DEFAULT_MAX
Definition coap_pdu.h:56
#define COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH
Definition coap_pdu.h:199
coap_proto_t
CoAP protocol types.
Definition coap_pdu.h:312
#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
Definition coap_pdu.h:198
#define COAPS_DEFAULT_PORT
Definition coap_pdu.h:38
coap_pdu_t * coap_pdu_init(coap_pdu_type_t type, coap_pdu_code_t code, coap_mid_t mid, size_t size)
Creates a new CoAP PDU with at least enough storage space for the given size maximum message size.
Definition coap_pdu.c:99
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:266
#define COAP_DEFAULT_MTU
Definition coap_pdu.h:41
#define COAP_BERT_BASE
Definition coap_pdu.h:44
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition coap_pdu.h:197
@ COAP_PROTO_WS
Definition coap_pdu.h:318
@ COAP_PROTO_DTLS
Definition coap_pdu.h:315
@ COAP_PROTO_UDP
Definition coap_pdu.h:314
@ COAP_PROTO_NONE
Definition coap_pdu.h:313
@ COAP_PROTO_TLS
Definition coap_pdu.h:317
@ COAP_PROTO_WSS
Definition coap_pdu.h:319
@ COAP_PROTO_TCP
Definition coap_pdu.h:316
@ COAP_PROTO_LAST
Definition coap_pdu.h:320
@ COAP_SIGNALING_CODE_CSM
Definition coap_pdu.h:365
@ COAP_SIGNALING_CODE_PING
Definition coap_pdu.h:366
@ COAP_MESSAGE_NON
Definition coap_pdu.h:70
@ COAP_MESSAGE_CON
Definition coap_pdu.h:69
#define COAP_NON_PROBING_WAIT_BASE(s)
void coap_session_reestablished(coap_session_t *session)
Session has been re-connected to server.
ssize_t coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
int coap_session_refresh_psk_hint(coap_session_t *session, const coap_bin_const_t *psk_hint)
Refresh the session's current Identity Hint (PSK).
void coap_session_send_csm(coap_session_t *session)
Notify session transport has just connected and CSM exchange can now start.
coap_session_t * coap_new_client_session_psk2_lkd(coap_context_t *ctx, const coap_address_t *local_if, const coap_address_t *server, coap_proto_t proto, coap_dtls_cpsk_t *setup_data)
Creates a new client session to the designated server with PSK credentials.
coap_fixed_point_t coap_add_fixed_uint(coap_fixed_point_t fp1, uint32_t u2)
void coap_handle_nack(coap_session_t *session, coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
size_t coap_session_max_pdu_rcv_size(const coap_session_t *session)
Get maximum acceptable receive PDU size.
coap_fixed_point_t coap_sub_fixed_uint(coap_fixed_point_t fp1, uint32_t u2)
coap_session_t * coap_endpoint_get_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Lookup the server session for the packet received on an endpoint, or create a new one.
#define COAP_ACK_RANDOM_FACTOR(s)
void coap_free_endpoint_lkd(coap_endpoint_t *endpoint)
Release an endpoint and all the structures associated with it.
coap_session_t * coap_new_client_session_psk_lkd(coap_context_t *ctx, const coap_address_t *local_if, const coap_address_t *server, coap_proto_t proto, const char *identity, const uint8_t *key, unsigned key_len)
Creates a new client session to the designated server with PSK credentials.
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.
void coap_session_establish(coap_session_t *session)
Layer function interface for layer below session accept/connect being established.
coap_session_t * coap_new_client_session_pki_lkd(coap_context_t *ctx, const coap_address_t *local_if, const coap_address_t *server, coap_proto_t proto, coap_dtls_pki_t *setup_data)
Creates a new client session to the designated server with PKI credentials.
coap_session_t * coap_new_client_session_lkd(coap_context_t *ctx, const coap_address_t *local_if, const coap_address_t *server, coap_proto_t proto)
Creates a new client session to the designated server.
coap_fixed_point_t coap_add_fixed_fixed(coap_fixed_point_t fp1, coap_fixed_point_t fp2)
coap_tick_t coap_get_non_timeout_random_ticks(coap_session_t *session)
#define COAP_NSTART(s)
int coap_session_refresh_psk_key(coap_session_t *session, const coap_bin_const_t *psk_key)
Refresh the session's current pre-shared key (PSK).
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
void coap_session_failed(coap_session_t *session)
Session has failed due to a socket error.
coap_fixed_point_t coap_multi_fixed_fixed(coap_fixed_point_t fp1, coap_fixed_point_t fp2)
ssize_t coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu)
Send a pdu according to the session's protocol.
Definition coap_net.c:1070
size_t coap_session_max_pdu_size_lkd(const coap_session_t *session)
Get maximum acceptable PDU size.
int coap_session_set_type_client_lkd(coap_session_t *session)
Set the session type to client.
coap_mid_t coap_session_send_ping_lkd(coap_session_t *session)
Send a ping message for the session.
coap_fixed_point_t coap_div_fixed_uint(coap_fixed_point_t fp1, uint32_t u2)
void coap_session_free(coap_session_t *session)
void coap_session_mfree(coap_session_t *session)
void coap_session_release_lkd(coap_session_t *session)
Decrement reference counter on a session.
int coap_session_refresh_psk_identity(coap_session_t *session, const coap_bin_const_t *psk_identity)
Refresh the session's current pre-shared identity (PSK).
coap_fixed_point_t coap_get_non_timeout_random(coap_session_t *session)
#define COAP_NON_MAX_RETRANSMIT(s)
coap_session_t * coap_session_reference_lkd(coap_session_t *session)
Increment reference counter on a session.
#define COAP_NON_TIMEOUT(s)
void * coap_session_set_app_data2_lkd(coap_session_t *session, void *app_data, coap_app_data_free_callback_t callback)
Stores data with the given session, returning the previously stored value or NULL.
coap_fixed_point_t coap_multi_fixed_uint(coap_fixed_point_t fp1, uint32_t u2)
#define COAP_NON_PARTIAL_TIMEOUT(s)
void coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
coap_endpoint_t * coap_new_endpoint_lkd(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto)
Create a new endpoint for communicating with peers.
coap_session_t * coap_new_server_session(coap_context_t *ctx, coap_endpoint_t *ep, void *extra)
Creates a new server session for the specified endpoint.
@ COAP_EXT_T_CHECKED
Token size valid.
COAP_API void coap_session_set_app_data(coap_session_t *session, void *app_data)
Stores data with the given session.
COAP_API coap_session_t * coap_session_reference(coap_session_t *session)
Increment reference counter on a session.
coap_session_type_t
coap_session_type_t values
COAP_API void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
void coap_session_set_mtu(coap_session_t *session, unsigned mtu)
Set the session MTU.
coap_context_t * coap_session_get_context(const coap_session_t *session)
Get the session context.
const coap_address_t * coap_session_get_addr_local(const coap_session_t *session)
Get the local IP address and port from the session.
coap_proto_t coap_session_get_proto(const coap_session_t *session)
Get the session protocol type.
COAP_API int coap_session_set_type_client(coap_session_t *session)
Set the session type to client.
const coap_bin_const_t * coap_session_get_psk_key(const coap_session_t *session)
Get the session's current pre-shared key (PSK).
void * coap_session_get_tls(const coap_session_t *session, coap_tls_library_t *tls_lib)
Get the session TLS security ptr (TLS type dependent)
coap_session_state_t coap_session_get_state(const coap_session_t *session)
Get the session state.
coap_session_state_t
coap_session_state_t values
#define COAP_PROTO_NOT_RELIABLE(p)
COAP_API coap_session_t * coap_new_client_session_pki(coap_context_t *ctx, const coap_address_t *local_if, const coap_address_t *server, coap_proto_t proto, coap_dtls_pki_t *setup_data)
Creates a new client session to the designated server with PKI credentials.
void coap_session_init_token(coap_session_t *session, size_t len, const uint8_t *data)
Initializes the token value to use as a starting point.
#define COAP_PROTO_RELIABLE(p)
void coap_session_new_token(coap_session_t *session, size_t *len, uint8_t *data)
Creates a new token for use.
COAP_API coap_session_t * coap_new_client_session(coap_context_t *ctx, const coap_address_t *local_if, const coap_address_t *server, coap_proto_t proto)
Creates a new client session to the designated server.
const coap_bin_const_t * coap_session_get_psk_identity(const coap_session_t *session)
Get the server session's current PSK identity (PSK).
coap_session_t * coap_session_get_by_peer(const coap_context_t *ctx, const coap_address_t *remote_addr, int ifindex)
Get the session associated with the specified remote_addr and index.
void coap_endpoint_set_default_mtu(coap_endpoint_t *endpoint, unsigned mtu)
Set the endpoint's default MTU.
const coap_bin_const_t * coap_session_get_psk_hint(const coap_session_t *session)
Get the server session's current Identity Hint (PSK).
COAP_API coap_endpoint_t * coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto)
Create a new endpoint for communicating with peers.
const coap_address_t * coap_session_get_addr_remote(const coap_session_t *session)
Get the remote IP address and port from the session.
COAP_API void coap_free_endpoint(coap_endpoint_t *endpoint)
Release an endpoint and all the structures associated with it.
COAP_API void coap_session_release(coap_session_t *session)
Decrement reference counter on a session.
COAP_API coap_session_t * coap_new_client_session_psk2(coap_context_t *ctx, const coap_address_t *local_if, const coap_address_t *server, coap_proto_t proto, coap_dtls_cpsk_t *setup_data)
Creates a new client session to the designated server with PSK credentials.
const coap_address_t * coap_session_get_addr_mcast(const coap_session_t *session)
Get the remote multicast IP address and port from the session if the original target IP was multicast...
COAP_API size_t coap_session_max_pdu_size(const coap_session_t *session)
Get maximum acceptable PDU size.
COAP_API coap_session_t * coap_new_client_session_psk(coap_context_t *ctx, const coap_address_t *local_if, const coap_address_t *server, coap_proto_t proto, const char *identity, const uint8_t *key, unsigned key_len)
Creates a new client session to the designated server with PSK credentials.
int coap_session_get_ifindex(const coap_session_t *session)
Get the session if index.
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_API void * coap_session_set_app_data2(coap_session_t *session, void *app_data, coap_app_data_free_callback_t callback)
Stores data with the given session, returning the previously stored value or NULL.
void * coap_session_get_app_data(const coap_session_t *session)
Returns any application-specific data that has been stored with session using the function coap_sessi...
coap_session_type_t coap_session_get_type(const coap_session_t *session)
Get the session type.
@ 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_HANDSHAKE
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_ESTABLISHED
@ COAP_SESSION_STATE_NONE
@ COAP_SESSION_STATE_CONNECTING
void coap_delete_bin_const(coap_bin_const_t *s)
Deletes the given const binary data and releases any memory allocated.
Definition coap_str.c:120
void coap_delete_str_const(coap_str_const_t *s)
Deletes the given const string and releases any memory allocated.
Definition coap_str.c:61
coap_bin_const_t * coap_new_bin_const(const uint8_t *data, size_t size)
Take the specified byte array (text) and create a coap_bin_const_t * Returns a new const binary objec...
Definition coap_str.c:110
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:211
int coap_delete_observer(coap_resource_t *resource, coap_session_t *session, const coap_bin_const_t *token)
Removes any subscription for session observer from resource and releases the allocated storage.
int coap_cancel_observe_lkd(coap_session_t *session, coap_binary_t *token, coap_pdu_type_t message_type)
Cancel an observe that is being tracked by the client large receive logic.
void coap_delete_observers(coap_context_t *context, coap_session_t *session)
Removes any subscription for session and releases the allocated storage.
int coap_tcp_is_supported(void)
Check whether TCP is available.
Definition coap_tcp.c:29
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition coap_notls.c:41
int coap_ws_is_supported(void)
Check whether WebSockets is available.
Definition coap_ws.c:933
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition coap_notls.c:36
int coap_wss_is_supported(void)
Check whether Secure WebSockets is available.
Definition coap_ws.c:938
Only used for servers for hashing incoming packets.
uint16_t lport
local port
coap_address_t remote
remote address and port
coap_proto_t proto
CoAP protocol.
coap_address_t remote
remote address and port
Definition coap_io.h:56
coap_address_t local
local address and port
Definition coap_io.h:57
Multi-purpose address abstraction.
CoAP binary data definition with const data.
Definition coap_str.h:64
size_t length
length of binary data
Definition coap_str.h:65
const uint8_t * s
read-only binary data
Definition coap_str.h:66
coap_session_t * session
The CoAP stack's global state is stored in a coap_context_t object.
unsigned int reconnect_time
Time to wait before reconnecting a failed client session.
coap_session_t * sessions
client sessions
coap_nack_handler_t nack_handler
Called when a response issue has occurred.
coap_resource_t * resources
hash table or list of known resources
uint32_t csm_max_message_size
Value for CSM Max-Message-Size.
unsigned int max_handshake_sessions
Maximum number of simultaneous negotating sessions per endpoint.
coap_queue_t * sendqueue
uint32_t max_token_size
Largest token size supported RFC8974.
coap_cache_entry_t * cache
CoAP cache-entry cache.
coap_endpoint_t * endpoint
the endpoints used for listening
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
coap_resource_t * unknown_resource
can be used for handling unknown resources
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
coap_bin_const_t key
Definition coap_dtls.h:381
coap_bin_const_t identity
Definition coap_dtls.h:380
The structure used for defining the Client PSK setup data to be used.
Definition coap_dtls.h:410
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition coap_dtls.h:437
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition coap_dtls.h:443
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:312
uint8_t version
Definition coap_dtls.h:313
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition coap_dtls.h:368
Abstraction of virtual endpoint that can be attached to coap_context_t.
coap_context_t * context
endpoint's context
uint16_t default_mtu
default mtu for this interface
coap_session_t * sessions
hash table or list of active sessions
coap_address_t bind_addr
local interface address
coap_socket_t sock
socket object for the interface, if any
coap_proto_t proto
protocol used on this interface
Abstraction of a fixed point number that can be used where necessary instead of a float.
uint16_t fractional_part
Fractional part of fixed point variable 1/1000 (3 points) precision.
uint16_t integer_part
Integer part of fixed point variable.
coap_layer_establish_t l_establish
coap_layer_close_t l_close
Structure to hold large body (many blocks) client receive information.
coap_binary_t * app_token
app requesting PDU token
coap_pdu_t * sent_pdu
The sent pdu with all the data.
uint8_t observe_set
Set if this is an observe receive PDU.
Structure to hold large body (many blocks) server receive information.
Structure to hold large body (many blocks) transmission information.
size_t length
length of payload
coap_addr_tuple_t addr_info
local and remote addresses
unsigned char * payload
payload
int ifindex
the interface index
structure for CoAP PDUs
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.
coap_mid_t mid
message id, if any, in regular host byte order
size_t used_size
used bytes of 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
struct coap_queue_t * next
coap_mid_t id
CoAP message id.
coap_tick_t t
when to send PDU for the next time
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.
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
coap_endpoint_t * endpoint
session's endpoint
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
coap_app_data_free_callback_t app_cb
call-back to release app_data
uint8_t doing_first
Set if doing client's first request.
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.
uint16_t nstart
maximum concurrent confirmable xmits (default 1)
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
uint64_t tx_token
Next token number to use.
coap_bin_const_t * client_cid
Contains client CID or NULL.
coap_address_t local_reconnect
local address to initiate reconnect from
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
uint16_t tx_mid
the last message id that was used in this session
uint8_t is_dtls13
Set if session is DTLS1.3.
unsigned ref
reference count from queues
size_t csm_rcv_mtu
CSM mtu (rcv)
coap_response_t last_con_handler_res
The result of calling the response handler of the last CON.
coap_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
coap_bin_const_t * last_token
uint8_t doing_send_recv
Set if coap_send_recv() active.
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
uint8_t no_observe_cancel
Set if do not cancel observe on session close.
size_t partial_read
if > 0 indicates number of bytes already read for an incoming message
int dtls_event
Tracking any (D)TLS events on this session.
uint16_t max_retransmit
maximum re-transmit count (default 4)
coap_fixed_point_t ack_random_factor
ack random factor backoff (default 1.5)
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
size_t tls_overhead
overhead of TLS layer
void * app_data
application-specific data
uint32_t tx_rtag
Next Request-Tag number to use.
coap_mid_t last_ping_mid
the last keepalive message id that was used in this session
coap_lg_srcv_t * lg_srcv
Server list of expected large receives.
coap_bin_const_t * req_token
Token in request pdu of coap_send_recv()
coap_lg_crcv_t * lg_crcv
Client list of expected large receives.
coap_fixed_point_t ack_timeout
timeout waiting for ack (default 2.0 secs)
coap_fixed_point_t default_leisure
Mcast leisure time (default 5.0 secs)
coap_mid_t last_con_mid
The last CON mid that has been been processed.
coap_session_type_t type
client or server side socket
uint32_t probing_rate
Max transfer wait when remote is not respoding (default 1 byte/sec)
coap_mid_t last_ack_mid
The last ACK mid that has been been processed.
coap_context_t * context
session's context
uint8_t session_failed
Set if session failed and can try re-connect.
size_t partial_write
if > 0 indicates number of bytes already written from the pdu at the head of sendqueue
coap_addr_hash_t addr_hash
Address hash for server incoming packets.
coap_pdu_t * cached_pdu
Cached copy of last ACK response PDU.
int ifindex
interface index
coap_bin_const_t * echo
last token used to make a request
coap_layer_func_t lfunc[COAP_LAYER_LAST]
Layer functions to use.
coap_session_t * session
Used to determine session owner.
coap_endpoint_t * endpoint
Used by the epoll logic for a listening endpoint.
coap_address_t mcast_addr
remote address and port (multicast track)
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values