Skip to main content

rtci_sctp/association/
reconfig.rs

1//! Stream re-configuration (RFC 6525): the RE-CONFIG chunk, this side's requests and the
2//! peer's.
3//!
4//! This side has one request in flight (5.1.1); the others wait in a queue. A received
5//! request is identified by its Re-configuration Request Sequence Number: one seen before is
6//! answered again as it was, one too old to tell is answered "Error - Bad Sequence Number".
7
8use super::*;
9use crate::param::{
10    param_add_streams_request::ParamAddStreamsRequest,
11    param_incoming_reset_request::ParamIncomingResetRequest,
12    param_ssn_tsn_reset_request::ParamSsnTsnResetRequest,
13};
14use crate::queue::payload_queue::PayloadQueue;
15
16/// RFC 6525 5.1.4: "Only one SSN/TSN Reset Request SHOULD be sent within 30 seconds".
17pub(crate) const MIN_TSN_RESET_INTERVAL: Duration = Duration::from_secs(30);
18
19/// How far around the request sequence numbers already seen a peer's request is taken as
20/// new. A peer that follows RFC 6525 5.1.1 sends each number once the one before it is
21/// answered; one that keeps several requests in flight has them reordered by the network at
22/// most this far apart.
23const PEER_RSN_WINDOW: u32 = 64;
24
25/// The outcome of a stream re-configuration (RFC 6525 section 6.1 describes these as socket
26/// events).
27#[derive(Debug, Clone, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum ReconfigEvent {
30    /// The peer performed the reset of these outgoing streams this side asked for: each sends
31    /// from Stream Sequence Number 0 again. No stream listed means all of them.
32    OutgoingStreamsReset {
33        /// The streams that were reset.
34        streams: Vec<StreamId>,
35    },
36    /// The peer did not perform a reset of outgoing streams this side asked for; the streams
37    /// go on with the sequence numbers they had.
38    OutgoingStreamsResetFailed {
39        /// The streams named by the request.
40        streams: Vec<StreamId>,
41        /// The peer denied the request, as opposed to reporting an error.
42        denied: bool,
43    },
44    /// The peer answered a request to reset its outgoing streams
45    /// ([`Association::request_incoming_stream_reset`]) without resetting them: it refused,
46    /// or it had nothing to do.
47    IncomingStreamsResetNotPerformed {
48        /// The streams named by the request.
49        streams: Vec<StreamId>,
50        /// The peer denied the request.
51        denied: bool,
52    },
53    /// The peer asked this side to reset these outgoing streams (all when none is listed),
54    /// and this side is doing so.
55    OutgoingResetRequestedByPeer {
56        /// The streams named by the peer.
57        streams: Vec<StreamId>,
58    },
59    /// The TSNs of both directions and the Stream Sequence Numbers of every stream started
60    /// over, at this side's request or at the peer's.
61    AssociationReset {
62        /// The TSN of the next DATA chunk this side sends.
63        local_next_tsn: u32,
64        /// The TSN of the next DATA chunk the peer sends.
65        remote_next_tsn: u32,
66    },
67    /// The peer did not perform the SSN/TSN reset this side asked for.
68    AssociationResetFailed {
69        /// The peer denied the request.
70        denied: bool,
71    },
72    /// The number of streams changed: the counts the association has now.
73    StreamsAdded {
74        /// Streams the peer may send on.
75        inbound_streams: u16,
76        /// Streams this side may send on.
77        outbound_streams: u16,
78    },
79    /// The peer did not add the streams this side asked for.
80    AddStreamsFailed {
81        /// The peer denied the request.
82        denied: bool,
83    },
84}
85
86/// A re-configuration request of this side's own (RFC 6525 5.1).
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub(crate) enum OwnRequest {
89    /// Outgoing SSN Reset Request (5.1.2). Each stream comes with the generation of the
90    /// stream that asked, `None` for a stream this side holds no state for. No stream at all
91    /// is a reset of every stream.
92    OutgoingReset {
93        streams: Vec<(u16, Option<u64>)>,
94        /// The peer's Incoming SSN Reset Request this answers (5.1.2 A4).
95        response_to: Option<u32>,
96    },
97    /// Incoming SSN Reset Request (5.1.3).
98    IncomingReset { streams: Vec<u16> },
99    /// SSN/TSN Reset Request (5.1.4).
100    SsnTsnReset,
101    /// Add Outgoing Streams Request (5.1.5).
102    AddOutgoingStreams(u16),
103    /// Add Incoming Streams Request (5.1.6).
104    AddIncomingStreams(u16),
105}
106
107/// An Incoming SSN Reset Request of the peer that this side performs: the reset of each of
108/// its streams waits in the send queue behind the data written before it.
109#[derive(Debug, Clone)]
110pub(crate) struct IncomingResetWaiting {
111    /// The stream numbers as the peer listed them, copied into the answer (5.1.2 A4).
112    streams: Vec<u16>,
113    /// The streams whose turn in the send queue has not come yet.
114    markers_left: usize,
115    /// The streams this side holds, with their generations.
116    generations: Vec<(u16, Option<u64>)>,
117}
118
119/// What a received RE-CONFIG chunk is answered with.
120#[derive(Default)]
121pub(crate) struct ReconfigAnswer {
122    responses: Vec<ParamReconfigResponse>,
123    /// Streams whose outgoing direction this side resets in turn (RFC 8831 6.7).
124    echo: Vec<u16>,
125    /// Answers given before, sent again as they were (RFC 6525 5.2.1).
126    repeats: Vec<ChunkReconfig>,
127}
128
129impl ReconfigAnswer {
130    fn respond(&mut self, rsn: u32, result: ReconfigResult) {
131        self.responses.push(ParamReconfigResponse {
132            reconfig_response_sequence_number: rsn,
133            result,
134            next_tsns: None,
135        });
136    }
137}
138
139/// How a request of the peer's stands, by its sequence number.
140enum PeerRequest {
141    New,
142    /// Accepted and not performed yet.
143    Deferred,
144    /// Answered for good, with this chunk.
145    Answered(ChunkReconfig),
146    /// Not a number the peer can be using now.
147    Bad,
148}
149
150/// Puts DATA chunks in TSN order (serial number arithmetic, RFC 9260 1.6: they lie within
151/// one receive window of each other).
152fn sort_by_tsn(chunks: &mut [ChunkPayloadData]) {
153    let Some(base) = chunks
154        .iter()
155        .map(|c| c.tsn)
156        .reduce(|a, b| if sna32lt(b, a) { b } else { a })
157    else {
158        return;
159    };
160    chunks.sort_by_key(|c| c.tsn.wrapping_sub(base));
161}
162
163/// RFC 6525 3.1: the ten combinations of parameters a RE-CONFIG chunk may hold.
164fn allowed_combination(a: u16, b: Option<u16>) -> bool {
165    match b {
166        None => matches!(a, 13..=18),
167        Some(b) => matches!(
168            (a.min(b), a.max(b)),
169            (13, 14) | (17, 18) | (13, 16) | (16, 16)
170        ),
171    }
172}
173
174impl Association {
175    /// Whether the peer announced the stream re-configuration extension (RFC 6525 5.1.1).
176    /// Without it no stream can be reset, which closing a WebRTC data channel needs.
177    pub fn peer_supports_reconfig(&self) -> bool {
178        self.peer_supports_reconfig
179    }
180
181    /// Asks the peer to reset some of its outgoing streams, this side's incoming ones (RFC
182    /// 6525 5.1.3); no stream listed asks for all of them. The peer answers by resetting
183    /// them, which arrives as a reset of each stream, or by refusing
184    /// ([`ReconfigEvent::IncomingStreamsResetNotPerformed`]).
185    pub fn request_incoming_stream_reset(&mut self, streams: &[StreamId]) -> Result<()> {
186        self.check_reconfig_allowed()?;
187        self.queue_own_request(OwnRequest::IncomingReset {
188            streams: streams.to_vec(),
189        })
190    }
191
192    /// Asks for the TSNs of both directions and the Stream Sequence Numbers of every stream
193    /// to start over (RFC 6525 5.1.4). Nothing new is sent from now until the peer has
194    /// answered ([`ReconfigEvent::AssociationReset`] or
195    /// [`ReconfigEvent::AssociationResetFailed`]); what is written meanwhile is queued. The
196    /// request goes out once everything sent so far is acknowledged.
197    ///
198    /// Refused within 30 seconds of the last such request.
199    pub fn request_ssn_tsn_reset(&mut self, now: Instant) -> Result<()> {
200        self.check_reconfig_allowed()?;
201        if self.tsn_reset_requested {
202            return Err(Error::OtherSctpErr(
203                "an SSN/TSN reset is already under way".into(),
204            ));
205        }
206        if self
207            .last_tsn_reset_request
208            .is_some_and(|last| now.saturating_duration_since(last) < MIN_TSN_RESET_INTERVAL)
209        {
210            return Err(Error::OtherSctpErr(
211                "one SSN/TSN reset per 30 seconds (RFC 6525 5.1.4)".into(),
212            ));
213        }
214        self.queue_own_request(OwnRequest::SsnTsnReset)?;
215        self.tsn_reset_requested = true;
216        self.last_tsn_reset_request = Some(now);
217        Ok(())
218    }
219
220    /// Asks for `count` more outgoing streams (RFC 6525 5.1.5). They may be used once the
221    /// peer has accepted ([`ReconfigEvent::StreamsAdded`]), and not before.
222    pub fn add_outgoing_streams(&mut self, count: u16) -> Result<()> {
223        self.check_reconfig_allowed()?;
224        if count == 0
225            || self
226                .my_max_num_outbound_streams
227                .checked_add(count)
228                .is_none()
229        {
230            return Err(Error::ErrStreamCreateFailed);
231        }
232        self.queue_own_request(OwnRequest::AddOutgoingStreams(count))
233    }
234
235    /// Asks the peer to add `count` outgoing streams of its own, this side's incoming ones
236    /// (RFC 6525 5.1.6). A peer that agrees adds them with a request of its own; asking
237    /// raises this side's inbound limit ([`set_stream_limits`](Self::set_stream_limits)) to
238    /// make room for them.
239    pub fn add_incoming_streams(&mut self, count: u16) -> Result<()> {
240        self.check_reconfig_allowed()?;
241        let Some(total) = self
242            .my_max_num_inbound_streams
243            .checked_add(count)
244            .filter(|_| count != 0)
245        else {
246            return Err(Error::ErrStreamCreateFailed);
247        };
248        self.queue_own_request(OwnRequest::AddIncomingStreams(count))?;
249        self.configured_inbound_streams = self.configured_inbound_streams.max(total);
250        Ok(())
251    }
252
253    /// Sets how many streams this association may grow to when the peer asks for more (RFC
254    /// 6525 5.2.5, 5.2.6: "a limit that should be configurable by the application"): a
255    /// request that would take the inbound or the outbound count past its limit is denied.
256    /// The limits start as the counts the association was configured with
257    /// ([`TransportConfig::with_max_num_inbound_streams`],
258    /// [`TransportConfig::with_max_num_outbound_streams`]). Streams the association already
259    /// has are not taken away.
260    pub fn set_stream_limits(&mut self, max_inbound: u16, max_outbound: u16) {
261        self.configured_inbound_streams = max_inbound;
262        self.configured_outbound_streams = max_outbound;
263    }
264
265    /// RFC 6525 5.1.1: no re-configuration request is sent to a peer that did not announce
266    /// the extension, and the application is told so.
267    fn check_reconfig_allowed(&self) -> Result<()> {
268        if self.state() != AssociationState::Established {
269            return Err(Error::ErrResetPacketInStateNotExist);
270        }
271        if !self.peer_supports_reconfig {
272            return Err(Error::OtherSctpErr(
273                "the peer does not support stream re-configuration (RFC 6525 5.1.1)".into(),
274            ));
275        }
276        Ok(())
277    }
278
279    /// Whether new DATA is held back for an SSN/TSN reset (RFC 6525 5.1.4 C2), this side's
280    /// own or the peer's.
281    pub(crate) fn sending_suspended(&self) -> bool {
282        self.tsn_reset_requested || self.deferred_tsn_reset.is_some()
283    }
284
285    /// Queues the reset of an outgoing stream (RFC 6525 5.1.2). It waits in the send queue
286    /// behind the data written before it, so the request's "Sender's Last Assigned TSN"
287    /// covers that data; its retransmission timer starts when the request is sent.
288    pub(crate) fn send_reset_request(
289        &mut self,
290        _now: Instant,
291        stream_identifier: StreamId,
292    ) -> Result<()> {
293        self.check_reconfig_allowed()?;
294        let mut generation = 0;
295        if let Some(s) = self.streams.get_mut(&stream_identifier) {
296            // 5.1.2 A1: from now on new data of this stream gets no sequence number.
297            s.outgoing_reset_pending = true;
298            generation = s.generation;
299        }
300        self.pending_queue.push_reset(ResetMarker {
301            stream_identifier,
302            generation,
303            response_to: None,
304        });
305        self.awake_write_loop();
306
307        Ok(())
308    }
309
310    /// Puts a request in the queue behind the one in flight. A reset of outgoing streams
311    /// joins the one waiting at the end of the queue.
312    fn queue_own_request(&mut self, request: OwnRequest) -> Result<()> {
313        self.queue_own_request_bounded(request, true)
314    }
315
316    fn queue_own_request_bounded(&mut self, request: OwnRequest, bounded: bool) -> Result<()> {
317        if let OwnRequest::OutgoingReset {
318            streams,
319            response_to: None,
320        } = &request
321            && let Some(OwnRequest::OutgoingReset {
322                streams: waiting,
323                response_to: None,
324            }) = self.reconfig_queue.back_mut()
325            && !waiting.is_empty()
326            && !streams.is_empty()
327        {
328            for stream in streams {
329                if !waiting.contains(stream) {
330                    waiting.push(*stream);
331                }
332            }
333            return Ok(());
334        }
335        if bounded && self.reconfig_queue.len() >= MAX_OUTSTANDING_RECONFIGS {
336            return Err(Error::OtherSctpErr(
337                "too many re-configuration requests are waiting".into(),
338            ));
339        }
340        self.reconfig_queue.push_back(request);
341        self.awake_write_loop();
342        Ok(())
343    }
344
345    /// A stream reset reached the head of the send queue: the data written before it has
346    /// been sent, and the reset can be asked for.
347    pub(crate) fn on_reset_marker_ready(&mut self, marker: ResetMarker) {
348        let Some(rsn) = marker.response_to else {
349            // Asked for by `Stream::stop`, which has changed the stream already: not refused
350            // for a full queue.
351            let _ = self.queue_own_request_bounded(
352                OwnRequest::OutgoingReset {
353                    streams: vec![(marker.stream_identifier, Some(marker.generation))],
354                    response_to: None,
355                },
356                false,
357            );
358            return;
359        };
360        // One stream of an Incoming SSN Reset Request the peer sent.
361        let done = self
362            .incoming_resets_waiting
363            .get_mut(&rsn)
364            .is_some_and(|waiting| {
365                waiting.markers_left = waiting.markers_left.saturating_sub(1);
366                waiting.markers_left == 0
367            });
368        // The request stays on record, as one being worked on, until its answer leaves.
369        if done && let Some(waiting) = self.incoming_resets_waiting.get(&rsn).cloned() {
370            self.answer_incoming_reset(rsn, waiting);
371        }
372    }
373
374    /// RFC 6525 5.2.3 F1: the Outgoing SSN Reset Request that answers the peer's Incoming
375    /// SSN Reset Request `rsn`. It is the answer, so it is not refused for a full queue.
376    fn answer_incoming_reset(&mut self, rsn: u32, waiting: IncomingResetWaiting) {
377        // 5.1.2 A4: the stream numbers are copied from the peer's request. `generations`
378        // says which of them this side holds.
379        let streams = waiting
380            .streams
381            .iter()
382            .map(|id| {
383                let generation = waiting
384                    .generations
385                    .iter()
386                    .find(|(held, _)| held == id)
387                    .and_then(|(_, generation)| *generation);
388                (*id, generation)
389            })
390            .collect();
391        self.reconfig_queue.push_back(OwnRequest::OutgoingReset {
392            streams,
393            response_to: Some(rsn),
394        });
395    }
396
397    /// The most stream numbers one Outgoing or Incoming SSN Reset Request holds: what fits a
398    /// packet.
399    fn max_streams_per_request(&self) -> usize {
400        if self.mtu == 0 {
401            return usize::MAX;
402        }
403        // Common header, chunk header, the largest request parameter header.
404        ((self.mtu as usize).saturating_sub(COMMON_HEADER_SIZE as usize + CHUNK_HEADER_SIZE + 16)
405            / 2)
406        .max(1)
407    }
408
409    /// The next request, if none is in flight and one waits (RFC 6525 5.1.1).
410    pub(crate) fn next_reconfig_request(&mut self, now: Instant) -> Option<Packet> {
411        if !self.reconfigs.is_empty() {
412            return None;
413        }
414        if matches!(self.reconfig_queue.front()?, OwnRequest::SsnTsnReset)
415            && !(self.inflight_queue.is_empty() && !self.pending_queue.is_mid_message())
416        {
417            // 5.1.4 C2: the sender has no outstanding TSNs.
418            return None;
419        }
420        let mut request = self.reconfig_queue.pop_front()?;
421        let limit = self.max_streams_per_request();
422        match &mut request {
423            OwnRequest::OutgoingReset {
424                streams,
425                response_to: None,
426            } if streams.len() > limit => {
427                let rest = streams.split_off(limit);
428                self.reconfig_queue.push_front(OwnRequest::OutgoingReset {
429                    streams: rest,
430                    response_to: None,
431                });
432            }
433            OwnRequest::IncomingReset { streams } if streams.len() > limit => {
434                let rest = streams.split_off(limit);
435                self.reconfig_queue
436                    .push_front(OwnRequest::IncomingReset { streams: rest });
437            }
438            _ => {}
439        }
440        if request == OwnRequest::SsnTsnReset {
441            self.last_tsn_reset_request = Some(now);
442        }
443        let (rsn, param) = self.own_request_param(&request);
444        debug!(
445            "[{}] sending RECONFIG: rsn={} {:?}",
446            self.side, rsn, request
447        );
448        let chunk = ChunkReconfig {
449            param_a: Some(param),
450            param_b: None,
451        };
452        if let OwnRequest::OutgoingReset {
453            response_to: Some(answered),
454            ..
455        } = &request
456        {
457            // This request is the answer to the peer's Incoming SSN Reset Request: a
458            // retransmission of that one gets it again (5.2.1).
459            self.incoming_resets_waiting.remove(answered);
460            self.remember_answer(*answered, chunk.clone());
461        }
462        self.reconfigs.insert(rsn, chunk.clone());
463        self.reconfig_in_flight = Some(request);
464        self.reconfig_in_progress = false;
465        // 5.1.1: the timer starts when the request is sent.
466        self.timers.stop(Timer::Reconfig);
467        self.timers
468            .start(Timer::Reconfig, now, self.rto_mgr.get_rto());
469        Some(self.create_packet(vec![Box::new(chunk)]))
470    }
471
472    /// Builds the parameter of `request`, with the next request sequence number (RFC 6525
473    /// 5.1.2 A2, 5.1.3 B1, 5.1.4 C1).
474    fn own_request_param(&mut self, request: &OwnRequest) -> (u32, Box<dyn Param>) {
475        let rsn = self.generate_next_rsn();
476        let param: Box<dyn Param> = match request {
477            OwnRequest::OutgoingReset {
478                streams,
479                response_to,
480            } => Box::new(ParamOutgoingResetRequest {
481                reconfig_request_sequence_number: rsn,
482                // 5.1.2 A4: the peer's request this answers, or else the peer's next
483                // expected request sequence number minus 1.
484                reconfig_response_sequence_number: response_to.unwrap_or_else(|| {
485                    self.peer_rsn_window
486                        .map_or(0, |(_, next)| next.wrapping_sub(1))
487                }),
488                // 5.1.2 A3.
489                sender_last_tsn: self.my_next_tsn.wrapping_sub(1),
490                stream_identifiers: streams.iter().map(|(id, _)| *id).collect(),
491            }),
492            OwnRequest::IncomingReset { streams } => Box::new(ParamIncomingResetRequest {
493                reconfig_request_sequence_number: rsn,
494                stream_identifiers: streams.clone(),
495            }),
496            OwnRequest::SsnTsnReset => Box::new(ParamSsnTsnResetRequest {
497                reconfig_request_sequence_number: rsn,
498            }),
499            OwnRequest::AddOutgoingStreams(count) => Box::new(ParamAddStreamsRequest {
500                incoming: false,
501                reconfig_request_sequence_number: rsn,
502                number_of_new_streams: *count,
503            }),
504            OwnRequest::AddIncomingStreams(count) => Box::new(ParamAddStreamsRequest {
505                incoming: true,
506                reconfig_request_sequence_number: rsn,
507                number_of_new_streams: *count,
508            }),
509        };
510        (rsn, param)
511    }
512
513    /// RFC 6525 5.2.1: a RE-CONFIG chunk. Each parameter is processed, and what is returned
514    /// goes back in one chunk.
515    pub(crate) fn handle_reconfig(&mut self, c: &ChunkReconfig) -> Result<Vec<Packet>> {
516        trace!("[{}] handle_reconfig", self.side);
517
518        let params: Vec<&Box<dyn Param>> = [&c.param_a, &c.param_b].into_iter().flatten().collect();
519        let types: Vec<u16> = params.iter().map(|p| u16::from(p.header().typ)).collect();
520        let known = |t: &u16| matches!(*t, 13..=18);
521        if types.iter().all(known)
522            && let Some(first) = types.first()
523            && !allowed_combination(*first, types.get(1).copied())
524        {
525            // 3.1: a combination that is not allowed is answered with an ERROR chunk,
526            // "Protocol Violation", and none of it is performed.
527            warn!(
528                "[{}] RE-CONFIG with parameters {:?}: not an allowed combination",
529                self.side, types
530            );
531            self.report_error(Self::protocol_violation(
532                "RE-CONFIG: parameter combination not allowed (RFC 6525 3.1)",
533            ));
534            return Ok(vec![]);
535        }
536
537        let mut answer = ReconfigAnswer::default();
538        let mut held_request = false;
539        for param in params {
540            // RFC 6525 4, RFC 9260 3.2.1: a parameter that is not recognized ends the
541            // processing of this chunk (its type's upper bits are 00), and of nothing else.
542            if !self.handle_reconfig_param(param, &mut answer)? {
543                break;
544            }
545            held_request |= u16::from(param.header().typ) != 16;
546        }
547        if held_request
548            && matches!(
549                self.state(),
550                AssociationState::Established
551                    | AssociationState::ShutdownPending
552                    | AssociationState::ShutdownReceived
553            )
554        {
555            // 5.2.1: a chunk with a request is acknowledged with a SACK as well, which
556            // hurries along whatever the request waits for.
557            self.immediate_ack_triggered = true;
558        }
559        Ok(self.reconfig_answer_packets(answer))
560    }
561
562    /// Handles one parameter of a RE-CONFIG chunk. `Ok(false)`: the parameter is not one
563    /// this side knows, and the rest of the chunk is not processed.
564    #[allow(clippy::borrowed_box)]
565    fn handle_reconfig_param(
566        &mut self,
567        raw: &Box<dyn Param>,
568        answer: &mut ReconfigAnswer,
569    ) -> Result<bool> {
570        let any = raw.as_any();
571        if let Some(p) = any.downcast_ref::<ParamReconfigResponse>() {
572            self.handle_reconfig_response(p);
573            return Ok(true);
574        }
575        let rsn = if let Some(p) = any.downcast_ref::<ParamOutgoingResetRequest>() {
576            // 5.2.2 E1: the request can be the answer to an Incoming SSN Reset Request of
577            // this side's.
578            self.acknowledge_incoming_reset_request(p.reconfig_response_sequence_number);
579            p.reconfig_request_sequence_number
580        } else if let Some(p) = any.downcast_ref::<ParamIncomingResetRequest>() {
581            p.reconfig_request_sequence_number
582        } else if let Some(p) = any.downcast_ref::<ParamSsnTsnResetRequest>() {
583            p.reconfig_request_sequence_number
584        } else if let Some(p) = any.downcast_ref::<ParamAddStreamsRequest>() {
585            p.reconfig_request_sequence_number
586        } else {
587            debug!("[{}] ignoring RE-CONFIG parameter {}", self.side, raw);
588            return Ok(false);
589        };
590
591        // 5.2.1: the request sequence number says whether this is a request seen before.
592        match self.classify_peer_request(rsn) {
593            PeerRequest::Deferred => {
594                if self.deferred_tsn_reset == Some(rsn) {
595                    // The retransmission of an SSN/TSN Reset Request that waited for this
596                    // side's outstanding DATA: perhaps it can be performed now.
597                    let performed = self.perform_deferred_tsn_reset();
598                    if performed.is_empty() {
599                        answer.respond(rsn, ReconfigResult::InProgress);
600                    } else if let Some((_, chunk)) = self
601                        .completed_reconfig_requests
602                        .iter()
603                        .find(|(done, _)| *done == rsn)
604                    {
605                        answer.repeats.push(chunk.clone());
606                    }
607                } else {
608                    answer.respond(rsn, ReconfigResult::InProgress);
609                }
610                return Ok(true);
611            }
612            PeerRequest::Answered(chunk) => {
613                answer.repeats.push(chunk);
614                return Ok(true);
615            }
616            PeerRequest::Bad => {
617                debug!(
618                    "[{}] RE-CONFIG request {} is not a sequence number the peer can be using",
619                    self.side, rsn
620                );
621                answer.respond(rsn, ReconfigResult::ErrorBadSequenceNumber);
622                return Ok(true);
623            }
624            PeerRequest::New => self.note_peer_request(rsn),
625        }
626
627        if let Some(p) = any.downcast_ref::<ParamOutgoingResetRequest>() {
628            if self.reconfig_requests.len() >= MAX_PENDING_RECONFIG_REQUESTS {
629                debug!(
630                    "[{}] deny reset request rsn={}: {} requests already pending",
631                    self.side,
632                    rsn,
633                    self.reconfig_requests.len()
634                );
635                answer.respond(rsn, ReconfigResult::Denied);
636                return Ok(true);
637            }
638            self.reconfig_requests.insert(rsn, p.clone());
639            let (result, mut echo) = self.perform_peer_outgoing_reset(p);
640            answer.respond(rsn, result);
641            answer.echo.append(&mut echo);
642        } else if let Some(p) = any.downcast_ref::<ParamIncomingResetRequest>() {
643            self.handle_incoming_reset_request(p, answer);
644        } else if any.downcast_ref::<ParamSsnTsnResetRequest>().is_some() {
645            self.handle_tsn_reset_request(rsn, answer);
646        } else if let Some(p) = any.downcast_ref::<ParamAddStreamsRequest>() {
647            self.handle_add_streams_request(p, answer);
648        }
649        Ok(true)
650    }
651
652    fn classify_peer_request(&self, rsn: u32) -> PeerRequest {
653        if self.reconfig_requests.contains_key(&rsn)
654            || self.incoming_resets_waiting.contains_key(&rsn)
655            || self.deferred_tsn_reset == Some(rsn)
656        {
657            return PeerRequest::Deferred;
658        }
659        if let Some((_, chunk)) = self
660            .completed_reconfig_requests
661            .iter()
662            .find(|(done, _)| *done == rsn)
663        {
664            return PeerRequest::Answered(chunk.clone());
665        }
666        match self.peer_rsn_window {
667            // No handshake told the peer's first number: the first request tells it.
668            None => PeerRequest::New,
669            Some((lowest, next)) => {
670                if sna32gte(rsn, lowest) && sna32lt(rsn, next.wrapping_add(PEER_RSN_WINDOW)) {
671                    PeerRequest::New
672                } else {
673                    PeerRequest::Bad
674                }
675            }
676        }
677    }
678
679    /// Takes `rsn` as a request sequence number the peer has used.
680    fn note_peer_request(&mut self, rsn: u32) {
681        let (mut lowest, mut next) = self.peer_rsn_window.unwrap_or((rsn, rsn));
682        if sna32gte(rsn, next) {
683            next = rsn.wrapping_add(1);
684        }
685        if next.wrapping_sub(lowest) > PEER_RSN_WINDOW {
686            lowest = next.wrapping_sub(PEER_RSN_WINDOW);
687        }
688        self.peer_rsn_window = Some((lowest, next));
689    }
690
691    /// Remembers the chunk a request was answered with for good.
692    fn remember_answer(&mut self, rsn: u32, chunk: ChunkReconfig) {
693        self.completed_reconfig_requests
694            .retain(|(done, _)| *done != rsn);
695        if self.completed_reconfig_requests.len() >= MAX_COMPLETED_RECONFIG_REQUESTS {
696            self.completed_reconfig_requests.pop_front();
697        }
698        self.completed_reconfig_requests.push_back((rsn, chunk));
699    }
700
701    /// Turns what a RE-CONFIG chunk is answered with into packets: the responses in one
702    /// chunk (RFC 6525 5.2.1), with this side's own reset of the same streams when it can go
703    /// along (3.1, combination 9).
704    pub(crate) fn reconfig_answer_packets(&mut self, answer: ReconfigAnswer) -> Vec<Packet> {
705        let mut packets: Vec<Packet> = answer
706            .repeats
707            .into_iter()
708            .map(|chunk| self.create_packet(vec![Box::new(chunk)]))
709            .collect();
710
711        let mut bundled: Option<(u32, OwnRequest, Box<dyn Param>)> = None;
712        if !answer.echo.is_empty() {
713            let own = OwnRequest::OutgoingReset {
714                streams: answer.echo.iter().map(|id| (*id, None)).collect(),
715                response_to: None,
716            };
717            if answer.responses.len() == 1
718                && self.reconfigs.is_empty()
719                && self.reconfig_queue.is_empty()
720                && self.peer_supports_reconfig
721                && answer.echo.len() <= self.max_streams_per_request()
722            {
723                let (rsn, param) = self.own_request_param(&own);
724                bundled = Some((rsn, own, param));
725            } else if self.queue_own_request(own).is_err() {
726                debug!(
727                    "[{}] resetStream(): not echoing reset of {:?}, {} requests waiting",
728                    self.side,
729                    answer.echo,
730                    self.reconfig_queue.len()
731                );
732            }
733        }
734
735        if answer.responses.is_empty() {
736            return packets;
737        }
738        let finals: Vec<u32> = answer
739            .responses
740            .iter()
741            .filter(|r| r.result != ReconfigResult::InProgress)
742            .map(|r| r.reconfig_response_sequence_number)
743            .collect();
744        let mut params: Vec<Box<dyn Param>> = answer
745            .responses
746            .into_iter()
747            .map(|r| Box::new(r) as Box<dyn Param>)
748            .collect();
749        let mut in_flight = None;
750        if let Some((rsn, own, param)) = bundled {
751            params.push(param);
752            in_flight = Some((rsn, own));
753        }
754        let mut params = params.into_iter();
755        let chunk = ChunkReconfig {
756            param_a: params.next(),
757            param_b: params.next(),
758        };
759        debug!("[{}] RESET RESPONSE: {}", self.side, chunk);
760        for rsn in finals {
761            self.remember_answer(rsn, chunk.clone());
762        }
763        if let Some((rsn, own)) = in_flight {
764            // The request is retransmitted with the response it left with.
765            self.reconfigs.insert(rsn, chunk.clone());
766            self.reconfig_in_flight = Some(own);
767            self.reconfig_in_progress = false;
768        }
769        packets.push(self.create_packet(vec![Box::new(chunk)]));
770        packets
771    }
772
773    /// Streams named by `p` that still hold a complete message the application
774    /// has not collected, so a reset naming them cannot be performed yet.
775    ///
776    /// Only *readable* data counts: an incomplete fragment set can never be
777    /// completed once the peer has reset, so it is discardable and must not
778    /// hold the reset open forever.
779    ///
780    /// Nor does data on a stream the application has stopped reading (`Stream::stop`, or
781    /// `Stream::close`: the close of a data channel): reads of it fail, so nothing would ever
782    /// drain it, and the reset that completes the close (RFC 8831 6.7) would wait for good,
783    /// with the stream id never freed and the bytes never given back to the window. That data
784    /// is abandoned with the stream ("[RFC6525] also guarantees that all the messages are
785    /// delivered (or abandoned) before the stream is reset"): its channel is closed.
786    fn streams_awaiting_drain(&self, p: &ParamOutgoingResetRequest) -> Vec<StreamId> {
787        p.stream_identifiers
788            .iter()
789            .copied()
790            .filter(|id| {
791                self.streams.get(id).is_some_and(|s| {
792                    let still_read = matches!(
793                        s.state,
794                        RecvSendState::Readable | RecvSendState::ReadWritable
795                    );
796                    still_read && s.reassembly_queue.is_readable()
797                })
798            })
799            .collect()
800    }
801
802    /// RFC 6525 5.2.2: performs the peer's Outgoing SSN Reset Request `p` as far as it can
803    /// be performed now. Returns the result to answer with and the streams whose outgoing
804    /// direction this side resets in turn.
805    fn perform_peer_outgoing_reset(
806        &mut self,
807        p: &ParamOutgoingResetRequest,
808    ) -> (ReconfigResult, Vec<u16>) {
809        // RFC 6525 5.2.2: a request without stream numbers is for every stream.
810        let every_stream = p.stream_identifiers.is_empty();
811        let all_streams;
812        let p = if every_stream {
813            let mut stream_identifiers: Vec<u16> = self.streams.keys().copied().collect();
814            stream_identifiers.sort_unstable();
815            all_streams = ParamOutgoingResetRequest {
816                stream_identifiers,
817                ..p.clone()
818            };
819            &all_streams
820        } else {
821            p
822        };
823        let mut result = ReconfigResult::SuccessPerformed;
824        let mut sis_to_reset = vec![];
825
826        if sna32lte(p.sender_last_tsn, self.peer_last_tsn) {
827            // The reset numbers the streams from 0 again: what a FORWARD TSN skipped on one
828            // this side never created is void.
829            if every_stream {
830                self.skipped_on_absent_streams.clear();
831            } else {
832                self.skipped_on_absent_streams
833                    .retain(|(id, _), _| !p.stream_identifiers.contains(id));
834            }
835            debug!(
836                "[{}] resetStream(): senderLastTSN={} <= peer_last_tsn={}",
837                self.side, p.sender_last_tsn, self.peer_last_tsn
838            );
839
840            let draining = self.streams_awaiting_drain(p);
841            let mut seen = FxHashSet::default();
842
843            for id in &p.stream_identifiers {
844                if draining.contains(id) || !seen.insert(*id) {
845                    continue;
846                }
847                if let Some(stream) = self.streams.get(id) {
848                    // RFC 8831 section 6.7: the receiver of a reset resets its own outgoing
849                    // stream too, unless it already has (the peer's request is then the
850                    // second half of a close this side started). Echoing it again would
851                    // send a reset after the stream id is free, and reset the next channel
852                    // that takes the id.
853                    let outgoing_open = !stream.outgoing_reset_started;
854                    if outgoing_open {
855                        if self.pending_queue.holds_stream(*id) {
856                            // What the application wrote to the stream before now is still
857                            // to be sent, all or part of it without a TSN. RFC 6525 5.1.2 A3
858                            // makes the request's Sender's Last Assigned TSN "the next TSN
859                            // the sender assigns minus 1", and RFC 8831 6.7 relies on it:
860                            // "[RFC6525] also guarantees that all the messages are delivered
861                            // (or abandoned) before the stream is reset". Sent at once, the
862                            // reset would leave that data after the Sender's Last Assigned
863                            // TSN, where the peer takes it for data of the stream after the
864                            // reset (5.2.2 E2, E4): the rest of a message half sent there
865                            // waits in front of the next channel on the stream for good. So
866                            // the reset waits behind it in the send queue, as a reset this
867                            // side asks for itself does (`send_reset_request`).
868                            let generation = stream.generation;
869                            self.pending_queue.push_reset(ResetMarker {
870                                stream_identifier: *id,
871                                generation,
872                                response_to: None,
873                            });
874                            self.awake_write_loop();
875                        } else {
876                            sis_to_reset.push(*id);
877                        }
878                    }
879                    self.unregister_stream(*id, AssociationError::Reset);
880                } else if self.my_max_num_inbound_streams == 0
881                    || *id < self.my_max_num_inbound_streams
882                {
883                    // A stream this side never sent or received on (a pre-negotiated data
884                    // channel left idle) has no state here, but the application still
885                    // holds it: report the reset, and reset the outgoing direction too.
886                    // An id past the negotiated stream count names no such channel.
887                    sis_to_reset.push(*id);
888                    self.events.push_back(Event::AssociationLost {
889                        reason: AssociationError::Reset,
890                        id: *id,
891                    });
892                }
893            }
894
895            if draining.is_empty() {
896                self.reconfig_requests
897                    .remove(&p.reconfig_request_sequence_number);
898            } else {
899                debug!(
900                    "[{}] resetStream(): deferring reset of {:?}, application has not drained",
901                    self.side, draining
902                );
903                result = ReconfigResult::InProgress;
904                // Keep only the streams still waiting, so a retry performs each reset once.
905                self.reconfig_requests.insert(
906                    p.reconfig_request_sequence_number,
907                    ParamOutgoingResetRequest {
908                        stream_identifiers: draining,
909                        ..p.clone()
910                    },
911                );
912            }
913            // 5.2.2 E4: the DATA that was held for the streams now reset is processed.
914            self.release_held_reset_data();
915        } else {
916            debug!(
917                "[{}] resetStream(): senderLastTSN={} > peer_last_tsn={}",
918                self.side, p.sender_last_tsn, self.peer_last_tsn
919            );
920            result = ReconfigResult::InProgress;
921        }
922
923        (result, sis_to_reset)
924    }
925
926    /// Whether DATA chunk `d` waits for a reset that is not performed yet: the peer sent it
927    /// after the request (RFC 6525 5.2.2 E2), so it belongs to the stream as it is after the
928    /// reset. Also everything received while this side's own SSN/TSN reset is in flight,
929    /// which is sorted out when the answer says where the peer's new TSNs start.
930    pub(crate) fn holds_for_reset(&self, d: &ChunkPayloadData) -> bool {
931        if matches!(self.reconfig_in_flight, Some(OwnRequest::SsnTsnReset)) {
932            return true;
933        }
934        self.reconfig_requests.values().any(|p| {
935            sna32gt(d.tsn, p.sender_last_tsn)
936                && (p.stream_identifiers.is_empty()
937                    || p.stream_identifiers.contains(&d.stream_identifier))
938        })
939    }
940
941    /// Delivers the held DATA that no deferred reset holds any more.
942    fn release_held_reset_data(&mut self) {
943        if self.held_reset_data.is_empty() {
944            return;
945        }
946        let mut held = std::mem::take(&mut self.held_reset_data);
947        // In TSN order, as they would have been processed had they not waited: a fragment
948        // goes to its stream after the one before it in its message.
949        sort_by_tsn(&mut held);
950        for d in held {
951            if self.holds_for_reset(&d) {
952                self.held_reset_data.push(d);
953            } else {
954                self.reassembly_bytes = self.reassembly_bytes.saturating_sub(d.user_data.len());
955                self.deliver_to_stream(&d);
956            }
957        }
958    }
959
960    /// Performs the stored reset requests whose sender's last TSN the cumulative TSN reached
961    /// since it stood at `prev_peer_last_tsn`.
962    pub(crate) fn reset_streams_reached_since(
963        &mut self,
964        prev_peer_last_tsn: u32,
965        reply: &mut Vec<Packet>,
966    ) -> Result<()> {
967        if self.peer_last_tsn == prev_peer_last_tsn || self.reconfig_requests.is_empty() {
968            return Ok(());
969        }
970        let peer_last_tsn = self.peer_last_tsn;
971        let mut reached: Vec<ParamOutgoingResetRequest> = self
972            .reconfig_requests
973            .values()
974            .filter(|p| {
975                sna32gt(p.sender_last_tsn, prev_peer_last_tsn)
976                    && sna32lte(p.sender_last_tsn, peer_last_tsn)
977            })
978            .cloned()
979            .collect();
980        reached.sort_by_key(|p| p.reconfig_request_sequence_number);
981        for request in reached {
982            // Performed late, the reset is answered as one performed at once is: with this
983            // side's own reset of the streams (RFC 8831 6.7). Each stream is performed (and
984            // unregistered) once, so none is answered twice; a stream still to drain is
985            // answered by `retry_deferred_resets`.
986            let mut answer = ReconfigAnswer::default();
987            let (result, mut echo) = self.perform_peer_outgoing_reset(&request);
988            answer.respond(request.reconfig_request_sequence_number, result);
989            answer.echo.append(&mut echo);
990            reply.append(&mut self.reconfig_answer_packets(answer));
991        }
992        Ok(())
993    }
994
995    /// Re-run any reset request that was answered In Progress because
996    /// `stream_identifier` still had data the application had not collected
997    /// Called when that stream drains.
998    ///
999    /// The reply is queued like any other control packet; a request naming
1000    /// several streams is retried as a whole and simply defers again if another
1001    /// of its streams is still readable.
1002    pub(crate) fn retry_deferred_resets(&mut self, stream_identifier: StreamId) {
1003        let mut pending: Vec<ParamOutgoingResetRequest> = self
1004            .reconfig_requests
1005            .values()
1006            .filter(|p| p.stream_identifiers.contains(&stream_identifier))
1007            .cloned()
1008            .collect();
1009        if pending.is_empty() {
1010            return;
1011        }
1012        pending.sort_by_key(|p| p.reconfig_request_sequence_number);
1013
1014        for p in pending {
1015            let mut answer = ReconfigAnswer::default();
1016            let (result, mut echo) = self.perform_peer_outgoing_reset(&p);
1017            answer.respond(p.reconfig_request_sequence_number, result);
1018            answer.echo.append(&mut echo);
1019            for packet in self.reconfig_answer_packets(answer) {
1020                self.control_queue.push_back(packet);
1021            }
1022        }
1023        self.awake_write_loop();
1024    }
1025
1026    /// RFC 6525 5.2.3: the peer asks this side to reset outgoing streams.
1027    fn handle_incoming_reset_request(
1028        &mut self,
1029        p: &ParamIncomingResetRequest,
1030        answer: &mut ReconfigAnswer,
1031    ) {
1032        let rsn = p.reconfig_request_sequence_number;
1033        let wanted = &p.stream_identifiers;
1034
1035        // "If the Outgoing SSN Reset Request Parameter that was just sent completely
1036        // overlaps the received Incoming SSN Reset Request Parameter, respond ... Nothing to
1037        // do".
1038        if let Some(OwnRequest::OutgoingReset { streams, .. }) = &self.reconfig_in_flight {
1039            let covered = streams.is_empty()
1040                || (!wanted.is_empty()
1041                    && wanted
1042                        .iter()
1043                        .all(|id| streams.iter().any(|(sent, _)| sent == id)));
1044            if covered {
1045                answer.respond(rsn, ReconfigResult::SuccessNop);
1046                return;
1047            }
1048        }
1049
1050        // The streams of the request this side holds and sends on.
1051        let mut held: Vec<u16> = if wanted.is_empty() {
1052            self.streams.keys().copied().collect()
1053        } else {
1054            let mut seen = FxHashSet::default();
1055            wanted
1056                .iter()
1057                .copied()
1058                .filter(|id| seen.insert(*id) && self.streams.contains_key(id))
1059                .collect()
1060        };
1061        held.sort_unstable();
1062
1063        // "the Incoming request will arrive after the Outgoing SSN Reset Request just
1064        // completed. In such a case, all of the streams being requested will be already set
1065        // to 0": nothing to do. A stream this side holds no state for has sent nothing.
1066        let untouched = held.iter().all(|id| {
1067            self.streams
1068                .get(id)
1069                .is_some_and(|s| s.sequence_number == 0 && !s.outgoing_reset_pending)
1070        });
1071        if untouched {
1072            answer.respond(rsn, ReconfigResult::SuccessNop);
1073            return;
1074        }
1075        if self.incoming_resets_waiting.len() >= MAX_PENDING_RECONFIG_REQUESTS
1076            || self.reconfig_queue.len() >= MAX_OUTSTANDING_RECONFIGS
1077        {
1078            answer.respond(rsn, ReconfigResult::Denied);
1079            return;
1080        }
1081
1082        // F1: the answer is an Outgoing SSN Reset Request for the same streams. Each stream
1083        // is reset when the data written before now has been sent (5.1.2 A3), and takes no
1084        // new sequence numbers until the peer has answered (A1).
1085        let mut waiting = IncomingResetWaiting {
1086            streams: wanted.clone(),
1087            markers_left: 0,
1088            generations: vec![],
1089        };
1090        for id in held {
1091            let Some(s) = self.streams.get_mut(&id) else {
1092                continue;
1093            };
1094            waiting.generations.push((id, Some(s.generation)));
1095            s.outgoing_reset_pending = true;
1096            // As after `Stream::stop`: this side has reset its direction of the stream, so
1097            // the peer's own reset of it (RFC 8831 6.7) is not answered with another. The
1098            // peer's direction is not touched (5.2.3): it stays readable, and what it holds is
1099            // delivered before the peer's reset is performed (5.2.2).
1100            s.outgoing_reset_started = true;
1101            let generation = s.generation;
1102            waiting.markers_left += 1;
1103            self.pending_queue.push_reset(ResetMarker {
1104                stream_identifier: id,
1105                generation,
1106                response_to: Some(rsn),
1107            });
1108        }
1109        self.events.push_back(Event::Reconfig(
1110            ReconfigEvent::OutgoingResetRequestedByPeer {
1111                streams: wanted.clone(),
1112            },
1113        ));
1114        let ready = waiting.markers_left == 0;
1115        self.incoming_resets_waiting.insert(rsn, waiting.clone());
1116        if ready {
1117            self.answer_incoming_reset(rsn, waiting);
1118        }
1119        self.awake_write_loop();
1120    }
1121
1122    /// RFC 6525 5.2.2 E1: an Outgoing SSN Reset Request whose Response Sequence Number is
1123    /// that of this side's Incoming SSN Reset Request in flight is the answer to it.
1124    fn acknowledge_incoming_reset_request(&mut self, rsn: u32) {
1125        if matches!(
1126            self.reconfig_in_flight,
1127            Some(OwnRequest::IncomingReset { .. })
1128        ) && self.reconfigs.remove(&rsn).is_some()
1129        {
1130            self.reconfig_in_flight = None;
1131            self.reconfig_in_progress = false;
1132            self.timers.stop(Timer::Reconfig);
1133        }
1134    }
1135
1136    /// RFC 6525 5.2.4: the peer asks for an SSN/TSN reset.
1137    fn handle_tsn_reset_request(&mut self, rsn: u32, answer: &mut ReconfigAnswer) {
1138        // Both sides asked at once: each would stop sending and wait for the other.
1139        if self.tsn_reset_requested {
1140            answer.respond(rsn, ReconfigResult::ErrorRequestAlreadyInProgress);
1141            return;
1142        }
1143        if let Some(earlier) = self.deferred_tsn_reset
1144            && earlier != rsn
1145        {
1146            answer.respond(rsn, ReconfigResult::ErrorRequestAlreadyInProgress);
1147            return;
1148        }
1149        self.deferred_tsn_reset = Some(rsn);
1150        let performed = self.perform_deferred_tsn_reset();
1151        if performed.is_empty() {
1152            // G3 takes everything this side sent as acknowledged. Rather than give up DATA
1153            // the peer may not have, the reset waits until it is acknowledged; no new DATA
1154            // is sent meanwhile.
1155            answer.respond(rsn, ReconfigResult::InProgress);
1156        } else if let Some((_, chunk)) = self
1157            .completed_reconfig_requests
1158            .iter()
1159            .find(|(done, _)| *done == rsn)
1160        {
1161            answer.repeats.push(chunk.clone());
1162        }
1163    }
1164
1165    /// Performs the peer's SSN/TSN reset that waited for this side's outstanding DATA, if
1166    /// there is one and nothing is outstanding now. Returns the packet with the response.
1167    pub(crate) fn perform_deferred_tsn_reset(&mut self) -> Vec<Packet> {
1168        let Some(rsn) = self.deferred_tsn_reset else {
1169            return vec![];
1170        };
1171        if !self.inflight_queue.is_empty() || self.pending_queue.is_mid_message() {
1172            return vec![];
1173        }
1174        self.deferred_tsn_reset = None;
1175
1176        // G1: the TSN the peer sends next: the smallest TSN this side has not acknowledged,
1177        // plus 2^31, so that anything of the old numbering still on its way is behind it.
1178        let receiver_next_tsn = self.peer_last_tsn.wrapping_add(1).wrapping_add(1 << 31);
1179        // G2: this side goes on from the highest TSN it sent, plus 1.
1180        let sender_next_tsn = self.my_next_tsn;
1181        // G3: a SACK for everything sent. Nothing is outstanding.
1182        // G4: a FORWARD TSN, all streams, up to the Receiver's Next TSN minus 1.
1183        let prev_peer_last_tsn = self.peer_last_tsn;
1184        self.payload_queue = PayloadQueue::new();
1185        self.peer_last_tsn = receiver_next_tsn.wrapping_sub(1);
1186        let mut packets = vec![];
1187        let _ = self.reset_streams_reached_since(prev_peer_last_tsn, &mut packets);
1188        // G5.
1189        self.reset_all_sequence_numbers();
1190        self.release_held_reset_data();
1191
1192        let chunk = ChunkReconfig {
1193            param_a: Some(Box::new(ParamReconfigResponse {
1194                reconfig_response_sequence_number: rsn,
1195                result: ReconfigResult::SuccessPerformed,
1196                next_tsns: Some((sender_next_tsn, receiver_next_tsn)),
1197            })),
1198            param_b: None,
1199        };
1200        self.remember_answer(rsn, chunk.clone());
1201        self.events
1202            .push_back(Event::Reconfig(ReconfigEvent::AssociationReset {
1203                local_next_tsn: sender_next_tsn,
1204                remote_next_tsn: receiver_next_tsn,
1205            }));
1206        packets.push(self.create_packet(vec![Box::new(chunk)]));
1207        self.awake_write_loop();
1208        packets
1209    }
1210
1211    /// RFC 6525 5.2.4 G5, 5.2.7 H5: the next expected and the outgoing Stream Sequence
1212    /// Numbers of every stream are 0. The ordered messages still queued are numbered again.
1213    fn reset_all_sequence_numbers(&mut self) {
1214        self.skipped_on_absent_streams.clear();
1215        let ids: Vec<StreamId> = self.streams.keys().copied().collect();
1216        for id in &ids {
1217            if let Some(s) = self.streams.get_mut(id) {
1218                let bytes_before = s.get_num_bytes_in_reassembly_queue();
1219                s.reassembly_queue.reset_sequence_numbers();
1220                s.reset_outgoing_numbers();
1221                if s.reassembly_queue.is_readable() {
1222                    self.events
1223                        .push_back(Event::Stream(StreamEvent::Readable { id: *id }));
1224                }
1225                self.reindex_stream(*id, bytes_before);
1226            }
1227        }
1228        // The messages still queued take the first numbers of their streams, and the streams
1229        // go on from there.
1230        let mut next: FxHashMap<u16, (u16, u32, u32)> = FxHashMap::default();
1231        self.pending_queue.renumber(|stream, unordered| {
1232            let (ssn, ordered_mid, unordered_mid) = next.entry(stream).or_insert((0, 0, 0));
1233            if unordered {
1234                let mid = *unordered_mid;
1235                *unordered_mid = unordered_mid.wrapping_add(1);
1236                (*ssn, mid)
1237            } else {
1238                let assigned = (*ssn, *ordered_mid);
1239                *ssn = ssn.wrapping_add(1);
1240                *ordered_mid = ordered_mid.wrapping_add(1);
1241                assigned
1242            }
1243        });
1244        for (id, (ssn, ordered_mid, unordered_mid)) in next {
1245            if let Some(s) = self.streams.get_mut(&id) {
1246                s.sequence_number = ssn;
1247                s.ordered_mid = ordered_mid;
1248                s.unordered_mid = unordered_mid;
1249            }
1250        }
1251    }
1252
1253    /// RFC 6525 5.2.5, 5.2.6: the peer adds outgoing streams, or asks this side to.
1254    fn handle_add_streams_request(
1255        &mut self,
1256        p: &ParamAddStreamsRequest,
1257        answer: &mut ReconfigAnswer,
1258    ) {
1259        let rsn = p.reconfig_request_sequence_number;
1260        let count = p.number_of_new_streams;
1261        if !p.incoming {
1262            // 5.2.6: the peer's Add Outgoing Streams Request is how it performs an Add
1263            // Incoming Streams Request of this side's, which is thereby answered.
1264            if matches!(
1265                self.reconfig_in_flight,
1266                Some(OwnRequest::AddIncomingStreams(_))
1267            ) {
1268                self.reconfigs.clear();
1269                self.reconfig_in_flight = None;
1270                self.reconfig_in_progress = false;
1271                self.timers.stop(Timer::Reconfig);
1272            }
1273            // 5.2.5: the new inbound streams are added, each expecting SSN 0, unless that
1274            // passes the limit the application configured.
1275            let total = self.my_max_num_inbound_streams.checked_add(count);
1276            match total {
1277                Some(total) if total <= self.configured_inbound_streams => {
1278                    if count == 0 {
1279                        answer.respond(rsn, ReconfigResult::SuccessNop);
1280                        return;
1281                    }
1282                    self.my_max_num_inbound_streams = total;
1283                    self.events
1284                        .push_back(Event::Reconfig(ReconfigEvent::StreamsAdded {
1285                            inbound_streams: self.my_max_num_inbound_streams,
1286                            outbound_streams: self.my_max_num_outbound_streams,
1287                        }));
1288                    answer.respond(rsn, ReconfigResult::SuccessPerformed);
1289                }
1290                _ => answer.respond(rsn, ReconfigResult::Denied),
1291            }
1292            return;
1293        }
1294
1295        // 5.2.6: the peer wants more streams from this side: denied, or done with an Add
1296        // Outgoing Streams Request of this side's own.
1297        let total = self.my_max_num_outbound_streams.checked_add(count);
1298        let allowed = total.is_some_and(|total| total <= self.configured_outbound_streams);
1299        if !allowed || !self.peer_supports_reconfig {
1300            answer.respond(rsn, ReconfigResult::Denied);
1301        } else if count == 0 {
1302            answer.respond(rsn, ReconfigResult::SuccessNop);
1303        } else if self
1304            .queue_own_request(OwnRequest::AddOutgoingStreams(count))
1305            .is_ok()
1306        {
1307            answer.respond(rsn, ReconfigResult::SuccessPerformed);
1308        } else {
1309            answer.respond(rsn, ReconfigResult::Denied);
1310        }
1311    }
1312
1313    /// RFC 6525 5.2.7: a Re-configuration Response.
1314    fn handle_reconfig_response(&mut self, p: &ParamReconfigResponse) {
1315        let rsn = p.reconfig_response_sequence_number;
1316        // H1: a response for no request in flight is done with.
1317        if !self.reconfigs.contains_key(&rsn) {
1318            return;
1319        }
1320        if p.result == ReconfigResult::InProgress {
1321            // H2: the timer starts again, and its next expiry is not counted as an error.
1322            self.restart_reconfig_timer = true;
1323            self.reconfig_in_progress = true;
1324            return;
1325        }
1326        self.reconfigs.remove(&rsn);
1327        self.timers.stop(Timer::Reconfig);
1328        self.reconfig_in_progress = false;
1329        let Some(request) = self.reconfig_in_flight.take() else {
1330            return;
1331        };
1332        let success = matches!(
1333            p.result,
1334            ReconfigResult::SuccessPerformed | ReconfigResult::SuccessNop
1335        );
1336        let denied = p.result == ReconfigResult::Denied;
1337        match request {
1338            OwnRequest::OutgoingReset { streams, .. } => {
1339                // H3, H4: on success the streams send from SSN 0; either way sequence
1340                // numbers are assigned again and the data that was queued goes out.
1341                self.finish_outgoing_reset(&streams, success);
1342                let streams = streams.into_iter().map(|(id, _)| id).collect();
1343                self.events.push_back(Event::Reconfig(if success {
1344                    ReconfigEvent::OutgoingStreamsReset { streams }
1345                } else {
1346                    ReconfigEvent::OutgoingStreamsResetFailed { streams, denied }
1347                }));
1348            }
1349            OwnRequest::IncomingReset { streams } => {
1350                // A peer that performs the request answers with an Outgoing SSN Reset
1351                // Request (5.2.2 E1); a response says it did not.
1352                self.events.push_back(Event::Reconfig(
1353                    ReconfigEvent::IncomingStreamsResetNotPerformed { streams, denied },
1354                ));
1355            }
1356            OwnRequest::SsnTsnReset => {
1357                self.finish_tsn_reset(success.then_some(p.next_tsns).flatten(), denied)
1358            }
1359            OwnRequest::AddOutgoingStreams(count) => {
1360                if success {
1361                    // H6: the streams exist from the positive response on.
1362                    self.my_max_num_outbound_streams =
1363                        self.my_max_num_outbound_streams.saturating_add(count);
1364                    self.events
1365                        .push_back(Event::Reconfig(ReconfigEvent::StreamsAdded {
1366                            inbound_streams: self.my_max_num_inbound_streams,
1367                            outbound_streams: self.my_max_num_outbound_streams,
1368                        }));
1369                } else {
1370                    self.events
1371                        .push_back(Event::Reconfig(ReconfigEvent::AddStreamsFailed { denied }));
1372                }
1373            }
1374            OwnRequest::AddIncomingStreams(_) => {
1375                if !success {
1376                    self.events
1377                        .push_back(Event::Reconfig(ReconfigEvent::AddStreamsFailed { denied }));
1378                }
1379            }
1380        }
1381        self.awake_write_loop();
1382    }
1383
1384    /// RFC 6525 5.2.7 H3, H4: the peer answered the reset of these outgoing streams.
1385    fn finish_outgoing_reset(&mut self, streams: &[(u16, Option<u64>)], success: bool) {
1386        let ids: Vec<(u16, Option<u64>)> = if streams.is_empty() {
1387            // Every stream.
1388            self.streams
1389                .iter()
1390                .map(|(id, s)| (*id, Some(s.generation)))
1391                .collect()
1392        } else {
1393            streams.to_vec()
1394        };
1395        for (id, generation) in ids {
1396            let Some(s) = self.streams.get_mut(&id) else {
1397                continue;
1398            };
1399            if generation != Some(s.generation) {
1400                // The stream that asked is gone; this one is another use of its number.
1401                continue;
1402            }
1403            if success {
1404                s.reset_outgoing_numbers();
1405            }
1406            s.outgoing_reset_pending = false;
1407            let held = std::mem::take(&mut s.held_writes);
1408            // They are numbered as they leave the queue, from the numbers just reset (or
1409            // kept, when the peer did not perform the reset).
1410            for chunks in held {
1411                self.held_write_count = self.held_write_count.saturating_sub(1);
1412                self.pending_queue.push_message(chunks);
1413            }
1414        }
1415    }
1416
1417    /// RFC 6525 5.2.7 H5: the peer answered this side's SSN/TSN Reset Request. `next_tsns`
1418    /// is the Sender's Next TSN and the Receiver's Next TSN of a successful response.
1419    fn finish_tsn_reset(&mut self, next_tsns: Option<(u32, u32)>, denied: bool) {
1420        self.tsn_reset_requested = false;
1421        let mut held = std::mem::take(&mut self.held_reset_data);
1422        sort_by_tsn(&mut held);
1423        let release = |this: &mut Self, chunks: Vec<ChunkPayloadData>| {
1424            for d in chunks {
1425                this.reassembly_bytes = this.reassembly_bytes.saturating_sub(d.user_data.len());
1426                this.deliver_to_stream(&d);
1427            }
1428        };
1429        let Some((sender_next_tsn, receiver_next_tsn)) = next_tsns else {
1430            release(self, held);
1431            self.events
1432                .push_back(Event::Reconfig(ReconfigEvent::AssociationResetFailed {
1433                    denied,
1434                }));
1435            return;
1436        };
1437
1438        // What arrived while the request was in flight: the peer's DATA from before its
1439        // reset is delivered first, what it sent after belongs to the streams as reset.
1440        let (after, before): (Vec<_>, Vec<_>) = held
1441            .into_iter()
1442            .partition(|d| sna32gte(d.tsn, sender_next_tsn));
1443        release(self, before);
1444
1445        // "new data MUST be sent from the Receiver's Next TSN, beginning with SSN 0 for all
1446        // outgoing streams".
1447        self.inflight_queue = PayloadQueue::new();
1448        self.my_next_tsn = receiver_next_tsn;
1449        self.cumulative_tsn_ack_point = receiver_next_tsn.wrapping_sub(1);
1450        self.advanced_peer_tsn_ack_point = self.cumulative_tsn_ack_point;
1451        self.min_tsn2measure_rtt = receiver_next_tsn;
1452        self.fwd_tsn_stream_map.clear();
1453        self.i_fwd_tsn_stream_map.clear();
1454        self.will_send_forward_tsn = false;
1455        self.forward_tsn_due_at = None;
1456        self.timers.stop(Timer::T3RTX);
1457        // "All incoming streams MUST be reset to 0 as the next expected SSN. The peer will
1458        // send DATA chunks starting with the Sender's Next TSN."
1459        let last_before = sender_next_tsn.wrapping_sub(1);
1460        if sna32lt(self.peer_last_tsn, last_before) {
1461            while let Some(&front) = self.payload_queue.sorted.front() {
1462                if !sna32lte(front, last_before) || self.payload_queue.pop(front).is_none() {
1463                    break;
1464                }
1465            }
1466            self.peer_last_tsn = last_before;
1467        }
1468        self.reset_all_sequence_numbers();
1469        release(self, after);
1470
1471        self.events
1472            .push_back(Event::Reconfig(ReconfigEvent::AssociationReset {
1473                local_next_tsn: receiver_next_tsn,
1474                remote_next_tsn: sender_next_tsn,
1475            }));
1476    }
1477}