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