Skip to main content

srt_runtime/
rendezvous.rs

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