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::cookie::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_core::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_core::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_core::impl_spec_display!(RendezvousRole);
188
189/// The sign bit of a 32-bit cookie, tested inside a wider (`i64`) type that
190/// has not been sign-extended into that width — see [`cookie_contest`].
191const COOKIE_SIGN_BIT: i64 = 0x8000_0000;
192
193/// The cookie contest tie-break (issue #1064): given two cookies (this
194/// side's and the peer's, both already known not to be equal — see
195/// [`RendezvousHandshake::resolve_role`]), decide which side is
196/// [`RendezvousRole::Initiator`].
197///
198/// A real SRT peer orders the two cookies as **signed** 32-bit integers, widened
199/// with sign extension, where the draft's role rule only says the greater cookie
200/// wins (`private/specs-verified/rules/srt-rendezvous.md`, "Cookie contest").
201/// A plain unsigned `own_cookie > peer_cookie` disagrees with that peer for
202/// roughly a quarter of all cookie pairs: whenever exactly one of the two
203/// cookies has its top bit set, the sign-extending widen and the unsigned widen
204/// order the pair differently, which showed up as an intermittent rendezvous
205/// failure against a real peer (issue #1064, `tests/it/libsrt_rendezvous.rs`).
206/// The exact tie-break below is that observed behaviour; no held text states
207/// it.
208///
209/// The `HSD_DRAW` arm is unreachable here (the caller already handles
210/// `own_cookie == peer_cookie` before this is called) and is not
211/// reproduced — this function always returns a role.
212fn cookie_contest(own_cookie: u32, peer_cookie: u32) -> RendezvousRole {
213    // Each cookie as a signed 32-bit integer: the same bits, reinterpreted (not
214    // converted).
215    let req = i32::from_ne_bytes(own_cookie.to_ne_bytes());
216    let res = i32::from_ne_bytes(peer_cookie.to_ne_bytes());
217    let xreq = i64::from(req);
218    let xres = i64::from(res);
219    let contest = xreq - xres;
220
221    if contest & COOKIE_SIGN_BIT != 0 {
222        let revert = xres - xreq;
223        if revert & COOKIE_SIGN_BIT != 0 && req > res {
224            return RendezvousRole::Initiator;
225        }
226        return RendezvousRole::Responder;
227    }
228
229    RendezvousRole::Initiator
230}
231
232/// The Handshake Extension content found on one received CONCLUSION, keyed by
233/// which side sends which (§4.3.2.2, L2282-2288). Internal to this module —
234/// [`crate::handshake_sm::parse_peer_extensions`] does not distinguish
235/// HSREQ from HSRSP, which the Rendezvous tables need to.
236enum PeerHsExt {
237    /// No Handshake Extension block present.
238    None,
239    /// An `HSREQ` block was present (only an Initiator sends this).
240    HsReq(HsExtMessage),
241    /// An `HSRSP` block was present (only a Responder sends this).
242    HsRsp(HsExtMessage),
243}
244
245/// Walks `hp`'s extension blocks looking for an HSREQ or HSRSP Handshake
246/// Extension Message. Returns [`Error::InvalidField`] on any malformed block
247/// or malformed HSREQ/HSRSP contents — never panics on untrusted input.
248fn parse_peer_hs_ext(hp: &HandshakePacket<'_>) -> Result<PeerHsExt> {
249    let mut found = PeerHsExt::None;
250    for block in hp.extensions.iter() {
251        match block.ext_type {
252            ExtensionType::HsReq => {
253                let msg = block.as_hs_ext_message().map_err(|_| {
254                    Error::InvalidField(InvalidField::new(
255                        "HSREQ extension message",
256                        "malformed contents",
257                    ))
258                })?;
259                found = PeerHsExt::HsReq(msg);
260            }
261            ExtensionType::HsRsp => {
262                let msg = block.as_hs_ext_message().map_err(|_| {
263                    Error::InvalidField(InvalidField::new(
264                        "HSRSP extension message",
265                        "malformed contents",
266                    ))
267                })?;
268                found = PeerHsExt::HsRsp(msg);
269            }
270            _ => {}
271        }
272    }
273    Ok(found)
274}
275
276/// A driveable, symmetric SRT Rendezvous handshake
277/// (`draft-sharabayko-srt-01` §4.3.2). See the module docs for the state
278/// machine and the design decisions not explicit in the curated rules.
279#[derive(Debug)]
280pub struct RendezvousHandshake {
281    own_socket_id: u32,
282    own_cookie: u32,
283    config: HandshakeConfig,
284    state: RendezvousHandshakeState,
285    role: Option<RendezvousRole>,
286    peer_socket_id: u32,
287    peer_cookie: u32,
288    peer_hs_msg: Option<HsExtMessage>,
289    /// The peer's `MTU` and `Maximum Flow Window Size` (§3.2.1), from the
290    /// packet that carried its Handshake Extension Message.
291    peer_limits: Option<(u32, u32)>,
292    retransmit: Retransmit,
293    clock: WireClock,
294    negotiated: Option<NegotiatedParams>,
295    #[cfg(feature = "crypto")]
296    crypto_recovered: Option<handshake_sm::RecoveredSek>,
297    #[cfg(feature = "crypto")]
298    km_echo: Option<alloc::vec::Vec<u8>>,
299    #[cfg(feature = "crypto")]
300    crypto_verified: bool,
301}
302
303impl RendezvousHandshake {
304    /// Creates a fresh Rendezvous handshake in
305    /// [`RendezvousHandshakeState::Idle`], with the 32-bit cookie this side
306    /// will offer in the cookie contest (§4.3.2, L2107-2135). This crate never
307    /// reads a clock or a socket address — see
308    /// [`crate::cookie::derive_cookie`] for a ready-made,
309    /// non-standardized derivation helper.
310    pub fn new(own_socket_id: u32, own_cookie: u32, config: HandshakeConfig) -> Self {
311        RendezvousHandshake {
312            own_socket_id,
313            own_cookie,
314            config,
315            state: RendezvousHandshakeState::Idle,
316            role: None,
317            peer_socket_id: 0,
318            peer_cookie: 0,
319            peer_hs_msg: None,
320            peer_limits: None,
321            retransmit: Retransmit::default(),
322            clock: WireClock::default(),
323            negotiated: None,
324            #[cfg(feature = "crypto")]
325            crypto_recovered: None,
326            #[cfg(feature = "crypto")]
327            km_echo: None,
328            #[cfg(feature = "crypto")]
329            crypto_verified: false,
330        }
331    }
332
333    /// Sets the time elapsed since the connection started; every packet built
334    /// from here on carries it as its wire timestamp (§3.2.1). The machine reads
335    /// no clock, so the driver calls this before each `start`, `feed` and `tick`.
336    pub fn set_elapsed(&mut self, elapsed: core::time::Duration) {
337        self.clock.set(elapsed);
338    }
339
340    /// The peer's SRT Socket ID once its first handshake packet has been accepted: later packets
341    /// naming another Socket ID are not the peer's and are ignored.
342    pub fn peer_socket_id(&self) -> Option<u32> {
343        match self.state {
344            RendezvousHandshakeState::Idle | RendezvousHandshakeState::Waving => None,
345            _ => Some(self.peer_socket_id),
346        }
347    }
348
349    /// The current state.
350    pub fn state(&self) -> RendezvousHandshakeState {
351        self.state
352    }
353
354    /// The role resolved by the cookie contest, once past
355    /// [`RendezvousHandshakeState::Waving`].
356    pub fn role(&self) -> Option<RendezvousRole> {
357        self.role
358    }
359
360    /// The negotiated parameters, once [`RendezvousHandshakeState::Connected`].
361    pub fn negotiated(&self) -> Option<&NegotiatedParams> {
362        self.negotiated.as_ref()
363    }
364
365    /// Builds the initial WAVEAHAND handshake (§4.3.2, L2100/L2153-2170:
366    /// Version 5, this side's own cookie, no extensions) and transitions to
367    /// [`RendezvousHandshakeState::Waving`].
368    ///
369    /// # Errors
370    /// [`Error::HandshakeOutOfSequence`] if called more than once.
371    pub fn start(&mut self) -> Result<Vec<u8>> {
372        if self.state != RendezvousHandshakeState::Idle {
373            return Err(Error::HandshakeOutOfSequence {
374                state: self.state.name(),
375                reason: "start() called after the handshake already began",
376            });
377        }
378        let hp = HandshakePacket {
379            timestamp: SrtTimestamp::from_wire(self.clock.now()),
380            dest_socket_id: SocketId::CONNECTION_REQUEST, // Unknown yet — mirrors CallerHandshake::start's INDUCTION.
381            version: HANDSHAKE_VERSION_5,
382            encryption_field: self.config.encryption_field,
383            extension_field: HandshakeExtensionFlags::new(0),
384            initial_seq_number: self.config.initial_seq_number,
385            mtu: self.config.mtu,
386            max_flow_window_size: self.config.max_flow_window_size,
387            handshake_type: HandshakeType::Wavehand,
388            srt_socket_id: self.own_socket_id,
389            syn_cookie: self.own_cookie,
390            peer_ip: self.config.local_ip,
391            extensions: HandshakeExtensions(Vec::new()),
392        };
393        let bytes = handshake_sm::build_bytes(hp)?;
394        self.retransmit.arm(&bytes);
395        self.state = RendezvousHandshakeState::Waving;
396        Ok(bytes)
397    }
398
399    /// Feeds an inbound control packet.
400    ///
401    /// A non-Handshake `ControlPacket` fed while this side is a Responder
402    /// stuck in [`RendezvousHandshakeState::Initiated`] is treated as
403    /// missing-packet recovery rule 3 (L2413-2422: "any control packet
404    /// normally only sent between connected parties") rather than an error —
405    /// see [`Self::on_recovery_trigger`] for the data-packet analogue.
406    ///
407    /// # Errors
408    /// [`Error::UnexpectedControlPacket`] for a non-Handshake packet outside
409    /// that one recovery case; [`Error::HandshakeOutOfSequence`] if fed before
410    /// [`Self::start`] or after a terminal state (a driver bug, not a peer
411    /// protocol failure).
412    pub fn feed(&mut self, packet: &ControlPacket<'_>) -> Result<Vec<HandshakeOutput>> {
413        let hp = match packet {
414            ControlPacket::Handshake(hp) => hp,
415            other => {
416                if self.state == RendezvousHandshakeState::Initiated
417                    && self.role == Some(RendezvousRole::Responder)
418                {
419                    return self.enter_connected();
420                }
421                return Err(Error::UnexpectedControlPacket {
422                    actual: other.control_type().name(),
423                });
424            }
425        };
426        if let Some(reason) = RejectionReason::from_handshake_type(hp.handshake_type) {
427            return Ok(self.reject(reason));
428        }
429        if hp.version != HANDSHAKE_VERSION_5 {
430            // §4.3.2, L2101-2105: Version-4 legacy Rendezvous is out of scope.
431            return Ok(self.reject(RejectionReason::Version));
432        }
433        if (hp.initial_seq_number > crate::packet::SEQ_NUMBER_MASK
434            || hp.mtu == 0
435            || hp.max_flow_window_size == 0)
436            && self.state != RendezvousHandshakeState::Idle
437        {
438            return Ok(self.reject(RejectionReason::Rogue));
439        }
440        if matches!(
441            self.state,
442            RendezvousHandshakeState::Attention
443                | RendezvousHandshakeState::Initiated
444                | RendezvousHandshakeState::Connected
445        ) && (hp.srt_socket_id != self.peer_socket_id || hp.syn_cookie != self.peer_cookie)
446        {
447            return Ok(Vec::new());
448        }
449        match self.state {
450            RendezvousHandshakeState::Idle => Err(Error::HandshakeOutOfSequence {
451                state: self.state.name(),
452                reason: "feed() called before start()",
453            }),
454            RendezvousHandshakeState::Waving => self.on_waving(hp),
455            RendezvousHandshakeState::Attention => self.on_attention(hp),
456            RendezvousHandshakeState::Initiated => self.on_initiated(hp),
457            RendezvousHandshakeState::Connected => self.on_connected(hp),
458            RendezvousHandshakeState::Rejected | RendezvousHandshakeState::TimedOut => {
459                Err(Error::HandshakeOutOfSequence {
460                    state: self.state.name(),
461                    reason: "handshake already reached a terminal state",
462                })
463            }
464        }
465    }
466
467    /// Convenience wrapper: parses `bytes` as a [`ControlPacket`] then
468    /// [`Self::feed`]s it.
469    pub fn feed_bytes(&mut self, bytes: &[u8]) -> Result<Vec<HandshakeOutput>> {
470        let packet = ControlPacket::parse(bytes)?;
471        self.feed(&packet)
472    }
473
474    /// Missing-packet recovery rule 3 (§4.3.2.2, L2413-2422): call this when
475    /// the driver receives a data packet (`SrtPacket::Data`) while this side
476    /// has not yet reached [`RendezvousHandshakeState::Connected`]. A no-op
477    /// (`Ok(Vec::new())`) unless this side is a Responder stuck in
478    /// [`RendezvousHandshakeState::Initiated`] — the one case the draft says
479    /// is "exceptionally allowed" to promote to Connected "as if it had
480    /// received AGREEMENT".
481    pub fn on_recovery_trigger(&mut self) -> Result<Vec<HandshakeOutput>> {
482        if self.state == RendezvousHandshakeState::Initiated
483            && self.role == Some(RendezvousRole::Responder)
484        {
485            self.enter_connected()
486        } else {
487            Ok(Vec::new())
488        }
489    }
490
491    /// Advances retransmit timing by one caller-defined tick, mirroring
492    /// [`crate::caller::CallerHandshake::tick`] /
493    /// [`crate::listener::ListenerHandshake::tick`].
494    pub fn tick(&mut self, elapsed: Duration) -> Vec<HandshakeOutput> {
495        if matches!(
496            self.state,
497            RendezvousHandshakeState::Idle
498                | RendezvousHandshakeState::Connected
499                | RendezvousHandshakeState::Rejected
500                | RendezvousHandshakeState::TimedOut
501        ) {
502            return Vec::new();
503        }
504        let step = self.retransmit.tick(elapsed, &self.config);
505        if matches!(step, RetransmitStep::TimedOut) {
506            self.state = RendezvousHandshakeState::TimedOut;
507        }
508        step.into_outputs()
509    }
510
511    /// [`RendezvousHandshakeState::Waving`]: the first message ever received
512    /// from the peer — either a genuine WAVEAHAND (§4.3.2.2 Waving row,
513    /// L2301-2306 Initiator / L2336-2342 Responder) or, in the Serial flow's
514    /// crossing case, a CONCLUSION directly (see module docs). Either way the
515    /// cookie contest is resolved here, from `hp.syn_cookie`.
516    fn on_waving(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
517        if !matches!(
518            hp.handshake_type,
519            HandshakeType::Wavehand | HandshakeType::Conclusion
520        ) {
521            return Ok(self.reject(RejectionReason::Rogue));
522        }
523        self.peer_socket_id = hp.srt_socket_id;
524        let role = match self.resolve_role(hp.syn_cookie) {
525            Ok(r) => r,
526            Err(_) => return Ok(self.reject(RejectionReason::RdvCookie)),
527        };
528        self.peer_cookie = hp.syn_cookie;
529        self.role = Some(role);
530
531        if hp.handshake_type == HandshakeType::Wavehand {
532            self.state = RendezvousHandshakeState::Attention;
533            match role {
534                // Initiator Waving row (L2301-2306): send CONCLUSION+HSREQ.
535                RendezvousRole::Initiator => self.send_conclusion(Some(ExtensionType::HsReq)),
536                // Responder Waving row (L2336-2342): send CONCLUSION, no
537                // extensions (it has not seen the peer's HSREQ yet).
538                RendezvousRole::Responder => self.send_conclusion(None),
539            }
540        } else {
541            // Serial-flow crossing (§4.3.2.1 step 3, L2203-2219): apply the
542            // same content-driven Attention-row logic (module docs).
543            self.on_attention_conclusion(hp, role)
544        }
545    }
546
547    /// [`RendezvousHandshakeState::Attention`]: a WAVEAHAND was already seen
548    /// and processed; only a CONCLUSION (Attention row) or a duplicate
549    /// WAVEAHAND (not covered by either table — treated as a benign resend,
550    /// module docs) is expected here.
551    fn on_attention(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
552        let role = self.role.ok_or(Error::HandshakeOutOfSequence {
553            state: self.state.name(),
554            reason: "no role was resolved before the Attention state",
555        })?;
556        if hp.handshake_type == HandshakeType::Conclusion {
557            return self.on_attention_conclusion(hp, role);
558        }
559        if hp.handshake_type == HandshakeType::Wavehand {
560            return Ok(self.resend());
561        }
562        Ok(self.reject(RejectionReason::Rogue))
563    }
564
565    /// The Attention row's CONCLUSION-handling logic (§4.3.2.2, L2307-2320
566    /// Initiator / L2343-2364 Responder), shared between a genuine
567    /// [`RendezvousHandshakeState::Attention`] and the Serial-flow crossing
568    /// case fed straight from [`RendezvousHandshakeState::Waving`].
569    fn on_attention_conclusion(
570        &mut self,
571        hp: &HandshakePacket<'_>,
572        role: RendezvousRole,
573    ) -> Result<Vec<HandshakeOutput>> {
574        self.peer_socket_id = hp.srt_socket_id;
575        let ext = match parse_peer_hs_ext(hp) {
576            Ok(e) => e,
577            Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
578        };
579        match (role, ext) {
580            (RendezvousRole::Initiator, PeerHsExt::None) => {
581                // L2312-2318: no extensions -> Initiated, still send
582                // CONCLUSION+HSREQ.
583                self.state = RendezvousHandshakeState::Initiated;
584                self.send_conclusion(Some(ExtensionType::HsReq))
585            }
586            (RendezvousRole::Initiator, PeerHsExt::HsRsp(msg)) => {
587                // L2318-2320: contains HSRSP -> Connected, send AGREEMENT.
588                self.peer_hs_msg = Some(msg);
589                self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
590                #[cfg(feature = "crypto")]
591                {
592                    let parsed = match handshake_sm::parse_peer_extensions(hp) {
593                        Ok(p) => p,
594                        Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
595                    };
596                    match (&self.config.crypto, parsed.km) {
597                        (Some(crypto), Some(km)) => {
598                            if !handshake_sm::verify_km_echo(crypto, &km) {
599                                return Ok(self.reject(RejectionReason::BadSecret));
600                            }
601                            self.crypto_verified = true;
602                        }
603                        (Some(_), None) | (None, Some(_)) => {
604                            return Ok(self.reject(RejectionReason::Unsecure));
605                        }
606                        (None, None) => {}
607                    }
608                }
609                self.enter_connected()
610            }
611            (RendezvousRole::Responder, PeerHsExt::None) => {
612                // L2357-2360: no extensions yet -> resend the empty
613                // CONCLUSION, remain in Attention.
614                self.state = RendezvousHandshakeState::Attention;
615                self.send_conclusion(None)
616            }
617            (RendezvousRole::Responder, PeerHsExt::HsReq(msg)) => {
618                // L2360-2364: HSREQ present -> Initiated, send
619                // CONCLUSION+HSRSP.
620                self.peer_hs_msg = Some(msg);
621                self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
622                #[cfg(feature = "crypto")]
623                if let Some(rejected) = self.accept_peer_crypto(hp) {
624                    return Ok(rejected);
625                }
626                self.state = RendezvousHandshakeState::Initiated;
627                self.send_conclusion(Some(ExtensionType::HsRsp))
628            }
629            // A peer sending the extension kind only its own role should ever
630            // send (HSREQ into an Initiator, HSRSP into a Responder) is not a
631            // transition either table defines — reject rather than guess.
632            _ => Ok(self.reject(RejectionReason::Rogue)),
633        }
634    }
635
636    /// [`RendezvousHandshakeState::Initiated`] (§4.3.2.2, L2321-2334 Initiator
637    /// / L2365-2382 Responder), including the idempotent-resend recovery
638    /// rules (L2383-2422).
639    fn on_initiated(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
640        let role = self.role.ok_or(Error::HandshakeOutOfSequence {
641            state: self.state.name(),
642            reason: "no role was resolved before the Initiated state",
643        })?;
644        if hp.handshake_type == HandshakeType::Wavehand {
645            return Ok(self.resend());
646        }
647        match role {
648            RendezvousRole::Initiator => {
649                if hp.handshake_type != HandshakeType::Conclusion {
650                    return Ok(self.reject(RejectionReason::Rogue));
651                }
652                let ext = match parse_peer_hs_ext(hp) {
653                    Ok(e) => e,
654                    Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
655                };
656                match ext {
657                    // L2325: "REMAINS IN THIS STATE" — still resend
658                    // CONCLUSION+HSREQ.
659                    PeerHsExt::None => self.send_conclusion(Some(ExtensionType::HsReq)),
660                    // L2325-2334ish: contains HSRSP -> Connected, AGREEMENT.
661                    PeerHsExt::HsRsp(msg) => {
662                        self.peer_hs_msg = Some(msg);
663                        self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
664                        #[cfg(feature = "crypto")]
665                        {
666                            let parsed = match handshake_sm::parse_peer_extensions(hp) {
667                                Ok(p) => p,
668                                Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
669                            };
670                            match (&self.config.crypto, parsed.km) {
671                                (Some(crypto), Some(km)) => {
672                                    if !handshake_sm::verify_km_echo(crypto, &km) {
673                                        return Ok(self.reject(RejectionReason::BadSecret));
674                                    }
675                                    self.crypto_verified = true;
676                                }
677                                (Some(_), None) | (None, Some(_)) => {
678                                    return Ok(self.reject(RejectionReason::Unsecure));
679                                }
680                                (None, None) => {}
681                            }
682                        }
683                        self.enter_connected()
684                    }
685                    PeerHsExt::HsReq(_) => Ok(self.reject(RejectionReason::Rogue)),
686                }
687            }
688            RendezvousRole::Responder => {
689                if hp.handshake_type == HandshakeType::Agreement {
690                    // Responder Initiated row: AGREEMENT -> respond AGREEMENT,
691                    // switch to Connected.
692                    return self.enter_connected();
693                }
694                if hp.handshake_type != HandshakeType::Conclusion {
695                    return Ok(self.reject(RejectionReason::Rogue));
696                }
697                let ext = match parse_peer_hs_ext(hp) {
698                    Ok(e) => e,
699                    Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
700                };
701                match ext {
702                    // Recovery rule 2 (L2391-2395): MUST always resend HSRSP,
703                    // even if this HSREQ was already seen and processed once.
704                    PeerHsExt::HsReq(msg) => {
705                        self.peer_hs_msg = Some(msg);
706                        self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
707                        #[cfg(feature = "crypto")]
708                        if let Some(rejected) = self.accept_peer_crypto(hp) {
709                            return Ok(rejected);
710                        }
711                        self.send_conclusion(Some(ExtensionType::HsRsp))
712                    }
713                    _ => Ok(self.reject(RejectionReason::Rogue)),
714                }
715            }
716        }
717    }
718
719    /// [`RendezvousHandshakeState::Connected`] (Initiator row item 4,
720    /// L2331-2334; Responder row item 4, L2377-2381): normally no more
721    /// handshake traffic, but a repeated CONCLUSION is answered with another
722    /// AGREEMENT (recovery rule 4, L2424-2432, from the other side's point of
723    /// view); anything else is disregarded rather than regressing a completed
724    /// handshake.
725    fn on_connected(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
726        if hp.handshake_type == HandshakeType::Conclusion {
727            return self.send_agreement();
728        }
729        Ok(Vec::new())
730    }
731
732    /// The cookie contest (§4.3.2, L2107-2135). Identical cookies are a
733    /// collision the draft says must not connect (L2119-2124) — surfaced by
734    /// the caller as [`RejectionReason::RdvCookie`].
735    ///
736    /// The draft's prose ("cookie value is greater than its peer's") reads
737    /// like a plain unsigned comparison, but a cookie is derived from a hash
738    /// (`derive_cookie`) and is effectively a uniformly random 32-bit value
739    /// — a plain `own_cookie > peer_cookie` unsigned compare gives the wrong
740    /// answer for roughly a quarter of all cookie pairs relative to a real
741    /// libsrt peer (whose own comparison is signed, not unsigned), which
742    /// shows up as an intermittent rendezvous failure against libsrt with no
743    /// pattern visible from either side alone (issue #1064). See
744    /// [`cookie_contest`].
745    fn resolve_role(&self, peer_cookie: u32) -> Result<RendezvousRole> {
746        if peer_cookie == self.own_cookie {
747            return Err(Error::InvalidField(InvalidField::new(
748                "rendezvous cookie",
749                "identical to the peer's cookie (collision, L2119-2124)",
750            )));
751        }
752        Ok(cookie_contest(self.own_cookie, peer_cookie))
753    }
754
755    #[cfg(feature = "crypto")]
756    fn accept_peer_crypto(&mut self, hp: &HandshakePacket<'_>) -> Option<Vec<HandshakeOutput>> {
757        let parsed = match handshake_sm::parse_peer_extensions(hp) {
758            Ok(p) => p,
759            Err(_) => return Some(self.reject(RejectionReason::Rogue)),
760        };
761        match (&self.config.crypto, parsed.km) {
762            (Some(crypto), Some(km)) => {
763                let mut kek_cache = crate::crypto::KekCache::new();
764                match handshake_sm::recover_sek(&crypto.passphrase, &km, &mut kek_cache) {
765                    Ok((sek, salt)) => {
766                        self.crypto_recovered = Some((sek, salt));
767                        let mut contents = alloc::vec![0u8; km.serialized_len()];
768                        match km.serialize_into(&mut contents) {
769                            Ok(_) => self.km_echo = Some(contents),
770                            Err(_) => return Some(self.reject(RejectionReason::Rogue)),
771                        }
772                    }
773                    Err(_) => return Some(self.reject(RejectionReason::BadSecret)),
774                }
775            }
776            (Some(_), None) | (None, Some(_)) => {
777                return Some(self.reject(RejectionReason::Unsecure));
778            }
779            (None, None) => {}
780        }
781        None
782    }
783
784    fn reject(&mut self, reason: RejectionReason) -> Vec<HandshakeOutput> {
785        self.state = RendezvousHandshakeState::Rejected;
786        vec![HandshakeOutput::Rejected(reason)]
787    }
788
789    fn resend(&mut self) -> Vec<HandshakeOutput> {
790        match self.retransmit.last_sent() {
791            Some(bytes) => vec![HandshakeOutput::Send(bytes.to_vec())],
792            None => Vec::new(),
793        }
794    }
795
796    /// Builds and sends a CONCLUSION: `ext_type` picks HSREQ/HSRSP, or `None`
797    /// for the extension-less greeting (§4.3.2.2, L2286-2288: no Stream ID /
798    /// Group Membership is ever attached — see module docs).
799    fn send_conclusion(&mut self, ext_type: Option<ExtensionType>) -> Result<Vec<HandshakeOutput>> {
800        let ext_contents = match ext_type {
801            None => None,
802            Some(_) => {
803                let hs_msg = HsExtMessage {
804                    srt_version: self.config.srt_version,
805                    srt_flags: self.config.flags,
806                    receiver_tsbpd_delay: self.config.latency,
807                    sender_tsbpd_delay: self.config.latency,
808                };
809                Some(handshake_sm::ConclusionExtensionContents::new(
810                    hs_msg, None, None,
811                ))
812            }
813        };
814        // §6.1.5: the Initiator (cookie-contest winner) sends the Key
815        // Material request piggybacked on its CONCLUSION's HSREQ block;
816        // the Responder echoes it back on its HSRSP CONCLUSION.
817        #[cfg(feature = "crypto")]
818        let mut ext_contents = ext_contents;
819        #[cfg(feature = "crypto")]
820        if let Some(contents) = ext_contents.as_mut() {
821            if ext_type == Some(ExtensionType::HsReq)
822                && let Some(crypto) = &self.config.crypto
823            {
824                contents.set_key_material(
825                    ExtensionType::KmReq,
826                    handshake_sm::build_key_material_contents(crypto)?,
827                );
828            }
829            if ext_type == Some(ExtensionType::HsRsp)
830                && let Some(echo) = &self.km_echo
831            {
832                contents.set_key_material(ExtensionType::KmRsp, echo.clone());
833            }
834        }
835        let (extensions, ext_flags) = match (&ext_type, &ext_contents) {
836            (Some(t), Some(contents)) => handshake_sm::build_conclusion_extensions(*t, contents),
837            _ => (HandshakeExtensions(Vec::new()), 0),
838        };
839        let hp = HandshakePacket {
840            timestamp: SrtTimestamp::from_wire(self.clock.now()),
841            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
842            version: HANDSHAKE_VERSION_5,
843            encryption_field: self.config.encryption_field,
844            extension_field: HandshakeExtensionFlags::new(ext_flags),
845            initial_seq_number: self.config.initial_seq_number,
846            mtu: self.config.mtu,
847            max_flow_window_size: self.config.max_flow_window_size,
848            handshake_type: HandshakeType::Conclusion,
849            srt_socket_id: self.own_socket_id,
850            syn_cookie: self.own_cookie,
851            peer_ip: self.config.local_ip,
852            extensions,
853        };
854        let bytes = handshake_sm::build_bytes(hp)?;
855        self.retransmit.arm_fresh(&bytes);
856        Ok(vec![HandshakeOutput::Send(bytes)])
857    }
858
859    /// Builds and sends an AGREEMENT: no extensions (§4.3.2.1, L2224-2230).
860    fn send_agreement(&mut self) -> Result<Vec<HandshakeOutput>> {
861        let hp = HandshakePacket {
862            timestamp: SrtTimestamp::from_wire(self.clock.now()),
863            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
864            version: HANDSHAKE_VERSION_5,
865            encryption_field: EncryptionField::NoEncryption,
866            extension_field: HandshakeExtensionFlags::new(0),
867            initial_seq_number: self.config.initial_seq_number,
868            mtu: self.config.mtu,
869            max_flow_window_size: self.config.max_flow_window_size,
870            handshake_type: HandshakeType::Agreement,
871            srt_socket_id: self.own_socket_id,
872            syn_cookie: self.own_cookie,
873            peer_ip: self.config.local_ip,
874            extensions: HandshakeExtensions(Vec::new()),
875        };
876        let bytes = handshake_sm::build_bytes(hp)?;
877        self.retransmit.arm_fresh(&bytes);
878        Ok(vec![HandshakeOutput::Send(bytes)])
879    }
880
881    /// Reaches [`RendezvousHandshakeState::Connected`]: builds
882    /// [`NegotiatedParams`] from `self.peer_hs_msg` (always captured by every
883    /// caller of this method before it is called) and sends the AGREEMENT
884    /// every documented transition into Connected requires.
885    fn enter_connected(&mut self) -> Result<Vec<HandshakeOutput>> {
886        let negotiated = self.build_negotiated()?;
887        self.negotiated = Some(negotiated.clone());
888        self.state = RendezvousHandshakeState::Connected;
889        let mut out = self.send_agreement()?;
890        out.push(HandshakeOutput::Connected(negotiated));
891        Ok(out)
892    }
893
894    fn build_negotiated(&self) -> Result<NegotiatedParams> {
895        let (Some(peer_msg), Some((peer_mtu, peer_mfw))) = (self.peer_hs_msg, self.peer_limits)
896        else {
897            return Err(Error::HandshakeOutOfSequence {
898                state: self.state.name(),
899                reason: "reached Connected without the peer's Handshake Extension Message",
900            });
901        };
902        Ok(NegotiatedParams {
903            version: HANDSHAKE_VERSION_5,
904            flags: HandshakeExtensionMessageFlags::new(
905                self.config.flags.get() & peer_msg.srt_flags.get(),
906            ),
907            latency: handshake_sm::negotiate_latency(self.config.latency, &peer_msg),
908            own_socket_id: self.own_socket_id,
909            peer_socket_id: self.peer_socket_id,
910            mtu: self.config.mtu.min(peer_mtu),
911            max_flow_window_size: self.config.max_flow_window_size.min(peer_mfw),
912            // §4.3.2 never mentions a Stream ID / Group Membership exchange.
913            stream_id: None,
914            group: None,
915            #[cfg(feature = "crypto")]
916            sek: {
917                match self.role {
918                    Some(RendezvousRole::Initiator) => {
919                        if self.config.crypto.is_some() && self.crypto_verified {
920                            self.config
921                                .crypto
922                                .as_ref()
923                                .map(|c| handshake_sm::SecretBytes::new(c.sek.clone()))
924                        } else {
925                            None
926                        }
927                    }
928                    Some(RendezvousRole::Responder) => {
929                        self.crypto_recovered.as_ref().map(|(sek, _)| sek.clone())
930                    }
931                    None => None,
932                }
933            },
934            #[cfg(feature = "crypto")]
935            salt: {
936                match self.role {
937                    Some(RendezvousRole::Initiator) => {
938                        if self.config.crypto.is_some() && self.crypto_verified {
939                            self.config.crypto.as_ref().map(|c| c.salt)
940                        } else {
941                            None
942                        }
943                    }
944                    Some(RendezvousRole::Responder) => {
945                        self.crypto_recovered.as_ref().map(|(_, salt)| *salt)
946                    }
947                    None => None,
948                }
949            },
950        })
951    }
952}
953
954#[cfg(test)]
955mod tests {
956    use super::*;
957    use crate::packet::handshake::HS_EXT_FLAG_HSREQ;
958
959    #[test]
960    fn start_is_idempotent_guard() {
961        let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
962        assert!(r.start().is_ok());
963        assert!(matches!(
964            r.start(),
965            Err(crate::error::Error::HandshakeOutOfSequence { .. })
966        ));
967    }
968
969    #[test]
970    fn wavehand_wire_values_match_draft_4_3_2() {
971        let mut r = RendezvousHandshake::new(0xAAAA_BBBB, 0xC0FF_EE00, HandshakeConfig::default());
972        let bytes = r.start().unwrap();
973        let pkt = ControlPacket::parse(&bytes).unwrap();
974        match pkt {
975            ControlPacket::Handshake(hp) => {
976                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
977                assert_eq!(hp.handshake_type, HandshakeType::Wavehand);
978                assert_eq!(hp.srt_socket_id, 0xAAAA_BBBB);
979                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
980                assert_eq!(hp.extension_field.get(), 0);
981            }
982            _ => panic!("expected handshake"),
983        }
984        assert_eq!(r.state(), RendezvousHandshakeState::Waving);
985    }
986
987    fn wavehand(socket_id: u32, cookie: u32) -> ControlPacket<'static> {
988        ControlPacket::Handshake(HandshakePacket {
989            timestamp: SrtTimestamp::ZERO,
990            dest_socket_id: SocketId::from_wire(0),
991            version: HANDSHAKE_VERSION_5,
992            encryption_field: EncryptionField::NoEncryption,
993            extension_field: HandshakeExtensionFlags::new(0),
994            initial_seq_number: 0,
995            mtu: 1500,
996            max_flow_window_size: 8192,
997            handshake_type: HandshakeType::Wavehand,
998            srt_socket_id: socket_id,
999            syn_cookie: cookie,
1000            peer_ip: [0; 4],
1001            extensions: HandshakeExtensions(Vec::new()),
1002        })
1003    }
1004
1005    #[test]
1006    fn greater_cookie_wins_initiator() {
1007        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1008        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1009        a.start().unwrap();
1010        b.start().unwrap();
1011
1012        a.feed(&wavehand(2, 100)).unwrap();
1013        b.feed(&wavehand(1, 500)).unwrap();
1014
1015        assert_eq!(a.role(), Some(RendezvousRole::Initiator));
1016        assert_eq!(b.role(), Some(RendezvousRole::Responder));
1017        assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1018        assert_eq!(b.state(), RendezvousHandshakeState::Attention);
1019    }
1020
1021    /// Sign-boundary cookie-contest table (issue #1064). Every case here
1022    /// pins `cookie_contest`'s result against the libsrt algorithm it ports
1023    /// — hand-traced from `CUDT::backwardCompatibleCookieContest`, not
1024    /// re-derived from this crate's own implementation (the point is
1025    /// catching a misport, not just re-checking `contest > 0`).
1026    ///
1027    /// A plain unsigned `own_cookie > peer_cookie` compare (this function's
1028    /// pre-#1064 behavior) gives the OPPOSITE answer to several of these —
1029    /// marked below — because it doesn't reinterpret either cookie as
1030    /// signed before comparing.
1031    #[test]
1032    fn cookie_contest_sign_boundary_table() {
1033        let cases: &[(u32, u32, RendezvousRole, &str)] = &[
1034            // Both positive as i32 (top bit clear): signed and unsigned
1035            // agree — the ordinary case.
1036            (
1037                500,
1038                100,
1039                RendezvousRole::Initiator,
1040                "both positive, own > peer",
1041            ),
1042            (
1043                100,
1044                500,
1045                RendezvousRole::Responder,
1046                "both positive, own < peer",
1047            ),
1048            // Exactly one cookie has the top bit set: signed and unsigned
1049            // DISAGREE. libsrt's signed compare makes the negative
1050            // (top-bit-set) one lose regardless of its unsigned magnitude.
1051            (
1052                0xAAAA_0002,
1053                0x1111_0001,
1054                RendezvousRole::Responder,
1055                "own top-bit-set (negative), peer positive — unsigned would say Initiator",
1056            ),
1057            (
1058                0x1111_0001,
1059                0xAAAA_0002,
1060                RendezvousRole::Initiator,
1061                "own positive, peer top-bit-set (negative) — unsigned would say Responder",
1062            ),
1063            // Both top-bit-set (both negative as i32): signed compare among
1064            // two negatives, still needs to agree with libsrt, not just
1065            // "unsigned compare of the raw bit pattern" (which happens to
1066            // still hold here since the *relative* order of two same-signed
1067            // values is the same either way — included as a same-sign
1068            // sanity check, not a disagreement case).
1069            (
1070                0xFFFF_FFFF,
1071                0x8000_0000,
1072                RendezvousRole::Initiator,
1073                "both negative, own > peer",
1074            ),
1075            (
1076                0x8000_0000,
1077                0xFFFF_FFFF,
1078                RendezvousRole::Responder,
1079                "both negative, own < peer",
1080            ),
1081            // The exact halfway point (`own - peer == i32::MIN`, `0x8000_0000`
1082            // as the wrapping 32-bit difference): libsrt's own tie-break for
1083            // this specific case falls back to a raw signed `req > res`
1084            // comparison of the two cookies themselves (see `cookie_contest`'s
1085            // doc) rather than the contest direction.
1086            (
1087                0x8000_0000,
1088                0,
1089                RendezvousRole::Responder,
1090                "halfway point, own negative vs peer zero: raw signed own(<0) > peer(0) is false",
1091            ),
1092            (
1093                0,
1094                0x8000_0000,
1095                RendezvousRole::Initiator,
1096                "halfway point, own zero vs peer negative: raw signed own(0) > peer(<0) is true",
1097            ),
1098        ];
1099        for &(own, peer, expected, why) in cases {
1100            let got = cookie_contest(own, peer);
1101            assert_eq!(
1102                got, expected,
1103                "own={own:#010x} peer={peer:#010x}: expected {expected:?}, got {got:?} ({why})"
1104            );
1105        }
1106    }
1107
1108    #[test]
1109    fn identical_cookies_are_rejected_as_a_collision() {
1110        let mut a = RendezvousHandshake::new(1, 0x00C0_FFEE, HandshakeConfig::default());
1111        a.start().unwrap();
1112        let outputs = a.feed(&wavehand(2, 0x00C0_FFEE)).unwrap();
1113        assert_eq!(
1114            outputs,
1115            vec![HandshakeOutput::Rejected(RejectionReason::RdvCookie)]
1116        );
1117        assert_eq!(a.state(), RendezvousHandshakeState::Rejected);
1118    }
1119
1120    #[test]
1121    fn initiator_attention_entry_sends_hsreq() {
1122        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1123        a.start().unwrap();
1124        let outputs = a.feed(&wavehand(2, 100)).unwrap();
1125        assert_eq!(outputs.len(), 1);
1126        let bytes = match &outputs[0] {
1127            HandshakeOutput::Send(b) => b.clone(),
1128            other => panic!("expected Send, got {other:?}"),
1129        };
1130        let pkt = ControlPacket::parse(&bytes).unwrap();
1131        match pkt {
1132            ControlPacket::Handshake(hp) => {
1133                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1134                assert_eq!(
1135                    hp.extension_field.get() & HS_EXT_FLAG_HSREQ,
1136                    HS_EXT_FLAG_HSREQ
1137                );
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.get(), 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::new(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::new(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    fn ext_hs_msg() -> HsExtMessage {
1263        HsExtMessage {
1264            srt_version: 0x0105_0000,
1265            srt_flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
1266            receiver_tsbpd_delay: Duration::from_millis(120),
1267            sender_tsbpd_delay: Duration::from_millis(120),
1268        }
1269    }
1270
1271    fn plain_handshake(
1272        handshake_type: HandshakeType,
1273        socket_id: u32,
1274        cookie: u32,
1275    ) -> ControlPacket<'static> {
1276        ControlPacket::Handshake(HandshakePacket {
1277            timestamp: SrtTimestamp::ZERO,
1278            dest_socket_id: SocketId::from_wire(1),
1279            version: HANDSHAKE_VERSION_5,
1280            encryption_field: EncryptionField::NoEncryption,
1281            extension_field: HandshakeExtensionFlags::new(0),
1282            initial_seq_number: 0,
1283            mtu: 1500,
1284            max_flow_window_size: 8192,
1285            handshake_type,
1286            srt_socket_id: socket_id,
1287            syn_cookie: cookie,
1288            peer_ip: [0; 4],
1289            extensions: HandshakeExtensions(Vec::new()),
1290        })
1291    }
1292
1293    fn conclusion_with_hs_ext(
1294        ext_type: ExtensionType,
1295        socket_id: u32,
1296        cookie: u32,
1297    ) -> ControlPacket<'static> {
1298        let contents = handshake_sm::ConclusionExtensionContents::new(ext_hs_msg(), None, None);
1299        let contents: &'static handshake_sm::ConclusionExtensionContents =
1300            alloc::boxed::Box::leak(alloc::boxed::Box::new(contents));
1301        let (extensions, ext_flags) = handshake_sm::build_conclusion_extensions(ext_type, contents);
1302        ControlPacket::Handshake(HandshakePacket {
1303            timestamp: SrtTimestamp::ZERO,
1304            dest_socket_id: SocketId::from_wire(1),
1305            version: HANDSHAKE_VERSION_5,
1306            encryption_field: EncryptionField::NoEncryption,
1307            extension_field: HandshakeExtensionFlags::new(ext_flags),
1308            initial_seq_number: 0,
1309            mtu: 1500,
1310            max_flow_window_size: 8192,
1311            handshake_type: HandshakeType::Conclusion,
1312            srt_socket_id: socket_id,
1313            syn_cookie: cookie,
1314            peer_ip: [0; 4],
1315            extensions,
1316        })
1317    }
1318
1319    fn sent_bytes(outputs: &[HandshakeOutput]) -> Vec<u8> {
1320        outputs
1321            .iter()
1322            .find_map(|o| match o {
1323                HandshakeOutput::Send(b) => Some(b.clone()),
1324                _ => None,
1325            })
1326            .expect("a Send output")
1327    }
1328
1329    /// §4.3.2 serial-flow crossing: an Initiator still in Waving receives a
1330    /// CONCLUSION+HSRSP directly and completes.
1331    #[test]
1332    fn initiator_completes_from_a_crossing_conclusion_with_hsrsp() {
1333        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1334        a.start().unwrap();
1335        let outputs = a
1336            .feed(&conclusion_with_hs_ext(ExtensionType::HsRsp, 2, 100))
1337            .unwrap();
1338        assert_eq!(a.role(), Some(RendezvousRole::Initiator));
1339        assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1340        assert!(
1341            outputs
1342                .iter()
1343                .any(|o| matches!(o, HandshakeOutput::Connected(_))),
1344            "{outputs:?}"
1345        );
1346    }
1347
1348    /// Attention + duplicate WAVEAHAND: resend the last message, no state
1349    /// change (neither table defines the duplicate).
1350    #[test]
1351    fn duplicate_wavehand_in_attention_is_resent() {
1352        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1353        b.start().unwrap();
1354        let first = b.feed(&wavehand(1, 500)).unwrap();
1355        let first_bytes = sent_bytes(&first);
1356        let again = b.feed(&wavehand(1, 500)).unwrap();
1357        assert_eq!(sent_bytes(&again), first_bytes);
1358        assert_eq!(b.state(), RendezvousHandshakeState::Attention);
1359    }
1360
1361    /// Responder Attention + extension-less CONCLUSION: resend the empty
1362    /// CONCLUSION and stay in Attention (L2357-2360).
1363    #[test]
1364    fn responder_attention_without_extensions_resends_empty_conclusion() {
1365        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1366        b.start().unwrap();
1367        b.feed(&wavehand(1, 500)).unwrap();
1368        let outputs = b
1369            .feed(&plain_handshake(HandshakeType::Conclusion, 1, 500))
1370            .unwrap();
1371        let bytes = sent_bytes(&outputs);
1372        let ControlPacket::Handshake(hp) = ControlPacket::parse(&bytes).unwrap() else {
1373            panic!("expected handshake");
1374        };
1375        assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1376        assert_eq!(hp.extensions.iter().count(), 0);
1377        assert_eq!(b.state(), RendezvousHandshakeState::Attention);
1378        assert_eq!(b.role(), Some(RendezvousRole::Responder));
1379    }
1380
1381    /// Responder Initiated + AGREEMENT: enter Connected and answer AGREEMENT.
1382    #[test]
1383    fn responder_initiated_agreement_connects() {
1384        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1385        b.start().unwrap();
1386        b.feed(&wavehand(1, 500)).unwrap();
1387        b.feed(&conclusion_with_hs_ext(ExtensionType::HsReq, 1, 500))
1388            .unwrap();
1389        assert_eq!(b.state(), RendezvousHandshakeState::Initiated);
1390        let outputs = b
1391            .feed(&plain_handshake(HandshakeType::Agreement, 1, 500))
1392            .unwrap();
1393        assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1394        let bytes = sent_bytes(&outputs);
1395        let ControlPacket::Handshake(hp) = ControlPacket::parse(&bytes).unwrap() else {
1396            panic!("expected handshake");
1397        };
1398        assert_eq!(hp.handshake_type, HandshakeType::Agreement);
1399    }
1400
1401    /// A Connected engine answers a repeated CONCLUSION with another
1402    /// AGREEMENT (recovery rule 4).
1403    #[test]
1404    fn connected_engine_answers_a_repeated_conclusion() {
1405        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1406        a.start().unwrap();
1407        a.feed(&conclusion_with_hs_ext(ExtensionType::HsRsp, 2, 100))
1408            .unwrap();
1409        assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1410        let outputs = a
1411            .feed(&plain_handshake(HandshakeType::Conclusion, 2, 100))
1412            .unwrap();
1413        let bytes = sent_bytes(&outputs);
1414        let ControlPacket::Handshake(hp) = ControlPacket::parse(&bytes).unwrap() else {
1415            panic!("expected handshake");
1416        };
1417        assert_eq!(hp.handshake_type, HandshakeType::Agreement);
1418        assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1419    }
1420
1421    /// `tick` resends the last message once the retransmit period has passed
1422    /// and times out after the retry budget.
1423    #[test]
1424    fn tick_retransmits_and_then_times_out() {
1425        let config = HandshakeConfig::default();
1426        let mut r = RendezvousHandshake::new(1, 500, config.clone());
1427        let sent = r.start().unwrap();
1428        let outputs = r.tick(config.retransmit_after);
1429        assert_eq!(sent_bytes(&outputs), sent, "the WAVEAHAND is re-sent");
1430        for _ in 0..=config.max_retries {
1431            let _ = r.tick(config.retransmit_after);
1432        }
1433        assert_eq!(r.state(), RendezvousHandshakeState::TimedOut);
1434    }
1435
1436    /// Recovery rule 3: only a Responder stuck in Initiated is promoted by a
1437    /// non-handshake packet or [`RendezvousHandshake::on_recovery_trigger`];
1438    /// an Initiator in the same state is an error, not a promotion.
1439    #[test]
1440    fn recovery_trigger_promotes_only_a_responder_in_initiated() {
1441        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1442        b.start().unwrap();
1443        b.feed(&wavehand(1, 500)).unwrap();
1444        b.feed(&conclusion_with_hs_ext(ExtensionType::HsReq, 1, 500))
1445            .unwrap();
1446        assert_eq!(b.state(), RendezvousHandshakeState::Initiated);
1447        let outputs = b.on_recovery_trigger().unwrap();
1448        assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1449        assert!(
1450            outputs
1451                .iter()
1452                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
1453        );
1454
1455        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1456        a.start().unwrap();
1457        a.feed(&wavehand(2, 100)).unwrap();
1458        a.feed(&plain_handshake(HandshakeType::Conclusion, 2, 100))
1459            .unwrap();
1460        assert_eq!(a.state(), RendezvousHandshakeState::Initiated);
1461        assert!(a.on_recovery_trigger().unwrap().is_empty());
1462        assert_eq!(a.state(), RendezvousHandshakeState::Initiated);
1463    }
1464
1465    #[test]
1466    fn recovery_feed_promotes_only_a_responder_in_initiated() {
1467        use crate::packet::misc::KeepAlivePacket;
1468        let keepalive = ControlPacket::KeepAlive(KeepAlivePacket {
1469            timestamp: SrtTimestamp::ZERO,
1470            dest_socket_id: SocketId::from_wire(1),
1471            libsrt_pad: false,
1472        });
1473
1474        let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1475        b.start().unwrap();
1476        b.feed(&wavehand(1, 500)).unwrap();
1477        b.feed(&conclusion_with_hs_ext(ExtensionType::HsReq, 1, 500))
1478            .unwrap();
1479        let outputs = b.feed(&keepalive).unwrap();
1480        assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1481        assert!(
1482            outputs
1483                .iter()
1484                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
1485        );
1486
1487        let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1488        a.start().unwrap();
1489        a.feed(&wavehand(2, 100)).unwrap();
1490        a.feed(&plain_handshake(HandshakeType::Conclusion, 2, 100))
1491            .unwrap();
1492        assert!(matches!(
1493            a.feed(&keepalive),
1494            Err(Error::UnexpectedControlPacket { .. })
1495        ));
1496        assert_eq!(a.state(), RendezvousHandshakeState::Initiated);
1497    }
1498
1499    /// The libsrt-port tie-break across the sign boundary: the cases where
1500    /// the bit-31 test differs from an XOR of the sign bit.
1501    #[test]
1502    fn cookie_contest_signed_boundary_cases() {
1503        assert_eq!(cookie_contest(1, 0x8000_0000), RendezvousRole::Responder);
1504        assert_eq!(cookie_contest(0x8000_0000, 1), RendezvousRole::Initiator);
1505        assert_eq!(
1506            cookie_contest(0x7FFF_FFFF, 0x8000_0000),
1507            RendezvousRole::Responder
1508        );
1509        assert_eq!(
1510            cookie_contest(0x8000_0000, 0x7FFF_FFFF),
1511            RendezvousRole::Initiator
1512        );
1513        assert_eq!(cookie_contest(0x8000_0001, 1), RendezvousRole::Responder);
1514        assert_eq!(cookie_contest(1, 0x8000_0001), RendezvousRole::Initiator);
1515    }
1516
1517    /// §3.2.1.1 (reused by §4.3.2): rendezvous flags are the intersection of
1518    /// both sides' advertised sets, exactly as in the Caller-Listener flow.
1519    #[test]
1520    fn negotiated_flags_are_the_intersection_of_both_sides() {
1521        use crate::packet::handshake::{
1522            HS_MSG_FLAG_REXMITFLG, HS_MSG_FLAG_TLPKTDROP, HS_MSG_FLAG_TSBPDRCV,
1523            HS_MSG_FLAG_TSBPDSND, HandshakeExtensionMessageFlags,
1524        };
1525        let local = HandshakeExtensionMessageFlags::new(
1526            HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV | HS_MSG_FLAG_TLPKTDROP,
1527        );
1528        let peer = HandshakeExtensionMessageFlags::new(
1529            HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV | HS_MSG_FLAG_REXMITFLG,
1530        );
1531        let config = HandshakeConfig {
1532            flags: local,
1533            ..HandshakeConfig::default()
1534        };
1535        let mut r = RendezvousHandshake::new(1, 500, config);
1536        r.start().unwrap();
1537        r.role = Some(RendezvousRole::Initiator);
1538        r.peer_hs_msg = Some(HsExtMessage {
1539            srt_version: 0x0105_0000,
1540            srt_flags: peer,
1541            receiver_tsbpd_delay: Duration::from_millis(120),
1542            sender_tsbpd_delay: Duration::from_millis(120),
1543        });
1544        r.peer_limits = Some((1500, 8192));
1545        assert_eq!(
1546            r.build_negotiated().expect("negotiated").flags,
1547            HandshakeExtensionMessageFlags::new(HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV)
1548        );
1549    }
1550
1551    #[test]
1552    fn state_and_role_labels_match_the_diagram() {
1553        assert_eq!(RendezvousHandshakeState::Idle.name(), "Idle");
1554        assert_eq!(RendezvousHandshakeState::Waving.name(), "Waving");
1555        assert_eq!(RendezvousHandshakeState::Attention.name(), "Attention");
1556        assert_eq!(RendezvousHandshakeState::Initiated.name(), "Initiated");
1557        assert_eq!(RendezvousHandshakeState::Connected.name(), "Connected");
1558        assert_eq!(RendezvousHandshakeState::Rejected.name(), "Rejected");
1559        assert_eq!(RendezvousHandshakeState::TimedOut.name(), "TimedOut");
1560        assert_eq!(RendezvousRole::Initiator.name(), "Initiator");
1561        assert_eq!(RendezvousRole::Responder.name(), "Responder");
1562    }
1563}
1564
1565#[cfg(test)]
1566#[cfg(feature = "crypto")]
1567mod crypto_echo_tests {
1568    use super::super::*;
1569    #[cfg(feature = "crypto")]
1570    use crate::handshake_sm::{CryptoConfig, HANDSHAKE_VERSION_5};
1571    #[cfg(feature = "crypto")]
1572    use crate::packet::{
1573        ControlPacket, EncryptionField, ExtensionType, HandshakeExtensionFlags, HandshakePacket,
1574        HandshakeType, HsExtMessage, SocketId, SrtTimestamp,
1575    };
1576    #[cfg(feature = "crypto")]
1577    use core::time::Duration;
1578
1579    #[cfg(feature = "crypto")]
1580    #[test]
1581    fn rendezvous_initiator_rejects_a_tampered_km_echo() {
1582        use crate::packet::{ControlPacket, EncryptionField};
1583
1584        const PEER_A_SOCKET_ID: u32 = 0x1111_1111;
1585        const PEER_B_SOCKET_ID: u32 = 0x2222_2222;
1586        const PEER_A_COOKIE: u32 = 0xAAAA_0002;
1587        const PEER_B_COOKIE: u32 = 0x1111_0001;
1588
1589        let passphrase = b"passphrase".to_vec();
1590        let crypto = CryptoConfig {
1591            passphrase: passphrase.clone(),
1592            salt: [0x11u8; 16],
1593            sek: vec![0x22u8; 16],
1594        };
1595        let config_a = HandshakeConfig {
1596            encryption_field: EncryptionField::Aes128,
1597            crypto: Some(crypto.clone()),
1598            ..HandshakeConfig::default()
1599        };
1600        let config_b = HandshakeConfig {
1601            encryption_field: EncryptionField::Aes128,
1602            crypto: Some(crypto),
1603            ..HandshakeConfig::default()
1604        };
1605
1606        // Untampered run must complete.
1607        {
1608            let mut a = RendezvousHandshake::new(PEER_A_SOCKET_ID, PEER_A_COOKIE, config_a.clone());
1609            let mut b = RendezvousHandshake::new(PEER_B_SOCKET_ID, PEER_B_COOKIE, config_b.clone());
1610            let mut to_a = vec![b.start().expect("b start")];
1611            let mut to_b = vec![a.start().expect("a start")];
1612            for _ in 0..20 {
1613                if a.state() == RendezvousHandshakeState::Connected
1614                    && b.state() == RendezvousHandshakeState::Connected
1615                {
1616                    break;
1617                }
1618                let mut next_to_a = Vec::new();
1619                let mut next_to_b = Vec::new();
1620                for msg in to_a.drain(..) {
1621                    if a.state() == RendezvousHandshakeState::Rejected {
1622                        continue;
1623                    }
1624                    let pkt = ControlPacket::parse(&msg).expect("valid");
1625                    for out in a.feed(&pkt).expect("a.feed") {
1626                        if let HandshakeOutput::Send(bytes) = out {
1627                            next_to_b.push(bytes);
1628                        }
1629                    }
1630                }
1631                for msg in to_b.drain(..) {
1632                    let pkt = ControlPacket::parse(&msg).expect("valid");
1633                    for out in b.feed(&pkt).expect("b.feed") {
1634                        if let HandshakeOutput::Send(bytes) = out {
1635                            next_to_a.push(bytes);
1636                        }
1637                    }
1638                }
1639                to_a = next_to_a;
1640                to_b = next_to_b;
1641                if to_a.is_empty() && to_b.is_empty() {
1642                    break;
1643                }
1644            }
1645            assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1646            assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1647        }
1648
1649        // Tampered run: flip a byte in the Responder's key-material echo.
1650        let mut a = RendezvousHandshake::new(PEER_A_SOCKET_ID, PEER_A_COOKIE, config_a);
1651        let mut b = RendezvousHandshake::new(PEER_B_SOCKET_ID, PEER_B_COOKIE, config_b);
1652        let mut to_a = vec![b.start().expect("b start")];
1653        let mut to_b = vec![a.start().expect("a start")];
1654        let mut tampered = false;
1655        let mut rejected = false;
1656        for _ in 0..20 {
1657            if rejected {
1658                break;
1659            }
1660            if a.state() == RendezvousHandshakeState::Connected
1661                && b.state() == RendezvousHandshakeState::Connected
1662            {
1663                break;
1664            }
1665            let mut next_to_a = Vec::new();
1666            let mut next_to_b = Vec::new();
1667            for msg in to_a.drain(..) {
1668                let pkt = ControlPacket::parse(&msg).expect("valid");
1669                for out in a.feed(&pkt).expect("a.feed") {
1670                    if let HandshakeOutput::Send(bytes) = out {
1671                        next_to_b.push(bytes);
1672                    }
1673                }
1674            }
1675            for msg in to_b.drain(..) {
1676                let mut msg = msg;
1677                if !tampered && msg.windows(2).any(|w| w == [0, 4]) {
1678                    if let Some(last) = msg.last_mut() {
1679                        *last ^= 0xFF;
1680                    }
1681                    tampered = true;
1682                }
1683                if b.state() == RendezvousHandshakeState::Rejected {
1684                    continue;
1685                }
1686                let pkt = ControlPacket::parse(&msg).expect("valid");
1687                for out in b.feed(&pkt).expect("b.feed") {
1688                    match out {
1689                        HandshakeOutput::Send(bytes) => next_to_a.push(bytes),
1690                        HandshakeOutput::Rejected(reason) => {
1691                            assert_eq!(reason, RejectionReason::BadSecret);
1692                            rejected = true;
1693                        }
1694                        _ => {}
1695                    }
1696                }
1697            }
1698            to_a = next_to_a;
1699            to_b = next_to_b;
1700            if to_a.is_empty() && to_b.is_empty() {
1701                break;
1702            }
1703        }
1704        assert!(tampered, "never found a key-material echo to tamper");
1705        assert!(rejected, "initiator did not reject the tampered echo");
1706        assert_eq!(b.state(), RendezvousHandshakeState::Rejected);
1707    }
1708
1709    fn test_crypto() -> CryptoConfig {
1710        CryptoConfig::new(
1711            b"rendezvous-crypto-passphrase".to_vec(),
1712            [0x11u8; 16],
1713            vec![0x22u8; 16],
1714        )
1715    }
1716
1717    fn test_hs_msg() -> HsExtMessage {
1718        HsExtMessage {
1719            srt_version: 0x0105_0000,
1720            srt_flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
1721            receiver_tsbpd_delay: Duration::from_millis(120),
1722            sender_tsbpd_delay: Duration::from_millis(120),
1723        }
1724    }
1725
1726    fn crossing_conclusion(
1727        hs_msg: HsExtMessage,
1728        km: Option<Vec<u8>>,
1729        socket_id: u32,
1730        cookie: u32,
1731    ) -> ControlPacket<'static> {
1732        let mut contents = handshake_sm::ConclusionExtensionContents::new(hs_msg, None, None);
1733        if let Some(bytes) = km {
1734            contents.set_key_material(ExtensionType::KmRsp, bytes);
1735        }
1736        let contents: &'static handshake_sm::ConclusionExtensionContents =
1737            alloc::boxed::Box::leak(alloc::boxed::Box::new(contents));
1738        let (extensions, ext_flags) =
1739            handshake_sm::build_conclusion_extensions(ExtensionType::HsRsp, contents);
1740        ControlPacket::Handshake(HandshakePacket {
1741            timestamp: SrtTimestamp::ZERO,
1742            dest_socket_id: SocketId::from_wire(1),
1743            version: HANDSHAKE_VERSION_5,
1744            encryption_field: EncryptionField::Aes128,
1745            extension_field: HandshakeExtensionFlags::new(ext_flags),
1746            initial_seq_number: 0,
1747            mtu: 1500,
1748            max_flow_window_size: 8192,
1749            handshake_type: HandshakeType::Conclusion,
1750            srt_socket_id: socket_id,
1751            syn_cookie: cookie,
1752            peer_ip: [0; 4],
1753            extensions,
1754        })
1755    }
1756
1757    fn crossing_initiator(crypto: Option<CryptoConfig>) -> RendezvousHandshake {
1758        let config = HandshakeConfig {
1759            encryption_field: EncryptionField::Aes128,
1760            crypto,
1761            ..HandshakeConfig::default()
1762        };
1763        let mut r = RendezvousHandshake::new(1, 500, config);
1764        r.start().unwrap();
1765        r
1766    }
1767
1768    /// The serial-crossing Initiator (Waving -> a CONCLUSION+HSRSP directly)
1769    /// verifies the Key Material echo before it may use the SEK.
1770    #[test]
1771    fn crossing_initiator_verifies_a_matching_km_echo() {
1772        let crypto = test_crypto();
1773        let km = handshake_sm::build_key_material_contents(&crypto).expect("key material");
1774        let mut r = crossing_initiator(Some(crypto.clone()));
1775        let outputs = r
1776            .feed(&crossing_conclusion(test_hs_msg(), Some(km), 2, 100))
1777            .expect("complete");
1778        assert_eq!(r.state(), RendezvousHandshakeState::Connected);
1779        assert!(
1780            outputs
1781                .iter()
1782                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
1783        );
1784        let negotiated = r.negotiated().expect("negotiated");
1785        assert_eq!(
1786            negotiated.sek.as_ref().map(|s| &s[..]),
1787            Some(crypto.sek.as_slice())
1788        );
1789        assert_eq!(negotiated.salt, Some(crypto.salt));
1790    }
1791
1792    #[test]
1793    fn crossing_initiator_rejects_a_tampered_km_echo() {
1794        let crypto = test_crypto();
1795        let mut km = handshake_sm::build_key_material_contents(&crypto).expect("key material");
1796        let last = km.len() - 1;
1797        km[last] ^= 0xFF;
1798        let mut r = crossing_initiator(Some(crypto));
1799        let outputs = r
1800            .feed(&crossing_conclusion(test_hs_msg(), Some(km), 2, 100))
1801            .expect("feed");
1802        assert!(
1803            outputs.contains(&HandshakeOutput::Rejected(RejectionReason::BadSecret)),
1804            "{outputs:?}"
1805        );
1806        assert_eq!(r.state(), RendezvousHandshakeState::Rejected);
1807    }
1808
1809    #[test]
1810    fn crossing_initiator_without_crypto_rejects_a_km_echo() {
1811        let km = handshake_sm::build_key_material_contents(&test_crypto()).expect("key material");
1812        let mut r = crossing_initiator(None);
1813        let outputs = r
1814            .feed(&crossing_conclusion(test_hs_msg(), Some(km), 2, 100))
1815            .expect("feed");
1816        assert!(
1817            outputs.contains(&HandshakeOutput::Rejected(RejectionReason::Unsecure)),
1818            "{outputs:?}"
1819        );
1820    }
1821
1822    #[test]
1823    fn crossing_initiator_with_crypto_rejects_a_missing_km_echo() {
1824        let mut r = crossing_initiator(Some(test_crypto()));
1825        let outputs = r
1826            .feed(&crossing_conclusion(test_hs_msg(), None, 2, 100))
1827            .expect("feed");
1828        assert!(
1829            outputs.contains(&HandshakeOutput::Rejected(RejectionReason::Unsecure)),
1830            "{outputs:?}"
1831        );
1832    }
1833
1834    /// SEK and Salt are only handed to a connection whose KM echo was
1835    /// verified (the `crypto_verified` conjunction).
1836    #[test]
1837    fn negotiated_secrets_require_a_verified_km_echo() {
1838        let crypto = test_crypto();
1839        let config = HandshakeConfig {
1840            encryption_field: EncryptionField::Aes128,
1841            crypto: Some(crypto.clone()),
1842            ..HandshakeConfig::default()
1843        };
1844        let mut r = RendezvousHandshake::new(1, 500, config);
1845        r.start().unwrap();
1846        r.role = Some(RendezvousRole::Initiator);
1847        r.peer_hs_msg = Some(test_hs_msg());
1848        r.peer_limits = Some((1500, 8192));
1849        r.crypto_verified = false;
1850        let unverified = r.build_negotiated().expect("negotiated");
1851        assert!(unverified.sek.is_none());
1852        assert!(unverified.salt.is_none());
1853
1854        r.crypto_verified = true;
1855        let verified = r.build_negotiated().expect("negotiated");
1856        assert_eq!(
1857            verified.sek.as_ref().map(|s| &s[..]),
1858            Some(crypto.sek.as_slice())
1859        );
1860        assert_eq!(verified.salt, Some(crypto.salt));
1861    }
1862}