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