Skip to main content

srt_runtime/packet/
misc.rs

1//! The CIF-less / single-scalar-CIF control packets: Keep-Alive (§3.2.3),
2//! Congestion Warning (§3.2.6), Shutdown (§3.2.7), ACKACK (§3.2.8), Message
3//! Drop Request (§3.2.9), and Peer Error (§3.2.10).
4
5use super::number::{AckNumber, MESSAGE_NUMBER_MASK, MessageNumber, SeqNo, SocketId, SrtTimestamp};
6use super::{Error, Result, put_be32};
7
8/// Length of a Drop Request CIF and the offset of its Last Packet Sequence
9/// Number (§3.2.5, Figure 15).
10const DROP_REQ_CIF_LEN: usize = 8;
11const DROP_REQ_LAST_SEQ_OFFSET: usize = 4;
12use broadcast_core::error::BufferTooShort;
13
14/// Peer error code for a file-system error — the only value
15/// `draft-sharabayko-srt-01` §3.2.10 currently defines.
16pub const PEER_ERROR_FILE_SYSTEM: u32 = 4000;
17
18/// Keep-Alive control packet (§3.2.3, Figure 12). No CIF.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize))]
21pub struct KeepAlivePacket {
22    /// Timestamp (§3).
23    pub timestamp: SrtTimestamp,
24    /// Destination Socket ID (§3).
25    pub dest_socket_id: SocketId,
26    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
27    /// empty CIF of draft-sharabayko-srt-01.
28    pub libsrt_pad: bool,
29}
30
31/// Congestion Warning control packet (§3.2.6, Figure 15). Reserved for future
32/// use; no CIF.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[cfg_attr(feature = "serde", derive(serde::Serialize))]
35pub struct CongestionWarningPacket {
36    /// Timestamp (§3).
37    pub timestamp: SrtTimestamp,
38    /// Destination Socket ID (§3).
39    pub dest_socket_id: SocketId,
40    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
41    /// empty CIF of draft-sharabayko-srt-01.
42    pub libsrt_pad: bool,
43}
44
45/// Shutdown control packet (§3.2.7, Figure 16). No CIF.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47#[cfg_attr(feature = "serde", derive(serde::Serialize))]
48pub struct ShutdownPacket {
49    /// Timestamp (§3).
50    pub timestamp: SrtTimestamp,
51    /// Destination Socket ID (§3).
52    pub dest_socket_id: SocketId,
53    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
54    /// empty CIF of draft-sharabayko-srt-01.
55    pub libsrt_pad: bool,
56}
57
58/// ACKACK control packet (§3.2.8, Figure 17). No CIF.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60#[cfg_attr(feature = "serde", derive(serde::Serialize))]
61pub struct AckAckPacket {
62    /// Acknowledgement Number of the Full ACK being acknowledged (§3.2.8,
63    /// Figure 17).
64    pub ack_number: AckNumber,
65    /// Timestamp (§3).
66    pub timestamp: SrtTimestamp,
67    /// Destination Socket ID (§3).
68    pub dest_socket_id: SocketId,
69    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
70    /// empty CIF of draft-sharabayko-srt-01.
71    pub libsrt_pad: bool,
72}
73
74/// Message Drop Request control packet (§3.2.9, Figure 18).
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76#[cfg_attr(feature = "serde", derive(serde::Serialize))]
77pub struct DropReqPacket {
78    /// The message number requested to be dropped (`0` if the sender no
79    /// longer has the packets and cannot restore it).
80    ///
81    /// §3.2.9 (Figure 18) calls this field 32 bits wide, but it names a
82    /// message, so it is bounded here by the 26-bit Message Number field of
83    /// §3.1 it refers to — the only values the sender can ever produce.
84    pub message_number: MessageNumber,
85    /// Timestamp (§3).
86    pub timestamp: SrtTimestamp,
87    /// Destination Socket ID (§3).
88    pub dest_socket_id: SocketId,
89    /// First Packet Sequence Number of the range to drop.
90    pub first_seq: SeqNo,
91    /// Last Packet Sequence Number of the range to drop.
92    pub last_seq: SeqNo,
93}
94
95impl DropReqPacket {
96    pub(crate) fn parse_cif(
97        message_number: u32,
98        timestamp: SrtTimestamp,
99        dest_socket_id: SocketId,
100        cif: &[u8],
101    ) -> Result<Self> {
102        if cif.len() != DROP_REQ_CIF_LEN {
103            return Err(Error::BufferTooShort(BufferTooShort::new(
104                DROP_REQ_CIF_LEN,
105                cif.len(),
106                "drop request CIF",
107            )));
108        }
109        let message_number = MessageNumber::try_new(message_number).map_err(|_| {
110            Error::FieldOverflow(broadcast_core::error::FieldOverflow::new(
111                "Message Number",
112                u64::from(message_number),
113                u64::from(MESSAGE_NUMBER_MASK),
114            ))
115        })?;
116        Ok(DropReqPacket {
117            message_number,
118            timestamp,
119            dest_socket_id,
120            first_seq: SeqNo::from_wire_masked(
121                broadcast_core::wire::Reader::at(cif, 0).u32("first_seq")?,
122            ),
123            last_seq: SeqNo::from_wire_masked(
124                broadcast_core::wire::Reader::at(cif, DROP_REQ_LAST_SEQ_OFFSET).u32("last_seq")?,
125            ),
126        })
127    }
128
129    pub(crate) fn cif_len(&self) -> usize {
130        DROP_REQ_CIF_LEN
131    }
132
133    pub(crate) fn write_cif(&self, buf: &mut [u8]) -> Result<()> {
134        put_be32(buf, 0, self.first_seq.value());
135        put_be32(buf, DROP_REQ_LAST_SEQ_OFFSET, self.last_seq.value());
136        Ok(())
137    }
138}
139
140/// Peer Error control packet (§3.2.10, Figure 19). No CIF.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
142#[cfg_attr(feature = "serde", derive(serde::Serialize))]
143pub struct PeerErrorPacket {
144    /// Peer error code (see [`PEER_ERROR_FILE_SYSTEM`]).
145    pub error_code: u32,
146    /// Timestamp (§3).
147    pub timestamp: SrtTimestamp,
148    /// Destination Socket ID (§3).
149    pub dest_socket_id: SocketId,
150    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
151    /// empty CIF of draft-sharabayko-srt-01.
152    pub libsrt_pad: bool,
153}
154
155#[cfg(test)]
156mod tests {
157    use alloc::vec::Vec;
158
159    use super::super::control::ControlPacket;
160    use super::super::data::MESSAGE_NUMBER_MASK as MESSAGE_NUMBER_MAX;
161    use super::*;
162
163    fn msg(n: u32) -> MessageNumber {
164        MessageNumber::try_new(n).expect("fits 26 bits")
165    }
166
167    fn sn(n: u32) -> SeqNo {
168        SeqNo::try_new(n).expect("fits 31 bits")
169    }
170
171    #[test]
172    fn drop_req_round_trips() {
173        let d = DropReqPacket {
174            message_number: msg(7),
175            timestamp: SrtTimestamp::from_wire(100),
176            dest_socket_id: SocketId::from_wire(200),
177            first_seq: sn(10),
178            last_seq: sn(20),
179        };
180        let pkt = ControlPacket::DropReq(d);
181        let mut buf = [0u8; 24];
182        let n = pkt.serialize_into(&mut buf).unwrap();
183        assert_eq!(n, 24);
184        assert_eq!(&buf[4..8], &7u32.to_be_bytes()); // message number in word1
185        assert_eq!(&buf[16..20], &10u32.to_be_bytes());
186        assert_eq!(&buf[20..24], &20u32.to_be_bytes());
187        let parsed = ControlPacket::parse(&buf).unwrap();
188        assert_eq!(parsed, pkt);
189    }
190
191    /// §3.2.9's fields are 32-bit words on the wire, but the two sequence
192    /// numbers share the data packet's 31-bit space (§3.1) and the Message
193    /// Number is the 26-bit one: a peer's top-bit-set values are accepted
194    /// (masked for the sequence numbers, since the typed `SeqNo` cannot hold
195    /// them) and serialize back to the same masked bytes — never a
196    /// serialize-time refusal of a packet parse accepted.
197    #[test]
198    fn drop_req_wide_wire_numbers_still_serialize() {
199        let mut buf = alloc::vec![0u8; 24];
200        ControlPacket::DropReq(DropReqPacket {
201            message_number: msg(7),
202            timestamp: SrtTimestamp::from_wire(100),
203            dest_socket_id: SocketId::from_wire(200),
204            first_seq: sn(10),
205            last_seq: sn(20),
206        })
207        .serialize_into(&mut buf)
208        .unwrap();
209        buf[16..20].copy_from_slice(&0xFFFF_FFFFu32.to_be_bytes());
210        buf[20..24].copy_from_slice(&0xFFFF_FFFEu32.to_be_bytes());
211        let parsed = ControlPacket::parse(&buf).unwrap();
212        let ControlPacket::DropReq(d) = parsed else {
213            panic!("a drop request");
214        };
215        assert_eq!(d.first_seq, SeqNo::MAX);
216        assert_eq!(d.last_seq, sn(0x7FFF_FFFE));
217        let mut out = alloc::vec![0u8; parsed.serialized_len()];
218        parsed.serialize_into(&mut out).unwrap();
219        assert_eq!(&out[0..16], &buf[0..16]);
220        assert_eq!(&out[16..20], &SeqNo::MAX.value().to_be_bytes());
221        assert_eq!(&out[20..24], &0x7FFF_FFFEu32.to_be_bytes());
222        assert_eq!(ControlPacket::parse(&out).unwrap(), parsed);
223    }
224
225    /// A DROPREQ whose Message Number word is wider than the 26-bit Message
226    /// Number it names is rejected at parse, so `parse` never yields a packet
227    /// `serialize` would refuse (#2766's bound now sits at the parse edge).
228    #[test]
229    fn drop_req_rejects_an_over_wide_message_number_at_parse() {
230        let mut buf = alloc::vec![0u8; 24];
231        ControlPacket::DropReq(DropReqPacket {
232            message_number: msg(MESSAGE_NUMBER_MAX),
233            timestamp: SrtTimestamp::from_wire(100),
234            dest_socket_id: SocketId::from_wire(200),
235            first_seq: sn(10),
236            last_seq: sn(20),
237        })
238        .serialize_into(&mut buf)
239        .unwrap();
240        assert!(ControlPacket::parse(&buf).is_ok());
241
242        for wide in [MESSAGE_NUMBER_MAX + 1, 0x8E8E_8E8E, u32::MAX] {
243            buf[4..8].copy_from_slice(&wide.to_be_bytes());
244            assert_eq!(
245                ControlPacket::parse(&buf).unwrap_err(),
246                Error::FieldOverflow(broadcast_core::error::FieldOverflow::new(
247                    "Message Number",
248                    u64::from(wide),
249                    u64::from(MESSAGE_NUMBER_MAX)
250                ))
251            );
252        }
253    }
254
255    /// An ACKACK echoes a Full ACK's Acknowledgement Number verbatim, and
256    /// that field is a whole 32-bit word (§3.2.8, Figure 17) — a value above
257    /// the 31-bit sequence space round-trips.
258    #[test]
259    fn ackack_carries_every_32_bit_ack_number() {
260        for ack_number in [0, 1, 0x8000_0000, 0x8E8E_8E8E, u32::MAX] {
261            let pkt = ControlPacket::AckAck(AckAckPacket {
262                ack_number: AckNumber::from_wire(ack_number),
263                timestamp: SrtTimestamp::from_wire(7),
264                dest_socket_id: SocketId::from_wire(8),
265                libsrt_pad: false,
266            });
267            let mut buf = alloc::vec![0u8; pkt.serialized_len()];
268            pkt.serialize_into(&mut buf).unwrap();
269            assert_eq!(&buf[4..8], &ack_number.to_be_bytes());
270            assert_eq!(ControlPacket::parse(&buf).unwrap(), pkt);
271        }
272    }
273
274    #[test]
275    fn keepalive_congestion_shutdown_ackack_peererror_round_trip() {
276        let cases: Vec<ControlPacket> = alloc::vec![
277            ControlPacket::KeepAlive(KeepAlivePacket {
278                timestamp: SrtTimestamp::from_wire(1),
279                dest_socket_id: SocketId::from_wire(2),
280                libsrt_pad: true,
281            }),
282            ControlPacket::CongestionWarning(CongestionWarningPacket {
283                timestamp: SrtTimestamp::from_wire(3),
284                dest_socket_id: SocketId::from_wire(4),
285                libsrt_pad: true,
286            }),
287            ControlPacket::Shutdown(ShutdownPacket {
288                timestamp: SrtTimestamp::from_wire(5),
289                dest_socket_id: SocketId::from_wire(6),
290                libsrt_pad: true,
291            }),
292            ControlPacket::AckAck(AckAckPacket {
293                ack_number: AckNumber::from_wire(9),
294                timestamp: SrtTimestamp::from_wire(7),
295                dest_socket_id: SocketId::from_wire(8),
296                libsrt_pad: true,
297            }),
298            ControlPacket::PeerError(PeerErrorPacket {
299                error_code: PEER_ERROR_FILE_SYSTEM,
300                timestamp: SrtTimestamp::from_wire(11),
301                dest_socket_id: SocketId::from_wire(12),
302                libsrt_pad: true,
303            }),
304        ];
305        for pkt in cases {
306            // 20 bytes when libsrt_pad is true: serializes with the 4-byte
307            // zero pad (see `control::LIBSRT_CIF_PAD_LEN`).
308            let mut buf = [0u8; 20];
309            let n = pkt.serialize_into(&mut buf).unwrap();
310            assert_eq!(n, 20);
311            assert_eq!(&buf[16..20], &[0, 0, 0, 0]);
312            let parsed = ControlPacket::parse(&buf).unwrap();
313            assert_eq!(parsed, pkt);
314        }
315    }
316
317    /// A peer (e.g. real libsrt — see `tests/it/libsrt_fixtures.rs`) may also
318    /// send these types with the pure-spec empty CIF instead of the pad.
319    /// Both 16-byte (no-pad) and 20-byte (with-pad) wire shapes parse correctly.
320    #[test]
321    fn keepalive_congestion_shutdown_ackack_peererror_accept_empty_cif() {
322        let cases: Vec<ControlPacket> = alloc::vec![
323            ControlPacket::KeepAlive(KeepAlivePacket {
324                timestamp: SrtTimestamp::from_wire(1),
325                dest_socket_id: SocketId::from_wire(2),
326                libsrt_pad: false,
327            }),
328            ControlPacket::CongestionWarning(CongestionWarningPacket {
329                timestamp: SrtTimestamp::from_wire(3),
330                dest_socket_id: SocketId::from_wire(4),
331                libsrt_pad: false,
332            }),
333            ControlPacket::Shutdown(ShutdownPacket {
334                timestamp: SrtTimestamp::from_wire(5),
335                dest_socket_id: SocketId::from_wire(6),
336                libsrt_pad: false,
337            }),
338            ControlPacket::AckAck(AckAckPacket {
339                ack_number: AckNumber::from_wire(9),
340                timestamp: SrtTimestamp::from_wire(7),
341                dest_socket_id: SocketId::from_wire(8),
342                libsrt_pad: false,
343            }),
344            ControlPacket::PeerError(PeerErrorPacket {
345                error_code: PEER_ERROR_FILE_SYSTEM,
346                timestamp: SrtTimestamp::from_wire(11),
347                dest_socket_id: SocketId::from_wire(12),
348                libsrt_pad: false,
349            }),
350        ];
351        for pkt in cases {
352            // Serialize with libsrt_pad: false -> 16 bytes
353            let mut buf = [0u8; 16];
354            let n = pkt.serialized_len();
355            assert_eq!(n, 16, "16-byte packets with libsrt_pad: false");
356            pkt.serialize_into(&mut buf).unwrap();
357
358            // Parse the 16-byte form back
359            let parsed = ControlPacket::parse(&buf).unwrap();
360            assert_eq!(parsed, pkt);
361        }
362    }
363
364    /// A 16-byte (pure-spec empty CIF) KEEPALIVE packet parses and
365    /// round-trips byte-identically.
366    #[test]
367    fn sixteen_byte_keepalive_round_trip_byte_identical() {
368        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
369            timestamp: SrtTimestamp::from_wire(0x1234),
370            dest_socket_id: SocketId::from_wire(0x5678),
371            libsrt_pad: false,
372        });
373        let mut buf = [0u8; 16];
374        let n = pkt.serialize_into(&mut buf).unwrap();
375        assert_eq!(n, 16, "16-byte packet with libsrt_pad: false");
376
377        let parsed = ControlPacket::parse(&buf).unwrap();
378        assert_eq!(parsed, pkt);
379
380        let mut reserialized = [0u8; 16];
381        let n = parsed.serialize_into(&mut reserialized).unwrap();
382        assert_eq!(n, 16);
383        assert_eq!(&reserialized[..], &buf[..], "round-trip is byte-identical");
384    }
385
386    /// A 20-byte (libsrt's 4-byte zero pad) KEEPALIVE packet parses and
387    /// round-trips byte-identically.
388    #[test]
389    fn twenty_byte_keepalive_round_trip_byte_identical() {
390        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
391            timestamp: SrtTimestamp::from_wire(0x1234),
392            dest_socket_id: SocketId::from_wire(0x5678),
393            libsrt_pad: true,
394        });
395        let mut buf = [0u8; 20];
396        let n = pkt.serialize_into(&mut buf).unwrap();
397        assert_eq!(n, 20, "20-byte packet with libsrt_pad: true");
398        assert_eq!(&buf[16..20], &[0, 0, 0, 0], "CIF is 4-byte zero pad");
399
400        let parsed = ControlPacket::parse(&buf).unwrap();
401        assert_eq!(parsed, pkt);
402
403        let mut reserialized = [0u8; 20];
404        let n = parsed.serialize_into(&mut reserialized).unwrap();
405        assert_eq!(n, 20);
406        assert_eq!(&reserialized[..], &buf[..], "round-trip is byte-identical");
407    }
408
409    #[test]
410    fn keepalive_rejects_trailing_bytes() {
411        // Neither 0 (pure spec) nor 4 (libsrt's pad, §control::LIBSRT_CIF_PAD_LEN):
412        // 1 stray byte must still be rejected.
413        let mut buf = [0u8; 17];
414        buf[0] = 0x80; // F=1
415        buf[1] = 0x01; // control type = 1 (KEEPALIVE)
416        assert!(matches!(
417            ControlPacket::parse(&buf),
418            Err(Error::UnexpectedTrailingBytes { .. })
419        ));
420    }
421
422    #[test]
423    fn keepalive_rejects_nonzero_pad() {
424        let mut buf = [0u8; 20];
425        buf[0] = 0x80; // F=1
426        buf[1] = 0x01; // control type = 1 (KEEPALIVE)
427        buf[19] = 0x01; // non-zero byte in the 4-byte pad
428        assert!(matches!(
429            ControlPacket::parse(&buf),
430            Err(Error::ReservedBits(_))
431        ));
432    }
433}