Skip to main content

rtci_sctp/endpoint/
mod.rs

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
54/// The main entry point to the library
55///
56/// This object performs no I/O whatsoever. Instead, it generates a stream of packets to send via
57/// `poll_transmit`, and consumes incoming packets and association-generated events via `handle` and
58/// `handle_event`.
59pub struct Endpoint {
60    local_addr: SocketAddr,
61    transport_protocol: TransportProtocol,
62    /// Identifies associations based on the INIT Dst AID the peer utilized
63    ///
64    /// Uses a standard `HashMap` to protect against hash collision attacks:
65    /// keys are remote-chosen initiate-tags.
66    association_ids_init: HashMap<AssociationId, AssociationHandle>,
67    /// Identifies associations based on locally created CIDs
68    ///
69    /// Uses a cheaper hash function since keys are locally created
70    association_ids: FxHashMap<AssociationId, AssociationHandle>,
71    /// Identifies associations by the peer's address and the two SCTP ports, which is what an
72    /// association is between (RFC 9260 1.3). An INIT with an Initiate Tag not seen before
73    /// finds the association it is for here.
74    ///
75    /// A standard `HashMap`: the keys are the peer's.
76    association_peers: HashMap<PeerKey, AssociationHandle>,
77
78    associations: Slab<AssociationMeta>,
79    /// Associations that have not ended: what `concurrent_associations` bounds. An ended
80    /// association may keep its entry in `associations` until its owner reports it drained.
81    live: usize,
82    local_cid_generator: Box<dyn AssociationIdGenerator>,
83    endpoint_config: Arc<EndpointConfig>,
84    server_config: Option<Arc<ServerConfig>>,
85    /// Whether incoming associations should be unconditionally rejected by a server
86    ///
87    /// Equivalent to a `ServerConfig.accept_buffer` of `0`, but can be changed after the endpoint is constructed.
88    reject_new_associations: bool,
89    /// Answers to packets that belong to no association (RFC 9260 8.4), for `poll_transmit`.
90    transmits: VecDeque<TransportMessage<Payload>>,
91    /// The keys State Cookies are authenticated with, the current one first, when the server
92    /// configuration gives a crypto provider (`ServerConfig::cookie_authentication`).
93    cookie_signers: Vec<Arc<CookieSigner>>,
94    /// The zero of the cookies' timestamps: the first time the endpoint was given.
95    cookie_epoch: Option<Instant>,
96}
97
98/// How long a State Cookie key is used before another replaces it (RFC 9260 5.1.3: "it
99/// SHOULD be changed reasonably frequently"). The key before the current one is kept, so a
100/// cookie made just before the change is still good for its lifetime.
101const COOKIE_KEY_LIFETIME: std::time::Duration = std::time::Duration::from_secs(3600);
102
103/// Answers to out-of-the-blue packets kept until the owner collects them. An answer past
104/// this many is not made: the endpoint must not be a store for whoever sends it packets.
105const 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    /// Create a new endpoint
122    ///
123    /// Returns `Err` if the configuration is invalid.
124    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    /// How many associations the endpoint holds, ended ones not yet drained included.
149    #[cfg(test)]
150    pub(crate) fn association_count(&self) -> usize {
151        self.associations.len()
152    }
153
154    /// Replace the server configuration, affecting new incoming associations only
155    pub fn set_server_config(&mut self, server_config: Option<Arc<ServerConfig>>) {
156        self.server_config = server_config;
157    }
158
159    /// Process `EndpointEvent`s emitted from related `Association`s
160    pub fn handle_event(&mut self, ch: AssociationHandle, event: EndpointEvent) {
161        match event.0 {
162            EndpointEventInner::Drained => {
163                // A handle the endpoint does not hold (reported twice, or never its own) is
164                // ignored: removing a vacant entry panics.
165                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    /// Stops routing to an association and frees its place under `concurrent_associations`.
201    /// Its entry stays, so the handle is not given to another association while the owner
202    /// may still report this one drained.
203    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        // Only the accepting side registers its peer's Initiate Tag, and another
213        // association may have registered the same tag since: remove only our own.
214        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    /// Whether the association behind `ch` has ended (RFC 9260 9.1: it is then removed from
226    /// the record). Releases it if so.
227    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    /// Releases every association that has ended. Linear in the associations held, so it runs
239    /// only when the endpoint would otherwise refuse a new one.
240    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    /// The association an INIT without a known Initiate Tag is for: the one between the same
253    /// peer address and ports. An endpoint that holds a single association and can take no
254    /// other (SCTP over one DTLS transport, RFC 8261) takes any INIT between the same ports as
255    /// its peer's: the address is the DTLS transport's affair and may have changed under it.
256    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    /// Process an incoming UDP datagram
279    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        //
295        // Handle packet on existing association, if any
296        //
297        let dst_cid = partial_decode.common_header.verification_tag;
298        let known_ch = if dst_cid > 0 {
299            // A packet whose tag is not an association's own still belongs to the association
300            // between its addresses and ports (RFC 9260 8.5): that association discards it,
301            // or takes it under one of the exceptions of 8.5.1 (an ABORT or SHUTDOWN COMPLETE
302            // that reflects the peer's tag). It is not an out-of-the-blue packet.
303            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            // INIT packets arrive with verification_tag=0 (per RFC 4960 §8.5.1).
313            // Full DoS hardening would require per-source-address rate limiting or
314            // stateless cookie exchange (RFC 4960 §5.1.3); the global
315            // server_config.concurrent_associations limit enforced during
316            // first-packet handling provides coarse-grained protection in the
317            // meantime.
318            //
319            // An INIT the peer sends again (its INIT ACK was lost, RFC 9260 5.1 C) carries the
320            // Initiate Tag of the first one, and belongs to the association that INIT started:
321            // that association answers it with the same INIT ACK. Treated as the first packet
322            // of another association instead, it is refused by an endpoint that holds one
323            // association at a time, and the handshake can never complete.
324            //
325            // An INIT with another Initiate Tag from a peer this endpoint has an association
326            // with belongs to that association too (RFC 9260 5.2.1, 5.2.2: the association
327            // answers an unexpected INIT). A peer that starts over before its COOKIE ECHO
328            // would otherwise be refused for as long as the half-open association lasts.
329            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        // An association that has ended takes no more packets (RFC 9260 9.1).
344        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        // RFC 9653 5.2, 5.3: a packet for no association has a correct CRC32c (an INIT
365        // always has), so one with a checksum of zero is dropped unless zero is its CRC32c.
366        // Section 5.3 lets an endpoint process an out-of-the-blue packet with a zero
367        // checksum, "faster SCTP association failure detection": one that announces the
368        // DTLS method (it runs under DTLS, which authenticates every packet, section 6)
369        // does, so that a peer that still sends to an association that ended here (a
370        // handshake that ran out of retransmissions while the peer, whose COOKIE ACK was
371        // lost, took the association for established) is told with an ABORT, instead of
372        // sending its DATA and HEARTBEATs into the void until its own limits run out. An
373        // INIT or a COOKIE ECHO always has its CRC32c (5.2 1.a, 2), so neither is taken.
374        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        // RFC 9260 5.1, 5.1.3: with authenticated State Cookies the accepting side keeps
392        // nothing between the INIT and the COOKIE ECHO.
393        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        //
406        // Potentially create a new association
407        //
408        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                // RFC 9260 5.1, 8.4 3): an INIT that cannot be accepted is answered with an
420                // ABORT sent to its Initiate Tag, T bit clear.
421                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    /// The signer of State Cookies, when the server configuration asks for authenticated
443    /// cookies: the current key, replaced when it has been in use for its lifetime.
444    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    /// Whether the endpoint has room for one more association.
464    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            // An association that ended has given its place back.
474            self.release_ended();
475        }
476        self.live < limit && !self.reject_new_associations && !self.is_full()
477    }
478
479    /// RFC 9260 5.1 B: an INIT is answered with an INIT ACK whose State Cookie holds all the
480    /// association will be made from, and nothing is kept. The answer is worked out by an
481    /// association that lives for this call only.
482    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            // RFC 9260 5.1, 8.4 3): an INIT that cannot be accepted is answered with an
500            // ABORT sent to its Initiate Tag.
501            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        // The INIT ACK, or the ABORT that refuses the INIT.
547        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    /// RFC 9260 5.1.5: a COOKIE ECHO for an association this endpoint does not hold. The
566    /// cookie's MAC is verified with the key it names, then its age; a good cookie makes the
567    /// association, which then takes the packet (and answers COOKIE ACK).
568    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        // 1), 2): a cookie whose key is gone, or whose MAC does not verify, is discarded
587        // silently.
588        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        // 3): the tag and the ports of the packet are those the cookie was made for.
596        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        // 4): past its lifetime the cookie is refused with an ERROR "Stale Cookie", which
604        // says by how many microseconds.
605        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        // 5): the association is made from what the cookie says.
644        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    /// RFC 9260 8.4: a packet that belongs to no association of this endpoint.
671    ///
672    /// Nothing is answered to a packet with an ABORT, a SHUTDOWN COMPLETE, a COOKIE ACK or a
673    /// "Stale Cookie" ERROR, nor to one with Verification Tag 0 (8.5.1 A: only a lone INIT
674    /// has that) or an INIT with another tag. A COOKIE ECHO is for an association made by
675    /// its INIT, which this endpoint no longer has: its cookie cannot be good. A SHUTDOWN
676    /// ACK is answered with SHUTDOWN COMPLETE and anything else with ABORT, each with the
677    /// packet's own tag and the T bit set.
678    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    /// Queues `chunk`, alone in a packet with Verification Tag `tag`, as the answer to the
718    /// packet with header `received`.
719    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    /// Returns a packet the endpoint itself has to send: the answer to a packet that belongs
755    /// to none of its associations (RFC 9260 section 8.4: an ABORT or a SHUTDOWN COMPLETE
756    /// that reflects the packet's Verification Tag, or the ABORT that refuses an INIT).
757    ///
758    /// To be polled after [`handle`](Self::handle). An owner that never polls it sends no such
759    /// answers, which costs a peer that kept an association this side has lost nothing but
760    /// time: its retransmissions run out instead of being cut short.
761    #[must_use]
762    pub fn poll_transmit(&mut self) -> Option<TransportMessage<Payload>> {
763        self.transmits.pop_front()
764    }
765
766    /// Initiate an Association
767    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        // RFC 9260 3.1: "The Source Port Number 0 MUST NOT be used" and "The Destination Port
780        // Number 0 MUST NOT be used". Every packet of the association would carry these two.
781        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            // An association that ended has given its place back.
837            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            //TODO: self.initial_close();
843            return None;
844        }
845
846        let server_config = server_config.clone();
847        let transport_config = server_config.transport.clone();
848
849        // The guard above (line ~214) already rejects packets with initiate_tag==None,
850        // but use `?`-style early return here so the safety invariant is compiler-verified.
851        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        // Where a retransmission of this INIT is routed (see `handle`).
872        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    /// Unconditionally reject future incoming associations
933    pub fn reject_new_associations(&mut self) {
934        self.reject_new_associations = true;
935    }
936
937    /// Access the configuration used by this endpoint
938    pub fn endpoint_config(&self) -> &EndpointConfig {
939        &self.endpoint_config
940    }
941
942    /// Whether we've used up 3/4 of the available AID space
943    fn is_full(&self) -> bool {
944        (((u32::MAX >> 1) + (u32::MAX >> 2)) as usize) < self.association_ids.len()
945    }
946
947    /// How many associations the endpoint routes to: the ones that have not ended.
948    #[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    /// Number of local association IDs.
958    cids_issued: u64,
959    loc_cids: HashMap<u64, AssociationId>,
960    /// Remote address the association began with
961    ///
962    /// Only needed to support associations with zero-length AIDs, which cannot migrate, so we don't
963    /// bother keeping it up to date.
964    initial_remote: SocketAddr,
965    /// The peer's address, its SCTP port and this side's.
966    peer: PeerKey,
967    /// Set by the association when it ends.
968    ended: Arc<AtomicBool>,
969    /// No longer routed to nor counted; the entry only keeps the handle from being reused.
970    released: bool,
971}
972
973/// The peer's address, the peer's SCTP port, this side's SCTP port.
974type PeerKey = (SocketAddr, u16, u16);
975
976/// Internal identifier for an `Association` currently associated with an endpoint
977#[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/// Event resulting from processing a single datagram
1000#[allow(clippy::large_enum_variant)] // Not passed around extensively
1001#[non_exhaustive]
1002pub enum DatagramEvent {
1003    /// The datagram is redirected to its `Association`
1004    AssociationEvent(AssociationEvent),
1005    /// The datagram has resulted in starting a new `Association`
1006    NewAssociation(Association),
1007}
1008
1009/// Errors in the parameters being used to create a new association
1010///
1011/// These arise before any I/O has been performed.
1012#[derive(Debug, Error, Clone, PartialEq, Eq)]
1013#[non_exhaustive]
1014pub enum ConnectError {
1015    /// The endpoint can no longer create new associations
1016    ///
1017    /// Indicates that a necessary component of the endpoint has been dropped or otherwise disabled.
1018    #[error("endpoint stopping")]
1019    EndpointStopping,
1020    /// The number of active associations on the local endpoint is at the limit
1021    ///
1022    /// Try using longer association IDs.
1023    #[error("too many associations")]
1024    TooManyAssociations,
1025    /// The domain name supplied was malformed
1026    #[error("invalid DNS name: {0}")]
1027    InvalidDnsName(String),
1028    /// The remote [`SocketAddr`] supplied was malformed
1029    ///
1030    /// Examples include attempting to connect to port 0, or using an inappropriate address family.
1031    #[error("invalid remote address: {0}")]
1032    InvalidRemoteAddress(SocketAddr),
1033    /// No default client configuration was set up
1034    ///
1035    /// Use `Endpoint::connect_with` to specify a client configuration.
1036    #[error("no default client config")]
1037    NoDefaultClientConfig,
1038    /// The transport configuration names port 0 as this endpoint's SCTP port
1039    /// ([`with_sctp_port`](crate::TransportConfig::with_sctp_port)) or the peer's
1040    /// ([`with_remote_sctp_port`](crate::TransportConfig::with_remote_sctp_port)): RFC 9260
1041    /// section 3.1, port 0 MUST NOT be used as a source or destination port.
1042    #[error("SCTP port 0 must not be used (RFC 9260 section 3.1)")]
1043    ZeroSctpPort,
1044}