Skip to main content

srt_runtime/
rendezvous.rs

1//! Rendezvous handshake engine — `draft-sharabayko-srt-01` §4.3.2 (Rendezvous
2//! Handshake), curated at `private/specs-verified/rules/srt-rendezvous.md`. Line cites below
3//! (`LNNNN`) are the source draft's line numbers, exactly as recorded in that
4//! curation.
5//!
6//! [`RendezvousHandshake`] is symmetric: both peers run the *same* engine
7//! (unlike [`crate::caller::CallerHandshake`] / [`crate::listener::ListenerHandshake`],
8//! which run different code for different roles). Which of the two logical
9//! roles — **Initiator** or **Responder** — a given instance ends up playing
10//! is decided at runtime by the **cookie contest** (§4.3.2, L2107-2135):
11//! each side supplies its own 32-bit cookie to [`RendezvousHandshake::new`]
12//! (this crate never reads a clock or a socket address — see
13//! [`crate::handshake_sm::derive_cookie`] for a ready-made, non-standardized
14//! derivation helper, exactly as for [`crate::listener::ListenerHandshake`]),
15//! and the greater cookie value wins ("becomes Initiator", L2133-2135).
16//!
17//! # State machine
18//!
19//! States are named exactly as the draft's Parallel Handshake Flow diagram
20//! (§4.3.2.2, L2280, quoted verbatim): **Waving → Attention → Initiated →
21//! Connected** (plus `Idle` before [`RendezvousHandshake::start`] is called —
22//! not spec-named, mirrors [`crate::caller::CallerHandshakeState::Idle`] — and
23//! `Rejected`/`TimedOut` terminal states, also not spec-named). Every
24//! transition below is the Initiator table (L2301-2334) or Responder table
25//! (L2336-2382), or a missing-packet recovery rule (L2383-2432).
26//!
27//! ## Serial vs Parallel flow: one engine, not two
28//!
29//! The draft narrates two "flows" (§4.3.2.1 Serial, L2140-2269; §4.3.2.2
30//! Parallel, L2270-2432) that differ only in *message interleaving*, not in
31//! any new transition rule: the Parallel flow's Initiator/Responder tables are
32//! complete state × received-message tables, driven purely by message
33//! content — so they already cover the Serial flow's crossing case. That case
34//! is: a peer still in `Waving` (having sent its own WAVEAHAND but never
35//! having received the other side's) receives a **CONCLUSION** directly
36//! instead of a WAVEAHAND (§4.3.2.1 step 3, L2203-2219 — the draft calls the
37//! resulting state "fine"). Tracing the draft's own worked example confirms
38//! the action taken is identical to applying the Parallel Attention row to
39//! that CONCLUSION: an Initiator receiving an extension-less CONCLUSION here
40//! behaves exactly like the Initiator-Attention-row "no extensions" case
41//! (L2312-2318); a Responder receiving a CONCLUSION+HSREQ here behaves
42//! exactly like the Responder-Attention-row HSREQ case (L2360-2364) — because
43//! by this point in the exchange the peer's role-appropriate first CONCLUSION
44//! already carries whatever extension its role dictates (Initiator: HSREQ
45//! immediately, L2286-2287; Responder: none until it has seen HSREQ,
46//! L2357-2360/L2287-2288). This implementation therefore has **no separate
47//! "Fine" state** — a received CONCLUSION while still in `Waving` dispatches
48//! straight into the same Attention-row logic used when genuinely in
49//! `Attention`, rather than inventing a fourth, behaviourally-divergent state
50//! the tables do not define.
51//!
52//! ## Resolved ambiguities (not explicit in the curated rules)
53//!
54//! - **Cookie collision → rejection.** The draft says only "the connection
55//!   will not be made until new, unique cookies are generated" (L2119-2124),
56//!   describing an out-of-band retry, not a wire action. This engine surfaces
57//!   it as [`RejectionReason::RdvCookie`] (Table 7 code `1009`, "rendezvous
58//!   cookie collision" — an exact fit) rather than blocking or retrying
59//!   internally; a driver that wants the "regenerate and retry" behaviour
60//!   builds a fresh [`RendezvousHandshake`] with a new cookie.
61//! - **CONCLUSION `SYN Cookie` field.** The draft specifies WAVEAHAND's SYN
62//!   Cookie (L2156-2165) but not what later CONCLUSION/AGREEMENT messages
63//!   carry in that field. Every message this engine sends after WAVEAHAND
64//!   continues to carry *this side's own* cookie (never an echo of the peer's,
65//!   unlike the Caller-Listener flood-protection cookie) — consistent with
66//!   the cookie's role here being mutual identification/contest, not a
67//!   flood-protection echo-token.
68//! - **No Stream ID / Group Membership exchange.** Neither extension is
69//!   mentioned anywhere in §4.3.2; unlike
70//!   [`crate::handshake_sm::NegotiatedParams`] from the Caller-Listener flow,
71//!   this engine never sends them and always reports `stream_id: None`,
72//!   `group: None` — flagged rather than fabricated.
73//! - **Latency/flags reconciliation.** §4.3.2 does not restate the
74//!   greater-latency / AND-flags rule from §4.3.1.2, but it is a property of
75//!   the Handshake Extension Message itself (§3.2.1.1), not of the flow that
76//!   carried it, so the same shared `handshake_sm` reconciliation helper used
77//!   by the Caller-Listener flow is reused unchanged.
78//! - **Duplicate WAVEAHAND while already `Attention`.** Not covered by either
79//!   table (which only fire on the *first* WAVEAHAND). Treated as a benign
80//!   duplicate: resend the last message, no state change.
81//! - **Recovery rule 3 (data packet promotes a stuck Responder, L2413-2422)**
82//!   is exposed as [`RendezvousHandshake::on_recovery_trigger`], since this
83//!   engine's `feed` takes a [`ControlPacket`] (matching
84//!   [`crate::caller::CallerHandshake`] / [`crate::listener::ListenerHandshake`]),
85//!   not the data-plane [`crate::packet::SrtPacket`]; a driver that receives a
86//!   `SrtPacket::Data` (or any Control packet normally only sent between
87//!   connected parties — [`RendezvousHandshake::feed`] already treats any
88//!   *inbound* non-Handshake `ControlPacket` this way for exactly this
89//!   reason) calls it directly.
90//!
91//! Explicit non-goals of THIS module (the sans-IO engine): ARQ/loss, TSBPD
92//! delivery, congestion control, AES key-wrap/unwrap crypto, and the Version-4
93//! legacy Rendezvous path (L2101-2105, out of
94//! scope of the draft excerpt this crate implements against). The `tokio`
95//! socket adapter drives this engine as `io::SrtSocket::rendezvous`.
96
97use alloc::vec;
98use alloc::vec::Vec;
99use broadcast_common::error::InvalidField;
100
101use crate::error::{Error, Result};
102use crate::handshake_sm::{
103    self, HANDSHAKE_VERSION_5, HandshakeConfig, HandshakeOutput, NegotiatedParams, RejectionReason,
104    Retransmit, RetransmitStep, WireClock,
105};
106use crate::packet::{
107    ControlPacket, EncryptionField, ExtensionType, HandshakeExtensionFlags,
108    HandshakeExtensionMessageFlags, HandshakeExtensions, HandshakePacket, HandshakeType,
109    HsExtMessage,
110};
111
112/// Rendezvous handshake lifecycle state (`draft-sharabayko-srt-01` §4.3.2).
113/// State names are exactly the Parallel Handshake Flow diagram (§4.3.2.2,
114/// L2280): `Waving -> Attention -> Initiated -> Connected`. See the module
115/// doc "Serial vs Parallel flow" note for why there is no separate state for
116/// the Serial flow's "fine".
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118#[cfg_attr(feature = "serde", derive(serde::Serialize))]
119#[non_exhaustive]
120pub enum RendezvousHandshakeState {
121    /// No handshake message sent yet. Not spec-named — mirrors
122    /// [`crate::caller::CallerHandshakeState::Idle`].
123    Idle,
124    /// L2100/L2153/L2280 "waving"/"Waving": both parties' initial state.
125    Waving,
126    /// L2172/L2280 "attention"/"Attention": a WAVEAHAND was received, the
127    /// cookie contest is resolved, awaiting the peer's CONCLUSION.
128    Attention,
129    /// L2234/L2280 "initiated"/"Initiated": role-appropriate extension
130    /// content has been seen at least once; awaiting the peer's confirmation.
131    Initiated,
132    /// L2224/L2251/L2280 "connected"/"Connected": the handshake completed;
133    /// [`NegotiatedParams`] are available.
134    Connected,
135    /// The handshake was rejected (locally, or by an explicit peer Table 7
136    /// code). Not spec-named.
137    Rejected,
138    /// No response arrived after the configured retry budget. Not spec-named.
139    TimedOut,
140}
141
142impl RendezvousHandshakeState {
143    /// A short label for this state.
144    pub fn name(&self) -> &'static str {
145        match self {
146            RendezvousHandshakeState::Idle => "Idle",
147            RendezvousHandshakeState::Waving => "Waving",
148            RendezvousHandshakeState::Attention => "Attention",
149            RendezvousHandshakeState::Initiated => "Initiated",
150            RendezvousHandshakeState::Connected => "Connected",
151            RendezvousHandshakeState::Rejected => "Rejected",
152            RendezvousHandshakeState::TimedOut => "TimedOut",
153        }
154    }
155}
156
157broadcast_common::impl_spec_display!(RendezvousHandshakeState);
158
159/// The role a [`RendezvousHandshake`] plays, resolved by the cookie contest
160/// (`draft-sharabayko-srt-01` §4.3.2, L2107-2135): "When one party's cookie
161/// value is greater than its peer's, it wins the cookie contest and becomes
162/// Initiator (the other party becomes the Responder)."
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
164#[cfg_attr(feature = "serde", derive(serde::Serialize))]
165#[non_exhaustive]
166pub enum RendezvousRole {
167    /// Wins the cookie contest (the greater cookie value, L2133-2135). MUST
168    /// attach the HSREQ extension (L2286-2287).
169    Initiator,
170    /// Loses the cookie contest. MUST attach the HSRSP extension
171    /// (L2287-2288).
172    Responder,
173}
174
175impl RendezvousRole {
176    /// A short label for this role.
177    pub fn name(&self) -> &'static str {
178        match self {
179            RendezvousRole::Initiator => "Initiator",
180            RendezvousRole::Responder => "Responder",
181        }
182    }
183}
184
185broadcast_common::impl_spec_display!(RendezvousRole);
186
187/// Bit 31 (the sign bit of a 32-bit value), used to test the sign of a
188/// 32-bit quantity carried in a wider (`i64`) type without it having been
189/// sign-extended into that width — see [`cookie_contest`].
190const SIGN_BIT_32: i64 = 0x8000_0000;
191
192/// The cookie contest tie-break (issue #1064): given two cookies (this
193/// side's and the peer's, both already known not to be equal — see
194/// [`RendezvousHandshake::resolve_role`]), decide which side is
195/// [`RendezvousRole::Initiator`].
196///
197/// A direct port of libsrt's own `CUDT::backwardCompatibleCookieContest`
198/// (`srtcore/core.cpp`, v1.5.5, as published at
199/// <https://github.com/Haivision/srt/blob/v1.5.5/srtcore/core.cpp#L4262-L4286>):
200///
201/// ```c
202/// enum HandshakeSide srt::CUDT::backwardCompatibleCookieContest(int32_t req, int32_t res)
203/// {
204///     const int64_t xreq = int64_t(req);
205///     const int64_t xres = int64_t(res);
206///     const int64_t contest = xreq - xres;
207///
208///     if ((contest & 0xFFFFFFFF) == 0)
209///     {
210///         return HSD_DRAW;
211///     }
212///     if (contest & 0x80000000)
213///     {
214///         const int64_t revert = xres - xreq;
215///         if (revert & 0x80000000 && req > res)
216///             return HSD_INITIATOR;
217///         return HSD_RESPONDER;
218///     }
219///
220///     return HSD_INITIATOR;
221/// }
222/// ```
223///
224/// `req`/`res` there are `int32_t` — the raw cookie bit pattern *reinterpreted
225/// as signed* — and `xreq`/`xres` sign-*extend* that signed value into
226/// `int64_t` (so a cookie with the top bit set becomes a large-magnitude
227/// *negative* `i64`, not the same positive value an unsigned widen would
228/// give). This is why a plain unsigned `own_cookie > peer_cookie` compare
229/// (this function's pre-fix behavior) disagrees with libsrt for roughly a
230/// quarter of all cookie pairs: whenever exactly one of the two cookies has
231/// its top bit set, the sign-extending widen and the unsigned widen order
232/// the pair differently.
233///
234/// The `HSD_DRAW` arm is unreachable here (the caller already handles
235/// `own_cookie == peer_cookie` before this is called) and is not
236/// reproduced — this function always returns a role.
237fn cookie_contest(own_cookie: u32, peer_cookie: u32) -> RendezvousRole {
238    // libsrt reads each cookie as a signed 32-bit integer: the same bits,
239    // reinterpreted (not converted).
240    let req = i32::from_ne_bytes(own_cookie.to_ne_bytes());
241    let res = i32::from_ne_bytes(peer_cookie.to_ne_bytes());
242    let xreq = i64::from(req);
243    let xres = i64::from(res);
244    let contest = xreq - xres;
245
246    if contest & SIGN_BIT_32 != 0 {
247        let revert = xres - xreq;
248        if revert & SIGN_BIT_32 != 0 && req > res {
249            return RendezvousRole::Initiator;
250        }
251        return RendezvousRole::Responder;
252    }
253
254    RendezvousRole::Initiator
255}
256
257/// The Handshake Extension content found on one received CONCLUSION, keyed by
258/// which side sends which (§4.3.2.2, L2282-2288). Internal to this module —
259/// [`crate::handshake_sm::parse_peer_extensions`] does not distinguish
260/// HSREQ from HSRSP, which the Rendezvous tables need to.
261enum PeerHsExt {
262    /// No Handshake Extension block present.
263    None,
264    /// An `HSREQ` block was present (only an Initiator sends this).
265    HsReq(HsExtMessage),
266    /// An `HSRSP` block was present (only a Responder sends this).
267    HsRsp(HsExtMessage),
268}
269
270/// Walks `hp`'s extension blocks looking for an HSREQ or HSRSP Handshake
271/// Extension Message. Returns [`Error::InvalidField`] on any malformed block
272/// or malformed HSREQ/HSRSP contents — never panics on untrusted input.
273fn parse_peer_hs_ext(hp: &HandshakePacket<'_>) -> Result<PeerHsExt> {
274    let mut found = PeerHsExt::None;
275    for block in hp.extensions.iter() {
276        let block = block.map_err(|_| {
277            Error::InvalidField(InvalidField {
278                field: "rendezvous handshake extensions",
279                reason: "malformed extension block",
280            })
281        })?;
282        match block.ext_type {
283            ExtensionType::HsReq => {
284                let msg = block.as_hs_ext_message().map_err(|_| {
285                    Error::InvalidField(InvalidField {
286                        field: "HSREQ extension message",
287                        reason: "malformed contents",
288                    })
289                })?;
290                found = PeerHsExt::HsReq(msg);
291            }
292            ExtensionType::HsRsp => {
293                let msg = block.as_hs_ext_message().map_err(|_| {
294                    Error::InvalidField(InvalidField {
295                        field: "HSRSP extension message",
296                        reason: "malformed contents",
297                    })
298                })?;
299                found = PeerHsExt::HsRsp(msg);
300            }
301            _ => {}
302        }
303    }
304    Ok(found)
305}
306
307/// A driveable, symmetric SRT Rendezvous handshake
308/// (`draft-sharabayko-srt-01` §4.3.2). See the module docs for the state
309/// machine and the design decisions not explicit in the curated rules.
310#[derive(Debug)]
311pub struct RendezvousHandshake {
312    own_socket_id: u32,
313    own_cookie: u32,
314    config: HandshakeConfig,
315    state: RendezvousHandshakeState,
316    role: Option<RendezvousRole>,
317    peer_socket_id: u32,
318    peer_cookie: u32,
319    peer_hs_msg: Option<HsExtMessage>,
320    /// The peer's `MTU` and `Maximum Flow Window Size` (§3.2.1), from the
321    /// packet that carried its Handshake Extension Message.
322    peer_limits: Option<(u32, u32)>,
323    retransmit: Retransmit,
324    clock: WireClock,
325    negotiated: Option<NegotiatedParams>,
326    #[cfg(feature = "crypto")]
327    crypto_recovered: Option<handshake_sm::RecoveredSek>,
328    #[cfg(feature = "crypto")]
329    km_echo_ext: Option<Vec<u8>>,
330    #[cfg(feature = "crypto")]
331    crypto_verified: bool,
332}
333
334impl RendezvousHandshake {
335    /// Creates a fresh Rendezvous handshake in
336    /// [`RendezvousHandshakeState::Idle`], with the 32-bit cookie this side
337    /// will offer in the cookie contest (§4.3.2, L2107-2135). This crate never
338    /// reads a clock or a socket address — see
339    /// [`crate::handshake_sm::derive_cookie`] for a ready-made,
340    /// non-standardized derivation helper.
341    pub fn new(own_socket_id: u32, own_cookie: u32, config: HandshakeConfig) -> Self {
342        RendezvousHandshake {
343            own_socket_id,
344            own_cookie,
345            config,
346            state: RendezvousHandshakeState::Idle,
347            role: None,
348            peer_socket_id: 0,
349            peer_cookie: 0,
350            peer_hs_msg: None,
351            peer_limits: None,
352            retransmit: Retransmit::default(),
353            clock: WireClock::default(),
354            negotiated: None,
355            #[cfg(feature = "crypto")]
356            crypto_recovered: None,
357            #[cfg(feature = "crypto")]
358            km_echo_ext: None,
359            #[cfg(feature = "crypto")]
360            crypto_verified: false,
361        }
362    }
363
364    /// Sets the time elapsed since the connection started; every packet built
365    /// from here on carries it as its wire timestamp (§3.2.1). The machine reads
366    /// no clock, so the driver calls this before each `start`, `feed` and `tick`.
367    pub fn set_elapsed(&mut self, elapsed: core::time::Duration) {
368        self.clock.set(elapsed);
369    }
370
371    /// The current state.
372    pub fn state(&self) -> RendezvousHandshakeState {
373        self.state
374    }
375
376    /// The role resolved by the cookie contest, once past
377    /// [`RendezvousHandshakeState::Waving`].
378    pub fn role(&self) -> Option<RendezvousRole> {
379        self.role
380    }
381
382    /// The negotiated parameters, once [`RendezvousHandshakeState::Connected`].
383    pub fn negotiated(&self) -> Option<&NegotiatedParams> {
384        self.negotiated.as_ref()
385    }
386
387    /// Builds the initial WAVEAHAND handshake (§4.3.2, L2100/L2153-2170:
388    /// Version 5, this side's own cookie, no extensions) and transitions to
389    /// [`RendezvousHandshakeState::Waving`].
390    ///
391    /// # Errors
392    /// [`Error::HandshakeOutOfSequence`] if called more than once.
393    pub fn start(&mut self) -> Result<Vec<u8>> {
394        if self.state != RendezvousHandshakeState::Idle {
395            return Err(Error::HandshakeOutOfSequence {
396                state: self.state.name(),
397                reason: "start() called after the handshake already began",
398            });
399        }
400        let hp = HandshakePacket {
401            timestamp: self.clock.now(),
402            dest_socket_id: 0, // Unknown yet — mirrors CallerHandshake::start's INDUCTION.
403            version: HANDSHAKE_VERSION_5,
404            encryption_field: self.config.encryption_field,
405            extension_field: HandshakeExtensionFlags(0),
406            initial_seq_number: self.config.initial_seq_number,
407            mtu: self.config.mtu,
408            max_flow_window_size: self.config.max_flow_window_size,
409            handshake_type: HandshakeType::Wavehand,
410            srt_socket_id: self.own_socket_id,
411            syn_cookie: self.own_cookie,
412            peer_ip: self.config.local_ip,
413            extensions: HandshakeExtensions(&[]),
414        };
415        let bytes = handshake_sm::build_bytes(hp)?;
416        self.retransmit.arm(&bytes);
417        self.state = RendezvousHandshakeState::Waving;
418        Ok(bytes)
419    }
420
421    /// Feeds an inbound control packet.
422    ///
423    /// A non-Handshake `ControlPacket` fed while this side is a Responder
424    /// stuck in [`RendezvousHandshakeState::Initiated`] is treated as
425    /// missing-packet recovery rule 3 (L2413-2422: "any control packet
426    /// normally only sent between connected parties") rather than an error —
427    /// see [`Self::on_recovery_trigger`] for the data-packet analogue.
428    ///
429    /// # Errors
430    /// [`Error::UnexpectedControlPacket`] for a non-Handshake packet outside
431    /// that one recovery case; [`Error::HandshakeOutOfSequence`] if fed before
432    /// [`Self::start`] or after a terminal state (a driver bug, not a peer
433    /// protocol failure).
434    pub fn feed(&mut self, packet: &ControlPacket<'_>) -> Result<Vec<HandshakeOutput>> {
435        let hp = match packet {
436            ControlPacket::Handshake(hp) => hp,
437            other => {
438                if self.state == RendezvousHandshakeState::Initiated
439                    && self.role == Some(RendezvousRole::Responder)
440                {
441                    return self.enter_connected();
442                }
443                return Err(Error::UnexpectedControlPacket {
444                    actual: other.control_type().name(),
445                });
446            }
447        };
448        if let Some(reason) = RejectionReason::from_handshake_type(hp.handshake_type) {
449            return Ok(self.reject(reason));
450        }
451        if hp.version != HANDSHAKE_VERSION_5 {
452            // §4.3.2, L2101-2105: Version-4 legacy Rendezvous is out of scope.
453            return Ok(self.reject(RejectionReason::Version));
454        }
455        if (hp.initial_seq_number > crate::packet::SEQ_NUMBER_MASK
456            || hp.mtu == 0
457            || hp.max_flow_window_size == 0)
458            && self.state != RendezvousHandshakeState::Idle
459        {
460            return Ok(self.reject(RejectionReason::Rogue));
461        }
462        match self.state {
463            RendezvousHandshakeState::Idle => Err(Error::HandshakeOutOfSequence {
464                state: self.state.name(),
465                reason: "feed() called before start()",
466            }),
467            RendezvousHandshakeState::Waving => self.on_waving(hp),
468            RendezvousHandshakeState::Attention => self.on_attention(hp),
469            RendezvousHandshakeState::Initiated => self.on_initiated(hp),
470            RendezvousHandshakeState::Connected => self.on_connected(hp),
471            RendezvousHandshakeState::Rejected | RendezvousHandshakeState::TimedOut => {
472                Err(Error::HandshakeOutOfSequence {
473                    state: self.state.name(),
474                    reason: "handshake already reached a terminal state",
475                })
476            }
477        }
478    }
479
480    /// Convenience wrapper: parses `bytes` as a [`ControlPacket`] then
481    /// [`Self::feed`]s it.
482    pub fn feed_bytes(&mut self, bytes: &[u8]) -> Result<Vec<HandshakeOutput>> {
483        let packet = ControlPacket::parse(bytes)?;
484        self.feed(&packet)
485    }
486
487    /// Missing-packet recovery rule 3 (§4.3.2.2, L2413-2422): call this when
488    /// the driver receives a data packet (`SrtPacket::Data`) while this side
489    /// has not yet reached [`RendezvousHandshakeState::Connected`]. A no-op
490    /// (`Ok(Vec::new())`) unless this side is a Responder stuck in
491    /// [`RendezvousHandshakeState::Initiated`] — the one case the draft says
492    /// is "exceptionally allowed" to promote to Connected "as if it had
493    /// received AGREEMENT".
494    pub fn on_recovery_trigger(&mut self) -> Result<Vec<HandshakeOutput>> {
495        if self.state == RendezvousHandshakeState::Initiated
496            && self.role == Some(RendezvousRole::Responder)
497        {
498            self.enter_connected()
499        } else {
500            Ok(Vec::new())
501        }
502    }
503
504    /// Advances retransmit timing by one caller-defined tick, mirroring
505    /// [`crate::caller::CallerHandshake::tick`] /
506    /// [`crate::listener::ListenerHandshake::tick`].
507    pub fn tick(&mut self) -> Vec<HandshakeOutput> {
508        if matches!(
509            self.state,
510            RendezvousHandshakeState::Idle
511                | RendezvousHandshakeState::Connected
512                | RendezvousHandshakeState::Rejected
513                | RendezvousHandshakeState::TimedOut
514        ) {
515            return Vec::new();
516        }
517        let step = self.retransmit.tick(&self.config);
518        if matches!(step, RetransmitStep::TimedOut) {
519            self.state = RendezvousHandshakeState::TimedOut;
520        }
521        step.into_outputs()
522    }
523
524    /// [`RendezvousHandshakeState::Waving`]: the first message ever received
525    /// from the peer — either a genuine WAVEAHAND (§4.3.2.2 Waving row,
526    /// L2301-2306 Initiator / L2336-2342 Responder) or, in the Serial flow's
527    /// crossing case, a CONCLUSION directly (see module docs). Either way the
528    /// cookie contest is resolved here, from `hp.syn_cookie`.
529    fn on_waving(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
530        if !matches!(
531            hp.handshake_type,
532            HandshakeType::Wavehand | HandshakeType::Conclusion
533        ) {
534            return Ok(self.reject(RejectionReason::Rogue));
535        }
536        self.peer_socket_id = hp.srt_socket_id;
537        let role = match self.resolve_role(hp.syn_cookie) {
538            Ok(r) => r,
539            Err(_) => return Ok(self.reject(RejectionReason::RdvCookie)),
540        };
541        self.peer_cookie = hp.syn_cookie;
542        self.role = Some(role);
543
544        if hp.handshake_type == HandshakeType::Wavehand {
545            self.state = RendezvousHandshakeState::Attention;
546            match role {
547                // Initiator Waving row (L2301-2306): send CONCLUSION+HSREQ.
548                RendezvousRole::Initiator => self.send_conclusion(Some(ExtensionType::HsReq)),
549                // Responder Waving row (L2336-2342): send CONCLUSION, no
550                // extensions (it has not seen the peer's HSREQ yet).
551                RendezvousRole::Responder => self.send_conclusion(None),
552            }
553        } else {
554            // Serial-flow crossing (§4.3.2.1 step 3, L2203-2219): apply the
555            // same content-driven Attention-row logic (module docs).
556            self.on_attention_conclusion(hp, role)
557        }
558    }
559
560    /// [`RendezvousHandshakeState::Attention`]: a WAVEAHAND was already seen
561    /// and processed; only a CONCLUSION (Attention row) or a duplicate
562    /// WAVEAHAND (not covered by either table — treated as a benign resend,
563    /// module docs) is expected here.
564    fn on_attention(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
565        let role = self.role.ok_or(Error::HandshakeOutOfSequence {
566            state: self.state.name(),
567            reason: "no role was resolved before the Attention state",
568        })?;
569        if hp.handshake_type == HandshakeType::Conclusion {
570            return self.on_attention_conclusion(hp, role);
571        }
572        if hp.handshake_type == HandshakeType::Wavehand {
573            return Ok(self.resend());
574        }
575        Ok(self.reject(RejectionReason::Rogue))
576    }
577
578    /// The Attention row's CONCLUSION-handling logic (§4.3.2.2, L2307-2320
579    /// Initiator / L2343-2364 Responder), shared between a genuine
580    /// [`RendezvousHandshakeState::Attention`] and the Serial-flow crossing
581    /// case fed straight from [`RendezvousHandshakeState::Waving`].
582    fn on_attention_conclusion(
583        &mut self,
584        hp: &HandshakePacket<'_>,
585        role: RendezvousRole,
586    ) -> Result<Vec<HandshakeOutput>> {
587        self.peer_socket_id = hp.srt_socket_id;
588        let ext = match parse_peer_hs_ext(hp) {
589            Ok(e) => e,
590            Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
591        };
592        match (role, ext) {
593            (RendezvousRole::Initiator, PeerHsExt::None) => {
594                // L2312-2318: no extensions -> Initiated, still send
595                // CONCLUSION+HSREQ.
596                self.state = RendezvousHandshakeState::Initiated;
597                self.send_conclusion(Some(ExtensionType::HsReq))
598            }
599            (RendezvousRole::Initiator, PeerHsExt::HsRsp(msg)) => {
600                // L2318-2320: contains HSRSP -> Connected, send AGREEMENT.
601                self.peer_hs_msg = Some(msg);
602                self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
603                #[cfg(feature = "crypto")]
604                {
605                    let parsed = match handshake_sm::parse_peer_extensions(hp) {
606                        Ok(p) => p,
607                        Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
608                    };
609                    match (&self.config.crypto, parsed.km) {
610                        (Some(crypto), Some(km)) => {
611                            if !handshake_sm::verify_km_echo(crypto, &km) {
612                                return Ok(self.reject(RejectionReason::BadSecret));
613                            }
614                            self.crypto_verified = true;
615                        }
616                        (Some(_), None) | (None, Some(_)) => {
617                            return Ok(self.reject(RejectionReason::Unsecure));
618                        }
619                        (None, None) => {}
620                    }
621                }
622                self.enter_connected()
623            }
624            (RendezvousRole::Responder, PeerHsExt::None) => {
625                // L2357-2360: no extensions yet -> resend the empty
626                // CONCLUSION, remain in Attention.
627                self.state = RendezvousHandshakeState::Attention;
628                self.send_conclusion(None)
629            }
630            (RendezvousRole::Responder, PeerHsExt::HsReq(msg)) => {
631                // L2360-2364: HSREQ present -> Initiated, send
632                // CONCLUSION+HSRSP.
633                self.peer_hs_msg = Some(msg);
634                self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
635                #[cfg(feature = "crypto")]
636                if let Some(rejected) = self.accept_peer_crypto(hp) {
637                    return Ok(rejected);
638                }
639                self.state = RendezvousHandshakeState::Initiated;
640                self.send_conclusion(Some(ExtensionType::HsRsp))
641            }
642            // A peer sending the extension kind only its own role should ever
643            // send (HSREQ into an Initiator, HSRSP into a Responder) is not a
644            // transition either table defines — reject rather than guess.
645            _ => Ok(self.reject(RejectionReason::Rogue)),
646        }
647    }
648
649    /// [`RendezvousHandshakeState::Initiated`] (§4.3.2.2, L2321-2334 Initiator
650    /// / L2365-2382 Responder), including the idempotent-resend recovery
651    /// rules (L2383-2422).
652    fn on_initiated(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
653        let role = self.role.ok_or(Error::HandshakeOutOfSequence {
654            state: self.state.name(),
655            reason: "no role was resolved before the Initiated state",
656        })?;
657        match role {
658            RendezvousRole::Initiator => {
659                if hp.handshake_type != HandshakeType::Conclusion {
660                    return Ok(self.reject(RejectionReason::Rogue));
661                }
662                let ext = match parse_peer_hs_ext(hp) {
663                    Ok(e) => e,
664                    Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
665                };
666                match ext {
667                    // L2325: "REMAINS IN THIS STATE" — still resend
668                    // CONCLUSION+HSREQ.
669                    PeerHsExt::None => self.send_conclusion(Some(ExtensionType::HsReq)),
670                    // L2325-2334ish: contains HSRSP -> Connected, AGREEMENT.
671                    PeerHsExt::HsRsp(msg) => {
672                        self.peer_hs_msg = Some(msg);
673                        self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
674                        #[cfg(feature = "crypto")]
675                        {
676                            let parsed = match handshake_sm::parse_peer_extensions(hp) {
677                                Ok(p) => p,
678                                Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
679                            };
680                            match (&self.config.crypto, parsed.km) {
681                                (Some(crypto), Some(km)) => {
682                                    if !handshake_sm::verify_km_echo(crypto, &km) {
683                                        return Ok(self.reject(RejectionReason::BadSecret));
684                                    }
685                                    self.crypto_verified = true;
686                                }
687                                (Some(_), None) | (None, Some(_)) => {
688                                    return Ok(self.reject(RejectionReason::Unsecure));
689                                }
690                                (None, None) => {}
691                            }
692                        }
693                        self.enter_connected()
694                    }
695                    PeerHsExt::HsReq(_) => Ok(self.reject(RejectionReason::Rogue)),
696                }
697            }
698            RendezvousRole::Responder => {
699                if hp.handshake_type == HandshakeType::Agreement {
700                    // Responder Initiated row: AGREEMENT -> respond AGREEMENT,
701                    // switch to Connected.
702                    return self.enter_connected();
703                }
704                if hp.handshake_type != HandshakeType::Conclusion {
705                    return Ok(self.reject(RejectionReason::Rogue));
706                }
707                let ext = match parse_peer_hs_ext(hp) {
708                    Ok(e) => e,
709                    Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
710                };
711                match ext {
712                    // Recovery rule 2 (L2391-2395): MUST always resend HSRSP,
713                    // even if this HSREQ was already seen and processed once.
714                    PeerHsExt::HsReq(msg) => {
715                        self.peer_hs_msg = Some(msg);
716                        self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
717                        #[cfg(feature = "crypto")]
718                        if let Some(rejected) = self.accept_peer_crypto(hp) {
719                            return Ok(rejected);
720                        }
721                        self.send_conclusion(Some(ExtensionType::HsRsp))
722                    }
723                    _ => Ok(self.reject(RejectionReason::Rogue)),
724                }
725            }
726        }
727    }
728
729    /// [`RendezvousHandshakeState::Connected`] (Initiator row item 4,
730    /// L2331-2334; Responder row item 4, L2377-2381): normally no more
731    /// handshake traffic, but a repeated CONCLUSION is answered with another
732    /// AGREEMENT (recovery rule 4, L2424-2432, from the other side's point of
733    /// view); anything else is disregarded rather than regressing a completed
734    /// handshake.
735    fn on_connected(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
736        if hp.handshake_type == HandshakeType::Conclusion {
737            return self.send_agreement();
738        }
739        Ok(Vec::new())
740    }
741
742    /// The cookie contest (§4.3.2, L2107-2135). Identical cookies are a
743    /// collision the draft says must not connect (L2119-2124) — surfaced by
744    /// the caller as [`RejectionReason::RdvCookie`].
745    ///
746    /// The draft's prose ("cookie value is greater than its peer's") reads
747    /// like a plain unsigned comparison, but a cookie is derived from a hash
748    /// (`derive_cookie`) and is effectively a uniformly random 32-bit value
749    /// — a plain `own_cookie > peer_cookie` unsigned compare gives the wrong
750    /// answer for roughly a quarter of all cookie pairs relative to a real
751    /// libsrt peer (whose own comparison is signed, not unsigned), which
752    /// shows up as an intermittent rendezvous failure against libsrt with no
753    /// pattern visible from either side alone (issue #1064). Ported from
754    /// libsrt's own tie-break (`srtcore/core.cpp`,
755    /// `CUDT::backwardCompatibleCookieContest`, v1.5.5): see
756    /// [`cookie_contest`].
757    fn resolve_role(&self, peer_cookie: u32) -> Result<RendezvousRole> {
758        if peer_cookie == self.own_cookie {
759            return Err(Error::InvalidField(InvalidField {
760                field: "rendezvous cookie",
761                reason: "identical to the peer's cookie (collision, L2119-2124)",
762            }));
763        }
764        Ok(cookie_contest(self.own_cookie, peer_cookie))
765    }
766
767    #[cfg(feature = "crypto")]
768    fn accept_peer_crypto(&mut self, hp: &HandshakePacket<'_>) -> Option<Vec<HandshakeOutput>> {
769        let parsed = match handshake_sm::parse_peer_extensions(hp) {
770            Ok(p) => p,
771            Err(_) => return Some(self.reject(RejectionReason::Rogue)),
772        };
773        match (&self.config.crypto, parsed.km) {
774            (Some(crypto), Some(km)) => match handshake_sm::recover_sek(&crypto.passphrase, &km) {
775                Ok((sek, salt)) => {
776                    self.crypto_recovered = Some((sek, salt));
777                    match handshake_sm::echo_key_material_as_response(&km) {
778                        Ok(e) => self.km_echo_ext = Some(e),
779                        Err(_) => return Some(self.reject(RejectionReason::Rogue)),
780                    }
781                }
782                Err(_) => return Some(self.reject(RejectionReason::BadSecret)),
783            },
784            (Some(_), None) | (None, Some(_)) => {
785                return Some(self.reject(RejectionReason::Unsecure));
786            }
787            (None, None) => {}
788        }
789        None
790    }
791
792    fn reject(&mut self, reason: RejectionReason) -> Vec<HandshakeOutput> {
793        self.state = RendezvousHandshakeState::Rejected;
794        vec![HandshakeOutput::Rejected(reason)]
795    }
796
797    fn resend(&mut self) -> Vec<HandshakeOutput> {
798        match self.retransmit.last_sent() {
799            Some(bytes) => vec![HandshakeOutput::Send(bytes.to_vec())],
800            None => Vec::new(),
801        }
802    }
803
804    /// Builds and sends a CONCLUSION: `ext_type` picks HSREQ/HSRSP, or `None`
805    /// for the extension-less greeting (§4.3.2.2, L2286-2288: no Stream ID /
806    /// Group Membership is ever attached — see module docs).
807    fn send_conclusion(&mut self, ext_type: Option<ExtensionType>) -> Result<Vec<HandshakeOutput>> {
808        let (ext_bytes, ext_flags): (Vec<u8>, u16) = match ext_type {
809            None => (Vec::new(), 0),
810            Some(t) => {
811                let hs_msg = HsExtMessage {
812                    srt_version: self.config.srt_version,
813                    srt_flags: self.config.flags,
814                    receiver_tsbpd_delay_ms: self.config.latency_ms,
815                    sender_tsbpd_delay_ms: self.config.latency_ms,
816                };
817                handshake_sm::build_conclusion_extensions(t, &hs_msg, None, None)?
818            }
819        };
820        #[cfg(feature = "crypto")]
821        let mut ext_bytes = ext_bytes;
822        #[cfg(feature = "crypto")]
823        let mut ext_flags = ext_flags;
824        // §6.1.5: the Initiator (cookie-contest winner) sends the Key
825        // Material request piggybacked on its CONCLUSION's HSREQ block;
826        // the Responder echoes it back on its HSRSP CONCLUSION.
827        #[cfg(feature = "crypto")]
828        if ext_type == Some(ExtensionType::HsReq)
829            && let Some(crypto) = &self.config.crypto
830        {
831            let km_ext = handshake_sm::build_key_material_extension(crypto)?;
832            ext_bytes.extend(km_ext);
833            ext_flags |= crate::packet::handshake::HS_EXT_FLAG_KMREQ;
834        }
835        #[cfg(feature = "crypto")]
836        if ext_type == Some(ExtensionType::HsRsp)
837            && let Some(echo) = &self.km_echo_ext
838        {
839            ext_bytes.extend(echo.clone());
840            ext_flags |= crate::packet::handshake::HS_EXT_FLAG_KMREQ;
841        }
842        let hp = HandshakePacket {
843            timestamp: self.clock.now(),
844            dest_socket_id: self.peer_socket_id,
845            version: HANDSHAKE_VERSION_5,
846            encryption_field: self.config.encryption_field,
847            extension_field: HandshakeExtensionFlags(ext_flags),
848            initial_seq_number: self.config.initial_seq_number,
849            mtu: self.config.mtu,
850            max_flow_window_size: self.config.max_flow_window_size,
851            handshake_type: HandshakeType::Conclusion,
852            srt_socket_id: self.own_socket_id,
853            syn_cookie: self.own_cookie,
854            peer_ip: self.config.local_ip,
855            extensions: HandshakeExtensions(&ext_bytes),
856        };
857        let bytes = handshake_sm::build_bytes(hp)?;
858        self.retransmit.arm_fresh(&bytes);
859        Ok(vec![HandshakeOutput::Send(bytes)])
860    }
861
862    /// Builds and sends an AGREEMENT: no extensions (§4.3.2.1, L2224-2230).
863    fn send_agreement(&mut self) -> Result<Vec<HandshakeOutput>> {
864        let hp = HandshakePacket {
865            timestamp: self.clock.now(),
866            dest_socket_id: self.peer_socket_id,
867            version: HANDSHAKE_VERSION_5,
868            encryption_field: EncryptionField::NoEncryption,
869            extension_field: HandshakeExtensionFlags(0),
870            initial_seq_number: self.config.initial_seq_number,
871            mtu: self.config.mtu,
872            max_flow_window_size: self.config.max_flow_window_size,
873            handshake_type: HandshakeType::Agreement,
874            srt_socket_id: self.own_socket_id,
875            syn_cookie: self.own_cookie,
876            peer_ip: self.config.local_ip,
877            extensions: HandshakeExtensions(&[]),
878        };
879        let bytes = handshake_sm::build_bytes(hp)?;
880        self.retransmit.arm_fresh(&bytes);
881        Ok(vec![HandshakeOutput::Send(bytes)])
882    }
883
884    /// Reaches [`RendezvousHandshakeState::Connected`]: builds
885    /// [`NegotiatedParams`] from `self.peer_hs_msg` (always captured by every
886    /// caller of this method before it is called) and sends the AGREEMENT
887    /// every documented transition into Connected requires.
888    fn enter_connected(&mut self) -> Result<Vec<HandshakeOutput>> {
889        let negotiated = self.build_negotiated()?;
890        self.negotiated = Some(negotiated.clone());
891        self.state = RendezvousHandshakeState::Connected;
892        let mut out = self.send_agreement()?;
893        out.push(HandshakeOutput::Connected(negotiated));
894        Ok(out)
895    }
896
897    fn build_negotiated(&self) -> Result<NegotiatedParams> {
898        let (Some(peer_msg), Some((peer_mtu, peer_mfw))) = (self.peer_hs_msg, self.peer_limits)
899        else {
900            return Err(Error::HandshakeOutOfSequence {
901                state: self.state.name(),
902                reason: "reached Connected without the peer's Handshake Extension Message",
903            });
904        };
905        Ok(NegotiatedParams {
906            version: HANDSHAKE_VERSION_5,
907            flags: HandshakeExtensionMessageFlags(self.config.flags.0 & peer_msg.srt_flags.0),
908            latency_ms: handshake_sm::negotiate_latency_ms(self.config.latency_ms, &peer_msg),
909            own_socket_id: self.own_socket_id,
910            peer_socket_id: self.peer_socket_id,
911            mtu: self.config.mtu.min(peer_mtu),
912            max_flow_window_size: self.config.max_flow_window_size.min(peer_mfw),
913            // §4.3.2 never mentions a Stream ID / Group Membership exchange.
914            stream_id: None,
915            group: None,
916            #[cfg(feature = "crypto")]
917            sek: {
918                match self.role {
919                    Some(RendezvousRole::Initiator) => {
920                        if self.config.crypto.is_some() && self.crypto_verified {
921                            self.config
922                                .crypto
923                                .as_ref()
924                                .map(|c| handshake_sm::SecretBytes::new(c.sek.clone()))
925                        } else {
926                            None
927                        }
928                    }
929                    Some(RendezvousRole::Responder) => {
930                        self.crypto_recovered.as_ref().map(|(sek, _)| sek.clone())
931                    }
932                    None => None,
933                }
934            },
935            #[cfg(feature = "crypto")]
936            salt: {
937                match self.role {
938                    Some(RendezvousRole::Initiator) => {
939                        if self.config.crypto.is_some() && self.crypto_verified {
940                            self.config.crypto.as_ref().map(|c| c.salt)
941                        } else {
942                            None
943                        }
944                    }
945                    Some(RendezvousRole::Responder) => {
946                        self.crypto_recovered.as_ref().map(|(_, salt)| *salt)
947                    }
948                    None => None,
949                }
950            },
951        })
952    }
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958    use crate::packet::handshake::HS_EXT_FLAG_HSREQ;
959
960    #[test]
961    fn start_is_idempotent_guard() {
962        let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
963        assert!(r.start().is_ok());
964        assert!(matches!(
965            r.start(),
966            Err(crate::error::Error::HandshakeOutOfSequence { .. })
967        ));
968    }
969
970    #[test]
971    fn wavehand_wire_values_match_draft_4_3_2() {
972        let mut r = RendezvousHandshake::new(0xAAAA_BBBB, 0xC0FF_EE00, HandshakeConfig::default());
973        let bytes = r.start().unwrap();
974        let pkt = ControlPacket::parse(&bytes).unwrap();
975        match pkt {
976            ControlPacket::Handshake(hp) => {
977                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
978                assert_eq!(hp.handshake_type, HandshakeType::Wavehand);
979                assert_eq!(hp.srt_socket_id, 0xAAAA_BBBB);
980                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
981                assert_eq!(hp.extension_field.0, 0);
982            }
983            _ => panic!("expected handshake"),
984        }
985        assert_eq!(r.state(), RendezvousHandshakeState::Waving);
986    }
987
988    fn wavehand(socket_id: u32, cookie: u32) -> ControlPacket<'static> {
989        ControlPacket::Handshake(HandshakePacket {
990            timestamp: 0,
991            dest_socket_id: 0,
992            version: HANDSHAKE_VERSION_5,
993            encryption_field: EncryptionField::NoEncryption,
994            extension_field: HandshakeExtensionFlags(0),
995            initial_seq_number: 0,
996            mtu: 1500,
997            max_flow_window_size: 8192,
998            handshake_type: HandshakeType::Wavehand,
999            srt_socket_id: socket_id,
1000            syn_cookie: cookie,
1001            peer_ip: [0; 4],
1002            extensions: HandshakeExtensions(&[]),
1003        })
1004    }
1005
1006    #[test]
1007    fn greater_cookie_wins_initiator() {
1008        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1009        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1010        a.start().unwrap();
1011        b.start().unwrap();
1012
1013        a.feed(&wavehand(2, 100)).unwrap();
1014        b.feed(&wavehand(1, 500)).unwrap();
1015
1016        assert_eq!(a.role(), Some(RendezvousRole::Initiator));
1017        assert_eq!(b.role(), Some(RendezvousRole::Responder));
1018        assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1019        assert_eq!(b.state(), RendezvousHandshakeState::Attention);
1020    }
1021
1022    /// Sign-boundary cookie-contest table (issue #1064). Every case here
1023    /// pins `cookie_contest`'s result against the libsrt algorithm it ports
1024    /// — hand-traced from `CUDT::backwardCompatibleCookieContest`, not
1025    /// re-derived from this crate's own implementation (the point is
1026    /// catching a misport, not just re-checking `contest > 0`).
1027    ///
1028    /// A plain unsigned `own_cookie > peer_cookie` compare (this function's
1029    /// pre-#1064 behavior) gives the OPPOSITE answer to several of these —
1030    /// marked below — because it doesn't reinterpret either cookie as
1031    /// signed before comparing.
1032    #[test]
1033    fn cookie_contest_sign_boundary_table() {
1034        let cases: &[(u32, u32, RendezvousRole, &str)] = &[
1035            // Both positive as i32 (top bit clear): signed and unsigned
1036            // agree — the ordinary case.
1037            (
1038                500,
1039                100,
1040                RendezvousRole::Initiator,
1041                "both positive, own > peer",
1042            ),
1043            (
1044                100,
1045                500,
1046                RendezvousRole::Responder,
1047                "both positive, own < peer",
1048            ),
1049            // Exactly one cookie has the top bit set: signed and unsigned
1050            // DISAGREE. libsrt's signed compare makes the negative
1051            // (top-bit-set) one lose regardless of its unsigned magnitude.
1052            (
1053                0xAAAA_0002,
1054                0x1111_0001,
1055                RendezvousRole::Responder,
1056                "own top-bit-set (negative), peer positive — unsigned would say Initiator",
1057            ),
1058            (
1059                0x1111_0001,
1060                0xAAAA_0002,
1061                RendezvousRole::Initiator,
1062                "own positive, peer top-bit-set (negative) — unsigned would say Responder",
1063            ),
1064            // Both top-bit-set (both negative as i32): signed compare among
1065            // two negatives, still needs to agree with libsrt, not just
1066            // "unsigned compare of the raw bit pattern" (which happens to
1067            // still hold here since the *relative* order of two same-signed
1068            // values is the same either way — included as a same-sign
1069            // sanity check, not a disagreement case).
1070            (
1071                0xFFFF_FFFF,
1072                0x8000_0000,
1073                RendezvousRole::Initiator,
1074                "both negative, own > peer",
1075            ),
1076            (
1077                0x8000_0000,
1078                0xFFFF_FFFF,
1079                RendezvousRole::Responder,
1080                "both negative, own < peer",
1081            ),
1082            // The exact halfway point (`own - peer == i32::MIN`, `0x8000_0000`
1083            // as the wrapping 32-bit difference): libsrt's own tie-break for
1084            // this specific case falls back to a raw signed `req > res`
1085            // comparison of the two cookies themselves (see `cookie_contest`'s
1086            // doc) rather than the contest direction.
1087            (
1088                0x8000_0000,
1089                0,
1090                RendezvousRole::Responder,
1091                "halfway point, own negative vs peer zero: raw signed own(<0) > peer(0) is false",
1092            ),
1093            (
1094                0,
1095                0x8000_0000,
1096                RendezvousRole::Initiator,
1097                "halfway point, own zero vs peer negative: raw signed own(0) > peer(<0) is true",
1098            ),
1099        ];
1100        for &(own, peer, expected, why) in cases {
1101            let got = cookie_contest(own, peer);
1102            assert_eq!(
1103                got, expected,
1104                "own={own:#010x} peer={peer:#010x}: expected {expected:?}, got {got:?} ({why})"
1105            );
1106        }
1107    }
1108
1109    #[test]
1110    fn identical_cookies_are_rejected_as_a_collision() {
1111        let mut a = RendezvousHandshake::new(1, 0x00C0_FFEE, HandshakeConfig::default());
1112        a.start().unwrap();
1113        let outputs = a.feed(&wavehand(2, 0x00C0_FFEE)).unwrap();
1114        assert_eq!(
1115            outputs,
1116            vec![HandshakeOutput::Rejected(RejectionReason::RdvCookie)]
1117        );
1118        assert_eq!(a.state(), RendezvousHandshakeState::Rejected);
1119    }
1120
1121    #[test]
1122    fn initiator_attention_entry_sends_hsreq() {
1123        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1124        a.start().unwrap();
1125        let outputs = a.feed(&wavehand(2, 100)).unwrap();
1126        assert_eq!(outputs.len(), 1);
1127        let bytes = match &outputs[0] {
1128            HandshakeOutput::Send(b) => b.clone(),
1129            other => panic!("expected Send, got {other:?}"),
1130        };
1131        let pkt = ControlPacket::parse(&bytes).unwrap();
1132        match pkt {
1133            ControlPacket::Handshake(hp) => {
1134                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1135                assert_eq!(hp.extension_field.0 & HS_EXT_FLAG_HSREQ, HS_EXT_FLAG_HSREQ);
1136                let blocks: Vec<_> = hp.extensions.iter().map(|b| b.unwrap()).collect();
1137                assert_eq!(blocks.len(), 1);
1138                assert_eq!(blocks[0].ext_type, ExtensionType::HsReq);
1139            }
1140            _ => panic!("expected handshake"),
1141        }
1142    }
1143
1144    #[test]
1145    fn responder_attention_entry_sends_empty_conclusion() {
1146        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1147        b.start().unwrap();
1148        let outputs = b.feed(&wavehand(1, 500)).unwrap();
1149        assert_eq!(outputs.len(), 1);
1150        let bytes = match &outputs[0] {
1151            HandshakeOutput::Send(b) => b.clone(),
1152            other => panic!("expected Send, got {other:?}"),
1153        };
1154        let pkt = ControlPacket::parse(&bytes).unwrap();
1155        match pkt {
1156            ControlPacket::Handshake(hp) => {
1157                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1158                assert_eq!(hp.extension_field.0, 0);
1159                assert_eq!(hp.extensions.iter().count(), 0);
1160            }
1161            _ => panic!("expected handshake"),
1162        }
1163    }
1164
1165    #[test]
1166    fn malformed_extension_mid_flow_is_rejected_not_panicking() {
1167        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1168        a.start().unwrap();
1169        a.feed(&wavehand(2, 100)).unwrap();
1170        assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1171
1172        // A CONCLUSION whose extension block declares a length far larger
1173        // than the bytes actually present.
1174        let bad_ext: &'static [u8] = &[0x00, 0x01, 0xFF, 0xFF];
1175        let bad = ControlPacket::Handshake(HandshakePacket {
1176            timestamp: 0,
1177            dest_socket_id: 1,
1178            version: HANDSHAKE_VERSION_5,
1179            encryption_field: EncryptionField::NoEncryption,
1180            extension_field: HandshakeExtensionFlags(HS_EXT_FLAG_HSREQ),
1181            initial_seq_number: 0,
1182            mtu: 1500,
1183            max_flow_window_size: 8192,
1184            handshake_type: HandshakeType::Conclusion,
1185            srt_socket_id: 2,
1186            syn_cookie: 100,
1187            peer_ip: [0; 4],
1188            extensions: HandshakeExtensions(bad_ext),
1189        });
1190        let outputs = a.feed(&bad).unwrap();
1191        assert_eq!(
1192            outputs,
1193            vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]
1194        );
1195        assert_eq!(a.state(), RendezvousHandshakeState::Rejected);
1196    }
1197
1198    #[test]
1199    fn feed_before_start_is_out_of_sequence() {
1200        let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1201        assert!(matches!(
1202            r.feed(&wavehand(2, 100)),
1203            Err(Error::HandshakeOutOfSequence { .. })
1204        ));
1205    }
1206
1207    #[test]
1208    fn feed_rejects_non_handshake_packets_outside_recovery_case() {
1209        use crate::packet::misc::KeepAlivePacket;
1210        let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1211        r.start().unwrap();
1212        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
1213            timestamp: 0,
1214            dest_socket_id: 0,
1215            libsrt_pad: false,
1216        });
1217        assert!(matches!(
1218            r.feed(&ka),
1219            Err(Error::UnexpectedControlPacket { .. })
1220        ));
1221    }
1222
1223    /// The state machine's internal invariants (a role is resolved before
1224    /// Attention/Initiated, the peer's HSREQ/HSRSP is known before Connected)
1225    /// are errors, not panics, if ever violated.
1226    #[test]
1227    fn broken_internal_invariants_are_errors_not_panics() {
1228        use crate::packet::{EncryptionField, HandshakeExtensionFlags, HandshakeExtensions};
1229        let hp = HandshakePacket {
1230            timestamp: 0,
1231            dest_socket_id: 1,
1232            version: 5,
1233            encryption_field: EncryptionField::NoEncryption,
1234            extension_field: HandshakeExtensionFlags(0),
1235            initial_seq_number: 0,
1236            mtu: 1500,
1237            max_flow_window_size: 8192,
1238            handshake_type: HandshakeType::Conclusion,
1239            srt_socket_id: 2,
1240            syn_cookie: 0,
1241            peer_ip: [0; 4],
1242            extensions: HandshakeExtensions(&[]),
1243        };
1244        let mut r = RendezvousHandshake::new(1, 5, HandshakeConfig::default());
1245        assert!(matches!(
1246            r.on_attention(&hp),
1247            Err(Error::HandshakeOutOfSequence { .. })
1248        ));
1249        assert!(matches!(
1250            r.on_initiated(&hp),
1251            Err(Error::HandshakeOutOfSequence { .. })
1252        ));
1253        assert!(matches!(
1254            r.enter_connected(),
1255            Err(Error::HandshakeOutOfSequence { .. })
1256        ));
1257    }
1258}
1259
1260#[cfg(all(test, feature = "crypto"))]
1261mod crypto_echo_tests {
1262    use super::super::*;
1263    #[cfg(feature = "crypto")]
1264    use crate::handshake_sm::CryptoConfig;
1265
1266    #[cfg(feature = "crypto")]
1267    #[test]
1268    fn rendezvous_initiator_rejects_a_tampered_km_echo() {
1269        use crate::packet::{ControlPacket, EncryptionField};
1270
1271        const PEER_A_SOCKET_ID: u32 = 0x1111_1111;
1272        const PEER_B_SOCKET_ID: u32 = 0x2222_2222;
1273        const PEER_A_COOKIE: u32 = 0xAAAA_0002;
1274        const PEER_B_COOKIE: u32 = 0x1111_0001;
1275
1276        let passphrase = b"passphrase".to_vec();
1277        let crypto = CryptoConfig {
1278            passphrase: passphrase.clone(),
1279            salt: [0x11u8; 16],
1280            sek: vec![0x22u8; 16],
1281        };
1282        let config_a = HandshakeConfig {
1283            encryption_field: EncryptionField::Aes128,
1284            crypto: Some(crypto.clone()),
1285            ..HandshakeConfig::default()
1286        };
1287        let config_b = HandshakeConfig {
1288            encryption_field: EncryptionField::Aes128,
1289            crypto: Some(crypto),
1290            ..HandshakeConfig::default()
1291        };
1292
1293        // Untampered run must complete.
1294        {
1295            let mut a = RendezvousHandshake::new(PEER_A_SOCKET_ID, PEER_A_COOKIE, config_a.clone());
1296            let mut b = RendezvousHandshake::new(PEER_B_SOCKET_ID, PEER_B_COOKIE, config_b.clone());
1297            let mut to_a = vec![b.start().expect("b start")];
1298            let mut to_b = vec![a.start().expect("a start")];
1299            for _ in 0..20 {
1300                if a.state() == RendezvousHandshakeState::Connected
1301                    && b.state() == RendezvousHandshakeState::Connected
1302                {
1303                    break;
1304                }
1305                let mut next_to_a = Vec::new();
1306                let mut next_to_b = Vec::new();
1307                for msg in to_a.drain(..) {
1308                    let pkt = ControlPacket::parse(&msg).expect("valid");
1309                    for out in a.feed(&pkt).expect("a.feed") {
1310                        if let HandshakeOutput::Send(bytes) = out {
1311                            next_to_b.push(bytes);
1312                        }
1313                    }
1314                }
1315                for msg in to_b.drain(..) {
1316                    let pkt = ControlPacket::parse(&msg).expect("valid");
1317                    for out in b.feed(&pkt).expect("b.feed") {
1318                        if let HandshakeOutput::Send(bytes) = out {
1319                            next_to_a.push(bytes);
1320                        }
1321                    }
1322                }
1323                to_a = next_to_a;
1324                to_b = next_to_b;
1325                if to_a.is_empty() && to_b.is_empty() {
1326                    break;
1327                }
1328            }
1329            assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1330            assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1331        }
1332
1333        // Tampered run: flip a byte in the Responder's key-material echo.
1334        let mut a = RendezvousHandshake::new(PEER_A_SOCKET_ID, PEER_A_COOKIE, config_a);
1335        let mut b = RendezvousHandshake::new(PEER_B_SOCKET_ID, PEER_B_COOKIE, config_b);
1336        let mut to_a = vec![b.start().expect("b start")];
1337        let mut to_b = vec![a.start().expect("a start")];
1338        let mut tampered = false;
1339        let mut rejected = false;
1340        for _ in 0..20 {
1341            if rejected {
1342                break;
1343            }
1344            if a.state() == RendezvousHandshakeState::Connected
1345                && b.state() == RendezvousHandshakeState::Connected
1346            {
1347                break;
1348            }
1349            let mut next_to_a = Vec::new();
1350            let mut next_to_b = Vec::new();
1351            for msg in to_a.drain(..) {
1352                let pkt = ControlPacket::parse(&msg).expect("valid");
1353                for out in a.feed(&pkt).expect("a.feed") {
1354                    if let HandshakeOutput::Send(bytes) = out {
1355                        next_to_b.push(bytes);
1356                    }
1357                }
1358            }
1359            for msg in to_b.drain(..) {
1360                let mut msg = msg;
1361                if !tampered && msg.windows(2).any(|w| w == [0, 4]) {
1362                    if let Some(last) = msg.last_mut() {
1363                        *last ^= 0xFF;
1364                    }
1365                    tampered = true;
1366                }
1367                let pkt = ControlPacket::parse(&msg).expect("valid");
1368                for out in b.feed(&pkt).expect("b.feed") {
1369                    match out {
1370                        HandshakeOutput::Send(bytes) => next_to_a.push(bytes),
1371                        HandshakeOutput::Rejected(reason) => {
1372                            assert_eq!(reason, RejectionReason::BadSecret);
1373                            rejected = true;
1374                        }
1375                        _ => {}
1376                    }
1377                }
1378            }
1379            to_a = next_to_a;
1380            to_b = next_to_b;
1381            if to_a.is_empty() && to_b.is_empty() {
1382                break;
1383            }
1384        }
1385        assert!(tampered, "never found a key-material echo to tamper");
1386        assert!(rejected, "initiator did not reject the tampered echo");
1387        assert_eq!(b.state(), RendezvousHandshakeState::Rejected);
1388    }
1389}