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