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