Skip to main content

rtci_sctp/association/
interleaving.rs

1//! User message interleaving (RFC 8260 section 2): the negotiation of I-DATA, and
2//! I-FORWARD-TSN, which takes the place of FORWARD TSN on an association that uses it.
3
4use super::*;
5use crate::chunk::chunk_i_forward_tsn::{
6    ChunkIForwardTsn, ChunkIForwardTsnStream, I_FORWARD_TSN_STREAM_LENGTH,
7};
8use crate::chunk::chunk_payload_data::{I_DATA_HEADER_SIZE, PAYLOAD_DATA_HEADER_SIZE};
9
10impl Association {
11    /// Whether user message interleaving (RFC 8260) is in use: both sides announced the
12    /// I-DATA chunk. `false` while the association is being set up.
13    pub fn message_interleaving(&self) -> bool {
14        self.use_interleaving
15    }
16
17    /// RFC 8260 2.2.1: user message interleaving is negotiated when both endpoints listed
18    /// the I-DATA chunk.
19    pub(super) fn negotiated_interleaving(&self, params: &HandshakeParams) -> bool {
20        self.interleaving_enabled && params.i_data
21    }
22
23    /// Whether PR-SCTP is used, by what the peer's INIT or INIT ACK said. RFC 3758 3.3.2,
24    /// 3.3.3: both sides announced it, and the peer did not report this side's
25    /// Forward-TSN-Supported parameter as unrecognized. RFC 8260 2.3.1: together with user
26    /// message interleaving, only if both sides listed the I-FORWARD-TSN chunk as well.
27    pub(super) fn negotiated_partial_reliability(&self, params: &HandshakeParams) -> bool {
28        if !self.partial_reliability_enabled || params.forward_tsn_rejected {
29            return false;
30        }
31        if self.negotiated_interleaving(params) {
32            params.i_forward_tsn
33        } else {
34            params.forward_tsn
35        }
36    }
37
38    /// Takes the outcome of the negotiation of user message interleaving.
39    pub(super) fn set_interleaving(&mut self, interleaving: bool) {
40        self.use_interleaving = interleaving;
41        self.pending_queue.set_interleaving(interleaving);
42        for s in self.streams.values_mut() {
43            s.reassembly_queue.interleaved = interleaving;
44        }
45    }
46
47    /// The most user data one DATA chunk carries: an I-DATA chunk's header is four bytes
48    /// longer than a DATA chunk's (RFC 8260 2.1), and the packet is no larger.
49    /// Whether user messages are fragmented (`TransportConfig::with_fragmentation`).
50    pub(crate) fn fragmentation(&self) -> bool {
51        self.transport_config
52            .as_ref()
53            .is_none_or(|config| config.fragmentation())
54    }
55
56    pub(crate) fn fragment_size(&self) -> u32 {
57        if self.use_interleaving {
58            self.max_payload_size
59                .saturating_sub((I_DATA_HEADER_SIZE - PAYLOAD_DATA_HEADER_SIZE) as u32)
60                .max(1)
61        } else {
62            self.max_payload_size
63        }
64    }
65
66    /// The cumulative TSN part of a FORWARD TSN or I-FORWARD-TSN (RFC 3758 3.6): the peer's
67    /// cumulative TSN moves to `new_cumulative_tsn`. Returns where it stood, or `None` when
68    /// the chunk is out of date, in which case a SACK is sent.
69    pub(super) fn forward_cumulative_tsn(&mut self, new_cumulative_tsn: u32) -> Option<u32> {
70        if sna32lte(new_cumulative_tsn, self.peer_last_tsn) {
71            trace!("[{}] sending ack on Forward TSN", self.side);
72            self.ack_state = AckState::Immediate;
73            self.timers.stop(Timer::Ack);
74            self.awake_write_loop();
75            return None;
76        }
77        // Advance peer_last_tsn. Drop only the chunks actually queued below the new point and
78        // jump straight to it: stepping one TSN at a time let a FORWARD-TSN about 2^31 ahead
79        // spin for billions of iterations.
80        while let Some(&front) = self.payload_queue.sorted.front() {
81            if !sna32lte(front, new_cumulative_tsn) || self.payload_queue.pop(front).is_none() {
82                break;
83            }
84        }
85        let prev_peer_last_tsn = self.peer_last_tsn;
86        self.peer_last_tsn = new_cumulative_tsn;
87        Some(prev_peer_last_tsn)
88    }
89
90    /// RFC 8260 2.3.1: an I-FORWARD-TSN chunk.
91    pub(super) fn handle_i_forward_tsn(&mut self, c: &ChunkIForwardTsn) -> Result<Vec<Packet>> {
92        trace!("[{}] I-FwdTSN: {}", self.side, c);
93
94        if !self.use_interleaving || !self.use_forward_tsn {
95            // "If I-FORWARD-TSN support has not been negotiated" the chunk is a violation.
96            warn!(
97                "[{}] I-FORWARD-TSN that was not negotiated: aborting",
98                self.side
99            );
100            self.abort_with(
101                vec![Self::protocol_violation(
102                    "I-FORWARD-TSN was not negotiated (RFC 8260 2.3.1)",
103                )],
104                AssociationError::TransportError,
105            )?;
106            return Ok(vec![]);
107        }
108
109        let Some(prev_peer_last_tsn) = self.forward_cumulative_tsn(c.new_cumulative_tsn) else {
110            return Ok(vec![]);
111        };
112
113        // Each entry says which messages of a stream will not be completed, for its ordered
114        // or its unordered messages; no other stream holds anything the chunk skips. Each
115        // (stream, U flag) is visited once, for the largest Message Identifier the chunk names
116        // for it (RFC 8260 2.3.1: the entry reports "the largest MID" skipped), so a chunk that
117        // repeats one costs no more than one pass over the stream's queue.
118        let forwarded = largest_per_stream(
119            c.streams
120                .iter()
121                .map(|forwarded| ((forwarded.identifier, forwarded.unordered), forwarded.mid)),
122            sna32lt,
123        );
124        for ((identifier, unordered), mid) in forwarded {
125            if let Some(s) = self.streams.get_mut(&identifier) {
126                let bytes_before = s.get_num_bytes_in_reassembly_queue();
127                s.reassembly_queue.forward_mid(unordered, mid);
128                if s.reassembly_queue.is_readable() {
129                    self.events.push_back(Event::Stream(StreamEvent::Readable {
130                        id: s.stream_identifier,
131                    }));
132                }
133                self.reindex_stream(identifier, bytes_before);
134            } else {
135                // As for FORWARD TSN (RFC 3758 3.6): a stream that has no state here yet
136                // starts after the messages skipped on it.
137                self.remember_skipped_on_absent_stream(identifier, unordered, mid);
138            }
139        }
140
141        let mut reset_reply = vec![];
142        self.reset_streams_reached_since(prev_peer_last_tsn, &mut reset_reply)?;
143        let mut reply = self.handle_peer_last_tsn_and_acknowledgement(false)?;
144        reset_reply.append(&mut reply);
145        Ok(reset_reply)
146    }
147
148    /// As `note_abandoned_for_forward_tsn`, for an abandoned I-DATA chunk: the greatest
149    /// Message Identifier skipped is reported per stream for ordered and for unordered
150    /// messages alike (RFC 8260 2.3.1).
151    pub(super) fn note_abandoned_for_i_forward_tsn(&mut self, unordered: bool, si: u16, mid: u32) {
152        self.i_fwd_tsn_stream_map
153            .entry((si, unordered))
154            .and_modify(|cur| {
155                if sna32lt(*cur, mid) {
156                    *cur = mid;
157                }
158            })
159            .or_insert(mid);
160    }
161
162    /// Builds the I-FORWARD-TSN for the abandoned chunks up to the Advanced.Peer.Ack.Point.
163    /// Like the FORWARD TSN (RFC 3758 3.5 C4) it fits one packet: with more entries than
164    /// fit, it covers the TSNs up to the last one whose entries do.
165    pub(super) fn create_i_forward_tsn(&self) -> ChunkIForwardTsn {
166        let room = if self.mtu == 0 {
167            usize::MAX
168        } else {
169            (self.mtu as usize).saturating_sub(COMMON_HEADER_SIZE as usize + CHUNK_HEADER_SIZE + 4)
170                / I_FORWARD_TSN_STREAM_LENGTH
171        };
172        let entry =
173            |(&(identifier, unordered), &mid): (&(u16, bool), &u32)| ChunkIForwardTsnStream {
174                identifier,
175                unordered,
176                mid,
177            };
178        if self.i_fwd_tsn_stream_map.len() <= room {
179            let mut streams: Vec<_> = self.i_fwd_tsn_stream_map.iter().map(entry).collect();
180            streams.sort_by_key(|s| (s.identifier, s.unordered));
181            return ChunkIForwardTsn {
182                new_cumulative_tsn: self.advanced_peer_tsn_ack_point,
183                streams,
184            };
185        }
186
187        let mut map: FxHashMap<(u16, bool), u32> = FxHashMap::default();
188        let mut covered = self.cumulative_tsn_ack_point;
189        let mut tsn = self.cumulative_tsn_ack_point.wrapping_add(1);
190        while sna32lte(tsn, self.advanced_peer_tsn_ack_point) {
191            let Some(c) = self.inflight_queue.get(tsn) else {
192                break;
193            };
194            let key = (c.stream_identifier, c.unordered);
195            if !map.contains_key(&key) && map.len() == room {
196                break;
197            }
198            let mid = c.mid;
199            map.entry(key)
200                .and_modify(|cur| {
201                    if sna32lt(*cur, mid) {
202                        *cur = mid;
203                    }
204                })
205                .or_insert(mid);
206            covered = tsn;
207            tsn = tsn.wrapping_add(1);
208        }
209        let mut streams: Vec<_> = map.iter().map(entry).collect();
210        streams.sort_by_key(|s| (s.identifier, s.unordered));
211        ChunkIForwardTsn {
212            new_cumulative_tsn: covered,
213            streams,
214        }
215    }
216}