Skip to main content

rtci_sctp/association/
mod.rs

1use crate::association::{
2    state::{AckMode, AckState, AssociationState},
3    stats::AssociationStats,
4};
5use crate::chunk::chunk_header::CHUNK_HEADER_SIZE;
6use crate::chunk::{
7    COOKIE_RECEIVED_WHILE_SHUTTING_DOWN, Chunk, ErrorCause, INVALID_MANDATORY_PARAMETER,
8    INVALID_STREAM_IDENTIFIER, MISSING_MANDATORY_PARAMETER, NO_USER_DATA, PROTOCOL_VIOLATION,
9    STALE_COOKIE_ERROR, UNRECOGNIZED_CHUNK_TYPE, UNRECOGNIZED_PARAMETERS, UNRESOLVABLE_ADDRESS,
10    USER_INITIATED_ABORT,
11    chunk_abort::ChunkAbort,
12    chunk_cookie_ack::ChunkCookieAck,
13    chunk_cookie_echo::ChunkCookieEcho,
14    chunk_error::ChunkError,
15    chunk_forward_tsn::ChunkForwardTsn,
16    chunk_forward_tsn::ChunkForwardTsnStream,
17    chunk_heartbeat::ChunkHeartbeat,
18    chunk_heartbeat_ack::ChunkHeartbeatAck,
19    chunk_i_forward_tsn::ChunkIForwardTsn,
20    chunk_init::ChunkInit,
21    chunk_init::ChunkInitAck,
22    chunk_padding::ChunkPadding,
23    chunk_payload_data::ChunkPayloadData,
24    chunk_payload_data::{MessageId, MessageReliability, PayloadProtocolIdentifier},
25    chunk_reconfig::ChunkReconfig,
26    chunk_selective_ack::{ChunkSelectiveAck, SELECTIVE_ACK_HEADER_SIZE},
27    chunk_shutdown::ChunkShutdown,
28    chunk_shutdown_ack::ChunkShutdownAck,
29    chunk_shutdown_complete::ChunkShutdownComplete,
30    chunk_type::{CT_FORWARD_TSN, CT_I_DATA, CT_I_FORWARD_TSN, CT_RECONFIG},
31    chunk_unknown::ChunkUnknown,
32};
33use crate::config::{COMMON_HEADER_SIZE, DATA_CHUNK_HEADER_SIZE, ServerConfig, TransportConfig};
34use crate::cookie::{CookieFields, CookieSigner};
35use crate::packet::{CommonHeader, Packet};
36use crate::param::{
37    Param, UNRECOGNIZED_PARAMETER,
38    param_forward_tsn_supported::ParamForwardTsnSupported,
39    param_heartbeat_info::ParamHeartbeatInfo,
40    param_outgoing_reset_request::ParamOutgoingResetRequest,
41    param_reconfig_response::{ParamReconfigResponse, ReconfigResult},
42    param_state_cookie::ParamStateCookie,
43    param_supported_extensions::ParamSupportedExtensions,
44    param_uknown::ParamUnknown,
45    param_zero_checksum_acceptable::{EDMID_SCTP_OVER_DTLS, ParamZeroChecksumAcceptable},
46};
47use crate::queue::{
48    payload_queue::{PayloadQueue, counted_wire_size},
49    pending_queue::{PendingQueue, ResetMarker},
50};
51use crate::shared::{AssociationEventInner, AssociationId, EndpointEvent, EndpointEventInner};
52use crate::util::{
53    RandomSource, constant_time_eq, get_padding_size, sna16lt, sna32gt, sna32gte, sna32lt, sna32lte,
54};
55use crate::{AssociationEvent, Payload, Side};
56use shared::error::{Error, Result};
57use shared::{TransportContext, TransportMessage, TransportProtocol};
58use stream::{Stream, StreamEvent, StreamId, StreamState};
59use timer::{ACK_INTERVAL, RtoManager, Timer, TimerTable};
60
61use crate::association::stream::RecvSendState;
62use bytes::{Bytes, BytesMut};
63use log::{debug, error, trace, warn};
64pub use reconfig::ReconfigEvent;
65use reconfig::{IncomingResetWaiting, OwnRequest};
66use rustc_hash::{FxHashMap, FxHashSet};
67use std::collections::{HashMap, VecDeque};
68use std::net::SocketAddr;
69use std::str::FromStr;
70use std::sync::Arc;
71use std::sync::atomic::{AtomicBool, Ordering};
72use std::time::{Duration, Instant};
73use thiserror::Error;
74
75pub(crate) mod bundling;
76pub(crate) mod interleaving;
77pub(crate) mod pmtud;
78use pmtud::PathMtuState;
79pub(crate) mod reconfig;
80pub(crate) mod state;
81pub(crate) mod stats;
82pub(crate) mod stream;
83pub(crate) mod timer;
84pub(crate) mod undelivered;
85use undelivered::{UndeliveredMessage, UndeliveredMode};
86
87#[cfg(test)]
88mod association_test;
89#[cfg(any(fuzzing, test, feature = "bench"))]
90pub(crate) mod recovery_bench;
91
92/// Incoming stream reset requests held at once while they wait for the peer's TSN or for the
93/// application to drain a stream. RFC 6525 has a peer keep one request in flight; a request
94/// beyond this many is answered Denied and not stored.
95pub(crate) const MAX_PENDING_RECONFIG_REQUESTS: usize = 64;
96
97/// Sequence numbers of incoming reset requests already performed, remembered so a
98/// retransmission is answered again without being performed a second time.
99pub(crate) const MAX_COMPLETED_RECONFIG_REQUESTS: usize = 64;
100
101/// Re-configuration requests of this side's own that may wait for the one in flight to be
102/// answered (RFC 6525 5.1.1 has one in flight). Past it a peer's reset is still performed and
103/// answered, but this side's own direction is not reset in turn, and the application's
104/// requests are refused.
105pub(crate) const MAX_OUTSTANDING_RECONFIGS: usize = 64;
106
107/// How long an accepting association waits for the COOKIE ECHO after an INIT before it gives
108/// itself up, in milliseconds. A peer that is still trying sends something within RTO.Max
109/// (60 s): another INIT if the INIT ACK was lost, or the COOKIE ECHO. Twice that leaves room
110/// for the last retransmission to arrive.
111pub(crate) const HALF_OPEN_LIFETIME: u64 = 120_000;
112
113/// The most TSNs kept outstanding, from the Cumulative TSN Ack Point to the next TSN to assign.
114///
115/// RFC 9260 6.1: fewer ordered messages of a stream may be outstanding than the Stream
116/// Sequence Number space holds, or the receiver cannot order them (it compares 16-bit serial
117/// numbers, which works within half the space). Every message takes at least one TSN, so
118/// bounding the TSNs bounds the messages of every stream. It also keeps the receiver's Gap Ack
119/// Blocks within their 16-bit offsets.
120pub(crate) const MAX_OUTSTANDING_TSNS: u32 = 0x7fff;
121
122/// The entries of a FORWARD TSN (RFC 3758 3.6) or I-FORWARD-TSN (RFC 8260 2.3.1) reduced to
123/// one per key (a stream, or a stream and its U flag) with the largest sequence number named
124/// for it, `later(kept, named)` being serial-number order (RFC 1982: `sna16lt` for an SSN,
125/// `sna32lt` for a MID), in the order the keys first appear. A sender lists each stream once,
126/// so a well-formed chunk comes back as it is; one that names a stream many times is applied
127/// as its largest entry, at the cost of one pass over the stream's reassembly queue instead
128/// of one per entry.
129pub(crate) fn largest_per_stream<K, S>(
130    entries: impl IntoIterator<Item = (K, S)>,
131    later: impl Fn(S, S) -> bool,
132) -> Vec<(K, S)>
133where
134    K: Copy + Eq + std::hash::Hash,
135    S: Copy,
136{
137    let mut reduced: Vec<(K, S)> = vec![];
138    let mut at: FxHashMap<K, usize> = FxHashMap::default();
139    for (key, sequence) in entries {
140        match at.get(&key) {
141            Some(&i) => {
142                if later(reduced[i].1, sequence) {
143                    reduced[i].1 = sequence;
144                }
145            }
146            None => {
147                at.insert(key, reduced.len());
148                reduced.push((key, sequence));
149            }
150        }
151    }
152    reduced
153}
154
155/// The Host Name Address parameter (RFC 9260 3.3.2.1.4), deprecated: an INIT or INIT ACK that
156/// carries one is answered with an ABORT.
157const PARAM_HOST_NAME_ADDRESS: u16 = 11;
158
159/// The State Cookie parameter, for the "Missing Mandatory Parameter" cause.
160const PARAM_STATE_COOKIE: u16 = 7;
161
162/// Path.Max.Retrans (RFC 9260 16): the consecutive failures (T3-rtx expiries, HEARTBEATs
163/// without an answer) after which the path to the peer is reported inactive.
164pub(crate) const PATH_MAX_RETRANS: usize = 5;
165
166/// T5-shutdown-guard (RFC 9260 9.2, 16): five times RTO.Max, in milliseconds.
167pub(crate) const T5_SHUTDOWN_GUARD: u64 = 5 * 60_000;
168
169/// What an accepted INIT said about its sender, kept with the State Cookie sent in answer
170/// and taken into the TCB when that cookie comes back (RFC 9260 5.1.3: "the State Cookie
171/// carries the information needed to create the association"; here the association holds
172/// it, see the note on [`Association::handle_cookie_echo`]).
173#[derive(Debug, Clone)]
174struct CookieTcb {
175    created_at: Instant,
176    peer_verification_tag: u32,
177    peer_initial_tsn: u32,
178    peer_rwnd: u32,
179    inbound_streams: u16,
180    outbound_streams: u16,
181    use_forward_tsn: bool,
182    /// User message interleaving is used: both sides listed I-DATA (RFC 8260 2.2.1).
183    use_interleaving: bool,
184    /// The INIT listed the RE-CONFIG chunk among its supported extensions (RFC 6525 5.1.1).
185    reconfig: bool,
186    /// The peer takes a zero checksum over DTLS and this side may send one (RFC 9653 5.2).
187    send_zero_checksum: bool,
188    /// This side's port and the peer's, as the INIT's packet had them.
189    source_port: u16,
190    destination_port: u16,
191}
192
193/// The optional parameters of an INIT or INIT ACK, as far as the engine reads them.
194#[derive(Default)]
195struct HandshakeParams {
196    cookie: Option<Bytes>,
197    /// Unrecognized parameters the sender asked to hear about, each as it arrived.
198    unrecognized: Vec<Bytes>,
199    /// A Host Name Address parameter, as it arrived.
200    host_name: Option<Bytes>,
201    forward_tsn: bool,
202    /// The peer reported this side's Forward-TSN-Supported parameter as unrecognized.
203    forward_tsn_rejected: bool,
204    /// The Supported Extensions parameter lists the RE-CONFIG chunk (RFC 6525 5.1.1).
205    reconfig: bool,
206    /// The Supported Extensions parameter lists the I-DATA chunk (RFC 8260 2.2.1).
207    i_data: bool,
208    /// The Supported Extensions parameter lists the I-FORWARD-TSN chunk (RFC 8260 2.3.1).
209    i_forward_tsn: bool,
210    /// The Error Detection Method Identifier of a Zero Checksum Acceptable parameter (RFC
211    /// 9653 4), the first one if the peer sent several.
212    zero_checksum_edmid: Option<u32>,
213}
214
215/// The Forward-TSN-Supported parameter (RFC 3758 3.1).
216const PARAM_FORWARD_TSN_SUPPORTED: u16 = 49152;
217
218/// Whether `raw`, the value of an Unrecognized Parameter parameter or of an "Unrecognized
219/// Parameters" error cause, names the Forward-TSN-Supported parameter.
220fn names_forward_tsn_supported(mut raw: &[u8]) -> bool {
221    while raw.len() >= 4 {
222        if u16::from_be_bytes([raw[0], raw[1]]) == PARAM_FORWARD_TSN_SUPPORTED {
223            return true;
224        }
225        let length = usize::from(u16::from_be_bytes([raw[2], raw[3]])).max(4);
226        let padded = length.next_multiple_of(4);
227        if padded > raw.len() {
228            break;
229        }
230        raw = &raw[padded..];
231    }
232    false
233}
234
235/// Error causes reported for one received packet, at most.
236const MAX_ERROR_CAUSES_PER_PACKET: usize = 16;
237
238/// Parameter types the engine has no parser for but RFC 9260 defines for INIT / INIT ACK:
239/// IPv4 Address, IPv6 Address, Unrecognized Parameter, Cookie Preservative, Supported Address
240/// Types. Accepted and ignored: an association over DTLS has one path (RFC 8261), and a
241/// longer cookie lifetime is the receiver's to grant or not (RFC 9260 5.2.6).
242const IGNORED_HANDSHAKE_PARAMS: [u16; 5] = [5, 6, 8, 9, 12];
243
244/// Reasons why an association might be lost
245#[derive(Debug, Error, Clone, PartialEq)]
246#[non_exhaustive]
247pub enum AssociationError {
248    /// Handshake failed
249    #[error("handshake failed due to {0}")]
250    HandshakeFailed(String),
251    /// The peer violated the QUIC specification as understood by this implementation
252    #[error("transport error")]
253    TransportError,
254    /// The peer's QUIC stack aborted the association automatically
255    #[error("aborted by peer")]
256    AssociationClosed,
257    /// The peer closed the association
258    #[error("closed by peer")]
259    ApplicationClosed,
260    /// The peer is unable to continue processing this association, usually due to having restarted
261    #[error("reset by peer")]
262    Reset,
263    /// Communication with the peer has lapsed for longer than the negotiated idle timeout
264    ///
265    /// If neither side is sending keep-alives, an association will time out after a long enough idle
266    /// period even if the peer is still reachable
267    #[error("timed out")]
268    TimedOut,
269    /// The local application closed the association
270    #[error("closed")]
271    LocallyClosed,
272}
273
274/// Events of interest to the application
275#[derive(Debug)]
276#[non_exhaustive]
277pub enum Event {
278    /// Handshake was failed
279    HandshakeFailed {
280        /// Reason that the association was closed
281        reason: AssociationError,
282    },
283
284    /// The association was successfully established
285    Connected,
286    /// The peer restarted the association (RFC 9260 5.2.4 action A): it sent an INIT and
287    /// then a COOKIE ECHO with the Tie-Tags of this association, as an endpoint that lost
288    /// its state does. The association is a new one from here on, with new tags and TSNs,
289    /// no streams and congestion control from its initial values; what was queued or in
290    /// flight on the old one is gone. Reported instead of [`Event::AssociationLost`] (5.2.4:
291    /// "a RESTART notification").
292    Restarted,
293    /// The association was lost
294    ///
295    /// Emitted if the peer closes the association or an error is encountered.
296    AssociationLost {
297        /// Reason that the association was closed
298        reason: AssociationError,
299        /// The stream the loss was reported against.
300        id: StreamId,
301    },
302    /// The association closed, after an `AssociationLost` for each of its streams. Emitted
303    /// whether or not it had streams, so an application that keeps state beside the
304    /// association (a pre-negotiated data channel that never carried data) learns of it.
305    AssociationClosed {
306        /// Reason that the association was closed
307        reason: AssociationError,
308    },
309    /// The path to the peer is inactive: Path.Max.Retrans consecutive retransmissions or
310    /// HEARTBEATs went unanswered (RFC 9260 sections 8.2, 8.3). The association goes on
311    /// trying, up to [`TimerConfig::max_t3_rtx_retrans`](crate::TimerConfig).
312    PathInactive,
313    /// The path to the peer answers again after [`Event::PathInactive`].
314    PathActive,
315    /// The peer sent an ERROR chunk (RFC 9260 11.2.5 COMMUNICATION ERROR): each cause's code
316    /// and its cause-specific information as received (RFC 9260 3.3.10).
317    CommunicationError {
318        /// The causes, in the order the chunk carried them.
319        causes: Vec<(crate::ErrorCauseCode, Bytes)>,
320    },
321    /// The association ended with user messages it did not deliver (RFC 9260 11.2.2 SEND
322    /// FAILURE, 8.1): read them with
323    /// [`Association::take_undelivered_messages`]. Reported before
324    /// [`Event::AssociationClosed`]. A message of a partially reliable stream given up while
325    /// the association ran is reported with
326    /// [`StreamEvent::MessageAbandoned`](crate::StreamEvent::MessageAbandoned) instead.
327    SendFailure {
328        /// Messages no part of which was sent.
329        unsent: usize,
330        /// Messages sent, at least in part, and not completely acknowledged.
331        unacknowledged: usize,
332    },
333    /// Stream events
334    Stream(StreamEvent),
335    /// One or more application datagrams have been received
336    DatagramReceived,
337    /// The outcome of a stream re-configuration (RFC 6525): a request of this side's own was
338    /// answered, or the peer changed the association.
339    Reconfig(ReconfigEvent),
340}
341
342/// What [`Association::status`] reports (RFC 9260 11.1.8).
343#[derive(Debug, Clone, PartialEq, Eq)]
344#[non_exhaustive]
345pub struct AssociationStatus {
346    /// The association ended.
347    pub closed: bool,
348    /// The peer's receive window ("current receiver window size"), in bytes.
349    pub peer_receive_window: u32,
350    /// The congestion window, in bytes.
351    pub congestion_window: u32,
352    /// The slow start threshold, in bytes.
353    pub slow_start_threshold: u32,
354    /// DATA chunks sent and not cumulatively acknowledged ("number of unacknowledged DATA
355    /// chunks").
356    pub unacknowledged_data_chunks: usize,
357    /// DATA chunks waiting to be sent for the first time.
358    pub pending_data_chunks: usize,
359    /// The smoothed round-trip time; zero before the first measurement.
360    pub srtt: Duration,
361    /// The retransmission timeout.
362    pub rto: Duration,
363    /// The path MTU the association packs to.
364    pub path_mtu: u32,
365}
366
367/// How many T3-rtx retransmitted TSNs are remembered for SACK loss detection (RFC 9260 6.2).
368const MAX_T3_RETRANSMITTED_KEPT: usize = 512;
369
370/// Selection is stable even after fragments leave either queue.
371#[derive(Debug, Copy, Clone)]
372struct MessageToAbandon {
373    id: MessageId,
374    // TSN of an inflight candidate; None when selected from pending.
375    // This permits a direct lookup for whole messages. Fragmented messages
376    // and pending selections use the index keyed by `id`.
377    sent_tsn: Option<u32>,
378}
379
380/// The most a bound on the send rate ([`Association::set_max_send_rate`]) lets out at once:
381/// what the rate gives in this long (two PMDCS at least).
382pub const SEND_RATE_BURST: Duration = Duration::from_millis(20);
383
384/// [`Association::set_max_send_rate`]: a token bucket in bytes on the wire.
385#[derive(Debug, Clone, Copy)]
386struct SendRateLimit {
387    bits_per_second: f64,
388    tokens: f64,
389    updated: Option<Instant>,
390}
391
392impl SendRateLimit {
393    /// Fills the bucket for the time since it was last filled, up to the burst.
394    fn fill(&mut self, now: Instant, pmdcs: u32) {
395        let burst = (self.bits_per_second / 8.0 * SEND_RATE_BURST.as_secs_f64())
396            .max(2.0 * f64::from(pmdcs));
397        if let Some(updated) = self.updated {
398            let elapsed = now.saturating_duration_since(updated).as_secs_f64();
399            self.tokens += elapsed * self.bits_per_second / 8.0;
400        }
401        self.tokens = self.tokens.min(burst);
402        self.updated = Some(now);
403    }
404}
405
406///Association represents an SCTP association
407//13.2.  Parameters Necessary per Association (i.e., the TCB)
408//Peer : Tag value to be sent in every packet and is received
409//Verification: in the INIT or INIT ACK chunk.
410//Tag :
411//
412//My : Tag expected in every inbound packet and sent in the
413//Verification: INIT or INIT ACK chunk.
414//
415//Tag :
416//State : A state variable indicating what state the association
417// : is in, i.e., COOKIE-WAIT, COOKIE-ECHOED, ESTABLISHED,
418// : SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED,
419// : SHUTDOWN-ACK-SENT.
420//
421// No Closed state is illustrated since if a
422// association is Closed its TCB SHOULD be removed.
423pub struct Association {
424    side: Side,
425    state: AssociationState,
426    handshake_completed: bool,
427    /// This side entered ESTABLISHED on the peer's COOKIE ECHO and nothing from the peer has
428    /// shown since that its COOKIE ACK arrived: the peer may still be in COOKIE-ECHOED,
429    /// discarding DATA (RFC 9260 5.1).
430    peer_awaits_cookie_ack: bool,
431    max_message_size: u32,
432    /// The largest message accepted from the peer: what this side advertised (RFC 8841 6.1).
433    max_receive_message_size: u32,
434    /// See [`TransportConfig::with_zero_window_overcommit`].
435    zero_window_overcommit: bool,
436    /// See [`TransportConfig::with_zero_window_renege`].
437    zero_window_renege: bool,
438    /// See [`TransportConfig::with_handshake_timers_back_off_rto`].
439    handshake_timers_back_off_rto: bool,
440    /// The partial delivery point (RFC 6458 8.1.21): see
441    /// [`TransportConfig::with_partial_delivery_point`].
442    partial_delivery_point: u32,
443    will_send_shutdown: bool,
444    bytes_received: usize,
445    bytes_sent: usize,
446
447    pub(crate) peer_verification_tag: u32,
448    my_verification_tag: u32,
449    pub(crate) my_next_tsn: u32,
450    peer_last_tsn: u32,
451    // for RTT measurement
452    min_tsn2measure_rtt: u32,
453    will_send_forward_tsn: bool,
454    /// When a FORWARD TSN held back in the hope of DATA to bundle it with goes alone
455    /// (`TransportConfig::with_forward_tsn_delay`, RFC 3758 3.5 F2, F3).
456    forward_tsn_due_at: Option<Instant>,
457    will_retransmit_fast: bool,
458    will_retransmit_reconfig: bool,
459    /// The peer answered a request "In progress": the reconfiguration timer starts over,
460    /// and the wait is not counted against the request (RFC 6525 5.2.7).
461    restart_reconfig_timer: bool,
462    /// True only while the in-flight queue may still hold chunks flagged for
463    /// T3-rtx retransmission (set when the timer marks them, cleared once the
464    /// scan has re-sent them all). Lets `gather_outbound` skip the O(in-flight)
465    /// retransmit scan entirely in the steady state, where nothing is ever
466    /// marked — that scan was the single hottest function in the send profile.
467    t3_retransmit_pending: bool,
468
469    will_send_shutdown_ack: bool,
470    will_send_shutdown_complete: bool,
471
472    // Reconfig
473    pub(crate) my_next_rsn: u32,
474    /// The request in flight, by its sequence number, as the chunk that is retransmitted.
475    /// RFC 6525 5.1.1: there is at most one.
476    reconfigs: HashMap<u32, ChunkReconfig>,
477    /// What the request in flight asks for.
478    reconfig_in_flight: Option<OwnRequest>,
479    /// The peer answered the request in flight "In progress": the next expiry of its timer
480    /// is not counted as an error (RFC 6525 5.2.7 H2).
481    reconfig_in_progress: bool,
482    /// Requests waiting for the one in flight to be answered.
483    reconfig_queue: VecDeque<OwnRequest>,
484    /// The peer's Outgoing SSN Reset Requests not performed yet: its TSN is not reached, or
485    /// the application has not read what the streams hold.
486    reconfig_requests: HashMap<u32, ParamOutgoingResetRequest>,
487    /// The peer's requests answered for good, each with the chunk it was answered with: a
488    /// retransmission gets the same chunk again (RFC 6525 5.2.1).
489    completed_reconfig_requests: VecDeque<(u32, ChunkReconfig)>,
490    /// The request sequence numbers accepted from the peer: the lowest still acceptable and
491    /// the next one expected. `None` until the peer's initial TSN is known.
492    peer_rsn_window: Option<(u32, u32)>,
493    /// The peer listed the RE-CONFIG chunk in its Supported Extensions (RFC 6525 5.1.1).
494    peer_supports_reconfig: bool,
495    /// The peer's Incoming SSN Reset Requests being answered: the Outgoing SSN Reset Request
496    /// that answers one goes out when the data queued on its streams has been sent.
497    incoming_resets_waiting: HashMap<u32, IncomingResetWaiting>,
498    /// DATA held back while a reset of its stream is deferred, or while this side's SSN/TSN
499    /// reset is in flight: it belongs to the stream as it is after the reset (RFC 6525 5.2.2
500    /// E2). Its bytes count against the receive window.
501    held_reset_data: Vec<ChunkPayloadData>,
502    /// DATA fragments dropped because they could never be part of a complete message
503    /// (`ReassemblyQueue::discard_orphans`).
504    pub(crate) orphans_dropped: usize,
505    /// The TSN of the last of them, so a run of them is reported once.
506    last_orphan_tsn: Option<u32>,
507    /// This side asked for an SSN/TSN reset that is not answered yet: no new DATA is sent
508    /// (RFC 6525 5.1.4 C2).
509    tsn_reset_requested: bool,
510    /// The peer's SSN/TSN Reset Request, answered "In progress" until what this side has
511    /// outstanding is acknowledged.
512    deferred_tsn_reset: Option<u32>,
513    /// When this side last sent an SSN/TSN Reset Request (RFC 6525 5.1.4: one per 30 s).
514    last_tsn_reset_request: Option<Instant>,
515    /// Messages written to streams whose outgoing reset is not answered yet, across all
516    /// streams: they are still to be sent.
517    held_write_count: usize,
518
519    // Non-RFC internal data
520    remote_addr: SocketAddr,
521    local_addr: SocketAddr,
522    transport_protocol: TransportProtocol,
523
524    pub(crate) source_port: u16,
525    pub(crate) destination_port: u16,
526    my_max_num_inbound_streams: u16,
527    my_max_num_outbound_streams: u16,
528    /// The stream counts this side is configured to offer, before a peer's INIT or INIT ACK
529    /// narrowed them.
530    configured_inbound_streams: u16,
531    configured_outbound_streams: u16,
532    my_cookie: Option<ParamStateCookie>,
533    /// What the INIT answered with `my_cookie` said, applied when the cookie is echoed.
534    cookie_tcb: Option<CookieTcb>,
535    /// Makes this association's State Cookies with a MAC (RFC 9260 5.1.3), when the endpoint
536    /// was given a crypto provider for it. Without one a cookie is random bytes, good only
537    /// because this association remembers them.
538    cookie_signer: Option<Arc<CookieSigner>>,
539    /// The Tie-Tags (RFC 9260 5.2.1, 5.2.2): random, drawn the first time an INIT is
540    /// answered while the association exists, and kept for its life; 0 until then.
541    local_tie_tag: u32,
542    peer_tie_tag: u32,
543    /// Without a cookie signer: the State Cookie of the INIT ACK that answered an
544    /// unexpected INIT, what it stands for, and when it was made. Its COOKIE ECHO restarts
545    /// the association (5.2.4 action A).
546    restart_cookie: Option<(Bytes, CookieFields, Instant)>,
547    /// The configuration the association was made with, for a restart.
548    transport_config: Option<Arc<TransportConfig>>,
549    /// Where the random values come from: the initial TSN, an unauthenticated State Cookie,
550    /// the Initiate Tag of an INIT ACK for an existing association, HEARTBEAT nonces and
551    /// jitter (`EndpointConfig::random_source`).
552    random: RandomSource,
553    /// Valid.Cookie.Life (RFC 9260 16): how long a State Cookie is accepted after it was made.
554    valid_cookie_life: Duration,
555    /// How many times a Stale Cookie error sent this side back to a new INIT.
556    stale_cookie_restarts: usize,
557    /// The TSNs most recently sent again on a retransmission timeout (at most
558    /// `MAX_T3_RETRANSMITTED_KEPT`): one the peer then reports as a duplicate shows a lost
559    /// SACK (RFC 9260 6.2).
560    t3_retransmitted: VecDeque<u32>,
561    /// When the last COOKIE ECHO was sent: the start of the COOKIE ECHO / ERROR exchange a
562    /// Cookie Preservative is sized from (RFC 9260 5.2.6).
563    cookie_echo_sent_at: Option<Instant>,
564    /// The TSN and wire size of DATA chunks acknowledged lately, for the bytes of the
565    /// duplicates a SACK reports (RFC 9260 7.2.2). Each counts once.
566    recently_acknowledged: VecDeque<(u32, u32)>,
567    /// The first DATA chunk of an association is acknowledged at once (RFC 9260 5.1).
568    first_data_received: bool,
569    /// Set while a packet is processed whose DATA must be acknowledged at once: it came with
570    /// the COOKIE ECHO (RFC 9260 5.1.5), or in SHUTDOWN-SENT (9.2).
571    sack_packet_immediately: bool,
572    /// Set by a chunk handler: the chunks after it in the packet are discarded.
573    discard_rest_of_packet: bool,
574    /// The SACK that is due and found no control packet to travel with: it goes with
575    /// outbound DATA, or alone.
576    unbundled_sack: Option<ChunkSelectiveAck>,
577    /// Where the packets of DATA begin among the packets being gathered.
578    first_data_packet: usize,
579
580    /// HB.interval (RFC 9260 8.3, 16); `None` sends no HEARTBEAT.
581    heartbeat_interval: Option<Duration>,
582    /// The HEARTBEAT sent and not yet acknowledged: its nonce and when it left.
583    heartbeat_outstanding: Option<(u64, Instant)>,
584    /// When a chunk that can measure the round trip last left: a DATA chunk sent for the
585    /// first time, or a HEARTBEAT. The path is idle from then on.
586    last_rtt_probe: Option<Instant>,
587    /// Consecutive failures on the path to the peer, for `Event::PathInactive`.
588    path_error_count: usize,
589    path_inactive: bool,
590    /// When the association was made: the zero of the time a HEARTBEAT carries.
591    created_at: Option<Instant>,
592    /// Path MTU discovery (RFC 8899), when configured.
593    pmtud: Option<pmtud::PathMtuDiscovery>,
594
595    pub(crate) payload_queue: PayloadQueue,
596    pub(crate) inflight_queue: PayloadQueue,
597    pub(crate) pending_queue: PendingQueue,
598    control_queue: VecDeque<Packet>,
599    stream_queue: VecDeque<u16>,
600
601    pub(crate) mtu: u32,
602    // max DATA chunk payload size
603    max_payload_size: u32,
604    cumulative_tsn_ack_point: u32,
605    pub(crate) advanced_peer_tsn_ack_point: u32,
606    use_forward_tsn: bool,
607    /// PR-SCTP is announced and used at all (`TransportConfig::with_partial_reliability`).
608    partial_reliability_enabled: bool,
609    /// User message interleaving is announced (`TransportConfig::with_message_interleaving`).
610    interleaving_enabled: bool,
611    /// "Zero Checksum Acceptable" is announced, for SCTP over DTLS, and packets with a zero
612    /// checksum are taken (`TransportConfig::with_zero_checksum`; RFC 9653 5.1, 5.3).
613    zero_checksum_enabled: bool,
614    /// The peer announced that it takes a zero checksum over DTLS, and this side may send
615    /// one: the CRC32c of what is sent is not computed (RFC 9653 5.2).
616    send_zero_checksum: bool,
617    /// User message interleaving is in use: both sides announced it (RFC 8260 2.2.1). DATA
618    /// and FORWARD TSN are then replaced by I-DATA and I-FORWARD-TSN.
619    use_interleaving: bool,
620    /// As `fwd_tsn_stream_map`, for I-FORWARD-TSN: the greatest Message Identifier among the
621    /// abandoned chunks of each stream, for its ordered (`false`) and its unordered (`true`)
622    /// messages (RFC 8260 2.3.1).
623    i_fwd_tsn_stream_map: FxHashMap<(u16, bool), u32>,
624    /// Max stream-sequence-number per *ordered* stream among abandoned chunks
625    /// currently in the forward-TSN window `(cumulative_tsn_ack_point,
626    /// advanced_peer_tsn_ack_point]`. Maintained incrementally as chunks are
627    /// abandoned (the two RFC 3758 C2 loops) so that `create_forward_tsn` is
628    /// O(streams) instead of rescanning the whole in-flight window — which, for
629    /// PR-SCTP data channels, ran ~1000 hashmap probes per FORWARD-TSN and was
630    /// ~9% of send CPU in profiles. Unordered chunks are omitted: the receiver
631    /// ignores the per-stream list for them (it advances by `new_cumulative_tsn`
632    /// alone), so reporting them was pure waste.
633    fwd_tsn_stream_map: FxHashMap<u16, u16>,
634    /// What a FORWARD TSN or I-FORWARD-TSN skipped on a stream this side holds no state for
635    /// yet: the last Stream Sequence Number (or Message Identifier, keyed by its ordered or
636    /// unordered kind) the peer will not complete (RFC 3758 3.6, RFC 8260 2.3.1). The stream
637    /// starts after it when it is created. Only streams within the negotiated inbound count
638    /// are kept, so a peer can make this hold at most two entries per stream it may use.
639    skipped_on_absent_streams: FxHashMap<(u16, bool), u32>,
640
641    pub(crate) rto_mgr: RtoManager,
642    timers: TimerTable,
643
644    // Congestion control parameters
645    max_receive_buffer_size: u32,
646    // my congestion window size
647    pub(crate) cwnd: u32,
648    // calculated peer's receiver windows size
649    rwnd: u32,
650    // slow start threshold
651    pub(crate) ssthresh: u32,
652    partial_bytes_acked: u32,
653    pub(crate) in_fast_recovery: bool,
654    fast_recover_exit_point: u32,
655    /// The Path Maximum DATA Chunk Size (RFC 9260 2.2): the largest DATA chunk, header
656    /// included, that fits a packet. The unit of the congestion window rules.
657    pub(crate) pmdcs: u32,
658    /// L of RFC 9260 7.2.1: in slow start one SACK grows cwnd by at most L x PMDCS.
659    slow_start_growth_limit: u32,
660    /// Max.Burst (RFC 9260 6.1 D), when applied.
661    pub(crate) max_burst: Option<u32>,
662    /// A bound from outside the association on the rate new DATA is sent at
663    /// ([`Association::set_max_send_rate`]), when set.
664    send_rate: Option<SendRateLimit>,
665    /// When DATA was last sent, for the decay of an idle congestion window (7.2.1).
666    last_data_sent: Option<Instant>,
667    /// Set by a T3-rtx expiry: the retransmission that follows is one packet (6.3.3 E3).
668    t3_single_packet: bool,
669    /// The TSNs marked for Fast Retransmit (their third miss indication) since the last
670    /// Fast Retransmit packet. What of them does not fit that packet waits for cwnd.
671    fast_retransmit_marked: Vec<u32>,
672    /// RFC 9260 6.1 A: when the peer's SACK closed its window (a_rwnd 0), the first zero
673    /// window probe waits one RTO from then.
674    zero_window_probe_at: Option<Instant>,
675    /// The TSN of the zero window probe outstanding (RFC 9260 6.1 A): new DATA sent with
676    /// nothing in flight although rwnd did not have room for it. A SACK that acknowledges it
677    /// shows the receiver taking DATA through its closed window (the chunk that completes a
678    /// message its full buffer holds the start of), which is progress: the next probe goes
679    /// at once instead of one RTO later.
680    zero_window_probe_tsn: Option<u32>,
681    /// The TSNs the last SACK showed the peer reneged on: they got their one miss indication
682    /// there (RFC 9260 6.2.1 D iii), not another from the same SACK's Fast Retransmit count.
683    reneged_in_last_sack: Vec<u32>,
684    /// A SHUTDOWN's Cumulative TSN Ack is being taken as a SACK without Gap Ack Blocks.
685    acknowledging_by_shutdown: bool,
686    /// The a_rwnd of the last SACK sent (of the INIT or INIT ACK before any).
687    last_advertised_window: u32,
688    /// User data taken since the last SACK: the sender counts it against
689    /// `last_advertised_window` until a SACK says otherwise.
690    received_since_sack: u32,
691    /// SACK.Delay (RFC 9260 6.2, 16), in milliseconds.
692    sack_delay: u64,
693
694    // Chunks stored for retransmission
695    stored_init: Option<ChunkInit>,
696    stored_cookie_echo: Option<ChunkCookieEcho>,
697    next_stream_generation: u64,
698    next_message_id: u64,
699    /// Per-chunk lookups on the receive path; SIDs are bounded by the
700    /// negotiated stream count, so the faster non-SipHash hasher is safe.
701    pub(crate) streams: FxHashMap<StreamId, StreamState>,
702    /// The `bytes_dequeued` of each stream at the moment it was unregistered, until a stream
703    /// with the same identifier is created again (see [`Association::stream_bytes_dequeued`]).
704    closed_stream_bytes_dequeued: FxHashMap<StreamId, u64>,
705    /// The streams the association held when the peer restarted it (RFC 9260 5.2.4 action
706    /// A), with the application bytes each had sent: see [`Self::streams_lost_in_restart`].
707    streams_lost_in_restart: Vec<(StreamId, u64)>,
708    /// Bytes held in every stream's reassembly queue, kept as a running total so the receive
709    /// window is not recomputed by walking every stream on each DATA chunk.
710    reassembly_bytes: usize,
711    /// Streams whose reassembly queue holds a readable message.
712    readable_streams: FxHashSet<StreamId>,
713    /// Streams with no readable message whose reassembly queue has part of a message to give
714    /// [`Stream::read_part`] (RFC 9260 6.9), each announced once with `StreamEvent::Readable`.
715    part_readable_streams: FxHashSet<StreamId>,
716    /// Streams whose reassembly queue holds anything at all; the only ones a FORWARD TSN can
717    /// change.
718    streams_with_data: FxHashSet<StreamId>,
719
720    events: VecDeque<Event>,
721    endpoint_events: VecDeque<EndpointEventInner>,
722    error: Option<AssociationError>,
723    /// Set by [`close`](Self::close): the association is over, whatever state it was in.
724    ended: bool,
725    /// The cause code (RFC 9260 section 3.3.10) the association was aborted with: the first
726    /// cause of the ABORT it received or sent.
727    abort_cause_code: Option<u16>,
728    /// The Upper Layer Abort Reason of the peer's User-Initiated Abort (RFC 9260 9.1).
729    peer_abort_reason: Option<Bytes>,
730    /// `ended`, as the endpoint that routes to this association sees it: an ended association
731    /// takes no more packets and no longer counts against the endpoint's limit.
732    ended_flag: Arc<AtomicBool>,
733    /// `Drained` is reported to the endpoint once.
734    drained_emitted: bool,
735    /// Error causes to report for the packet being processed, sent as one ERROR chunk when
736    /// its last chunk has been handled.
737    pending_error_causes: Vec<ErrorCause>,
738    /// What the association did not deliver, once it ended (RFC 9260 8.1, 11.1.14, 11.1.15).
739    undelivered: Vec<UndeliveredMessage>,
740    /// Messages held for a stream reset when the association ended.
741    undelivered_held: Vec<Vec<ChunkPayloadData>>,
742
743    // per inbound packet context
744    delayed_ack_triggered: bool,
745    immediate_ack_triggered: bool,
746
747    pub(crate) stats: AssociationStats,
748    ack_state: AckState,
749
750    // for testing
751    pub(crate) ack_mode: AckMode,
752}
753
754impl Default for Association {
755    fn default() -> Self {
756        Association {
757            side: Side::default(),
758            state: AssociationState::default(),
759            handshake_completed: false,
760            peer_awaits_cookie_ack: false,
761            max_message_size: 0,
762            max_receive_message_size: 0,
763            zero_window_overcommit: false,
764            zero_window_renege: false,
765            handshake_timers_back_off_rto: true,
766            partial_delivery_point: 1,
767            will_send_shutdown: false,
768            bytes_received: 0,
769            bytes_sent: 0,
770
771            peer_verification_tag: 0,
772            my_verification_tag: 0,
773            my_next_tsn: 0,
774            peer_last_tsn: 0,
775            // for RTT measurement
776            min_tsn2measure_rtt: 0,
777            will_send_forward_tsn: false,
778            forward_tsn_due_at: None,
779            will_retransmit_fast: false,
780            will_retransmit_reconfig: false,
781            restart_reconfig_timer: false,
782            t3_retransmit_pending: false,
783
784            will_send_shutdown_ack: false,
785            will_send_shutdown_complete: false,
786
787            // Reconfig
788            my_next_rsn: 0,
789            reconfigs: HashMap::default(),
790            reconfig_in_flight: None,
791            reconfig_in_progress: false,
792            reconfig_queue: VecDeque::new(),
793            reconfig_requests: HashMap::default(),
794            completed_reconfig_requests: VecDeque::new(),
795            peer_rsn_window: None,
796            peer_supports_reconfig: true,
797            incoming_resets_waiting: HashMap::default(),
798            held_reset_data: vec![],
799            orphans_dropped: 0,
800            last_orphan_tsn: None,
801            tsn_reset_requested: false,
802            deferred_tsn_reset: None,
803            last_tsn_reset_request: None,
804            held_write_count: 0,
805
806            // Non-RFC internal data
807            remote_addr: SocketAddr::from_str("0.0.0.0:0").unwrap(),
808            local_addr: SocketAddr::from_str("0.0.0.0:0").unwrap(),
809            transport_protocol: TransportProtocol::UDP,
810
811            source_port: 0,
812            destination_port: 0,
813            my_max_num_inbound_streams: 0,
814            my_max_num_outbound_streams: 0,
815            configured_inbound_streams: 0,
816            configured_outbound_streams: 0,
817            my_cookie: None,
818            cookie_tcb: None,
819            cookie_signer: None,
820            local_tie_tag: 0,
821            peer_tie_tag: 0,
822            restart_cookie: None,
823            transport_config: None,
824            random: RandomSource::default(),
825            valid_cookie_life: Duration::from_secs(60),
826            stale_cookie_restarts: 0,
827            t3_retransmitted: VecDeque::new(),
828            cookie_echo_sent_at: None,
829            recently_acknowledged: VecDeque::new(),
830            first_data_received: false,
831            sack_packet_immediately: false,
832            discard_rest_of_packet: false,
833            unbundled_sack: None,
834            first_data_packet: 0,
835            heartbeat_interval: None,
836            heartbeat_outstanding: None,
837            last_rtt_probe: None,
838            path_error_count: 0,
839            path_inactive: false,
840            created_at: None,
841            pmtud: None,
842
843            payload_queue: PayloadQueue::default(),
844            inflight_queue: PayloadQueue::default(),
845            pending_queue: PendingQueue::default(),
846            control_queue: VecDeque::default(),
847            stream_queue: VecDeque::default(),
848
849            mtu: 0,
850            // max DATA chunk payload size
851            max_payload_size: 0,
852            cumulative_tsn_ack_point: 0,
853            advanced_peer_tsn_ack_point: 0,
854            use_forward_tsn: false,
855            partial_reliability_enabled: true,
856            interleaving_enabled: false,
857            zero_checksum_enabled: false,
858            send_zero_checksum: false,
859            use_interleaving: false,
860            i_fwd_tsn_stream_map: FxHashMap::default(),
861            fwd_tsn_stream_map: FxHashMap::default(),
862            skipped_on_absent_streams: FxHashMap::default(),
863
864            rto_mgr: RtoManager::default(),
865            timers: TimerTable::default().with_t1_following_rto(true),
866
867            // Congestion control parameters
868            max_receive_buffer_size: 0,
869            // my congestion window size
870            cwnd: 0,
871            send_rate: None,
872            // calculated peer's receiver windows size
873            rwnd: 0,
874            // slow start threshold
875            ssthresh: 0,
876            partial_bytes_acked: 0,
877            in_fast_recovery: false,
878            fast_recover_exit_point: 0,
879            pmdcs: 0,
880            slow_start_growth_limit: 1,
881            max_burst: None,
882            last_data_sent: None,
883            t3_single_packet: false,
884            fast_retransmit_marked: vec![],
885            zero_window_probe_at: None,
886            zero_window_probe_tsn: None,
887            reneged_in_last_sack: vec![],
888            acknowledging_by_shutdown: false,
889            last_advertised_window: 0,
890            received_since_sack: 0,
891            sack_delay: ACK_INTERVAL,
892
893            // Chunks stored for retransmission
894            stored_init: None,
895            stored_cookie_echo: None,
896            next_stream_generation: 0,
897            next_message_id: 0,
898            streams: FxHashMap::default(),
899            closed_stream_bytes_dequeued: FxHashMap::default(),
900            streams_lost_in_restart: vec![],
901            reassembly_bytes: 0,
902            readable_streams: FxHashSet::default(),
903            part_readable_streams: FxHashSet::default(),
904            streams_with_data: FxHashSet::default(),
905
906            events: VecDeque::default(),
907            endpoint_events: VecDeque::default(),
908            error: None,
909            ended: false,
910            abort_cause_code: None,
911            peer_abort_reason: None,
912            ended_flag: Arc::new(AtomicBool::new(false)),
913            drained_emitted: false,
914            pending_error_causes: vec![],
915            undelivered: vec![],
916            undelivered_held: vec![],
917
918            // per inbound packet context
919            delayed_ack_triggered: false,
920            immediate_ack_triggered: false,
921
922            stats: AssociationStats::default(),
923            ack_state: AckState::default(),
924
925            // for testing
926            ack_mode: AckMode::default(),
927        }
928    }
929}
930
931impl Association {
932    #[allow(clippy::too_many_arguments)]
933    pub(crate) fn new(
934        server_config: Option<Arc<ServerConfig>>,
935        config: Arc<TransportConfig>,
936        max_payload_size: u32,
937        local_aid: AssociationId,
938        remote_addr: SocketAddr,
939        local_addr: SocketAddr,
940        protocol: TransportProtocol,
941        now: Instant,
942        random: RandomSource,
943    ) -> Self {
944        let side = if server_config.is_some() {
945            Side::Server
946        } else {
947            Side::Client
948        };
949
950        // It's a bit strange, but we're going backwards from the calculation in
951        // config.rs to get max_payload_size from INITIAL_MTU.
952        let mtu = max_payload_size.saturating_add(COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE);
953
954        let pmdcs = mtu.saturating_sub(COMMON_HEADER_SIZE);
955        let cwnd = Self::initial_cwnd(pmdcs, remote_addr.is_ipv6());
956        // RFC 9260 3.3.2: an unpredictable initial TSN, from the endpoint's random source
957        // (`rand`'s thread-local CSPRNG unless a provider was given).
958        let tsn = random.nonzero_u32();
959
960        let mut this = Association {
961            side,
962            handshake_completed: false,
963            peer_awaits_cookie_ack: false,
964            max_receive_buffer_size: config.max_receive_buffer_size(),
965            max_message_size: config.max_message_size(),
966            max_receive_message_size: config.max_receive_message_size(),
967            zero_window_overcommit: config.zero_window_overcommit(),
968            zero_window_renege: config.zero_window_renege(),
969            handshake_timers_back_off_rto: config.handshake_timers_back_off_rto(),
970            partial_delivery_point: config.partial_delivery_point(),
971            transport_config: Some(config.clone()),
972            my_max_num_outbound_streams: config.max_num_outbound_streams(),
973            my_max_num_inbound_streams: config.max_num_inbound_streams(),
974            configured_outbound_streams: config.max_num_outbound_streams(),
975            configured_inbound_streams: config.max_num_inbound_streams(),
976            valid_cookie_life: config.valid_cookie_life(),
977            partial_reliability_enabled: config.partial_reliability(),
978            interleaving_enabled: config.message_interleaving(),
979            zero_checksum_enabled: config.zero_checksum(),
980            heartbeat_interval: config.heartbeat_interval(),
981            pmtud: config
982                .path_mtu_discovery()
983                .map(|pmtud| pmtud::PathMtuDiscovery::new(pmtud, mtu)),
984            created_at: Some(now),
985            random,
986            max_payload_size,
987            // RFC 8841 5: each side's `a=sctp-port`. An accepting side takes the INIT's ports
988            // instead (`handle_init`).
989            source_port: config.sctp_port(),
990            destination_port: config.remote_sctp_port(),
991
992            rto_mgr: RtoManager::with_config(config.rto_config()),
993            timers: TimerTable::new(config.timer_config())
994                .with_rto_config(config.rto_config())
995                .with_t1_following_rto(config.handshake_timers_back_off_rto()),
996            pending_queue: {
997                let mut queue = PendingQueue::with_scheduler(config.stream_scheduler());
998                queue.set_packet_budget(mtu.saturating_sub(COMMON_HEADER_SIZE) as usize);
999                queue
1000            },
1001
1002            mtu,
1003            cwnd,
1004            send_rate: None,
1005            pmdcs,
1006            slow_start_growth_limit: config.slow_start_growth_limit(),
1007            max_burst: config.max_burst(),
1008            last_advertised_window: config.max_receive_buffer_size(),
1009            received_since_sack: 0,
1010            sack_delay: config.sack_delay().as_millis() as u64,
1011            remote_addr,
1012            local_addr,
1013            transport_protocol: protocol,
1014
1015            my_verification_tag: local_aid,
1016            my_next_tsn: tsn,
1017            my_next_rsn: tsn,
1018            min_tsn2measure_rtt: tsn,
1019            cumulative_tsn_ack_point: tsn - 1,
1020            advanced_peer_tsn_ack_point: tsn - 1,
1021            error: None,
1022
1023            ..Default::default()
1024        };
1025
1026        if !side.is_client() {
1027            // The accepting side exists from the peer's INIT on. Without a COOKIE ECHO it
1028            // must not exist for ever (and an INIT that is not valid starts no handshake at
1029            // all), so the wait is timed from the start.
1030            this.timers.start(Timer::HalfOpen, now, HALF_OPEN_LIFETIME);
1031        }
1032
1033        if side.is_client() {
1034            let mut init = ChunkInit {
1035                initial_tsn: this.my_next_tsn,
1036                num_outbound_streams: this.my_max_num_outbound_streams,
1037                num_inbound_streams: this.my_max_num_inbound_streams,
1038                initiate_tag: this.my_verification_tag,
1039                advertised_receiver_window_credit: this.max_receive_buffer_size,
1040                ..Default::default()
1041            };
1042            init.announce_extensions(
1043                this.partial_reliability_enabled,
1044                this.interleaving_enabled,
1045                this.zero_checksum_enabled,
1046            );
1047
1048            this.set_state(AssociationState::CookieWait);
1049            this.stored_init = Some(init);
1050            let _ = this.send_init();
1051            this.timers
1052                .start(Timer::T1Init, now, this.rto_mgr.get_rto());
1053        }
1054
1055        this
1056    }
1057
1058    /// RFC 9260 7.2.1: the initial cwnd, before DATA is sent and after a change of path, is
1059    /// min(4 x PMDCS, max(2 x PMDCS, 4404)), with 4344 in place of 4404 over IPv6.
1060    ///
1061    /// Written in total form: `clamp` panics when the bounds cross, which a small PMDCS
1062    /// makes them do, and the products saturate.
1063    fn initial_cwnd(pmdcs: u32, ipv6: bool) -> u32 {
1064        let floor = if ipv6 { 4344 } else { 4404 };
1065        pmdcs
1066            .saturating_mul(2)
1067            .max(floor)
1068            .min(pmdcs.saturating_mul(4))
1069    }
1070
1071    /// The congestion window, in bytes of user data.
1072    pub fn congestion_window(&self) -> u32 {
1073        self.cwnd
1074    }
1075
1076    /// Bounds the rate new DATA is sent at to `bits_per_second` (DATA chunks on the wire), or
1077    /// lifts the bound with `None` (the default). The association's own congestion control
1078    /// runs as ever (RFC 9260 7.2) and new DATA goes when both it and the bound let it: a
1079    /// token bucket that fills at the rate, holds at most [`SEND_RATE_BURST`] of it (and two
1080    /// PMDCS at least), and lets the chunk out that takes it below empty, the last. A window
1081    /// held under cwnd by the bound is not in full use, so cwnd does not grow meanwhile (7.2.1,
1082    /// 7.2.2). Retransmissions are not held. The caller wakes the association
1083    /// (`handle_timeout`, `poll_transmit`) while DATA waits on the bound: it sets no timer.
1084    ///
1085    /// For an application that shares one congestion controller's estimate among several
1086    /// flows over one path (RFC 8836 section 2, requirement 6a; RFC 8699): the data channels
1087    /// of a WebRTC peer connection take their share of the media's estimate this way.
1088    pub fn set_max_send_rate(&mut self, bits_per_second: Option<f64>) {
1089        match (bits_per_second, self.send_rate.as_mut()) {
1090            (Some(rate), Some(limit)) => limit.bits_per_second = rate.max(0.0),
1091            (Some(rate), None) => {
1092                self.send_rate = Some(SendRateLimit {
1093                    bits_per_second: rate.max(0.0),
1094                    tokens: f64::from(self.pmdcs),
1095                    updated: None,
1096                });
1097            }
1098            (None, _) => self.send_rate = None,
1099        }
1100    }
1101
1102    /// The bound [`set_max_send_rate`](Self::set_max_send_rate) set, bits per second.
1103    pub fn max_send_rate(&self) -> Option<f64> {
1104        self.send_rate.as_ref().map(|limit| limit.bits_per_second)
1105    }
1106
1107    /// The window DATA is sent in: the congestion window.
1108    fn send_window(&self) -> u32 {
1109        self.cwnd
1110    }
1111
1112    /// The slow start threshold, in bytes of user data.
1113    pub fn slow_start_threshold(&self) -> u32 {
1114        self.ssthresh
1115    }
1116
1117    /// The current retransmission timeout.
1118    pub fn rto(&self) -> Duration {
1119        Duration::from_millis(self.rto_mgr.get_rto())
1120    }
1121
1122    /// The peer's receive window as this side tracks it (RFC 9260 6.2.1: the last a_rwnd
1123    /// less the bytes sent since and not acknowledged), in bytes of user data.
1124    pub fn peer_receive_window(&self) -> u32 {
1125        self.rwnd
1126    }
1127
1128    /// RFC 9260 11.1.8 Status: the association's state in one call (single-homed, RFC 8261
1129    /// 6.1, so one destination: no address list or primary path).
1130    pub fn status(&self) -> AssociationStatus {
1131        AssociationStatus {
1132            closed: self.is_closed(),
1133            peer_receive_window: self.rwnd,
1134            congestion_window: self.cwnd,
1135            slow_start_threshold: self.ssthresh,
1136            unacknowledged_data_chunks: self.inflight_queue.len(),
1137            pending_data_chunks: self.pending_queue.len(),
1138            srtt: self.rtt(),
1139            rto: self.rto(),
1140            path_mtu: self.path_mtu(),
1141        }
1142    }
1143
1144    /// Tells the association that its packets take another path from now on: the transport
1145    /// underneath switched (for WebRTC, ICE selected another candidate pair).
1146    ///
1147    /// RFC 9260 7.2.5: what was learned about the old path says nothing about the new one, so
1148    /// the congestion control state and the RTO start again from their initial values. DATA
1149    /// outstanding stays outstanding, and its retransmission timer runs on with the initial
1150    /// RTO.
1151    pub fn on_path_change(&mut self, now: Instant) {
1152        debug!(
1153            "[{}] path change: congestion control starts over",
1154            self.side
1155        );
1156        // RFC 8261 section 6.1 and RFC 8831 section 5: the path MTU is tested again. The
1157        // discovery starts over from BASE_PLPMTU, which is what the packets use until a
1158        // probe confirms more.
1159        if let Some(pmtud) = self.pmtud.as_mut() {
1160            let base = pmtud.base();
1161            pmtud.reset(base);
1162            self.use_path_mtu(base, true);
1163        }
1164        self.cwnd = Self::initial_cwnd(self.pmdcs, self.remote_addr.is_ipv6());
1165        // RFC 9260 7.2.1: the initial ssthresh is arbitrarily high; the peer's window is.
1166        self.ssthresh = self
1167            .rwnd
1168            .saturating_add(self.inflight_queue.get_num_bytes() as u32);
1169        self.partial_bytes_acked = 0;
1170        self.in_fast_recovery = false;
1171        self.will_retransmit_fast = false;
1172        self.last_data_sent = None;
1173        self.rto_mgr.reset();
1174        // No RTT sample of the old path may be taken for the new one.
1175        self.min_tsn2measure_rtt = self.my_next_tsn;
1176        self.path_error_count = 0;
1177        if self.timers.get(Timer::T3RTX).is_some() {
1178            self.timers.stop(Timer::T3RTX);
1179            self.timers.start(Timer::T3RTX, now, self.rto_mgr.get_rto());
1180        }
1181    }
1182
1183    /// The largest SCTP packet (common header and chunks) the association sends: the path
1184    /// MTU as it knows it.
1185    pub fn path_mtu(&self) -> u32 {
1186        self.mtu
1187    }
1188
1189    /// Tells the association the largest SCTP packet the path below carries, in bytes: the
1190    /// path MTU less what lies beneath SCTP (for WebRTC: the DTLS record overhead, the UDP
1191    /// and IP headers, and TURN framing where a relay is used). The entry point for whatever
1192    /// learns the path MTU: the transport's initial value for a path, the application's own
1193    /// discovery, or an ICMP "Packet Too Big" it has validated (RFC 9260 section 7.3, RFC 8261
1194    /// section 4).
1195    ///
1196    /// With path MTU discovery on ([`TransportConfig::with_path_mtu_discovery`]) the value
1197    /// is BASE_PLPMTU (RFC 8899 section 5.1.2): the association uses it, confirms it with a
1198    /// probe once established and searches above it; a new value starts the discovery over.
1199    /// Setting the value in use again changes nothing.
1200    ///
1201    /// From now on packets are bundled up to the packet size, the Path Maximum DATA Chunk
1202    /// Size of the congestion control rules follows it, and messages written from now on are
1203    /// fragmented to fit. A message already fragmented keeps its fragments: after a reduction
1204    /// they are sent as they are, each alone in a packet larger than the new MTU, and the
1205    /// layer below has to fragment or the caller to accept the loss (RFC 9260 section 6.9:
1206    /// SCTP does not re-fragment). A value below
1207    /// [`MIN_DATA_PACKET_MTU`](crate::MIN_DATA_PACKET_MTU) is raised to it.
1208    pub fn set_path_mtu(&mut self, mtu: u32) {
1209        let mtu = mtu.max(crate::config::MIN_DATA_PACKET_MTU);
1210        if let Some(pmtud) = self.pmtud.as_mut() {
1211            if pmtud.base() == mtu {
1212                return;
1213            }
1214            pmtud.reset(mtu);
1215        }
1216        self.use_path_mtu(mtu, true);
1217    }
1218
1219    /// The layer below reported, from a Packet Too Big it validated (RFC 8899 section
1220    /// 4.6.1), that the path carries SCTP packets of `ptb_size` bytes (PL_PTB_SIZE: the
1221    /// headers below SCTP taken off). Returns whether the packet size went down.
1222    ///
1223    /// With path MTU discovery the report is one of its inputs, never the size itself (RFC
1224    /// 8899 section 4.6.2; see `PathMtuDiscovery::on_packet_too_big`): a size below the
1225    /// PLPMTU and not below BASE_PLPMTU takes the PLPMTU back to BASE_PLPMTU and the search
1226    /// starts again. Without discovery the packet size comes down to the size reported (RFC
1227    /// 9260 section 10, ICMP7: for an ICMPv6 Packet Too Big or ICMPv4 Fragmentation Needed
1228    /// "an implementation SHOULD process this information as defined for PMTU discovery";
1229    /// RFC 8201 section 4), never below
1230    /// [`MIN_DATA_PACKET_MTU`](crate::MIN_DATA_PACKET_MTU) and never up. A report never
1231    /// raises the congestion window, and SCTP does not rely on reports: discovery goes on
1232    /// without them (RFC 8261 section 6.1, RFC 8831 section 5).
1233    pub fn handle_packet_too_big(&mut self, ptb_size: u32) -> bool {
1234        let before = self.mtu;
1235        match self.pmtud.as_mut() {
1236            Some(pmtud) => {
1237                if let Some(mtu) = pmtud.on_packet_too_big(ptb_size) {
1238                    debug!("[{}] packet too big: back to {mtu} bytes", self.side);
1239                    self.use_path_mtu(mtu, false);
1240                }
1241            }
1242            None if ptb_size < self.mtu => self.use_path_mtu(ptb_size, false),
1243            None => {}
1244        }
1245        self.mtu < before
1246    }
1247
1248    /// MAX_PLPMTU of the path MTU discovery (RFC 8899 section 5.1.2): the largest SCTP packet
1249    /// the search tries, the local interface MTU less what lies under SCTP. Nothing without
1250    /// discovery.
1251    pub fn set_max_path_mtu(&mut self, max: u32) {
1252        if let Some(mtu) = self.pmtud.as_mut().and_then(|p| p.set_max_path_mtu(max)) {
1253            self.use_path_mtu(mtu, false);
1254        }
1255    }
1256
1257    /// Where the path MTU discovery is (RFC 8899 section 5.2); `None` without discovery.
1258    pub fn path_mtu_state(&self) -> Option<PathMtuState> {
1259        self.pmtud.as_ref().map(|p| p.state())
1260    }
1261
1262    /// Takes `mtu` as the size of the packets sent from now on. `raise_cwnd`: the congestion
1263    /// window grows to one packet if it is smaller (RFC 9260 7.2.1); a PLPMTU found by
1264    /// discovery leaves it as it is (RFC 8899 section 3 item 7: "An update to the PLPMTU (or
1265    /// MPS) MUST NOT increase the congestion window measured in bytes").
1266    fn use_path_mtu(&mut self, mtu: u32, raise_cwnd: bool) {
1267        let mtu = mtu.max(crate::config::MIN_DATA_PACKET_MTU);
1268        if mtu == self.mtu {
1269            return;
1270        }
1271        debug!("[{}] path MTU {} -> {}", self.side, self.mtu, mtu);
1272        self.mtu = mtu;
1273        self.pmdcs = mtu.saturating_sub(COMMON_HEADER_SIZE);
1274        self.max_payload_size = crate::config::max_payload_size_for_mtu(mtu);
1275        for s in self.streams.values_mut() {
1276            s.max_payload_size = self.max_payload_size;
1277        }
1278        self.pending_queue.set_packet_budget(self.pmdcs as usize);
1279        if raise_cwnd {
1280            // RFC 9260 7.2.1: cwnd is never below one packet of the size now in use.
1281            self.cwnd = self.cwnd.max(self.pmdcs);
1282        }
1283    }
1284
1285    /// Returns application-facing event
1286    ///
1287    /// Associations should be polled for events after:
1288    /// - a call was made to `handle_event`
1289    /// - a call was made to `handle_timeout`
1290    #[must_use]
1291    pub fn poll(&mut self) -> Option<Event> {
1292        if let Some(x) = self.events.pop_front() {
1293            return Some(x);
1294        }
1295
1296        /*TODO: if let Some(event) = self.streams.poll() {
1297            return Some(Event::Stream(event));
1298        }*/
1299
1300        if let Some(err) = self.error.take() {
1301            return Some(Event::HandshakeFailed { reason: err });
1302        }
1303
1304        None
1305    }
1306
1307    /// Return endpoint-facing event
1308    #[must_use]
1309    pub fn poll_endpoint_event(&mut self) -> Option<EndpointEvent> {
1310        self.endpoint_events.pop_front().map(EndpointEvent)
1311    }
1312
1313    /// Returns the next time at which `handle_timeout` should be called
1314    ///
1315    /// The value returned may change after:
1316    /// - the application performed some I/O on the association
1317    /// - a call was made to `handle_transmit`
1318    /// - a call to `poll_transmit` returned `Some`
1319    /// - a call was made to `handle_timeout`
1320    #[must_use]
1321    pub fn poll_timeout(&self) -> Option<Instant> {
1322        // The discovery runs while the association is established only.
1323        let pmtud = self
1324            .pmtud
1325            .as_ref()
1326            .filter(|_| self.state() == AssociationState::Established)
1327            .and_then(|p| p.deadline());
1328        // The first zero window probe's time, while there is DATA to probe with.
1329        let probe = self.zero_window_probe_at;
1330        // A FORWARD TSN held back for DATA goes at the end of its delay.
1331        let forward_tsn = self
1332            .forward_tsn_due_at
1333            .filter(|_| self.will_send_forward_tsn);
1334        [self.timers.next_timeout(), pmtud, probe, forward_tsn]
1335            .into_iter()
1336            .flatten()
1337            .min()
1338    }
1339
1340    /// Returns packets to transmit
1341    ///
1342    /// Associations should be polled for transmit after:
1343    /// - the application performed some I/O on the Association
1344    /// - a call was made to `handle_event`
1345    /// - a call was made to `handle_timeout`
1346    #[must_use]
1347    pub fn poll_transmit(&mut self, now: Instant) -> Option<TransportMessage<Payload>> {
1348        let (contents, keep_open) = self.gather_outbound(now);
1349        if !keep_open && !self.ended {
1350            // The SHUTDOWN COMPLETE just gathered is the last packet of a graceful shutdown
1351            // this side started: RFC 9260 9.2 removes the association once it is sent. It
1352            // stayed in SHUTDOWN-SENT for good, with nothing left to happen.
1353            if let Err(err) = self.close(AssociationError::LocallyClosed) {
1354                error!("[{}] failed to close association: {err}", self.side);
1355            }
1356        }
1357        if contents.is_empty() {
1358            None
1359        } else {
1360            self.bytes_sent = self
1361                .bytes_sent
1362                .saturating_add(contents.iter().map(Bytes::len).sum());
1363            trace!(
1364                "[{}] sending {} bytes (total {} datagrams)",
1365                self.side,
1366                contents.iter().fold(0, |l, c| l + c.len()),
1367                contents.len()
1368            );
1369            Some(TransportMessage {
1370                now,
1371                transport: TransportContext {
1372                    local_addr: self.local_addr,
1373                    peer_addr: self.remote_addr,
1374                    ecn: None,
1375                    transport_protocol: Default::default(),
1376                },
1377                message: Payload::RawEncode(contents),
1378            })
1379        }
1380    }
1381
1382    /// Process timer expirations
1383    ///
1384    /// Executes protocol logic, potentially preparing signals (including application `Event`s,
1385    /// `EndpointEvent`s and outgoing datagrams) that should be extracted through the relevant
1386    /// methods.
1387    ///
1388    /// It is most efficient to call this immediately after the system clock reaches the latest
1389    /// `Instant` that was output by `poll_timeout`; however spurious extra calls will simply
1390    /// no-op and therefore are safe.
1391    pub fn handle_timeout(&mut self, now: Instant) {
1392        // RFC 9260 6.1 A: the first zero window probe may go now.
1393        if self.zero_window_probe_at.is_some_and(|at| now >= at) {
1394            self.zero_window_probe_at = None;
1395        }
1396        for &timer in &Timer::VALUES {
1397            let (expired, failure, n_rtos) = self.timers.is_expired(timer, now);
1398            if !expired {
1399                continue;
1400            }
1401            self.timers.set(timer, None);
1402            //trace!("{:?} timeout", timer);
1403
1404            if timer == Timer::Ack {
1405                self.on_ack_timeout();
1406            } else if timer == Timer::Heartbeat {
1407                self.on_heartbeat_timeout(now);
1408            } else if failure && timer != Timer::Reconfig {
1409                self.on_retransmission_failure(timer);
1410            } else {
1411                self.on_retransmission_timeout(timer, n_rtos, now);
1412                if self.state() == AssociationState::Closed {
1413                    break;
1414                }
1415                self.timers.start(timer, now, self.rto_mgr.get_rto());
1416            }
1417        }
1418        if self
1419            .pmtud
1420            .as_ref()
1421            .and_then(|p| p.deadline())
1422            .is_some_and(|at| now >= at)
1423        {
1424            self.handle_path_mtu_timeout(now);
1425        }
1426    }
1427
1428    /// Process `AssociationEvent`s generated by the associated `Endpoint`
1429    ///
1430    /// Will execute protocol logic upon receipt of an association event, in turn preparing signals
1431    /// (including application `Event`s, `EndpointEvent`s and outgoing datagrams) that should be
1432    /// extracted through the relevant methods.
1433    pub fn handle_event(&mut self, event: AssociationEvent) {
1434        match event.0 {
1435            AssociationEventInner::Datagram(transmit) => {
1436                // If this packet could initiate a migration and we're a client or a server that
1437                // forbids migration, drop the datagram. This could be relaxed to heuristically
1438                // permit NAT-rebinding-like migration.
1439                /*TODO:if remote != self.remote && self.server_config.as_ref().map_or(true, |x| !x.migration)
1440                {
1441                    trace!("discarding packet from unrecognized peer {}", remote);
1442                    return;
1443                }*/
1444
1445                if let Payload::PartialDecode(partial_decode) = transmit.message {
1446                    // RFC 9653 5.3: a zero checksum is taken only by an endpoint that
1447                    // announced it; otherwise the packet is dropped as one with a wrong
1448                    // CRC32c (RFC 9260 6.8).
1449                    if !partial_decode.checksum_ok(self.zero_checksum_enabled) {
1450                        debug!("[{}] discarding a packet with a zero checksum", self.side);
1451                        return;
1452                    }
1453                    let len = COMMON_HEADER_SIZE as usize + partial_decode.remaining.len();
1454                    debug!("[{}] recving {} bytes", self.side, len);
1455                    self.bytes_received = self.bytes_received.saturating_add(len);
1456
1457                    let pkt = match partial_decode.finish() {
1458                        Ok(p) => p,
1459                        Err(err) => {
1460                            warn!("[{}] unable to parse SCTP packet {}", self.side, err);
1461                            return;
1462                        }
1463                    };
1464
1465                    if let Err(err) = self.handle_inbound(pkt, transmit.now) {
1466                        error!("handle_inbound got err: {}", err);
1467                        let _ = self.close(AssociationError::TransportError);
1468                    }
1469                } else {
1470                    trace!("discarding invalid partial_decode");
1471                }
1472            } //TODO:
1473        }
1474    }
1475
1476    /// Whether PR-SCTP (RFC 3758) is in use: both sides announced it. `false` while the
1477    /// association is being set up, and for good when the peer does not support it, in which
1478    /// case every message is sent reliably whatever its stream's reliability parameters say.
1479    pub fn partial_reliability(&self) -> bool {
1480        self.use_forward_tsn
1481    }
1482
1483    /// Returns Association statistics
1484    pub fn stats(&self) -> AssociationStats {
1485        self.stats
1486    }
1487
1488    /// Whether the Association is in the process of being established
1489    ///
1490    /// If this returns `false`, the Association may be either established or closed, signaled by the
1491    /// emission of a `Connected` or `AssociationLost` message respectively.
1492    pub fn is_handshaking(&self) -> bool {
1493        !self.handshake_completed
1494    }
1495
1496    /// The number of streams negotiated for this association: the smaller of the inbound and
1497    /// outbound counts the two endpoints agreed on in INIT/INIT ACK.
1498    ///
1499    /// `None` while the association is still handshaking. Before the peer's INIT (or INIT ACK) has
1500    /// been processed, the two counts still hold this endpoint's *configured* limits rather than
1501    /// anything agreed, so reporting them would overstate what the association can carry.
1502    ///
1503    /// This is what [RFC 8831] data channels are limited by, and what W3C
1504    /// `RTCSctpTransport.maxChannels` reports.
1505    ///
1506    /// [RFC 8831]: https://datatracker.ietf.org/doc/html/rfc8831
1507    pub fn negotiated_max_streams(&self) -> Option<u16> {
1508        if self.is_handshaking() {
1509            None
1510        } else {
1511            Some(
1512                self.my_max_num_inbound_streams
1513                    .min(self.my_max_num_outbound_streams),
1514            )
1515        }
1516    }
1517
1518    /// Whether the Association is closed
1519    ///
1520    /// Closed Associations cannot transport any further data. An association becomes closed when
1521    /// either peer application intentionally closes it, or when either transport layer detects an
1522    /// error such as a time-out or certificate validation failure.
1523    ///
1524    /// A `AssociationLost` event is emitted with details when the association becomes closed.
1525    pub fn is_closed(&self) -> bool {
1526        self.state == AssociationState::Closed
1527    }
1528
1529    /// Whether the association is over: closed by either side, by an error, or by a handshake
1530    /// that failed.
1531    ///
1532    /// Unlike [`is_closed`](Self::is_closed), false for an association still handshaking in
1533    /// SCTP's initial CLOSED state (RFC 9260 section 4), which has not ended.
1534    pub fn is_ended(&self) -> bool {
1535        self.ended
1536    }
1537
1538    /// Whether there is no longer any need to keep the association around
1539    ///
1540    /// Closed associations become drained after a brief timeout to absorb any remaining in-flight
1541    /// packets from the peer. All drained associations have been closed.
1542    pub fn is_drained(&self) -> bool {
1543        self.state.is_drained()
1544    }
1545
1546    /// The Verification Tag this association expects in the packets it receives (RFC 9260
1547    /// section 8.5): its own Initiate Tag.
1548    pub fn verification_tag(&self) -> u32 {
1549        self.my_verification_tag
1550    }
1551
1552    /// Look up whether we're the client or server of this Association
1553    pub fn side(&self) -> Side {
1554        self.side
1555    }
1556
1557    /// The latest socket address for this Association's peer
1558    pub fn remote_addr(&self) -> SocketAddr {
1559        self.remote_addr
1560    }
1561
1562    /// Smoothed round-trip time, or zero before the first RTT measurement.
1563    /// Retransmission timeout backoff does not change this estimate.
1564    pub fn rtt(&self) -> Duration {
1565        Duration::from_millis(self.rto_mgr.srtt)
1566    }
1567
1568    /// The local IP address which was used when the peer established
1569    /// the association
1570    ///
1571    /// This can be different from the address the endpoint is bound to, in case
1572    /// the endpoint is bound to a wildcard address like `0.0.0.0` or `::`.
1573    ///
1574    /// This will return `None` for clients.
1575    ///
1576    /// Retrieving the local IP address is currently supported on the following
1577    /// platforms:
1578    /// - Linux
1579    ///
1580    /// On all non-supported platforms the local IP address will not be available,
1581    /// and the method will return `None`.
1582    pub fn local_addr(&self) -> SocketAddr {
1583        self.local_addr
1584    }
1585
1586    /// Shutdown initiates the shutdown sequence. The method blocks until the
1587    /// shutdown sequence is completed and the association is closed, or until the
1588    /// passed context is done, in which case the context's error is returned.
1589    pub fn shutdown(&mut self) -> Result<()> {
1590        debug!("[{}] closing association..", self.side);
1591
1592        let state = self.state();
1593        if state != AssociationState::Established {
1594            return Err(Error::ErrShutdownNonEstablished);
1595        }
1596
1597        // Attempt a graceful shutdown. RFC 9260 9.2: SHUTDOWN-PENDING lasts until everything
1598        // the application handed over has been sent and acknowledged. This tested a counter
1599        // that was never updated, so SHUTDOWN went out at once, ahead of the DATA still in
1600        // flight or queued, and the queued DATA was never sent.
1601        self.set_state(AssociationState::ShutdownPending);
1602
1603        if self.nothing_left_to_send() {
1604            // No more outstanding, send shutdown.
1605            self.send_shutdown();
1606        }
1607
1608        Ok(())
1609    }
1610
1611    /// Moves SHUTDOWN-PENDING on to SHUTDOWN-SENT and queues the SHUTDOWN.
1612    ///
1613    /// The endpoint's `Drained` goes out with it, as it always has: the owner flushes this
1614    /// association's final packets and may then stop routing to it. It used to be emitted by
1615    /// `shutdown()` itself, which with DATA still outstanding cut the association off from the
1616    /// SACKs it was waiting for.
1617    fn send_shutdown(&mut self) {
1618        self.will_send_shutdown = true;
1619        self.awake_write_loop();
1620        self.set_state(AssociationState::ShutdownSent);
1621        self.emit_drained();
1622    }
1623
1624    /// RFC 9260 9.2: the T5-shutdown-guard timer bounds the whole shutdown, however often the
1625    /// peer's packets restart T2-shutdown.
1626    fn start_shutdown_guard(&mut self, now: Instant) {
1627        if self.timers.get(Timer::T5ShutdownGuard).is_none() {
1628            self.timers
1629                .start(Timer::T5ShutdownGuard, now, T5_SHUTDOWN_GUARD);
1630        }
1631    }
1632
1633    /// Tells the endpoint to stop routing to this association, once.
1634    fn emit_drained(&mut self) {
1635        if !self.drained_emitted {
1636            self.drained_emitted = true;
1637            self.endpoint_events.push_back(EndpointEventInner::Drained);
1638        }
1639    }
1640
1641    /// The flag the endpoint reads to learn that this association has ended.
1642    pub(crate) fn ended_flag(&self) -> Arc<AtomicBool> {
1643        self.ended_flag.clone()
1644    }
1645
1646    /// Aborts the association (RFC 9260 §9.1): queues an ABORT chunk and closes the association.
1647    ///
1648    /// Unlike [`shutdown`](Self::shutdown) this needs no round trip, which is what closing a
1649    /// WebRTC peer connection calls for: W3C `close()` tears the association down "by sending an
1650    /// SCTP ABORT chunk". The ABORT carries a "User-Initiated Abort" error cause (RFC 9260
1651    /// §3.3.10.12), which a peer takes as an intentional close rather than an error.
1652    ///
1653    /// The ABORT is sent by the next [`poll_transmit`](Self::poll_transmit). Anything not handed to
1654    /// `poll_transmit` before this call is discarded, so drain it first if it should still go out.
1655    /// A no-op on a closed association.
1656    pub fn abort(&mut self) -> Result<()> {
1657        if self.ended {
1658            return Ok(());
1659        }
1660        self.abort_with(
1661            vec![ErrorCause {
1662                code: USER_INITIATED_ABORT,
1663                ..Default::default()
1664            }],
1665            AssociationError::LocallyClosed,
1666        )
1667    }
1668
1669    /// Sends an ABORT with `causes` to the peer and ends the association with `reason`
1670    /// (RFC 9260 9.1). The ABORT goes alone in its packet, with the peer's tag; before the
1671    /// peer's tag is known (no INIT ACK yet) there is no one to send it to.
1672    fn abort_with(&mut self, causes: Vec<ErrorCause>, reason: AssociationError) -> Result<()> {
1673        if self.ended {
1674            return Ok(());
1675        }
1676        if let Some(cause) = causes.first() {
1677            self.abort_cause_code.get_or_insert(cause.code.0);
1678        }
1679        if self.peer_verification_tag != 0 {
1680            let packet = self.abort_packet(self.peer_verification_tag, false, causes);
1681            self.control_queue.push_back(packet);
1682            self.awake_write_loop();
1683        }
1684        self.close(reason)
1685    }
1686
1687    /// A packet holding one ABORT chunk, sent with Verification Tag `tag`. `reflected` sets
1688    /// the T bit: the tag is the one of the packet being answered, not the receiver's own
1689    /// (RFC 9260 8.4, 8.5.1).
1690    fn abort_packet(&self, tag: u32, reflected: bool, causes: Vec<ErrorCause>) -> Packet {
1691        Packet {
1692            common_header: CommonHeader {
1693                verification_tag: tag,
1694                source_port: self.source_port,
1695                destination_port: self.destination_port,
1696            },
1697            chunks: vec![Box::new(ChunkAbort {
1698                error_causes: causes,
1699                tag_reflected: reflected,
1700            })],
1701        }
1702    }
1703
1704    fn protocol_violation(text: &str) -> ErrorCause {
1705        ErrorCause {
1706            code: PROTOCOL_VIOLATION,
1707            raw: Bytes::copy_from_slice(text.as_bytes()),
1708        }
1709    }
1710
1711    /// The cause code (RFC 9260 section 3.3.10) of the ABORT that ended the association: the
1712    /// first error cause of the one received, or of the one this side sent. `None` when no
1713    /// ABORT ended it, or the ABORT carried no cause. What W3C webrtc-pc reports as an
1714    /// `RTCError`'s `sctpCauseCode`.
1715    pub fn abort_cause_code(&self) -> Option<u16> {
1716        self.abort_cause_code
1717    }
1718
1719    /// The Upper Layer Abort Reason the peer gave when it aborted the association (RFC 9260
1720    /// sections 3.3.10.12 and 9.1: "the Upper Layer Abort Reason ... SHOULD be made available
1721    /// to the upper layer"). `None` when the association did not end by the peer's
1722    /// User-Initiated Abort; empty when that carried no reason.
1723    pub fn peer_abort_reason(&self) -> Option<&[u8]> {
1724        self.peer_abort_reason.as_deref()
1725    }
1726
1727    /// As [`abort`](Self::abort), with an Upper Layer Abort Reason in the User-Initiated
1728    /// Abort error cause (RFC 9260 section 3.3.10.12) for the peer's application.
1729    pub fn abort_with_reason(&mut self, reason: &[u8]) -> Result<()> {
1730        if self.ended {
1731            return Ok(());
1732        }
1733        self.abort_with(
1734            vec![ErrorCause {
1735                code: USER_INITIATED_ABORT,
1736                raw: Bytes::copy_from_slice(reason),
1737            }],
1738            AssociationError::LocallyClosed,
1739        )
1740    }
1741
1742    /// Close ends the SCTP Association and cleans up any state
1743    pub fn close(&mut self, reason: AssociationError) -> Result<()> {
1744        // Keyed on `ended`, not on the CLOSED state: an accepting association is in SCTP's
1745        // initial CLOSED state until the COOKIE ECHO, so an ABORT or an error during its
1746        // handshake used to close nothing and leave it handshaking for good.
1747        if !self.ended {
1748            self.ended = true;
1749            // The endpoint stops routing to an ended association and frees its place for the
1750            // next one (RFC 9260 9.1: the association is removed from the record). The owner
1751            // may keep the association itself to read how it ended.
1752            self.ended_flag.store(true, Ordering::Relaxed);
1753            self.set_state(AssociationState::Closed);
1754
1755            debug!("[{}] closing association..", self.side);
1756
1757            self.close_all_timers();
1758
1759            for si in self.streams.keys().cloned().collect::<Vec<u16>>() {
1760                self.unregister_stream(si, reason.clone());
1761            }
1762            self.collect_undelivered_messages();
1763            self.events.push_back(Event::AssociationClosed {
1764                reason: reason.clone(),
1765            });
1766
1767            debug!("[{}] association closed", self.side);
1768            debug!(
1769                "[{}] stats nDATAs (in) : {}",
1770                self.side,
1771                self.stats.get_num_datas()
1772            );
1773            debug!(
1774                "[{}] stats nSACKs (in) : {}",
1775                self.side,
1776                self.stats.get_num_sacks()
1777            );
1778            debug!(
1779                "[{}] stats nT3Timeouts : {}",
1780                self.side,
1781                self.stats.get_num_t3timeouts()
1782            );
1783            debug!(
1784                "[{}] stats nAckTimeouts: {}",
1785                self.side,
1786                self.stats.get_num_ack_timeouts()
1787            );
1788            debug!(
1789                "[{}] stats nFastRetrans: {}",
1790                self.side,
1791                self.stats.get_num_fast_retrans()
1792            );
1793        }
1794
1795        Ok(())
1796    }
1797
1798    /// open_stream opens a stream
1799    pub fn open_stream(
1800        &mut self,
1801        stream_identifier: StreamId,
1802        default_payload_type: PayloadProtocolIdentifier,
1803    ) -> Result<Stream<'_>> {
1804        if self.streams.contains_key(&stream_identifier) {
1805            return Err(Error::ErrStreamAlreadyExist);
1806        }
1807
1808        // RFC 9260 5.1.1, 6.5: the outgoing stream ids are 0 to min(own OS, peer's MIS) - 1.
1809        // DATA on any other is answered by the peer with an ERROR and thrown away.
1810        if self.my_max_num_outbound_streams != 0
1811            && stream_identifier >= self.my_max_num_outbound_streams
1812        {
1813            return Err(Error::ErrStreamCreateFailed);
1814        }
1815
1816        if let Some(s) = self.create_stream(stream_identifier, false, default_payload_type) {
1817            Ok(s)
1818        } else {
1819            Err(Error::ErrStreamCreateFailed)
1820        }
1821    }
1822
1823    /// accept_stream accepts a stream
1824    pub fn accept_stream(&mut self) -> Option<Stream<'_>> {
1825        self.stream_queue
1826            .pop_front()
1827            .map(move |stream_identifier| Stream {
1828                stream_identifier,
1829                association: self,
1830            })
1831    }
1832
1833    /// stream returns a stream
1834    pub fn stream(&mut self, stream_identifier: StreamId) -> Result<Stream<'_>> {
1835        if !self.streams.contains_key(&stream_identifier) {
1836            Err(Error::ErrStreamNotExisted)
1837        } else {
1838            Ok(Stream {
1839                stream_identifier,
1840                association: self,
1841            })
1842        }
1843    }
1844
1845    /// The identifiers of every stream currently open on this association.
1846    pub fn stream_ids(&self) -> Vec<StreamId> {
1847        self.streams.keys().cloned().collect()
1848    }
1849
1850    /// The bytes of every SCTP packet handed out by `poll_transmit`, common headers included.
1851    pub fn bytes_sent(&self) -> usize {
1852        self.bytes_sent
1853    }
1854
1855    /// The bytes of every SCTP packet handed in through `handle_event`, common headers included.
1856    pub(crate) fn bytes_received(&self) -> usize {
1857        self.bytes_received
1858    }
1859
1860    /// max_message_size returns the maximum message size you can send.
1861    pub(crate) fn max_message_size(&self) -> u32 {
1862        self.max_message_size
1863    }
1864
1865    /// Sets the maximum message size this side may send: what a later offer/answer exchange
1866    /// negotiated (W3C webrtc 4.4.1.4 "update the data max message size", RFC 8841 section
1867    /// 6.1).
1868    pub fn set_max_message_size(&mut self, max_message_size: u32) {
1869        self.max_message_size = max_message_size;
1870    }
1871
1872    /// unregister_stream un-registers a stream from the association
1873    /// The caller should hold the association write lock.
1874    fn unregister_stream(&mut self, stream_identifier: StreamId, reason: AssociationError) {
1875        if let Some(s) = self.streams.get_mut(&stream_identifier) {
1876            // What the stream wrote and has not sent yet still goes, numbered by the stream
1877            // it was written to.
1878            let generation = s.generation;
1879            self.pending_queue
1880                .number_messages(stream_identifier, generation, false, |unordered| {
1881                    s.next_message_numbers(unordered)
1882                });
1883        }
1884        if let Some(mut s) = self.streams.remove(&stream_identifier) {
1885            debug!("[{}] unregister_stream {}", self.side, stream_identifier);
1886            self.closed_stream_bytes_dequeued
1887                .insert(stream_identifier, s.bytes_dequeued);
1888            self.reindex_stream(stream_identifier, s.get_num_bytes_in_reassembly_queue());
1889            // Messages held for a reset of the stream go with it: when the association is
1890            // ending, they are handed back as unsent (RFC 9260 8.1).
1891            self.held_write_count = self.held_write_count.saturating_sub(s.held_writes.len());
1892            if self.ended {
1893                self.undelivered_held.append(&mut s.held_writes);
1894            }
1895            self.events.push_back(Event::AssociationLost {
1896                reason,
1897                id: stream_identifier,
1898            });
1899            s.state = RecvSendState::Closed;
1900        }
1901    }
1902
1903    /// RFC 9260 8.1: an association that ends "SHOULD report the failure to the upper layer
1904    /// and optionally report back all outstanding user data remaining in its outbound
1905    /// queue". What was sent and not cumulatively acknowledged, what waits to be sent and
1906    /// what was held for a stream reset become [`UndeliveredMessage`]s, reported with one
1907    /// [`Event::SendFailure`] (11.2.2) and read with [`Self::take_undelivered_messages`].
1908    fn collect_undelivered_messages(&mut self) {
1909        let sent = self.inflight_queue.take_all();
1910        let mut unsent = self.pending_queue.take_all_messages();
1911        unsent.append(&mut self.undelivered_held);
1912        let messages = undelivered::undelivered_messages(sent, unsent);
1913        if messages.is_empty() {
1914            return;
1915        }
1916        let unacknowledged = messages
1917            .iter()
1918            .filter(|m| m.mode == UndeliveredMode::Unacknowledged)
1919            .count();
1920        self.events.push_back(Event::SendFailure {
1921            unsent: messages.len() - unacknowledged,
1922            unacknowledged,
1923        });
1924        self.undelivered.extend(messages);
1925    }
1926
1927    /// The user messages this association did not deliver, once it ended (RFC 9260 11.1.14
1928    /// Receive Unsent Message, 11.1.15 Receive Unacknowledged Message): each message that
1929    /// was never sent and each one sent and not completely acknowledged, in the order sent
1930    /// then written, as [`Event::SendFailure`] counted them. Taken once; empty while the
1931    /// association runs. A graceful shutdown ends only when everything was acknowledged, so
1932    /// it leaves none.
1933    pub fn take_undelivered_messages(&mut self) -> Vec<UndeliveredMessage> {
1934        std::mem::take(&mut self.undelivered)
1935    }
1936
1937    /// set_state atomically sets the state of the Association.
1938    fn set_state(&mut self, new_state: AssociationState) {
1939        if new_state != self.state {
1940            debug!(
1941                "[{}] state change: '{}' => '{}'",
1942                self.side, self.state, new_state,
1943            );
1944        }
1945        self.state = new_state;
1946    }
1947
1948    /// state atomically returns the state of the Association.
1949    pub(crate) fn state(&self) -> AssociationState {
1950        self.state
1951    }
1952
1953    /// caller must hold self.lock
1954    fn send_init(&mut self) -> Result<()> {
1955        if let Some(stored_init) = &self.stored_init {
1956            debug!("[{}] sending INIT", self.side);
1957
1958            let outbound = Packet {
1959                common_header: CommonHeader {
1960                    source_port: self.source_port,
1961                    destination_port: self.destination_port,
1962                    verification_tag: self.peer_verification_tag,
1963                },
1964                chunks: vec![Box::new(stored_init.clone())],
1965            };
1966
1967            self.control_queue.push_back(outbound);
1968            self.awake_write_loop();
1969
1970            Ok(())
1971        } else {
1972            Err(Error::ErrInitNotStoredToSend)
1973        }
1974    }
1975
1976    /// caller must hold self.lock
1977    fn send_cookie_echo(&mut self) -> Result<()> {
1978        if let Some(stored_cookie_echo) = &self.stored_cookie_echo {
1979            debug!("[{}] sending COOKIE-ECHO", self.side);
1980
1981            let outbound = Packet {
1982                common_header: CommonHeader {
1983                    source_port: self.source_port,
1984                    destination_port: self.destination_port,
1985                    verification_tag: self.peer_verification_tag,
1986                },
1987                chunks: vec![Box::new(stored_cookie_echo.clone())],
1988            };
1989
1990            self.control_queue.push_back(outbound);
1991            self.awake_write_loop();
1992
1993            Ok(())
1994        } else {
1995            Err(Error::ErrCookieEchoNotStoredToSend)
1996        }
1997    }
1998
1999    /// handle_inbound parses incoming raw packets
2000    fn handle_inbound(&mut self, p: Packet, now: Instant) -> Result<()> {
2001        // RFC 9260 9.1: an association that has ended is gone. Whatever still arrives for it
2002        // (a copy of the COOKIE ECHO, DATA in flight) is discarded.
2003        if self.ended {
2004            trace!(
2005                "[{}] discarding a packet for an ended association",
2006                self.side
2007            );
2008            return Ok(());
2009        }
2010
2011        if let Err(err) = p.check_packet() {
2012            warn!("[{}] failed validating packet {}", self.side, err);
2013            return Ok(());
2014        }
2015
2016        // RFC 9260 8.5.1 E: a SHUTDOWN ACK while this side is still setting the association
2017        // up belongs to an association it no longer has. It is answered as an out-of-the-blue
2018        // packet (8.4): SHUTDOWN COMPLETE with the tag of the SHUTDOWN ACK and the T bit.
2019        if matches!(
2020            self.state(),
2021            AssociationState::CookieWait | AssociationState::CookieEchoed
2022        ) && p.chunks.iter().any(|c| c.as_any().is::<ChunkShutdownAck>())
2023        {
2024            let packet = Packet {
2025                common_header: CommonHeader {
2026                    verification_tag: p.common_header.verification_tag,
2027                    source_port: self.source_port,
2028                    destination_port: self.destination_port,
2029                },
2030                chunks: vec![Box::new(ChunkShutdownComplete {
2031                    tag_reflected: true,
2032                })],
2033            };
2034            self.control_queue.push_back(packet);
2035            self.awake_write_loop();
2036            return Ok(());
2037        }
2038
2039        if !self.accepts_verification_tag(&p) {
2040            debug!(
2041                "[{}] discarding a packet with Verification Tag {}",
2042                self.side, p.common_header.verification_tag
2043            );
2044            return Ok(());
2045        }
2046
2047        self.handle_chunk_start();
2048        let replies_before = self.control_queue.len();
2049
2050        // RFC 9260 9.1: a packet that carries an ABORT is not answered. The ABORT is taken
2051        // first, so nothing queued for the chunks bundled before it goes out.
2052        if let Some(abort) = p.chunks.iter().find(|c| c.as_any().is::<ChunkAbort>()) {
2053            self.handle_chunk(&p, abort, now)?;
2054            return Ok(());
2055        }
2056
2057        // RFC 9260 9.2: in SHUTDOWN-SENT any packet from the peer shows it is still there
2058        // (it is sending what it had queued): the retransmission count starts over and so
2059        // does T2-shutdown.
2060        if self.state() == AssociationState::ShutdownSent {
2061            self.timers.reset_retrans(Timer::T2Shutdown);
2062            if self.timers.get(Timer::T2Shutdown).is_some() {
2063                self.timers.stop(Timer::T2Shutdown);
2064                self.timers
2065                    .start(Timer::T2Shutdown, now, self.rto_mgr.get_rto());
2066            }
2067        }
2068
2069        for c in &p.chunks {
2070            // `false`: the rest of the packet is discarded. An association that a chunk ended
2071            // processes none of the chunks after it either.
2072            if !self.handle_chunk(&p, c, now)? || self.ended || self.discard_rest_of_packet {
2073                break;
2074            }
2075        }
2076
2077        self.handle_chunk_end(now);
2078        // RFC 9260 12.4: one packet of control chunks answers one received packet.
2079        self.bundle_replies(replies_before);
2080
2081        Ok(())
2082    }
2083
2084    /// RFC 9260 8.5, 8.5.1: whether a received packet carries the Verification Tag it must.
2085    ///
2086    /// A packet with an INIT has tag 0 (and nothing else: `check_packet`). A packet with an
2087    /// ABORT or a SHUTDOWN COMPLETE has this side's tag, or the peer's tag with the T bit set
2088    /// (the sender had no TCB and reflected the tag it was sent). Every other packet has this
2089    /// side's tag.
2090    fn accepts_verification_tag(&self, p: &Packet) -> bool {
2091        let tag = p.common_header.verification_tag;
2092        // RFC 9260 8.5.1 D: the receiver of a COOKIE ECHO follows section 5, which compares
2093        // the tag with the one in the cookie (`handle_cookie_echo`): the cookie of a restart
2094        // (5.2.4) carries a new tag of this side's.
2095        if p.chunks
2096            .first()
2097            .is_some_and(|chunk| chunk.as_any().is::<ChunkCookieEcho>())
2098        {
2099            return true;
2100        }
2101        for chunk in &p.chunks {
2102            let any = chunk.as_any();
2103            if any.downcast_ref::<ChunkInit>().is_some_and(|c| !c.is_ack) {
2104                return tag == 0;
2105            }
2106            let reflected = any
2107                .downcast_ref::<ChunkAbort>()
2108                .map(|c| c.tag_reflected)
2109                .or_else(|| {
2110                    any.downcast_ref::<ChunkShutdownComplete>()
2111                        .map(|c| c.tag_reflected)
2112                });
2113            if let Some(reflected) = reflected {
2114                return if reflected {
2115                    tag != 0 && tag == self.peer_verification_tag
2116                } else {
2117                    tag == self.my_verification_tag
2118                };
2119            }
2120        }
2121        tag == self.my_verification_tag
2122    }
2123
2124    fn handle_chunk_start(&mut self) {
2125        self.delayed_ack_triggered = false;
2126        self.immediate_ack_triggered = false;
2127        self.pending_error_causes.clear();
2128        self.sack_packet_immediately = false;
2129        self.discard_rest_of_packet = false;
2130    }
2131
2132    /// Queues an error cause for the ERROR chunk that answers the packet being processed.
2133    fn report_error(&mut self, cause: ErrorCause) {
2134        if self.pending_error_causes.len() < MAX_ERROR_CAUSES_PER_PACKET {
2135            self.pending_error_causes.push(cause);
2136        }
2137    }
2138
2139    /// Sends the causes collected for this packet as one ERROR chunk, no larger than the MTU.
2140    fn flush_error_causes(&mut self) {
2141        if self.pending_error_causes.is_empty() || self.ended {
2142            self.pending_error_causes.clear();
2143            return;
2144        }
2145        let room = (self.mtu as usize)
2146            .saturating_sub(COMMON_HEADER_SIZE as usize + CHUNK_HEADER_SIZE)
2147            & !3;
2148        let mut used = 0;
2149        let mut causes = vec![];
2150        for mut cause in std::mem::take(&mut self.pending_error_causes) {
2151            let header = crate::chunk::ERROR_CAUSE_HEADER_LENGTH;
2152            if used + header >= room {
2153                break;
2154            }
2155            // A cause that quotes what was received (an unrecognized chunk) can be as large
2156            // as the packet it came in: it is cut to what fits.
2157            let fits = room - used - header;
2158            if cause.raw.len() > fits {
2159                cause.raw.truncate(fits);
2160            }
2161            used += cause.length() + get_padding_size(cause.length());
2162            causes.push(cause);
2163        }
2164        if !causes.is_empty() {
2165            let packet = self.create_packet(vec![Box::new(ChunkError {
2166                error_causes: causes,
2167            })]);
2168            self.control_queue.push_back(packet);
2169            self.awake_write_loop();
2170        }
2171    }
2172
2173    fn handle_chunk_end(&mut self, now: Instant) {
2174        self.flush_error_causes();
2175        if self.immediate_ack_triggered {
2176            self.ack_state = AckState::Immediate;
2177            self.timers.stop(Timer::Ack);
2178            self.awake_write_loop();
2179        } else if self.delayed_ack_triggered {
2180            // Will send delayed ack in the next ack timeout
2181            self.ack_state = AckState::Delay;
2182            self.timers.start(Timer::Ack, now, self.sack_delay);
2183        }
2184    }
2185
2186    /// Handles one chunk. `Ok(false)` stops the processing of its packet: the chunks that
2187    /// follow are discarded.
2188    #[allow(clippy::borrowed_box)]
2189    fn handle_chunk(&mut self, p: &Packet, chunk: &Box<dyn Chunk>, now: Instant) -> Result<bool> {
2190        // A chunk that is not valid in itself (an INIT with a zero Initiate Tag, an a_rwnd
2191        // below the minimum) is discarded with the rest of its packet. It is no reason to
2192        // close an association: anyone who can reach this endpoint can send one.
2193        if let Err(err) = chunk.check() {
2194            warn!("[{}] discarding an invalid chunk: {}", self.side, err);
2195            if let Some(c) = chunk.as_any().downcast_ref::<ChunkInit>() {
2196                self.refuse_invalid_init(p, c, &err);
2197            }
2198            return Ok(false);
2199        }
2200        let chunk_any = chunk.as_any();
2201        // Anything but the handshake's own chunks comes from a peer past COOKIE-ECHOED
2202        // (RFC 9260 5.1 C: it sends nothing else until the COOKIE ACK arrives).
2203        if !chunk_any.is::<ChunkInit>() && !chunk_any.is::<ChunkCookieEcho>() {
2204            self.peer_awaits_cookie_ack = false;
2205        }
2206        let packets = if let Some(c) = chunk_any.downcast_ref::<ChunkInit>() {
2207            if c.is_ack {
2208                self.handle_init_ack(p, c, now)?
2209            } else {
2210                self.handle_init(p, c, now)?
2211            }
2212        } else if let Some(c) = chunk_any.downcast_ref::<ChunkAbort>() {
2213            if let Some(cause) = c.error_causes.first() {
2214                self.abort_cause_code.get_or_insert(cause.code.0);
2215            }
2216            let mut err_str = String::new();
2217            for e in &c.error_causes {
2218                if matches!(e.code, USER_INITIATED_ABORT) {
2219                    debug!("User initiated abort received");
2220                    self.peer_abort_reason = Some(e.raw.clone());
2221                    // The peer aborted the association: its streams are lost with it, which
2222                    // is not the stream reset `Reset` reports for a channel's own close.
2223                    let _ = self.close(AssociationError::AssociationClosed);
2224                    return Ok(false);
2225                }
2226                err_str += &format!("({})", e);
2227            }
2228            return Err(Error::ErrAbortChunk(err_str));
2229        } else if let Some(c) = chunk_any.downcast_ref::<ChunkError>() {
2230            self.handle_error(c, now);
2231            // RFC 9260 §3.3.10 (RFC 4960 §3.3.10): "An Operation Error is not considered fatal
2232            // in and of itself". Only an ABORT ends the association, so report the causes and
2233            // carry on with the rest of the packet.
2234            let mut err_str = String::new();
2235            for e in &c.error_causes {
2236                err_str += &format!("({})", e);
2237            }
2238            warn!(
2239                "[{}] received ERROR chunk, with following errors: {}",
2240                self.side, err_str
2241            );
2242            vec![]
2243        } else if let Some(c) = chunk_any.downcast_ref::<ChunkHeartbeat>() {
2244            self.handle_heartbeat(c)?
2245        } else if let Some(c) = chunk_any.downcast_ref::<ChunkHeartbeatAck>() {
2246            self.handle_heartbeat_ack(c, now);
2247            vec![]
2248        } else if let Some(c) = chunk_any.downcast_ref::<ChunkCookieEcho>() {
2249            self.handle_cookie_echo(p, c, now)?
2250        } else if chunk_any.downcast_ref::<ChunkCookieAck>().is_some() {
2251            self.handle_cookie_ack(now)?
2252        } else if let Some(c) = chunk_any.downcast_ref::<ChunkPayloadData>() {
2253            self.handle_data(c)?
2254        } else if let Some(c) = chunk_any.downcast_ref::<ChunkSelectiveAck>() {
2255            match self.handle_sack(c, now) {
2256                Ok(packets) => packets,
2257                Err(err) => {
2258                    // RFC 9260 6.2.1, 12.4: a SACK that acknowledges a TSN this side never
2259                    // sent is a protocol violation, and the association is aborted. It was
2260                    // closed without telling the peer (or, for the cumulative TSN, ignored).
2261                    warn!("[{}] aborting on an invalid SACK: {}", self.side, err);
2262                    self.abort_with(
2263                        vec![Self::protocol_violation(
2264                            "SACK acknowledges a TSN that was not sent",
2265                        )],
2266                        AssociationError::TransportError,
2267                    )?;
2268                    return Ok(false);
2269                }
2270            }
2271        } else if let Some(c) = chunk_any.downcast_ref::<ChunkReconfig>() {
2272            self.handle_reconfig(c)?
2273        } else if let Some(c) = chunk_any.downcast_ref::<ChunkForwardTsn>() {
2274            self.handle_forward_tsn(c)?
2275        } else if let Some(c) = chunk_any.downcast_ref::<ChunkIForwardTsn>() {
2276            self.handle_i_forward_tsn(c)?
2277        } else if let Some(c) = chunk_any.downcast_ref::<ChunkShutdown>() {
2278            self.handle_shutdown(c, now)?
2279        } else if let Some(c) = chunk_any.downcast_ref::<ChunkShutdownAck>() {
2280            self.handle_shutdown_ack(c)?
2281        } else if let Some(c) = chunk_any.downcast_ref::<ChunkShutdownComplete>() {
2282            self.handle_shutdown_complete(c)?
2283        } else if chunk_any.downcast_ref::<ChunkPadding>().is_some() {
2284            // RFC 4820 section 3: the PAD chunk is discarded, and the rest of the packet is
2285            // processed.
2286            vec![]
2287        } else if let Some(c) = chunk_any.downcast_ref::<ChunkUnknown>() {
2288            return Ok(self.handle_unknown_chunk(c));
2289        } else {
2290            return Err(Error::ErrChunkTypeUnhandled);
2291        };
2292
2293        if !packets.is_empty() {
2294            let mut buf: VecDeque<_> = packets.into_iter().collect();
2295            self.control_queue.append(&mut buf);
2296            self.awake_write_loop();
2297        }
2298
2299        Ok(true)
2300    }
2301
2302    /// RFC 9260 3.2: a chunk of an unrecognized type is handled by the upper two bits of the
2303    /// type. Returns whether the chunks after it are processed.
2304    fn handle_unknown_chunk(&mut self, c: &ChunkUnknown) -> bool {
2305        debug!(
2306            "[{}] unrecognized chunk type {}: {}{}",
2307            self.side,
2308            c.typ.0,
2309            if c.stops_processing() { "stop" } else { "skip" },
2310            if c.is_reported() { ", report" } else { "" },
2311        );
2312        if c.is_reported()
2313            && let Ok(raw) = c.marshal()
2314        {
2315            // The cause holds the chunk: type, flags, length and value.
2316            self.report_error(ErrorCause {
2317                code: UNRECOGNIZED_CHUNK_TYPE,
2318                raw,
2319            });
2320        }
2321        !c.stops_processing()
2322    }
2323
2324    /// RFC 9260 3.3.2, 3.3.3: what follows the discarding of an INIT or INIT ACK that failed
2325    /// its checks. A zero Initiate Tag in an INIT is discarded silently. The other failures
2326    /// (a_rwnd below 1500, no outbound or no inbound streams) are answered with an ABORT sent
2327    /// to the chunk's Initiate Tag. The state of an existing association does not change,
2328    /// with the one exception the RFC makes: an INIT ACK in COOKIE-WAIT with a zero Initiate
2329    /// Tag or no streams is the answer to this side's INIT, and destroys the TCB.
2330    fn refuse_invalid_init(&mut self, p: &Packet, c: &ChunkInit, err: &Error) {
2331        let cause = ErrorCause {
2332            code: INVALID_MANDATORY_PARAMETER,
2333            ..Default::default()
2334        };
2335        let ends_handshake = c.is_ack
2336            && self.state() == AssociationState::CookieWait
2337            && (c.initiate_tag == 0 || c.num_outbound_streams == 0 || c.num_inbound_streams == 0);
2338        let abort = if c.initiate_tag != 0 {
2339            Some(self.abort_packet(c.initiate_tag, false, vec![cause]))
2340        } else if ends_handshake {
2341            // The peer gave no tag to send to: its own packet's tag is reflected.
2342            Some(self.abort_packet(p.common_header.verification_tag, true, vec![cause]))
2343        } else {
2344            None
2345        };
2346        if c.is_ack && self.state() != AssociationState::CookieWait {
2347            // RFC 9260 3.3.3: outside COOKIE-WAIT such an INIT ACK is discarded silently.
2348            return;
2349        }
2350        if let Some(mut abort) = abort {
2351            if !c.is_ack {
2352                // The answer to an INIT goes between the ports its packet came between.
2353                abort.common_header.source_port = p.common_header.destination_port;
2354                abort.common_header.destination_port = p.common_header.source_port;
2355            }
2356            self.control_queue.push_back(abort);
2357            self.awake_write_loop();
2358        }
2359        // An accepting association that was made for this INIT and has seen no valid one has
2360        // nothing to keep: it ends now and gives its place back.
2361        let unused_acceptor = !c.is_ack
2362            && self.side == Side::Server
2363            && self.state() == AssociationState::Closed
2364            && self.cookie_tcb.is_none();
2365        if ends_handshake || unused_acceptor {
2366            let reason = AssociationError::HandshakeFailed(err.to_string());
2367            self.error = Some(reason.clone());
2368            let _ = self.close(reason);
2369        }
2370    }
2371
2372    /// RFC 9260 3.3.10: an ERROR is not fatal in itself. One cause is acted on: "Stale Cookie
2373    /// Error" in COOKIE-ECHOED (5.2.6), where the cookie this side echoed had outlived its
2374    /// lifetime. The setup is tried again with a new INIT, a bounded number of times.
2375    fn handle_error(&mut self, c: &ChunkError, now: Instant) {
2376        // RFC 9260 11.2.5 COMMUNICATION ERROR: the causes the peer's ERROR chunk carried.
2377        if !self.ended {
2378            self.events.push_back(Event::CommunicationError {
2379                causes: c
2380                    .error_causes
2381                    .iter()
2382                    .map(|e| (e.code, e.raw.clone()))
2383                    .collect(),
2384            });
2385        }
2386        // RFC 3758 3.3.3: a peer that reports the Forward-TSN-Supported parameter as
2387        // unrecognized does not do PR-SCTP: no FORWARD TSN for the life of the association.
2388        if c.error_causes
2389            .iter()
2390            .any(|e| e.code == UNRECOGNIZED_PARAMETERS && names_forward_tsn_supported(&e.raw))
2391            && self.use_forward_tsn
2392        {
2393            warn!("[{}] the peer does not support PR-SCTP", self.side);
2394            self.use_forward_tsn = false;
2395        }
2396        if self.state() != AssociationState::CookieEchoed
2397            || !c.error_causes.iter().any(|e| e.code == STALE_COOKIE_ERROR)
2398        {
2399            return;
2400        }
2401        self.timers.stop(Timer::T1Cookie);
2402        self.stored_cookie_echo = None;
2403        self.stale_cookie_restarts += 1;
2404        if self.stale_cookie_restarts > self.timers.max_retrans(Timer::T1Init) {
2405            let reason =
2406                AssociationError::HandshakeFailed(Error::ErrHandshakeCookieEcho.to_string());
2407            self.error = Some(reason.clone());
2408            let _ = self.close(reason);
2409            return;
2410        }
2411        debug!("[{}] stale cookie: sending a new INIT", self.side);
2412        // What the INIT ACK said is void with its cookie.
2413        self.peer_verification_tag = 0;
2414        let mut init = ChunkInit {
2415            initial_tsn: self.my_next_tsn,
2416            num_outbound_streams: self.configured_outbound_streams,
2417            num_inbound_streams: self.configured_inbound_streams,
2418            initiate_tag: self.my_verification_tag,
2419            advertised_receiver_window_credit: self.max_receive_buffer_size,
2420            ..Default::default()
2421        };
2422        init.announce_extensions(
2423            self.partial_reliability_enabled,
2424            self.interleaving_enabled,
2425            self.zero_checksum_enabled,
2426        );
2427        // RFC 9260 5.2.6: "The endpoint MAY add a Cookie Preservative parameter requesting
2428        // an extension to the lifetime of the State Cookie. When calculating the time
2429        // extension, an implementation SHOULD use the RTT information measured based on the
2430        // previous COOKIE ECHO / ERROR exchange and SHOULD add no more than 1 second beyond
2431        // the measured RTT". The increment is what the cookie was late by (the Measure of
2432        // Staleness, in microseconds), at least that round trip and at most a second more.
2433        let rtt_ms = self
2434            .cookie_echo_sent_at
2435            .take()
2436            .map_or(0, |sent| now.saturating_duration_since(sent).as_millis())
2437            .min(u128::from(u32::MAX)) as u32;
2438        let staleness_ms = c
2439            .error_causes
2440            .iter()
2441            .find(|e| e.code == STALE_COOKIE_ERROR)
2442            .and_then(|e| e.raw.get(..4))
2443            .map_or(0, |b| {
2444                u32::from_be_bytes([b[0], b[1], b[2], b[3]]).div_ceil(1000)
2445            });
2446        let increment = staleness_ms
2447            .max(rtt_ms)
2448            .min(rtt_ms.saturating_add(1000))
2449            .max(1);
2450        init.params.push(Box::new(
2451            crate::param::param_cookie_preservative::ParamCookiePreservative {
2452                suggested_increment_ms: increment,
2453            },
2454        ));
2455        self.stored_init = Some(init);
2456        self.set_state(AssociationState::CookieWait);
2457        let _ = self.send_init();
2458        self.timers
2459            .start(Timer::T1Init, now, self.rto_mgr.get_rto());
2460    }
2461
2462    /// Reads the optional parameters of a received INIT or INIT ACK (RFC 9260 3.3.2, 3.3.3).
2463    ///
2464    /// An unrecognized parameter is handled by the upper two bits of its type (RFC 9260
2465    /// 3.2.1): it ends the processing of the parameters after it or is skipped, and is
2466    /// reported or not.
2467    fn process_handshake_params(&self, params: &[Box<dyn Param>]) -> HandshakeParams {
2468        let mut out = HandshakeParams::default();
2469        for param in params {
2470            let any = param.as_any();
2471            if let Some(v) = any.downcast_ref::<ParamStateCookie>() {
2472                out.cookie = Some(v.cookie.clone());
2473            } else if let Some(v) = any.downcast_ref::<ParamSupportedExtensions>() {
2474                if v.chunk_types.contains(&CT_FORWARD_TSN) {
2475                    out.forward_tsn = true;
2476                }
2477                if v.chunk_types.contains(&CT_RECONFIG) {
2478                    out.reconfig = true;
2479                }
2480                if v.chunk_types.contains(&CT_I_DATA) {
2481                    out.i_data = true;
2482                }
2483                if v.chunk_types.contains(&CT_I_FORWARD_TSN) {
2484                    out.i_forward_tsn = true;
2485                }
2486            } else if any.downcast_ref::<ParamForwardTsnSupported>().is_some() {
2487                // RFC 3758 3.3.1: this parameter alone announces PR-SCTP.
2488                out.forward_tsn = true;
2489            } else if let Some(v) = any.downcast_ref::<ParamZeroChecksumAcceptable>() {
2490                // RFC 9653 4: the parameter appears once; a second one changes nothing.
2491                out.zero_checksum_edmid.get_or_insert(v.edmid);
2492            } else if let Some(v) = any.downcast_ref::<ParamUnknown>() {
2493                if v.typ() == PARAM_HOST_NAME_ADDRESS {
2494                    out.host_name = param.marshal().ok();
2495                    continue;
2496                }
2497                if v.typ() == UNRECOGNIZED_PARAMETER && names_forward_tsn_supported(v.value()) {
2498                    out.forward_tsn_rejected = true;
2499                }
2500                if IGNORED_HANDSHAKE_PARAMS.contains(&v.typ()) {
2501                    continue;
2502                }
2503                if v.is_reported()
2504                    && let Ok(raw) = param.marshal()
2505                {
2506                    out.unrecognized.push(raw);
2507                }
2508                if v.stops_processing() {
2509                    break;
2510                }
2511            }
2512        }
2513        out
2514    }
2515
2516    fn handle_init(&mut self, p: &Packet, i: &ChunkInit, now: Instant) -> Result<Vec<Packet>> {
2517        let state = self.state();
2518        debug!("[{}] chunkInit received in state '{}'", self.side, state);
2519
2520        if state == AssociationState::ShutdownAckSent {
2521            // RFC 9260 9.2: an INIT in SHUTDOWN-ACK-SENT (the SHUTDOWN COMPLETE was lost and
2522            // the peer starts over) is discarded and the SHUTDOWN ACK sent again.
2523            self.will_send_shutdown_ack = true;
2524            self.awake_write_loop();
2525            return Ok(vec![]);
2526        }
2527        if state != AssociationState::Closed
2528            && state != AssociationState::CookieWait
2529            && state != AssociationState::CookieEchoed
2530        {
2531            // RFC 9260 5.2.2: an unexpected INIT is answered and changes nothing. It used to
2532            // be an error, and an error closed the association: a late copy of the peer's own
2533            // INIT ended an established association.
2534            return Ok(vec![self.answer_unexpected_init(i, now)]);
2535        }
2536
2537        let params = self.process_handshake_params(&i.params);
2538        if let Some(host_name) = params.host_name {
2539            // RFC 9260 5.1.2: an INIT with a Host Name Address is answered with an ABORT.
2540            debug!("[{}] INIT with a Host Name Address: ABORT", self.side);
2541            let mut abort = self.abort_packet(
2542                i.initiate_tag,
2543                false,
2544                vec![ErrorCause {
2545                    code: UNRESOLVABLE_ADDRESS,
2546                    raw: host_name,
2547                }],
2548            );
2549            abort.common_header.source_port = p.common_header.destination_port;
2550            abort.common_header.destination_port = p.common_header.source_port;
2551            if state == AssociationState::Closed && self.cookie_tcb.is_none() {
2552                let reason =
2553                    AssociationError::HandshakeFailed(Error::ErrHandshakeInitAck.to_string());
2554                self.error = Some(reason.clone());
2555                self.close(reason)?;
2556            }
2557            return Ok(vec![abort]);
2558        }
2559
2560        // RFC 9260 5.1.1: this side sends on min(own OS, peer's MIS) streams and receives on
2561        // min(own MIS, peer's OS). Taken from the configured counts each time, so an INIT sent
2562        // again with other values is not narrowed by the one before it.
2563        let inbound_streams =
2564            std::cmp::min(i.num_outbound_streams, self.configured_inbound_streams);
2565        let outbound_streams =
2566            std::cmp::min(i.num_inbound_streams, self.configured_outbound_streams);
2567        let source_port = p.common_header.destination_port;
2568        let destination_port = p.common_header.source_port;
2569
2570        // A State Cookie for this INIT: a new one for a new attempt (another Initiate Tag) or
2571        // when the one in hand has outlived its lifetime, the same one for an INIT sent again,
2572        // so that the cookie of an INIT ACK already under way stays good.
2573        // RFC 9260 5.2.1, 5.2.2: the Tie-Tags are 0 for an INIT in CLOSED or COOKIE-WAIT, and
2574        // this association's in COOKIE-ECHOED.
2575        let tie_tags = if state == AssociationState::CookieEchoed {
2576            self.tie_tags()
2577        } else {
2578            (0, 0)
2579        };
2580        let reuse = self.my_cookie.is_some()
2581            && state != AssociationState::CookieEchoed
2582            && self.cookie_tcb.as_ref().is_some_and(|tcb| {
2583                tcb.peer_verification_tag == i.initiate_tag
2584                    && now.saturating_duration_since(tcb.created_at) < self.valid_cookie_life
2585            });
2586        let created_at = match (&self.cookie_tcb, reuse) {
2587            (Some(tcb), true) => tcb.created_at,
2588            _ => now,
2589        };
2590        let tcb = CookieTcb {
2591            created_at,
2592            peer_verification_tag: i.initiate_tag,
2593            peer_initial_tsn: i.initial_tsn,
2594            peer_rwnd: i.advertised_receiver_window_credit,
2595            inbound_streams,
2596            outbound_streams,
2597            use_forward_tsn: self.negotiated_partial_reliability(&params),
2598            use_interleaving: self.negotiated_interleaving(&params),
2599            reconfig: params.reconfig,
2600            send_zero_checksum: self.may_send_zero_checksum(&params),
2601            source_port,
2602            destination_port,
2603        };
2604
2605        // RFC 9260 5.2.1: in COOKIE-WAIT and COOKIE-ECHOED the INIT is answered with this
2606        // side's own INIT parameters and nothing in the TCB changes: what the INIT said is
2607        // kept with the cookie and taken when the cookie comes back. In CLOSED the accepting
2608        // association has no TCB to protect, and takes it now.
2609        if state == AssociationState::Closed {
2610            self.apply_cookie_tcb(&tcb);
2611            if !self.use_forward_tsn {
2612                warn!("[{}] not using ForwardTSN (on init)", self.side);
2613            }
2614        }
2615        if !reuse {
2616            // RFC 9260 5.1.3: the cookie holds what the association is made from, the time
2617            // it was made, and a MAC over both. Without a crypto provider to make the MAC
2618            // with, it is random bytes this association remembers.
2619            let sealed = self.cookie_signer.as_ref().and_then(|signer| {
2620                signer.seal(&self.cookie_fields(&tcb, signer.timestamp(now), tie_tags))
2621            });
2622            self.my_cookie = Some(match sealed {
2623                Some(cookie) => ParamStateCookie { cookie },
2624                None => ParamStateCookie::random(&self.random),
2625            });
2626        }
2627        self.cookie_tcb = Some(tcb);
2628
2629        let mut init_ack = ChunkInit {
2630            is_ack: true,
2631            initial_tsn: self.my_next_tsn,
2632            num_outbound_streams: outbound_streams,
2633            num_inbound_streams: inbound_streams,
2634            initiate_tag: self.my_verification_tag,
2635            advertised_receiver_window_credit: self.max_receive_buffer_size,
2636            ..Default::default()
2637        };
2638
2639        if let Some(my_cookie) = &self.my_cookie {
2640            init_ack.params = vec![Box::new(my_cookie.clone())];
2641        }
2642
2643        // RFC 9260 3.2.2, 3.3.3: the unrecognized parameters the INIT asked to hear about go
2644        // back in the INIT ACK, each in an Unrecognized Parameter parameter.
2645        for raw in params.unrecognized {
2646            init_ack
2647                .params
2648                .push(Box::new(ParamUnknown::new(UNRECOGNIZED_PARAMETER, raw)));
2649        }
2650
2651        init_ack.announce_extensions(
2652            self.partial_reliability_enabled,
2653            self.interleaving_enabled,
2654            self.zero_checksum_enabled,
2655        );
2656
2657        if state == AssociationState::Closed {
2658            // The accepting side holds this association from the INIT on. If no COOKIE ECHO
2659            // follows it must not be held for ever: every INIT restarts the wait.
2660            self.timers.stop(Timer::HalfOpen);
2661            self.timers.start(Timer::HalfOpen, now, HALF_OPEN_LIFETIME);
2662        }
2663
2664        Ok(vec![Packet {
2665            common_header: CommonHeader {
2666                verification_tag: i.initiate_tag,
2667                source_port,
2668                destination_port,
2669            },
2670            chunks: vec![Box::new(init_ack)],
2671        }])
2672    }
2673
2674    /// What a State Cookie made at `created_ms` says for `tcb` (RFC 9260 5.1.3).
2675    fn cookie_fields(
2676        &self,
2677        tcb: &CookieTcb,
2678        created_ms: u64,
2679        tie_tags: (u32, u32),
2680    ) -> CookieFields {
2681        CookieFields {
2682            key_id: 0,
2683            created_ms,
2684            my_tag: self.my_verification_tag,
2685            my_initial_tsn: self.my_next_tsn,
2686            peer_tag: tcb.peer_verification_tag,
2687            peer_initial_tsn: tcb.peer_initial_tsn,
2688            peer_rwnd: tcb.peer_rwnd,
2689            inbound_streams: tcb.inbound_streams,
2690            outbound_streams: tcb.outbound_streams,
2691            use_forward_tsn: tcb.use_forward_tsn,
2692            use_interleaving: tcb.use_interleaving,
2693            reconfig: tcb.reconfig,
2694            send_zero_checksum: tcb.send_zero_checksum,
2695            source_port: tcb.source_port,
2696            destination_port: tcb.destination_port,
2697            local_tie_tag: tie_tags.0,
2698            peer_tie_tag: tie_tags.1,
2699        }
2700    }
2701
2702    /// This association's Tie-Tags, drawn the first time they are needed (RFC 9260 5.2.2:
2703    /// "populated with a random value other than 0").
2704    fn tie_tags(&mut self) -> (u32, u32) {
2705        if self.local_tie_tag == 0 {
2706            self.local_tie_tag = self.random.nonzero_u32();
2707            self.peer_tie_tag = self.random.nonzero_u32();
2708        }
2709        (self.local_tie_tag, self.peer_tie_tag)
2710    }
2711
2712    /// RFC 9653 5.2: this side sends a zero checksum when the peer announced that it takes
2713    /// one for an error detection method this side uses, which is SCTP over DTLS, and the
2714    /// application said the association runs over DTLS (`TransportConfig::with_zero_checksum`).
2715    fn may_send_zero_checksum(&self, params: &HandshakeParams) -> bool {
2716        self.zero_checksum_enabled && params.zero_checksum_edmid == Some(EDMID_SCTP_OVER_DTLS)
2717    }
2718
2719    /// Whether packets are sent with a zero checksum (RFC 9653): both sides announced that
2720    /// they take one over DTLS.
2721    pub fn zero_checksum(&self) -> bool {
2722        self.send_zero_checksum
2723    }
2724
2725    /// Serializes a packet. Its CRC32c is left out when the peer takes a zero checksum,
2726    /// except where RFC 9653 5.2 asks for a correct one: a packet with an INIT or a COOKIE
2727    /// ECHO, and one that answers an out-of-the-blue packet (it reflects a tag, or does not
2728    /// carry the peer's).
2729    fn marshal_packet(&self, p: &Packet) -> Result<Bytes> {
2730        let zero = self.send_zero_checksum
2731            && p.common_header.verification_tag == self.peer_verification_tag
2732            && p.chunks.iter().all(|c| {
2733                let any = c.as_any();
2734                !any.is::<ChunkCookieEcho>()
2735                    && any.downcast_ref::<ChunkInit>().is_none_or(|i| i.is_ack)
2736                    && any
2737                        .downcast_ref::<ChunkAbort>()
2738                        .is_none_or(|a| !a.tag_reflected)
2739                    && any
2740                        .downcast_ref::<ChunkShutdownComplete>()
2741                        .is_none_or(|s| !s.tag_reflected)
2742            });
2743        p.marshal_with(zero)
2744    }
2745
2746    /// Has this association make its State Cookies with a MAC.
2747    pub(crate) fn set_cookie_signer(&mut self, signer: Arc<CookieSigner>) {
2748        self.cookie_signer = Some(signer);
2749    }
2750
2751    /// Makes this association what it was when it answered an INIT with the State Cookie
2752    /// `cookie`, whose MAC the endpoint has verified: nothing was kept since, and the
2753    /// cookie says it all (RFC 9260 5.1.3, 5.1.5). The COOKIE ECHO is then handled as if the
2754    /// association had been there all along.
2755    pub(crate) fn restore_from_cookie(
2756        &mut self,
2757        fields: &CookieFields,
2758        cookie: Bytes,
2759        signer: Arc<CookieSigner>,
2760        now: Instant,
2761    ) {
2762        let tsn = fields.my_initial_tsn;
2763        self.my_next_tsn = tsn;
2764        self.my_next_rsn = tsn;
2765        self.min_tsn2measure_rtt = tsn;
2766        self.cumulative_tsn_ack_point = tsn.wrapping_sub(1);
2767        self.advanced_peer_tsn_ack_point = tsn.wrapping_sub(1);
2768        let age = signer.age(fields, now);
2769        let tcb = CookieTcb {
2770            created_at: now.checked_sub(age).unwrap_or(now),
2771            peer_verification_tag: fields.peer_tag,
2772            peer_initial_tsn: fields.peer_initial_tsn,
2773            peer_rwnd: fields.peer_rwnd,
2774            inbound_streams: fields.inbound_streams,
2775            outbound_streams: fields.outbound_streams,
2776            use_forward_tsn: fields.use_forward_tsn,
2777            use_interleaving: fields.use_interleaving,
2778            reconfig: fields.reconfig,
2779            send_zero_checksum: fields.send_zero_checksum,
2780            source_port: fields.source_port,
2781            destination_port: fields.destination_port,
2782        };
2783        self.apply_cookie_tcb(&tcb);
2784        self.cookie_tcb = Some(tcb);
2785        self.my_cookie = Some(ParamStateCookie { cookie });
2786        self.cookie_signer = Some(signer);
2787    }
2788
2789    /// Takes into the TCB what the peer's INIT said (RFC 9260 5.1 B, 5.2.4 B).
2790    fn apply_cookie_tcb(&mut self, tcb: &CookieTcb) {
2791        self.my_max_num_inbound_streams = tcb.inbound_streams;
2792        self.my_max_num_outbound_streams = tcb.outbound_streams;
2793        self.peer_verification_tag = tcb.peer_verification_tag;
2794        self.source_port = tcb.source_port;
2795        self.destination_port = tcb.destination_port;
2796
2797        // 13.2 This is the last TSN received in sequence.  This value
2798        // is set initially by taking the peer's initial TSN,
2799        // received in the INIT or INIT ACK chunk, and
2800        // subtracting one from it.
2801        self.peer_last_tsn = tcb.peer_initial_tsn.wrapping_sub(1);
2802
2803        // Adopt the peer's advertised receive window and seed ssthresh from it,
2804        // mirroring handle_init_ack (and Pion's shared init path). RFC 4960
2805        // §7.2.1 (Slow-Start) permits initialising ssthresh to the advertised
2806        // receiver window; without this the answerer keeps ssthresh at its
2807        // initial 0, so cwnd never starts below it, slow-start never runs, and
2808        // cwnd only grows linearly under congestion avoidance (§7.2.2).
2809        self.rwnd = tcb.peer_rwnd;
2810        debug!("[{}] initial rwnd={}", self.side, self.rwnd);
2811        self.ssthresh = self.rwnd;
2812        self.use_forward_tsn = tcb.use_forward_tsn;
2813        self.set_interleaving(tcb.use_interleaving);
2814        self.peer_supports_reconfig = tcb.reconfig;
2815        self.send_zero_checksum = tcb.send_zero_checksum;
2816        // RFC 6525 4.1: the peer's request sequence numbers start at its initial TSN.
2817        self.peer_rsn_window = Some((tcb.peer_initial_tsn, tcb.peer_initial_tsn));
2818    }
2819
2820    /// RFC 9260 5.2.2: the INIT ACK for an INIT that arrives while the association exists. It
2821    /// goes to the INIT's Initiate Tag and carries a new one of its own; the association and
2822    /// its TCB stay as they are.
2823    ///
2824    /// Its State Cookie stands for a new association with the peer as the INIT describes it,
2825    /// this side's new tag and initial TSN, and this association's Tie-Tags: a COOKIE ECHO
2826    /// that brings it back is a restart (5.2.4 action A). With a cookie signer it is sealed
2827    /// and nothing is kept; without one it is kept beside the association's own cookie.
2828    fn answer_unexpected_init(&mut self, i: &ChunkInit, now: Instant) -> Packet {
2829        let initiate_tag = self.random.nonzero_u32();
2830        let initial_tsn = self.random.nonzero_u32();
2831        let tie_tags = self.tie_tags();
2832        let params = self.process_handshake_params(&i.params);
2833        // 5.2.2: the other parameters are the association's.
2834        let tcb = CookieTcb {
2835            created_at: now,
2836            peer_verification_tag: i.initiate_tag,
2837            peer_initial_tsn: i.initial_tsn,
2838            peer_rwnd: i.advertised_receiver_window_credit,
2839            inbound_streams: std::cmp::min(i.num_outbound_streams, self.my_max_num_inbound_streams),
2840            outbound_streams: std::cmp::min(
2841                i.num_inbound_streams,
2842                self.my_max_num_outbound_streams,
2843            ),
2844            use_forward_tsn: self.negotiated_partial_reliability(&params),
2845            use_interleaving: self.negotiated_interleaving(&params),
2846            reconfig: params.reconfig,
2847            send_zero_checksum: self.may_send_zero_checksum(&params),
2848            source_port: self.source_port,
2849            destination_port: self.destination_port,
2850        };
2851        let fields = |created_ms| {
2852            let mut fields = self.cookie_fields(&tcb, created_ms, tie_tags);
2853            fields.my_tag = initiate_tag;
2854            fields.my_initial_tsn = initial_tsn;
2855            fields
2856        };
2857        let cookie = match self.cookie_signer.clone() {
2858            Some(signer) => {
2859                let sealed = signer.seal(&fields(signer.timestamp(now)));
2860                sealed.unwrap_or_else(|| ParamStateCookie::random(&self.random).cookie)
2861            }
2862            None => {
2863                let cookie = ParamStateCookie::random(&self.random).cookie;
2864                let kept = fields(0);
2865                self.restart_cookie = Some((cookie.clone(), kept, now));
2866                cookie
2867            }
2868        };
2869        let mut init_ack = ChunkInit {
2870            is_ack: true,
2871            initial_tsn,
2872            num_outbound_streams: self.my_max_num_outbound_streams,
2873            num_inbound_streams: self.my_max_num_inbound_streams,
2874            initiate_tag,
2875            advertised_receiver_window_credit: self.max_receive_buffer_size,
2876            params: vec![Box::new(ParamStateCookie { cookie })],
2877        };
2878        init_ack.announce_extensions(
2879            self.partial_reliability_enabled,
2880            self.interleaving_enabled,
2881            self.zero_checksum_enabled,
2882        );
2883        Packet {
2884            common_header: CommonHeader {
2885                verification_tag: i.initiate_tag,
2886                source_port: self.source_port,
2887                destination_port: self.destination_port,
2888            },
2889            chunks: vec![Box::new(init_ack)],
2890        }
2891    }
2892
2893    /// The cookie of a COOKIE ECHO, if it is one of this association's restart cookies
2894    /// (RFC 9260 5.2.4, Table 12 row A): the tags of a new association, both unlike this
2895    /// association's, and this association's Tie-Tags. With when it was made.
2896    fn restart_cookie_fields(
2897        &self,
2898        cookie: &[u8],
2899        now: Instant,
2900    ) -> Option<(CookieFields, Instant)> {
2901        if self.local_tie_tag == 0
2902            || !matches!(
2903                self.state(),
2904                AssociationState::Established
2905                    | AssociationState::ShutdownPending
2906                    | AssociationState::ShutdownSent
2907                    | AssociationState::ShutdownReceived
2908                    | AssociationState::ShutdownAckSent
2909            )
2910        {
2911            return None;
2912        }
2913        let (fields, created_at) = match &self.cookie_signer {
2914            Some(signer) => {
2915                let fields = signer.open(cookie)?;
2916                let age = signer.age(&fields, now);
2917                (fields, now.checked_sub(age).unwrap_or(now))
2918            }
2919            None => {
2920                let (kept, fields, created_at) = self.restart_cookie.as_ref()?;
2921                if !constant_time_eq(kept, cookie) {
2922                    return None;
2923                }
2924                (fields.clone(), *created_at)
2925            }
2926        };
2927        let row_a = fields.my_tag != self.my_verification_tag
2928            && fields.peer_tag != self.peer_verification_tag
2929            && fields.local_tie_tag == self.local_tie_tag
2930            && fields.peer_tie_tag == self.peer_tie_tag;
2931        row_a.then_some((fields, created_at))
2932    }
2933
2934    /// RFC 9260 5.2.4 action A: the peer restarted. Handled as an ABORT followed by a new
2935    /// COOKIE ECHO: everything of the old association goes (streams, queues, timers, the
2936    /// reconfiguration state; the DATA is not retained, which 5.2.4 leaves open: a peer
2937    /// that restarted has none of the old streams), the TCB comes from the cookie,
2938    /// congestion control and the RTO from their initial values, and the association is
2939    /// ESTABLISHED. In SHUTDOWN-ACK-SENT no new association is made: the SHUTDOWN ACK is
2940    /// sent again with an ERROR "Cookie Received While Shutting Down".
2941    fn handle_restart_cookie(
2942        &mut self,
2943        p: &Packet,
2944        fields: CookieFields,
2945        created_at: Instant,
2946        now: Instant,
2947    ) -> Result<Vec<Packet>> {
2948        // 5.1.5 3): the packet's tag and ports are those the cookie was made for.
2949        if p.common_header.verification_tag != fields.my_tag
2950            || p.common_header.source_port != fields.destination_port
2951            || p.common_header.destination_port != fields.source_port
2952        {
2953            self.discard_rest_of_packet = true;
2954            return Ok(vec![]);
2955        }
2956        let to_peer = |chunk: Box<dyn Chunk + Send + Sync>| Packet {
2957            common_header: CommonHeader {
2958                verification_tag: fields.peer_tag,
2959                source_port: fields.source_port,
2960                destination_port: fields.destination_port,
2961            },
2962            chunks: vec![chunk],
2963        };
2964        // 5.2.4 3): a stale restart cookie (its tags are not the association's) is refused
2965        // with an ERROR "Stale Cookie".
2966        let age = now.saturating_duration_since(created_at);
2967        if age > self.valid_cookie_life {
2968            let staleness =
2969                u32::try_from((age - self.valid_cookie_life).as_micros()).unwrap_or(u32::MAX);
2970            self.discard_rest_of_packet = true;
2971            return Ok(vec![to_peer(Box::new(ChunkError {
2972                error_causes: vec![ErrorCause {
2973                    code: STALE_COOKIE_ERROR,
2974                    raw: Bytes::copy_from_slice(&staleness.to_be_bytes()),
2975                }],
2976            }))]);
2977        }
2978        if self.state() == AssociationState::ShutdownAckSent {
2979            debug!(
2980                "[{}] COOKIE ECHO of a restart in SHUTDOWN-ACK-SENT: no new association",
2981                self.side
2982            );
2983            self.discard_rest_of_packet = true;
2984            self.will_send_shutdown_ack = true;
2985            self.awake_write_loop();
2986            return Ok(vec![to_peer(Box::new(ChunkError {
2987                error_causes: vec![ErrorCause {
2988                    code: COOKIE_RECEIVED_WHILE_SHUTTING_DOWN,
2989                    raw: Bytes::new(),
2990                }],
2991            }))]);
2992        }
2993        if !self.restart(&fields, created_at, now) {
2994            self.discard_rest_of_packet = true;
2995            return Ok(vec![]);
2996        }
2997        Ok(vec![Packet {
2998            common_header: CommonHeader {
2999                verification_tag: self.peer_verification_tag,
3000                source_port: self.source_port,
3001                destination_port: self.destination_port,
3002            },
3003            chunks: vec![Box::new(ChunkCookieAck {})],
3004        }])
3005    }
3006
3007    /// Replaces this association with the one the restart cookie `fields` describes.
3008    /// Returns false when it cannot (an association not made by `new`).
3009    fn restart(&mut self, fields: &CookieFields, created_at: Instant, now: Instant) -> bool {
3010        let Some(config) = self.transport_config.clone() else {
3011            return false;
3012        };
3013        let old_tag = self.my_verification_tag;
3014        let old_peer_tag = self.peer_verification_tag;
3015        let random = std::mem::take(&mut self.random);
3016        let mut fresh = Association::new(
3017            None,
3018            config,
3019            self.max_payload_size,
3020            fields.my_tag,
3021            self.remote_addr,
3022            self.local_addr,
3023            self.transport_protocol,
3024            now,
3025            random,
3026        );
3027        // `new` made an initiating association: it is an accepting one, made from the
3028        // cookie, as `Endpoint::accept_cookie_echo` makes one.
3029        fresh.side = self.side;
3030        fresh.stored_init = None;
3031        fresh.control_queue.clear();
3032        fresh.timers.stop(Timer::T1Init);
3033        fresh.timers.stop(Timer::HalfOpen);
3034        fresh.mtu = self.mtu;
3035        // The path is the same: its discovery starts over from the same base.
3036        if let Some(pmtud) = &self.pmtud {
3037            fresh.pmtud = Some(pmtud::PathMtuDiscovery::new(*pmtud.config(), pmtud.base()));
3038            fresh.use_path_mtu(pmtud.base(), true);
3039        }
3040        fresh.cookie_signer = self.cookie_signer.clone();
3041        let tsn = fields.my_initial_tsn;
3042        fresh.my_next_tsn = tsn;
3043        fresh.my_next_rsn = tsn;
3044        fresh.min_tsn2measure_rtt = tsn;
3045        fresh.cumulative_tsn_ack_point = tsn.wrapping_sub(1);
3046        fresh.advanced_peer_tsn_ack_point = tsn.wrapping_sub(1);
3047        let tcb = CookieTcb {
3048            created_at,
3049            peer_verification_tag: fields.peer_tag,
3050            peer_initial_tsn: fields.peer_initial_tsn,
3051            peer_rwnd: fields.peer_rwnd,
3052            inbound_streams: fields.inbound_streams,
3053            outbound_streams: fields.outbound_streams,
3054            use_forward_tsn: fields.use_forward_tsn,
3055            use_interleaving: fields.use_interleaving,
3056            reconfig: fields.reconfig,
3057            send_zero_checksum: fields.send_zero_checksum,
3058            source_port: fields.source_port,
3059            destination_port: fields.destination_port,
3060        };
3061        fresh.apply_cookie_tcb(&tcb);
3062        fresh.cookie_tcb = Some(tcb);
3063        fresh.handshake_completed = true;
3064        fresh.set_state(AssociationState::Established);
3065        fresh.start_heartbeat_timer(now);
3066        // 5.1.5 7): DATA that came with the COOKIE ECHO is acknowledged at once.
3067        fresh.sack_packet_immediately = true;
3068        // What the application has not read of the old association's events stays, and the
3069        // restart follows it.
3070        // The old association's streams are gone: what each had sent is kept, for the
3071        // application to settle its own accounts of them (`streams_lost_in_restart`,
3072        // `stream_bytes_dequeued`).
3073        let mut lost: Vec<(StreamId, u64)> = self
3074            .streams
3075            .iter()
3076            .map(|(id, s)| (*id, s.bytes_dequeued))
3077            .collect();
3078        lost.sort_unstable();
3079        fresh.closed_stream_bytes_dequeued = std::mem::take(&mut self.closed_stream_bytes_dequeued);
3080        fresh
3081            .closed_stream_bytes_dequeued
3082            .extend(lost.iter().copied());
3083        fresh.streams_lost_in_restart = lost;
3084        fresh.events = std::mem::take(&mut self.events);
3085        fresh.events.push_back(Event::Restarted);
3086        fresh.endpoint_events = std::mem::take(&mut self.endpoint_events);
3087        fresh
3088            .endpoint_events
3089            .push_back(EndpointEventInner::Retagged {
3090                old_local: old_tag,
3091                new_local: fields.my_tag,
3092                old_peer: old_peer_tag,
3093                new_peer: fields.peer_tag,
3094            });
3095        debug!(
3096            "[{}] the peer restarted the association: tag {:#x} -> {:#x}",
3097            self.side, old_tag, fields.my_tag
3098        );
3099        *self = fresh;
3100        true
3101    }
3102
3103    fn handle_init_ack(
3104        &mut self,
3105        p: &Packet,
3106        i: &ChunkInitAck,
3107        now: Instant,
3108    ) -> Result<Vec<Packet>> {
3109        let state = self.state();
3110        debug!("[{}] chunkInitAck received in state '{}'", self.side, state);
3111        if state != AssociationState::CookieWait {
3112            // RFC 4960
3113            // 5.2.3.  Unexpected INIT ACK
3114            //   If an INIT ACK is received by an endpoint in any state other than the
3115            //   COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
3116            //   An unexpected INIT ACK usually indicates the processing of an old or
3117            //   duplicated INIT chunk.
3118            return Ok(vec![]);
3119        }
3120
3121        // Checked before anything is taken from the chunk: an INIT ACK between other ports
3122        // is not this association's.
3123        if self.source_port != p.common_header.destination_port
3124            || self.destination_port != p.common_header.source_port
3125        {
3126            warn!("[{}] handle_init_ack: port mismatch", self.side);
3127            return Ok(vec![]);
3128        }
3129
3130        // RFC 9260 5.1.1: own OS against the peer's MIS, own MIS against the peer's OS.
3131        self.my_max_num_inbound_streams =
3132            std::cmp::min(i.num_outbound_streams, self.configured_inbound_streams);
3133        self.my_max_num_outbound_streams =
3134            std::cmp::min(i.num_inbound_streams, self.configured_outbound_streams);
3135        self.peer_verification_tag = i.initiate_tag;
3136        self.peer_last_tsn = i.initial_tsn.wrapping_sub(1);
3137
3138        self.rwnd = i.advertised_receiver_window_credit;
3139        debug!("[{}] initial rwnd={}", self.side, self.rwnd);
3140
3141        // RFC 4690 Sec 7.2.1
3142        //  o  The initial value of ssthresh MAY be arbitrarily high (for
3143        //     example, implementations MAY use the size of the receiver
3144        //     advertised window).
3145        self.ssthresh = self.rwnd;
3146        trace!(
3147            "[{}] updated cwnd={} ssthresh={} inflight={} (INI)",
3148            self.side,
3149            self.cwnd,
3150            self.ssthresh,
3151            self.inflight_queue.get_num_bytes()
3152        );
3153
3154        self.timers.stop(Timer::T1Init);
3155        self.stored_init = None;
3156
3157        let params = self.process_handshake_params(&i.params);
3158        // RFC 3758 3.3.2, 3.3.3: PR-SCTP is used when the peer announced it too, and not when
3159        // the peer reported this side's Forward-TSN-Supported parameter as unrecognized.
3160        self.use_forward_tsn = self.negotiated_partial_reliability(&params);
3161        self.set_interleaving(self.negotiated_interleaving(&params));
3162        self.send_zero_checksum = self.may_send_zero_checksum(&params);
3163        if !self.use_forward_tsn {
3164            warn!("[{}] not using ForwardTSN (on initAck)", self.side);
3165        }
3166        self.peer_supports_reconfig = params.reconfig;
3167        // RFC 6525 4.1: the peer's request sequence numbers start at its initial TSN.
3168        self.peer_rsn_window = Some((i.initial_tsn, i.initial_tsn));
3169
3170        if let Some(host_name) = params.host_name {
3171            // RFC 9260 3.3.3, 5.1.2: an INIT ACK with a Host Name Address is answered with
3172            // an ABORT, and the attempt is over.
3173            let reason = AssociationError::HandshakeFailed(Error::ErrHandshakeInitAck.to_string());
3174            self.error = Some(reason.clone());
3175            self.abort_with(
3176                vec![ErrorCause {
3177                    code: UNRESOLVABLE_ADDRESS,
3178                    raw: host_name,
3179                }],
3180                reason,
3181            )?;
3182            return Ok(vec![]);
3183        }
3184
3185        let Some(cookie) = params.cookie else {
3186            // RFC 9260 3.3.3: the State Cookie is mandatory. An INIT ACK without one cannot
3187            // be answered: ABORT "Missing Mandatory Parameter" (one parameter, type 7), and
3188            // the attempt is over.
3189            let mut raw = BytesMut::with_capacity(6);
3190            raw.extend_from_slice(&1u32.to_be_bytes());
3191            raw.extend_from_slice(&PARAM_STATE_COOKIE.to_be_bytes());
3192            let reason = AssociationError::HandshakeFailed(Error::ErrInitAckNoCookie.to_string());
3193            self.error = Some(reason.clone());
3194            self.abort_with(
3195                vec![ErrorCause {
3196                    code: MISSING_MANDATORY_PARAMETER,
3197                    raw: raw.freeze(),
3198                }],
3199                reason,
3200            )?;
3201            return Ok(vec![]);
3202        };
3203
3204        self.stored_cookie_echo = Some(ChunkCookieEcho { cookie });
3205
3206        if params.unrecognized.is_empty() {
3207            self.send_cookie_echo()?;
3208        } else {
3209            // RFC 9260 3.2.2, 3.3.3: the unrecognized parameters the INIT ACK asked to
3210            // hear about are reported in an ERROR chunk bundled with the COOKIE ECHO,
3211            // which stays the first chunk of the packet. A retransmission carries the
3212            // COOKIE ECHO alone.
3213            let mut raw = BytesMut::new();
3214            for (n, param) in params.unrecognized.iter().enumerate() {
3215                raw.extend_from_slice(param);
3216                if n + 1 != params.unrecognized.len() {
3217                    raw.extend_from_slice(&[0u8; 3][..get_padding_size(param.len())]);
3218                }
3219            }
3220            let error = ChunkError {
3221                error_causes: vec![ErrorCause {
3222                    code: UNRECOGNIZED_PARAMETERS,
3223                    raw: raw.freeze(),
3224                }],
3225            };
3226            let cookie_echo = self
3227                .stored_cookie_echo
3228                .clone()
3229                .ok_or(Error::ErrCookieEchoNotStoredToSend)?;
3230            let packet = self.create_packet(vec![Box::new(cookie_echo), Box::new(error)]);
3231            self.control_queue.push_back(packet);
3232            self.awake_write_loop();
3233        }
3234
3235        self.timers
3236            .start(Timer::T1Cookie, now, self.rto_mgr.get_rto());
3237        self.cookie_echo_sent_at = Some(now);
3238
3239        self.set_state(AssociationState::CookieEchoed);
3240
3241        Ok(vec![])
3242    }
3243
3244    fn handle_heartbeat(&self, c: &ChunkHeartbeat) -> Result<Vec<Packet>> {
3245        trace!("[{}] chunkHeartbeat", self.side);
3246        // RFC 9260 5.1 C: in COOKIE-WAIT and COOKIE-ECHOED, "until the COOKIE ACK chunk is
3247        // returned, the sender MUST NOT send any other packets to the peer" (than the INIT and
3248        // the COOKIE ECHO). A HEARTBEAT (or a path MTU probe) from a peer that is ESTABLISHED
3249        // while its COOKIE ACK to this side was lost is not answered: the answer told the peer
3250        // this side was up when it was not.
3251        if matches!(
3252            self.state(),
3253            AssociationState::CookieWait | AssociationState::CookieEchoed
3254        ) {
3255            debug!(
3256                "[{}] HEARTBEAT before the COOKIE ACK: not answered",
3257                self.side
3258            );
3259            return Ok(vec![]);
3260        }
3261        // RFC 9260 5.1 C: in COOKIE-WAIT and COOKIE-ECHOED, "until the COOKIE ACK chunk is
3262        // returned, the sender MUST NOT send any other packets to the peer" (than the INIT and
3263        // the COOKIE ECHO). A HEARTBEAT (or a path MTU probe) from a peer that is ESTABLISHED
3264        // while its COOKIE ACK to this side was lost is not answered: the answer also told the
3265        // peer this side was up when it was not.
3266        if matches!(
3267            self.state(),
3268            AssociationState::CookieWait | AssociationState::CookieEchoed
3269        ) {
3270            debug!(
3271                "[{}] HEARTBEAT before the COOKIE ACK: not answered",
3272                self.side
3273            );
3274            return Ok(vec![]);
3275        }
3276        if let Some(p) = c.params.first() {
3277            if let Some(hbi) = p.as_any().downcast_ref::<ParamHeartbeatInfo>() {
3278                return Ok(vec![Packet {
3279                    common_header: CommonHeader {
3280                        verification_tag: self.peer_verification_tag,
3281                        source_port: self.source_port,
3282                        destination_port: self.destination_port,
3283                    },
3284                    chunks: vec![Box::new(ChunkHeartbeatAck {
3285                        params: vec![Box::new(ParamHeartbeatInfo {
3286                            heartbeat_information: hbi.heartbeat_information.clone(),
3287                        })],
3288                    })],
3289                }]);
3290            } else {
3291                warn!(
3292                    "[{}] failed to handle Heartbeat, no ParamHeartbeatInfo",
3293                    self.side,
3294                );
3295            }
3296        }
3297
3298        Ok(vec![])
3299    }
3300
3301    /// RFC 9260 5.1.5 and 5.2.4: a COOKIE ECHO.
3302    ///
3303    /// An association handles the COOKIE ECHO for a cookie it sent itself and remembers
3304    /// (`my_cookie`, with what it stands for in `cookie_tcb`): the cookie echoed is compared
3305    /// with it in constant time, and its creation time and the peer's tag and ports are
3306    /// checked from the kept copy. That is so in two cases. Without a crypto provider
3307    /// (`ServerConfig::cookie_authentication`) the accepting association exists from the
3308    /// INIT on (see `HALF_OPEN_LIFETIME`) and the cookie is 32 random bytes. With one, the
3309    /// endpoint keeps nothing after the INIT ACK: the cookie is a MAC-protected TCB
3310    /// (`crate::cookie`), the endpoint verifies it and makes this association from it
3311    /// (`restore_from_cookie`) just before handing it the COOKIE ECHO, and the MAC is
3312    /// verified here once more.
3313    ///
3314    /// With one cookie per association there is no cookie whose tags differ from the TCB's,
3315    /// so of Table 12 only the actions for matching tags arise: B and D (enter or stay in
3316    /// ESTABLISHED, send COOKIE ACK) for the cookie in hand, and the silent discard of C for
3317    /// any other. Restarting an association (action A) is not supported.
3318    fn handle_cookie_echo(
3319        &mut self,
3320        p: &Packet,
3321        c: &ChunkCookieEcho,
3322        now: Instant,
3323    ) -> Result<Vec<Packet>> {
3324        let state = self.state();
3325        debug!("[{}] COOKIE-ECHO received in state '{}'", self.side, state);
3326
3327        // RFC 9260 5.2.4, Table 12 row A: the cookie of an INIT ACK that answered an
3328        // unexpected INIT, with this association's Tie-Tags: the peer restarted.
3329        if let Some((fields, created_at)) = self.restart_cookie_fields(&c.cookie, now) {
3330            return self.handle_restart_cookie(p, fields, created_at, now);
3331        }
3332
3333        // RFC 9260 5.1.5 2), 3): a cookie that is not the one sent, or that comes between
3334        // other ports, has its whole packet discarded, DATA included.
3335        let (Some(my_cookie), Some(tcb)) = (&self.my_cookie, self.cookie_tcb.clone()) else {
3336            debug!("[{}] COOKIE-ECHO received before initialization", self.side);
3337            self.discard_rest_of_packet = true;
3338            return Ok(vec![]);
3339        };
3340        // 5.1.5 1), 2): the MAC is computed over the cookie and compared with the one it
3341        // carries; a cookie that fails is discarded silently.
3342        if let Some(signer) = &self.cookie_signer
3343            && signer.open(&c.cookie).is_none()
3344        {
3345            debug!("[{}] COOKIE-ECHO: the MAC does not verify", self.side);
3346            self.discard_rest_of_packet = true;
3347            return Ok(vec![]);
3348        }
3349        if !constant_time_eq(&my_cookie.cookie, &c.cookie)
3350            || p.common_header.source_port != tcb.destination_port
3351            || p.common_header.destination_port != tcb.source_port
3352        {
3353            self.discard_rest_of_packet = true;
3354            return Ok(vec![]);
3355        }
3356
3357        match state {
3358            AssociationState::Closed
3359            | AssociationState::CookieWait
3360            | AssociationState::CookieEchoed => {
3361                // RFC 9260 5.1.5 4): past its lifetime the cookie is refused with an ERROR
3362                // "Stale Cookie", which tells the peer by how many microseconds.
3363                let age = now.saturating_duration_since(tcb.created_at);
3364                if age > self.valid_cookie_life {
3365                    let staleness = (age - self.valid_cookie_life).as_micros();
3366                    let staleness = u32::try_from(staleness).unwrap_or(u32::MAX);
3367                    self.discard_rest_of_packet = true;
3368                    return Ok(vec![Packet {
3369                        common_header: CommonHeader {
3370                            verification_tag: tcb.peer_verification_tag,
3371                            source_port: tcb.source_port,
3372                            destination_port: tcb.destination_port,
3373                        },
3374                        chunks: vec![Box::new(ChunkError {
3375                            error_causes: vec![ErrorCause {
3376                                code: STALE_COOKIE_ERROR,
3377                                raw: Bytes::copy_from_slice(&staleness.to_be_bytes()),
3378                            }],
3379                        })],
3380                    }]);
3381                }
3382
3383                // RFC 9260 5.2.4 B: after an INIT collision the peer's tag is the one that
3384                // came with this cookie.
3385                if state != AssociationState::Closed {
3386                    self.apply_cookie_tcb(&tcb);
3387                }
3388
3389                self.timers.stop(Timer::T1Init);
3390                self.stored_init = None;
3391
3392                self.timers.stop(Timer::T1Cookie);
3393                self.stored_cookie_echo = None;
3394                self.timers.stop(Timer::HalfOpen);
3395
3396                self.events.push_back(Event::Connected);
3397                self.set_state(AssociationState::Established);
3398                self.handshake_completed = true;
3399                self.peer_awaits_cookie_ack = true;
3400                self.start_heartbeat_timer(now);
3401                // RFC 9260 5.1.5 7): DATA that came with the COOKIE ECHO is acknowledged
3402                // at once.
3403                self.sack_packet_immediately = true;
3404            }
3405            // RFC 9260 5.2.4 D, and case E of 5.2: the cookie of the association that exists
3406            // (the COOKIE ACK was lost) is acknowledged again, whatever its age.
3407            AssociationState::Established => {
3408                let mut chunks: Vec<Box<dyn Chunk>> = vec![Box::new(ChunkCookieAck {})];
3409                for data in self.outstanding_data_after_a_cookie_ack(now)? {
3410                    chunks.push(Box::new(data));
3411                }
3412                return Ok(vec![Packet {
3413                    common_header: CommonHeader {
3414                        verification_tag: self.peer_verification_tag,
3415                        source_port: self.source_port,
3416                        destination_port: self.destination_port,
3417                    },
3418                    chunks,
3419                }]);
3420            }
3421            _ => {}
3422        };
3423
3424        Ok(vec![Packet {
3425            common_header: CommonHeader {
3426                verification_tag: self.peer_verification_tag,
3427                source_port: self.source_port,
3428                destination_port: self.destination_port,
3429            },
3430            chunks: vec![Box::new(ChunkCookieAck {})],
3431        }])
3432    }
3433
3434    /// The DATA that goes after the COOKIE ACK answering a duplicate COOKIE ECHO in
3435    /// ESTABLISHED: the earliest outstanding chunks that fit the packet with it, sent again.
3436    ///
3437    /// The duplicate says the peer is still in COOKIE-ECHOED: it did not receive the COOKIE
3438    /// ACK, and it discarded what DATA reached it (RFC 9260 5.1, "SHOULD discard" in
3439    /// COOKIE-ECHOED), so what is outstanding is waiting for T3-rtx, whose RTO those discards
3440    /// have backed off. RFC 9260 5.1 D lets DATA come with the COOKIE ACK, and the peer takes
3441    /// the packet's COOKIE ACK first (5.1 E), so this DATA arrives in ESTABLISHED. It counts as
3442    /// a retransmission: no round trip is measured with it (6.3.1 C5), and partially reliable
3443    /// DATA whose retransmissions are spent is abandoned instead (RFC 3758 3.5 A3).
3444    fn outstanding_data_after_a_cookie_ack(
3445        &mut self,
3446        now: Instant,
3447    ) -> Result<Vec<ChunkPayloadData>> {
3448        // The common header and the COOKIE ACK chunk (a 4-byte chunk header).
3449        self.outstanding_data_that_fits(now, COMMON_HEADER_SIZE as usize + 4)
3450    }
3451
3452    /// The earliest outstanding DATA chunks that fit a packet whose other chunks take `size`
3453    /// bytes, marked as sent again (retransmissions: no round trip is measured with them,
3454    /// RFC 9260 6.3.1 C5). Partially reliable DATA whose retransmissions are spent is
3455    /// abandoned instead.
3456    pub(super) fn outstanding_data_that_fits(
3457        &mut self,
3458        now: Instant,
3459        mut size: usize,
3460    ) -> Result<Vec<ChunkPayloadData>> {
3461        let mut chosen = vec![];
3462        let mut tsn = self.cumulative_tsn_ack_point.wrapping_add(1);
3463        while sna32lt(tsn, self.my_next_tsn) {
3464            let outstanding = self
3465                .inflight_queue
3466                .get(tsn)
3467                .is_some_and(|c| c.is_outstanding() && c.nsent > 0);
3468            if outstanding && !self.abandon_retransmit_candidate(tsn, now)? {
3469                let Some(c) = self.inflight_queue.get(tsn) else {
3470                    break;
3471                };
3472                if size + c.wire_size() > self.mtu as usize {
3473                    break;
3474                }
3475                size += c.wire_size();
3476                chosen.push(tsn);
3477            }
3478            tsn = tsn.wrapping_add(1);
3479        }
3480        let mut chunks = vec![];
3481        for tsn in chosen {
3482            if let Some(c) = self.inflight_queue.get_mut(tsn)
3483                && c.is_outstanding()
3484            {
3485                c.retransmit = false;
3486                c.nsent += 1;
3487                self.stats.inc_retransmissions();
3488                if c.reliability.limits_retransmission() {
3489                    self.stats.inc_partially_reliable_retransmissions();
3490                }
3491                chunks.push(c.clone());
3492            }
3493        }
3494        if !chunks.is_empty() {
3495            debug!(
3496                "[{}] {} outstanding DATA chunk(s) behind a handshake chunk",
3497                self.side,
3498                chunks.len()
3499            );
3500            self.min_tsn2measure_rtt = self.my_next_tsn;
3501        }
3502        Ok(chunks)
3503    }
3504
3505    fn handle_cookie_ack(&mut self, now: Instant) -> Result<Vec<Packet>> {
3506        let state = self.state();
3507        debug!("[{}] COOKIE-ACK received in state '{}'", self.side, state);
3508        if state != AssociationState::CookieEchoed {
3509            // RFC 4960
3510            // 5.2.5.  Handle Duplicate COOKIE-ACK.
3511            //   At any state other than COOKIE-ECHOED, an endpoint should silently
3512            //   discard a received COOKIE ACK chunk.
3513            return Ok(vec![]);
3514        }
3515
3516        self.timers.stop(Timer::T1Cookie);
3517        self.stored_cookie_echo = None;
3518
3519        self.events.push_back(Event::Connected);
3520        self.set_state(AssociationState::Established);
3521        self.handshake_completed = true;
3522        self.start_heartbeat_timer(now);
3523        // DATA that went with the COOKIE ECHO (`with_data_in_cookie_echo`) was covered by
3524        // T1-cookie until now; from here on by T3-rtx (RFC 9260 6.3.2 R1).
3525        if !self.inflight_queue.is_empty() {
3526            self.timers
3527                .start_if_idle(Timer::T3RTX, now, self.rto_mgr.get_rto());
3528        }
3529
3530        Ok(vec![])
3531    }
3532
3533    /// The time a HEARTBEAT is sent after the path went idle: RTO + HB.interval, with a
3534    /// jitter of up to half an RTO either way (RFC 9260 8.3).
3535    fn heartbeat_period(&self) -> Option<Duration> {
3536        let interval = self.heartbeat_interval?;
3537        let rto = self.rto_mgr.get_rto();
3538        let jitter = u64::from(self.random.u32()) % (rto + 1);
3539        Some(interval + Duration::from_millis(rto / 2 + jitter))
3540    }
3541
3542    /// RFC 9260 8.3: HEARTBEATs start when the association is established.
3543    fn start_heartbeat_timer(&mut self, now: Instant) {
3544        self.heartbeat_outstanding = None;
3545        match self.heartbeat_period() {
3546            Some(period) => self.timers.set(Timer::Heartbeat, Some(now + period)),
3547            None => self.timers.stop(Timer::Heartbeat),
3548        }
3549    }
3550
3551    /// The heartbeat timer expired: either the wait for the path to be idle is over and a
3552    /// HEARTBEAT goes out, or the HEARTBEAT that went out has not been answered within an
3553    /// RTO.
3554    fn on_heartbeat_timeout(&mut self, now: Instant) {
3555        if !self.may_send_heartbeat() {
3556            return;
3557        }
3558
3559        if self.heartbeat_outstanding.take().is_some() {
3560            // RFC 9260 8.3: a HEARTBEAT not acknowledged within an RTO counts against the
3561            // path and the association, and the RTO backs off. The next one follows after
3562            // HB.interval.
3563            debug!("[{}] HEARTBEAT not acknowledged", self.side);
3564            self.rto_mgr.backoff();
3565            if self.on_path_failure() {
3566                return;
3567            }
3568            if let Some(interval) = self.heartbeat_interval {
3569                self.timers.set(Timer::Heartbeat, Some(now + interval));
3570            }
3571            return;
3572        }
3573        let Some(interval) = self.heartbeat_interval else {
3574            return;
3575        };
3576
3577        // The path is idle when nothing that measures the round trip has left for a
3578        // heartbeat period: not while DATA is being sent for the first time.
3579        let Some(period) = self.heartbeat_period() else {
3580            return;
3581        };
3582        if let Some(last) = self.last_rtt_probe
3583            && now.saturating_duration_since(last) < interval
3584        {
3585            self.timers.set(Timer::Heartbeat, Some(last + period));
3586            return;
3587        }
3588        self.send_heartbeat(now);
3589    }
3590
3591    /// HEARTBEATs go in ESTABLISHED, SHUTDOWN-PENDING and SHUTDOWN-RECEIVED only.
3592    fn may_send_heartbeat(&self) -> bool {
3593        matches!(
3594            self.state(),
3595            AssociationState::Established
3596                | AssociationState::ShutdownPending
3597                | AssociationState::ShutdownReceived
3598        )
3599    }
3600
3601    /// Queues a HEARTBEAT and waits an RTO for its HEARTBEAT ACK (RFC 9260 8.3).
3602    fn send_heartbeat(&mut self, now: Instant) {
3603        // RFC 9260 8.3: the HEARTBEAT carries the time it is sent, and a nonce, so that the
3604        // HEARTBEAT ACK can be told from any other.
3605        let nonce = self.random.u64();
3606        let sent_ms = self.created_at.map_or(0, |start| {
3607            now.saturating_duration_since(start).as_millis() as u64
3608        });
3609        let mut info = BytesMut::with_capacity(16);
3610        info.extend_from_slice(&sent_ms.to_be_bytes());
3611        info.extend_from_slice(&nonce.to_be_bytes());
3612        let packet = self.create_packet(vec![Box::new(ChunkHeartbeat {
3613            params: vec![Box::new(ParamHeartbeatInfo {
3614                heartbeat_information: info.freeze(),
3615            })],
3616        })]);
3617        self.control_queue.push_back(packet);
3618        self.awake_write_loop();
3619        self.heartbeat_outstanding = Some((nonce, now));
3620        self.last_rtt_probe = Some(now);
3621        self.timers.set(
3622            Timer::Heartbeat,
3623            Some(now + Duration::from_millis(self.rto_mgr.get_rto())),
3624        );
3625    }
3626
3627    /// RFC 9260 11.1.10 Request Heartbeat: "Instructs the local endpoint to perform a
3628    /// heartbeat on the specified destination transport address". Sends a HEARTBEAT now,
3629    /// whether or not heartbeats are enabled ([`TransportConfig::with_heartbeat_interval`]),
3630    /// unless one is waiting for its HEARTBEAT ACK already (its answer serves). Its HEARTBEAT
3631    /// ACK measures the round trip ([`Self::rtt`]); left unanswered for an RTO it counts as an
3632    /// error of the path, as a periodic one does (8.3). Returns whether a HEARTBEAT was
3633    /// queued: `false` outside ESTABLISHED, SHUTDOWN-PENDING and SHUTDOWN-RECEIVED, or with
3634    /// one outstanding. The association is single-homed (RFC 8261 6.1), so there is no
3635    /// address to name.
3636    pub fn request_heartbeat(&mut self, now: Instant) -> bool {
3637        if !self.may_send_heartbeat() || self.heartbeat_outstanding.is_some() {
3638            return false;
3639        }
3640        self.send_heartbeat(now);
3641        true
3642    }
3643
3644    /// RFC 8899 section 6.2: the path MTU probe that is due, if any, as a packet of its own
3645    /// that is exactly the size probed: a HEARTBEAT whose Heartbeat Information is the probe
3646    /// size, the time it is sent and a nonce, and a PAD chunk (RFC 4820) for the rest. It
3647    /// carries no user data and is not held back by the congestion or the receive window
3648    /// (section 3, items 7 and 8); it waits for the established association.
3649    fn gather_path_mtu_probe(&mut self, raw_packets: &mut Vec<Bytes>, now: Instant) {
3650        let Some(pmtud) = self.pmtud.as_mut() else {
3651            return;
3652        };
3653        pmtud.start();
3654        let Some(size) = pmtud.poll_probe() else {
3655            return;
3656        };
3657        let nonce = self.random.u64();
3658        let sent_ms = self.created_at.map_or(0, |start| {
3659            now.saturating_duration_since(start).as_millis() as u64
3660        });
3661        let mut info = BytesMut::with_capacity(20);
3662        info.extend_from_slice(&size.to_be_bytes());
3663        info.extend_from_slice(&sent_ms.to_be_bytes());
3664        info.extend_from_slice(&nonce.to_be_bytes());
3665        let padding_length = size.saturating_sub(pmtud::PROBE_OVERHEAD) as usize;
3666        let packet = self.create_packet(vec![
3667            Box::new(ChunkHeartbeat {
3668                params: vec![Box::new(ParamHeartbeatInfo {
3669                    heartbeat_information: info.freeze(),
3670                })],
3671            }),
3672            Box::new(ChunkPadding { padding_length }),
3673        ]);
3674        match self.marshal_packet(&packet) {
3675            Ok(raw) => {
3676                debug!("[{}] path MTU probe of {} bytes", self.side, raw.len());
3677                raw_packets.push(raw);
3678                if let Some(pmtud) = self.pmtud.as_mut() {
3679                    pmtud.probe_sent(nonce, size, now);
3680                }
3681            }
3682            Err(err) => warn!(
3683                "[{}] failed to serialize a path MTU probe: {err}",
3684                self.side
3685            ),
3686        }
3687    }
3688
3689    /// A HEARTBEAT ACK that echoes a path MTU probe (`gather_path_mtu_probe`): the probe
3690    /// crossed the path. A successful probe counts as an answer from the peer (RFC 8899
3691    /// section 6.2.1.2: it "updates the association and path counters"). Returns whether the
3692    /// acknowledgement was a probe's.
3693    fn handle_path_mtu_probe_ack(&mut self, info: &Bytes, now: Instant) -> bool {
3694        if info.len() != 20 || self.pmtud.is_none() {
3695            return false;
3696        }
3697        let nonce = u64::from_be_bytes(info[12..20].try_into().unwrap_or_default());
3698        if let Some(mtu) = self.pmtud.as_mut().and_then(|p| p.on_probe_ack(nonce, now)) {
3699            self.use_path_mtu(mtu, false);
3700        }
3701        self.on_path_success();
3702        true
3703    }
3704
3705    /// The path MTU discovery's timers (PROBE_TIMER, PMTU_RAISE_TIMER).
3706    fn handle_path_mtu_timeout(&mut self, now: Instant) {
3707        if let Some(mtu) = self.pmtud.as_mut().and_then(|p| p.on_timeout(now)) {
3708            self.use_path_mtu(mtu, false);
3709        }
3710        if self
3711            .pmtud
3712            .as_ref()
3713            .is_some_and(|p| p.poll_probe().is_some())
3714        {
3715            self.awake_write_loop();
3716        }
3717    }
3718
3719    /// RFC 9260 8.3: a HEARTBEAT ACK for the HEARTBEAT outstanding measures the round trip,
3720    /// clears the error counters and shows the path active. Any other is ignored.
3721    fn handle_heartbeat_ack(&mut self, c: &ChunkHeartbeatAck, now: Instant) {
3722        if let Some(info) = c.params.first().and_then(|p| {
3723            p.as_any()
3724                .downcast_ref::<ParamHeartbeatInfo>()
3725                .map(|info| info.heartbeat_information.clone())
3726        }) && self.handle_path_mtu_probe_ack(&info, now)
3727        {
3728            return;
3729        }
3730        let Some((nonce, sent_at)) = self.heartbeat_outstanding else {
3731            trace!("[{}] HEARTBEAT ACK for no HEARTBEAT", self.side);
3732            return;
3733        };
3734        let echoed = c.params.first().and_then(|p| {
3735            p.as_any()
3736                .downcast_ref::<ParamHeartbeatInfo>()
3737                .map(|info| info.heartbeat_information.clone())
3738        });
3739        let matches = echoed.is_some_and(|info| {
3740            info.len() == 16 && constant_time_eq(&info[8..], &nonce.to_be_bytes())
3741        });
3742        if !matches {
3743            debug!(
3744                "[{}] HEARTBEAT ACK does not match the HEARTBEAT sent",
3745                self.side
3746            );
3747            return;
3748        }
3749        self.heartbeat_outstanding = None;
3750        let rtt = now.saturating_duration_since(sent_at);
3751        self.rto_mgr.set_new_rtt(rtt.as_millis() as u64);
3752        self.timers.reset_retrans(Timer::T3RTX);
3753        self.on_path_success();
3754        if let Some(period) = self.heartbeat_period() {
3755            self.timers.set(Timer::Heartbeat, Some(now + period));
3756        }
3757    }
3758
3759    /// One more consecutive failure on the path (RFC 9260 8.1, 8.2): a HEARTBEAT without an
3760    /// answer. Returns whether the association ended over it.
3761    fn on_path_failure(&mut self) -> bool {
3762        self.note_path_error();
3763        if self.timers.count_error(Timer::T3RTX) {
3764            // RFC 9260 8.1: past Association.Max.Retrans the peer is unreachable.
3765            error!("[{}] the peer does not answer: giving up", self.side);
3766            if let Err(err) = self.close(AssociationError::TimedOut) {
3767                error!("[{}] failed to close association: {err}", self.side);
3768            }
3769            return true;
3770        }
3771        false
3772    }
3773
3774    /// Counts a failure against the path and reports the path inactive past
3775    /// Path.Max.Retrans.
3776    fn note_path_error(&mut self) {
3777        self.path_error_count += 1;
3778        if self.path_error_count > PATH_MAX_RETRANS && !self.path_inactive {
3779            self.path_inactive = true;
3780            self.events.push_back(Event::PathInactive);
3781        }
3782    }
3783
3784    /// The peer answered: new DATA was acknowledged, or a HEARTBEAT.
3785    fn on_path_success(&mut self) {
3786        self.path_error_count = 0;
3787        if self.path_inactive {
3788            self.path_inactive = false;
3789            self.events.push_back(Event::PathActive);
3790        }
3791    }
3792
3793    /// Sets HB.interval for this association (RFC 9260 11.1.9, "Change Heartbeat"). `None`
3794    /// stops the HEARTBEATs.
3795    pub fn set_heartbeat_interval(&mut self, interval: Option<Duration>, now: Instant) {
3796        self.heartbeat_interval = interval;
3797        if self.state() == AssociationState::Established {
3798            self.start_heartbeat_timer(now);
3799        }
3800    }
3801
3802    fn handle_data(&mut self, d: &ChunkPayloadData) -> Result<Vec<Packet>> {
3803        debug!(
3804            "[{}] DATA: tsn={} peer_last_tsn={} immediateSack={} len={}, unordered={}",
3805            self.side,
3806            d.tsn,
3807            self.peer_last_tsn,
3808            d.immediate_sack,
3809            d.user_data.len(),
3810            d.unordered,
3811        );
3812        self.stats.inc_datas();
3813
3814        // RFC 8260 2.2.3: with user message interleaving negotiated a DATA chunk is a
3815        // violation, and without it an I-DATA chunk is: the association is aborted.
3816        if d.i_data != self.use_interleaving {
3817            warn!(
3818                "[{}] {} chunk on an association that uses the other: aborting",
3819                self.side,
3820                if d.i_data { "I-DATA" } else { "DATA" }
3821            );
3822            self.abort_with(
3823                vec![Self::protocol_violation(if d.i_data {
3824                    "I-DATA without user message interleaving (RFC 8260 2.2.3)"
3825                } else {
3826                    "DATA with user message interleaving (RFC 8260 2.2.3)"
3827                })],
3828                AssociationError::TransportError,
3829            )?;
3830            return Ok(vec![]);
3831        }
3832
3833        // RFC 9260 section 6: DATA is received by the normal rules in ESTABLISHED,
3834        // SHUTDOWN-PENDING and SHUTDOWN-SENT, and discarded in any other state.
3835        match self.state() {
3836            AssociationState::Established
3837            | AssociationState::ShutdownPending
3838            | AssociationState::ShutdownSent => {}
3839            AssociationState::Closed if self.side == Side::Server => {
3840                // An accepting association that has seen no COOKIE ECHO has no association
3841                // to receive on: the DATA is out of the blue (8.4), answered with an ABORT
3842                // that reflects the packet's tag.
3843                debug!("[{}] DATA before the COOKIE ECHO: ABORT", self.side);
3844                self.discard_rest_of_packet = true;
3845                return Ok(vec![self.abort_packet(
3846                    self.my_verification_tag,
3847                    true,
3848                    vec![],
3849                )]);
3850            }
3851            state => {
3852                // COOKIE-WAIT and COOKIE-ECHOED (DATA that overtook the COOKIE ACK is sent
3853                // again by the peer); SHUTDOWN-RECEIVED and SHUTDOWN-ACK-SENT, where the peer
3854                // has said it sends nothing more: discarded.
3855                debug!("[{}] discarding DATA in state '{}'", self.side, state);
3856                return Ok(vec![]);
3857            }
3858        }
3859
3860        // RFC 9260 section 6.2: a DATA chunk with no user data is answered with an ABORT
3861        // carrying the "No User Data" cause. Accepting one would cost receive state without
3862        // counting against the byte-based receive window.
3863        if d.user_data.is_empty() {
3864            debug!(
3865                "[{}] DATA tsn={} has no user data: aborting",
3866                self.side, d.tsn
3867            );
3868            let abort = ChunkAbort {
3869                error_causes: vec![ErrorCause {
3870                    code: NO_USER_DATA,
3871                    raw: Bytes::copy_from_slice(&d.tsn.to_be_bytes()),
3872                }],
3873                ..Default::default()
3874            };
3875            let packet = self.create_packet(vec![Box::new(abort)]);
3876            self.control_queue.push_back(packet);
3877            self.awake_write_loop();
3878            self.close(AssociationError::TransportError)?;
3879            return Err(Error::ErrAbortChunk(NO_USER_DATA.to_string()));
3880        }
3881
3882        // A stream id at or past the inbound stream count negotiated in INIT/INIT-ACK is not
3883        // one the peer may use (RFC 9260 6.5); creating state for it would let a peer make us
3884        // hold up to 65536 streams.
3885        //
3886        // RFC 9260 6.5: such a chunk is still acknowledged (it only is not delivered), and
3887        // answered with an ERROR "Invalid Stream Identifier". Its TSN is recorded without the
3888        // payload. Left unrecorded, as it was, the cumulative TSN could never pass it: the
3889        // peer retransmitted it for ever and in the end every chunk after it was refused.
3890        if self.my_max_num_inbound_streams != 0
3891            && d.stream_identifier >= self.my_max_num_inbound_streams
3892        {
3893            debug!(
3894                "[{}] discard DATA on stream {} (negotiated inbound streams: {})",
3895                self.side, d.stream_identifier, self.my_max_num_inbound_streams
3896            );
3897            let can_push = self.payload_queue.can_push(d, self.peer_last_tsn);
3898            if can_push {
3899                self.payload_queue.push(
3900                    ChunkPayloadData {
3901                        user_data: Bytes::new(),
3902                        ..d.clone()
3903                    },
3904                    self.peer_last_tsn,
3905                );
3906                let mut raw = BytesMut::with_capacity(4);
3907                raw.extend_from_slice(&d.stream_identifier.to_be_bytes());
3908                raw.extend_from_slice(&[0, 0]);
3909                self.report_error(ErrorCause {
3910                    code: INVALID_STREAM_IDENTIFIER,
3911                    raw: raw.freeze(),
3912                });
3913            } else {
3914                self.payload_queue.record_duplicate(d.tsn);
3915            }
3916            return self.handle_peer_last_tsn_and_acknowledgement(d.immediate_sack || !can_push);
3917        }
3918
3919        let can_push = self.payload_queue.can_push(d, self.peer_last_tsn);
3920        let mut stream_handle_data = false;
3921        let mut dropped_for_window = false;
3922        // RFC 9260 6.1 A: after a SACK advertised a_rwnd 0, the sender sends one chunk at a
3923        // time (a zero window probe) and the next only when that one is acknowledged. A
3924        // delayed SACK (6.2) would hold each of them for up to the SACK delay; what this side
3925        // takes then is acknowledged at once.
3926        let window_was_closed = self.last_advertised_window == 0;
3927        let mut taken_through_closed_window = false;
3928        if can_push {
3929            if self.get_or_create_stream(d.stream_identifier).is_some() {
3930                // RFC 9260 6.2: "When the receiver's advertised window is 0, ... if the new
3931                // incoming DATA chunk holds a TSN value less than the largest TSN received so
3932                // far, then the receiver SHOULD drop the largest TSN held for reordering and
3933                // accept the new incoming DATA chunk." With
3934                // `TransportConfig::with_zero_window_renege` a gap filler takes that chunk's
3935                // place (a renege, 6.2.1). The condition is the window last advertised, not the
3936                // space left: silly window avoidance advertises 0 with up to a full chunk
3937                // free (`advertised_window`), and a sender stopped by that a_rwnd sends nothing
3938                // more that would use the rest. Not taken past one inbound message beyond the
3939                // buffer, as below.
3940                let renege = if self.zero_window_renege
3941                    && window_was_closed
3942                    && self
3943                        .payload_queue
3944                        .get_last_tsn_received()
3945                        .is_some_and(|last_tsn| sna32lt(d.tsn, *last_tsn))
3946                {
3947                    let held = self.bytes_in_reassembly_queues();
3948                    let limit = self.max_receive_buffer_size as usize
3949                        + self.max_receive_message_size as usize;
3950                    self.zero_window_renege_candidate()
3951                        .filter(|&(_, _, freed)| {
3952                            held.saturating_sub(freed) + d.user_data.len() <= limit
3953                        })
3954                } else {
3955                    None
3956                };
3957                if let Some((tsn, stream, _)) = renege {
3958                    self.renege_held(tsn, stream);
3959                    self.payload_queue.push(d.clone(), self.peer_last_tsn);
3960                    stream_handle_data = true;
3961                    taken_through_closed_window = true;
3962                } else if self.get_my_receiver_window_credit() > 0
3963                    && !(window_was_closed
3964                        && self.advertised_window() == 0
3965                        && self
3966                            .payload_queue
3967                            .get_last_tsn_received()
3968                            .is_none_or(|last_tsn| sna32gt(d.tsn, *last_tsn)))
3969                {
3970                    // RFC 9260 6.2: "When the receiver's advertised window is 0, the receiver
3971                    // MUST drop any new incoming DATA chunk with a TSN larger than the largest
3972                    // TSN received so far." The window advertised, as for the renege above:
3973                    // silly window avoidance advertises 0 with up to a full chunk free, and a
3974                    // chunk above the largest TSN (a zero window probe, 6.1 A) goes to the
3975                    // full-buffer rules below, which drop it (the overcommit escape aside).
3976                    // The window stays closed until it has space to reopen: once the
3977                    // application has read enough, the SACK that announces it is due at once
3978                    // (`on_receive_buffer_drained`, 6.2 "When the window opens up ..."), and a
3979                    // chunk that arrives before that SACK goes out is taken, not dropped.
3980                    // Pass the new chunk to stream level as soon as it arrives
3981                    self.payload_queue.push(d.clone(), self.peer_last_tsn);
3982                    stream_handle_data = true;
3983                    taken_through_closed_window = window_was_closed;
3984                } else {
3985                    // Receive buffer is full, or the window was advertised as closed and the
3986                    // chunk is above the largest TSN. Two kinds of chunk are still worth taking,
3987                    // because refusing them is not something the application can relieve by
3988                    // draining.
3989                    //
3990                    // The first fills a gap below the highest TSN already queued.
3991                    let fills_gap = self
3992                        .payload_queue
3993                        .get_last_tsn_received()
3994                        .is_some_and(|last_tsn| sna32lt(d.tsn, *last_tsn));
3995
3996                    // The second is the next in-sequence chunk when nothing is readable at
3997                    // all, and it is what keeps a full buffer from becoming permanent. Bytes
3998                    // are released only when the application reads; `is_readable()` is
3999                    // head-of-line blocked by an incomplete chunk set; and the chunk that
4000                    // would complete that set is exactly `peer_last_tsn + 1`. Dropping it
4001                    // leaves the window at zero with no way to reopen — every retransmission
4002                    // is refused for the same reason, forever.
4003                    // See <https://github.com/webrtc-rs/webrtc/issues/822>.
4004                    //
4005                    // Guarded on nothing being readable so this stays an escape from deadlock
4006                    // rather than a licence to overrun the bound. A merely slow receiver has
4007                    // data to take and must be made to take it. Without the guard, the chunk
4008                    // accepted here is `peer_last_tsn + 1` — precisely the one that advances
4009                    // the cumulative ack — so every chunk would qualify and
4010                    // `max_receive_buffer_size` would stop bounding anything.
4011                    //
4012                    // RFC 9260 6.2: once the window has been advertised as closed, a new DATA
4013                    // chunk above the largest TSN received MUST be dropped; the escape then
4014                    // needs `TransportConfig::with_zero_window_overcommit`. An application
4015                    // that reads in parts (`Stream::read_part`, RFC 9260 6.9) needs no
4016                    // escape: a buffer full of incomplete messages is given out in parts
4017                    // (`partial_delivery_threshold`), and the window opens again.
4018                    let window_advertised_closed = self.last_advertised_window == 0;
4019                    let unblocks_reassembly = d.tsn == self.peer_last_tsn.wrapping_add(1)
4020                        && !self.has_readable_data()
4021                        && (!window_advertised_closed || self.zero_window_overcommit);
4022
4023                    // Either kind may take the receiver past `max_receive_buffer_size`, which
4024                    // is what lets a message larger than the buffer be reassembled at all. But
4025                    // the headroom this needs is one message, so neither kind is taken past
4026                    // one inbound message (the size this side advertised) beyond the buffer.
4027                    let within_headroom = self.bytes_in_reassembly_queues() + d.user_data.len()
4028                        <= self.max_receive_buffer_size as usize
4029                            + self.max_receive_message_size as usize;
4030
4031                    if (fills_gap || unblocks_reassembly) && within_headroom {
4032                        debug!(
4033                            "[{}] receive buffer full, but accepted {} with tsn={} ssn={}",
4034                            self.side,
4035                            if fills_gap {
4036                                "as this is a missing chunk"
4037                            } else {
4038                                "as the in-sequence chunk that unblocks reassembly"
4039                            },
4040                            d.tsn,
4041                            d.stream_sequence_number
4042                        );
4043                        self.payload_queue.push(d.clone(), self.peer_last_tsn);
4044                        stream_handle_data = true;
4045                        taken_through_closed_window = window_was_closed;
4046                    } else {
4047                        debug!(
4048                            "[{}] receive buffer full. dropping DATA with tsn={} ssn={}",
4049                            self.side, d.tsn, d.stream_sequence_number
4050                        );
4051                        // RFC 9260 6.2: a DATA chunk dropped for lack of window is
4052                        // answered with a SACK at once, which shows the sender the window
4053                        // and that the chunk is not held.
4054                        dropped_for_window = true;
4055                    }
4056                }
4057            } else {
4058                // silently discard the data. (sender will retry on T3-rtx timeout)
4059                debug!("[{}] discard {}", self.side, d.stream_sequence_number);
4060                return Ok(vec![]);
4061            }
4062        } else {
4063            self.payload_queue.record_duplicate(d.tsn);
4064        }
4065
4066        // RFC 9260 section 6.2: a repeat is listed in a SACK sent at once. So is the first
4067        // DATA chunk of the association (5.1), DATA that came with the COOKIE ECHO (5.1.5),
4068        // and DATA received in SHUTDOWN-SENT (9.2), which is also answered with the SHUTDOWN
4069        // again.
4070        let first = !self.first_data_received;
4071        self.first_data_received = true;
4072        let mut immediate_sack = d.immediate_sack
4073            || !can_push
4074            || first
4075            || self.sack_packet_immediately
4076            || dropped_for_window
4077            || taken_through_closed_window;
4078        if self.state() == AssociationState::ShutdownSent {
4079            immediate_sack = true;
4080            self.will_send_shutdown = true;
4081            self.awake_write_loop();
4082        }
4083
4084        if stream_handle_data {
4085            self.received_since_sack = self
4086                .received_since_sack
4087                .saturating_add(u32::try_from(d.user_data.len()).unwrap_or(u32::MAX));
4088            if self.holds_for_reset(d) {
4089                // RFC 6525 5.2.2 E2: this DATA belongs to its stream as it will be after a
4090                // reset that is not performed yet. Its TSN is acknowledged; it is delivered
4091                // when the reset is done.
4092                debug!(
4093                    "[{}] holding DATA tsn={} of stream {} for a deferred reset",
4094                    self.side, d.tsn, d.stream_identifier
4095                );
4096                self.reassembly_bytes = self.reassembly_bytes.saturating_add(d.user_data.len());
4097                self.held_reset_data.push(d.clone());
4098            } else {
4099                self.deliver_to_stream(d);
4100            }
4101        }
4102        // A chunk taken may have used the buffer up; one dropped arrives while it is.
4103        self.offer_partial_delivery();
4104
4105        self.handle_peer_last_tsn_and_acknowledgement(immediate_sack)
4106    }
4107
4108    /// RFC 9260 6.2, the zero window renege: "the largest TSN held for reordering", its stream
4109    /// and its user data's length. The largest TSN above the cumulative TSN whose chunk its
4110    /// stream's reassembly queue still holds in a message that is not readable whole and not
4111    /// in partial delivery (`ReassemblyQueue::remove_held`); a chunk the application can read
4112    /// now, has read part of, or that waits for a stream reset is not held for reordering.
4113    fn zero_window_renege_candidate(&self) -> Option<(u32, StreamId, usize)> {
4114        self.payload_queue.sorted.iter().rev().find_map(|&tsn| {
4115            let c = self.payload_queue.get(tsn)?;
4116            if c.user_data.is_empty() {
4117                return None;
4118            }
4119            let s = self.streams.get(&c.stream_identifier)?;
4120            s.reassembly_queue.is_held_for_reordering(tsn).then_some((
4121                tsn,
4122                c.stream_identifier,
4123                c.user_data.len(),
4124            ))
4125        })
4126    }
4127
4128    /// Drops the chunk with `tsn`, held for reordering on `stream` (see
4129    /// `zero_window_renege_candidate`), from its reassembly queue and from the TSNs held above
4130    /// the cumulative TSN: it is no longer reported in a Gap Ack Block (RFC 9260 6.2: the
4131    /// receiver "MUST NOT include" DATA it no longer holds), and the peer sends it again.
4132    fn renege_held(&mut self, tsn: u32, stream: StreamId) {
4133        let Some(s) = self.streams.get_mut(&stream) else {
4134            return;
4135        };
4136        let bytes_before = s.get_num_bytes_in_reassembly_queue();
4137        if s.reassembly_queue.remove_held(tsn).is_none() {
4138            return;
4139        }
4140        self.reindex_stream(stream, bytes_before);
4141        self.payload_queue.remove(tsn);
4142        self.stats.inc_reneged();
4143        debug!(
4144            "[{}] receive window closed: dropped tsn={} of stream {} held for reordering, to \
4145             take a chunk that fills a gap (RFC 9260 6.2)",
4146            self.side, tsn, stream
4147        );
4148    }
4149
4150    /// Hands a DATA chunk that was accepted to its stream.
4151    fn deliver_to_stream(&mut self, d: &ChunkPayloadData) {
4152        let cumulative_tsn = self.peer_last_tsn;
4153        // A fragment that does not begin a message, for a stream that holds nothing, when the
4154        // TSN before it has been received: the start of its message went to a stream that is
4155        // gone (see `ReassemblyQueue::discard_orphans`). It makes no stream.
4156        if !self.streams.contains_key(&d.stream_identifier)
4157            && !d.beginning_fragment
4158            && sna32lte(d.tsn.wrapping_sub(1), cumulative_tsn)
4159        {
4160            self.note_orphan(d);
4161            return;
4162        }
4163        if self.get_or_create_stream(d.stream_identifier).is_none() {
4164            return;
4165        }
4166        if let Some(s) = self.streams.get_mut(&d.stream_identifier) {
4167            if s.reads_stopped {
4168                // The application closed the stream: nothing will read this. Its TSN stays
4169                // acknowledged.
4170                trace!(
4171                    "[{}] dropping DATA tsn={} of stream {}, which is no longer read",
4172                    self.side, d.tsn, d.stream_identifier
4173                );
4174                return;
4175            }
4176            self.events.push_back(Event::DatagramReceived);
4177            let bytes_before = s.get_num_bytes_in_reassembly_queue();
4178            let orphans_before = s.reassembly_queue.orphans_dropped;
4179            if s.handle_received(d, cumulative_tsn) && s.reassembly_queue.is_readable() {
4180                self.events.push_back(Event::Stream(StreamEvent::Readable {
4181                    id: s.stream_identifier,
4182                }));
4183            }
4184            let dropped = s.reassembly_queue.orphans_dropped - orphans_before;
4185            self.reindex_stream(d.stream_identifier, bytes_before);
4186            if dropped == 0 {
4187                // Nothing dropped.
4188            } else if !d.beginning_fragment {
4189                // The chunk itself: the rest of a message whose start went elsewhere.
4190                self.note_orphan(d);
4191            } else {
4192                // Held fragments the message this chunk begins supersedes.
4193                self.orphans_dropped += dropped;
4194                self.last_orphan_tsn = None;
4195                warn!(
4196                    "[{}] dropped {dropped} DATA fragments of stream {} held ahead of the \
4197                     message starting at tsn={}: sent before it with later numbers, they are \
4198                     from before a reset of the stream (a peer that sent data queued on the \
4199                     stream after its Sender's Last Assigned TSN, RFC 6525 5.1.2 A3)",
4200                    self.side, d.stream_identifier, d.tsn
4201                );
4202            }
4203        }
4204    }
4205
4206    /// What this side has acknowledged and not delivered: a description of every stream whose
4207    /// reassembly queue holds a fragment or a message, and of DATA held for a reset. `None`
4208    /// when there is nothing. Once the link is quiet (the peer has nothing outstanding) and the
4209    /// application has read everything it was told was readable, a reliable association holds
4210    /// nothing: whatever it holds then is stuck, acknowledged and never to be delivered.
4211    #[cfg(test)]
4212    pub(crate) fn undelivered(&self) -> Option<String> {
4213        let mut held: Vec<String> = self
4214            .streams
4215            .iter()
4216            .filter(|(_, s)| !s.reassembly_queue.is_empty())
4217            .map(|(id, s)| {
4218                let q = &s.reassembly_queue;
4219                format!(
4220                    "stream {id}: {} bytes, ordered sets {:?} (next ssn {} mid {}), {} unordered \
4221                     messages, {} unordered fragments, in partial delivery: {}",
4222                    q.get_num_bytes(),
4223                    q.ordered
4224                        .iter()
4225                        .map(|c| (c.ssn, c.mid, c.chunks.len(), c.is_complete()))
4226                        .collect::<Vec<_>>(),
4227                    q.next_ssn,
4228                    q.next_mid,
4229                    q.unordered.len(),
4230                    q.unordered_chunks.len(),
4231                    q.in_partial_delivery(),
4232                )
4233            })
4234            .collect();
4235        held.sort();
4236        if !self.held_reset_data.is_empty() {
4237            held.push(format!(
4238                "{} DATA chunks held for a reset",
4239                self.held_reset_data.len()
4240            ));
4241        }
4242        (!held.is_empty()).then(|| held.join("; "))
4243    }
4244
4245    /// DATA chunk `d` was dropped as a fragment that can never be part of a complete message.
4246    /// Its TSN stays acknowledged.
4247    fn note_orphan(&mut self, d: &ChunkPayloadData) {
4248        self.orphans_dropped += 1;
4249        if self.last_orphan_tsn != Some(d.tsn.wrapping_sub(1)) {
4250            warn!(
4251                "[{}] dropping DATA of stream {} at tsn={} (ssn={} mid={}): it can never be \
4252                 delivered in its place, being the rest of a message from before a reset of the \
4253                 stream (a peer that sent data queued on the stream after its Sender's Last \
4254                 Assigned TSN, RFC 6525 5.1.2 A3)",
4255                self.side, d.stream_identifier, d.tsn, d.stream_sequence_number, d.mid
4256            );
4257        }
4258        self.last_orphan_tsn = Some(d.tsn);
4259    }
4260
4261    /// Drops, on every stream, the fragments that can never be part of a complete message
4262    /// now that the cumulative TSN has passed TSNs that were missing
4263    /// (`ReassemblyQueue::discard_orphans`).
4264    fn discard_orphaned_fragments(&mut self) {
4265        let cumulative_tsn = self.peer_last_tsn;
4266        let ids: Vec<StreamId> = self.streams_with_data.iter().copied().collect();
4267        for id in ids {
4268            let Some(s) = self.streams.get_mut(&id) else {
4269                continue;
4270            };
4271            let bytes_before = s.get_num_bytes_in_reassembly_queue();
4272            let dropped = s.reassembly_queue.discard_orphans(cumulative_tsn);
4273            if dropped == 0 {
4274                continue;
4275            }
4276            let readable = s.reassembly_queue.is_readable();
4277            self.orphans_dropped += dropped;
4278            warn!(
4279                "[{}] dropped {dropped} DATA fragments of stream {id} that can never be \
4280                 completed: the start of their message went to another stream",
4281                self.side
4282            );
4283            self.reindex_stream(id, bytes_before);
4284            if readable {
4285                self.events
4286                    .push_back(Event::Stream(StreamEvent::Readable { id }));
4287            }
4288        }
4289    }
4290
4291    fn handle_sack(&mut self, d: &ChunkSelectiveAck, now: Instant) -> Result<Vec<Packet>> {
4292        trace!(
4293            "[{}] {}, SACK: cumTSN={} a_rwnd={}",
4294            self.side,
4295            self.cumulative_tsn_ack_point,
4296            d.cumulative_tsn_ack,
4297            d.advertised_receiver_window_credit
4298        );
4299        let state = self.state();
4300        if state == AssociationState::Closed && self.side == Side::Server && !self.ended {
4301            // RFC 9260 section 6: a SACK for an association that is not there yet is out of
4302            // the blue (8.4).
4303            self.discard_rest_of_packet = true;
4304            return Ok(vec![self.abort_packet(
4305                self.my_verification_tag,
4306                true,
4307                vec![],
4308            )]);
4309        }
4310        if state != AssociationState::Established
4311            && state != AssociationState::ShutdownPending
4312            && state != AssociationState::ShutdownReceived
4313        {
4314            return Ok(vec![]);
4315        }
4316
4317        self.stats.inc_sacks();
4318
4319        if sna32gt(self.cumulative_tsn_ack_point, d.cumulative_tsn_ack) {
4320            // RFC 4960 sec 6.2.1.  Processing a Received SACK
4321            // D)
4322            //   i) If Cumulative TSN Ack is less than the Cumulative TSN Ack
4323            //      Point, then drop the SACK.  Since Cumulative TSN Ack is
4324            //      monotonically increasing, a SACK whose Cumulative TSN Ack is
4325            //      less than the Cumulative TSN Ack Point indicates an out-of-
4326            //      order SACK.
4327
4328            debug!(
4329                "[{}] SACK Cumulative ACK {} is older than ACK point {}",
4330                self.side, d.cumulative_tsn_ack, self.cumulative_tsn_ack_point
4331            );
4332
4333            return Ok(vec![]);
4334        }
4335
4336        // A SACK may not acknowledge DATA this side never sent (RFC 9260 6.2.1, 12.4): it is
4337        // an error, and the caller aborts the association. Nothing is taken from it.
4338        if sna32gte(d.cumulative_tsn_ack, self.my_next_tsn) {
4339            debug!(
4340                "[{}] SACK Cumulative ACK {} is beyond the next TSN {}",
4341                self.side, d.cumulative_tsn_ack, self.my_next_tsn
4342            );
4343            return Err(Error::ErrTsnRequestNotExist);
4344        }
4345
4346        // RFC 9260 6.2: "When an endpoint receives a SACK chunk, it MAY use the duplicate TSN
4347        // information to determine if SACK chunk loss is occurring." A TSN this side sent
4348        // again on a retransmission timeout and that the peer reports as a duplicate had
4349        // reached the peer before: the SACK that said so was lost (or came after the RTO).
4350        for tsn in &d.duplicate_tsn {
4351            if let Some(i) = self.t3_retransmitted.iter().position(|t| t == tsn) {
4352                self.t3_retransmitted.remove(i);
4353                self.stats.inc_sack_losses();
4354            }
4355        }
4356
4357        // The bytes outstanding before this SACK: the congestion window may grow only when
4358        // it was in full use (RFC 9260 7.2.1, 7.2.2).
4359        let flight_before =
4360            u32::try_from(self.inflight_queue.get_num_wire_bytes()).unwrap_or(u32::MAX);
4361        let marked_before = self.fast_retransmit_marked.len();
4362
4363        // Process selective ack
4364        let (bytes_acked_per_stream, total_bytes_acked, htna) =
4365            self.process_selective_ack(d, now)?;
4366
4367        let mut cum_tsn_ack_point_advanced = false;
4368        if sna32lt(self.cumulative_tsn_ack_point, d.cumulative_tsn_ack) {
4369            trace!(
4370                "[{}] SACK: cumTSN advanced: {} -> {}",
4371                self.side, self.cumulative_tsn_ack_point, d.cumulative_tsn_ack
4372            );
4373
4374            self.cumulative_tsn_ack_point = d.cumulative_tsn_ack;
4375            cum_tsn_ack_point_advanced = true;
4376            if let Some(pmtud) = self.pmtud.as_mut() {
4377                pmtud.on_progress();
4378            }
4379            self.on_cumulative_tsn_ack_point_advanced(now);
4380        }
4381        // RFC 9260 7.2.4: the window growth of 7.2.1 and 7.2.2 comes before the adjustments
4382        // for loss this SACK may bring.
4383        // RFC 9260 7.2.2: partial_bytes_acked also counts "the number of bytes of duplicated
4384        // chunks reported in Duplicate TSNs". Only chunks this side sent and saw acknowledged
4385        // count, each once, so a receiver cannot inflate the count by repeating TSNs.
4386        let duplicate_bytes = self.duplicate_bytes(&d.duplicate_tsn);
4387        self.grow_congestion_window(
4388            total_bytes_acked,
4389            duplicate_bytes,
4390            flight_before,
4391            cum_tsn_ack_point_advanced,
4392        );
4393
4394        self.release_stream_buffers(&bytes_acked_per_stream);
4395
4396        // New rwnd value
4397        // RFC 4960 sec 6.2.1.  Processing a Received SACK
4398        // D)
4399        //   ii) Set rwnd equal to the newly received a_rwnd minus the number
4400        //       of bytes still outstanding after processing the Cumulative
4401        //       TSN Ack and the Gap Ack Blocks.
4402
4403        // acknowledged payload bytes were already released from the in-flight queue
4404        let bytes_outstanding = self.inflight_queue.get_num_bytes() as u32;
4405        if bytes_outstanding >= d.advertised_receiver_window_credit {
4406            self.rwnd = 0;
4407        } else {
4408            self.rwnd = d.advertised_receiver_window_credit - bytes_outstanding;
4409        }
4410        // RFC 9260 6.1 A: the receiver closed its window. The first zero window probe goes one
4411        // RTO from now, and the probes sent while SACKs keep coming do not count as errors: the
4412        // receiver may keep its window closed for as long as it likes.
4413        //
4414        // A SACK that acknowledges the outstanding probe is not the window closing again: the
4415        // receiver took that DATA although it advertised no room (it completes a message its
4416        // full buffer holds the start of). Waiting one RTO before each such chunk delivered a
4417        // message larger than the receive buffer at one fragment per RTO, which is a stall.
4418        // The next probe goes at once; one that is dropped stays outstanding and is
4419        // retransmitted by T3-rtx, whose interval doubles.
4420        let probe_acknowledged = self
4421            .zero_window_probe_tsn
4422            .is_some_and(|tsn| sna32gte(d.cumulative_tsn_ack, tsn));
4423        if probe_acknowledged {
4424            self.zero_window_probe_tsn = None;
4425        }
4426        if d.advertised_receiver_window_credit == 0 {
4427            if probe_acknowledged {
4428                self.zero_window_probe_at = None;
4429            } else if self.zero_window_probe_at.is_none() {
4430                self.zero_window_probe_at =
4431                    Some(now + Duration::from_millis(self.rto_mgr.get_rto()));
4432            }
4433            self.timers.reset_retrans(Timer::T3RTX);
4434            self.on_path_success();
4435        } else {
4436            self.zero_window_probe_at = None;
4437        }
4438
4439        // The highest TSN this SACK acknowledges: every outstanding TSN below it is one the
4440        // SACK reports missing (RFC 9260 7.2.4).
4441        // A block whose Start is past its End covers no TSN (RFC 9260 3.3.4: the TSNs from
4442        // Start to End): it reports nothing received, so nothing missing below it either.
4443        let highest_reported = d
4444            .gap_ack_blocks
4445            .iter()
4446            .filter(|g| g.start <= g.end)
4447            .map(|g| d.cumulative_tsn_ack.wrapping_add(g.end as u32))
4448            .fold(d.cumulative_tsn_ack, |highest, tsn| {
4449                if sna32gt(tsn, highest) { tsn } else { highest }
4450            });
4451        self.process_fast_retransmission(
4452            d.cumulative_tsn_ack,
4453            htna,
4454            highest_reported,
4455            cum_tsn_ack_point_advanced,
4456            now,
4457        )?;
4458
4459        if self.use_forward_tsn {
4460            // RFC 3758 Sec 3.5 C1
4461            if sna32lt(
4462                self.advanced_peer_tsn_ack_point,
4463                self.cumulative_tsn_ack_point,
4464            ) {
4465                self.advanced_peer_tsn_ack_point = self.cumulative_tsn_ack_point;
4466                // Window reset: everything previously tracked is now at/below
4467                // the cumulative ack point, so start the stream map fresh.
4468                self.fwd_tsn_stream_map.clear();
4469                self.i_fwd_tsn_stream_map.clear();
4470            }
4471
4472            self.advance_peer_ack_point();
4473            self.awake_write_loop();
4474        }
4475
4476        // RFC 9260 6.2.1 C: the chunks this SACK marked for retransmission go back to rwnd.
4477        let marked: usize = self.fast_retransmit_marked
4478            [marked_before.min(self.fast_retransmit_marked.len())..]
4479            .iter()
4480            .filter_map(|tsn| self.inflight_queue.get(*tsn))
4481            .map(|c| c.user_data.len())
4482            .sum();
4483        self.rwnd = self
4484            .rwnd
4485            .saturating_add(u32::try_from(marked).unwrap_or(u32::MAX));
4486
4487        self.postprocess_sack(state, cum_tsn_ack_point_advanced, now);
4488
4489        // The peer's SSN/TSN reset waited for what this side had outstanding.
4490        Ok(self.perform_deferred_tsn_reset())
4491    }
4492
4493    fn handle_forward_tsn(&mut self, c: &ChunkForwardTsn) -> Result<Vec<Packet>> {
4494        trace!("[{}] FwdTSN: {}", self.side, c);
4495
4496        if self.use_interleaving {
4497            // RFC 8260 2.3.1: FORWARD TSN is not used with I-DATA.
4498            warn!("[{}] FORWARD TSN with I-DATA in use: aborting", self.side);
4499            self.abort_with(
4500                vec![Self::protocol_violation(
4501                    "FORWARD-TSN with user message interleaving (RFC 8260 2.3.1)",
4502                )],
4503                AssociationError::TransportError,
4504            )?;
4505            return Ok(vec![]);
4506        }
4507
4508        if !self.use_forward_tsn {
4509            warn!("[{}] received FwdTSN but not enabled", self.side);
4510            // RFC 3758 3.3.1: answered as a chunk this side does not recognize, with the
4511            // chunk in the cause.
4512            self.report_error(ErrorCause {
4513                code: UNRECOGNIZED_CHUNK_TYPE,
4514                raw: c.marshal()?,
4515            });
4516            return Ok(vec![]);
4517        }
4518
4519        // From RFC 3758 Sec 3.6:
4520        //   Note, if the "New Cumulative TSN" value carried in the arrived
4521        //   FORWARD TSN chunk is found to be behind or at the current cumulative
4522        //   TSN point, the data receiver MUST treat this FORWARD TSN as out-of-
4523        //   date and MUST NOT update its Cumulative TSN.  The receiver SHOULD
4524        //   send a SACK to its peer (the sender of the FORWARD TSN) since such a
4525        //   duplicate may indicate the previous SACK was lost in the network.
4526
4527        trace!(
4528            "[{}] should send ack? newCumTSN={} peer_last_tsn={}",
4529            self.side, c.new_cumulative_tsn, self.peer_last_tsn
4530        );
4531        let Some(prev_peer_last_tsn) = self.forward_cumulative_tsn(c.new_cumulative_tsn) else {
4532            return Ok(vec![]);
4533        };
4534
4535        // From RFC 3758 Sec 3.6:
4536        //   the receiver MUST perform the same TSN handling, including duplicate
4537        //   detection, gap detection, SACK generation, cumulative TSN
4538        //   advancement, etc. as defined in RFC 2960 [2]---with the following
4539        //   exceptions and additions.
4540
4541        //   When a FORWARD TSN chunk arrives, the data receiver MUST first update
4542        //   its cumulative TSN point to the value carried in the FORWARD TSN
4543        //   chunk,
4544
4545        // Report new peer_last_tsn value and abandoned largest SSN value to
4546        // corresponding streams so that the abandoned chunks can be removed
4547        // from the reassemblyQueue. A stream is visited once, for the largest SSN the chunk
4548        // names for it (RFC 3758 3.5: an entry carries "the largest stream sequence number in
4549        // this stream being skipped"): a chunk that names one stream thousands of times
4550        // would otherwise cost a pass over its reassembly queue per entry.
4551        let forwarded = largest_per_stream(
4552            c.streams
4553                .iter()
4554                .map(|forwarded| (forwarded.identifier, forwarded.sequence)),
4555            sna16lt,
4556        );
4557        for (identifier, sequence) in forwarded {
4558            if let Some(s) = self.streams.get_mut(&identifier) {
4559                let bytes_before = s.get_num_bytes_in_reassembly_queue();
4560                s.handle_forward_tsn_for_ordered(sequence);
4561                if s.reassembly_queue.is_readable() {
4562                    self.events.push_back(Event::Stream(StreamEvent::Readable {
4563                        id: s.stream_identifier,
4564                    }));
4565                }
4566                self.reindex_stream(identifier, bytes_before);
4567            } else {
4568                // RFC 3758 3.6: the receiver "MUST ... mark the stream sequence number(s) as
4569                // received" for the streams the chunk lists, also one whose first message was
4570                // abandoned before any of it arrived. Forgotten, the next message on it waited
4571                // for the skipped one for good.
4572                self.remember_skipped_on_absent_stream(identifier, false, u32::from(sequence));
4573            }
4574        }
4575
4576        // TSN may be forwarded for unordered chunks. ForwardTSN chunk does not
4577        // report which stream identifier it skipped for unordered chunks.
4578        // Therefore, we need to broadcast this event to all existing streams for
4579        // unordered chunks. A stream with an empty reassembly queue has nothing to
4580        // forward and nothing to read, so only the streams holding data are visited.
4581        let with_data: Vec<StreamId> = self.streams_with_data.iter().copied().collect();
4582        for id in with_data {
4583            if let Some(s) = self.streams.get_mut(&id) {
4584                let bytes_before = s.get_num_bytes_in_reassembly_queue();
4585                s.handle_forward_tsn_for_unordered(c.new_cumulative_tsn);
4586                if s.reassembly_queue.is_readable() {
4587                    self.events.push_back(Event::Stream(StreamEvent::Readable {
4588                        id: s.stream_identifier,
4589                    }));
4590                }
4591                self.reindex_stream(id, bytes_before);
4592            }
4593        }
4594
4595        // A stored reset request the new cumulative TSN reached is performed now, after the
4596        // streams have taken what the FORWARD TSN made readable.
4597        let mut reset_reply = vec![];
4598        self.reset_streams_reached_since(prev_peer_last_tsn, &mut reset_reply)?;
4599        let mut reply = self.handle_peer_last_tsn_and_acknowledgement(false)?;
4600        reset_reply.append(&mut reply);
4601        Ok(reset_reply)
4602    }
4603
4604    fn handle_shutdown(&mut self, c: &ChunkShutdown, now: Instant) -> Result<Vec<Packet>> {
4605        let state = self.state();
4606
4607        if state == AssociationState::Established
4608            || state == AssociationState::ShutdownReceived
4609            || state == AssociationState::ShutdownPending
4610        {
4611            // RFC 9260 9.2: a SHUTDOWN is taken in SHUTDOWN-PENDING too (both sides are
4612            // shutting down and the peer's SHUTDOWN came first).
4613            //
4614            // RFC 9260 9.2: the SHUTDOWN's Cumulative TSN Ack acknowledges our DATA up to it,
4615            // and the receiver checks by it that all its outstanding DATA has arrived. A
4616            // SHUTDOWN that crossed our last SACK is the only acknowledgement left for the
4617            // data in flight, so without this the association waited for T3-rtx.
4618            self.acknowledge_by_shutdown(c.cumulative_tsn_ack, now)?;
4619            if self.state() != state {
4620                // The acknowledgement drained the queue from SHUTDOWN-RECEIVED, which
4621                // already moved on to SHUTDOWN-ACK-SENT.
4622                return Ok(vec![]);
4623            }
4624
4625            if !self.nothing_left_to_send() {
4626                self.set_state(AssociationState::ShutdownReceived);
4627            } else {
4628                // No more outstanding, send shutdown ack.
4629                self.will_send_shutdown_ack = true;
4630                self.set_state(AssociationState::ShutdownAckSent);
4631
4632                self.awake_write_loop();
4633            }
4634        } else if state == AssociationState::ShutdownSent {
4635            self.will_send_shutdown_ack = true;
4636            self.set_state(AssociationState::ShutdownAckSent);
4637
4638            self.awake_write_loop();
4639        }
4640
4641        Ok(vec![])
4642    }
4643
4644    /// Processes a SHUTDOWN's Cumulative TSN Ack as a SACK without gap blocks (RFC 9260 9.2).
4645    ///
4646    /// The peer's receive window is left as it was: a SHUTDOWN does not carry one.
4647    fn acknowledge_by_shutdown(&mut self, cumulative_tsn_ack: u32, now: Instant) -> Result<()> {
4648        if !sna32gt(cumulative_tsn_ack, self.cumulative_tsn_ack_point)
4649            || sna32gte(cumulative_tsn_ack, self.my_next_tsn)
4650        {
4651            return Ok(());
4652        }
4653        let outstanding = self.inflight_queue.get_num_bytes() as u32;
4654        let sack = ChunkSelectiveAck {
4655            cumulative_tsn_ack,
4656            advertised_receiver_window_credit: self.rwnd.saturating_add(outstanding),
4657            gap_ack_blocks: vec![],
4658            duplicate_tsn: vec![],
4659        };
4660        // RFC 9260 3.3.8: a SHUTDOWN has no Gap Ack Blocks, and their absence is no renege.
4661        self.acknowledging_by_shutdown = true;
4662        let handled = self.handle_sack(&sack, now);
4663        self.acknowledging_by_shutdown = false;
4664        handled?;
4665        Ok(())
4666    }
4667
4668    fn handle_shutdown_ack(&mut self, _: &ChunkShutdownAck) -> Result<Vec<Packet>> {
4669        let state = self.state();
4670        if state == AssociationState::ShutdownSent || state == AssociationState::ShutdownAckSent {
4671            self.timers.stop(Timer::T2Shutdown);
4672            self.will_send_shutdown_complete = true;
4673            // RFC 9260 9.2: the SHUTDOWN ACK ends the association here ("send a SHUTDOWN
4674            // COMPLETE chunk to its peer, and remove all record of the association"); 6.10:
4675            // nothing the peer sends comes after it in its packet. DATA bundled after it (ETSI
4676            // TS 102 369 bdc-v-7-8) was taken and answered with a SACK and a new SHUTDOWN
4677            // before the SHUTDOWN COMPLETE: two control packets for one (12.4).
4678            self.discard_rest_of_packet = true;
4679
4680            self.awake_write_loop();
4681        }
4682
4683        Ok(vec![])
4684    }
4685
4686    fn handle_shutdown_complete(&mut self, _: &ChunkShutdownComplete) -> Result<Vec<Packet>> {
4687        let state = self.state();
4688        if state == AssociationState::ShutdownAckSent {
4689            self.timers.stop(Timer::T2Shutdown);
4690            self.close(AssociationError::AssociationClosed)?;
4691        }
4692
4693        Ok(vec![])
4694    }
4695
4696    /// A common routine for handle_data and handle_forward_tsn routines
4697    fn handle_peer_last_tsn_and_acknowledgement(
4698        &mut self,
4699        sack_immediately: bool,
4700    ) -> Result<Vec<Packet>> {
4701        let mut reply = vec![];
4702        let prev_peer_last_tsn = self.peer_last_tsn;
4703
4704        // Try to advance peer_last_tsn
4705
4706        // From RFC 3758 Sec 3.6:
4707        //   .. and then MUST further advance its cumulative TSN point locally
4708        //   if possible
4709        // Meaning, if peer_last_tsn+1 points to a chunk that is received,
4710        // advance peer_last_tsn until peer_last_tsn+1 points to unreceived chunk.
4711        //debug!("[{}] peer_last_tsn = {}", self.side, self.peer_last_tsn);
4712        // TSNs are serial numbers (RFC 4960 §1.6): the cumulative point wraps past u32::MAX,
4713        // which a peer reaches at once with an initial TSN of 0 or a FORWARD-TSN to u32::MAX.
4714        while self
4715            .payload_queue
4716            .pop(self.peer_last_tsn.wrapping_add(1))
4717            .is_some()
4718        {
4719            self.peer_last_tsn = self.peer_last_tsn.wrapping_add(1);
4720            //debug!("[{}] peer_last_tsn = {}", self.side, self.peer_last_tsn);
4721        }
4722        // The cumulative TSN passed a TSN that came late and the ones held after it: a
4723        // fragment held from before may only now be known to have lost the start of its
4724        // message (the check made as each fragment arrives saw the TSN before it missing).
4725        if self.peer_last_tsn.wrapping_sub(prev_peer_last_tsn) >= 2
4726            && sna32gt(self.peer_last_tsn, prev_peer_last_tsn)
4727        {
4728            self.discard_orphaned_fragments();
4729        }
4730
4731        // Perform the stored reset requests the cumulative TSN has just reached, each once.
4732        // A request reached earlier and still stored waits for its stream to drain
4733        // (`retry_deferred_resets`), so it is not answered again here.
4734        self.reset_streams_reached_since(prev_peer_last_tsn, &mut reply)?;
4735
4736        let has_packet_loss = !self.payload_queue.is_empty();
4737        if has_packet_loss {
4738            trace!(
4739                "[{}] packetloss: {}",
4740                self.side,
4741                self.payload_queue
4742                    .get_gap_ack_blocks_string(self.peer_last_tsn)
4743            );
4744        }
4745
4746        if (self.ack_state != AckState::Immediate
4747            && !sack_immediately
4748            && !has_packet_loss
4749            && self.ack_mode == AckMode::Normal)
4750            || self.ack_mode == AckMode::AlwaysDelay
4751        {
4752            if self.ack_state == AckState::Idle {
4753                self.delayed_ack_triggered = true;
4754            } else {
4755                self.immediate_ack_triggered = true;
4756            }
4757        } else {
4758            self.immediate_ack_triggered = true;
4759        }
4760
4761        Ok(reply)
4762    }
4763
4764    fn process_selective_ack(
4765        &mut self,
4766        d: &ChunkSelectiveAck,
4767        now: Instant,
4768    ) -> Result<(FxHashMap<u16, i64>, i64, u32)> {
4769        let mut bytes_acked_per_stream = FxHashMap::default();
4770        let mut total_bytes_acked = 0;
4771        let mut newly_acked_data = false;
4772        // Abandoned DATA can precede the earliest outstanding TSN. RFC 9260
4773        // 6.3.2 R3 applies to that outstanding DATA, including gap acknowledgments.
4774        let earliest_outstanding = self.inflight_queue.sorted.iter().copied().find(|tsn| {
4775            self.inflight_queue
4776                .get(*tsn)
4777                .is_some_and(ChunkPayloadData::is_outstanding)
4778        });
4779
4780        // New ack point, so pop all ACKed packets from inflight_queue
4781        // We add 1 because the "currentAckPoint" has already been popped from the inflight queue
4782        // For the first SACK we take care of this by setting the ackpoint to cumAck - 1
4783        let mut i = self.cumulative_tsn_ack_point.wrapping_add(1);
4784        //log::debug!("[{}] i={} d={}", self.name, i, d.cumulative_tsn_ack);
4785        while sna32lte(i, d.cumulative_tsn_ack) {
4786            if let Some(mut c) = self.inflight_queue.pop(i) {
4787                let wire = counted_wire_size(&c);
4788                if wire > 0 && !c.abandoned() {
4789                    self.note_acknowledged(c.tsn, wire);
4790                }
4791                if c.acknowledge() {
4792                    newly_acked_data |= c.nsent > 0;
4793
4794                    let n_bytes_acked = c.user_data.len() as i64;
4795                    // RFC 9260 7.2, 7.2.1, 7.2.2: the congestion control counts the chunk with
4796                    // its header and padding.
4797                    total_bytes_acked += wire as i64;
4798                    // A late SACK for a retired stream must not release bytes
4799                    // belonging to a new channel that reused its SID.
4800                    if self.is_current_stream_data(&c) {
4801                        *bytes_acked_per_stream
4802                            .entry(c.stream_identifier)
4803                            .or_default() += n_bytes_acked;
4804                    }
4805
4806                    // RFC 4960 sec 6.3.1.  RTO Calculation
4807                    //   C4)  When data is in flight and when allowed by rule C5 below, a new
4808                    //        RTT measurement MUST be made each round trip.  Furthermore, new
4809                    //        RTT measurements SHOULD be made no more than once per round trip
4810                    //        for a given destination transport address.
4811                    //   C5)  Karn's algorithm: RTT measurements MUST NOT be made using
4812                    //        packets that were retransmitted (and thus for which it is
4813                    //        ambiguous whether the reply was for the first instance of the
4814                    //        chunk or for a later instance)
4815                    if !c.abandoned() && c.nsent == 1 && sna32gte(c.tsn, self.min_tsn2measure_rtt) {
4816                        self.min_tsn2measure_rtt = self.my_next_tsn;
4817                        if let Some(since) = &c.since {
4818                            let rtt = now.duration_since(*since);
4819                            let srtt = self.rto_mgr.set_new_rtt(rtt.as_millis() as u64);
4820                            trace!(
4821                                "[{}] SACK: measured-rtt={} srtt={} new-rto={}",
4822                                self.side,
4823                                rtt.as_millis(),
4824                                srtt,
4825                                self.rto_mgr.get_rto()
4826                            );
4827                        } else {
4828                            error!("[{}] invalid c.since", self.side);
4829                        }
4830                    }
4831                }
4832
4833                if self.in_fast_recovery && c.tsn == self.fast_recover_exit_point {
4834                    debug!("[{}] exit fast-recovery", self.side);
4835                    self.in_fast_recovery = false;
4836                }
4837            } else {
4838                return Err(Error::ErrInflightQueueTsnPop);
4839            }
4840
4841            i = i.wrapping_add(1);
4842        }
4843
4844        let mut htna = d.cumulative_tsn_ack;
4845
4846        // RFC 9260 6.2.1 D iii, 6.3.2 R4: a TSN an earlier Gap Ack Block acknowledged that
4847        // this SACK neither covers cumulatively nor in a block was reneged on by the
4848        // receiver: it is outstanding again, counts one miss indication towards Fast
4849        // Retransmit, and T3-rtx runs if it was not running.
4850        let gap_acknowledged = if self.acknowledging_by_shutdown {
4851            vec![]
4852        } else {
4853            self.inflight_queue.gap_acknowledged()
4854        };
4855        let reneged: Vec<u32> = gap_acknowledged
4856            .into_iter()
4857            .filter(|tsn| {
4858                sna32gt(*tsn, d.cumulative_tsn_ack)
4859                    && !d.gap_ack_blocks.iter().any(|g| {
4860                        let offset = tsn.wrapping_sub(d.cumulative_tsn_ack);
4861                        offset >= u32::from(g.start) && offset <= u32::from(g.end)
4862                    })
4863            })
4864            .collect();
4865        for tsn in &reneged {
4866            if self.inflight_queue.renege(*tsn) {
4867                debug!("[{}] SACK: the peer reneged on TSN {}", self.side, tsn);
4868                if let Some(c) = self.inflight_queue.get_mut(*tsn)
4869                    && c.miss_indicator < 3
4870                {
4871                    c.miss_indicator += 1;
4872                    if c.miss_indicator == 3 {
4873                        self.fast_retransmit_marked.push(*tsn);
4874                    }
4875                }
4876            }
4877        }
4878        if !reneged.is_empty() {
4879            self.timers
4880                .start_if_idle(Timer::T3RTX, now, self.rto_mgr.get_rto());
4881        }
4882        self.reneged_in_last_sack = reneged;
4883
4884        // Record peer acknowledgments independently of local payload release.
4885        for g in &d.gap_ack_blocks {
4886            for i in g.start..=g.end {
4887                let tsn = d.cumulative_tsn_ack.wrapping_add(i as u32);
4888                // Offset 0 is the Cumulative TSN Ack itself, which the SACK has acknowledged
4889                // already: a TSN this side sent, so no reason to abort (RFC 9260 12.4 is for
4890                // a TSN "that has not been sent"). It was taken for one.
4891                if i == 0 {
4892                    continue;
4893                }
4894
4895                let newly_acknowledged = self.inflight_queue.acknowledge(tsn);
4896                let wire = if newly_acknowledged {
4897                    self.inflight_queue.get(tsn).map_or(0, counted_wire_size) as i64
4898                } else {
4899                    0
4900                };
4901                // The payload stays until the Cumulative TSN Ack covers it: the receiver
4902                // may renege on what a Gap Ack Block acknowledged (RFC 9260 6.2.1).
4903                let n_bytes_acked = if newly_acknowledged {
4904                    self.inflight_queue.hold_acknowledged(tsn) as i64
4905                } else {
4906                    0
4907                };
4908
4909                if let Some(c) = self.inflight_queue.get(tsn) {
4910                    if newly_acknowledged {
4911                        newly_acked_data |= c.nsent > 0;
4912                        total_bytes_acked += wire;
4913                        if self.is_current_stream_data(c) {
4914                            *bytes_acked_per_stream
4915                                .entry(c.stream_identifier)
4916                                .or_default() += n_bytes_acked;
4917                        }
4918
4919                        trace!("[{}] tsn={} has been sacked", self.side, c.tsn);
4920
4921                        // RFC 9260 6.3.1 C4, C5: as for the cumulative TSN above, one
4922                        // measurement per round trip and none across a retransmission.
4923                        if !c.abandoned()
4924                            && c.nsent == 1
4925                            && sna32gte(c.tsn, self.min_tsn2measure_rtt)
4926                        {
4927                            self.min_tsn2measure_rtt = self.my_next_tsn;
4928                            if let Some(since) = &c.since {
4929                                let rtt = now.duration_since(*since);
4930                                let srtt = self.rto_mgr.set_new_rtt(rtt.as_millis() as u64);
4931                                trace!(
4932                                    "[{}] SACK: measured-rtt={} srtt={} new-rto={}",
4933                                    self.side,
4934                                    rtt.as_millis(),
4935                                    srtt,
4936                                    self.rto_mgr.get_rto()
4937                                );
4938                            } else {
4939                                error!("[{}] invalid c.since", self.side);
4940                            }
4941                        }
4942
4943                        if sna32lt(htna, tsn) {
4944                            htna = tsn;
4945                        }
4946                    }
4947                } else {
4948                    return Err(Error::ErrTsnRequestNotExist);
4949                }
4950            }
4951        }
4952
4953        // RFC 9260 8.1-8.2: an acknowledgment of new DATA clears the error
4954        // counter, including a late SACK after local abandonment. Payload
4955        // release does not acknowledge DATA; duplicates and never-sent TSNs
4956        // assigned only for FORWARD TSN do not count as newly acknowledged DATA.
4957        if newly_acked_data {
4958            self.timers.reset_retrans(Timer::T3RTX);
4959            self.on_path_success();
4960        }
4961        if earliest_outstanding.is_some_and(|tsn| {
4962            sna32lte(tsn, d.cumulative_tsn_ack)
4963                || self.inflight_queue.get(tsn).is_some_and(|c| c.acknowledged)
4964        }) {
4965            // Postprocessing restarts T3 with the current RTO if DATA/FORWARD
4966            // TSN remains outstanding.
4967            self.timers.set(Timer::T3RTX, None);
4968        }
4969        Ok((bytes_acked_per_stream, total_bytes_acked, htna))
4970    }
4971
4972    fn on_cumulative_tsn_ack_point_advanced(&mut self, now: Instant) {
4973        // RFC 4096, sec 6.3.2.  Retransmission Timer Rules
4974        //   R2)  Whenever all outstanding data sent to an address have been
4975        //        acknowledged, turn off the T3-rtx timer of that address.
4976        if self.inflight_queue.is_empty() {
4977            trace!(
4978                "[{}] SACK: no more packet in-flight (pending={})",
4979                self.side,
4980                self.pending_queue.len()
4981            );
4982            self.timers.stop(Timer::T3RTX);
4983        } else {
4984            trace!("[{}] T3-rtx timer start (pt2)", self.side);
4985            self.timers
4986                .start_if_idle(Timer::T3RTX, now, self.rto_mgr.get_rto());
4987        }
4988    }
4989
4990    /// RFC 9260 7.2.1 and 7.2.2: what a SACK does to the congestion window.
4991    ///
4992    /// `total_bytes_acked` is what the SACK newly acknowledged, by its Cumulative TSN Ack and
4993    /// by Gap Ack Blocks; `flight_before` the bytes outstanding before it.
4994    fn grow_congestion_window(
4995        &mut self,
4996        total_bytes_acked: i64,
4997        duplicate_bytes: u32,
4998        flight_before: u32,
4999        cum_tsn_ack_point_advanced: bool,
5000    ) {
5001        // Every addition below saturates: cwnd is bounded by nothing else, and a plain `+=`
5002        // wrapped it to a tiny window (and panicked with overflow checks on).
5003        let acked = u32::try_from(total_bytes_acked.max(0)).unwrap_or(u32::MAX);
5004        // The window was in full use if as much as it allows was outstanding. Rule B of 6.1
5005        // lets the last chunk sent cross it, so a sender with data to send gets there.
5006        let fully_utilized = flight_before >= self.cwnd;
5007
5008        if self.cwnd <= self.ssthresh {
5009            // 7.2.1, slow start: cwnd grows only if it is fully utilized, the SACK advances
5010            // the Cumulative TSN Ack Point and the sender is not in Fast Recovery, and then
5011            // by at most the lesser of the bytes acknowledged and L x PMDCS. The second bound
5012            // is what keeps a receiver from growing the window by splitting its SACKs.
5013            if fully_utilized && cum_tsn_ack_point_advanced && !self.in_fast_recovery {
5014                let limit = self.slow_start_growth_limit.saturating_mul(self.pmdcs);
5015                self.cwnd = self.cwnd.saturating_add(acked.min(limit));
5016                trace!(
5017                    "[{}] updated cwnd={} ssthresh={} acked={} (SS)",
5018                    self.side, self.cwnd, self.ssthresh, acked
5019                );
5020            }
5021        } else {
5022            // 7.2.2, congestion avoidance: partial_bytes_acked counts what every SACK newly
5023            // acknowledges. Once it reaches cwnd, and cwnd was in full use, cwnd grows by one
5024            // PMDCS: at most one per round trip. When cwnd was not in full use the count is
5025            // held at cwnd.
5026            self.partial_bytes_acked = self
5027                .partial_bytes_acked
5028                .saturating_add(acked)
5029                .saturating_add(duplicate_bytes);
5030            if fully_utilized {
5031                if self.partial_bytes_acked >= self.cwnd {
5032                    self.partial_bytes_acked -= self.cwnd;
5033                    self.cwnd = self.cwnd.saturating_add(self.pmdcs);
5034                    trace!(
5035                        "[{}] updated cwnd={} ssthresh={} acked={} (CA)",
5036                        self.side, self.cwnd, self.ssthresh, acked
5037                    );
5038                }
5039            } else if self.partial_bytes_acked > self.cwnd {
5040                self.partial_bytes_acked = self.cwnd;
5041            }
5042        }
5043
5044        // 7.2.2: when all the data sent has been acknowledged the count starts over.
5045        if self.inflight_queue.is_empty() {
5046            self.partial_bytes_acked = 0;
5047        }
5048    }
5049
5050    /// Remembers that the chunk `tsn`, `wire` bytes on the wire, was acknowledged, for a
5051    /// duplicate report of it later (`duplicate_bytes`).
5052    fn note_acknowledged(&mut self, tsn: u32, wire: usize) {
5053        const KEPT: usize = 4096;
5054        if self.recently_acknowledged.len() >= KEPT {
5055            self.recently_acknowledged.pop_front();
5056        }
5057        self.recently_acknowledged
5058            .push_back((tsn, u32::try_from(wire).unwrap_or(u32::MAX)));
5059    }
5060
5061    /// The wire bytes of the chunks a SACK reports as duplicates (RFC 9260 7.2.2), each chunk
5062    /// this side saw acknowledged counted once.
5063    fn duplicate_bytes(&mut self, duplicates: &[u32]) -> u32 {
5064        let mut bytes = 0u32;
5065        for tsn in duplicates {
5066            if let Some(at) = self
5067                .recently_acknowledged
5068                .iter()
5069                .position(|(acked, _)| acked == tsn)
5070                && let Some((_, wire)) = self.recently_acknowledged.remove(at)
5071            {
5072                bytes = bytes.saturating_add(wire);
5073            }
5074        }
5075        bytes
5076    }
5077
5078    /// RFC 9260 7.2.1: a congestion window that is not used decays, to max(cwnd / 2,
5079    /// 4 x PMDCS) once per RTO without DATA sent, and ssthresh takes the value cwnd had
5080    /// before the first of those steps. Applied when DATA is about to be sent after the
5081    /// pause, which is when the window matters.
5082    fn decay_idle_congestion_window(&mut self, now: Instant) {
5083        let Some(last) = self.last_data_sent else {
5084            return;
5085        };
5086        if !self.inflight_queue.is_empty() {
5087            return;
5088        }
5089        let rto = self.rto_mgr.get_rto().max(1);
5090        let idle = now.saturating_duration_since(last).as_millis() as u64;
5091        let floor = self.pmdcs.saturating_mul(4);
5092        let mut periods = idle / rto;
5093        if periods == 0 || self.cwnd <= floor {
5094            return;
5095        }
5096        self.ssthresh = self.cwnd;
5097        while periods > 0 && self.cwnd > floor {
5098            self.cwnd = (self.cwnd / 2).max(floor);
5099            periods -= 1;
5100        }
5101        self.partial_bytes_acked = 0;
5102        trace!(
5103            "[{}] updated cwnd={} ssthresh={} after {} ms idle",
5104            self.side, self.cwnd, self.ssthresh, idle
5105        );
5106    }
5107
5108    fn process_fast_retransmission(
5109        &mut self,
5110        cum_tsn_ack_point: u32,
5111        htna: u32,
5112        highest_reported: u32,
5113        cum_tsn_ack_point_advanced: bool,
5114        now: Instant,
5115    ) -> Result<()> {
5116        // RFC 9260 7.2.4, the HTNA algorithm: "For each incoming SACK chunk, miss indications
5117        // are incremented only for missing TSNs prior to the HTNA in the SACK chunk", and "if an
5118        // endpoint is in Fast Recovery and a SACK chunk arrives that advances the Cumulative
5119        // TSN Ack Point, the miss indications are incremented for all TSNs reported missing",
5120        // which are those below the highest TSN the SACK acknowledges. DATA sent after that
5121        // is not reported missing, only not acknowledged yet: counting it, as the whole
5122        // in-flight queue was counted here, retransmitted DATA that was not lost and
5123        // abandoned partially reliable messages that would have arrived.
5124        //
5125        // In Fast Recovery a SACK that does not advance the Cumulative TSN Ack Point counted
5126        // nothing here: a chunk lost inside the recovery window after it began was never
5127        // retransmitted by gap reports, however many reported it missing, and waited for
5128        // T3-rtx, which leaves one packet in flight at a doubling RTO. At 10 % loss a few lost
5129        // SACKs after that held 176 reliable messages back for more than 90 seconds.
5130        let max_tsn = if self.in_fast_recovery && cum_tsn_ack_point_advanced {
5131            highest_reported
5132        } else {
5133            htna
5134        };
5135        // A chunk that reaches three miss indications during a Fast Recovery that began
5136        // before this SACK, whether or not the SACK advances the Cumulative TSN Ack Point, is
5137        // not sent at once, ignoring cwnd: step 3 is "If not in Fast Recovery", for the SACK
5138        // that starts it. The chunk is marked for retransmission (step 1), goes out "as soon as
5139        // cwnd allows" and is not fast retransmitted again (step 5). A partially reliable
5140        // chunk whose retransmission budget is spent (RFC 3758 3.5 A3, RFC 7496 3.1) is never
5141        // sent again: it takes the fast retransmit path, which abandons it and sends FORWARD
5142        // TSN (RFC 3758 3.5 C1-C3) without waiting for the timer.
5143        let recovering = self.in_fast_recovery;
5144
5145        let mut tsn = cum_tsn_ack_point.wrapping_add(1);
5146        while sna32lt(tsn, max_tsn) {
5147            let reneged = self.reneged_in_last_sack.contains(&tsn);
5148            let Some(c) = self.inflight_queue.get(tsn) else {
5149                return Err(Error::ErrTsnRequestNotExist);
5150            };
5151            let exhausted = recovering
5152                && self.use_forward_tsn
5153                && c.is_outstanding()
5154                && self.retransmission_policy_exhausted(c, now, true);
5155            if let Some(c) = self.inflight_queue.get_mut(tsn)
5156                && c.is_outstanding()
5157                && c.miss_indicator < 3
5158                && !reneged
5159            {
5160                c.miss_indicator += 1;
5161                if c.miss_indicator == 3 {
5162                    if recovering && !exhausted {
5163                        if c.is_fast_retransmit_candidate() {
5164                            c.no_fast_retransmit = true;
5165                            c.retransmit = true;
5166                            self.t3_retransmit_pending = true;
5167                        }
5168                    } else {
5169                        self.fast_retransmit_marked.push(tsn);
5170                        if recovering {
5171                            self.will_retransmit_fast = true;
5172                        }
5173                    }
5174                }
5175                if c.miss_indicator == 3 && !self.in_fast_recovery {
5176                    // 2)  If not in Fast Recovery, adjust the ssthresh and cwnd of the
5177                    //     destination address(es) to which the missing DATA chunks were
5178                    //     last sent, according to the formula described in Section 7.2.3.
5179                    self.in_fast_recovery = true;
5180                    // RFC 9260 7.2.4 step 6: Fast Recovery lasts until everything
5181                    // outstanding now is acknowledged. The exit point was the highest
5182                    // TSN this SACK newly acknowledged, below it, so recovery ended
5183                    // early and a second loss in the same window cut cwnd again.
5184                    self.fast_recover_exit_point = self.my_next_tsn.wrapping_sub(1);
5185                    self.ssthresh = std::cmp::max(self.cwnd / 2, self.pmdcs.saturating_mul(4));
5186                    self.cwnd = self.ssthresh;
5187                    self.partial_bytes_acked = 0;
5188                    self.will_retransmit_fast = true;
5189
5190                    trace!(
5191                        "[{}] updated cwnd={} ssthresh={} inflight={} (FR)",
5192                        self.side,
5193                        self.cwnd,
5194                        self.ssthresh,
5195                        self.inflight_queue.get_num_bytes()
5196                    );
5197                }
5198            }
5199
5200            tsn = tsn.wrapping_add(1);
5201        }
5202
5203        Ok(())
5204    }
5205
5206    /// The caller must hold the lock. This method was only added because the
5207    /// linter was complaining about the "cognitive complexity" of handle_sack.
5208    fn postprocess_sack(
5209        &mut self,
5210        state: AssociationState,
5211        mut should_awake_write_loop: bool,
5212        now: Instant,
5213    ) {
5214        if !self.inflight_queue.is_empty() {
5215            // Start timer. (noop if already started)
5216            trace!("[{}] T3-rtx timer start (pt3)", self.side);
5217            self.timers
5218                .start_if_idle(Timer::T3RTX, now, self.rto_mgr.get_rto());
5219        } else if !self.pending_queue.is_empty() || self.held_write_count > 0 {
5220            // Queued DATA still goes out before the shutdown proceeds (RFC 9260 9.2).
5221        } else if state == AssociationState::ShutdownPending {
5222            // No more outstanding, send shutdown.
5223            should_awake_write_loop = true;
5224            self.send_shutdown();
5225        } else if state == AssociationState::ShutdownReceived {
5226            // No more outstanding, send shutdown ack.
5227            should_awake_write_loop = true;
5228            self.will_send_shutdown_ack = true;
5229            self.set_state(AssociationState::ShutdownAckSent);
5230        }
5231
5232        if should_awake_write_loop {
5233            self.awake_write_loop();
5234        }
5235    }
5236
5237    /// create_packet wraps chunks in a packet.
5238    /// The caller should hold the read lock.
5239    pub(crate) fn create_packet(&self, chunks: Vec<Box<dyn Chunk>>) -> Packet {
5240        Packet {
5241            common_header: CommonHeader {
5242                verification_tag: self.peer_verification_tag,
5243                source_port: self.source_port,
5244                destination_port: self.destination_port,
5245            },
5246            chunks,
5247        }
5248    }
5249
5250    /// Marshal a single control chunk into one SCTP packet, bypassing the
5251    /// `Vec<Box<dyn Chunk>>` + `Packet` allocations of `create_packet(..).marshal()`.
5252    /// Feeds the borrowed chunk straight to the shared framing path
5253    /// ([`Packet::write_framed`]). Used on the hot SACK / FORWARD-TSN send path
5254    /// (a SACK is emitted roughly every 1-2 inbound DATA chunks). The caller holds
5255    /// the lock.
5256    fn marshal_control_chunk(&self, chunk: &dyn Chunk) -> Result<Bytes> {
5257        let common_header = CommonHeader {
5258            verification_tag: self.peer_verification_tag,
5259            source_port: self.source_port,
5260            destination_port: self.destination_port,
5261        };
5262        // common header + chunk header + value + up to 3 bytes of trailing padding.
5263        let mut buf = BytesMut::with_capacity(
5264            COMMON_HEADER_SIZE as usize + CHUNK_HEADER_SIZE + chunk.value_length() + 3,
5265        );
5266        Packet::write_framed_with(
5267            &common_header,
5268            std::iter::once(chunk),
5269            &mut buf,
5270            self.send_zero_checksum,
5271        )?;
5272        Ok(buf.freeze())
5273    }
5274
5275    /// create_stream creates a stream. The caller should hold the lock and check no stream exists for this id.
5276    fn create_stream(
5277        &mut self,
5278        stream_identifier: StreamId,
5279        accept: bool,
5280        default_payload_type: PayloadProtocolIdentifier,
5281    ) -> Option<Stream<'_>> {
5282        let mut s = StreamState::new(
5283            self.side,
5284            stream_identifier,
5285            self.max_payload_size,
5286            default_payload_type,
5287        );
5288
5289        s.generation = self.next_stream_generation;
5290        self.next_stream_generation = self.next_stream_generation.wrapping_add(1);
5291        self.closed_stream_bytes_dequeued.remove(&stream_identifier);
5292        s.reassembly_queue.interleaved = self.use_interleaving;
5293        // A FORWARD TSN / I-FORWARD-TSN skipped messages of this stream before it existed:
5294        // it starts after them.
5295        for unordered in [false, true] {
5296            if let Some(sequence) = self
5297                .skipped_on_absent_streams
5298                .remove(&(stream_identifier, unordered))
5299            {
5300                if self.use_interleaving {
5301                    s.reassembly_queue.forward_mid(unordered, sequence);
5302                } else {
5303                    s.reassembly_queue.forward_tsn_for_ordered(sequence as u16);
5304                }
5305            }
5306        }
5307        self.pending_queue.forget_weight(stream_identifier);
5308
5309        if accept {
5310            self.stream_queue.push_back(stream_identifier);
5311            self.events.push_back(Event::Stream(StreamEvent::Opened {
5312                id: stream_identifier,
5313            }));
5314        }
5315
5316        let replaced_bytes = self
5317            .streams
5318            .insert(stream_identifier, s)
5319            .map_or(0, |old| old.get_num_bytes_in_reassembly_queue());
5320        self.reindex_stream(stream_identifier, replaced_bytes);
5321
5322        Some(Stream {
5323            stream_identifier,
5324            association: self,
5325        })
5326    }
5327
5328    /// Keeps what a FORWARD TSN (`sequence` an SSN) or I-FORWARD-TSN (a MID) skipped on
5329    /// stream `id`, which has no state here yet, for when the stream is created. A stream
5330    /// beyond the negotiated inbound count carries nothing (its DATA is discarded) and is
5331    /// not kept.
5332    pub(crate) fn remember_skipped_on_absent_stream(
5333        &mut self,
5334        id: StreamId,
5335        unordered: bool,
5336        sequence: u32,
5337    ) {
5338        if id >= self.my_max_num_inbound_streams {
5339            return;
5340        }
5341        let interleaved = self.use_interleaving;
5342        self.skipped_on_absent_streams
5343            .entry((id, unordered))
5344            .and_modify(|kept| {
5345                let later = if interleaved {
5346                    sna32lt(*kept, sequence)
5347                } else {
5348                    sna16lt(*kept as u16, sequence as u16)
5349                };
5350                if later {
5351                    *kept = sequence;
5352                }
5353            })
5354            .or_insert(sequence);
5355    }
5356
5357    /// get_or_create_stream gets or creates a stream. The caller should hold the lock.
5358    fn get_or_create_stream(&mut self, stream_identifier: StreamId) -> Option<Stream<'_>> {
5359        if self.streams.contains_key(&stream_identifier) {
5360            Some(Stream {
5361                stream_identifier,
5362                association: self,
5363            })
5364        } else {
5365            self.create_stream(
5366                stream_identifier,
5367                true,
5368                PayloadProtocolIdentifier::default(),
5369            )
5370        }
5371    }
5372
5373    /// Whether any stream currently holds a complete message the application could read.
5374    ///
5375    /// Distinguishes a receiver that is merely slow — it has data to take, and back-pressure
5376    /// should make it take it — from one wedged behind an incomplete chunk set, which cannot
5377    /// drain anything however attentive it is. Only the second justifies accepting a chunk
5378    /// into a full receive buffer.
5379    fn has_readable_data(&self) -> bool {
5380        !self.readable_streams.is_empty()
5381    }
5382
5383    fn bytes_in_reassembly_queues(&self) -> usize {
5384        self.reassembly_bytes
5385    }
5386
5387    /// Brings the running totals up to date after stream `id`'s reassembly queue changed
5388    /// from holding `bytes_before` bytes. A stream no longer in `streams` counts as empty.
5389    ///
5390    /// Every change to a reassembly queue goes through here, so the receive window and
5391    /// "is anything readable" cost the same however many streams the peer opened.
5392    pub(crate) fn reindex_stream(&mut self, id: StreamId, bytes_before: usize) {
5393        let (bytes_after, readable, holds_data, aborted) = match self.streams.get_mut(&id) {
5394            Some(s) => (
5395                s.get_num_bytes_in_reassembly_queue(),
5396                s.reassembly_queue.is_readable(),
5397                !s.reassembly_queue.is_empty(),
5398                s.reassembly_queue.take_partial_abort(),
5399            ),
5400            None => (0, false, false, None),
5401        };
5402        // RFC 6458 6.1.7, SCTP_PARTIAL_DELIVERY_ABORTED: "the user message gets abandoned
5403        // using PR-SCTP while the partial delivery of this message is going on".
5404        if let Some(abort) = aborted {
5405            debug!(
5406                "[{}] partial delivery of message {} on stream {id} aborted",
5407                self.side, abort.sequence
5408            );
5409            self.events
5410                .push_back(Event::Stream(StreamEvent::PartialDeliveryAborted {
5411                    id,
5412                    unordered: abort.unordered,
5413                    sequence: abort.sequence,
5414                }));
5415        }
5416        self.reassembly_bytes = self
5417            .reassembly_bytes
5418            .saturating_sub(bytes_before)
5419            .saturating_add(bytes_after);
5420        if readable {
5421            self.readable_streams.insert(id);
5422        } else {
5423            self.readable_streams.remove(&id);
5424        }
5425        if holds_data {
5426            self.streams_with_data.insert(id);
5427        } else {
5428            self.streams_with_data.remove(&id);
5429        }
5430        self.reindex_parts(id, readable);
5431    }
5432
5433    /// Brings `part_readable_streams` up to date for stream `id`, and announces a stream
5434    /// that has just come to hold part of a message to read (and nothing readable whole,
5435    /// which `StreamEvent::Readable` is raised for where the message completes).
5436    fn reindex_parts(&mut self, id: StreamId, readable: bool) {
5437        let threshold = self.partial_delivery_threshold();
5438        let parts = !readable
5439            && self
5440                .streams
5441                .get(&id)
5442                .is_some_and(|s| s.reassembly_queue.part_readable(threshold));
5443        if parts {
5444            if self.part_readable_streams.insert(id) {
5445                self.events
5446                    .push_back(Event::Stream(StreamEvent::Readable { id }));
5447            }
5448        } else {
5449            self.part_readable_streams.remove(&id);
5450        }
5451    }
5452
5453    /// RFC 9260 6.9: "If the data receiver runs out of buffer space while still waiting for
5454    /// more fragments to complete the reassembly of the message, it SHOULD dispatch part of
5455    /// its inbound message through a partial delivery API". Out of space is a window that
5456    /// would be advertised as closed (6.2, silly window avoidance included) with no message
5457    /// readable whole; then the first fragments of a message are given out whatever their
5458    /// size. Otherwise a message starts partial delivery at the partial delivery point
5459    /// (RFC 6458 8.1.21).
5460    pub(crate) fn partial_delivery_threshold(&self) -> usize {
5461        if self.advertised_window() == 0 && !self.has_readable_data() {
5462            1
5463        } else {
5464            self.partial_delivery_point.max(1) as usize
5465        }
5466    }
5467
5468    /// The receive buffer may have run out of space: every stream that holds the first
5469    /// fragments of a message is announced, so the application can take them in parts.
5470    pub(crate) fn offer_partial_delivery(&mut self) {
5471        if self.partial_delivery_threshold() > 1 || self.partial_delivery_point <= 1 {
5472            return;
5473        }
5474        let candidates: Vec<StreamId> = self
5475            .streams_with_data
5476            .iter()
5477            .copied()
5478            .filter(|id| {
5479                !self.readable_streams.contains(id) && !self.part_readable_streams.contains(id)
5480            })
5481            .collect();
5482        for id in candidates {
5483            self.reindex_parts(id, false);
5484        }
5485    }
5486
5487    /// The a_rwnd of the last SACK sent (tests outside this module).
5488    #[cfg(test)]
5489    pub(crate) fn last_advertised_window(&self) -> u32 {
5490        self.last_advertised_window
5491    }
5492
5493    pub(crate) fn get_my_receiver_window_credit(&self) -> u32 {
5494        let bytes_queued = u32::try_from(self.bytes_in_reassembly_queues()).unwrap_or(u32::MAX);
5495        self.max_receive_buffer_size.saturating_sub(bytes_queued)
5496    }
5497
5498    /// gather_outbound gathers outgoing packets. The returned bool value set to
5499    /// false means the association should be closed down after the final send.
5500    fn gather_outbound(&mut self, now: Instant) -> (Vec<Bytes>, bool) {
5501        let mut raw_packets = vec![];
5502        let state = self.state();
5503
5504        // RFC 9260 6.10, 12.4: control chunks share packets. The SACK that is due goes
5505        // with them; if there are none it goes with outbound DATA (6.1), or alone.
5506        let mut sack = None;
5507        if self.ack_state == AckState::Immediate
5508            && matches!(
5509                state,
5510                AssociationState::Established
5511                    | AssociationState::ShutdownPending
5512                    | AssociationState::ShutdownSent
5513                    | AssociationState::ShutdownReceived
5514            )
5515        {
5516            self.ack_state = AckState::Idle;
5517            let chunk = self.create_selective_ack_chunk();
5518            debug!("[{}] sending SACK: {}", self.side, chunk);
5519            sack = Some(chunk);
5520        }
5521        if !self.control_queue.is_empty() {
5522            let packets: Vec<Packet> = self.control_queue.drain(..).collect();
5523            let packets = self.bundle_data_with_cookie_echo(packets, now);
5524            for p in self.bundle_control_packets(packets, &mut sack) {
5525                if let Ok(raw) = self.marshal_packet(&p) {
5526                    raw_packets.push(raw);
5527                } else {
5528                    warn!("[{}] failed to serialize a control packet", self.side);
5529                    continue;
5530                }
5531            }
5532        }
5533        self.unbundled_sack = sack;
5534        self.first_data_packet = raw_packets.len();
5535
5536        match state {
5537            AssociationState::Established => {
5538                raw_packets = self.gather_data_packets_to_retransmit(raw_packets, now);
5539                if self.state() == AssociationState::Closed {
5540                    return (vec![], false);
5541                }
5542                raw_packets = self.gather_outbound_data_and_reconfig_packets(raw_packets, now);
5543                if self.state() == AssociationState::Closed {
5544                    return (vec![], false);
5545                }
5546                raw_packets = self.gather_outbound_fast_retransmission_packets(raw_packets, now);
5547                if self.state() == AssociationState::Closed {
5548                    return (vec![], false);
5549                }
5550                raw_packets = self.gather_outbound_sack_packets(raw_packets);
5551                raw_packets = self.gather_outbound_forward_tsn_packets(raw_packets, now);
5552                self.gather_path_mtu_probe(&mut raw_packets, now);
5553                (raw_packets, true)
5554            }
5555            AssociationState::ShutdownPending
5556            | AssociationState::ShutdownSent
5557            | AssociationState::ShutdownReceived => {
5558                raw_packets = self.gather_data_packets_to_retransmit(raw_packets, now);
5559                if self.state() == AssociationState::Closed {
5560                    return (vec![], false);
5561                }
5562                // RFC 9260 9.2: no new data is accepted, but what is already queued is still
5563                // sent, by the endpoint shutting down and by the one that received SHUTDOWN.
5564                // (In SHUTDOWN-SENT nothing is queued: SHUTDOWN waited for the queue.)
5565                if state != AssociationState::ShutdownSent {
5566                    raw_packets = self.gather_outbound_data_and_reconfig_packets(raw_packets, now);
5567                    if self.state() == AssociationState::Closed {
5568                        return (vec![], false);
5569                    }
5570                }
5571                raw_packets = self.gather_outbound_fast_retransmission_packets(raw_packets, now);
5572                if self.state() == AssociationState::Closed {
5573                    return (vec![], false);
5574                }
5575                raw_packets = self.gather_outbound_sack_packets(raw_packets);
5576                raw_packets = self.gather_outbound_forward_tsn_packets(raw_packets, now);
5577                // Everything handed over is sent and acknowledged (a queue can also empty by
5578                // abandonment, with no SACK to notice it): the shutdown proceeds.
5579                if self.nothing_left_to_send() {
5580                    if state == AssociationState::ShutdownPending {
5581                        self.send_shutdown();
5582                    } else if state == AssociationState::ShutdownReceived {
5583                        self.will_send_shutdown_ack = true;
5584                        self.set_state(AssociationState::ShutdownAckSent);
5585                    }
5586                }
5587                self.gather_outbound_shutdown_packets(raw_packets, now)
5588            }
5589            AssociationState::ShutdownAckSent => {
5590                self.gather_outbound_shutdown_packets(raw_packets, now)
5591            }
5592            _ => (raw_packets, true),
5593        }
5594    }
5595
5596    fn gather_data_packets_to_retransmit(
5597        &mut self,
5598        mut raw_packets: Vec<Bytes>,
5599        now: Instant,
5600    ) -> Vec<Bytes> {
5601        // Nothing is ever flagged for T3-rtx in the steady state, so skip the
5602        // full in-flight scan unless the T3-rtx timer has actually marked chunks.
5603        if self.t3_retransmit_pending
5604            && let Err(err) = self.get_data_packets_to_retransmit(now, &mut raw_packets)
5605        {
5606            self.fail_message_queue(err);
5607            raw_packets.clear();
5608        }
5609        raw_packets
5610    }
5611
5612    fn gather_outbound_data_and_reconfig_packets(
5613        &mut self,
5614        mut raw_packets: Vec<Bytes>,
5615        now: Instant,
5616    ) -> Vec<Bytes> {
5617        // Pop unsent data chunks from the pending queue to send as much as
5618        // cwnd and rwnd allow.
5619        let (mut chunks, resets) = self.pop_pending_data_chunks_to_send(now);
5620        if self.state() == AssociationState::Closed {
5621            return vec![];
5622        }
5623        // RFC 9260 3.3.1: "The (I)mmediate bit MAY be set by the sender whenever the sender of
5624        // a DATA chunk can benefit from the corresponding SACK chunk being sent back without
5625        // delay" (RFC 7053 4). The last DATA before a SHUTDOWN is such a chunk: the SHUTDOWN
5626        // waits for its acknowledgement (9.2), which a delayed SACK would hold back.
5627        if self.state() == AssociationState::ShutdownPending
5628            && self.pending_queue.is_empty()
5629            && self.held_write_count == 0
5630            && let Some(last) = chunks.last_mut()
5631        {
5632            last.immediate_sack = true;
5633        }
5634        if !chunks.is_empty() {
5635            // Start timer. (noop if already started)
5636            trace!("[{}] T3-rtx timer start (pt1)", self.side);
5637            self.timers
5638                .start_if_idle(Timer::T3RTX, now, self.rto_mgr.get_rto());
5639
5640            if self.pending_queue.one_stream_per_packet() {
5641                // RFC 8260 3.3: only chunks of the same stream are bundled in a packet.
5642                let mut run: Vec<ChunkPayloadData> = vec![];
5643                for chunk in chunks {
5644                    if run
5645                        .last()
5646                        .is_some_and(|last| last.stream_identifier != chunk.stream_identifier)
5647                    {
5648                        self.bundle_data_chunks_into_packets(
5649                            std::mem::take(&mut run),
5650                            &mut raw_packets,
5651                        );
5652                    }
5653                    run.push(chunk);
5654                }
5655                self.bundle_data_chunks_into_packets(run, &mut raw_packets);
5656            } else {
5657                self.bundle_data_chunks_into_packets(chunks, &mut raw_packets);
5658            }
5659        }
5660
5661        // RFC 6525 5.1.1: the request in flight is sent again when its timer has expired.
5662        if std::mem::take(&mut self.will_retransmit_reconfig) {
5663            debug!(
5664                "[{}] retransmit {} RECONFIG chunk(s)",
5665                self.side,
5666                self.reconfigs.len()
5667            );
5668            for c in self.reconfigs.values() {
5669                let p = self.create_packet(vec![Box::new(c.clone())]);
5670                if let Ok(raw) = self.marshal_packet(&p) {
5671                    raw_packets.push(raw);
5672                } else {
5673                    warn!(
5674                        "[{}] failed to serialize a RECONFIG packet to be retransmitted",
5675                        self.side,
5676                    );
5677                }
5678            }
5679        }
5680
5681        // The resets whose streams have sent what was queued before them become requests,
5682        // and the next request goes out if none is in flight.
5683        for marker in resets {
5684            self.on_reset_marker_ready(marker);
5685        }
5686        while let Some(packet) = self.next_reconfig_request(now) {
5687            if let Ok(raw) = self.marshal_packet(&packet) {
5688                raw_packets.push(raw);
5689            } else {
5690                warn!(
5691                    "[{}] failed to serialize a RECONFIG packet to be transmitted",
5692                    self.side
5693                );
5694            }
5695        }
5696
5697        // RFC 6525 5.1.1: a request outstanding is timed, whoever started it. The request
5698        // sent in answer to the peer's reset had no timer, so it was never retransmitted.
5699        if std::mem::take(&mut self.restart_reconfig_timer) {
5700            self.timers.stop(Timer::Reconfig);
5701        }
5702        if !self.reconfigs.is_empty() {
5703            self.timers
5704                .start_if_idle(Timer::Reconfig, now, self.rto_mgr.get_rto());
5705        }
5706
5707        raw_packets
5708    }
5709
5710    fn gather_outbound_fast_retransmission_packets(
5711        &mut self,
5712        mut raw_packets: Vec<Bytes>,
5713        now: Instant,
5714    ) -> Vec<Bytes> {
5715        if self.will_retransmit_fast {
5716            self.will_retransmit_fast = false;
5717
5718            let mut to_fast_retrans: Vec<ChunkPayloadData> = vec![];
5719            let mut fast_retrans_size = COMMON_HEADER_SIZE;
5720
5721            let mut i = 0;
5722            loop {
5723                let tsn = self.cumulative_tsn_ack_point.wrapping_add(i + 1);
5724                if let Some(c) = self.inflight_queue.get(tsn) {
5725                    if !c.is_fast_retransmit_candidate() {
5726                        i += 1;
5727                        continue;
5728                    }
5729
5730                    // Only the retry being considered needs a policy check.
5731                    // Retire an exhausted candidate's whole message first.
5732                    match self.abandon_retransmit_candidate(tsn, now) {
5733                        Ok(true) => {
5734                            self.stats.inc_fast_retrans_abandoned();
5735                            to_fast_retrans.retain(|chunk| {
5736                                self.inflight_queue
5737                                    .get(chunk.tsn)
5738                                    .is_some_and(|c| !c.abandoned())
5739                            });
5740                            fast_retrans_size = COMMON_HEADER_SIZE
5741                                + to_fast_retrans
5742                                    .iter()
5743                                    .map(|c| c.wire_size() as u32)
5744                                    .sum::<u32>();
5745                            i += 1;
5746                            continue;
5747                        }
5748                        Ok(false) => {}
5749                        Err(err) => {
5750                            self.fail_message_queue(err);
5751                            return vec![];
5752                        }
5753                    }
5754                    let Some(c) = self.inflight_queue.get(tsn) else {
5755                        break;
5756                    };
5757
5758                    // RFC 4960 Sec 7.2.4 Fast Retransmit on Gap Reports
5759                    //  3)  Determine how many of the earliest (i.e., lowest TSN) DATA chunks
5760                    //      marked for retransmission will fit into a single packet, subject
5761                    //      to constraint of the path MTU of the destination transport
5762                    //      address to which the packet is being sent.  Call this value K.
5763                    //      Retransmit those K DATA chunks in a single packet.  When a Fast
5764                    //      Retransmit is being performed, the sender SHOULD ignore the value
5765                    //      of cwnd and SHOULD NOT delay retransmission for this single
5766                    //		packet.
5767
5768                    // Padded wire size, the same accounting
5769                    // bundle_data_chunks_into_packets uses for bundle
5770                    // decisions.
5771                    let data_chunk_size = c.wire_size() as u32;
5772                    if self.mtu < fast_retrans_size + data_chunk_size {
5773                        break;
5774                    }
5775
5776                    fast_retrans_size += data_chunk_size;
5777                } else {
5778                    break; // end of pending data
5779                }
5780
5781                if let Some(c) = self.inflight_queue.get(tsn) {
5782                    to_fast_retrans.push(c.clone());
5783                }
5784                i += 1;
5785            }
5786
5787            // RFC 9260 7.2.4 step 5: the chunks marked for retransmission that did not fit
5788            // this one packet are no longer eligible for Fast Retransmit. They go out as
5789            // retransmissions when cwnd allows, instead of in a later burst that ignores it.
5790            // Only the chunks marked since the last Fast Retransmit are looked at, not the
5791            // window.
5792            for tsn in std::mem::take(&mut self.fast_retransmit_marked) {
5793                if to_fast_retrans.iter().any(|c| c.tsn == tsn) {
5794                    continue;
5795                }
5796                if let Some(c) = self.inflight_queue.get_mut(tsn)
5797                    && c.is_fast_retransmit_candidate()
5798                {
5799                    c.no_fast_retransmit = true;
5800                    c.retransmit = true;
5801                    self.t3_retransmit_pending = true;
5802                }
5803            }
5804
5805            // RFC 9260 7.2.4 step 4: T3-rtx starts over when the first outstanding chunk is
5806            // among those retransmitted (the count of its expiries is kept).
5807            let earliest_outstanding = self.inflight_queue.sorted.iter().copied().find(|tsn| {
5808                self.inflight_queue
5809                    .get(*tsn)
5810                    .is_some_and(ChunkPayloadData::is_outstanding)
5811            });
5812            if earliest_outstanding.is_some()
5813                && to_fast_retrans.first().map(|c| c.tsn) == earliest_outstanding
5814            {
5815                self.timers.set(
5816                    Timer::T3RTX,
5817                    Some(now + Duration::from_millis(self.rto_mgr.get_rto())),
5818                );
5819            }
5820
5821            if !to_fast_retrans.is_empty() {
5822                // RFC 9260 6.3.1 C5, as after a T3-rtx retransmission.
5823                self.min_tsn2measure_rtt = self.my_next_tsn;
5824            }
5825            for chunk in &mut to_fast_retrans {
5826                if let Some(c) = self.inflight_queue.get_mut(chunk.tsn) {
5827                    c.nsent += 1;
5828                    chunk.nsent = c.nsent;
5829                    self.stats.inc_retransmissions();
5830                    if c.reliability.limits_retransmission() {
5831                        self.stats.inc_partially_reliable_retransmissions();
5832                    }
5833                    // RFC 9260 6.2.1 B, for a Fast Retransmit too.
5834                    self.rwnd = self
5835                        .rwnd
5836                        .saturating_sub(u32::try_from(c.user_data.len()).unwrap_or(u32::MAX));
5837                    self.stats.inc_fast_retrans();
5838                    trace!(
5839                        "[{}] fast-retransmit: tsn={} sent={} htna={}",
5840                        self.side, c.tsn, c.nsent, self.fast_recover_exit_point
5841                    );
5842                }
5843            }
5844            self.bundle_data_chunks_into_packets(to_fast_retrans, &mut raw_packets);
5845        }
5846
5847        raw_packets
5848    }
5849
5850    fn gather_outbound_sack_packets(&mut self, mut raw_packets: Vec<Bytes>) -> Vec<Bytes> {
5851        if let Some(sack) = self.unbundled_sack.take() {
5852            // RFC 9260 6.1: "the endpoint SHOULD bundle the SACK with the outbound DATA".
5853            if self.bundle_with_data(&sack, &mut raw_packets, self.first_data_packet) {
5854                return raw_packets;
5855            }
5856            if let Ok(raw) = self.marshal_control_chunk(&sack) {
5857                raw_packets.push(raw);
5858            } else {
5859                warn!("[{}] failed to serialize a SACK packet", self.side);
5860            }
5861        }
5862
5863        raw_packets
5864    }
5865
5866    fn gather_outbound_forward_tsn_packets(
5867        &mut self,
5868        mut raw_packets: Vec<Bytes>,
5869        now: Instant,
5870    ) -> Vec<Bytes> {
5871        if !self.will_send_forward_tsn {
5872            return raw_packets;
5873        }
5874        if !sna32gt(
5875            self.advanced_peer_tsn_ack_point,
5876            self.cumulative_tsn_ack_point,
5877        ) {
5878            self.will_send_forward_tsn = false;
5879            self.forward_tsn_due_at = None;
5880            return raw_packets;
5881        }
5882        // RFC 8260 2.3.1: with I-DATA the chunk is I-FORWARD-TSN.
5883        let fwd_tsn: Box<dyn Chunk> = if self.use_interleaving {
5884            Box::new(self.create_i_forward_tsn())
5885        } else {
5886            Box::new(self.create_forward_tsn())
5887        };
5888        // RFC 3758 3.5 F2: it goes with outbound DATA when a packet has room.
5889        let first_data_packet = self.first_data_packet;
5890        if !self.bundle_with_data(fwd_tsn.as_ref(), &mut raw_packets, first_data_packet) {
5891            // F2: "A sender MAY even choose to delay the sending of the FORWARD TSN in the
5892            // hope of bundling it with an outbound DATA chunk"
5893            // (`TransportConfig::with_forward_tsn_delay`), F3: for no more than the delay,
5894            // counted from when it was first due.
5895            if let Some(delay) = self.forward_tsn_delay() {
5896                let due = *self.forward_tsn_due_at.get_or_insert(now + delay);
5897                if now < due {
5898                    return raw_packets;
5899                }
5900            }
5901            match self.marshal_control_chunk(fwd_tsn.as_ref()) {
5902                Ok(raw) => raw_packets.push(raw),
5903                Err(_) => {
5904                    warn!("[{}] failed to serialize a Forward TSN packet", self.side);
5905                    self.will_send_forward_tsn = false;
5906                    self.forward_tsn_due_at = None;
5907                    return raw_packets;
5908                }
5909            }
5910        }
5911        self.stats.inc_forward_tsns();
5912        self.will_send_forward_tsn = false;
5913        self.forward_tsn_due_at = None;
5914        raw_packets
5915    }
5916
5917    fn gather_outbound_shutdown_packets(
5918        &mut self,
5919        mut raw_packets: Vec<Bytes>,
5920        now: Instant,
5921    ) -> (Vec<Bytes>, bool) {
5922        let mut ok = true;
5923
5924        if self.will_send_shutdown {
5925            self.will_send_shutdown = false;
5926
5927            // RFC 9260 9.2: the SHUTDOWN carries the TSN of the last DATA chunk received in
5928            // sequence from the peer, which is what a SACK would acknowledge, not this side's
5929            // own acknowledgement point.
5930            let shutdown = ChunkShutdown {
5931                cumulative_tsn_ack: self.peer_last_tsn,
5932            };
5933            // RFC 9260 3.3.8: "The sender of the SHUTDOWN chunk MAY bundle a SACK chunk to
5934            // indicate any gaps in the received TSNs", which the SHUTDOWN's Cumulative TSN Ack
5935            // cannot report: the peer then knows what arrived beyond it and need not send it
5936            // again.
5937            let mut chunks: Vec<Box<dyn Chunk>> = vec![];
5938            if !self
5939                .payload_queue
5940                .get_gap_ack_blocks(self.peer_last_tsn)
5941                .is_empty()
5942            {
5943                chunks.push(Box::new(self.create_selective_ack_chunk()));
5944            }
5945            chunks.push(Box::new(shutdown));
5946
5947            if let Ok(raw) = self.marshal_packet(&self.create_packet(chunks)) {
5948                self.timers
5949                    .start(Timer::T2Shutdown, now, self.rto_mgr.get_rto());
5950                self.start_shutdown_guard(now);
5951                raw_packets.push(raw);
5952            } else {
5953                warn!("[{}] failed to serialize a Shutdown packet", self.side);
5954            }
5955        } else if self.will_send_shutdown_ack {
5956            self.will_send_shutdown_ack = false;
5957
5958            let shutdown_ack = ChunkShutdownAck {};
5959
5960            if let Ok(raw) = self.marshal_packet(&self.create_packet(vec![Box::new(shutdown_ack)]))
5961            {
5962                self.timers
5963                    .start(Timer::T2Shutdown, now, self.rto_mgr.get_rto());
5964                raw_packets.push(raw);
5965            } else {
5966                warn!("[{}] failed to serialize a ShutdownAck packet", self.side);
5967            }
5968        } else if self.will_send_shutdown_complete {
5969            self.will_send_shutdown_complete = false;
5970
5971            let shutdown_complete = ChunkShutdownComplete::default();
5972
5973            if let Ok(raw) =
5974                self.marshal_packet(&self.create_packet(vec![Box::new(shutdown_complete)]))
5975            {
5976                raw_packets.push(raw);
5977                ok = false;
5978            } else {
5979                warn!(
5980                    "[{}] failed to serialize a ShutdownComplete packet",
5981                    self.side
5982                );
5983            }
5984        }
5985
5986        (raw_packets, ok)
5987    }
5988
5989    /// get_data_packets_to_retransmit is called when T3-rtx is timed out and retransmit outstanding data chunks
5990    /// that are not acked or abandoned yet.
5991    fn get_data_packets_to_retransmit(
5992        &mut self,
5993        now: Instant,
5994        raw_packets: &mut Vec<Bytes>,
5995    ) -> Result<()> {
5996        // RFC 9260 6.3.3 E3, 7.2.3: the retransmission that follows a T3-rtx expiry is the
5997        // earliest outstanding chunks that fit one packet, and that packet is alone in flight
5998        // until it is acknowledged. cwnd (one PMDCS) is counted in user bytes, which a second
5999        // packet of small chunks could still fit under.
6000        let single_packet = std::mem::take(&mut self.t3_single_packet);
6001        let mut packet_size = COMMON_HEADER_SIZE as usize;
6002        // RFC 9260 6.1: retransmissions are limited by cwnd too. What is marked for
6003        // retransmission is taken as lost, not as in flight; each chunk retransmitted is in
6004        // flight again. Counting only the bytes of one call, as this did, retransmitted a
6005        // window's worth on every poll, the whole of what was outstanding in the end.
6006        let mut in_flight = self
6007            .inflight_queue
6008            .get_num_bytes()
6009            .saturating_sub(self.inflight_queue.marked_for_retransmission_bytes());
6010        // What this call retransmits, against rwnd (6.2.1 B: rwnd is the peer's buffer
6011        // space, the bytes outstanding already taken out of it).
6012        let mut retransmitted = 0usize;
6013        let mut chunks: Vec<ChunkPayloadData> = vec![];
6014        let mut done = false;
6015        let mut i = 0;
6016        // Assume we will re-send every flagged chunk; flip back on if we stop
6017        // early (a marked chunk that doesn't fit awnd, or a zero-window probe)
6018        // so the next gather_outbound still scans.
6019        let mut chunks_remaining = false;
6020        while !done {
6021            let tsn = self.cumulative_tsn_ack_point.wrapping_add(i + 1);
6022            if let Some(c) = self.inflight_queue.get(tsn) {
6023                if !c.retransmit {
6024                    i += 1;
6025                    continue;
6026                }
6027
6028                // A T3-marked candidate can expire while waiting for the send
6029                // window. Recheck it now (RFC 3758 TR4), without a window scan.
6030                if self.abandon_retransmit_candidate(tsn, now)? {
6031                    chunks.retain(|chunk| {
6032                        self.inflight_queue
6033                            .get(chunk.tsn)
6034                            .is_some_and(|c| !c.abandoned())
6035                    });
6036                    // The abandonment released payload and cleared marks: count again.
6037                    in_flight = self
6038                        .inflight_queue
6039                        .get_num_bytes()
6040                        .saturating_sub(self.inflight_queue.marked_for_retransmission_bytes())
6041                        + chunks.iter().map(|c| c.user_data.len()).sum::<usize>();
6042                    retransmitted = chunks.iter().map(|c| c.user_data.len()).sum::<usize>();
6043                    packet_size = COMMON_HEADER_SIZE as usize
6044                        + chunks.iter().map(|c| c.wire_size()).sum::<usize>();
6045                    i += 1;
6046                    continue;
6047                }
6048                let Some(c) = self.inflight_queue.get(tsn) else {
6049                    break;
6050                };
6051
6052                let wire = c.wire_size();
6053                if single_packet && !chunks.is_empty() && packet_size + wire > self.mtu as usize {
6054                    chunks_remaining = true;
6055                    break;
6056                }
6057                packet_size += wire;
6058
6059                if i == 0 && self.rwnd < c.user_data.len() as u32 {
6060                    // Send it as a zero window probe
6061                    done = true;
6062                    chunks_remaining = true;
6063                } else if (in_flight + c.user_data.len() > self.send_window() as usize
6064                    && in_flight > 0)
6065                    || (retransmitted + c.user_data.len() > self.rwnd as usize
6066                        && !chunks.is_empty())
6067                {
6068                    // With nothing in flight one chunk always goes, whatever its size.
6069                    chunks_remaining = true;
6070                    break;
6071                }
6072
6073                in_flight += c.user_data.len();
6074                retransmitted += c.user_data.len();
6075            } else {
6076                break; // end of pending data
6077            }
6078
6079            if let Some(c) = self.inflight_queue.get(tsn) {
6080                chunks.push(c.clone());
6081            }
6082            i += 1;
6083        }
6084
6085        // Cleared once the whole in-flight window has been rescanned with nothing
6086        // left flagged; kept set while awnd/zero-window left chunks behind.
6087        self.t3_retransmit_pending = chunks_remaining;
6088
6089        // RFC 9260 6.3.1 C5: no round trip is measured with a TSN sent before this
6090        // retransmission; an acknowledgement of it may be for either transmission of what
6091        // was sent again.
6092        if !chunks.is_empty() {
6093            self.min_tsn2measure_rtt = self.my_next_tsn;
6094        }
6095
6096        // A later candidate can abandon an earlier fragment already selected
6097        // into this batch. Commit attempts only after whole-message retirement.
6098        for chunk in &mut chunks {
6099            if let Some(c) = self.inflight_queue.get_mut(chunk.tsn) {
6100                c.retransmit = false;
6101                c.nsent += 1;
6102                chunk.nsent = c.nsent;
6103                self.stats.inc_retransmissions();
6104                if c.reliability.limits_retransmission() {
6105                    self.stats.inc_partially_reliable_retransmissions();
6106                }
6107                if self.t3_retransmitted.len() == MAX_T3_RETRANSMITTED_KEPT {
6108                    self.t3_retransmitted.pop_front();
6109                }
6110                self.t3_retransmitted.push_back(chunk.tsn);
6111                // RFC 9260 6.2.1 B: a retransmitted chunk takes its size from rwnd again.
6112                self.rwnd = self
6113                    .rwnd
6114                    .saturating_sub(u32::try_from(c.user_data.len()).unwrap_or(u32::MAX));
6115                trace!(
6116                    "[{}] retransmitting tsn={} ssn={} sent={}",
6117                    self.side, c.tsn, c.stream_sequence_number, c.nsent
6118                );
6119            }
6120        }
6121        self.bundle_data_chunks_into_packets(chunks, raw_packets);
6122        Ok(())
6123    }
6124
6125    fn release_stream_buffers(&mut self, bytes_acked_per_stream: &FxHashMap<u16, i64>) {
6126        for (si, n_bytes_acked) in bytes_acked_per_stream {
6127            if *n_bytes_acked > 0 {
6128                // Report the exact bytes released for this stream (acknowledged OR
6129                // abandoned — both funnel through bytes_acked_per_stream) so upper
6130                // layers can decrement their own send-buffer accounting. Unlike the
6131                // edge-triggered BufferedAmountLow advisory below, this fires on
6132                // every release with the byte delta.
6133                self.events
6134                    .push_back(Event::Stream(StreamEvent::BufferedAmountReleased {
6135                        id: *si,
6136                        n_bytes: *n_bytes_acked as usize,
6137                    }));
6138            }
6139            if let Some(s) = self.streams.get_mut(si)
6140                && s.on_buffer_released(*n_bytes_acked)
6141            {
6142                trace!("StreamEvent::BufferedAmountLow");
6143                self.events
6144                    .push_back(Event::Stream(StreamEvent::BufferedAmountLow { id: *si }))
6145            }
6146        }
6147    }
6148
6149    /// RFC 3758 section 3.5 C2-C4. Retain the stream map until the peer catches up.
6150    fn advance_peer_ack_point(&mut self) {
6151        let mut tsn = self.advanced_peer_tsn_ack_point.wrapping_add(1);
6152        while let Some(c) = self.inflight_queue.get(tsn) {
6153            if !c.abandoned() {
6154                break;
6155            }
6156            let (unordered, si, ssn) = (c.unordered, c.stream_identifier, c.stream_sequence_number);
6157            let (i_data, mid) = (c.i_data, c.mid);
6158            self.advanced_peer_tsn_ack_point = tsn;
6159            if i_data {
6160                self.note_abandoned_for_i_forward_tsn(unordered, si, mid);
6161            } else {
6162                self.note_abandoned_for_forward_tsn(unordered, si, ssn);
6163            }
6164            tsn = tsn.wrapping_add(1);
6165        }
6166        if sna32gt(
6167            self.advanced_peer_tsn_ack_point,
6168            self.cumulative_tsn_ack_point,
6169        ) {
6170            self.will_send_forward_tsn = true;
6171        } else {
6172            self.fwd_tsn_stream_map.clear();
6173            self.i_fwd_tsn_stream_map.clear();
6174        }
6175    }
6176
6177    fn timed_data_expired(&self, c: &ChunkPayloadData, now: Instant) -> bool {
6178        self.use_forward_tsn
6179            && c.reliability
6180                .deadline()
6181                .is_some_and(|deadline| now >= deadline)
6182    }
6183
6184    /// Application bytes of `stream_identifier` that have left the send queue (see
6185    /// [`Stream::bytes_dequeued`]). For a stream that was closed (reset, or lost with the
6186    /// association), the count it had when it was closed, until a stream with the same
6187    /// identifier is opened; 0 for a stream this association never held.
6188    pub fn stream_bytes_dequeued(&self, stream_identifier: StreamId) -> u64 {
6189        self.streams.get(&stream_identifier).map_or_else(
6190            || {
6191                self.closed_stream_bytes_dequeued
6192                    .get(&stream_identifier)
6193                    .copied()
6194                    .unwrap_or(0)
6195            },
6196            |s| s.bytes_dequeued,
6197        )
6198    }
6199
6200    /// The streams of the association before the peer's last restart (`Event::Restarted`),
6201    /// each with the application bytes that had left its send queue: what was sent on it
6202    /// before it went with the restart.
6203    pub fn streams_lost_in_restart(&self) -> &[(StreamId, u64)] {
6204        &self.streams_lost_in_restart
6205    }
6206
6207    /// Credits a chunk leaving the send queue to its stream's `bytes_dequeued`.
6208    fn note_dequeued(&mut self, c: &ChunkPayloadData) {
6209        if !matches!(
6210            c.payload_type,
6211            PayloadProtocolIdentifier::String | PayloadProtocolIdentifier::Binary
6212        ) || !self.is_current_stream_data(c)
6213        {
6214            return;
6215        }
6216        if let Some(s) = self.streams.get_mut(&c.stream_identifier) {
6217            s.bytes_dequeued += c.user_data.len() as u64;
6218        }
6219    }
6220
6221    fn is_current_stream_data(&self, c: &ChunkPayloadData) -> bool {
6222        self.streams
6223            .get(&c.stream_identifier)
6224            .is_some_and(|s| s.generation == c.stream_generation)
6225    }
6226
6227    /// A positive deadline can expire at any time. Timed(0) and Rexmit limits
6228    /// instead apply when this particular DATA is considered for retransmission.
6229    fn retransmission_policy_exhausted(
6230        &self,
6231        c: &ChunkPayloadData,
6232        now: Instant,
6233        is_candidate: bool,
6234    ) -> bool {
6235        if !self.use_forward_tsn {
6236            return false;
6237        }
6238        match c.reliability {
6239            MessageReliability::Reliable | MessageReliability::Priority { .. } => false,
6240            MessageReliability::Timed { deadline } => {
6241                now >= deadline && (Some(deadline) != c.created_at || is_candidate)
6242            }
6243            // RFC 7496 3.1: the limit excludes the first transmission and counts
6244            // both fast and timer-based retries. nsent includes that first send.
6245            MessageReliability::Rexmit { max_retransmits } => {
6246                is_candidate && c.nsent > max_retransmits
6247            }
6248        }
6249    }
6250
6251    fn abandon_retransmit_candidate(&mut self, tsn: u32, now: Instant) -> Result<bool> {
6252        let c = self
6253            .inflight_queue
6254            .get(tsn)
6255            .ok_or_else(|| Error::OtherSctpErr("missing retransmission candidate".into()))?;
6256        if !self.retransmission_policy_exhausted(c, now, true) {
6257            return Ok(false);
6258        }
6259        let message = MessageToAbandon {
6260            id: c.message_id.ok_or_else(|| {
6261                Error::OtherSctpErr("outbound DATA has no message identity".into())
6262            })?,
6263            sent_tsn: Some(tsn),
6264        };
6265        if self.abandon_message(message)? {
6266            self.on_messages_abandoned(now);
6267        }
6268        Ok(true)
6269    }
6270
6271    /// Select identities without changing ACK, retry or buffer state. Only a
6272    /// fragment selected for recovery can exhaust that message's retry budget.
6273    fn unretransmittable_messages(
6274        &self,
6275        now: Instant,
6276        is_candidate: impl Fn(&ChunkPayloadData) -> bool,
6277    ) -> Result<Vec<MessageToAbandon>> {
6278        let mut messages = vec![];
6279        let mut selected = FxHashSet::default();
6280        for &tsn in &self.inflight_queue.sorted {
6281            let c = self
6282                .inflight_queue
6283                .get(tsn)
6284                .ok_or_else(|| Error::OtherSctpErr("missing inflight message fragment".into()))?;
6285            if c.is_outstanding()
6286                && self.retransmission_policy_exhausted(c, now, is_candidate(c))
6287                && let Some(id) = c.message_id
6288                && selected.insert(id)
6289            {
6290                messages.push(MessageToAbandon {
6291                    id,
6292                    sent_tsn: Some(tsn),
6293                });
6294            }
6295        }
6296        Ok(messages)
6297    }
6298
6299    /// RFC 3758 A2/A3: abandon all fragments by identity, including Gap-ACKed
6300    /// siblings and an unsent tail. Each payload is released at most once.
6301    /// FORWARD TSN and timers are updated after the complete operation.
6302    fn abandon_message(&mut self, message: MessageToAbandon) -> Result<bool> {
6303        let whole_tsn = message.sent_tsn.filter(|&tsn| {
6304            self.inflight_queue.get(tsn).is_some_and(|c| {
6305                c.message_id == Some(message.id) && c.beginning_fragment && c.ending_fragment
6306            })
6307        });
6308        let mut inflight = whole_tsn.map_or_else(
6309            || self.inflight_queue.message_tsns(message.id),
6310            |tsn| vec![tsn],
6311        );
6312        let mut released_per_stream = FxHashMap::default();
6313        let mut changed = false;
6314        let transmitted = !inflight.is_empty();
6315        let tail = self.pending_queue.drain_message(message.id)?;
6316        // The stream the message was written to, if it is still the stream of that id.
6317        let stream = tail
6318            .first()
6319            .or_else(|| {
6320                inflight
6321                    .first()
6322                    .and_then(|tsn| self.inflight_queue.get(*tsn))
6323            })
6324            .filter(|c| self.is_current_stream_data(c))
6325            .map(|c| c.stream_identifier);
6326        // A message none of which was sent goes without TSNs, unless it is ordered and has
6327        // its Stream Sequence Number already: the peer then waits for that number, and only
6328        // a FORWARD TSN past it lets the stream go on.
6329        let assign_tsns = !inflight.is_empty()
6330            || tail
6331                .first()
6332                .is_some_and(|c| !c.beginning_fragment || (!c.unordered && !c.numbers_pending));
6333        for mut c in tail {
6334            self.note_dequeued(&c);
6335            if assign_tsns {
6336                c.tsn = self.generate_next_tsn();
6337                inflight.push(c.tsn);
6338                self.inflight_queue.push_no_check(c);
6339            } else {
6340                if self.is_current_stream_data(&c) {
6341                    *released_per_stream.entry(c.stream_identifier).or_default() +=
6342                        c.user_data.len() as i64;
6343                }
6344                changed = true;
6345            }
6346        }
6347        for tsn in inflight {
6348            if let Some(c) = self.inflight_queue.get_mut(tsn) {
6349                changed |= !c.abandoned();
6350                c.mark_abandoned();
6351                let (si, generation) = (c.stream_identifier, c.stream_generation);
6352                let released = self.inflight_queue.release_payload(tsn) as i64;
6353                if released > 0
6354                    && self
6355                        .streams
6356                        .get(&si)
6357                        .is_some_and(|s| s.generation == generation)
6358                {
6359                    *released_per_stream.entry(si).or_default() += released;
6360                }
6361            }
6362        }
6363        self.release_stream_buffers(&released_per_stream);
6364        if changed {
6365            self.stats.inc_abandoned_messages();
6366        }
6367        if changed && let Some(id) = stream {
6368            // RFC 3758 4.1 TR3: the upper layer is told.
6369            self.events
6370                .push_back(Event::Stream(StreamEvent::MessageAbandoned {
6371                    id,
6372                    transmitted,
6373                }));
6374        }
6375        Ok(changed)
6376    }
6377
6378    /// RFC 7496 3.2, the priority policy: room in a send buffer of a set size
6379    /// (`TransportConfig::with_send_buffer_size`) for a message of `bytes` sent with
6380    /// `reliability`. When it does not fit, the unsent messages of the policy with a lower
6381    /// priority (a larger value) are abandoned, the lowest first and the earliest written among
6382    /// equals, as long as that makes room; a message written without the policy ranks above
6383    /// every one of them ("User messages sent reliably are considered to have a priority
6384    /// higher than all messages sent with the Priority Policy"). When abandoning all of them
6385    /// would not make room, nothing is abandoned and the write fails with `ErrBufferFull`.
6386    pub(crate) fn make_room_in_send_buffer(
6387        &mut self,
6388        bytes: usize,
6389        reliability: MessageReliability,
6390    ) -> Result<()> {
6391        let Some(size) = self
6392            .transport_config
6393            .as_ref()
6394            .and_then(|config| config.send_buffer_size())
6395        else {
6396            return Ok(());
6397        };
6398        let used = self.buffered_amount();
6399        let Some(excess) = (used + bytes).checked_sub(size as usize).filter(|n| *n > 0) else {
6400            return Ok(());
6401        };
6402        let rank = match reliability {
6403            MessageReliability::Priority { priority } => Some(priority),
6404            _ => None,
6405        };
6406        let mut candidates: Vec<_> = self
6407            .pending_queue
6408            .unsent_priority_messages()
6409            .into_iter()
6410            .filter(|&(_, priority, _, _)| rank.is_none_or(|rank| priority > rank))
6411            .collect();
6412        candidates.sort_by_key(|&(_, priority, _, arrival)| (std::cmp::Reverse(priority), arrival));
6413        let mut freed = 0;
6414        let mut chosen = vec![];
6415        for (id, _, message_bytes, _) in candidates {
6416            if freed >= excess {
6417                break;
6418            }
6419            freed += message_bytes;
6420            chosen.push(id);
6421        }
6422        if freed < excess {
6423            return Err(Error::ErrBufferFull);
6424        }
6425        for id in chosen {
6426            self.abandon_unsent_message(id)?;
6427        }
6428        Ok(())
6429    }
6430
6431    /// Abandons a message nothing of which has been sent (RFC 7496 3.2): it leaves the send
6432    /// queue without a TSN, and the upper layer is told.
6433    fn abandon_unsent_message(&mut self, id: MessageId) -> Result<()> {
6434        let chunks = self.pending_queue.remove_unsent_message(id)?;
6435        let Some(first) = chunks.first() else {
6436            return Ok(());
6437        };
6438        let stream = self
6439            .is_current_stream_data(first)
6440            .then_some(first.stream_identifier);
6441        let mut released_per_stream = FxHashMap::default();
6442        for c in &chunks {
6443            self.note_dequeued(c);
6444            if self.is_current_stream_data(c) {
6445                *released_per_stream.entry(c.stream_identifier).or_default() +=
6446                    c.user_data.len() as i64;
6447            }
6448        }
6449        self.release_stream_buffers(&released_per_stream);
6450        self.stats.inc_abandoned_messages();
6451        if let Some(id) = stream {
6452            self.events
6453                .push_back(Event::Stream(StreamEvent::MessageAbandoned {
6454                    id,
6455                    transmitted: false,
6456                }));
6457        }
6458        Ok(())
6459    }
6460
6461    fn fail_message_queue(&mut self, err: Error) {
6462        error!("[{}] inconsistent message queue: {err}", self.side);
6463        if let Err(err) = self.close(AssociationError::TransportError) {
6464            error!("[{}] failed to close association: {err}", self.side);
6465        }
6466        self.control_queue.clear();
6467        self.emit_drained();
6468    }
6469
6470    fn on_messages_abandoned(&mut self, now: Instant) {
6471        self.advance_peer_ack_point();
6472        // RFC 3758 C5: recovery must continue even with no DATA left to retry.
6473        if sna32gt(
6474            self.advanced_peer_tsn_ack_point,
6475            self.cumulative_tsn_ack_point,
6476        ) {
6477            self.timers
6478                .start_if_idle(Timer::T3RTX, now, self.rto_mgr.get_rto());
6479        }
6480    }
6481
6482    fn abandon_unretransmittable_messages(
6483        &mut self,
6484        now: Instant,
6485        is_candidate: impl Fn(&ChunkPayloadData) -> bool,
6486    ) -> Result<()> {
6487        let mut changed = false;
6488        for message in self.unretransmittable_messages(now, is_candidate)? {
6489            changed |= self.abandon_message(message)?;
6490        }
6491        if changed {
6492            self.on_messages_abandoned(now);
6493        }
6494        Ok(())
6495    }
6496
6497    /// An unsent unordered message can be dropped without assigning TSNs.
6498    /// A selected fragment tail instead needs the whole-message abandonment path.
6499    /// Timed(0) permits first transmissions until an actual retry is considered.
6500    ///
6501    /// RFC 3758 4.1 (TR3, TR4): the lifetime is checked before every transmission, the first
6502    /// included, of ordered messages too. A message takes its Stream Sequence Number when its
6503    /// first fragment is sent, so one that expires before that is dropped without a TSN or a
6504    /// FORWARD TSN; one that expires part sent is abandoned by `abandon_message` with them.
6505    fn pending_message_expired(&self, c: &ChunkPayloadData, now: Instant) -> bool {
6506        c.reliability.deadline() != c.created_at && self.timed_data_expired(c, now)
6507    }
6508
6509    fn pending_message_to_abandon(&self) -> Result<MessageToAbandon> {
6510        Ok(MessageToAbandon {
6511            id: self
6512                .pending_queue
6513                .peek()
6514                .and_then(|c| c.message_id)
6515                .ok_or_else(|| {
6516                    Error::OtherSctpErr("outbound DATA has no message identity".into())
6517                })?,
6518            sent_tsn: None,
6519        })
6520    }
6521
6522    /// pop_pending_data_chunks_to_send pops chunks from the pending queues as many as
6523    /// the cwnd and rwnd allows to send.
6524    fn pop_pending_data_chunks_to_send(
6525        &mut self,
6526        now: Instant,
6527    ) -> (Vec<ChunkPayloadData>, Vec<ResetMarker>) {
6528        let mut chunks = vec![];
6529        let mut resets = vec![]; // the stream resets whose turn has come
6530        // RFC 6525 5.1.4 C2: while an SSN/TSN reset is under way no new DATA is sent. A
6531        // message part sent is finished first: its fragments have consecutive TSNs.
6532        let suspended = self.sending_suspended();
6533        // New DATA held by the bound on the send rate: no zero window probe stands in for it.
6534        let mut rate_limited = false;
6535        if !self.pending_queue.is_empty() {
6536            self.decay_idle_congestion_window(now);
6537            // RFC 9260 6.1 D: with Max.Burst, cwnd is brought down to what is outstanding
6538            // plus Max.Burst packets before DATA is sent, so that a SACK for many chunks at
6539            // once does not release them all at once.
6540            if let Some(max_burst) = self.max_burst {
6541                let flight =
6542                    u32::try_from(self.inflight_queue.get_num_wire_bytes()).unwrap_or(u32::MAX);
6543                let limit = flight.saturating_add(max_burst.saturating_mul(self.pmdcs));
6544                if limit < self.cwnd {
6545                    self.cwnd = limit;
6546                }
6547            }
6548            // RFC 4960 sec 6.1.  Transmission of DATA Chunks
6549            //   A) At any given time, the data sender MUST NOT transmit new data to
6550            //      any destination transport address if its peer's rwnd indicates
6551            //      that the peer has no buffer space (i.e., rwnd is 0; see Section
6552            //      6.2.1).  However, regardless of the value of rwnd (including if it
6553            //      is 0), the data sender can always have one DATA chunk in flight to
6554            //      the receiver if allowed by cwnd (see rule B, below).
6555
6556            // What is sent now starts a new packet (RFC 8260 3.3, for the scheduler that
6557            // gives a packet to one stream).
6558            self.pending_queue.start_packet();
6559            self.pending_queue.set_only_part_sent(suspended);
6560            loop {
6561                if suspended && !self.pending_queue.is_mid_message() {
6562                    break;
6563                }
6564                // A reset whose stream has sent what was written before it takes no window.
6565                if !suspended && let Some(reset) = self.pending_queue.pop_ready_reset() {
6566                    resets.push(reset);
6567                    continue;
6568                }
6569                let Some(c) = self.pending_queue.peek() else {
6570                    break;
6571                };
6572                let (beginning_fragment, unordered, data_len) =
6573                    (c.beginning_fragment, c.unordered, c.user_data.len());
6574
6575                if data_len == 0 {
6576                    self.fail_message_queue(Error::OtherSctpErr(
6577                        "outbound DATA has no user data".into(),
6578                    ));
6579                    return (vec![], vec![]);
6580                }
6581
6582                // RFC 3758 timed reliability: a message whose lifetime has run
6583                // out must be abandoned even if it was never transmitted. Doing
6584                // this here, ahead of the window checks and before a TSN is
6585                // allocated, means there is no gap for the peer to reconcile and
6586                // no ForwardTSN to send.
6587                if self.pending_message_expired(c, now) {
6588                    // Abandoning an ordered message that has its number takes TSNs: not
6589                    // past what may be outstanding (see `MAX_OUTSTANDING_TSNS`).
6590                    if !unordered
6591                        && !c.numbers_pending
6592                        && self.my_next_tsn.wrapping_sub(self.cumulative_tsn_ack_point)
6593                            > MAX_OUTSTANDING_TSNS
6594                    {
6595                        break;
6596                    }
6597                    match self
6598                        .pending_message_to_abandon()
6599                        .and_then(|message| self.abandon_message(message))
6600                    {
6601                        Ok(true) => self.on_messages_abandoned(now),
6602                        Ok(false) => {}
6603                        Err(err) => {
6604                            self.fail_message_queue(err);
6605                            return (vec![], vec![]);
6606                        }
6607                    }
6608                    continue;
6609                }
6610
6611                // RFC 9260 6.1 B: new DATA is sent while less than cwnd is outstanding. The
6612                // chunk that crosses cwnd is still sent (by less than one PMDCS), and it is
6613                // the last: a window that the next chunk does not fit exactly would
6614                // otherwise never be in full use, and so never grow.
6615                if self.inflight_queue.get_num_wire_bytes() >= self.send_window() as usize {
6616                    break; // cwnd is in full use
6617                }
6618
6619                // The bound on the send rate from outside, when set: the chunk that empties
6620                // the bucket is the last.
6621                if let Some(limit) = self.send_rate.as_mut() {
6622                    limit.fill(now, self.pmdcs);
6623                    if limit.tokens <= 0.0 {
6624                        rate_limited = true;
6625                        break;
6626                    }
6627                }
6628
6629                if self.my_next_tsn.wrapping_sub(self.cumulative_tsn_ack_point)
6630                    > MAX_OUTSTANDING_TSNS
6631                {
6632                    break; // the receiver could no longer order what is outstanding
6633                }
6634
6635                if data_len > self.rwnd as usize {
6636                    break; // no more rwnd
6637                }
6638
6639                if let Some(chunk) = self.move_pending_data_chunk_to_inflight_queue(
6640                    beginning_fragment,
6641                    unordered,
6642                    now,
6643                ) {
6644                    self.rwnd -= data_len as u32;
6645                    if let Some(limit) = self.send_rate.as_mut() {
6646                        limit.tokens -= chunk.wire_size() as f64;
6647                    }
6648                    chunks.push(chunk);
6649                } else {
6650                    self.fail_message_queue(Error::OtherSctpErr(
6651                        "failed to pop pending DATA".into(),
6652                    ));
6653                    return (vec![], vec![]);
6654                }
6655            }
6656
6657            // the data sender can always have one DATA chunk in flight to the receiver; after
6658            // the receiver closed its window, from one RTO on (RFC 9260 6.1 A)
6659            if chunks.is_empty()
6660                && self.inflight_queue.is_empty()
6661                && !rate_limited
6662                && !(suspended && !self.pending_queue.is_mid_message())
6663                // Its time is cleared by `handle_timeout` once it has come.
6664                && self.zero_window_probe_at.is_none()
6665            {
6666                // Send zero window probe.
6667                //
6668                // With I-DATA (RFC 8260) several messages may be part sent, and together they
6669                // can fill the receiver's buffer without one of them being complete. What
6670                // reopens a closed window is a message completed and read, so while probing,
6671                // a message that is part sent goes on before another is started: the probes
6672                // finish one message at a time, which the receiver can always take (it keeps
6673                // room for one message beyond its buffer while nothing is readable).
6674                let finish_first = self.pending_queue.is_mid_message();
6675                self.pending_queue
6676                    .set_only_part_sent(suspended || finish_first);
6677                let probe = self
6678                    .pending_queue
6679                    .peek()
6680                    .map(|c| (c.beginning_fragment, c.unordered));
6681                let moved = probe.map(|(beginning_fragment, unordered)| {
6682                    self.move_pending_data_chunk_to_inflight_queue(
6683                        beginning_fragment,
6684                        unordered,
6685                        now,
6686                    )
6687                });
6688                self.pending_queue.set_only_part_sent(suspended);
6689                match moved {
6690                    Some(Some(chunk)) => {
6691                        self.zero_window_probe_tsn = Some(chunk.tsn);
6692                        chunks.push(chunk);
6693                    }
6694                    Some(None) => {
6695                        self.fail_message_queue(Error::OtherSctpErr(
6696                            "failed to pop pending DATA".into(),
6697                        ));
6698                        return (vec![], vec![]);
6699                    }
6700                    None => {}
6701                }
6702            }
6703        }
6704
6705        (chunks, resets)
6706    }
6707
6708    /// bundle_data_chunks_into_packets packs DATA chunks into packets. It tries to bundle
6709    /// DATA chunks into a packet so long as the resulting packet size does not exceed
6710    /// the path MTU.
6711    fn bundle_data_chunks_into_packets(
6712        &self,
6713        chunks: Vec<ChunkPayloadData>,
6714        raw_packets: &mut Vec<Bytes>,
6715    ) {
6716        // RFC 4960 sec 6.1.  Transmission of DATA Chunks
6717        //   Multiple DATA chunks committed for transmission MAY be bundled in a
6718        //   single packet.  Furthermore, DATA chunks being retransmitted MAY be
6719        //   bundled with new DATA chunks, as long as the resulting packet size
6720        //   does not exceed the path MTU.
6721        //
6722        // Marshal each bundle straight into `raw_packets` from the borrowed
6723        // chunks: no intermediate `Vec<Packet>`, no `Box<dyn Chunk>` per chunk.
6724        // The chunks are already retained in the in-flight queue, so this send
6725        // copy is throwaway.
6726        if chunks.is_empty() {
6727            return;
6728        }
6729        let common_header = CommonHeader {
6730            verification_tag: self.peer_verification_tag,
6731            source_port: self.source_port,
6732            destination_port: self.destination_port,
6733        };
6734
6735        // First pass: split the chunks into MTU-bounded datagrams and total up
6736        // their marshalled (4-byte-padded) length. The whole burst is then
6737        // written into ONE buffer and `split_to` hands out each datagram as a
6738        // zero-copy `Bytes` view sharing that single allocation — one malloc per
6739        // burst instead of one per packet on the hot send path. The bundle
6740        // boundaries are computed once here and reused below, so the MTU-split
6741        // rule lives in exactly one place.
6742        let hdr = COMMON_HEADER_SIZE as usize;
6743        let mut bundles: Vec<(usize, usize)> = Vec::new();
6744        let mut total_len = 0usize;
6745        let mut bundle_start = 0;
6746        let mut bundle_len = hdr;
6747        for (i, chunk) in chunks.iter().enumerate() {
6748            // Marshalled chunk size: header + payload, padded up to the SCTP
6749            // 4-byte boundary. Bundle decisions must use this wire size —
6750            // deciding on raw payload sizes admitted bundles that marshalled
6751            // past the MTU (e.g. payloads of 1147 + 16 pass a payload-only
6752            // check at an MTU of 1191 but serialize to a 1208-byte packet).
6753            let wire = chunk.wire_size();
6754            // Close the current bundle before a chunk whose padded wire size
6755            // would push the datagram past the MTU.
6756            if bundle_len + wire > self.mtu as usize && i > bundle_start {
6757                bundles.push((bundle_start, i));
6758                total_len += bundle_len;
6759                bundle_start = i;
6760                bundle_len = hdr;
6761            }
6762            bundle_len += wire;
6763        }
6764        bundles.push((bundle_start, chunks.len()));
6765        total_len += bundle_len;
6766
6767        // Second pass: marshal each datagram into the shared buffer.
6768        let mut buf = BytesMut::with_capacity(total_len);
6769        for (start, end) in bundles {
6770            match Packet::write_framed_with(
6771                &common_header,
6772                chunks[start..end].iter().map(|c| c as &dyn Chunk),
6773                &mut buf,
6774                self.send_zero_checksum,
6775            ) {
6776                Ok(_) => {
6777                    let plen = buf.len();
6778                    raw_packets.push(buf.split_to(plen).freeze());
6779                }
6780                Err(_) => {
6781                    warn!("[{}] failed to serialize a DATA packet", self.side);
6782                    buf.clear();
6783                }
6784            }
6785        }
6786    }
6787
6788    /// generate_next_tsn returns the my_next_tsn and increases it. The caller should hold the lock.
6789    fn generate_next_tsn(&mut self) -> u32 {
6790        let tsn = self.my_next_tsn;
6791        self.my_next_tsn = self.my_next_tsn.wrapping_add(1);
6792        tsn
6793    }
6794
6795    /// generate_next_rsn returns the my_next_rsn and increases it. The caller should hold the lock.
6796    fn generate_next_rsn(&mut self) -> u32 {
6797        let rsn = self.my_next_rsn;
6798        self.my_next_rsn = self.my_next_rsn.wrapping_add(1);
6799        rsn
6800    }
6801
6802    /// Builds the SACK, keeping the gap blocks nearest the cumulative TSN and then the repeats
6803    /// that fit, so the packet carrying it stays within the MTU.
6804    fn create_selective_ack_chunk(&mut self) -> ChunkSelectiveAck {
6805        let fixed = COMMON_HEADER_SIZE as usize + CHUNK_HEADER_SIZE + SELECTIVE_ACK_HEADER_SIZE;
6806        let room = (self.mtu as usize).saturating_sub(fixed) / 4;
6807        let mut gap_ack_blocks = self.payload_queue.get_gap_ack_blocks(self.peer_last_tsn);
6808        gap_ack_blocks.truncate(room);
6809        let mut duplicate_tsn = self.payload_queue.pop_duplicates();
6810        duplicate_tsn.truncate(room - gap_ack_blocks.len());
6811        self.last_advertised_window = self.advertised_window();
6812        self.received_since_sack = 0;
6813        ChunkSelectiveAck {
6814            cumulative_tsn_ack: self.peer_last_tsn,
6815            advertised_receiver_window_credit: self.last_advertised_window,
6816            gap_ack_blocks,
6817            duplicate_tsn,
6818        }
6819    }
6820
6821    /// The a_rwnd to advertise. RFC 9260 6.2 asks the receiver for silly window syndrome
6822    /// avoidance (RFC 1122 4.2.3.3): a window too small for a full packet is advertised as
6823    /// closed, so the sender does not fill it with scraps.
6824    fn advertised_window(&self) -> u32 {
6825        let free = self.get_my_receiver_window_credit();
6826        let threshold = (self.max_receive_buffer_size / 2).min(self.pmdcs);
6827        if free < threshold { 0 } else { free }
6828    }
6829
6830    /// The application took data from the receive buffer. RFC 9260 6.2: "When the window
6831    /// opens up, an SCTP receiver SHOULD send additional SACK chunks to update the window even
6832    /// if no new data is received." A window the sender sees as too small for a full chunk
6833    /// (advertised as closed, or used up by what it sent since the last SACK) that has opened
6834    /// again is announced by a SACK at once. Without it the sender, stopped by a_rwnd 0,
6835    /// learns of the space only from its next window probe, a retransmission timeout later
6836    /// (and that timeout doubles); and one whose window a single chunk used up waits for the
6837    /// delayed SACK. A sender that still sees room for a full chunk gets no extra SACK.
6838    pub(crate) fn on_receive_buffer_drained(&mut self) {
6839        // The window as the sender sees it: what the last SACK advertised, less what it has
6840        // sent since. Too small for a full chunk, the sender waits for a SACK (RFC 9260 6.1
6841        // A); a delayed one held each chunk of a receiver with a small buffer that reads in
6842        // parts for the SACK delay, though its window was open again at once.
6843        let threshold = (self.max_receive_buffer_size / 2).min(self.pmdcs);
6844        let sender_view = self
6845            .last_advertised_window
6846            .saturating_sub(self.received_since_sack);
6847        if sender_view < threshold
6848            && self.advertised_window() > 0
6849            && matches!(
6850                self.state(),
6851                AssociationState::Established
6852                    | AssociationState::ShutdownPending
6853                    | AssociationState::ShutdownSent
6854            )
6855        {
6856            self.ack_state = AckState::Immediate;
6857            self.timers.stop(Timer::Ack);
6858            self.awake_write_loop();
6859        }
6860    }
6861
6862    /// Record an abandoned chunk into the forward-TSN stream map (RFC 3758 C4),
6863    /// called from the two C2 loops as `advanced_peer_tsn_ack_point` advances
6864    /// over each newly-abandoned in-flight chunk. Only *ordered* streams are
6865    /// tracked: the receiver ignores the per-stream SSN list for unordered
6866    /// chunks (it advances purely by `new_cumulative_tsn`). Keeps the greatest
6867    /// SSN seen per stream, which is the value RFC 3758 C4 requires to report.
6868    ///
6869    /// A stream's entry may briefly outlive the chunk that set it (until the
6870    /// window closes and the map is cleared), so a stale SSN can be re-reported;
6871    /// that is safe because the receiver only advances a stream forward and the
6872    /// SSN always corresponds to a really-abandoned chunk. The `u16` SSN compare
6873    /// (`sna16lt`) is sound because the window span is bounded by rwnd — a
6874    /// stream cannot lap the full 65536-sequence space before the window closes.
6875    fn note_abandoned_for_forward_tsn(&mut self, unordered: bool, si: u16, ssn: u16) {
6876        if unordered {
6877            return;
6878        }
6879        self.fwd_tsn_stream_map
6880            .entry(si)
6881            .and_modify(|cur| {
6882                if sna16lt(*cur, ssn) {
6883                    *cur = ssn;
6884                }
6885            })
6886            .or_insert(ssn);
6887    }
6888
6889    /// Test-only observer for the incremental forward-TSN stream map, so the
6890    /// endpoint tests can assert it is cleared once the forward-TSN window
6891    /// closes (the C1/C3 clear paths, which the unit tests can't reach).
6892    #[cfg(test)]
6893    pub(crate) fn fwd_tsn_stream_map_is_empty(&self) -> bool {
6894        self.fwd_tsn_stream_map.is_empty()
6895    }
6896
6897    /// create_forward_tsn generates ForwardTSN chunk.
6898    /// This method will be be called if use_forward_tsn is set to false.
6899    fn create_forward_tsn(&self) -> ChunkForwardTsn {
6900        // RFC 3758 Sec 3.5 C4: report, once per ordered stream, the greatest
6901        // stream-sequence-number among abandoned chunks in the forward-TSN
6902        // window. This is maintained incrementally in `fwd_tsn_stream_map` (see
6903        // its declaration and the two C2 loops that feed it), so we no longer
6904        // rescan `(cumulative_tsn_ack_point, advanced_peer_tsn_ack_point]` with
6905        // a per-TSN hashmap probe on every FORWARD-TSN — that scan was O(rwnd)
6906        // (~1000 probes/call for a 1 MB window) and dominated the send profile.
6907        // RFC 3758 3.5 C4: the chunk fits one packet. When more streams have abandoned data
6908        // than fit, it covers the TSNs up to the last one whose streams do, and the next
6909        // FORWARD TSN goes on from there once the peer has acknowledged this one. Only then
6910        // is the window walked.
6911        let room = if self.mtu == 0 {
6912            // No packet size is known (an association that was never set up): no bound.
6913            usize::MAX
6914        } else {
6915            (self.mtu as usize).saturating_sub(COMMON_HEADER_SIZE as usize + CHUNK_HEADER_SIZE + 4)
6916                / 4
6917        };
6918        let mut fwd_tsn = ChunkForwardTsn {
6919            new_cumulative_tsn: self.advanced_peer_tsn_ack_point,
6920            streams: Vec::with_capacity(self.fwd_tsn_stream_map.len().min(room)),
6921        };
6922        if self.fwd_tsn_stream_map.len() <= room {
6923            for (si, ssn) in &self.fwd_tsn_stream_map {
6924                fwd_tsn.streams.push(ChunkForwardTsnStream {
6925                    identifier: *si,
6926                    sequence: *ssn,
6927                });
6928            }
6929        } else {
6930            let mut streams: FxHashMap<u16, u16> = FxHashMap::default();
6931            let mut covered = self.cumulative_tsn_ack_point;
6932            let mut tsn = self.cumulative_tsn_ack_point.wrapping_add(1);
6933            while sna32lte(tsn, self.advanced_peer_tsn_ack_point) {
6934                let Some(c) = self.inflight_queue.get(tsn) else {
6935                    break;
6936                };
6937                if !c.unordered {
6938                    if !streams.contains_key(&c.stream_identifier) && streams.len() == room {
6939                        break;
6940                    }
6941                    let ssn = c.stream_sequence_number;
6942                    streams
6943                        .entry(c.stream_identifier)
6944                        .and_modify(|cur| {
6945                            if sna16lt(*cur, ssn) {
6946                                *cur = ssn;
6947                            }
6948                        })
6949                        .or_insert(ssn);
6950                }
6951                covered = tsn;
6952                tsn = tsn.wrapping_add(1);
6953            }
6954            fwd_tsn.new_cumulative_tsn = covered;
6955            for (si, ssn) in streams {
6956                fwd_tsn.streams.push(ChunkForwardTsnStream {
6957                    identifier: si,
6958                    sequence: ssn,
6959                });
6960            }
6961        }
6962        // `trace!` evaluates its arguments lazily, so the stream list is only
6963        // formatted when trace logging is enabled -- no per-FORWARD-TSN string
6964        // allocation on the hot send path (this fires often for PR-SCTP data
6965        // channels, which is exactly where it was showing up in profiles).
6966        trace!(
6967            "[{}] building fwd_tsn: newCumulativeTSN={} cumTSN={} streams={:?}",
6968            self.side, fwd_tsn.new_cumulative_tsn, self.cumulative_tsn_ack_point, fwd_tsn.streams
6969        );
6970
6971        fwd_tsn
6972    }
6973
6974    /// Move the chunk peeked with self.pending_queue.peek() to the inflight_queue.
6975    /// The message whose first fragment is about to leave the pending queue takes its Stream
6976    /// Sequence Number and Message Identifier now (RFC 3758 4.1 TR3: a message abandoned
6977    /// while it waited took none).
6978    fn number_next_message(&mut self) {
6979        let Some(c) = self.pending_queue.peek() else {
6980            return;
6981        };
6982        if !c.numbers_pending || !c.beginning_fragment {
6983            return;
6984        }
6985        let (id, generation) = (c.stream_identifier, c.stream_generation);
6986        let Some(s) = self.streams.get_mut(&id) else {
6987            return;
6988        };
6989        if s.generation == generation {
6990            self.pending_queue
6991                .number_messages(id, generation, true, |unordered| {
6992                    s.next_message_numbers(unordered)
6993                });
6994        }
6995    }
6996
6997    fn move_pending_data_chunk_to_inflight_queue(
6998        &mut self,
6999        beginning_fragment: bool,
7000        unordered: bool,
7001        now: Instant,
7002    ) -> Option<ChunkPayloadData> {
7003        self.number_next_message();
7004        if let Some(mut c) = self.pending_queue.pop(beginning_fragment, unordered) {
7005            // Assign TSN
7006            c.tsn = self.generate_next_tsn();
7007
7008            // RTT baseline only; maxPacketLifeTime measures from `created_at`.
7009            c.since = Some(now);
7010            self.last_rtt_probe = Some(now);
7011            self.last_data_sent = Some(now);
7012            c.nsent = 1; // being sent for the first time
7013
7014            trace!(
7015                "[{}] sending ppi={} tsn={} ssn={} sent={} len={} ({},{})",
7016                self.side,
7017                c.ppid(),
7018                c.tsn,
7019                c.stream_sequence_number,
7020                c.nsent,
7021                c.user_data.len(),
7022                c.beginning_fragment,
7023                c.ending_fragment
7024            );
7025
7026            self.inflight_queue.push_no_check(c.clone());
7027            self.note_dequeued(&c);
7028
7029            Some(c)
7030        } else {
7031            error!("[{}] failed to pop from pending queue", self.side);
7032            None
7033        }
7034    }
7035
7036    /// Allocate an identity before consuming input or changing stream state.
7037    /// See `TransportConfig::with_forward_tsn_delay`.
7038    fn forward_tsn_delay(&self) -> Option<Duration> {
7039        self.transport_config
7040            .as_ref()
7041            .and_then(|config| config.forward_tsn_delay())
7042    }
7043
7044    /// See `TransportConfig::with_data_in_cookie_echo`.
7045    pub(crate) fn data_in_cookie_echo(&self) -> bool {
7046        self.transport_config
7047            .as_ref()
7048            .is_some_and(|config| config.data_in_cookie_echo())
7049    }
7050
7051    /// RFC 9260 5.1 C (`with_data_in_cookie_echo`): new DATA for the packet of a COOKIE ECHO,
7052    /// in `room` bytes, as far as the peer's a_rwnd and cwnd allow. A message whose lifetime
7053    /// has run out stops it: the established path abandons it.
7054    pub(super) fn pending_data_for_cookie_echo(
7055        &mut self,
7056        mut room: usize,
7057        now: Instant,
7058    ) -> Vec<ChunkPayloadData> {
7059        let mut chunks = vec![];
7060        if self.pending_queue.is_empty() {
7061            return chunks;
7062        }
7063        self.pending_queue.start_packet();
7064        while let Some(c) = self.pending_queue.peek() {
7065            let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered);
7066            let (data_len, wire) = (c.user_data.len(), c.wire_size());
7067            if data_len == 0
7068                || wire > room
7069                || self.pending_message_expired(c, now)
7070                || self.inflight_queue.get_num_wire_bytes() >= self.cwnd as usize
7071                || data_len > self.rwnd as usize
7072            {
7073                break;
7074            }
7075            let Some(chunk) =
7076                self.move_pending_data_chunk_to_inflight_queue(beginning_fragment, unordered, now)
7077            else {
7078                break;
7079            };
7080            self.rwnd -= data_len as u32;
7081            room = room.saturating_sub(chunk.wire_size());
7082            chunks.push(chunk);
7083        }
7084        chunks
7085    }
7086
7087    pub(crate) fn allocate_message_id(&mut self) -> Result<MessageId> {
7088        let state = self.state();
7089        // RFC 9260 5.1 C: with `TransportConfig::with_data_in_cookie_echo`, DATA written in
7090        // COOKIE-ECHOED goes with the COOKIE ECHO.
7091        let cookie_echoed = state == AssociationState::CookieEchoed && self.data_in_cookie_echo();
7092        if state != AssociationState::Established && !cookie_echoed {
7093            return Err(Error::ErrPayloadDataStateNotExist);
7094        }
7095
7096        let id = MessageId::new(self.next_message_id)
7097            .ok_or_else(|| Error::OtherSctpErr("message identity exhausted".into()))?;
7098        // MessageId::new has already checked that this increment cannot overflow.
7099        self.next_message_id += 1;
7100        Ok(id)
7101    }
7102
7103    /// send_payload_data sends the data chunks with their allocated identity.
7104    ///
7105    /// The queueing instant is already recorded on each chunk by `Stream::packetize`, so this
7106    /// does not need one of its own.
7107    pub(crate) fn send_payload_data(&mut self, id: MessageId, mut chunks: Vec<ChunkPayloadData>) {
7108        for c in &mut chunks {
7109            c.message_id = Some(id);
7110        }
7111        self.pending_queue.push_message(chunks);
7112
7113        self.awake_write_loop();
7114    }
7115
7116    /// buffered_amount returns total amount (in bytes) of currently buffered user data.
7117    /// This is used only by testing.
7118    pub(crate) fn buffered_amount(&self) -> usize {
7119        self.pending_queue.get_num_bytes() + self.inflight_queue.get_num_bytes()
7120    }
7121
7122    /// Whether everything the application handed over has been sent and acknowledged
7123    /// (RFC 9260 9.2), messages held for a stream reset included.
7124    fn nothing_left_to_send(&self) -> bool {
7125        self.inflight_queue.is_empty()
7126            && self.pending_queue.is_empty()
7127            && self.held_write_count == 0
7128    }
7129
7130    fn awake_write_loop(&self) {
7131        // No Op on Purpose
7132    }
7133
7134    fn close_all_timers(&mut self) {
7135        // Close all retransmission & ack timers
7136        for timer in Timer::VALUES {
7137            self.timers.stop(timer);
7138        }
7139    }
7140
7141    fn on_ack_timeout(&mut self) {
7142        trace!(
7143            "[{}] ack timed out (ack_state: {})",
7144            self.side, self.ack_state
7145        );
7146        self.stats.inc_ack_timeouts();
7147        self.ack_state = AckState::Immediate;
7148        self.awake_write_loop();
7149    }
7150
7151    /// RFC 9260 5.1: "The T1-init timer and T1-cookie timer SHOULD follow the same rules
7152    /// given in Section 6.3": an expiry backs off the path's RTO (6.3.3 E2, bounded by
7153    /// RTO.Max), which the timer is started again with, as the next handshake timer and the
7154    /// first T3-rtx are, until a round trip is measured. Not with
7155    /// `TransportConfig::with_handshake_timers_back_off_rto(false)` (dcSCTP's form), where
7156    /// the timer doubles its own interval and the RTO is left alone.
7157    fn back_off_rto_for_handshake_timer(&mut self) {
7158        if self.handshake_timers_back_off_rto {
7159            self.rto_mgr.backoff();
7160        }
7161    }
7162
7163    fn on_retransmission_timeout(&mut self, timer_id: Timer, n_rtos: usize, now: Instant) {
7164        match timer_id {
7165            Timer::T1Init => {
7166                self.back_off_rto_for_handshake_timer();
7167                if let Err(err) = self.send_init() {
7168                    debug!(
7169                        "[{}] failed to retransmit init (n_rtos={}): {:?}",
7170                        self.side, n_rtos, err
7171                    );
7172                }
7173            }
7174
7175            Timer::T1Cookie => {
7176                self.cookie_echo_sent_at = Some(now);
7177                self.back_off_rto_for_handshake_timer();
7178                if let Err(err) = self.send_cookie_echo() {
7179                    debug!(
7180                        "[{}] failed to retransmit cookie-echo (n_rtos={}): {:?}",
7181                        self.side, n_rtos, err
7182                    );
7183                }
7184            }
7185
7186            Timer::T2Shutdown => {
7187                debug!(
7188                    "[{}] retransmission of shutdown timeout (n_rtos={})",
7189                    self.side, n_rtos
7190                );
7191                let state = self.state();
7192                match state {
7193                    AssociationState::ShutdownSent => {
7194                        self.will_send_shutdown = true;
7195                        self.awake_write_loop();
7196                    }
7197                    AssociationState::ShutdownAckSent => {
7198                        self.will_send_shutdown_ack = true;
7199                        self.awake_write_loop();
7200                    }
7201                    _ => {}
7202                }
7203            }
7204
7205            Timer::T3RTX => {
7206                self.stats.inc_t3timeouts();
7207                self.stats.add_t3_wait(self.rto_mgr.get_rto());
7208                self.rto_mgr.backoff();
7209                self.note_path_error();
7210                // Refresh before C2 or mark_all_to_retrasmit reads abandoned().
7211                if let Err(err) =
7212                    self.abandon_unretransmittable_messages(now, ChunkPayloadData::is_outstanding)
7213                {
7214                    self.fail_message_queue(err);
7215                    return;
7216                }
7217
7218                // RFC 4960 sec 6.3.3
7219                //  E1)  For the destination address for which the timer expires, adjust
7220                //       its ssthresh with rules defined in Section 7.2.3 and set the
7221                //       cwnd <- MTU.
7222                // RFC 4960 sec 7.2.3
7223                //   When the T3-rtx timer expires on an address, SCTP should perform slow
7224                //   start by:
7225                //      ssthresh = max(cwnd/2, 4*MTU)
7226                //      cwnd = 1*MTU
7227
7228                // RFC 9260 7.2.3: ssthresh = max(cwnd / 2, 4 x PMDCS), cwnd = PMDCS,
7229                // partial_bytes_acked = 0, and one packet in flight until it is acknowledged.
7230                self.ssthresh = std::cmp::max(self.cwnd / 2, self.pmdcs.saturating_mul(4));
7231                self.cwnd = self.pmdcs;
7232                self.partial_bytes_acked = 0;
7233                self.t3_single_packet = true;
7234                // A retransmission timeout ends Fast Recovery: the window is one packet now.
7235                self.in_fast_recovery = false;
7236                trace!(
7237                    "[{}] updated cwnd={} ssthresh={} inflight={} (RTO)",
7238                    self.side,
7239                    self.cwnd,
7240                    self.ssthresh,
7241                    self.inflight_queue.get_num_bytes()
7242                );
7243
7244                // RFC 3758 sec 3.5
7245                //  A5) Any time the T3-rtx timer expires, on any destination, the sender
7246                //  SHOULD try to advance the "Advanced.Peer.Ack.Point" by following
7247                //  the procedures outlined in C2 - C5.
7248                if self.use_forward_tsn {
7249                    self.advance_peer_ack_point();
7250                }
7251
7252                debug!(
7253                    "[{}] T3-rtx timed out: n_rtos={} cwnd={} ssthresh={}",
7254                    self.side, n_rtos, self.cwnd, self.ssthresh
7255                );
7256
7257                // RFC 8899 section 4.3: data at the PLPMTU that keeps going unacknowledged
7258                // is the sign of a path that no longer carries it.
7259                if let Some(mtu) = self
7260                    .pmtud
7261                    .as_mut()
7262                    .and_then(|p| p.on_retransmission_timeout())
7263                {
7264                    debug!("[{}] path MTU black hole: back to {mtu} bytes", self.side);
7265                    self.use_path_mtu(mtu, false);
7266                }
7267
7268                // RFC 9260 6.2.1 C: what is marked for retransmission goes back to rwnd.
7269                let marked = self.inflight_queue.mark_all_for_retransmission();
7270                self.rwnd = self
7271                    .rwnd
7272                    .saturating_add(u32::try_from(marked).unwrap_or(u32::MAX));
7273                self.t3_retransmit_pending = true;
7274                // RFC 9260 5.1 D, 5.2.5: while nothing from the peer has shown that the COOKIE
7275                // ACK reached it, the peer may be in COOKIE-ECHOED, discarding this DATA
7276                // again. The retransmission goes behind a COOKIE ACK, which a peer in
7277                // COOKIE-ECHOED takes first, and one in ESTABLISHED discards. Without it the
7278                // DATA waits until the peer's T1-cookie, backed off to 16 s and more, gets a
7279                // COOKIE ECHO through and its answer back.
7280                if self.peer_awaits_cookie_ack && self.state() == AssociationState::Established {
7281                    match self.outstanding_data_after_a_cookie_ack(now) {
7282                        Ok(chunks) => {
7283                            let mut packet: Vec<Box<dyn Chunk>> = vec![Box::new(ChunkCookieAck {})];
7284                            for chunk in chunks {
7285                                packet.push(Box::new(chunk));
7286                            }
7287                            self.control_queue.push_back(Packet {
7288                                common_header: CommonHeader {
7289                                    verification_tag: self.peer_verification_tag,
7290                                    source_port: self.source_port,
7291                                    destination_port: self.destination_port,
7292                                },
7293                                chunks: packet,
7294                            });
7295                        }
7296                        Err(err) => {
7297                            self.fail_message_queue(err);
7298                            return;
7299                        }
7300                    }
7301                }
7302                self.awake_write_loop();
7303            }
7304
7305            Timer::Reconfig => {
7306                // RFC 6525 5.1.1: an expiry counts against the association and the path,
7307                // and past the retransmission limit the association ends. 5.2.7 H2: not the
7308                // expiry that follows an "In progress" answer, which only says the peer is
7309                // not done yet.
7310                if !std::mem::take(&mut self.reconfig_in_progress) && self.on_path_failure() {
7311                    return;
7312                }
7313                self.will_retransmit_reconfig = true;
7314                self.awake_write_loop();
7315            }
7316
7317            _ => {}
7318        }
7319    }
7320
7321    fn on_retransmission_failure(&mut self, id: Timer) {
7322        match id {
7323            // A handshake that runs out of retransmissions is over (RFC 9260 5.1 A, C). It
7324            // used to only report HandshakeFailed and stay in COOKIE-WAIT / COOKIE-ECHOED, so
7325            // whatever watched the association saw it connecting for good.
7326            Timer::T1Init => {
7327                error!("[{}] retransmission failure: T1-init", self.side);
7328                let reason =
7329                    AssociationError::HandshakeFailed(Error::ErrHandshakeInitAck.to_string());
7330                self.error = Some(reason.clone());
7331                if let Err(err) = self.close(reason) {
7332                    error!("[{}] failed to close association: {err}", self.side);
7333                }
7334            }
7335
7336            Timer::T1Cookie => {
7337                error!("[{}] retransmission failure: T1-cookie", self.side);
7338                let reason =
7339                    AssociationError::HandshakeFailed(Error::ErrHandshakeCookieEcho.to_string());
7340                self.error = Some(reason.clone());
7341                if let Err(err) = self.close(reason) {
7342                    error!("[{}] failed to close association: {err}", self.side);
7343                }
7344            }
7345
7346            Timer::T2Shutdown => {
7347                // RFC 9260 9.2: past the limit the peer is unreachable and the association is
7348                // over. This only logged, and the timer was not started again: the association
7349                // stayed in SHUTDOWN-SENT (or SHUTDOWN-ACK-SENT) for good.
7350                error!("[{}] retransmission failure: T2-shutdown", self.side);
7351                if let Err(err) = self.close(AssociationError::TimedOut) {
7352                    error!("[{}] failed to close association: {err}", self.side);
7353                }
7354            }
7355
7356            Timer::T5ShutdownGuard => {
7357                // RFC 9260 9.2: the shutdown did not finish in time. The association is
7358                // aborted and the upper layer told.
7359                error!("[{}] T5-shutdown-guard expired", self.side);
7360                if let Err(err) = self.abort_with(vec![], AssociationError::TimedOut) {
7361                    error!("[{}] failed to close association: {err}", self.side);
7362                }
7363            }
7364
7365            Timer::HalfOpen => {
7366                debug!("[{}] no COOKIE ECHO followed the INIT", self.side);
7367                let reason =
7368                    AssociationError::HandshakeFailed(Error::ErrHandshakeCookieEcho.to_string());
7369                self.error = Some(reason.clone());
7370                if let Err(err) = self.close(reason) {
7371                    error!("[{}] failed to close association: {err}", self.side);
7372                }
7373            }
7374
7375            Timer::T3RTX => {
7376                // Reached only with a finite `TimerConfig::max_t3_rtx_retrans`; the default
7377                // is unlimited because a WebRTC peer learns of a lost path from ICE. RFC 9260
7378                // 8.1: once the limit is exceeded the peer is unreachable and the association
7379                // ends. Returning without re-arming the timer, as this did, left it running
7380                // with no retransmission and no FORWARD TSN for ever.
7381                error!("[{}] retransmission failure: T3-rtx (DATA)", self.side);
7382                if let Err(err) = self.close(AssociationError::TimedOut) {
7383                    error!("[{}] failed to close association: {err}", self.side);
7384                }
7385            }
7386
7387            _ => {}
7388        }
7389    }
7390
7391    /// Whether no timers are running
7392    #[cfg(test)]
7393    pub(crate) fn is_idle(&self) -> bool {
7394        // A zero window probe waiting for its time (RFC 9260 6.1 A) is something to wake for,
7395        // and so is a FORWARD TSN held back for DATA.
7396        self.zero_window_probe_at.is_none()
7397            && !(self.will_send_forward_tsn && self.forward_tsn_due_at.is_some())
7398            && Timer::VALUES
7399                .iter()
7400                // The heartbeat timer always runs on an established association.
7401                .filter(|&&t| t != Timer::Heartbeat)
7402                .filter_map(|&t| Some((t, self.timers.get(t)?)))
7403                .min_by_key(|&(_, time)| time)
7404                //.map_or(true, |(timer, _)| timer == Timer::Idle)
7405                .is_none()
7406    }
7407}