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,
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    negotiated: Option<NegotiatedParams>,
325    #[cfg(feature = "crypto")]
326    crypto_recovered: Option<handshake_sm::RecoveredSek>,
327    #[cfg(feature = "crypto")]
328    km_echo_ext: Option<Vec<u8>>,
329    #[cfg(feature = "crypto")]
330    crypto_verified: bool,
331}
332
333impl RendezvousHandshake {
334    /// Creates a fresh Rendezvous handshake in
335    /// [`RendezvousHandshakeState::Idle`], with the 32-bit cookie this side
336    /// will offer in the cookie contest (§4.3.2, L2107-2135). This crate never
337    /// reads a clock or a socket address — see
338    /// [`crate::handshake_sm::derive_cookie`] for a ready-made,
339    /// non-standardized derivation helper.
340    pub fn new(own_socket_id: u32, own_cookie: u32, config: HandshakeConfig) -> Self {
341        RendezvousHandshake {
342            own_socket_id,
343            own_cookie,
344            config,
345            state: RendezvousHandshakeState::Idle,
346            role: None,
347            peer_socket_id: 0,
348            peer_cookie: 0,
349            peer_hs_msg: None,
350            peer_limits: None,
351            retransmit: Retransmit::default(),
352            negotiated: None,
353            #[cfg(feature = "crypto")]
354            crypto_recovered: None,
355            #[cfg(feature = "crypto")]
356            km_echo_ext: None,
357            #[cfg(feature = "crypto")]
358            crypto_verified: false,
359        }
360    }
361
362    /// The current state.
363    pub fn state(&self) -> RendezvousHandshakeState {
364        self.state
365    }
366
367    /// The role resolved by the cookie contest, once past
368    /// [`RendezvousHandshakeState::Waving`].
369    pub fn role(&self) -> Option<RendezvousRole> {
370        self.role
371    }
372
373    /// The negotiated parameters, once [`RendezvousHandshakeState::Connected`].
374    pub fn negotiated(&self) -> Option<&NegotiatedParams> {
375        self.negotiated.as_ref()
376    }
377
378    /// Builds the initial WAVEAHAND handshake (§4.3.2, L2100/L2153-2170:
379    /// Version 5, this side's own cookie, no extensions) and transitions to
380    /// [`RendezvousHandshakeState::Waving`].
381    ///
382    /// # Errors
383    /// [`Error::HandshakeOutOfSequence`] if called more than once.
384    pub fn start(&mut self) -> Result<Vec<u8>> {
385        if self.state != RendezvousHandshakeState::Idle {
386            return Err(Error::HandshakeOutOfSequence {
387                state: self.state.name(),
388                reason: "start() called after the handshake already began",
389            });
390        }
391        let hp = HandshakePacket {
392            timestamp: 0,
393            dest_socket_id: 0, // Unknown yet — mirrors CallerHandshake::start's INDUCTION.
394            version: HANDSHAKE_VERSION_5,
395            encryption_field: self.config.encryption_field,
396            extension_field: HandshakeExtensionFlags(0),
397            initial_seq_number: self.config.initial_seq_number,
398            mtu: self.config.mtu,
399            max_flow_window_size: self.config.max_flow_window_size,
400            handshake_type: HandshakeType::Wavehand,
401            srt_socket_id: self.own_socket_id,
402            syn_cookie: self.own_cookie,
403            peer_ip: self.config.local_ip,
404            extensions: HandshakeExtensions(&[]),
405        };
406        let bytes = handshake_sm::build_bytes(hp)?;
407        self.retransmit.arm(&bytes);
408        self.state = RendezvousHandshakeState::Waving;
409        Ok(bytes)
410    }
411
412    /// Feeds an inbound control packet.
413    ///
414    /// A non-Handshake `ControlPacket` fed while this side is a Responder
415    /// stuck in [`RendezvousHandshakeState::Initiated`] is treated as
416    /// missing-packet recovery rule 3 (L2413-2422: "any control packet
417    /// normally only sent between connected parties") rather than an error —
418    /// see [`Self::on_recovery_trigger`] for the data-packet analogue.
419    ///
420    /// # Errors
421    /// [`Error::UnexpectedControlPacket`] for a non-Handshake packet outside
422    /// that one recovery case; [`Error::HandshakeOutOfSequence`] if fed before
423    /// [`Self::start`] or after a terminal state (a driver bug, not a peer
424    /// protocol failure).
425    pub fn feed(&mut self, packet: &ControlPacket<'_>) -> Result<Vec<HandshakeOutput>> {
426        let hp = match packet {
427            ControlPacket::Handshake(hp) => hp,
428            other => {
429                if self.state == RendezvousHandshakeState::Initiated
430                    && self.role == Some(RendezvousRole::Responder)
431                {
432                    return self.enter_connected();
433                }
434                return Err(Error::UnexpectedControlPacket {
435                    actual: other.control_type().name(),
436                });
437            }
438        };
439        if let Some(reason) = RejectionReason::from_handshake_type(hp.handshake_type) {
440            return Ok(self.reject(reason));
441        }
442        if hp.version != HANDSHAKE_VERSION_5 {
443            // §4.3.2, L2101-2105: Version-4 legacy Rendezvous is out of scope.
444            return Ok(self.reject(RejectionReason::Version));
445        }
446        match self.state {
447            RendezvousHandshakeState::Idle => Err(Error::HandshakeOutOfSequence {
448                state: self.state.name(),
449                reason: "feed() called before start()",
450            }),
451            RendezvousHandshakeState::Waving => self.on_waving(hp),
452            RendezvousHandshakeState::Attention => self.on_attention(hp),
453            RendezvousHandshakeState::Initiated => self.on_initiated(hp),
454            RendezvousHandshakeState::Connected => self.on_connected(hp),
455            RendezvousHandshakeState::Rejected | RendezvousHandshakeState::TimedOut => {
456                Err(Error::HandshakeOutOfSequence {
457                    state: self.state.name(),
458                    reason: "handshake already reached a terminal state",
459                })
460            }
461        }
462    }
463
464    /// Convenience wrapper: parses `bytes` as a [`ControlPacket`] then
465    /// [`Self::feed`]s it.
466    pub fn feed_bytes(&mut self, bytes: &[u8]) -> Result<Vec<HandshakeOutput>> {
467        let packet = ControlPacket::parse(bytes)?;
468        self.feed(&packet)
469    }
470
471    /// Missing-packet recovery rule 3 (§4.3.2.2, L2413-2422): call this when
472    /// the driver receives a data packet (`SrtPacket::Data`) while this side
473    /// has not yet reached [`RendezvousHandshakeState::Connected`]. A no-op
474    /// (`Ok(Vec::new())`) unless this side is a Responder stuck in
475    /// [`RendezvousHandshakeState::Initiated`] — the one case the draft says
476    /// is "exceptionally allowed" to promote to Connected "as if it had
477    /// received AGREEMENT".
478    pub fn on_recovery_trigger(&mut self) -> Result<Vec<HandshakeOutput>> {
479        if self.state == RendezvousHandshakeState::Initiated
480            && self.role == Some(RendezvousRole::Responder)
481        {
482            self.enter_connected()
483        } else {
484            Ok(Vec::new())
485        }
486    }
487
488    /// Advances retransmit timing by one caller-defined tick, mirroring
489    /// [`crate::caller::CallerHandshake::tick`] /
490    /// [`crate::listener::ListenerHandshake::tick`].
491    pub fn tick(&mut self) -> Vec<HandshakeOutput> {
492        if matches!(
493            self.state,
494            RendezvousHandshakeState::Idle
495                | RendezvousHandshakeState::Connected
496                | RendezvousHandshakeState::Rejected
497                | RendezvousHandshakeState::TimedOut
498        ) {
499            return Vec::new();
500        }
501        let step = self.retransmit.tick(&self.config);
502        if matches!(step, RetransmitStep::TimedOut) {
503            self.state = RendezvousHandshakeState::TimedOut;
504        }
505        step.into_outputs()
506    }
507
508    /// [`RendezvousHandshakeState::Waving`]: the first message ever received
509    /// from the peer — either a genuine WAVEAHAND (§4.3.2.2 Waving row,
510    /// L2301-2306 Initiator / L2336-2342 Responder) or, in the Serial flow's
511    /// crossing case, a CONCLUSION directly (see module docs). Either way the
512    /// cookie contest is resolved here, from `hp.syn_cookie`.
513    fn on_waving(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
514        if !matches!(
515            hp.handshake_type,
516            HandshakeType::Wavehand | HandshakeType::Conclusion
517        ) {
518            return Ok(self.reject(RejectionReason::Rogue));
519        }
520        self.peer_socket_id = hp.srt_socket_id;
521        let role = match self.resolve_role(hp.syn_cookie) {
522            Ok(r) => r,
523            Err(_) => return Ok(self.reject(RejectionReason::RdvCookie)),
524        };
525        self.peer_cookie = hp.syn_cookie;
526        self.role = Some(role);
527
528        if hp.handshake_type == HandshakeType::Wavehand {
529            self.state = RendezvousHandshakeState::Attention;
530            match role {
531                // Initiator Waving row (L2301-2306): send CONCLUSION+HSREQ.
532                RendezvousRole::Initiator => self.send_conclusion(Some(ExtensionType::HsReq)),
533                // Responder Waving row (L2336-2342): send CONCLUSION, no
534                // extensions (it has not seen the peer's HSREQ yet).
535                RendezvousRole::Responder => self.send_conclusion(None),
536            }
537        } else {
538            // Serial-flow crossing (§4.3.2.1 step 3, L2203-2219): apply the
539            // same content-driven Attention-row logic (module docs).
540            self.on_attention_conclusion(hp, role)
541        }
542    }
543
544    /// [`RendezvousHandshakeState::Attention`]: a WAVEAHAND was already seen
545    /// and processed; only a CONCLUSION (Attention row) or a duplicate
546    /// WAVEAHAND (not covered by either table — treated as a benign resend,
547    /// module docs) is expected here.
548    fn on_attention(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
549        let role = self.role.ok_or(Error::HandshakeOutOfSequence {
550            state: self.state.name(),
551            reason: "no role was resolved before the Attention state",
552        })?;
553        if hp.handshake_type == HandshakeType::Conclusion {
554            return self.on_attention_conclusion(hp, role);
555        }
556        if hp.handshake_type == HandshakeType::Wavehand {
557            return Ok(self.resend());
558        }
559        Ok(self.reject(RejectionReason::Rogue))
560    }
561
562    /// The Attention row's CONCLUSION-handling logic (§4.3.2.2, L2307-2320
563    /// Initiator / L2343-2364 Responder), shared between a genuine
564    /// [`RendezvousHandshakeState::Attention`] and the Serial-flow crossing
565    /// case fed straight from [`RendezvousHandshakeState::Waving`].
566    fn on_attention_conclusion(
567        &mut self,
568        hp: &HandshakePacket<'_>,
569        role: RendezvousRole,
570    ) -> Result<Vec<HandshakeOutput>> {
571        self.peer_socket_id = hp.srt_socket_id;
572        let ext = match parse_peer_hs_ext(hp) {
573            Ok(e) => e,
574            Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
575        };
576        match (role, ext) {
577            (RendezvousRole::Initiator, PeerHsExt::None) => {
578                // L2312-2318: no extensions -> Initiated, still send
579                // CONCLUSION+HSREQ.
580                self.state = RendezvousHandshakeState::Initiated;
581                self.send_conclusion(Some(ExtensionType::HsReq))
582            }
583            (RendezvousRole::Initiator, PeerHsExt::HsRsp(msg)) => {
584                // L2318-2320: contains HSRSP -> Connected, send AGREEMENT.
585                self.peer_hs_msg = Some(msg);
586                self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
587                #[cfg(feature = "crypto")]
588                {
589                    let parsed = match handshake_sm::parse_peer_extensions(hp) {
590                        Ok(p) => p,
591                        Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
592                    };
593                    match (&self.config.crypto, parsed.km) {
594                        (Some(crypto), Some(km)) => {
595                            if !handshake_sm::verify_km_echo(crypto, &km) {
596                                return Ok(self.reject(RejectionReason::BadSecret));
597                            }
598                            self.crypto_verified = true;
599                        }
600                        (Some(_), None) | (None, Some(_)) => {
601                            return Ok(self.reject(RejectionReason::Unsecure));
602                        }
603                        (None, None) => {}
604                    }
605                }
606                self.enter_connected()
607            }
608            (RendezvousRole::Responder, PeerHsExt::None) => {
609                // L2357-2360: no extensions yet -> resend the empty
610                // CONCLUSION, remain in Attention.
611                self.state = RendezvousHandshakeState::Attention;
612                self.send_conclusion(None)
613            }
614            (RendezvousRole::Responder, PeerHsExt::HsReq(msg)) => {
615                // L2360-2364: HSREQ present -> Initiated, send
616                // CONCLUSION+HSRSP.
617                self.peer_hs_msg = Some(msg);
618                self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
619                #[cfg(feature = "crypto")]
620                if let Some(rejected) = self.accept_peer_crypto(hp) {
621                    return Ok(rejected);
622                }
623                self.state = RendezvousHandshakeState::Initiated;
624                self.send_conclusion(Some(ExtensionType::HsRsp))
625            }
626            // A peer sending the extension kind only its own role should ever
627            // send (HSREQ into an Initiator, HSRSP into a Responder) is not a
628            // transition either table defines — reject rather than guess.
629            _ => Ok(self.reject(RejectionReason::Rogue)),
630        }
631    }
632
633    /// [`RendezvousHandshakeState::Initiated`] (§4.3.2.2, L2321-2334 Initiator
634    /// / L2365-2382 Responder), including the idempotent-resend recovery
635    /// rules (L2383-2422).
636    fn on_initiated(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
637        let role = self.role.ok_or(Error::HandshakeOutOfSequence {
638            state: self.state.name(),
639            reason: "no role was resolved before the Initiated state",
640        })?;
641        match role {
642            RendezvousRole::Initiator => {
643                if hp.handshake_type != HandshakeType::Conclusion {
644                    return Ok(self.reject(RejectionReason::Rogue));
645                }
646                let ext = match parse_peer_hs_ext(hp) {
647                    Ok(e) => e,
648                    Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
649                };
650                match ext {
651                    // L2325: "REMAINS IN THIS STATE" — still resend
652                    // CONCLUSION+HSREQ.
653                    PeerHsExt::None => self.send_conclusion(Some(ExtensionType::HsReq)),
654                    // L2325-2334ish: contains HSRSP -> Connected, AGREEMENT.
655                    PeerHsExt::HsRsp(msg) => {
656                        self.peer_hs_msg = Some(msg);
657                        self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
658                        #[cfg(feature = "crypto")]
659                        {
660                            let parsed = match handshake_sm::parse_peer_extensions(hp) {
661                                Ok(p) => p,
662                                Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
663                            };
664                            match (&self.config.crypto, parsed.km) {
665                                (Some(crypto), Some(km)) => {
666                                    if !handshake_sm::verify_km_echo(crypto, &km) {
667                                        return Ok(self.reject(RejectionReason::BadSecret));
668                                    }
669                                    self.crypto_verified = true;
670                                }
671                                (Some(_), None) | (None, Some(_)) => {
672                                    return Ok(self.reject(RejectionReason::Unsecure));
673                                }
674                                (None, None) => {}
675                            }
676                        }
677                        self.enter_connected()
678                    }
679                    PeerHsExt::HsReq(_) => Ok(self.reject(RejectionReason::Rogue)),
680                }
681            }
682            RendezvousRole::Responder => {
683                if hp.handshake_type == HandshakeType::Agreement {
684                    // Responder Initiated row: AGREEMENT -> respond AGREEMENT,
685                    // switch to Connected.
686                    return self.enter_connected();
687                }
688                if hp.handshake_type != HandshakeType::Conclusion {
689                    return Ok(self.reject(RejectionReason::Rogue));
690                }
691                let ext = match parse_peer_hs_ext(hp) {
692                    Ok(e) => e,
693                    Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
694                };
695                match ext {
696                    // Recovery rule 2 (L2391-2395): MUST always resend HSRSP,
697                    // even if this HSREQ was already seen and processed once.
698                    PeerHsExt::HsReq(msg) => {
699                        self.peer_hs_msg = Some(msg);
700                        self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
701                        #[cfg(feature = "crypto")]
702                        if let Some(rejected) = self.accept_peer_crypto(hp) {
703                            return Ok(rejected);
704                        }
705                        self.send_conclusion(Some(ExtensionType::HsRsp))
706                    }
707                    _ => Ok(self.reject(RejectionReason::Rogue)),
708                }
709            }
710        }
711    }
712
713    /// [`RendezvousHandshakeState::Connected`] (Initiator row item 4,
714    /// L2331-2334; Responder row item 4, L2377-2381): normally no more
715    /// handshake traffic, but a repeated CONCLUSION is answered with another
716    /// AGREEMENT (recovery rule 4, L2424-2432, from the other side's point of
717    /// view); anything else is disregarded rather than regressing a completed
718    /// handshake.
719    fn on_connected(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
720        if hp.handshake_type == HandshakeType::Conclusion {
721            return self.send_agreement();
722        }
723        Ok(Vec::new())
724    }
725
726    /// The cookie contest (§4.3.2, L2107-2135). Identical cookies are a
727    /// collision the draft says must not connect (L2119-2124) — surfaced by
728    /// the caller as [`RejectionReason::RdvCookie`].
729    ///
730    /// The draft's prose ("cookie value is greater than its peer's") reads
731    /// like a plain unsigned comparison, but a cookie is derived from a hash
732    /// (`derive_cookie`) and is effectively a uniformly random 32-bit value
733    /// — a plain `own_cookie > peer_cookie` unsigned compare gives the wrong
734    /// answer for roughly a quarter of all cookie pairs relative to a real
735    /// libsrt peer (whose own comparison is signed, not unsigned), which
736    /// shows up as an intermittent rendezvous failure against libsrt with no
737    /// pattern visible from either side alone (issue #1064). Ported from
738    /// libsrt's own tie-break (`srtcore/core.cpp`,
739    /// `CUDT::backwardCompatibleCookieContest`, v1.5.5): see
740    /// [`cookie_contest`].
741    fn resolve_role(&self, peer_cookie: u32) -> Result<RendezvousRole> {
742        if peer_cookie == self.own_cookie {
743            return Err(Error::InvalidField(InvalidField {
744                field: "rendezvous cookie",
745                reason: "identical to the peer's cookie (collision, L2119-2124)",
746            }));
747        }
748        Ok(cookie_contest(self.own_cookie, peer_cookie))
749    }
750
751    #[cfg(feature = "crypto")]
752    fn accept_peer_crypto(&mut self, hp: &HandshakePacket<'_>) -> Option<Vec<HandshakeOutput>> {
753        let parsed = match handshake_sm::parse_peer_extensions(hp) {
754            Ok(p) => p,
755            Err(_) => return Some(self.reject(RejectionReason::Rogue)),
756        };
757        match (&self.config.crypto, parsed.km) {
758            (Some(crypto), Some(km)) => match handshake_sm::recover_sek(&crypto.passphrase, &km) {
759                Ok((sek, salt)) => {
760                    self.crypto_recovered = Some((sek, salt));
761                    match handshake_sm::echo_key_material_as_response(&km) {
762                        Ok(e) => self.km_echo_ext = Some(e),
763                        Err(_) => return Some(self.reject(RejectionReason::Rogue)),
764                    }
765                }
766                Err(_) => return Some(self.reject(RejectionReason::BadSecret)),
767            },
768            (Some(_), None) | (None, Some(_)) => {
769                return Some(self.reject(RejectionReason::Unsecure));
770            }
771            (None, None) => {}
772        }
773        None
774    }
775
776    fn reject(&mut self, reason: RejectionReason) -> Vec<HandshakeOutput> {
777        self.state = RendezvousHandshakeState::Rejected;
778        vec![HandshakeOutput::Rejected(reason)]
779    }
780
781    fn resend(&mut self) -> Vec<HandshakeOutput> {
782        match self.retransmit.last_sent() {
783            Some(bytes) => vec![HandshakeOutput::Send(bytes.to_vec())],
784            None => Vec::new(),
785        }
786    }
787
788    /// Builds and sends a CONCLUSION: `ext_type` picks HSREQ/HSRSP, or `None`
789    /// for the extension-less greeting (§4.3.2.2, L2286-2288: no Stream ID /
790    /// Group Membership is ever attached — see module docs).
791    fn send_conclusion(&mut self, ext_type: Option<ExtensionType>) -> Result<Vec<HandshakeOutput>> {
792        #[allow(unused_mut)]
793        let (mut ext_bytes, mut ext_flags): (Vec<u8>, u16) = match ext_type {
794            None => (Vec::new(), 0),
795            Some(t) => {
796                let hs_msg = HsExtMessage {
797                    srt_version: self.config.srt_version,
798                    srt_flags: self.config.flags,
799                    receiver_tsbpd_delay_ms: self.config.latency_ms,
800                    sender_tsbpd_delay_ms: self.config.latency_ms,
801                };
802                handshake_sm::build_conclusion_extensions(t, &hs_msg, None, None)?
803            }
804        };
805        // §6.1.5: the Initiator (cookie-contest winner) sends the Key
806        // Material request piggybacked on its CONCLUSION's HSREQ block;
807        // the Responder echoes it back on its HSRSP CONCLUSION.
808        #[cfg(feature = "crypto")]
809        if ext_type == Some(ExtensionType::HsReq)
810            && let Some(crypto) = &self.config.crypto
811        {
812            let km_ext = handshake_sm::build_key_material_extension(crypto)?;
813            ext_bytes.extend(km_ext);
814            ext_flags |= crate::packet::handshake::HS_EXT_FLAG_KMREQ;
815        }
816        #[cfg(feature = "crypto")]
817        if ext_type == Some(ExtensionType::HsRsp)
818            && let Some(echo) = &self.km_echo_ext
819        {
820            ext_bytes.extend(echo.clone());
821            ext_flags |= crate::packet::handshake::HS_EXT_FLAG_KMREQ;
822        }
823        let hp = HandshakePacket {
824            timestamp: 0,
825            dest_socket_id: self.peer_socket_id,
826            version: HANDSHAKE_VERSION_5,
827            encryption_field: self.config.encryption_field,
828            extension_field: HandshakeExtensionFlags(ext_flags),
829            initial_seq_number: self.config.initial_seq_number,
830            mtu: self.config.mtu,
831            max_flow_window_size: self.config.max_flow_window_size,
832            handshake_type: HandshakeType::Conclusion,
833            srt_socket_id: self.own_socket_id,
834            syn_cookie: self.own_cookie,
835            peer_ip: self.config.local_ip,
836            extensions: HandshakeExtensions(&ext_bytes),
837        };
838        let bytes = handshake_sm::build_bytes(hp)?;
839        self.retransmit.arm_fresh(&bytes);
840        Ok(vec![HandshakeOutput::Send(bytes)])
841    }
842
843    /// Builds and sends an AGREEMENT: no extensions (§4.3.2.1, L2224-2230).
844    fn send_agreement(&mut self) -> Result<Vec<HandshakeOutput>> {
845        let hp = HandshakePacket {
846            timestamp: 0,
847            dest_socket_id: self.peer_socket_id,
848            version: HANDSHAKE_VERSION_5,
849            encryption_field: EncryptionField::NoEncryption,
850            extension_field: HandshakeExtensionFlags(0),
851            initial_seq_number: self.config.initial_seq_number,
852            mtu: self.config.mtu,
853            max_flow_window_size: self.config.max_flow_window_size,
854            handshake_type: HandshakeType::Agreement,
855            srt_socket_id: self.own_socket_id,
856            syn_cookie: self.own_cookie,
857            peer_ip: self.config.local_ip,
858            extensions: HandshakeExtensions(&[]),
859        };
860        let bytes = handshake_sm::build_bytes(hp)?;
861        self.retransmit.arm_fresh(&bytes);
862        Ok(vec![HandshakeOutput::Send(bytes)])
863    }
864
865    /// Reaches [`RendezvousHandshakeState::Connected`]: builds
866    /// [`NegotiatedParams`] from `self.peer_hs_msg` (always captured by every
867    /// caller of this method before it is called) and sends the AGREEMENT
868    /// every documented transition into Connected requires.
869    fn enter_connected(&mut self) -> Result<Vec<HandshakeOutput>> {
870        let negotiated = self.build_negotiated()?;
871        self.negotiated = Some(negotiated.clone());
872        self.state = RendezvousHandshakeState::Connected;
873        let mut out = self.send_agreement()?;
874        out.push(HandshakeOutput::Connected(negotiated));
875        Ok(out)
876    }
877
878    fn build_negotiated(&self) -> Result<NegotiatedParams> {
879        let (Some(peer_msg), Some((peer_mtu, peer_mfw))) = (self.peer_hs_msg, self.peer_limits)
880        else {
881            return Err(Error::HandshakeOutOfSequence {
882                state: self.state.name(),
883                reason: "reached Connected without the peer's Handshake Extension Message",
884            });
885        };
886        Ok(NegotiatedParams {
887            version: HANDSHAKE_VERSION_5,
888            flags: HandshakeExtensionMessageFlags(self.config.flags.0 & peer_msg.srt_flags.0),
889            latency_ms: handshake_sm::negotiate_latency_ms(self.config.latency_ms, &peer_msg),
890            own_socket_id: self.own_socket_id,
891            peer_socket_id: self.peer_socket_id,
892            mtu: self.config.mtu.min(peer_mtu),
893            max_flow_window_size: self.config.max_flow_window_size.min(peer_mfw),
894            // §4.3.2 never mentions a Stream ID / Group Membership exchange.
895            stream_id: None,
896            group: None,
897            #[cfg(feature = "crypto")]
898            sek: {
899                match self.role {
900                    Some(RendezvousRole::Initiator) => {
901                        if self.config.crypto.is_some() && self.crypto_verified {
902                            self.config
903                                .crypto
904                                .as_ref()
905                                .map(|c| handshake_sm::SecretBytes::new(c.sek.clone()))
906                        } else {
907                            None
908                        }
909                    }
910                    Some(RendezvousRole::Responder) => {
911                        self.crypto_recovered.as_ref().map(|(sek, _)| sek.clone())
912                    }
913                    None => None,
914                }
915            },
916            #[cfg(feature = "crypto")]
917            salt: {
918                match self.role {
919                    Some(RendezvousRole::Initiator) => {
920                        if self.config.crypto.is_some() && self.crypto_verified {
921                            self.config.crypto.as_ref().map(|c| c.salt)
922                        } else {
923                            None
924                        }
925                    }
926                    Some(RendezvousRole::Responder) => {
927                        self.crypto_recovered.as_ref().map(|(_, salt)| *salt)
928                    }
929                    None => None,
930                }
931            },
932        })
933    }
934}
935
936#[cfg(test)]
937mod tests {
938    use super::*;
939    use crate::packet::handshake::HS_EXT_FLAG_HSREQ;
940
941    #[test]
942    fn start_is_idempotent_guard() {
943        let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
944        assert!(r.start().is_ok());
945        assert!(matches!(
946            r.start(),
947            Err(crate::error::Error::HandshakeOutOfSequence { .. })
948        ));
949    }
950
951    #[test]
952    fn wavehand_wire_values_match_draft_4_3_2() {
953        let mut r = RendezvousHandshake::new(0xAAAA_BBBB, 0xC0FF_EE00, HandshakeConfig::default());
954        let bytes = r.start().unwrap();
955        let pkt = ControlPacket::parse(&bytes).unwrap();
956        match pkt {
957            ControlPacket::Handshake(hp) => {
958                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
959                assert_eq!(hp.handshake_type, HandshakeType::Wavehand);
960                assert_eq!(hp.srt_socket_id, 0xAAAA_BBBB);
961                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
962                assert_eq!(hp.extension_field.0, 0);
963            }
964            _ => panic!("expected handshake"),
965        }
966        assert_eq!(r.state(), RendezvousHandshakeState::Waving);
967    }
968
969    fn wavehand(socket_id: u32, cookie: u32) -> ControlPacket<'static> {
970        ControlPacket::Handshake(HandshakePacket {
971            timestamp: 0,
972            dest_socket_id: 0,
973            version: HANDSHAKE_VERSION_5,
974            encryption_field: EncryptionField::NoEncryption,
975            extension_field: HandshakeExtensionFlags(0),
976            initial_seq_number: 0,
977            mtu: 1500,
978            max_flow_window_size: 8192,
979            handshake_type: HandshakeType::Wavehand,
980            srt_socket_id: socket_id,
981            syn_cookie: cookie,
982            peer_ip: [0; 4],
983            extensions: HandshakeExtensions(&[]),
984        })
985    }
986
987    #[test]
988    fn greater_cookie_wins_initiator() {
989        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
990        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
991        a.start().unwrap();
992        b.start().unwrap();
993
994        a.feed(&wavehand(2, 100)).unwrap();
995        b.feed(&wavehand(1, 500)).unwrap();
996
997        assert_eq!(a.role(), Some(RendezvousRole::Initiator));
998        assert_eq!(b.role(), Some(RendezvousRole::Responder));
999        assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1000        assert_eq!(b.state(), RendezvousHandshakeState::Attention);
1001    }
1002
1003    /// Sign-boundary cookie-contest table (issue #1064). Every case here
1004    /// pins `cookie_contest`'s result against the libsrt algorithm it ports
1005    /// — hand-traced from `CUDT::backwardCompatibleCookieContest`, not
1006    /// re-derived from this crate's own implementation (the point is
1007    /// catching a misport, not just re-checking `contest > 0`).
1008    ///
1009    /// A plain unsigned `own_cookie > peer_cookie` compare (this function's
1010    /// pre-#1064 behavior) gives the OPPOSITE answer to several of these —
1011    /// marked below — because it doesn't reinterpret either cookie as
1012    /// signed before comparing.
1013    #[test]
1014    fn cookie_contest_sign_boundary_table() {
1015        let cases: &[(u32, u32, RendezvousRole, &str)] = &[
1016            // Both positive as i32 (top bit clear): signed and unsigned
1017            // agree — the ordinary case.
1018            (
1019                500,
1020                100,
1021                RendezvousRole::Initiator,
1022                "both positive, own > peer",
1023            ),
1024            (
1025                100,
1026                500,
1027                RendezvousRole::Responder,
1028                "both positive, own < peer",
1029            ),
1030            // Exactly one cookie has the top bit set: signed and unsigned
1031            // DISAGREE. libsrt's signed compare makes the negative
1032            // (top-bit-set) one lose regardless of its unsigned magnitude.
1033            (
1034                0xAAAA_0002,
1035                0x1111_0001,
1036                RendezvousRole::Responder,
1037                "own top-bit-set (negative), peer positive — unsigned would say Initiator",
1038            ),
1039            (
1040                0x1111_0001,
1041                0xAAAA_0002,
1042                RendezvousRole::Initiator,
1043                "own positive, peer top-bit-set (negative) — unsigned would say Responder",
1044            ),
1045            // Both top-bit-set (both negative as i32): signed compare among
1046            // two negatives, still needs to agree with libsrt, not just
1047            // "unsigned compare of the raw bit pattern" (which happens to
1048            // still hold here since the *relative* order of two same-signed
1049            // values is the same either way — included as a same-sign
1050            // sanity check, not a disagreement case).
1051            (
1052                0xFFFF_FFFF,
1053                0x8000_0000,
1054                RendezvousRole::Initiator,
1055                "both negative, own > peer",
1056            ),
1057            (
1058                0x8000_0000,
1059                0xFFFF_FFFF,
1060                RendezvousRole::Responder,
1061                "both negative, own < peer",
1062            ),
1063            // The exact halfway point (`own - peer == i32::MIN`, `0x8000_0000`
1064            // as the wrapping 32-bit difference): libsrt's own tie-break for
1065            // this specific case falls back to a raw signed `req > res`
1066            // comparison of the two cookies themselves (see `cookie_contest`'s
1067            // doc) rather than the contest direction.
1068            (
1069                0x8000_0000,
1070                0,
1071                RendezvousRole::Responder,
1072                "halfway point, own negative vs peer zero: raw signed own(<0) > peer(0) is false",
1073            ),
1074            (
1075                0,
1076                0x8000_0000,
1077                RendezvousRole::Initiator,
1078                "halfway point, own zero vs peer negative: raw signed own(0) > peer(<0) is true",
1079            ),
1080        ];
1081        for &(own, peer, expected, why) in cases {
1082            let got = cookie_contest(own, peer);
1083            assert_eq!(
1084                got, expected,
1085                "own={own:#010x} peer={peer:#010x}: expected {expected:?}, got {got:?} ({why})"
1086            );
1087        }
1088    }
1089
1090    #[test]
1091    fn identical_cookies_are_rejected_as_a_collision() {
1092        let mut a = RendezvousHandshake::new(1, 0x00C0_FFEE, HandshakeConfig::default());
1093        a.start().unwrap();
1094        let outputs = a.feed(&wavehand(2, 0x00C0_FFEE)).unwrap();
1095        assert_eq!(
1096            outputs,
1097            vec![HandshakeOutput::Rejected(RejectionReason::RdvCookie)]
1098        );
1099        assert_eq!(a.state(), RendezvousHandshakeState::Rejected);
1100    }
1101
1102    #[test]
1103    fn initiator_attention_entry_sends_hsreq() {
1104        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1105        a.start().unwrap();
1106        let outputs = a.feed(&wavehand(2, 100)).unwrap();
1107        assert_eq!(outputs.len(), 1);
1108        let bytes = match &outputs[0] {
1109            HandshakeOutput::Send(b) => b.clone(),
1110            other => panic!("expected Send, got {other:?}"),
1111        };
1112        let pkt = ControlPacket::parse(&bytes).unwrap();
1113        match pkt {
1114            ControlPacket::Handshake(hp) => {
1115                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1116                assert_eq!(hp.extension_field.0 & HS_EXT_FLAG_HSREQ, HS_EXT_FLAG_HSREQ);
1117                let blocks: Vec<_> = hp.extensions.iter().map(|b| b.unwrap()).collect();
1118                assert_eq!(blocks.len(), 1);
1119                assert_eq!(blocks[0].ext_type, ExtensionType::HsReq);
1120            }
1121            _ => panic!("expected handshake"),
1122        }
1123    }
1124
1125    #[test]
1126    fn responder_attention_entry_sends_empty_conclusion() {
1127        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1128        b.start().unwrap();
1129        let outputs = b.feed(&wavehand(1, 500)).unwrap();
1130        assert_eq!(outputs.len(), 1);
1131        let bytes = match &outputs[0] {
1132            HandshakeOutput::Send(b) => b.clone(),
1133            other => panic!("expected Send, got {other:?}"),
1134        };
1135        let pkt = ControlPacket::parse(&bytes).unwrap();
1136        match pkt {
1137            ControlPacket::Handshake(hp) => {
1138                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1139                assert_eq!(hp.extension_field.0, 0);
1140                assert_eq!(hp.extensions.iter().count(), 0);
1141            }
1142            _ => panic!("expected handshake"),
1143        }
1144    }
1145
1146    #[test]
1147    fn malformed_extension_mid_flow_is_rejected_not_panicking() {
1148        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1149        a.start().unwrap();
1150        a.feed(&wavehand(2, 100)).unwrap();
1151        assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1152
1153        // A CONCLUSION whose extension block declares a length far larger
1154        // than the bytes actually present.
1155        let bad_ext: &'static [u8] = &[0x00, 0x01, 0xFF, 0xFF];
1156        let bad = ControlPacket::Handshake(HandshakePacket {
1157            timestamp: 0,
1158            dest_socket_id: 1,
1159            version: HANDSHAKE_VERSION_5,
1160            encryption_field: EncryptionField::NoEncryption,
1161            extension_field: HandshakeExtensionFlags(HS_EXT_FLAG_HSREQ),
1162            initial_seq_number: 0,
1163            mtu: 1500,
1164            max_flow_window_size: 8192,
1165            handshake_type: HandshakeType::Conclusion,
1166            srt_socket_id: 2,
1167            syn_cookie: 100,
1168            peer_ip: [0; 4],
1169            extensions: HandshakeExtensions(bad_ext),
1170        });
1171        let outputs = a.feed(&bad).unwrap();
1172        assert_eq!(
1173            outputs,
1174            vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]
1175        );
1176        assert_eq!(a.state(), RendezvousHandshakeState::Rejected);
1177    }
1178
1179    #[test]
1180    fn feed_before_start_is_out_of_sequence() {
1181        let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1182        assert!(matches!(
1183            r.feed(&wavehand(2, 100)),
1184            Err(Error::HandshakeOutOfSequence { .. })
1185        ));
1186    }
1187
1188    #[test]
1189    fn feed_rejects_non_handshake_packets_outside_recovery_case() {
1190        use crate::packet::misc::KeepAlivePacket;
1191        let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1192        r.start().unwrap();
1193        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
1194            timestamp: 0,
1195            dest_socket_id: 0,
1196            libsrt_pad: false,
1197        });
1198        assert!(matches!(
1199            r.feed(&ka),
1200            Err(Error::UnexpectedControlPacket { .. })
1201        ));
1202    }
1203
1204    /// The state machine's internal invariants (a role is resolved before
1205    /// Attention/Initiated, the peer's HSREQ/HSRSP is known before Connected)
1206    /// are errors, not panics, if ever violated.
1207    #[test]
1208    fn broken_internal_invariants_are_errors_not_panics() {
1209        use crate::packet::{EncryptionField, HandshakeExtensionFlags, HandshakeExtensions};
1210        let hp = HandshakePacket {
1211            timestamp: 0,
1212            dest_socket_id: 1,
1213            version: 5,
1214            encryption_field: EncryptionField::NoEncryption,
1215            extension_field: HandshakeExtensionFlags(0),
1216            initial_seq_number: 0,
1217            mtu: 1500,
1218            max_flow_window_size: 8192,
1219            handshake_type: HandshakeType::Conclusion,
1220            srt_socket_id: 2,
1221            syn_cookie: 0,
1222            peer_ip: [0; 4],
1223            extensions: HandshakeExtensions(&[]),
1224        };
1225        let mut r = RendezvousHandshake::new(1, 5, HandshakeConfig::default());
1226        assert!(matches!(
1227            r.on_attention(&hp),
1228            Err(Error::HandshakeOutOfSequence { .. })
1229        ));
1230        assert!(matches!(
1231            r.on_initiated(&hp),
1232            Err(Error::HandshakeOutOfSequence { .. })
1233        ));
1234        assert!(matches!(
1235            r.enter_connected(),
1236            Err(Error::HandshakeOutOfSequence { .. })
1237        ));
1238    }
1239}
1240
1241#[cfg(all(test, feature = "crypto"))]
1242mod crypto_echo_tests {
1243    use super::super::*;
1244    #[cfg(feature = "crypto")]
1245    use crate::handshake_sm::CryptoConfig;
1246
1247    #[cfg(feature = "crypto")]
1248    #[test]
1249    fn rendezvous_initiator_rejects_a_tampered_km_echo() {
1250        use crate::packet::{ControlPacket, EncryptionField};
1251
1252        const PEER_A_SOCKET_ID: u32 = 0x1111_1111;
1253        const PEER_B_SOCKET_ID: u32 = 0x2222_2222;
1254        const PEER_A_COOKIE: u32 = 0xAAAA_0002;
1255        const PEER_B_COOKIE: u32 = 0x1111_0001;
1256
1257        let passphrase = b"passphrase".to_vec();
1258        let crypto = CryptoConfig {
1259            passphrase: passphrase.clone(),
1260            salt: [0x11u8; 16],
1261            sek: vec![0x22u8; 16],
1262        };
1263        let config_a = HandshakeConfig {
1264            encryption_field: EncryptionField::Aes128,
1265            crypto: Some(crypto.clone()),
1266            ..HandshakeConfig::default()
1267        };
1268        let config_b = HandshakeConfig {
1269            encryption_field: EncryptionField::Aes128,
1270            crypto: Some(crypto),
1271            ..HandshakeConfig::default()
1272        };
1273
1274        // Untampered run must complete.
1275        {
1276            let mut a = RendezvousHandshake::new(PEER_A_SOCKET_ID, PEER_A_COOKIE, config_a.clone());
1277            let mut b = RendezvousHandshake::new(PEER_B_SOCKET_ID, PEER_B_COOKIE, config_b.clone());
1278            let mut to_a = vec![b.start().expect("b start")];
1279            let mut to_b = vec![a.start().expect("a start")];
1280            for _ in 0..20 {
1281                if a.state() == RendezvousHandshakeState::Connected
1282                    && b.state() == RendezvousHandshakeState::Connected
1283                {
1284                    break;
1285                }
1286                let mut next_to_a = Vec::new();
1287                let mut next_to_b = Vec::new();
1288                for msg in to_a.drain(..) {
1289                    let pkt = ControlPacket::parse(&msg).expect("valid");
1290                    for out in a.feed(&pkt).expect("a.feed") {
1291                        if let HandshakeOutput::Send(bytes) = out {
1292                            next_to_b.push(bytes);
1293                        }
1294                    }
1295                }
1296                for msg in to_b.drain(..) {
1297                    let pkt = ControlPacket::parse(&msg).expect("valid");
1298                    for out in b.feed(&pkt).expect("b.feed") {
1299                        if let HandshakeOutput::Send(bytes) = out {
1300                            next_to_a.push(bytes);
1301                        }
1302                    }
1303                }
1304                to_a = next_to_a;
1305                to_b = next_to_b;
1306                if to_a.is_empty() && to_b.is_empty() {
1307                    break;
1308                }
1309            }
1310            assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1311            assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1312        }
1313
1314        // Tampered run: flip a byte in the Responder's key-material echo.
1315        let mut a = RendezvousHandshake::new(PEER_A_SOCKET_ID, PEER_A_COOKIE, config_a);
1316        let mut b = RendezvousHandshake::new(PEER_B_SOCKET_ID, PEER_B_COOKIE, config_b);
1317        let mut to_a = vec![b.start().expect("b start")];
1318        let mut to_b = vec![a.start().expect("a start")];
1319        let mut tampered = false;
1320        let mut rejected = false;
1321        for _ in 0..20 {
1322            if rejected {
1323                break;
1324            }
1325            if a.state() == RendezvousHandshakeState::Connected
1326                && b.state() == RendezvousHandshakeState::Connected
1327            {
1328                break;
1329            }
1330            let mut next_to_a = Vec::new();
1331            let mut next_to_b = Vec::new();
1332            for msg in to_a.drain(..) {
1333                let pkt = ControlPacket::parse(&msg).expect("valid");
1334                for out in a.feed(&pkt).expect("a.feed") {
1335                    if let HandshakeOutput::Send(bytes) = out {
1336                        next_to_b.push(bytes);
1337                    }
1338                }
1339            }
1340            for msg in to_b.drain(..) {
1341                let mut msg = msg;
1342                if !tampered && msg.windows(2).any(|w| w == [0, 4]) {
1343                    if let Some(last) = msg.last_mut() {
1344                        *last ^= 0xFF;
1345                    }
1346                    tampered = true;
1347                }
1348                let pkt = ControlPacket::parse(&msg).expect("valid");
1349                for out in b.feed(&pkt).expect("b.feed") {
1350                    match out {
1351                        HandshakeOutput::Send(bytes) => next_to_a.push(bytes),
1352                        HandshakeOutput::Rejected(reason) => {
1353                            assert_eq!(reason, RejectionReason::BadSecret);
1354                            rejected = true;
1355                        }
1356                        _ => {}
1357                    }
1358                }
1359            }
1360            to_a = next_to_a;
1361            to_b = next_to_b;
1362            if to_a.is_empty() && to_b.is_empty() {
1363                break;
1364            }
1365        }
1366        assert!(tampered, "never found a key-material echo to tamper");
1367        assert!(rejected, "initiator did not reject the tampered echo");
1368        assert_eq!(b.state(), RendezvousHandshakeState::Rejected);
1369    }
1370}