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