Skip to main content

rtmp_runtime/
handshake.rs

1//! RTMP handshake — C0/C1/C2 and S0/S1/S2 (Adobe RTMP 1.0 §5.2).
2//!
3//! See `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` §2 (Handshake) for the wire layout:
4//! C0/S0 (§5.2.2), C1/S1 (§5.2.3), C2/S2 (§5.2.4), and the handshake sequence
5//! diagram (§5.2.5).
6//!
7//! # Scope: simple handshake only
8//!
9//! This module implements only the **simple** (plain) handshake described by
10//! §5.2 itself: C0/C1/C2 and S0/S1/S2 carry no HMAC-SHA256 digest and no
11//! "complex handshake" key-exchange scheme (that scheme is an Adobe Flash
12//! Media Server addition, not part of the RTMP 1.0 spec text transcribed in
13//! `private/specs-verified/rtmp/rtmp-runtime/rtmp.md`). This is sufficient for interoperating with real-world
14//! publishers such as ffmpeg and OBS Studio, which fall back to (or always
15//! use) the simple handshake for `rtmp://` publish. Complex-handshake support
16//! is out of scope for this crate.
17//!
18//! # No wall clock in the sans-IO core
19//!
20//! This crate has no socket or clock of its own (see the crate-root sans-IO
21//! contract doc). `time` in S1 and `time2` in S2 are therefore not read from
22//! a real clock: [`Handshake::new`] uses `0` for both and a fixed,
23//! non-cryptographic filler pattern for S1's random bytes (see
24//! [`default_random_fill`]); [`Handshake::with_time_and_random`] lets a
25//! caller supply real values instead. Per §5.2.3/§5.2.4 neither field is
26//! required to be meaningful (the spec itself calls the bandwidth estimate
27//! they enable "unlikely to be useful"), and no `rand`-style dependency is
28//! pulled in to generate them.
29
30use broadcast_common::len::need_in;
31use broadcast_common::{Parse, Serialize};
32
33use crate::RtmpError;
34use alloc::vec;
35use alloc::vec::Vec;
36
37type Result<T> = core::result::Result<T, RtmpError>;
38
39/// RTMP version this handshake implements/advertises (§5.2.2): `3`.
40pub const RTMP_VERSION: u8 = 3;
41
42/// Wire length in bytes of C1/S1 and C2/S2 (§5.2.3/§5.2.4): `1536`.
43pub const HANDSHAKE_PACKET_LEN: usize = 1536;
44
45/// Wire length in bytes of C0/S0 (§5.2.2): `1`.
46const VERSION_LEN: usize = 1;
47/// Byte width of the `time`/`zero`/`time2` fields.
48const FIELD_LEN: usize = 4;
49/// Byte width of the `random bytes`/`random echo` field:
50/// `HANDSHAKE_PACKET_LEN` minus two 4-byte fields.
51const RANDOM_LEN: usize = HANDSHAKE_PACKET_LEN - FIELD_LEN - FIELD_LEN;
52
53/// C0 (client→server) or S0 (server→client): the 1-byte RTMP version
54/// (§5.2.2).
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct Version(pub u8);
57
58impl<'a> Parse<'a> for Version {
59    type Error = RtmpError;
60
61    fn parse(bytes: &'a [u8]) -> Result<Self> {
62        need_in(bytes, VERSION_LEN, "C0/S0 version")?;
63        Ok(Version(bytes[0]))
64    }
65}
66
67impl Serialize for Version {
68    type Error = RtmpError;
69
70    fn serialized_len(&self) -> usize {
71        VERSION_LEN
72    }
73
74    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
75        need_in(buf, VERSION_LEN, "C0/S0 version output")?;
76        buf[0] = self.0;
77        Ok(VERSION_LEN)
78    }
79}
80
81impl Version {
82    /// The C0/S0 byte, built without a fallible length check.
83    #[must_use]
84    pub const fn to_bytes(&self) -> [u8; VERSION_LEN] {
85        [self.0]
86    }
87}
88
89/// C1 (client→server) or S1 (server→client): the 1536-byte time/zero/random
90/// handshake packet (§5.2.3).
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct HandshakePacket {
93    /// `time` — timestamp epoch for this endpoint's future chunks. May be 0
94    /// or arbitrary (§5.2.3).
95    pub time: u32,
96    /// `zero` — MUST be all zeros on the wire (§5.2.3).
97    pub zero: u32,
98    /// `random bytes` — arbitrary data distinguishing this handshake from
99    /// the peer's; no cryptographic randomness required (§5.2.3).
100    pub random: [u8; RANDOM_LEN],
101}
102
103impl<'a> Parse<'a> for HandshakePacket {
104    type Error = RtmpError;
105
106    fn parse(bytes: &'a [u8]) -> Result<Self> {
107        need_in(bytes, HANDSHAKE_PACKET_LEN, "C1/S1")?;
108        let time = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
109        let zero = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
110        let mut random = [0u8; RANDOM_LEN];
111        random.copy_from_slice(&bytes[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN]);
112        Ok(HandshakePacket { time, zero, random })
113    }
114}
115
116impl Serialize for HandshakePacket {
117    type Error = RtmpError;
118
119    fn serialized_len(&self) -> usize {
120        HANDSHAKE_PACKET_LEN
121    }
122
123    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
124        need_in(buf, HANDSHAKE_PACKET_LEN, "C1/S1 output")?;
125        buf[0..FIELD_LEN].copy_from_slice(&self.time.to_be_bytes());
126        buf[FIELD_LEN..2 * FIELD_LEN].copy_from_slice(&self.zero.to_be_bytes());
127        buf[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN].copy_from_slice(&self.random);
128        Ok(HANDSHAKE_PACKET_LEN)
129    }
130}
131
132impl HandshakePacket {
133    /// The 1536-byte C1/S1 packet, built without a fallible length check.
134    #[must_use]
135    pub fn to_bytes(&self) -> [u8; HANDSHAKE_PACKET_LEN] {
136        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
137        buf[0..FIELD_LEN].copy_from_slice(&self.time.to_be_bytes());
138        buf[FIELD_LEN..2 * FIELD_LEN].copy_from_slice(&self.zero.to_be_bytes());
139        buf[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN].copy_from_slice(&self.random);
140        buf
141    }
142}
143
144/// C2 (client→server) or S2 (server→client): the 1536-byte near-echo packet
145/// (§5.2.4).
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub struct EchoPacket {
148    /// `time` — MUST equal the peer's S1 `time` (for C2) or C1 `time` (for
149    /// S2) (§5.2.4).
150    pub time: u32,
151    /// `time2` — MUST be the timestamp at which the peer's previous packet
152    /// (S1 or C1) was read (§5.2.4).
153    pub time2: u32,
154    /// `random echo` — MUST equal the peer's S1/C1 `random bytes`, verbatim
155    /// (§5.2.4).
156    pub random_echo: [u8; RANDOM_LEN],
157}
158
159impl<'a> Parse<'a> for EchoPacket {
160    type Error = RtmpError;
161
162    fn parse(bytes: &'a [u8]) -> Result<Self> {
163        need_in(bytes, HANDSHAKE_PACKET_LEN, "C2/S2")?;
164        let time = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
165        let time2 = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
166        let mut random_echo = [0u8; RANDOM_LEN];
167        random_echo.copy_from_slice(&bytes[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN]);
168        Ok(EchoPacket {
169            time,
170            time2,
171            random_echo,
172        })
173    }
174}
175
176impl Serialize for EchoPacket {
177    type Error = RtmpError;
178
179    fn serialized_len(&self) -> usize {
180        HANDSHAKE_PACKET_LEN
181    }
182
183    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
184        need_in(buf, HANDSHAKE_PACKET_LEN, "C2/S2 output")?;
185        buf[0..FIELD_LEN].copy_from_slice(&self.time.to_be_bytes());
186        buf[FIELD_LEN..2 * FIELD_LEN].copy_from_slice(&self.time2.to_be_bytes());
187        buf[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN].copy_from_slice(&self.random_echo);
188        Ok(HANDSHAKE_PACKET_LEN)
189    }
190}
191
192/// A fixed, non-cryptographic 1528-byte fill pattern for a server's own S1
193/// `random bytes` when the caller has no specific bytes to supply. Per
194/// §5.2.3 the field only needs to "distinguish this handshake from the
195/// peer's" — no cryptographic randomness is required, so a deterministic
196/// repeating byte pattern is spec-conformant and keeps this crate free of a
197/// `rand`-style dependency.
198#[must_use]
199pub fn default_random_fill() -> [u8; RANDOM_LEN] {
200    let mut random = [0u8; RANDOM_LEN];
201    for (i, b) in random.iter_mut().enumerate() {
202        *b = (i & 0xFF) as u8;
203    }
204    random
205}
206
207/// Server-side handshake driver state (§5.2.5's Uninitialized → Version Sent
208/// → Ack Sent → Handshake Done, collapsed to the three states this driver
209/// actually distinguishes).
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
211enum HandshakeState {
212    /// Awaiting C0+C1 from the client (spec's "Uninitialized").
213    WaitC0C1,
214    /// S0+S1+S2 sent; awaiting C2 from the client (spec's "Version
215    /// Sent"/"Ack Sent" collapsed into one wait).
216    WaitC2,
217    /// C2 received; handshake complete (spec's "Handshake Done").
218    Done,
219}
220
221/// Sans-IO server-side RTMP handshake driver (§5.2, simple handshake only —
222/// see the module doc).
223///
224/// Drive it by feeding inbound bytes to [`read`](Self::read); it returns any
225/// outbound reply bytes, how many input bytes it consumed, and whether the
226/// handshake is now complete. It never touches a socket or clock itself.
227#[derive(Debug)]
228pub struct Handshake {
229    state: HandshakeState,
230    /// Written into our own S1 `time` field.
231    local_time: u32,
232    /// Written into our own S1 `random bytes` field.
233    local_random: [u8; RANDOM_LEN],
234    /// Written into our own S2 `time2` field (see the module doc: this core
235    /// has no wall clock, so this is caller-supplied or `0`, not a real
236    /// read-timestamp).
237    read_time: u32,
238}
239
240impl Default for Handshake {
241    fn default() -> Self {
242        Self::new()
243    }
244}
245
246impl Handshake {
247    /// A new server-side handshake in the initial (`WaitC0C1`) state, using
248    /// `0` for S1's `time`/S2's `time2` and [`default_random_fill`] for S1's
249    /// random bytes. Use [`with_time_and_random`](Self::with_time_and_random)
250    /// to supply real values instead.
251    #[must_use]
252    pub fn new() -> Self {
253        Self::with_time_and_random(0, default_random_fill(), 0)
254    }
255
256    /// A new server-side handshake with caller-supplied S1 `time`, S1
257    /// `random bytes`, and S2 `time2` values.
258    #[must_use]
259    pub fn with_time_and_random(
260        local_time: u32,
261        local_random: [u8; RANDOM_LEN],
262        read_time: u32,
263    ) -> Self {
264        Self {
265            state: HandshakeState::WaitC0C1,
266            local_time,
267            local_random,
268            read_time,
269        }
270    }
271
272    /// True once C2 has been received and the handshake is complete.
273    #[must_use]
274    pub fn is_done(&self) -> bool {
275        self.state == HandshakeState::Done
276    }
277
278    /// Feed inbound bytes to the handshake driver.
279    ///
280    /// - In `WaitC0C1`, requires a full C0(1)+C1(1536) = 1537 bytes at the
281    ///   front of `input`; on success returns the S0+S1+S2 reply
282    ///   (1+1536+1536 = 3073 bytes), consumes 1537 input bytes, and advances
283    ///   to `WaitC2`.
284    /// - In `WaitC2`, requires a full C2(1536) bytes; on success returns no
285    ///   reply bytes, consumes 1536 input bytes, and advances to `Done`.
286    /// - In `Done`, is a no-op: returns no reply, consumes 0 bytes, and
287    ///   reports done.
288    ///
289    /// Returns `(reply_bytes, consumed, done)`.
290    ///
291    /// # Errors
292    /// [`RtmpError::BufferTooShort`] if `input` does not yet hold a full
293    /// C0+C1 (`WaitC0C1`) or C2 (`WaitC2`). This driver does not buffer
294    /// partial input itself — callers should re-invoke `read` once more
295    /// bytes have arrived.
296    pub fn read(&mut self, input: &[u8]) -> Result<(Vec<u8>, usize, bool)> {
297        match self.state {
298            HandshakeState::WaitC0C1 => {
299                let need = VERSION_LEN + HANDSHAKE_PACKET_LEN;
300                need_in(input, need, "C0+C1")?;
301                let c0 = Version::parse(&input[..VERSION_LEN])?;
302                // #1108/RTMP-W11: the C0 version byte was parsed and
303                // discarded, so an RTMPE client (C0 = 6) or garbage was
304                // accepted, only to fail later as a confusing chunk-parse
305                // error instead of a clear one here.
306                if c0.0 != RTMP_VERSION {
307                    return Err(RtmpError::HandshakeVersion {
308                        value: c0.0,
309                        expected: RTMP_VERSION,
310                    });
311                }
312                let c1 = HandshakePacket::parse(&input[VERSION_LEN..need])?;
313
314                let s0 = Version(RTMP_VERSION);
315                let s1 = HandshakePacket {
316                    time: self.local_time,
317                    zero: 0,
318                    random: self.local_random,
319                };
320                let s2 = EchoPacket {
321                    time: c1.time,
322                    time2: self.read_time,
323                    random_echo: c1.random,
324                };
325
326                let reply_len = VERSION_LEN + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN;
327                let mut reply = vec![0u8; reply_len];
328                s0.serialize_into(&mut reply[..VERSION_LEN])?;
329                s1.serialize_into(&mut reply[VERSION_LEN..VERSION_LEN + HANDSHAKE_PACKET_LEN])?;
330                s2.serialize_into(&mut reply[VERSION_LEN + HANDSHAKE_PACKET_LEN..])?;
331
332                self.state = HandshakeState::WaitC2;
333                Ok((reply, need, false))
334            }
335            HandshakeState::WaitC2 => {
336                need_in(input, HANDSHAKE_PACKET_LEN, "C2")?;
337                let _c2 = EchoPacket::parse(&input[..HANDSHAKE_PACKET_LEN])?;
338                self.state = HandshakeState::Done;
339                Ok((Vec::new(), HANDSHAKE_PACKET_LEN, true))
340            }
341            HandshakeState::Done => Ok((Vec::new(), 0, true)),
342        }
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use broadcast_common::error::BufferTooShort;
349
350    use super::*;
351
352    fn patterned_random(seed: u8) -> [u8; RANDOM_LEN] {
353        let mut r = [0u8; RANDOM_LEN];
354        for (i, b) in r.iter_mut().enumerate() {
355            *b = seed.wrapping_add((i & 0xFF) as u8);
356        }
357        r
358    }
359
360    // ── C0/S0 round-trip ─────────────────────────────────────────────────
361
362    #[test]
363    fn version_round_trip_build_serialize_parse() {
364        let v = Version(RTMP_VERSION);
365        let mut buf = [0u8; VERSION_LEN];
366        let n = v.serialize_into(&mut buf).unwrap();
367        assert_eq!(n, VERSION_LEN);
368        let parsed = Version::parse(&buf).unwrap();
369        assert_eq!(parsed, v);
370    }
371
372    #[test]
373    fn version_round_trip_parse_serialize_byte_identical() {
374        let bytes = [3u8];
375        let v = Version::parse(&bytes).unwrap();
376        let mut buf = [0u8; VERSION_LEN];
377        v.serialize_into(&mut buf).unwrap();
378        assert_eq!(buf, bytes);
379    }
380
381    #[test]
382    fn version_to_bytes_matches_the_serializer() {
383        for byte in [RTMP_VERSION, 0, 0xFF] {
384            let v = Version(byte);
385            let mut buf = [0u8; VERSION_LEN];
386            v.serialize_into(&mut buf).unwrap();
387            assert_eq!(v.to_bytes(), buf);
388        }
389    }
390
391    #[test]
392    fn version_short_input_is_buffer_too_short() {
393        let bytes: [u8; 0] = [];
394        assert!(matches!(
395            Version::parse(&bytes),
396            Err(RtmpError::BufferTooShort(BufferTooShort {
397                need: VERSION_LEN,
398                have: 0,
399                ..
400            }))
401        ));
402    }
403
404    // ── C1/S1 round-trip ─────────────────────────────────────────────────
405
406    #[test]
407    fn handshake_packet_round_trip_build_serialize_parse() {
408        let hp = HandshakePacket {
409            time: 0x1122_3344,
410            zero: 0,
411            random: patterned_random(0xAB),
412        };
413        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
414        let n = hp.serialize_into(&mut buf).unwrap();
415        assert_eq!(n, HANDSHAKE_PACKET_LEN);
416        let parsed = HandshakePacket::parse(&buf).unwrap();
417        assert_eq!(parsed, hp);
418    }
419
420    #[test]
421    fn handshake_packet_round_trip_parse_serialize_byte_identical() {
422        let mut bytes = [0u8; HANDSHAKE_PACKET_LEN];
423        bytes[0..4].copy_from_slice(&0xDEAD_BEEFu32.to_be_bytes());
424        // bytes[4..8] left as the required-zero `zero` field.
425        for (i, b) in bytes[8..].iter_mut().enumerate() {
426            *b = (i as u8).wrapping_mul(7);
427        }
428        let hp = HandshakePacket::parse(&bytes).unwrap();
429        assert_eq!(hp.time, 0xDEAD_BEEF);
430        assert_eq!(hp.zero, 0);
431        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
432        hp.serialize_into(&mut buf).unwrap();
433        assert_eq!(buf, bytes, "C1/S1 byte-identical round trip");
434    }
435
436    #[test]
437    fn handshake_packet_to_bytes_matches_the_serializer() {
438        let hp = HandshakePacket {
439            time: 0x1122_3344,
440            zero: 0,
441            random: patterned_random(0x5C),
442        };
443        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
444        hp.serialize_into(&mut buf).unwrap();
445        assert_eq!(hp.to_bytes(), buf);
446    }
447
448    #[test]
449    fn handshake_packet_short_input_is_buffer_too_short() {
450        let bytes = [0u8; HANDSHAKE_PACKET_LEN - 1];
451        assert!(matches!(
452            HandshakePacket::parse(&bytes),
453            Err(RtmpError::BufferTooShort(BufferTooShort {
454                need: HANDSHAKE_PACKET_LEN,
455                have,
456                ..
457            })) if have == HANDSHAKE_PACKET_LEN - 1
458        ));
459    }
460
461    // ── C2/S2 round-trip ─────────────────────────────────────────────────
462
463    #[test]
464    fn echo_packet_round_trip_build_serialize_parse() {
465        let ep = EchoPacket {
466            time: 0x0102_0304,
467            time2: 0x0506_0708,
468            random_echo: patterned_random(0x5A),
469        };
470        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
471        let n = ep.serialize_into(&mut buf).unwrap();
472        assert_eq!(n, HANDSHAKE_PACKET_LEN);
473        let parsed = EchoPacket::parse(&buf).unwrap();
474        assert_eq!(parsed, ep);
475    }
476
477    #[test]
478    fn echo_packet_round_trip_parse_serialize_byte_identical() {
479        let mut bytes = [0u8; HANDSHAKE_PACKET_LEN];
480        bytes[0..4].copy_from_slice(&0x1111_2222u32.to_be_bytes());
481        bytes[4..8].copy_from_slice(&0x3333_4444u32.to_be_bytes());
482        for (i, b) in bytes[8..].iter_mut().enumerate() {
483            *b = (i as u8) ^ 0x5A;
484        }
485        let ep = EchoPacket::parse(&bytes).unwrap();
486        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
487        ep.serialize_into(&mut buf).unwrap();
488        assert_eq!(buf, bytes, "C2/S2 byte-identical round trip");
489    }
490
491    #[test]
492    fn echo_packet_short_input_is_buffer_too_short() {
493        let bytes = [0u8; 10];
494        assert!(matches!(
495            EchoPacket::parse(&bytes),
496            Err(RtmpError::BufferTooShort(BufferTooShort {
497                need: HANDSHAKE_PACKET_LEN,
498                have: 10,
499                ..
500            }))
501        ));
502    }
503
504    // ── FSM happy path ────────────────────────────────────────────────────
505
506    fn build_c0_c1(client_time: u32, client_random: [u8; RANDOM_LEN]) -> Vec<u8> {
507        let mut v = vec![0u8; VERSION_LEN + HANDSHAKE_PACKET_LEN];
508        v[0] = RTMP_VERSION;
509        let c1 = HandshakePacket {
510            time: client_time,
511            zero: 0,
512            random: client_random,
513        };
514        c1.serialize_into(&mut v[VERSION_LEN..]).unwrap();
515        v
516    }
517
518    fn build_c2(time: u32, time2: u32, random_echo: [u8; RANDOM_LEN]) -> Vec<u8> {
519        let c2 = EchoPacket {
520            time,
521            time2,
522            random_echo,
523        };
524        let mut v = vec![0u8; HANDSHAKE_PACKET_LEN];
525        c2.serialize_into(&mut v).unwrap();
526        v
527    }
528
529    #[test]
530    fn fsm_happy_path_reaches_done_and_s2_echoes_c1() {
531        let client_time = 0x0000_1234;
532        let client_random = patterned_random(0x77);
533
534        let mut hs = Handshake::new();
535        assert!(!hs.is_done());
536
537        let c0_c1 = build_c0_c1(client_time, client_random);
538        let (reply, consumed, done) = hs.read(&c0_c1).unwrap();
539
540        assert_eq!(consumed, VERSION_LEN + HANDSHAKE_PACKET_LEN);
541        assert!(!done);
542        assert!(!hs.is_done());
543        assert_eq!(
544            reply.len(),
545            VERSION_LEN + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN,
546            "S0+S1+S2 must total 3073 bytes"
547        );
548
549        // S0.
550        let s0 = Version::parse(&reply[..VERSION_LEN]).unwrap();
551        assert_eq!(s0.0, RTMP_VERSION);
552
553        // S1 (not checked for content beyond length — S1 is our own data).
554        let s1_start = VERSION_LEN;
555        let s1_end = s1_start + HANDSHAKE_PACKET_LEN;
556        let _s1 = HandshakePacket::parse(&reply[s1_start..s1_end]).unwrap();
557
558        // S2 — MUST echo C1's time and random bytes (§5.2.4).
559        let s2 = EchoPacket::parse(&reply[s1_end..]).unwrap();
560        assert_eq!(s2.time, client_time, "S2.time must echo C1.time");
561        assert_eq!(
562            s2.random_echo, client_random,
563            "S2.random_echo must equal C1's random bytes verbatim"
564        );
565
566        // Client now sends C2, echoing S1's time/random (use S1's actual
567        // values, which the client would have parsed out of the reply).
568        let s1 = HandshakePacket::parse(&reply[s1_start..s1_end]).unwrap();
569        let c2 = build_c2(s1.time, 0, s1.random);
570        let (reply2, consumed2, done2) = hs.read(&c2).unwrap();
571        assert_eq!(consumed2, HANDSHAKE_PACKET_LEN);
572        assert!(done2);
573        assert!(hs.is_done());
574        assert!(
575            reply2.is_empty(),
576            "C2 receipt produces no further reply bytes"
577        );
578    }
579
580    /// RTMP-W11 (#1108): C0's version byte used to be parsed and discarded,
581    /// so an RTMPE client (C0 = 6) or garbage was accepted here and only
582    /// surfaced later as a confusing chunk-parse error.
583    #[test]
584    fn fsm_rejects_bad_c0_version() {
585        let mut hs = Handshake::new();
586        let mut c0_c1 = build_c0_c1(0, patterned_random(3));
587        c0_c1[0] = 6; // RTMPE, not plain RTMP
588        let err = hs.read(&c0_c1).unwrap_err();
589        assert!(matches!(
590            err,
591            RtmpError::HandshakeVersion {
592                value: 6,
593                expected: RTMP_VERSION
594            }
595        ));
596    }
597
598    #[test]
599    fn fsm_partial_c1_is_buffer_too_short() {
600        let mut hs = Handshake::new();
601        // C0 present, C1 truncated by one byte.
602        let full = build_c0_c1(0, patterned_random(1));
603        let partial = &full[..full.len() - 1];
604        let err = hs.read(partial).unwrap_err();
605        assert!(matches!(err, RtmpError::BufferTooShort(..)));
606        assert!(!hs.is_done(), "state must not advance on a short read");
607    }
608
609    #[test]
610    fn fsm_partial_c2_is_buffer_too_short() {
611        let mut hs = Handshake::new();
612        let c0_c1 = build_c0_c1(0, patterned_random(2));
613        let (_reply, _consumed, done) = hs.read(&c0_c1).unwrap();
614        assert!(!done);
615
616        let full_c2 = build_c2(0, 0, patterned_random(2));
617        let partial_c2 = &full_c2[..full_c2.len() - 1];
618        let err = hs.read(partial_c2).unwrap_err();
619        assert!(matches!(err, RtmpError::BufferTooShort(..)));
620        assert!(
621            !hs.is_done(),
622            "state must not advance to Done on a short C2 read"
623        );
624    }
625
626    #[test]
627    fn fsm_done_is_idempotent_noop() {
628        let mut hs = Handshake::new();
629        let c0_c1 = build_c0_c1(0, patterned_random(3));
630        hs.read(&c0_c1).unwrap();
631        let full_c2 = build_c2(0, 0, patterned_random(3));
632        hs.read(&full_c2).unwrap();
633        assert!(hs.is_done());
634
635        let (reply, consumed, done) = hs.read(&[]).unwrap();
636        assert!(reply.is_empty());
637        assert_eq!(consumed, 0);
638        assert!(done);
639    }
640
641    // ── Mutation-check sentinels ──────────────────────────────────────────
642    // These pin the exact behaviors a broken serializer/FSM could silently
643    // drop; see the module-level test suite as a whole for the mutation
644    // scenarios the brief calls out (dropped random tail, non-echoing S2).
645
646    #[test]
647    fn handshake_packet_serialize_writes_full_random_tail() {
648        let hp = HandshakePacket {
649            time: 1,
650            zero: 0,
651            random: [0xFFu8; RANDOM_LEN],
652        };
653        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
654        hp.serialize_into(&mut buf).unwrap();
655        assert!(
656            buf[8..].iter().all(|&b| b == 0xFF),
657            "every random byte must be written, not just a prefix"
658        );
659    }
660
661    #[test]
662    fn echo_packet_random_echo_must_differ_from_local_pattern_to_catch_non_echo_bugs() {
663        // Sanity check that our two "seeds" actually produce different byte
664        // sequences, so a test asserting S2.random_echo == client_random
665        // would fail if the FSM instead echoed its *own* S1 random.
666        assert_ne!(patterned_random(0x77), default_random_fill());
667    }
668
669    /// Audit 22: `serialized_len` is the size `serialize_into` requires, on the
670    /// wire lengths §5.2.2 (`1`) and §5.2.3/§5.2.4 (`1536`).
671    #[test]
672    fn serialized_len_sizes_exactly_what_serialize_into_writes() {
673        let version = Version(RTMP_VERSION);
674        assert_eq!(version.serialized_len(), 1);
675        let mut buf = vec![0u8; version.serialized_len()];
676        assert_eq!(version.serialize_into(&mut buf).unwrap(), 1);
677        assert_eq!(buf, vec![3]);
678        assert!(version.serialize_into(&mut [0u8; 0]).is_err());
679
680        let packet = HandshakePacket {
681            time: 0x1122_3344,
682            zero: 0,
683            random: patterned_random(0x5A),
684        };
685        assert_eq!(packet.serialized_len(), 1536);
686        let mut buf = vec![0u8; packet.serialized_len()];
687        assert_eq!(packet.serialize_into(&mut buf).unwrap(), 1536);
688        assert_eq!(&buf[..8], &[0x11, 0x22, 0x33, 0x44, 0, 0, 0, 0]);
689        assert!(packet.serialize_into(&mut [0u8; 1535]).is_err());
690
691        let echo = EchoPacket {
692            time: 1,
693            time2: 2,
694            random_echo: patterned_random(0xA5),
695        };
696        assert_eq!(echo.serialized_len(), 1536);
697        let mut buf = vec![0u8; echo.serialized_len()];
698        assert_eq!(echo.serialize_into(&mut buf).unwrap(), 1536);
699        assert_eq!(&buf[..8], &[0, 0, 0, 1, 0, 0, 0, 2]);
700        assert!(echo.serialize_into(&mut [0u8; 1535]).is_err());
701    }
702}