1#[cfg(test)]
2mod association_flow_test;
3#[cfg(test)]
4mod endpoint_test;
5#[cfg(test)]
6mod handshake_failure_test;
7#[cfg(test)]
8mod handshake_loss_test;
9#[cfg(test)]
10pub(crate) mod link_test;
11#[cfg(test)]
12mod loss_recovery_test;
13#[cfg(test)]
14mod random_source_test;
15#[cfg(test)]
16mod sctp_port_test;
17
18use std::{
19 collections::{HashMap, VecDeque},
20 fmt, iter,
21 net::SocketAddr,
22 ops::{Index, IndexMut},
23 sync::Arc,
24 sync::atomic::{AtomicBool, Ordering},
25 time::Instant,
26};
27
28use rustc_hash::FxHashMap;
29
30use crate::Payload;
31use crate::association::Association;
32use crate::chunk::chunk_abort::ChunkAbort;
33use crate::chunk::chunk_shutdown_complete::ChunkShutdownComplete;
34use crate::chunk::chunk_type::{
35 CT_ABORT, CT_COOKIE_ACK, CT_COOKIE_ECHO, CT_ERROR, CT_INIT, CT_SHUTDOWN_ACK,
36 CT_SHUTDOWN_COMPLETE,
37};
38use crate::chunk::{Chunk, ErrorCause, OUT_OF_RESOURCE, STALE_COOKIE_ERROR};
39use crate::config::{ClientConfig, EndpointConfig, ServerConfig, TransportConfig};
40use crate::cookie::{CookieSigner, cookie_key_id};
41use crate::packet::PartialDecode;
42use crate::packet::{CommonHeader, Packet};
43use crate::shared::{
44 AssociationEvent, AssociationEventInner, AssociationId, EndpointEvent, EndpointEventInner,
45};
46use crate::util::AssociationIdGenerator;
47use shared::{EcnCodepoint, TransportContext, TransportMessage, TransportProtocol};
48
49use bytes::Bytes;
50use log::{debug, trace, warn};
51use slab::Slab;
52use thiserror::Error;
53
54pub struct Endpoint {
60 local_addr: SocketAddr,
61 transport_protocol: TransportProtocol,
62 association_ids_init: HashMap<AssociationId, AssociationHandle>,
67 association_ids: FxHashMap<AssociationId, AssociationHandle>,
71 association_peers: HashMap<PeerKey, AssociationHandle>,
77
78 associations: Slab<AssociationMeta>,
79 live: usize,
82 local_cid_generator: Box<dyn AssociationIdGenerator>,
83 endpoint_config: Arc<EndpointConfig>,
84 server_config: Option<Arc<ServerConfig>>,
85 reject_new_associations: bool,
89 transmits: VecDeque<TransportMessage<Payload>>,
91 cookie_signers: Vec<Arc<CookieSigner>>,
94 cookie_epoch: Option<Instant>,
96}
97
98const COOKIE_KEY_LIFETIME: std::time::Duration = std::time::Duration::from_secs(3600);
102
103const MAX_QUEUED_OOTB_RESPONSES: usize = 16;
106
107impl fmt::Debug for Endpoint {
108 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
109 fmt.debug_struct("Endpoint<T>")
110 .field("association_ids_initial", &self.association_ids_init)
111 .field("association_ids", &self.association_ids)
112 .field("associations", &self.associations)
113 .field("config", &self.endpoint_config)
114 .field("server_config", &self.server_config)
115 .field("reject_new_associations", &self.reject_new_associations)
116 .finish()
117 }
118}
119
120impl Endpoint {
121 pub fn new(
125 local_addr: SocketAddr,
126 transport_protocol: TransportProtocol,
127 endpoint_config: Arc<EndpointConfig>,
128 server_config: Option<Arc<ServerConfig>>,
129 ) -> Self {
130 Self {
131 local_addr,
132 transport_protocol,
133 association_ids_init: HashMap::default(),
134 association_ids: FxHashMap::default(),
135 association_peers: HashMap::default(),
136 associations: Slab::new(),
137 live: 0,
138 local_cid_generator: (endpoint_config.aid_generator_factory.as_ref())(),
139 reject_new_associations: false,
140 transmits: VecDeque::new(),
141 cookie_signers: vec![],
142 cookie_epoch: None,
143 endpoint_config,
144 server_config,
145 }
146 }
147
148 #[cfg(test)]
150 pub(crate) fn association_count(&self) -> usize {
151 self.associations.len()
152 }
153
154 pub fn set_server_config(&mut self, server_config: Option<Arc<ServerConfig>>) {
156 self.server_config = server_config;
157 }
158
159 pub fn handle_event(&mut self, ch: AssociationHandle, event: EndpointEvent) {
161 match event.0 {
162 EndpointEventInner::Drained => {
163 self.release(ch);
166 self.associations.try_remove(ch.0);
167 }
168 EndpointEventInner::Retagged {
169 old_local,
170 new_local,
171 old_peer,
172 new_peer,
173 } => {
174 let Some(meta) = self.associations.get_mut(ch.0) else {
175 return;
176 };
177 if meta.released {
178 return;
179 }
180 for cid in meta.loc_cids.values_mut() {
181 if *cid == old_local {
182 *cid = new_local;
183 }
184 }
185 if self.association_ids.get(&old_local) == Some(&ch) {
186 self.association_ids.remove(&old_local);
187 }
188 self.association_ids.insert(new_local, ch);
189 if meta.init_cid == old_peer {
190 if self.association_ids_init.get(&old_peer) == Some(&ch) {
191 self.association_ids_init.remove(&old_peer);
192 }
193 meta.init_cid = new_peer;
194 self.association_ids_init.insert(new_peer, ch);
195 }
196 }
197 }
198 }
199
200 fn release(&mut self, ch: AssociationHandle) {
204 let Some(meta) = self.associations.get_mut(ch.0) else {
205 return;
206 };
207 if meta.released {
208 return;
209 }
210 meta.released = true;
211 self.live = self.live.saturating_sub(1);
212 if self.association_ids_init.get(&meta.init_cid) == Some(&ch) {
215 self.association_ids_init.remove(&meta.init_cid);
216 }
217 if self.association_peers.get(&meta.peer) == Some(&ch) {
218 self.association_peers.remove(&meta.peer);
219 }
220 for cid in meta.loc_cids.values() {
221 self.association_ids.remove(cid);
222 }
223 }
224
225 fn release_if_ended(&mut self, ch: AssociationHandle) -> bool {
228 let ended = self
229 .associations
230 .get(ch.0)
231 .is_none_or(|meta| meta.ended.load(Ordering::Relaxed));
232 if ended {
233 self.release(ch);
234 }
235 ended
236 }
237
238 fn release_ended(&mut self) {
241 let ended: Vec<AssociationHandle> = self
242 .associations
243 .iter()
244 .filter(|(_, meta)| !meta.released && meta.ended.load(Ordering::Relaxed))
245 .map(|(id, _)| AssociationHandle(id))
246 .collect();
247 for ch in ended {
248 self.release(ch);
249 }
250 }
251
252 fn association_for_peer(
257 &self,
258 remote: SocketAddr,
259 ports: (u16, u16),
260 ) -> Option<AssociationHandle> {
261 if let Some(ch) = self.association_peers.get(&(remote, ports.0, ports.1)) {
262 return Some(*ch);
263 }
264 let single = self
265 .server_config
266 .as_ref()
267 .is_some_and(|config| config.concurrent_associations == 1);
268 if single && self.live == 1 {
269 return self
270 .associations
271 .iter()
272 .find(|(_, meta)| !meta.released && (meta.peer.1, meta.peer.2) == ports)
273 .map(|(id, _)| AssociationHandle(id));
274 }
275 None
276 }
277
278 pub fn handle(
280 &mut self,
281 now: Instant,
282 remote: SocketAddr,
283 ecn: Option<EcnCodepoint>,
284 data: Bytes,
285 ) -> Option<(AssociationHandle, DatagramEvent)> {
286 let partial_decode = match PartialDecode::unmarshal(&data) {
287 Ok(x) => x,
288 Err(err) => {
289 trace!("malformed header: {}", err);
290 return None;
291 }
292 };
293
294 let dst_cid = partial_decode.common_header.verification_tag;
298 let known_ch = if dst_cid > 0 {
299 let ports = (
304 partial_decode.common_header.source_port,
305 partial_decode.common_header.destination_port,
306 );
307 self.association_ids
308 .get(&dst_cid)
309 .cloned()
310 .or_else(|| self.association_for_peer(remote, ports))
311 } else {
312 if partial_decode.first_chunk_type == CT_INIT {
330 let ports = (
331 partial_decode.common_header.source_port,
332 partial_decode.common_header.destination_port,
333 );
334 partial_decode
335 .initiate_tag
336 .and_then(|initiate_tag| self.association_ids_init.get(&initiate_tag))
337 .copied()
338 .or_else(|| self.association_for_peer(remote, ports))
339 } else {
340 None
341 }
342 };
343 let known_ch = known_ch.filter(|ch| !self.release_if_ended(*ch));
345
346 if let Some(ch) = known_ch {
347 return Some((
348 ch,
349 DatagramEvent::AssociationEvent(AssociationEvent(AssociationEventInner::Datagram(
350 TransportMessage {
351 now,
352 transport: TransportContext {
353 local_addr: self.local_addr,
354 peer_addr: remote,
355 ecn,
356 transport_protocol: self.transport_protocol,
357 },
358 message: Payload::PartialDecode(partial_decode),
359 },
360 ))),
361 ));
362 }
363
364 if !partial_decode.checksum_ok(false) {
375 let announces_zero_checksum = self
376 .server_config
377 .as_ref()
378 .is_some_and(|config| config.transport.zero_checksum());
379 if announces_zero_checksum
380 && partial_decode.first_chunk_type != CT_INIT
381 && partial_decode.first_chunk_type != CT_COOKIE_ECHO
382 && partial_decode.checksum_ok(true)
383 {
384 self.handle_out_of_the_blue(now, remote, &partial_decode);
385 return None;
386 }
387 trace!("discarding a packet with a zero checksum that belongs to no association");
388 return None;
389 }
390
391 if let Some(signer) = self.cookie_signer(now) {
394 if partial_decode.first_chunk_type == CT_INIT && dst_cid == 0 {
395 self.answer_init_without_state(now, remote, ecn, partial_decode, signer);
396 return None;
397 }
398 if partial_decode.first_chunk_type == CT_COOKIE_ECHO {
399 return self
400 .accept_cookie_echo(now, remote, ecn, partial_decode)
401 .map(|(ch, a)| (ch, DatagramEvent::NewAssociation(a)));
402 }
403 }
404
405 if partial_decode.first_chunk_type == CT_INIT && dst_cid == 0 {
409 let common_header = CommonHeader {
410 source_port: partial_decode.common_header.source_port,
411 destination_port: partial_decode.common_header.destination_port,
412 verification_tag: 0,
413 };
414 let initiate_tag = partial_decode.initiate_tag;
415 let accepted = self.handle_first_packet(now, remote, ecn, partial_decode);
416 if accepted.is_none()
417 && let Some(tag) = initiate_tag.filter(|tag| *tag != 0)
418 {
419 self.respond(
422 now,
423 remote,
424 &common_header,
425 tag,
426 Box::new(ChunkAbort {
427 error_causes: vec![ErrorCause {
428 code: OUT_OF_RESOURCE,
429 ..Default::default()
430 }],
431 tag_reflected: false,
432 }),
433 );
434 }
435 return accepted.map(|(ch, a)| (ch, DatagramEvent::NewAssociation(a)));
436 }
437
438 self.handle_out_of_the_blue(now, remote, &partial_decode);
439 None
440 }
441
442 fn cookie_signer(&mut self, now: Instant) -> Option<Arc<CookieSigner>> {
445 let provider = self.server_config.as_ref()?.cookie_provider.clone()?;
446 let epoch = *self.cookie_epoch.get_or_insert(now);
447 let expired = self
448 .cookie_signers
449 .first()
450 .is_none_or(|s| now.saturating_duration_since(s.since) >= COOKIE_KEY_LIFETIME);
451 if expired {
452 let key_id = self
453 .cookie_signers
454 .first()
455 .map_or(0, |s| s.key_id().wrapping_add(1));
456 let signer = Arc::new(CookieSigner::new(provider, key_id, epoch, now)?);
457 self.cookie_signers.insert(0, signer);
458 self.cookie_signers.truncate(2);
459 }
460 self.cookie_signers.first().cloned()
461 }
462
463 fn has_room(&mut self) -> bool {
465 let Some(limit) = self
466 .server_config
467 .as_ref()
468 .map(|config| config.concurrent_associations as usize)
469 else {
470 return false;
471 };
472 if self.live >= limit {
473 self.release_ended();
475 }
476 self.live < limit && !self.reject_new_associations && !self.is_full()
477 }
478
479 fn answer_init_without_state(
483 &mut self,
484 now: Instant,
485 remote: SocketAddr,
486 ecn: Option<EcnCodepoint>,
487 partial_decode: PartialDecode,
488 signer: Arc<CookieSigner>,
489 ) {
490 let Some(initiate_tag) = partial_decode.initiate_tag else {
491 return;
492 };
493 let received = CommonHeader {
494 source_port: partial_decode.common_header.source_port,
495 destination_port: partial_decode.common_header.destination_port,
496 verification_tag: 0,
497 };
498 if !self.has_room() {
499 if initiate_tag != 0 {
502 self.respond(
503 now,
504 remote,
505 &received,
506 initiate_tag,
507 Box::new(ChunkAbort {
508 error_causes: vec![ErrorCause {
509 code: OUT_OF_RESOURCE,
510 ..Default::default()
511 }],
512 tag_reflected: false,
513 }),
514 );
515 }
516 return;
517 }
518 let Some(server_config) = self.server_config.clone() else {
519 return;
520 };
521 let local_aid = self.new_aid();
522 let mut association = Association::new(
523 Some(server_config.clone()),
524 server_config.transport.clone(),
525 self.endpoint_config.get_max_payload_size(),
526 local_aid,
527 remote,
528 self.local_addr,
529 self.transport_protocol,
530 now,
531 self.endpoint_config.random.clone(),
532 );
533 association.set_cookie_signer(signer);
534 association.handle_event(AssociationEvent(AssociationEventInner::Datagram(
535 TransportMessage {
536 now,
537 transport: TransportContext {
538 local_addr: self.local_addr,
539 peer_addr: remote,
540 ecn,
541 transport_protocol: self.transport_protocol,
542 },
543 message: Payload::PartialDecode(partial_decode),
544 },
545 )));
546 while let Some(transmit) = association.poll_transmit(now) {
548 if self.transmits.len() >= MAX_QUEUED_OOTB_RESPONSES {
549 trace!("too many answers queued; not answering an INIT");
550 break;
551 }
552 self.transmits.push_back(TransportMessage {
553 now,
554 transport: TransportContext {
555 local_addr: self.local_addr,
556 peer_addr: remote,
557 ecn: None,
558 transport_protocol: self.transport_protocol,
559 },
560 message: transmit.message,
561 });
562 }
563 }
564
565 fn accept_cookie_echo(
569 &mut self,
570 now: Instant,
571 remote: SocketAddr,
572 ecn: Option<EcnCodepoint>,
573 partial_decode: PartialDecode,
574 ) -> Option<(AssociationHandle, Association)> {
575 let header = &partial_decode.common_header;
576 let received = CommonHeader {
577 source_port: header.source_port,
578 destination_port: header.destination_port,
579 verification_tag: header.verification_tag,
580 };
581 let cookie = partial_decode
582 .chunk_headers()
583 .into_iter()
584 .find(|(typ, _)| *typ == CT_COOKIE_ECHO)
585 .map(|(_, value)| value)?;
586 let key_id = cookie_key_id(&cookie)?;
589 let signer = self
590 .cookie_signers
591 .iter()
592 .find(|s| s.key_id() == key_id)
593 .cloned()?;
594 let fields = signer.open(&cookie)?;
595 if fields.my_tag != received.verification_tag
597 || fields.destination_port != received.source_port
598 || fields.source_port != received.destination_port
599 {
600 return None;
601 }
602 let server_config = self.server_config.clone()?;
603 let age = signer.age(&fields, now);
606 let life = server_config.transport.valid_cookie_life();
607 if age > life {
608 let staleness = u32::try_from((age - life).as_micros()).unwrap_or(u32::MAX);
609 self.respond(
610 now,
611 remote,
612 &received,
613 fields.peer_tag,
614 Box::new(crate::chunk::chunk_error::ChunkError {
615 error_causes: vec![ErrorCause {
616 code: STALE_COOKIE_ERROR,
617 raw: Bytes::copy_from_slice(&staleness.to_be_bytes()),
618 }],
619 }),
620 );
621 return None;
622 }
623 if self.association_ids.contains_key(&fields.my_tag) {
624 return None;
625 }
626 if !self.has_room() {
627 self.respond(
628 now,
629 remote,
630 &received,
631 fields.peer_tag,
632 Box::new(ChunkAbort {
633 error_causes: vec![ErrorCause {
634 code: OUT_OF_RESOURCE,
635 ..Default::default()
636 }],
637 tag_reflected: false,
638 }),
639 );
640 return None;
641 }
642
643 let (ch, mut association) = self.add_association(
645 fields.peer_tag,
646 fields.my_tag,
647 remote,
648 (received.source_port, received.destination_port),
649 now,
650 Some(server_config.clone()),
651 server_config.transport.clone(),
652 );
653 self.association_ids_init.insert(fields.peer_tag, ch);
654 association.restore_from_cookie(&fields, cookie, signer, now);
655 association.handle_event(AssociationEvent(AssociationEventInner::Datagram(
656 TransportMessage {
657 now,
658 transport: TransportContext {
659 local_addr: self.local_addr,
660 peer_addr: remote,
661 ecn,
662 transport_protocol: self.transport_protocol,
663 },
664 message: Payload::PartialDecode(partial_decode),
665 },
666 )));
667 Some((ch, association))
668 }
669
670 fn handle_out_of_the_blue(
679 &mut self,
680 now: Instant,
681 remote: SocketAddr,
682 partial_decode: &PartialDecode,
683 ) {
684 let header = &partial_decode.common_header;
685 if header.verification_tag == 0 || header.source_port == 0 || header.destination_port == 0 {
686 return;
687 }
688 let chunks = partial_decode.chunk_headers();
689 let has = |typ: crate::chunk::chunk_type::ChunkType| chunks.iter().any(|(t, _)| *t == typ);
690 let stale_cookie = chunks.iter().any(|(typ, value)| {
691 *typ == CT_ERROR
692 && crate::chunk::chunk_error::ChunkError::causes(value)
693 .contains(&STALE_COOKIE_ERROR)
694 });
695 if has(CT_ABORT) || has(CT_INIT) {
696 return;
697 }
698 if partial_decode.first_chunk_type == CT_COOKIE_ECHO {
699 return;
700 }
701 let response: Box<dyn Chunk> = if has(CT_SHUTDOWN_ACK) {
702 Box::new(ChunkShutdownComplete {
703 tag_reflected: true,
704 })
705 } else if has(CT_SHUTDOWN_COMPLETE) || has(CT_COOKIE_ACK) || stale_cookie {
706 return;
707 } else {
708 Box::new(ChunkAbort {
709 error_causes: vec![],
710 tag_reflected: true,
711 })
712 };
713 let tag = header.verification_tag;
714 self.respond(now, remote, header, tag, response);
715 }
716
717 fn respond(
720 &mut self,
721 now: Instant,
722 remote: SocketAddr,
723 received: &CommonHeader,
724 tag: u32,
725 chunk: Box<dyn Chunk>,
726 ) {
727 if self.transmits.len() >= MAX_QUEUED_OOTB_RESPONSES {
728 trace!("too many answers to out-of-the-blue packets queued; not answering");
729 return;
730 }
731 let packet = Packet {
732 common_header: CommonHeader {
733 source_port: received.destination_port,
734 destination_port: received.source_port,
735 verification_tag: tag,
736 },
737 chunks: vec![chunk],
738 };
739 let Ok(raw) = packet.marshal() else {
740 return;
741 };
742 self.transmits.push_back(TransportMessage {
743 now,
744 transport: TransportContext {
745 local_addr: self.local_addr,
746 peer_addr: remote,
747 ecn: None,
748 transport_protocol: self.transport_protocol,
749 },
750 message: Payload::RawEncode(vec![raw]),
751 });
752 }
753
754 #[must_use]
762 pub fn poll_transmit(&mut self) -> Option<TransportMessage<Payload>> {
763 self.transmits.pop_front()
764 }
765
766 pub fn connect(
768 &mut self,
769 now: Instant,
770 config: ClientConfig,
771 remote: SocketAddr,
772 ) -> Result<(AssociationHandle, Association), ConnectError> {
773 if self.is_full() {
774 return Err(ConnectError::TooManyAssociations);
775 }
776 if remote.port() == 0 {
777 return Err(ConnectError::InvalidRemoteAddress(remote));
778 }
779 if config.transport.sctp_port() == 0 || config.transport.remote_sctp_port() == 0 {
782 return Err(ConnectError::ZeroSctpPort);
783 }
784
785 let remote_aid = self.endpoint_config.random.nonzero_u32();
786 let local_aid = self.new_aid();
787
788 let ports = (
789 config.transport.remote_sctp_port(),
790 config.transport.sctp_port(),
791 );
792 let (ch, conn) = self.add_association(
793 remote_aid,
794 local_aid,
795 remote,
796 ports,
797 now,
798 None,
799 config.transport,
800 );
801 Ok((ch, conn))
802 }
803
804 fn new_aid(&mut self) -> AssociationId {
805 loop {
806 let aid = self.local_cid_generator.generate_aid();
807 if !self.association_ids.contains_key(&aid) {
808 break aid;
809 }
810 }
811 }
812
813 fn handle_first_packet(
814 &mut self,
815 now: Instant,
816 remote: SocketAddr,
817 ecn: Option<EcnCodepoint>,
818 partial_decode: PartialDecode,
819 ) -> Option<(AssociationHandle, Association)> {
820 if partial_decode.first_chunk_type != CT_INIT
821 || (partial_decode.first_chunk_type == CT_INIT && partial_decode.initiate_tag.is_none())
822 {
823 debug!("refusing first packet with Non-INIT or empty initial_tag INIT");
824 return None;
825 }
826
827 let server_config = if let Some(server_config) = self.server_config.as_ref() {
828 server_config
829 } else {
830 warn!("refusing first packet due to empty server_config");
831 return None;
832 };
833
834 let limit = server_config.concurrent_associations as usize;
835 if self.live >= limit {
836 self.release_ended();
838 }
839 let server_config = self.server_config.as_ref()?;
840 if self.live >= limit || self.reject_new_associations || self.is_full() {
841 debug!("refusing association");
842 return None;
844 }
845
846 let server_config = server_config.clone();
847 let transport_config = server_config.transport.clone();
848
849 let Some(initiate_tag) = partial_decode.initiate_tag.as_ref() else {
852 debug!("refusing INIT with empty initiate_tag (should have been caught above)");
853 return None;
854 };
855 let remote_aid = *initiate_tag;
856 let local_aid = self.new_aid();
857
858 let ports = (
859 partial_decode.common_header.source_port,
860 partial_decode.common_header.destination_port,
861 );
862 let (ch, mut conn) = self.add_association(
863 remote_aid,
864 local_aid,
865 remote,
866 ports,
867 now,
868 Some(server_config),
869 transport_config,
870 );
871 self.association_ids_init.insert(remote_aid, ch);
873
874 conn.handle_event(AssociationEvent(AssociationEventInner::Datagram(
875 TransportMessage {
876 now,
877 transport: TransportContext {
878 local_addr: self.local_addr,
879 peer_addr: remote,
880 ecn,
881 transport_protocol: self.transport_protocol,
882 },
883 message: Payload::PartialDecode(partial_decode),
884 },
885 )));
886
887 Some((ch, conn))
888 }
889
890 #[allow(clippy::too_many_arguments)]
891 fn add_association(
892 &mut self,
893 remote_aid: AssociationId,
894 local_aid: AssociationId,
895 remote_addr: SocketAddr,
896 ports: (u16, u16),
897 now: Instant,
898 server_config: Option<Arc<ServerConfig>>,
899 transport_config: Arc<TransportConfig>,
900 ) -> (AssociationHandle, Association) {
901 let conn = Association::new(
902 server_config,
903 transport_config,
904 self.endpoint_config.get_max_payload_size(),
905 local_aid,
906 remote_addr,
907 self.local_addr,
908 self.transport_protocol,
909 now,
910 self.endpoint_config.random.clone(),
911 );
912
913 let peer = (remote_addr, ports.0, ports.1);
914 let id = self.associations.insert(AssociationMeta {
915 init_cid: remote_aid,
916 cids_issued: 0,
917 loc_cids: iter::once((0, local_aid)).collect(),
918 initial_remote: remote_addr,
919 peer,
920 ended: conn.ended_flag(),
921 released: false,
922 });
923 self.live += 1;
924
925 let ch = AssociationHandle(id);
926 self.association_ids.insert(local_aid, ch);
927 self.association_peers.insert(peer, ch);
928
929 (ch, conn)
930 }
931
932 pub fn reject_new_associations(&mut self) {
934 self.reject_new_associations = true;
935 }
936
937 pub fn endpoint_config(&self) -> &EndpointConfig {
939 &self.endpoint_config
940 }
941
942 fn is_full(&self) -> bool {
944 (((u32::MAX >> 1) + (u32::MAX >> 2)) as usize) < self.association_ids.len()
945 }
946
947 #[cfg(test)]
949 pub(crate) fn live_associations(&self) -> usize {
950 self.live
951 }
952}
953
954#[derive(Debug)]
955pub(crate) struct AssociationMeta {
956 init_cid: AssociationId,
957 cids_issued: u64,
959 loc_cids: HashMap<u64, AssociationId>,
960 initial_remote: SocketAddr,
965 peer: PeerKey,
967 ended: Arc<AtomicBool>,
969 released: bool,
971}
972
973type PeerKey = (SocketAddr, u16, u16);
975
976#[derive(Default, Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
978pub struct AssociationHandle(pub usize);
979
980impl From<AssociationHandle> for usize {
981 fn from(x: AssociationHandle) -> usize {
982 x.0
983 }
984}
985
986impl Index<AssociationHandle> for Slab<AssociationMeta> {
987 type Output = AssociationMeta;
988 fn index(&self, ch: AssociationHandle) -> &AssociationMeta {
989 &self[ch.0]
990 }
991}
992
993impl IndexMut<AssociationHandle> for Slab<AssociationMeta> {
994 fn index_mut(&mut self, ch: AssociationHandle) -> &mut AssociationMeta {
995 &mut self[ch.0]
996 }
997}
998
999#[allow(clippy::large_enum_variant)] #[non_exhaustive]
1002pub enum DatagramEvent {
1003 AssociationEvent(AssociationEvent),
1005 NewAssociation(Association),
1007}
1008
1009#[derive(Debug, Error, Clone, PartialEq, Eq)]
1013#[non_exhaustive]
1014pub enum ConnectError {
1015 #[error("endpoint stopping")]
1019 EndpointStopping,
1020 #[error("too many associations")]
1024 TooManyAssociations,
1025 #[error("invalid DNS name: {0}")]
1027 InvalidDnsName(String),
1028 #[error("invalid remote address: {0}")]
1032 InvalidRemoteAddress(SocketAddr),
1033 #[error("no default client config")]
1037 NoDefaultClientConfig,
1038 #[error("SCTP port 0 must not be used (RFC 9260 section 3.1)")]
1043 ZeroSctpPort,
1044}