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    /// Sets the time elapsed since the connection started; every packet built
106    /// from here on carries it as its wire timestamp (§3.2.1). The machine reads
107    /// no clock, so the driver calls this before each `start`, `feed` and `tick`.
108    pub fn set_elapsed(&mut self, elapsed: core::time::Duration) {
109        self.clock.set(elapsed);
110    }
111
112    /// The current state.
113    pub fn state(&self) -> ListenerHandshakeState {
114        self.state
115    }
116
117    /// The negotiated parameters, once [`ListenerHandshakeState::Connected`].
118    pub fn negotiated(&self) -> Option<&NegotiatedParams> {
119        self.negotiated.as_ref()
120    }
121
122    /// Feeds an inbound control packet.
123    ///
124    /// A repeated INDUCTION while awaiting the CONCLUSION re-sends the
125    /// INDUCTION response; a repeated CONCLUSION from the connected peer
126    /// (matching Socket ID and cookie) re-sends the CONCLUSION response.
127    ///
128    /// # Errors
129    /// [`Error::UnexpectedControlPacket`] if `packet` is not a Handshake
130    /// packet; [`Error::HandshakeOutOfSequence`] if fed in a state that
131    /// expects nothing more (a driver bug, or a stranger's packet after the
132    /// handshake finished — not a peer failure).
133    pub fn feed(&mut self, packet: &ControlPacket<'_>) -> Result<Vec<HandshakeOutput>> {
134        let hp = match packet {
135            ControlPacket::Handshake(hp) => hp,
136            other => {
137                return Err(Error::UnexpectedControlPacket {
138                    actual: other.control_type().name(),
139                });
140            }
141        };
142        match self.state {
143            ListenerHandshakeState::Idle => self.on_induction(hp),
144            // The Caller retransmits its INDUCTION until it hears an answer,
145            // so a repeat here means the answer was lost: answer again (the
146            // INDUCTION response is deterministic — same cookie) instead of
147            // rejecting the Caller's second INDUCTION as Rogue.
148            ListenerHandshakeState::AwaitingConclusion
149                if hp.handshake_type == HandshakeType::Induction =>
150            {
151                self.on_induction(hp)
152            }
153            ListenerHandshakeState::AwaitingConclusion => self.on_conclusion(hp),
154            // The Caller retransmits its CONCLUSION until it hears our
155            // response; if that response was lost the Caller repeats the
156            // very same CONCLUSION (same Socket ID, same cookie). libsrt
157            // re-sends its response to a repeated CONCLUSION, and so do we —
158            // otherwise one lost datagram leaves the Caller timing out
159            // against a Listener that already considers it connected. Only
160            // the exact connected peer is answered; anything else is
161            // out-of-sequence as before.
162            ListenerHandshakeState::Connected
163                if hp.handshake_type == HandshakeType::Conclusion
164                    && hp.srt_socket_id == self.peer_socket_id
165                    && hp.syn_cookie == self.syn_cookie =>
166            {
167                Ok(self
168                    .retransmit
169                    .last_sent()
170                    .map(|bytes| HandshakeOutput::Send(bytes.to_vec()))
171                    .into_iter()
172                    .collect())
173            }
174            _ => Err(Error::HandshakeOutOfSequence {
175                state: self.state.name(),
176                reason: "not awaiting an induction or conclusion",
177            }),
178        }
179    }
180
181    /// Convenience wrapper: parses `bytes` as a [`ControlPacket`] then
182    /// [`Self::feed`]s it.
183    pub fn feed_bytes(&mut self, bytes: &[u8]) -> Result<Vec<HandshakeOutput>> {
184        let packet = ControlPacket::parse(bytes)?;
185        self.feed(&packet)
186    }
187
188    /// Advances retransmit timing by `elapsed` of the caller's own clock,
189    /// mirroring [`crate::caller::CallerHandshake::tick`].
190    pub fn tick(&mut self, elapsed: Duration) -> Vec<HandshakeOutput> {
191        if self.state != ListenerHandshakeState::AwaitingConclusion {
192            return Vec::new();
193        }
194        let step = self.retransmit.tick(elapsed, &self.config);
195        if matches!(step, RetransmitStep::TimedOut) {
196            self.state = ListenerHandshakeState::TimedOut;
197        }
198        step.into_outputs()
199    }
200
201    fn on_induction(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
202        if hp.handshake_type != HandshakeType::Induction {
203            return Err(Error::HandshakeOutOfSequence {
204                state: self.state.name(),
205                reason: "expected an INDUCTION handshake",
206            });
207        }
208        // The ISN seeds the receiver's sequence tracking; it is a 31-bit
209        // number (§3.1), and one that is not would stall the connection (the
210        // ack point could never be reached).
211        if hp.initial_seq_number > crate::packet::SEQ_NUMBER_MASK {
212            return self.reject(RejectionReason::Rogue, hp);
213        }
214        // §4.3.1.1: the Listener does not yet know if the Caller is SRT or
215        // UDT, and always responds the same way.
216        self.peer_socket_id = hp.srt_socket_id;
217
218        let hp_out = HandshakePacket {
219            timestamp: SrtTimestamp::from_wire(self.clock.now()),
220            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
221            version: HANDSHAKE_VERSION_5,
222            encryption_field: self.config.encryption_field,
223            extension_field: HandshakeExtensionFlags(SRT_MAGIC_CODE),
224            initial_seq_number: self.config.initial_seq_number,
225            mtu: self.config.mtu,
226            max_flow_window_size: self.config.max_flow_window_size,
227            handshake_type: HandshakeType::Induction,
228            srt_socket_id: self.own_socket_id,
229            syn_cookie: self.syn_cookie,
230            peer_ip: self.config.local_ip,
231            extensions: HandshakeExtensions(Vec::new()),
232        };
233        let bytes = handshake_sm::build_bytes(hp_out)?;
234        self.retransmit.arm(&bytes);
235        self.state = ListenerHandshakeState::AwaitingConclusion;
236        Ok(vec![HandshakeOutput::Send(bytes)])
237    }
238
239    fn on_conclusion(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
240        if hp.handshake_type != HandshakeType::Conclusion {
241            return self.reject(RejectionReason::Rogue, hp);
242        }
243        if hp.version != HANDSHAKE_VERSION_5 {
244            return self.reject(RejectionReason::Version, hp);
245        }
246        if hp.initial_seq_number > crate::packet::SEQ_NUMBER_MASK {
247            return self.reject(RejectionReason::Rogue, hp);
248        }
249        if hp.mtu == 0 || hp.max_flow_window_size == 0 {
250            return self.reject(RejectionReason::Rogue, hp);
251        }
252        if hp.syn_cookie != self.syn_cookie {
253            // §4.3.1.1: the cookie exists precisely so the Listener can
254            // refuse to allocate resources for an unverified Caller.
255            return self.reject(RejectionReason::Rogue, hp);
256        }
257
258        let parsed = match handshake_sm::parse_peer_extensions(hp) {
259            Ok(p) => p,
260            Err(_) => return self.reject(RejectionReason::Rogue, hp),
261        };
262        let peer_msg = match parsed.hs_msg {
263            Some(m) => m,
264            None => return self.reject(RejectionReason::Rogue, hp),
265        };
266
267        self.peer_socket_id = hp.srt_socket_id;
268
269        // §6.1.5: the Listener (responder) requires the pre-shared
270        // passphrase to recover the SEK from the Caller's Key Material
271        // request; a mismatch in *either* direction (one side configured
272        // for encryption, the other not) is rejected as
273        // `RejectionReason::Unsecure` ("password required or unexpected",
274        // Table 7 code 1011) — a wrong passphrase (RFC 3394 wrap-integrity
275        // failure) is `RejectionReason::BadSecret` (code 1010) instead.
276        #[cfg(feature = "crypto")]
277        let crypto_cfg = self.config.crypto.clone();
278        #[cfg(feature = "crypto")]
279        type CryptoConclusionResult<'a> = (
280            Option<handshake_sm::RecoveredSek>,
281            Option<&'a crate::packet::KeyMaterial<'a>>,
282        );
283        #[cfg(feature = "crypto")]
284        let (crypto_result, km_echo_ext): CryptoConclusionResult<'_> =
285            match (&crypto_cfg, &parsed.km) {
286                (Some(crypto), Some(km_req)) => {
287                    match handshake_sm::recover_sek(&crypto.passphrase, km_req) {
288                        Ok((sek, salt)) => (Some((sek, salt)), Some(km_req)),
289                        Err(_) => return self.reject(RejectionReason::BadSecret, hp),
290                    }
291                }
292                (Some(_), None) | (None, Some(_)) => {
293                    return self.reject(RejectionReason::Unsecure, hp);
294                }
295                (None, None) => (None, None),
296            };
297
298        let negotiated = NegotiatedParams {
299            version: HANDSHAKE_VERSION_5,
300            flags: crate::packet::HandshakeExtensionMessageFlags(
301                self.config.flags.0 & peer_msg.srt_flags.0,
302            ),
303            latency: handshake_sm::negotiate_latency(self.config.latency, &peer_msg),
304            own_socket_id: self.own_socket_id,
305            peer_socket_id: self.peer_socket_id,
306            mtu: self.config.mtu.min(hp.mtu),
307            max_flow_window_size: self
308                .config
309                .max_flow_window_size
310                .min(hp.max_flow_window_size),
311            stream_id: parsed.stream_id,
312            group: parsed.group,
313            #[cfg(feature = "crypto")]
314            sek: crypto_result.as_ref().map(|(sek, _)| sek.clone()),
315            #[cfg(feature = "crypto")]
316            salt: crypto_result.as_ref().map(|(_, salt)| *salt),
317        };
318
319        let hs_msg = HsExtMessage {
320            srt_version: self.config.srt_version,
321            srt_flags: self.config.flags,
322            receiver_tsbpd_delay: self.config.latency,
323            sender_tsbpd_delay: self.config.latency,
324        };
325        // §4.3.1.2: the Listener's CONCLUSION response carries the HSv5
326        // extensions "without the cookie" — no Stream ID is echoed back
327        // (only the Caller advertises one; the Listener already knows it via
328        // `negotiated.stream_id`).
329        let ext_contents =
330            handshake_sm::ConclusionExtensionContents::new(hs_msg, None, self.config.group);
331        // §6.1.5: echo the Caller's Key Material back as confirmation.
332        #[cfg(feature = "crypto")]
333        let mut ext_contents = ext_contents;
334        #[cfg(feature = "crypto")]
335        if let Some(echo) = km_echo_ext {
336            ext_contents.set_key_material(
337                crate::packet::ExtensionType::KmRsp,
338                handshake_sm::echo_key_material_contents(hp, echo)?.into_owned(),
339            );
340        }
341        let (extensions, ext_flags) =
342            handshake_sm::build_conclusion_extensions(ExtensionType::HsRsp, &ext_contents);
343
344        let hp_out = HandshakePacket {
345            timestamp: SrtTimestamp::from_wire(self.clock.now()),
346            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
347            version: HANDSHAKE_VERSION_5,
348            encryption_field: self.config.encryption_field,
349            extension_field: HandshakeExtensionFlags(ext_flags),
350            initial_seq_number: self.config.initial_seq_number,
351            mtu: self.config.mtu,
352            max_flow_window_size: self.config.max_flow_window_size,
353            handshake_type: HandshakeType::Conclusion,
354            srt_socket_id: self.own_socket_id,
355            syn_cookie: 0, // §4.3.1.2: "without the cookie (which is not needed here)".
356            peer_ip: self.config.local_ip,
357            extensions,
358        };
359        let bytes = handshake_sm::build_bytes(hp_out)?;
360        self.retransmit.remember(&bytes);
361        self.negotiated = Some(negotiated.clone());
362        self.state = ListenerHandshakeState::Connected;
363        Ok(vec![
364            HandshakeOutput::Send(bytes),
365            HandshakeOutput::Connected(negotiated),
366        ])
367    }
368
369    /// Builds and returns a rejection handshake packet, transitioning to
370    /// [`ListenerHandshakeState::Rejected`].
371    fn reject(
372        &mut self,
373        reason: RejectionReason,
374        hp: &HandshakePacket<'_>,
375    ) -> Result<Vec<HandshakeOutput>> {
376        self.state = ListenerHandshakeState::Rejected;
377        let hp_out = HandshakePacket {
378            timestamp: SrtTimestamp::from_wire(self.clock.now()),
379            dest_socket_id: SocketId::from_wire(hp.srt_socket_id),
380            version: HANDSHAKE_VERSION_5,
381            encryption_field: EncryptionField::NoEncryption,
382            extension_field: HandshakeExtensionFlags(0),
383            initial_seq_number: 0,
384            mtu: self.config.mtu,
385            max_flow_window_size: self.config.max_flow_window_size,
386            handshake_type: reason.to_handshake_type(),
387            srt_socket_id: self.own_socket_id,
388            syn_cookie: 0,
389            peer_ip: self.config.local_ip,
390            extensions: HandshakeExtensions(Vec::new()),
391        };
392        let bytes = handshake_sm::build_bytes(hp_out)?;
393        self.retransmit.remember(&bytes);
394        Ok(vec![
395            HandshakeOutput::Send(bytes),
396            HandshakeOutput::Rejected(reason),
397        ])
398    }
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404    use crate::packet::handshake::HS_EXT_FLAG_HSREQ;
405
406    fn caller_induction(caller_id: u32) -> ControlPacket<'static> {
407        ControlPacket::Handshake(HandshakePacket {
408            timestamp: SrtTimestamp::ZERO,
409            dest_socket_id: SocketId::CONNECTION_REQUEST,
410            version: crate::handshake_sm::HANDSHAKE_VERSION_4,
411            encryption_field: EncryptionField::NoEncryption,
412            extension_field: HandshakeExtensionFlags(2),
413            initial_seq_number: 0,
414            mtu: 1500,
415            max_flow_window_size: 8192,
416            handshake_type: HandshakeType::Induction,
417            srt_socket_id: caller_id,
418            syn_cookie: 0,
419            peer_ip: [0; 4],
420            extensions: HandshakeExtensions(Vec::new()),
421        })
422    }
423
424    #[test]
425    fn induction_response_wire_values_match_draft_4_3_1_1() {
426        let mut l = ListenerHandshake::new(0x9999, 0xC0FF_EE00, HandshakeConfig::default());
427        let outputs = l.feed(&caller_induction(0x1234)).unwrap();
428        assert_eq!(outputs.len(), 1);
429        let bytes = match &outputs[0] {
430            HandshakeOutput::Send(b) => b.clone(),
431            other => panic!("expected Send, got {other:?}"),
432        };
433        let pkt = ControlPacket::parse(&bytes).unwrap();
434        match pkt {
435            ControlPacket::Handshake(hp) => {
436                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
437                assert_eq!(hp.extension_field.0, SRT_MAGIC_CODE);
438                assert_eq!(hp.handshake_type, HandshakeType::Induction);
439                assert_eq!(hp.srt_socket_id, 0x9999);
440                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
441                assert_eq!(hp.dest_socket_id, SocketId::from_wire(0x1234));
442            }
443            _ => panic!("expected handshake"),
444        }
445        assert_eq!(l.state(), ListenerHandshakeState::AwaitingConclusion);
446    }
447
448    fn caller_conclusion(
449        caller_id: u32,
450        listener_id: u32,
451        cookie: u32,
452        latency_ms: u16,
453    ) -> ControlPacket<'static> {
454        let hs_msg = HsExtMessage {
455            srt_version: 0x0105_0000,
456            srt_flags: crate::packet::HandshakeExtensionMessageFlags(0x6F),
457            receiver_tsbpd_delay: Duration::from_millis(u64::from(latency_ms)),
458            sender_tsbpd_delay: Duration::from_millis(u64::from(latency_ms)),
459        };
460        let ext = crate::packet::handshake::build_extension_block(
461            ExtensionType::HsReq,
462            &hs_msg.to_bytes(),
463        )
464        .unwrap();
465        let ext: &'static [u8] = Vec::leak(ext);
466        let ext = HandshakeExtensions::parse(ext).expect("test extension bytes");
467        ControlPacket::Handshake(HandshakePacket {
468            timestamp: SrtTimestamp::ZERO,
469            dest_socket_id: SocketId::from_wire(listener_id),
470            version: HANDSHAKE_VERSION_5,
471            encryption_field: EncryptionField::NoEncryption,
472            extension_field: HandshakeExtensionFlags(HS_EXT_FLAG_HSREQ),
473            initial_seq_number: 0,
474            mtu: 1500,
475            max_flow_window_size: 8192,
476            handshake_type: HandshakeType::Conclusion,
477            srt_socket_id: caller_id,
478            syn_cookie: cookie,
479            peer_ip: [0; 4],
480            extensions: ext,
481        })
482    }
483
484    #[test]
485    fn conclusion_bad_cookie_is_rejected() {
486        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
487        l.feed(&caller_induction(2)).unwrap();
488        let outputs = l.feed(&caller_conclusion(2, 1, 0xBAD_C00C, 120)).unwrap();
489        assert_eq!(outputs.len(), 2);
490        assert_eq!(
491            outputs[1],
492            HandshakeOutput::Rejected(RejectionReason::Rogue)
493        );
494        let bytes = match &outputs[0] {
495            HandshakeOutput::Send(b) => b,
496            other => panic!("expected Send, got {other:?}"),
497        };
498        let pkt = ControlPacket::parse(bytes).unwrap();
499        if let ControlPacket::Handshake(hp) = pkt {
500            assert_eq!(
501                hp.handshake_type,
502                RejectionReason::Rogue.to_handshake_type()
503            );
504        } else {
505            panic!("expected handshake");
506        }
507        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
508    }
509
510    #[test]
511    fn conclusion_version_mismatch_is_rejected() {
512        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
513        l.feed(&caller_induction(2)).unwrap();
514        let mut bad = caller_conclusion(2, 1, 0xC0FF_EE00, 120);
515        if let ControlPacket::Handshake(hp) = &mut bad {
516            hp.version = 4;
517        }
518        let outputs = l.feed(&bad).unwrap();
519        assert_eq!(
520            outputs[1],
521            HandshakeOutput::Rejected(RejectionReason::Version)
522        );
523        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
524    }
525
526    #[test]
527    fn conclusion_malformed_extension_is_rejected_not_panicking() {
528        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
529        l.feed(&caller_induction(2)).unwrap();
530        // An extension block whose contents are not a Handshake Extension
531        // Message — must reject cleanly, not panic.
532        let ext: &'static [u8] = &[0x00, 0x01, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF];
533        let bad = ControlPacket::Handshake(HandshakePacket {
534            timestamp: SrtTimestamp::ZERO,
535            dest_socket_id: SocketId::from_wire(1),
536            version: HANDSHAKE_VERSION_5,
537            encryption_field: EncryptionField::NoEncryption,
538            extension_field: HandshakeExtensionFlags(HS_EXT_FLAG_HSREQ),
539            initial_seq_number: 0,
540            mtu: 1500,
541            max_flow_window_size: 8192,
542            handshake_type: HandshakeType::Conclusion,
543            srt_socket_id: 2,
544            syn_cookie: 0xC0FF_EE00,
545            peer_ip: [0; 4],
546            extensions: HandshakeExtensions::parse(ext).expect("test extension bytes"),
547        });
548        let outputs = l.feed(&bad).unwrap();
549        assert_eq!(
550            outputs[1],
551            HandshakeOutput::Rejected(RejectionReason::Rogue)
552        );
553        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
554    }
555
556    #[test]
557    fn successful_conclusion_reaches_connected() {
558        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
559        l.feed(&caller_induction(2)).unwrap();
560        let outputs = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
561        assert_eq!(outputs.len(), 2);
562        assert!(matches!(outputs[0], HandshakeOutput::Send(_)));
563        assert!(matches!(outputs[1], HandshakeOutput::Connected(_)));
564        assert_eq!(l.state(), ListenerHandshakeState::Connected);
565        assert!(l.negotiated().is_some());
566    }
567
568    #[test]
569    fn feed_before_induction_seen_still_requires_induction_first() {
570        let mut l = ListenerHandshake::new(1, 1, HandshakeConfig::default());
571        let outputs = l.feed(&caller_induction(2));
572        assert!(outputs.is_ok());
573    }
574
575    fn conclusion_response_bytes(outputs: &[HandshakeOutput]) -> Vec<u8> {
576        match &outputs[0] {
577            HandshakeOutput::Send(b) => b.clone(),
578            other => panic!("expected Send, got {other:?}"),
579        }
580    }
581
582    /// r08-SRT-W5: a duplicate CONCLUSION from the connected Caller (its
583    /// response was lost) is answered with the identical response bytes.
584    #[test]
585    fn duplicate_conclusion_after_connected_is_reanswered() {
586        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
587        l.feed(&caller_induction(2)).unwrap();
588        let first = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
589        let original = conclusion_response_bytes(&first);
590        assert_eq!(l.state(), ListenerHandshakeState::Connected);
591
592        let again = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
593        assert_eq!(again, vec![HandshakeOutput::Send(original.clone())]);
594        // And again: it is stateless on the Listener side.
595        let third = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
596        assert_eq!(third, vec![HandshakeOutput::Send(original)]);
597        assert_eq!(l.state(), ListenerHandshakeState::Connected);
598    }
599
600    /// Only the connected peer (its Socket ID and the cookie) is re-answered:
601    /// another Caller's CONCLUSION, or one with a wrong cookie, is still
602    /// out-of-sequence — never an oracle for the response bytes.
603    #[test]
604    fn conclusion_from_a_stranger_after_connected_is_not_answered() {
605        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
606        l.feed(&caller_induction(2)).unwrap();
607        l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
608        // A different Caller Socket ID.
609        assert!(matches!(
610            l.feed(&caller_conclusion(3, 1, 0xC0FF_EE00, 120)),
611            Err(Error::HandshakeOutOfSequence { .. })
612        ));
613        // The right Socket ID but a wrong cookie.
614        assert!(matches!(
615            l.feed(&caller_conclusion(2, 1, 0xBAD0_BAD0, 120)),
616            Err(Error::HandshakeOutOfSequence { .. })
617        ));
618        // An INDUCTION after Connected is not answered either.
619        assert!(matches!(
620            l.feed(&caller_induction(2)),
621            Err(Error::HandshakeOutOfSequence { .. })
622        ));
623        assert_eq!(l.state(), ListenerHandshakeState::Connected);
624    }
625
626    /// r08-SRT-W10 (Listener side): a repeated INDUCTION while awaiting the
627    /// CONCLUSION re-sends the same INDUCTION response rather than rejecting
628    /// the Caller as Rogue and abandoning the handshake.
629    #[test]
630    fn repeated_induction_while_awaiting_conclusion_is_reanswered() {
631        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
632        let first = l.feed(&caller_induction(2)).unwrap();
633        let again = l.feed(&caller_induction(2)).unwrap();
634        assert_eq!(again, first);
635        assert_eq!(l.state(), ListenerHandshakeState::AwaitingConclusion);
636        // The handshake still completes afterwards.
637        let done = l.feed(&caller_conclusion(2, 1, 0xC0FF_EE00, 120)).unwrap();
638        assert!(
639            done.iter()
640                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
641        );
642    }
643
644    fn with_limits(
645        mut pkt: ControlPacket<'static>,
646        mtu: u32,
647        mfw: u32,
648        isn: u32,
649    ) -> ControlPacket<'static> {
650        if let ControlPacket::Handshake(hp) = &mut pkt {
651            hp.mtu = mtu;
652            hp.max_flow_window_size = mfw;
653            hp.initial_seq_number = isn;
654        }
655        pkt
656    }
657
658    /// §3.2.1: the connection runs with the smaller of the two sides' MTU and
659    /// Maximum Flow Window Size, whichever side is smaller.
660    #[test]
661    fn negotiated_mtu_and_flow_window_are_the_smaller_of_both() {
662        for (peer_mtu, peer_mfw, want_mtu, want_mfw) in [
663            (576, 64, 576, 64),
664            (9000, 65_536, 1500, 8192),
665            (1500, 64, 1500, 64),
666        ] {
667            let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
668            l.feed(&caller_induction(2)).unwrap();
669            l.feed(&with_limits(
670                caller_conclusion(2, 1, 0xC0FF_EE00, 120),
671                peer_mtu,
672                peer_mfw,
673                0,
674            ))
675            .unwrap();
676            let n = l.negotiated().expect("connected");
677            assert_eq!((n.mtu, n.max_flow_window_size), (want_mtu, want_mfw));
678        }
679    }
680
681    /// A peer ISN that is not a 31-bit sequence number is refused outright
682    /// (it would seed `next_expected` out of range and stall forever).
683    #[test]
684    fn an_isn_wider_than_31_bits_is_rejected() {
685        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
686        let out = l
687            .feed(&with_limits(caller_induction(2), 1500, 8192, 0x8000_0000))
688            .unwrap();
689        assert!(matches!(
690            out.last(),
691            Some(HandshakeOutput::Rejected(RejectionReason::Rogue))
692        ));
693        assert_eq!(l.state(), ListenerHandshakeState::Rejected);
694
695        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
696        l.feed(&caller_induction(2)).unwrap();
697        let out = l
698            .feed(&with_limits(
699                caller_conclusion(2, 1, 0xC0FF_EE00, 120),
700                1500,
701                8192,
702                u32::MAX,
703            ))
704            .unwrap();
705        assert!(matches!(
706            out.last(),
707            Some(HandshakeOutput::Rejected(RejectionReason::Rogue))
708        ));
709        // The largest legal ISN is fine.
710        let mut l = ListenerHandshake::new(1, 0xC0FF_EE00, HandshakeConfig::default());
711        let out = l
712            .feed(&with_limits(caller_induction(2), 1500, 8192, 0x7FFF_FFFF))
713            .unwrap();
714        assert!(matches!(out[0], HandshakeOutput::Send(_)));
715    }
716}