Skip to main content

rtci_sctp/chunk/
chunk_payload_data.rs

1use super::{chunk_header::*, chunk_type::*, *};
2
3use bytes::{Buf, BufMut, Bytes, BytesMut};
4use std::fmt;
5use std::num::NonZeroU64;
6use std::time::Instant;
7
8pub(crate) const PAYLOAD_DATA_ENDING_FRAGMENT_BITMASK: u8 = 1;
9pub(crate) const PAYLOAD_DATA_BEGINING_FRAGMENT_BITMASK: u8 = 2;
10pub(crate) const PAYLOAD_DATA_UNORDERED_BITMASK: u8 = 4;
11pub(crate) const PAYLOAD_DATA_IMMEDIATE_SACK: u8 = 8;
12pub(crate) const PAYLOAD_DATA_HEADER_SIZE: usize = 12;
13/// What follows the chunk header of an I-DATA chunk before the user data (RFC 8260 2.1): TSN,
14/// Stream Identifier, Reserved, Message Identifier, and the PPID or the Fragment Sequence
15/// Number.
16pub(crate) const I_DATA_HEADER_SIZE: usize = 16;
17
18/// PayloadProtocolIdentifier is an enum for DataChannel payload types
19/// PayloadProtocolIdentifier enums
20/// <https://www.iana.org/assignments/sctp-parameters/sctp-parameters.xhtml#sctp-parameters-25>
21#[derive(Default, Debug, Copy, Clone, PartialEq)]
22#[repr(C)]
23#[non_exhaustive]
24pub enum PayloadProtocolIdentifier {
25    /// `WebRTC DCEP` (50): a Data Channel Establishment Protocol control message.
26    Dcep = 50,
27    /// `WebRTC String` (51): a non-empty UTF-8 string message.
28    String = 51,
29    /// `WebRTC Binary` (53): a non-empty binary message.
30    Binary = 53,
31    /// `WebRTC String Empty` (56): an empty string message.
32    ///
33    /// Needed because SCTP cannot carry a zero-length payload.
34    StringEmpty = 56,
35    /// `WebRTC Binary Empty` (57): an empty binary message.
36    BinaryEmpty = 57,
37    #[default]
38    /// An identifier this crate does not recognise.
39    Unknown,
40}
41
42impl fmt::Display for PayloadProtocolIdentifier {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        let s = match *self {
45            PayloadProtocolIdentifier::Dcep => "WebRTC DCEP",
46            PayloadProtocolIdentifier::String => "WebRTC String",
47            PayloadProtocolIdentifier::Binary => "WebRTC Binary",
48            PayloadProtocolIdentifier::StringEmpty => "WebRTC String (Empty)",
49            PayloadProtocolIdentifier::BinaryEmpty => "WebRTC Binary (Empty)",
50            _ => "Unknown Payload Protocol Identifier",
51        };
52        write!(f, "{}", s)
53    }
54}
55
56impl PayloadProtocolIdentifier {
57    /// The identifier's number on the wire. `Unknown` is 0, "not specified by the upper
58    /// layer" (RFC 9260 3.3.1); a value without a name is sent with
59    /// [`Stream::write_sctp_with_ppid`](crate::Stream::write_sctp_with_ppid).
60    pub fn number(self) -> u32 {
61        match self {
62            PayloadProtocolIdentifier::Unknown => 0,
63            named => named as u32,
64        }
65    }
66}
67
68impl From<u32> for PayloadProtocolIdentifier {
69    fn from(v: u32) -> PayloadProtocolIdentifier {
70        match v {
71            50 => PayloadProtocolIdentifier::Dcep,
72            51 => PayloadProtocolIdentifier::String,
73            53 => PayloadProtocolIdentifier::Binary,
74            56 => PayloadProtocolIdentifier::StringEmpty,
75            57 => PayloadProtocolIdentifier::BinaryEmpty,
76            _ => PayloadProtocolIdentifier::Unknown,
77        }
78    }
79}
80
81/// Association-local identity, unrelated to TSN, SSN, SID reuse or time.
82#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
83pub(crate) struct MessageId(NonZeroU64);
84
85impl MessageId {
86    /// Encode a zero-based association sequence with a niche for decoded DATA,
87    /// which has no local identity. Option<MessageId> stays one machine word.
88    /// Returns None when the sequence is exhausted.
89    pub(crate) fn new(sequence: u64) -> Option<Self> {
90        NonZeroU64::new(sequence.checked_add(1)?).map(Self)
91    }
92}
93
94/// Sender policy captured once per message and copied to every fragment.
95/// It remains valid after stream reset, SID reuse, or later policy changes.
96#[derive(Debug, Default, Copy, Clone)]
97pub(crate) enum MessageReliability {
98    #[default]
99    Reliable,
100    Rexmit {
101        max_retransmits: u32,
102    },
103    Timed {
104        deadline: Instant,
105    },
106    /// RFC 7496 3.2: abandoned only unsent, to make room in the send buffer for a message of a
107    /// higher priority (a lower value); otherwise sent as a reliable message.
108    Priority {
109        priority: u32,
110    },
111}
112
113impl MessageReliability {
114    /// Whether a lifetime or a retransmission limit can abandon the message once it is sent
115    /// (RFC 3758, RFC 7496 3.1).
116    pub(crate) fn limits_retransmission(self) -> bool {
117        matches!(self, Self::Rexmit { .. } | Self::Timed { .. })
118    }
119
120    pub(crate) fn deadline(self) -> Option<Instant> {
121        match self {
122            Self::Timed { deadline } => Some(deadline),
123            _ => None,
124        }
125    }
126}
127
128/// ChunkPayloadData represents an SCTP Chunk of type DATA
129//
130// 0                   1                   2                   3
131// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
132//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
133//|   Type = 0    | Reserved|U|B|E|    Length                     |
134//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
135//|                              TSN                              |
136//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
137//|      Stream Identifier S      |   Stream Sequence Number n    |
138//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
139//|                  Payload Protocol Identifier                  |
140//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
141//|                                                               |
142//|                 User Data (seq n of Stream S)                 |
143//|                                                               |
144//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
145//
146//
147//An unfragmented user message shall have both the B and E bits set to
148//'1'.  Setting both B and E bits to '0' indicates a middle fragment of
149//a multi-fragment user message, as summarized in the following table:
150//   B E                  Description
151//============================================================
152//|  1 0 | First piece of a fragmented user message          |
153//+----------------------------------------------------------+
154//|  0 0 | Middle piece of a fragmented user message         |
155//+----------------------------------------------------------+
156//|  0 1 | Last piece of a fragmented user message           |
157//+----------------------------------------------------------+
158//|  1 1 | Unfragmented message                              |
159//============================================================
160//|             Table 1: Fragment Description Flags          |
161//============================================================
162#[derive(Debug, Clone)]
163pub struct ChunkPayloadData {
164    pub(crate) unordered: bool,
165    pub(crate) beginning_fragment: bool,
166    pub(crate) ending_fragment: bool,
167    pub(crate) immediate_sack: bool,
168
169    pub(crate) tsn: u32,
170    pub(crate) stream_identifier: u16,
171    pub(crate) stream_sequence_number: u16,
172    pub(crate) payload_type: PayloadProtocolIdentifier,
173    /// The Payload Protocol Identifier as a number, used when `payload_type` has no name for
174    /// it (`Unknown`): RFC 9260 3.3.1 passes any value through unchanged.
175    pub(crate) payload_protocol_id: u32,
176    pub(crate) user_data: Bytes,
177
178    /// This is an I-DATA chunk (RFC 8260 2.1), used when user message interleaving was
179    /// negotiated: it carries `mid` and `fsn` in place of the Stream Sequence Number.
180    pub(crate) i_data: bool,
181    /// The Message Identifier of an I-DATA chunk: counted per stream, separately for ordered
182    /// and unordered messages.
183    pub(crate) mid: u32,
184    /// The Fragment Sequence Number of an I-DATA chunk: the place of this fragment in its
185    /// message, from 0. On the wire only when the B bit is not set.
186    pub(crate) fsn: u32,
187
188    /// Acknowledged by a peer SACK, independently of local payload release.
189    pub(crate) acknowledged: bool,
190    /// Sender: the chunk was acknowledged by a Gap Ack Block, so its bytes no longer count as
191    /// outstanding, and its payload is kept until the Cumulative TSN Ack covers it, in case
192    /// the receiver reneges (RFC 9260 6.2.1 D iii).
193    pub(crate) payload_held: bool,
194    pub(crate) miss_indicator: u32,
195
196    /// Partial-reliability parameters used only by sender.
197    ///
198    /// Reassigned on every (re)transmission, so it is the RTT baseline. It is
199    /// deliberately *not* the timed-reliability baseline: a message may wait in
200    /// the pending queue for a long time before it is first transmitted, and
201    /// `maxPacketLifeTime` has to cover that wait. See `created_at`.
202    pub(crate) since: Option<Instant>,
203    /// When the message this chunk belongs to was handed to the association.
204    ///
205    /// Set once, from the instant the caller passed to `Stream::write*`, and
206    /// never reassigned. This is the baseline for `ReliabilityType::Timed`.
207    pub(crate) created_at: Option<Instant>,
208    /// Sender identity shared by every fragment; absent on decoded peer DATA.
209    pub(crate) message_id: Option<MessageId>,
210    /// Reliability belongs to the queued message, independently of its stream.
211    pub(crate) reliability: MessageReliability,
212    /// Identifies the stream incarnation whose send buffer owns this DATA.
213    pub(crate) stream_generation: u64,
214    /// number of transmission made for this chunk
215    pub(crate) nsent: u32,
216
217    /// This fragment belongs to an atomically abandoned message.
218    pub(crate) abandoned: bool,
219
220    /// Retransmission flag set when T1-RTX timeout occurred and this
221    /// chunk is still in the inflight queue
222    pub(crate) retransmit: bool,
223
224    /// Marked for Fast Retransmit when the one packet of that Fast Retransmit was full (RFC
225    /// 9260 7.2.4 step 5): not eligible for another, and retransmitted when cwnd allows.
226    pub(crate) no_fast_retransmit: bool,
227
228    /// Sender: the message has no Stream Sequence Number or Message Identifier yet. It takes
229    /// them when its first fragment leaves the pending queue, so that an ordered message
230    /// abandoned before that uses up no number and needs no TSN (RFC 3758 4.1 TR3).
231    pub(crate) numbers_pending: bool,
232}
233
234impl Default for ChunkPayloadData {
235    fn default() -> Self {
236        ChunkPayloadData {
237            unordered: false,
238            beginning_fragment: false,
239            ending_fragment: false,
240            immediate_sack: false,
241            tsn: 0,
242            stream_identifier: 0,
243            stream_sequence_number: 0,
244            payload_type: PayloadProtocolIdentifier::default(),
245            payload_protocol_id: 0,
246            user_data: Bytes::new(),
247            i_data: false,
248            mid: 0,
249            fsn: 0,
250            acknowledged: false,
251            payload_held: false,
252            miss_indicator: 0,
253            since: None,
254            created_at: None,
255            message_id: None,
256            reliability: MessageReliability::Reliable,
257            stream_generation: 0,
258            nsent: 0,
259            abandoned: false,
260            retransmit: false,
261            no_fast_retransmit: false,
262            numbers_pending: false,
263        }
264    }
265}
266
267/// makes chunkPayloadData printable
268impl fmt::Display for ChunkPayloadData {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        write!(f, "{}\n{}", self.header(), self.tsn)
271    }
272}
273
274impl Chunk for ChunkPayloadData {
275    fn header(&self) -> ChunkHeader {
276        let mut flags: u8 = 0;
277        if self.ending_fragment {
278            flags = 1;
279        }
280        if self.beginning_fragment {
281            flags |= 1 << 1;
282        }
283        if self.unordered {
284            flags |= 1 << 2;
285        }
286        if self.immediate_sack {
287            flags |= 1 << 3;
288        }
289
290        ChunkHeader {
291            // RFC 8260 2.1: the four Res bits of an I-DATA chunk are sent as 0.
292            typ: if self.i_data {
293                CT_I_DATA
294            } else {
295                CT_PAYLOAD_DATA
296            },
297            flags,
298            value_length: self.value_length() as u16,
299        }
300    }
301
302    fn unmarshal(raw: &Bytes) -> Result<Self> {
303        let header = ChunkHeader::unmarshal(raw)?;
304
305        let i_data = header.typ == CT_I_DATA;
306        if header.typ != CT_PAYLOAD_DATA && !i_data {
307            return Err(Error::ErrChunkTypeNotPayloadData);
308        }
309        let fixed = if i_data {
310            I_DATA_HEADER_SIZE
311        } else {
312            PAYLOAD_DATA_HEADER_SIZE
313        };
314
315        let immediate_sack = (header.flags & PAYLOAD_DATA_IMMEDIATE_SACK) != 0;
316        let unordered = (header.flags & PAYLOAD_DATA_UNORDERED_BITMASK) != 0;
317        let beginning_fragment = (header.flags & PAYLOAD_DATA_BEGINING_FRAGMENT_BITMASK) != 0;
318        let ending_fragment = (header.flags & PAYLOAD_DATA_ENDING_FRAGMENT_BITMASK) != 0;
319
320        if raw.len() < CHUNK_HEADER_SIZE + fixed {
321            return Err(Error::ErrChunkPayloadSmall);
322        }
323
324        if header.value_length() < fixed {
325            return Err(Error::ErrChunkUnmarshalPayloadData);
326        }
327
328        let reader = &mut raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length());
329
330        let tsn = reader.get_u32();
331        let stream_identifier = reader.get_u16();
332        // RFC 8260 2.1: an I-DATA chunk has a Reserved field here, ignored on receipt.
333        let stream_sequence_number = if i_data {
334            reader.advance(2);
335            0
336        } else {
337            reader.get_u16()
338        };
339        let mid = if i_data { reader.get_u32() } else { 0 };
340        // The last field of an I-DATA chunk is the PPID in the first fragment (whose FSN is
341        // 0) and the FSN in the others.
342        let ppid_or_fsn = reader.get_u32();
343        let (payload_protocol_id, fsn) = if i_data && !beginning_fragment {
344            (0, ppid_or_fsn)
345        } else {
346            (ppid_or_fsn, 0)
347        };
348        let payload_type: PayloadProtocolIdentifier = payload_protocol_id.into();
349        let user_data =
350            raw.slice(CHUNK_HEADER_SIZE + fixed..CHUNK_HEADER_SIZE + header.value_length());
351
352        Ok(ChunkPayloadData {
353            unordered,
354            beginning_fragment,
355            ending_fragment,
356            immediate_sack,
357            tsn,
358            stream_identifier,
359            stream_sequence_number,
360            payload_type,
361            payload_protocol_id,
362            user_data,
363            i_data,
364            mid,
365            fsn,
366
367            acknowledged: false,
368            payload_held: false,
369            miss_indicator: 0,
370            since: None,
371            created_at: None,
372            message_id: None,
373            reliability: MessageReliability::Reliable,
374            stream_generation: 0,
375            nsent: 0,
376            abandoned: false,
377            retransmit: false,
378            no_fast_retransmit: false,
379            numbers_pending: false,
380        })
381    }
382
383    fn marshal_to(&self, writer: &mut BytesMut) -> Result<usize> {
384        self.header().marshal_to(writer)?;
385
386        writer.put_u32(self.tsn);
387        writer.put_u16(self.stream_identifier);
388        if self.i_data {
389            // Reserved: 0 on send.
390            writer.put_u16(0);
391            writer.put_u32(self.mid);
392            writer.put_u32(if self.beginning_fragment {
393                self.ppid()
394            } else {
395                self.fsn
396            });
397        } else {
398            writer.put_u16(self.stream_sequence_number);
399            writer.put_u32(self.ppid());
400        }
401        // NB: `extend(Bytes)` iterates the payload one byte at a time (Bytes is
402        // `IntoIterator<Item = u8>`); `extend_from_slice` does a single bulk copy.
403        writer.extend_from_slice(&self.user_data);
404
405        Ok(writer.len())
406    }
407
408    fn check(&self) -> Result<()> {
409        Ok(())
410    }
411
412    fn value_length(&self) -> usize {
413        self.header_size() - CHUNK_HEADER_SIZE + self.user_data.len()
414    }
415
416    fn as_any(&self) -> &dyn Any {
417        self
418    }
419}
420
421impl ChunkPayloadData {
422    /// The Payload Protocol Identifier on the wire: the named value, or the number given for
423    /// one that has no name.
424    pub fn ppid(&self) -> u32 {
425        match self.payload_type {
426            PayloadProtocolIdentifier::Unknown => self.payload_protocol_id,
427            named => named.number(),
428        }
429    }
430
431    /// The size of the chunk without its user data: 16 bytes for DATA, 20 for I-DATA.
432    pub(crate) fn header_size(&self) -> usize {
433        CHUNK_HEADER_SIZE
434            + if self.i_data {
435                I_DATA_HEADER_SIZE
436            } else {
437                PAYLOAD_DATA_HEADER_SIZE
438            }
439    }
440
441    /// The size of the chunk on the wire, padding included.
442    pub(crate) fn wire_size(&self) -> usize {
443        (self.header_size() + self.user_data.len()).next_multiple_of(4)
444    }
445
446    pub(crate) fn abandoned(&self) -> bool {
447        self.abandoned
448    }
449
450    pub(crate) fn is_outstanding(&self) -> bool {
451        !self.acknowledged && !self.abandoned
452    }
453
454    pub(crate) fn is_fast_retransmit_candidate(&self) -> bool {
455        self.is_outstanding()
456            && self.nsent == 1
457            && self.miss_indicator >= 3
458            && !self.no_fast_retransmit
459    }
460
461    /// Record peer progress without changing payload ownership.
462    pub(crate) fn acknowledge(&mut self) -> bool {
463        let newly_acknowledged = !self.acknowledged;
464        self.acknowledged = true;
465        self.retransmit = false;
466        newly_acknowledged
467    }
468
469    /// The receiver reneged on this chunk, which a Gap Ack Block had acknowledged (RFC 9260
470    /// 6.2.1 D iii): it is outstanding again.
471    pub(crate) fn renege(&mut self) {
472        self.acknowledged = false;
473    }
474
475    pub(crate) fn mark_abandoned(&mut self) {
476        self.abandoned = true;
477        self.retransmit = false;
478    }
479}