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