Skip to main content

srt_runtime/
listener.rs

1//! Listener-side handshake engine — `draft-sharabayko-srt-01` §4.3.1
2//! (Caller-Listener Handshake), Listener role.
3//!
4//! [`ListenerHandshake`] is the mirror of [`crate::caller::CallerHandshake`]:
5//! it starts passively (no output) and reacts to inbound handshake packets
6//! via [`ListenerHandshake::feed`].
7//!
8//! Flow implemented (§4.3.1.1 / §4.3.1.2):
9//!
10//! 1. `feed()` the Caller's INDUCTION: reply with an INDUCTION response
11//!    (Version 5, the SRT magic code `0x4A17`, the configured/derived SYN
12//!    Cookie) regardless of what the Caller sent — per §4.3.1.1 the Listener
13//!    "still does not know if the Caller is SRT or UDT" at this point and
14//!    "responds with the same set of values regardless."
15//! 2. `feed()` the Caller's CONCLUSION: validate `Handshake Type`, `Version`,
16//!    the echoed SYN Cookie, and decode the extensions (HSREQ, optional
17//!    Stream ID / Group). On success, reply with the CONCLUSION response
18//!    (HSRSP + optional Group) and reach
19//!    [`ListenerHandshakeState::Connected`] with [`NegotiatedParams`]. On
20//!    failure, reply with a rejection handshake packet (`Handshake Type` =
21//!    `1000 + code`, §4.3, Table 7) and reach
22//!    [`ListenerHandshakeState::Rejected`].
23
24use alloc::vec;
25use alloc::vec::Vec;
26use core::time::Duration;
27
28use crate::error::{Error, Result};
29use crate::handshake_sm::{
30    self, HANDSHAKE_VERSION_5, HandshakeConfig, HandshakeOutput, NegotiatedParams, RejectionReason,
31    Retransmit, RetransmitStep, SRT_MAGIC_CODE, WireClock,
32};
33use crate::packet::number::{SocketId, SrtTimestamp};
34use crate::packet::{
35    ControlPacket, EncryptionField, ExtensionType, HandshakeExtensionFlags, HandshakeExtensions,
36    HandshakePacket, HandshakeType, HsExtMessage,
37};
38
39/// Listener-side handshake lifecycle state (`draft-sharabayko-srt-01` §4.3.1).
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize))]
42#[non_exhaustive]
43pub enum ListenerHandshakeState {
44    /// Waiting for the Caller's INDUCTION.
45    Idle,
46    /// INDUCTION response sent; awaiting the Caller's CONCLUSION.
47    AwaitingConclusion,
48    /// The handshake completed; [`NegotiatedParams`] are available.
49    Connected,
50    /// The handshake was rejected (the Caller sent invalid data).
51    Rejected,
52    /// No CONCLUSION arrived after the configured retry budget.
53    TimedOut,
54}
55
56impl ListenerHandshakeState {
57    /// A short label for this state.
58    pub fn name(&self) -> &'static str {
59        match self {
60            ListenerHandshakeState::Idle => "Idle",
61            ListenerHandshakeState::AwaitingConclusion => "AwaitingConclusion",
62            ListenerHandshakeState::Connected => "Connected",
63            ListenerHandshakeState::Rejected => "Rejected",
64            ListenerHandshakeState::TimedOut => "TimedOut",
65        }
66    }
67}
68
69broadcast_core::impl_spec_display!(ListenerHandshakeState);
70
71/// A driveable Listener-side SRT handshake (`draft-sharabayko-srt-01`
72/// §4.3.1). `syn_cookie` is supplied by the caller/driver — this crate's core
73/// never reads a clock or a socket address; see
74/// [`crate::cookie::derive_cookie`] for a ready-made (non-standardized)
75/// derivation helper.
76#[derive(Debug)]
77pub struct ListenerHandshake {
78    own_socket_id: u32,
79    syn_cookie: u32,
80    config: HandshakeConfig,
81    state: ListenerHandshakeState,
82    peer_socket_id: u32,
83    retransmit: Retransmit,
84    clock: WireClock,
85    negotiated: Option<NegotiatedParams>,
86}
87
88impl ListenerHandshake {
89    /// Creates a fresh Listener handshake in [`ListenerHandshakeState::Idle`],
90    /// with the SYN Cookie it will hand out on INDUCTION and check on
91    /// CONCLUSION.
92    pub fn new(own_socket_id: u32, syn_cookie: u32, config: HandshakeConfig) -> Self {
93        ListenerHandshake {
94            own_socket_id,
95            syn_cookie,
96            config,
97            state: ListenerHandshakeState::Idle,
98            peer_socket_id: 0,
99            retransmit: Retransmit::default(),
100            clock: WireClock::default(),
101            negotiated: None,
102        }
103    }
104
105    /// A machine already past its INDUCTION, for a driver that answered the
106    /// INDUCTION statelessly and has only now, on a cookie-validated
107    /// CONCLUSION, allocated the connection's state (#2820).
108    #[cfg(feature = "tokio")]
109    pub(crate) fn awaiting_conclusion(
110        own_socket_id: u32,
111        syn_cookie: u32,
112        config: HandshakeConfig,
113    ) -> Self {
114        ListenerHandshake {
115            own_socket_id,
116            syn_cookie,
117            config,
118            state: ListenerHandshakeState::AwaitingConclusion,
119            peer_socket_id: 0,
120            retransmit: Retransmit::default(),
121            clock: WireClock::default(),
122            negotiated: None,
123        }
124    }
125
126    /// Sets the time elapsed since the connection started; every packet built
127    /// from here on carries it as its wire timestamp (§3.2.1). The machine reads
128    /// no clock, so the driver calls this before each `start`, `feed` and `tick`.
129    pub fn set_elapsed(&mut self, elapsed: core::time::Duration) {
130        self.clock.set(elapsed);
131    }
132
133    /// The current state.
134    pub fn state(&self) -> ListenerHandshakeState {
135        self.state
136    }
137
138    /// The negotiated parameters, once [`ListenerHandshakeState::Connected`].
139    pub fn negotiated(&self) -> Option<&NegotiatedParams> {
140        self.negotiated.as_ref()
141    }
142
143    /// Feeds an inbound control packet.
144    ///
145    /// A repeated INDUCTION while awaiting the CONCLUSION re-sends the
146    /// INDUCTION response; a repeated CONCLUSION from the connected peer
147    /// (matching Socket ID and cookie) re-sends the CONCLUSION response.
148    ///
149    /// # Errors
150    /// [`Error::UnexpectedControlPacket`] if `packet` is not a Handshake
151    /// packet; [`Error::HandshakeOutOfSequence`] if fed in a state that
152    /// expects nothing more (a driver bug, or a stranger's packet after the
153    /// handshake finished — not a peer failure).
154    pub fn feed(&mut self, packet: &ControlPacket<'_>) -> Result<Vec<HandshakeOutput>> {
155        let hp = match packet {
156            ControlPacket::Handshake(hp) => hp,
157            other => {
158                return Err(Error::UnexpectedControlPacket {
159                    actual: other.control_type().name(),
160                });
161            }
162        };
163        match self.state {
164            ListenerHandshakeState::Idle => self.on_induction(hp),
165            // The Caller retransmits its INDUCTION until it hears an answer,
166            // so a repeat here means the answer was lost: answer again (the
167            // INDUCTION response is deterministic — same cookie) instead of
168            // rejecting the Caller's second INDUCTION as Rogue.
169            ListenerHandshakeState::AwaitingConclusion
170                if hp.handshake_type == HandshakeType::Induction =>
171            {
172                self.on_induction(hp)
173            }
174            ListenerHandshakeState::AwaitingConclusion => self.on_conclusion(hp),
175            // The Caller retransmits its CONCLUSION until it hears our
176            // response; if that response was lost the Caller repeats the
177            // very same CONCLUSION (same Socket ID, same cookie). libsrt
178            // re-sends its response to a repeated CONCLUSION, and so do we —
179            // otherwise one lost datagram leaves the Caller timing out
180            // against a Listener that already considers it connected. Only
181            // the exact connected peer is answered; anything else is
182            // out-of-sequence as before.
183            ListenerHandshakeState::Connected
184                if hp.handshake_type == HandshakeType::Conclusion
185                    && hp.srt_socket_id == self.peer_socket_id
186                    && hp.syn_cookie == self.syn_cookie =>
187            {
188                Ok(self
189                    .retransmit
190                    .last_sent()
191                    .map(|bytes| HandshakeOutput::Send(bytes.to_vec()))
192                    .into_iter()
193                    .collect())
194            }
195            _ => Err(Error::HandshakeOutOfSequence {
196                state: self.state.name(),
197                reason: "not awaiting an induction or conclusion",
198            }),
199        }
200    }
201
202    /// Convenience wrapper: parses `bytes` as a [`ControlPacket`] then
203    /// [`Self::feed`]s it.
204    pub fn feed_bytes(&mut self, bytes: &[u8]) -> Result<Vec<HandshakeOutput>> {
205        let packet = ControlPacket::parse(bytes)?;
206        self.feed(&packet)
207    }
208
209    /// Advances retransmit timing by `elapsed` of the caller's own clock,
210    /// mirroring [`crate::caller::CallerHandshake::tick`].
211    pub fn tick(&mut self, elapsed: Duration) -> Vec<HandshakeOutput> {
212        if self.state != ListenerHandshakeState::AwaitingConclusion {
213            return Vec::new();
214        }
215        let step = self.retransmit.tick(elapsed, &self.config);
216        if matches!(step, RetransmitStep::TimedOut) {
217            self.state = ListenerHandshakeState::TimedOut;
218        }
219        step.into_outputs()
220    }
221
222    fn on_induction(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
223        if hp.handshake_type != HandshakeType::Induction {
224            return Err(Error::HandshakeOutOfSequence {
225                state: self.state.name(),
226                reason: "expected an INDUCTION handshake",
227            });
228        }
229        // The ISN seeds the receiver's sequence tracking; it is a 31-bit
230        // number (§3.1), and one that is not would stall the connection (the
231        // ack point could never be reached).
232        if hp.initial_seq_number > crate::packet::SEQ_NUMBER_MASK {
233            return self.reject(RejectionReason::Rogue, hp);
234        }
235        // §4.3.1.1: the Listener does not yet know if the Caller is SRT or
236        // UDT, and always responds the same way.
237        self.peer_socket_id = hp.srt_socket_id;
238
239        let hp_out = HandshakePacket {
240            timestamp: SrtTimestamp::from_wire(self.clock.now()),
241            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
242            version: HANDSHAKE_VERSION_5,
243            encryption_field: self.config.encryption_field,
244            extension_field: HandshakeExtensionFlags::new(SRT_MAGIC_CODE),
245            initial_seq_number: self.config.initial_seq_number,
246            mtu: self.config.mtu,
247            max_flow_window_size: self.config.max_flow_window_size,
248            handshake_type: HandshakeType::Induction,
249            srt_socket_id: self.own_socket_id,
250            syn_cookie: self.syn_cookie,
251            peer_ip: self.config.local_ip,
252            extensions: HandshakeExtensions(Vec::new()),
253        };
254        let bytes = handshake_sm::build_bytes(hp_out)?;
255        self.retransmit.arm(&bytes);
256        self.state = ListenerHandshakeState::AwaitingConclusion;
257        Ok(vec![HandshakeOutput::Send(bytes)])
258    }
259
260    fn on_conclusion(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
261        if hp.handshake_type != HandshakeType::Conclusion {
262            return self.reject(RejectionReason::Rogue, hp);
263        }
264        if hp.version != HANDSHAKE_VERSION_5 {
265            return self.reject(RejectionReason::Version, hp);
266        }
267        if hp.initial_seq_number > crate::packet::SEQ_NUMBER_MASK {
268            return self.reject(RejectionReason::Rogue, hp);
269        }
270        if hp.mtu == 0 || hp.max_flow_window_size == 0 {
271            return self.reject(RejectionReason::Rogue, hp);
272        }
273        if hp.syn_cookie != self.syn_cookie {
274            // §4.3.1.1: the cookie exists precisely so the Listener can
275            // refuse to allocate resources for an unverified Caller.
276            return self.reject(RejectionReason::Rogue, hp);
277        }
278
279        let parsed = match handshake_sm::parse_peer_extensions(hp) {
280            Ok(p) => p,
281            Err(_) => return self.reject(RejectionReason::Rogue, hp),
282        };
283        let peer_msg = match parsed.hs_msg {
284            Some(m) => m,
285            None => return self.reject(RejectionReason::Rogue, hp),
286        };
287
288        self.peer_socket_id = hp.srt_socket_id;
289
290        // §6.1.5: the Listener (responder) requires the pre-shared
291        // passphrase to recover the SEK from the Caller's Key Material
292        // request; a mismatch in *either* direction (one side configured
293        // for encryption, the other not) is rejected as
294        // `RejectionReason::Unsecure` ("password required or unexpected",
295        // Table 7 code 1011) — a wrong passphrase (RFC 3394 wrap-integrity
296        // failure) is `RejectionReason::BadSecret` (code 1010) instead.
297        #[cfg(feature = "crypto")]
298        let crypto_cfg = self.config.crypto.clone();
299        #[cfg(feature = "crypto")]
300        type CryptoConclusionResult<'a> = (
301            Option<handshake_sm::RecoveredSek>,
302            Option<&'a crate::packet::KeyMaterial<'a>>,
303        );
304        #[cfg(feature = "crypto")]
305        let (crypto_result, km_echo_ext): CryptoConclusionResult<'_> =
306            match (&crypto_cfg, &parsed.km) {
307                (Some(crypto), Some(km_req)) => {
308                    let mut kek_cache = crate::crypto::KekCache::new();
309                    match handshake_sm::recover_sek(&crypto.passphrase, km_req, &mut kek_cache) {
310                        Ok((sek, salt)) => (Some((sek, salt)), Some(km_req)),
311                        Err(_) => return self.reject(RejectionReason::BadSecret, hp),
312                    }
313                }
314                (Some(_), None) | (None, Some(_)) => {
315                    return self.reject(RejectionReason::Unsecure, hp);
316                }
317                (None, None) => (None, None),
318            };
319
320        let negotiated = NegotiatedParams {
321            version: HANDSHAKE_VERSION_5,
322            flags: crate::packet::HandshakeExtensionMessageFlags::new(
323                self.config.flags.get() & peer_msg.srt_flags.get(),
324            ),
325            latency: handshake_sm::negotiate_latency(self.config.latency, &peer_msg),
326            own_socket_id: self.own_socket_id,
327            peer_socket_id: self.peer_socket_id,
328            mtu: self.config.mtu.min(hp.mtu),
329            max_flow_window_size: self
330                .config
331                .max_flow_window_size
332                .min(hp.max_flow_window_size),
333            stream_id: parsed.stream_id,
334            group: parsed.group,
335            #[cfg(feature = "crypto")]
336            sek: crypto_result.as_ref().map(|(sek, _)| sek.clone()),
337            #[cfg(feature = "crypto")]
338            salt: crypto_result.as_ref().map(|(_, salt)| *salt),
339        };
340
341        let hs_msg = HsExtMessage {
342            srt_version: self.config.srt_version,
343            srt_flags: self.config.flags,
344            receiver_tsbpd_delay: self.config.latency,
345            sender_tsbpd_delay: self.config.latency,
346        };
347        // §4.3.1.2: the Listener's CONCLUSION response carries the HSv5
348        // extensions "without the cookie" — no Stream ID is echoed back
349        // (only the Caller advertises one; the Listener already knows it via
350        // `negotiated.stream_id`).
351        let ext_contents =
352            handshake_sm::ConclusionExtensionContents::new(hs_msg, None, self.config.group);
353        // §6.1.5: echo the Caller's Key Material back as confirmation.
354        #[cfg(feature = "crypto")]
355        let mut ext_contents = ext_contents;
356        #[cfg(feature = "crypto")]
357        if let Some(echo) = km_echo_ext {
358            ext_contents.set_key_material(
359                crate::packet::ExtensionType::KmRsp,
360                handshake_sm::echo_key_material_contents(hp, echo)?.into_owned(),
361            );
362        }
363        let (extensions, ext_flags) =
364            handshake_sm::build_conclusion_extensions(ExtensionType::HsRsp, &ext_contents);
365
366        let hp_out = HandshakePacket {
367            timestamp: SrtTimestamp::from_wire(self.clock.now()),
368            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
369            version: HANDSHAKE_VERSION_5,
370            encryption_field: self.config.encryption_field,
371            extension_field: HandshakeExtensionFlags::new(ext_flags),
372            initial_seq_number: self.config.initial_seq_number,
373            mtu: self.config.mtu,
374            max_flow_window_size: self.config.max_flow_window_size,
375            handshake_type: HandshakeType::Conclusion,
376            srt_socket_id: self.own_socket_id,
377            syn_cookie: 0, // §4.3.1.2: "without the cookie (which is not needed here)".
378            peer_ip: self.config.local_ip,
379            extensions,
380        };
381        let bytes = handshake_sm::build_bytes(hp_out)?;
382        self.retransmit.remember(&bytes);
383        self.negotiated = Some(negotiated.clone());
384        self.state = ListenerHandshakeState::Connected;
385        Ok(vec![
386            HandshakeOutput::Send(bytes),
387            HandshakeOutput::Connected(negotiated),
388        ])
389    }
390
391    /// Builds and returns a rejection handshake packet, transitioning to
392    /// [`ListenerHandshakeState::Rejected`].
393    fn reject(
394        &mut self,
395        reason: RejectionReason,
396        hp: &HandshakePacket<'_>,
397    ) -> Result<Vec<HandshakeOutput>> {
398        self.state = ListenerHandshakeState::Rejected;
399        let hp_out = HandshakePacket {
400            timestamp: SrtTimestamp::from_wire(self.clock.now()),
401            dest_socket_id: SocketId::from_wire(hp.srt_socket_id),
402            version: HANDSHAKE_VERSION_5,
403            encryption_field: EncryptionField::NoEncryption,
404            extension_field: HandshakeExtensionFlags::new(0),
405            initial_seq_number: 0,
406            mtu: self.config.mtu,
407            max_flow_window_size: self.config.max_flow_window_size,
408            handshake_type: reason.to_handshake_type(),
409            srt_socket_id: self.own_socket_id,
410            syn_cookie: 0,
411            peer_ip: self.config.local_ip,
412            extensions: HandshakeExtensions(Vec::new()),
413        };
414        let bytes = handshake_sm::build_bytes(hp_out)?;
415        self.retransmit.remember(&bytes);
416        Ok(vec![
417            HandshakeOutput::Send(bytes),
418            HandshakeOutput::Rejected(reason),
419        ])
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use crate::packet::handshake::HS_EXT_FLAG_HSREQ;
427
428    fn caller_induction(caller_id: u32) -> ControlPacket<'static> {
429        ControlPacket::Handshake(HandshakePacket {
430            timestamp: SrtTimestamp::ZERO,
431            dest_socket_id: SocketId::CONNECTION_REQUEST,
432            version: crate::handshake_sm::HANDSHAKE_VERSION_4,
433            encryption_field: EncryptionField::NoEncryption,
434            extension_field: HandshakeExtensionFlags::new(2),
435            initial_seq_number: 0,
436            mtu: 1500,
437            max_flow_window_size: 8192,
438            handshake_type: HandshakeType::Induction,
439            srt_socket_id: caller_id,
440            syn_cookie: 0,
441            peer_ip: [0; 4],
442            extensions: HandshakeExtensions(Vec::new()),
443        })
444    }
445
446    #[test]
447    fn induction_response_wire_values_match_draft_4_3_1_1() {
448        let mut l = ListenerHandshake::new(
449            0x9999,
450            0xC0FF_EE00,
451            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
452        );
453        let outputs = l.feed(&caller_induction(0x1234)).unwrap();
454        assert_eq!(outputs.len(), 1);
455        let bytes = match &outputs[0] {
456            HandshakeOutput::Send(b) => b.clone(),
457            other => panic!("expected Send, got {other:?}"),
458        };
459        let pkt = ControlPacket::parse(&bytes).unwrap();
460        match pkt {
461            ControlPacket::Handshake(hp) => {
462                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
463                assert_eq!(hp.extension_field.get(), SRT_MAGIC_CODE);
464                assert_eq!(hp.handshake_type, HandshakeType::Induction);
465                assert_eq!(hp.srt_socket_id, 0x9999);
466                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
467                assert_eq!(hp.dest_socket_id, SocketId::from_wire(0x1234));
468            }
469            _ => panic!("expected handshake"),
470        }
471        assert_eq!(l.state(), ListenerHandshakeState::AwaitingConclusion);
472    }
473
474    fn caller_conclusion(
475        caller_id: u32,
476        listener_id: u32,
477        cookie: u32,
478        latency_ms: u16,
479    ) -> ControlPacket<'static> {
480        let hs_msg = HsExtMessage {
481            srt_version: 0x0105_0000,
482            srt_flags: crate::packet::HandshakeExtensionMessageFlags::new(0x6F),
483            receiver_tsbpd_delay: Duration::from_millis(u64::from(latency_ms)),
484            sender_tsbpd_delay: Duration::from_millis(u64::from(latency_ms)),
485        };
486        let ext = crate::packet::handshake::build_extension_block(
487            ExtensionType::HsReq,
488            &hs_msg.to_bytes(),
489        )
490        .unwrap();
491        let ext: &'static [u8] = Vec::leak(ext);
492        let ext = HandshakeExtensions::parse(ext).expect("test extension bytes");
493        ControlPacket::Handshake(HandshakePacket {
494            timestamp: SrtTimestamp::ZERO,
495            dest_socket_id: SocketId::from_wire(listener_id),
496            version: HANDSHAKE_VERSION_5,
497            encryption_field: EncryptionField::NoEncryption,
498            extension_field: HandshakeExtensionFlags::new(HS_EXT_FLAG_HSREQ),
499            initial_seq_number: 0,
500            mtu: 1500,
501            max_flow_window_size: 8192,
502            handshake_type: HandshakeType::Conclusion,
503            srt_socket_id: caller_id,
504            syn_cookie: cookie,
505            peer_ip: [0; 4],
506            extensions: ext,
507        })
508    }
509
510    #[test]
511    fn conclusion_bad_cookie_is_rejected() {
512        let mut l = ListenerHandshake::new(
513            1,
514            0xC0FF_EE00,
515            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
516        );
517        l.feed(&caller_induction(2)).unwrap();
518        let outputs = l.feed(&caller_conclusion(2, 1, 0xBAD_C00C, 120)).unwrap();
519        assert_eq!(outputs.len(), 2);
520        assert_eq!(
521            outputs[1],
522            HandshakeOutput::Rejected(RejectionReason::Rogue)
523        );
524        let bytes = match &outputs[0] {
525            HandshakeOutput::Send(b) => b,
526            other => panic!("expected Send, got {other:?}"),
527        };
528        let pkt = ControlPacket::parse(bytes).unwrap();
529        if let ControlPacket::Handshake(hp) = pkt {
530            assert_eq!(
531                hp.handshake_type,
532                RejectionReason::Rogue.to_handshake_type()
533            );
534        } else {
535            panic!("expected handshake");
536        }
537        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
538    }
539
540    #[test]
541    fn conclusion_version_mismatch_is_rejected() {
542        let mut l = ListenerHandshake::new(
543            1,
544            0xC0FF_EE00,
545            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
546        );
547        l.feed(&caller_induction(2)).unwrap();
548        let mut bad = caller_conclusion(2, 1, 0xC0FF_EE00, 120);
549        if let ControlPacket::Handshake(hp) = &mut bad {
550            hp.version = 4;
551        }
552        let outputs = l.feed(&bad).unwrap();
553        assert_eq!(
554            outputs[1],
555            HandshakeOutput::Rejected(RejectionReason::Version)
556        );
557        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
558    }
559
560    #[test]
561    fn conclusion_malformed_extension_is_rejected_not_panicking() {
562        let mut l = ListenerHandshake::new(
563            1,
564            0xC0FF_EE00,
565            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
566        );
567        l.feed(&caller_induction(2)).unwrap();
568        // An extension block whose contents are not a Handshake Extension
569        // Message — must reject cleanly, not panic.
570        let ext: &'static [u8] = &[0x00, 0x01, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF];
571        let bad = ControlPacket::Handshake(HandshakePacket {
572            timestamp: SrtTimestamp::ZERO,
573            dest_socket_id: SocketId::from_wire(1),
574            version: HANDSHAKE_VERSION_5,
575            encryption_field: EncryptionField::NoEncryption,
576            extension_field: HandshakeExtensionFlags::new(HS_EXT_FLAG_HSREQ),
577            initial_seq_number: 0,
578            mtu: 1500,
579            max_flow_window_size: 8192,
580            handshake_type: HandshakeType::Conclusion,
581            srt_socket_id: 2,
582            syn_cookie: 0xC0FF_EE00,
583            peer_ip: [0; 4],
584            extensions: HandshakeExtensions::parse(ext).expect("test extension bytes"),
585        });
586        let outputs = l.feed(&bad).unwrap();
587        assert_eq!(
588            outputs[1],
589            HandshakeOutput::Rejected(RejectionReason::Rogue)
590        );
591        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
592    }
593
594    #[test]
595    fn successful_conclusion_reaches_connected() {
596        let mut l = ListenerHandshake::new(
597            1,
598            0xC0FF_EE00,
599            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
600        );
601        l.feed(&caller_induction(2)).unwrap();
602        let outputs = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
603        assert_eq!(outputs.len(), 2);
604        assert!(matches!(outputs[0], HandshakeOutput::Send(_)));
605        assert!(matches!(outputs[1], HandshakeOutput::Connected(_)));
606        assert_eq!(l.state(), ListenerHandshakeState::Connected);
607        assert!(l.negotiated().is_some());
608    }
609
610    #[test]
611    fn feed_before_induction_seen_still_requires_induction_first() {
612        let mut l = ListenerHandshake::new(
613            1,
614            1,
615            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
616        );
617        let outputs = l.feed(&caller_induction(2));
618        assert!(outputs.is_ok());
619    }
620
621    fn conclusion_response_bytes(outputs: &[HandshakeOutput]) -> Vec<u8> {
622        match &outputs[0] {
623            HandshakeOutput::Send(b) => b.clone(),
624            other => panic!("expected Send, got {other:?}"),
625        }
626    }
627
628    /// r08-SRT-W5: a duplicate CONCLUSION from the connected Caller (its
629    /// response was lost) is answered with the identical response bytes.
630    #[test]
631    fn duplicate_conclusion_after_connected_is_reanswered() {
632        let mut l = ListenerHandshake::new(
633            1,
634            0xC0FF_EE00,
635            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
636        );
637        l.feed(&caller_induction(2)).unwrap();
638        let first = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
639        let original = conclusion_response_bytes(&first);
640        assert_eq!(l.state(), ListenerHandshakeState::Connected);
641
642        let again = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
643        assert_eq!(again, vec![HandshakeOutput::Send(original.clone())]);
644        // And again: it is stateless on the Listener side.
645        let third = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
646        assert_eq!(third, vec![HandshakeOutput::Send(original)]);
647        assert_eq!(l.state(), ListenerHandshakeState::Connected);
648    }
649
650    /// Only the connected peer (its Socket ID and the cookie) is re-answered:
651    /// another Caller's CONCLUSION, or one with a wrong cookie, is still
652    /// out-of-sequence — never an oracle for the response bytes.
653    #[test]
654    fn conclusion_from_a_stranger_after_connected_is_not_answered() {
655        let mut l = ListenerHandshake::new(
656            1,
657            0xC0FF_EE00,
658            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
659        );
660        l.feed(&caller_induction(2)).unwrap();
661        l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
662        // A different Caller Socket ID.
663        assert!(matches!(
664            l.feed(&caller_conclusion(3, 1, 0xC0FF_EE00, 120)),
665            Err(Error::HandshakeOutOfSequence { .. })
666        ));
667        // The right Socket ID but a wrong cookie.
668        assert!(matches!(
669            l.feed(&caller_conclusion(2, 1, 0xBAD0_BAD0, 120)),
670            Err(Error::HandshakeOutOfSequence { .. })
671        ));
672        // An INDUCTION after Connected is not answered either.
673        assert!(matches!(
674            l.feed(&caller_induction(2)),
675            Err(Error::HandshakeOutOfSequence { .. })
676        ));
677        assert_eq!(l.state(), ListenerHandshakeState::Connected);
678    }
679
680    /// r08-SRT-W10 (Listener side): a repeated INDUCTION while awaiting the
681    /// CONCLUSION re-sends the same INDUCTION response rather than rejecting
682    /// the Caller as Rogue and abandoning the handshake.
683    #[test]
684    fn repeated_induction_while_awaiting_conclusion_is_reanswered() {
685        let mut l = ListenerHandshake::new(
686            1,
687            0xC0FF_EE00,
688            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
689        );
690        let first = l.feed(&caller_induction(2)).unwrap();
691        let again = l.feed(&caller_induction(2)).unwrap();
692        assert_eq!(again, first);
693        assert_eq!(l.state(), ListenerHandshakeState::AwaitingConclusion);
694        // The handshake still completes afterwards.
695        let done = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
696        assert!(
697            done.iter()
698                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
699        );
700    }
701
702    fn with_limits(
703        mut pkt: ControlPacket<'static>,
704        mtu: u32,
705        mfw: u32,
706        isn: u32,
707    ) -> ControlPacket<'static> {
708        if let ControlPacket::Handshake(hp) = &mut pkt {
709            hp.mtu = mtu;
710            hp.max_flow_window_size = mfw;
711            hp.initial_seq_number = isn;
712        }
713        pkt
714    }
715
716    /// §3.2.1: the connection runs with the smaller of the two sides' MTU and
717    /// Maximum Flow Window Size, whichever side is smaller.
718    #[test]
719    fn negotiated_mtu_and_flow_window_are_the_smaller_of_both() {
720        for (peer_mtu, peer_mfw, want_mtu, want_mfw) in [
721            (576, 64, 576, 64),
722            (9000, 65_536, 1500, 8192),
723            (1500, 64, 1500, 64),
724        ] {
725            let mut l = ListenerHandshake::new(
726                1,
727                0xC0FF_EE00,
728                HandshakeConfig::for_profile(broadcast_core::Profile::Server),
729            );
730            l.feed(&caller_induction(2)).unwrap();
731            l.feed(&with_limits(
732                caller_conclusion(2, 1, 0xC0FF_EE00, 120),
733                peer_mtu,
734                peer_mfw,
735                0,
736            ))
737            .unwrap();
738            let n = l.negotiated().expect("connected");
739            assert_eq!((n.mtu, n.max_flow_window_size), (want_mtu, want_mfw));
740        }
741    }
742
743    /// A peer ISN that is not a 31-bit sequence number is refused outright
744    /// (it would seed `next_expected` out of range and stall forever).
745    #[test]
746    fn an_isn_wider_than_31_bits_is_rejected() {
747        let mut l = ListenerHandshake::new(
748            1,
749            0xC0FF_EE00,
750            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
751        );
752        let out = l
753            .feed(&with_limits(caller_induction(2), 1500, 8192, 0x8000_0000))
754            .unwrap();
755        assert!(matches!(
756            out.last(),
757            Some(HandshakeOutput::Rejected(RejectionReason::Rogue))
758        ));
759        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
760
761        let mut l = ListenerHandshake::new(
762            1,
763            0xC0FF_EE00,
764            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
765        );
766        l.feed(&caller_induction(2)).unwrap();
767        let out = l
768            .feed(&with_limits(
769                caller_conclusion(2, 1, 0xC0FF_EE00, 120),
770                1500,
771                8192,
772                u32::MAX,
773            ))
774            .unwrap();
775        assert!(matches!(
776            out.last(),
777            Some(HandshakeOutput::Rejected(RejectionReason::Rogue))
778        ));
779        // The largest legal ISN is fine.
780        let mut l = ListenerHandshake::new(
781            1,
782            0xC0FF_EE00,
783            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
784        );
785        let out = l
786            .feed(&with_limits(caller_induction(2), 1500, 8192, 0x7FFF_FFFF))
787            .unwrap();
788        assert!(matches!(out[0], HandshakeOutput::Send(_)));
789    }
790
791    /// The CONCLUSION's ISN boundary is inclusive: exactly the 31-bit mask is
792    /// legal and connects, one more is rogue.
793    #[test]
794    fn conclusion_isn_boundary_is_the_31_bit_mask() {
795        let mut l = ListenerHandshake::new(
796            1,
797            0xC0FF_EE00,
798            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
799        );
800        l.feed(&caller_induction(2)).unwrap();
801        let out = l
802            .feed(&with_limits(
803                caller_conclusion(2, 1, 0xC0FF_EE00, 120),
804                1500,
805                8192,
806                crate::packet::SEQ_NUMBER_MASK,
807            ))
808            .unwrap();
809        assert!(
810            out.iter()
811                .any(|o| matches!(o, HandshakeOutput::Connected(_))),
812            "the maximum legal ISN must be accepted: {out:?}"
813        );
814        assert_eq!(l.state(), ListenerHandshakeState::Connected);
815
816        let mut l = ListenerHandshake::new(
817            1,
818            0xC0FF_EE00,
819            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
820        );
821        l.feed(&caller_induction(2)).unwrap();
822        let out = l
823            .feed(&with_limits(
824                caller_conclusion(2, 1, 0xC0FF_EE00, 120),
825                1500,
826                8192,
827                crate::packet::SEQ_NUMBER_MASK + 1,
828            ))
829            .unwrap();
830        assert!(matches!(
831            out.last(),
832            Some(HandshakeOutput::Rejected(RejectionReason::Rogue))
833        ));
834        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
835    }
836
837    #[test]
838    fn state_labels_match_the_diagram_names() {
839        assert_eq!(ListenerHandshakeState::Idle.name(), "Idle");
840        assert_eq!(
841            ListenerHandshakeState::AwaitingConclusion.name(),
842            "AwaitingConclusion"
843        );
844        assert_eq!(ListenerHandshakeState::Connected.name(), "Connected");
845        assert_eq!(ListenerHandshakeState::Rejected.name(), "Rejected");
846        assert_eq!(ListenerHandshakeState::TimedOut.name(), "TimedOut");
847    }
848}