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_common::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::handshake_sm::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(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(
323                self.config.flags.0 & peer_msg.srt_flags.0,
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(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(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(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(0x9999, 0xC0FF_EE00, HandshakeConfig::default());
449        let outputs = l.feed(&caller_induction(0x1234)).unwrap();
450        assert_eq!(outputs.len(), 1);
451        let bytes = match &outputs[0] {
452            HandshakeOutput::Send(b) => b.clone(),
453            other => panic!("expected Send, got {other:?}"),
454        };
455        let pkt = ControlPacket::parse(&bytes).unwrap();
456        match pkt {
457            ControlPacket::Handshake(hp) => {
458                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
459                assert_eq!(hp.extension_field.0, SRT_MAGIC_CODE);
460                assert_eq!(hp.handshake_type, HandshakeType::Induction);
461                assert_eq!(hp.srt_socket_id, 0x9999);
462                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
463                assert_eq!(hp.dest_socket_id, SocketId::from_wire(0x1234));
464            }
465            _ => panic!("expected handshake"),
466        }
467        assert_eq!(l.state(), ListenerHandshakeState::AwaitingConclusion);
468    }
469
470    fn caller_conclusion(
471        caller_id: u32,
472        listener_id: u32,
473        cookie: u32,
474        latency_ms: u16,
475    ) -> ControlPacket<'static> {
476        let hs_msg = HsExtMessage {
477            srt_version: 0x0105_0000,
478            srt_flags: crate::packet::HandshakeExtensionMessageFlags(0x6F),
479            receiver_tsbpd_delay: Duration::from_millis(u64::from(latency_ms)),
480            sender_tsbpd_delay: Duration::from_millis(u64::from(latency_ms)),
481        };
482        let ext = crate::packet::handshake::build_extension_block(
483            ExtensionType::HsReq,
484            &hs_msg.to_bytes(),
485        )
486        .unwrap();
487        let ext: &'static [u8] = Vec::leak(ext);
488        let ext = HandshakeExtensions::parse(ext).expect("test extension bytes");
489        ControlPacket::Handshake(HandshakePacket {
490            timestamp: SrtTimestamp::ZERO,
491            dest_socket_id: SocketId::from_wire(listener_id),
492            version: HANDSHAKE_VERSION_5,
493            encryption_field: EncryptionField::NoEncryption,
494            extension_field: HandshakeExtensionFlags(HS_EXT_FLAG_HSREQ),
495            initial_seq_number: 0,
496            mtu: 1500,
497            max_flow_window_size: 8192,
498            handshake_type: HandshakeType::Conclusion,
499            srt_socket_id: caller_id,
500            syn_cookie: cookie,
501            peer_ip: [0; 4],
502            extensions: ext,
503        })
504    }
505
506    #[test]
507    fn conclusion_bad_cookie_is_rejected() {
508        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
509        l.feed(&caller_induction(2)).unwrap();
510        let outputs = l.feed(&caller_conclusion(2, 1, 0xBAD_C00C, 120)).unwrap();
511        assert_eq!(outputs.len(), 2);
512        assert_eq!(
513            outputs[1],
514            HandshakeOutput::Rejected(RejectionReason::Rogue)
515        );
516        let bytes = match &outputs[0] {
517            HandshakeOutput::Send(b) => b,
518            other => panic!("expected Send, got {other:?}"),
519        };
520        let pkt = ControlPacket::parse(bytes).unwrap();
521        if let ControlPacket::Handshake(hp) = pkt {
522            assert_eq!(
523                hp.handshake_type,
524                RejectionReason::Rogue.to_handshake_type()
525            );
526        } else {
527            panic!("expected handshake");
528        }
529        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
530    }
531
532    #[test]
533    fn conclusion_version_mismatch_is_rejected() {
534        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
535        l.feed(&caller_induction(2)).unwrap();
536        let mut bad = caller_conclusion(2, 1, 0xC0FF_EE00, 120);
537        if let ControlPacket::Handshake(hp) = &mut bad {
538            hp.version = 4;
539        }
540        let outputs = l.feed(&bad).unwrap();
541        assert_eq!(
542            outputs[1],
543            HandshakeOutput::Rejected(RejectionReason::Version)
544        );
545        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
546    }
547
548    #[test]
549    fn conclusion_malformed_extension_is_rejected_not_panicking() {
550        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
551        l.feed(&caller_induction(2)).unwrap();
552        // An extension block whose contents are not a Handshake Extension
553        // Message — must reject cleanly, not panic.
554        let ext: &'static [u8] = &[0x00, 0x01, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF];
555        let bad = ControlPacket::Handshake(HandshakePacket {
556            timestamp: SrtTimestamp::ZERO,
557            dest_socket_id: SocketId::from_wire(1),
558            version: HANDSHAKE_VERSION_5,
559            encryption_field: EncryptionField::NoEncryption,
560            extension_field: HandshakeExtensionFlags(HS_EXT_FLAG_HSREQ),
561            initial_seq_number: 0,
562            mtu: 1500,
563            max_flow_window_size: 8192,
564            handshake_type: HandshakeType::Conclusion,
565            srt_socket_id: 2,
566            syn_cookie: 0xC0FF_EE00,
567            peer_ip: [0; 4],
568            extensions: HandshakeExtensions::parse(ext).expect("test extension bytes"),
569        });
570        let outputs = l.feed(&bad).unwrap();
571        assert_eq!(
572            outputs[1],
573            HandshakeOutput::Rejected(RejectionReason::Rogue)
574        );
575        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
576    }
577
578    #[test]
579    fn successful_conclusion_reaches_connected() {
580        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
581        l.feed(&caller_induction(2)).unwrap();
582        let outputs = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
583        assert_eq!(outputs.len(), 2);
584        assert!(matches!(outputs[0], HandshakeOutput::Send(_)));
585        assert!(matches!(outputs[1], HandshakeOutput::Connected(_)));
586        assert_eq!(l.state(), ListenerHandshakeState::Connected);
587        assert!(l.negotiated().is_some());
588    }
589
590    #[test]
591    fn feed_before_induction_seen_still_requires_induction_first() {
592        let mut l = ListenerHandshake::new(1, 1, HandshakeConfig::default());
593        let outputs = l.feed(&caller_induction(2));
594        assert!(outputs.is_ok());
595    }
596
597    fn conclusion_response_bytes(outputs: &[HandshakeOutput]) -> Vec<u8> {
598        match &outputs[0] {
599            HandshakeOutput::Send(b) => b.clone(),
600            other => panic!("expected Send, got {other:?}"),
601        }
602    }
603
604    /// r08-SRT-W5: a duplicate CONCLUSION from the connected Caller (its
605    /// response was lost) is answered with the identical response bytes.
606    #[test]
607    fn duplicate_conclusion_after_connected_is_reanswered() {
608        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
609        l.feed(&caller_induction(2)).unwrap();
610        let first = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
611        let original = conclusion_response_bytes(&first);
612        assert_eq!(l.state(), ListenerHandshakeState::Connected);
613
614        let again = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
615        assert_eq!(again, vec![HandshakeOutput::Send(original.clone())]);
616        // And again: it is stateless on the Listener side.
617        let third = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
618        assert_eq!(third, vec![HandshakeOutput::Send(original)]);
619        assert_eq!(l.state(), ListenerHandshakeState::Connected);
620    }
621
622    /// Only the connected peer (its Socket ID and the cookie) is re-answered:
623    /// another Caller's CONCLUSION, or one with a wrong cookie, is still
624    /// out-of-sequence — never an oracle for the response bytes.
625    #[test]
626    fn conclusion_from_a_stranger_after_connected_is_not_answered() {
627        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
628        l.feed(&caller_induction(2)).unwrap();
629        l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
630        // A different Caller Socket ID.
631        assert!(matches!(
632            l.feed(&caller_conclusion(3, 1, 0xC0FF_EE00, 120)),
633            Err(Error::HandshakeOutOfSequence { .. })
634        ));
635        // The right Socket ID but a wrong cookie.
636        assert!(matches!(
637            l.feed(&caller_conclusion(2, 1, 0xBAD0_BAD0, 120)),
638            Err(Error::HandshakeOutOfSequence { .. })
639        ));
640        // An INDUCTION after Connected is not answered either.
641        assert!(matches!(
642            l.feed(&caller_induction(2)),
643            Err(Error::HandshakeOutOfSequence { .. })
644        ));
645        assert_eq!(l.state(), ListenerHandshakeState::Connected);
646    }
647
648    /// r08-SRT-W10 (Listener side): a repeated INDUCTION while awaiting the
649    /// CONCLUSION re-sends the same INDUCTION response rather than rejecting
650    /// the Caller as Rogue and abandoning the handshake.
651    #[test]
652    fn repeated_induction_while_awaiting_conclusion_is_reanswered() {
653        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
654        let first = l.feed(&caller_induction(2)).unwrap();
655        let again = l.feed(&caller_induction(2)).unwrap();
656        assert_eq!(again, first);
657        assert_eq!(l.state(), ListenerHandshakeState::AwaitingConclusion);
658        // The handshake still completes afterwards.
659        let done = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
660        assert!(
661            done.iter()
662                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
663        );
664    }
665
666    fn with_limits(
667        mut pkt: ControlPacket<'static>,
668        mtu: u32,
669        mfw: u32,
670        isn: u32,
671    ) -> ControlPacket<'static> {
672        if let ControlPacket::Handshake(hp) = &mut pkt {
673            hp.mtu = mtu;
674            hp.max_flow_window_size = mfw;
675            hp.initial_seq_number = isn;
676        }
677        pkt
678    }
679
680    /// §3.2.1: the connection runs with the smaller of the two sides' MTU and
681    /// Maximum Flow Window Size, whichever side is smaller.
682    #[test]
683    fn negotiated_mtu_and_flow_window_are_the_smaller_of_both() {
684        for (peer_mtu, peer_mfw, want_mtu, want_mfw) in [
685            (576, 64, 576, 64),
686            (9000, 65_536, 1500, 8192),
687            (1500, 64, 1500, 64),
688        ] {
689            let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
690            l.feed(&caller_induction(2)).unwrap();
691            l.feed(&with_limits(
692                caller_conclusion(2, 1, 0xC0FF_EE00, 120),
693                peer_mtu,
694                peer_mfw,
695                0,
696            ))
697            .unwrap();
698            let n = l.negotiated().expect("connected");
699            assert_eq!((n.mtu, n.max_flow_window_size), (want_mtu, want_mfw));
700        }
701    }
702
703    /// A peer ISN that is not a 31-bit sequence number is refused outright
704    /// (it would seed `next_expected` out of range and stall forever).
705    #[test]
706    fn an_isn_wider_than_31_bits_is_rejected() {
707        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
708        let out = l
709            .feed(&with_limits(caller_induction(2), 1500, 8192, 0x8000_0000))
710            .unwrap();
711        assert!(matches!(
712            out.last(),
713            Some(HandshakeOutput::Rejected(RejectionReason::Rogue))
714        ));
715        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
716
717        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
718        l.feed(&caller_induction(2)).unwrap();
719        let out = l
720            .feed(&with_limits(
721                caller_conclusion(2, 1, 0xC0FF_EE00, 120),
722                1500,
723                8192,
724                u32::MAX,
725            ))
726            .unwrap();
727        assert!(matches!(
728            out.last(),
729            Some(HandshakeOutput::Rejected(RejectionReason::Rogue))
730        ));
731        // The largest legal ISN is fine.
732        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
733        let out = l
734            .feed(&with_limits(caller_induction(2), 1500, 8192, 0x7FFF_FFFF))
735            .unwrap();
736        assert!(matches!(out[0], HandshakeOutput::Send(_)));
737    }
738}