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(
962            1,
963            500,
964            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
965        );
966        assert!(r.start().is_ok());
967        assert!(matches!(
968            r.start(),
969            Err(crate::error::Error::HandshakeOutOfSequence { .. })
970        ));
971    }
972
973    #[test]
974    fn wavehand_wire_values_match_draft_4_3_2() {
975        let mut r = RendezvousHandshake::new(
976            0xAAAA_BBBB,
977            0xC0FF_EE00,
978            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
979        );
980        let bytes = r.start().unwrap();
981        let pkt = ControlPacket::parse(&bytes).unwrap();
982        match pkt {
983            ControlPacket::Handshake(hp) => {
984                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
985                assert_eq!(hp.handshake_type, HandshakeType::Wavehand);
986                assert_eq!(hp.srt_socket_id, 0xAAAA_BBBB);
987                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
988                assert_eq!(hp.extension_field.get(), 0);
989            }
990            _ => panic!("expected handshake"),
991        }
992        assert_eq!(r.state(), RendezvousHandshakeState::Waving);
993    }
994
995    fn wavehand(socket_id: u32, cookie: u32) -> ControlPacket<'static> {
996        ControlPacket::Handshake(HandshakePacket {
997            timestamp: SrtTimestamp::ZERO,
998            dest_socket_id: SocketId::from_wire(0),
999            version: HANDSHAKE_VERSION_5,
1000            encryption_field: EncryptionField::NoEncryption,
1001            extension_field: HandshakeExtensionFlags::new(0),
1002            initial_seq_number: 0,
1003            mtu: 1500,
1004            max_flow_window_size: 8192,
1005            handshake_type: HandshakeType::Wavehand,
1006            srt_socket_id: socket_id,
1007            syn_cookie: cookie,
1008            peer_ip: [0; 4],
1009            extensions: HandshakeExtensions(Vec::new()),
1010        })
1011    }
1012
1013    #[test]
1014    fn greater_cookie_wins_initiator() {
1015        let mut a = RendezvousHandshake::new(
1016            1,
1017            500,
1018            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1019        );
1020        let mut b = RendezvousHandshake::new(
1021            2,
1022            100,
1023            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1024        );
1025        a.start().unwrap();
1026        b.start().unwrap();
1027
1028        a.feed(&wavehand(2, 100)).unwrap();
1029        b.feed(&wavehand(1, 500)).unwrap();
1030
1031        assert_eq!(a.role(), Some(RendezvousRole::Initiator));
1032        assert_eq!(b.role(), Some(RendezvousRole::Responder));
1033        assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1034        assert_eq!(b.state(), RendezvousHandshakeState::Attention);
1035    }
1036
1037    /// Sign-boundary cookie-contest table (issue #1064). Every case here
1038    /// pins `cookie_contest`'s result against the libsrt algorithm it ports
1039    /// — hand-traced from `CUDT::backwardCompatibleCookieContest`, not
1040    /// re-derived from this crate's own implementation (the point is
1041    /// catching a misport, not just re-checking `contest > 0`).
1042    ///
1043    /// A plain unsigned `own_cookie > peer_cookie` compare (this function's
1044    /// pre-#1064 behavior) gives the OPPOSITE answer to several of these —
1045    /// marked below — because it doesn't reinterpret either cookie as
1046    /// signed before comparing.
1047    #[test]
1048    fn cookie_contest_sign_boundary_table() {
1049        let cases: &[(u32, u32, RendezvousRole, &str)] = &[
1050            // Both positive as i32 (top bit clear): signed and unsigned
1051            // agree — the ordinary case.
1052            (
1053                500,
1054                100,
1055                RendezvousRole::Initiator,
1056                "both positive, own > peer",
1057            ),
1058            (
1059                100,
1060                500,
1061                RendezvousRole::Responder,
1062                "both positive, own < peer",
1063            ),
1064            // Exactly one cookie has the top bit set: signed and unsigned
1065            // DISAGREE. libsrt's signed compare makes the negative
1066            // (top-bit-set) one lose regardless of its unsigned magnitude.
1067            (
1068                0xAAAA_0002,
1069                0x1111_0001,
1070                RendezvousRole::Responder,
1071                "own top-bit-set (negative), peer positive — unsigned would say Initiator",
1072            ),
1073            (
1074                0x1111_0001,
1075                0xAAAA_0002,
1076                RendezvousRole::Initiator,
1077                "own positive, peer top-bit-set (negative) — unsigned would say Responder",
1078            ),
1079            // Both top-bit-set (both negative as i32): signed compare among
1080            // two negatives, still needs to agree with libsrt, not just
1081            // "unsigned compare of the raw bit pattern" (which happens to
1082            // still hold here since the *relative* order of two same-signed
1083            // values is the same either way — included as a same-sign
1084            // sanity check, not a disagreement case).
1085            (
1086                0xFFFF_FFFF,
1087                0x8000_0000,
1088                RendezvousRole::Initiator,
1089                "both negative, own > peer",
1090            ),
1091            (
1092                0x8000_0000,
1093                0xFFFF_FFFF,
1094                RendezvousRole::Responder,
1095                "both negative, own < peer",
1096            ),
1097            // The exact halfway point (`own - peer == i32::MIN`, `0x8000_0000`
1098            // as the wrapping 32-bit difference): libsrt's own tie-break for
1099            // this specific case falls back to a raw signed `req > res`
1100            // comparison of the two cookies themselves (see `cookie_contest`'s
1101            // doc) rather than the contest direction.
1102            (
1103                0x8000_0000,
1104                0,
1105                RendezvousRole::Responder,
1106                "halfway point, own negative vs peer zero: raw signed own(<0) > peer(0) is false",
1107            ),
1108            (
1109                0,
1110                0x8000_0000,
1111                RendezvousRole::Initiator,
1112                "halfway point, own zero vs peer negative: raw signed own(0) > peer(<0) is true",
1113            ),
1114        ];
1115        for &(own, peer, expected, why) in cases {
1116            let got = cookie_contest(own, peer);
1117            assert_eq!(
1118                got, expected,
1119                "own={own:#010x} peer={peer:#010x}: expected {expected:?}, got {got:?} ({why})"
1120            );
1121        }
1122    }
1123
1124    #[test]
1125    fn identical_cookies_are_rejected_as_a_collision() {
1126        let mut a = RendezvousHandshake::new(
1127            1,
1128            0x00C0_FFEE,
1129            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1130        );
1131        a.start().unwrap();
1132        let outputs = a.feed(&wavehand(2, 0x00C0_FFEE)).unwrap();
1133        assert_eq!(
1134            outputs,
1135            vec![HandshakeOutput::Rejected(RejectionReason::RdvCookie)]
1136        );
1137        assert_eq!(a.state(), RendezvousHandshakeState::Rejected);
1138    }
1139
1140    #[test]
1141    fn initiator_attention_entry_sends_hsreq() {
1142        let mut a = RendezvousHandshake::new(
1143            1,
1144            500,
1145            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1146        );
1147        a.start().unwrap();
1148        let outputs = a.feed(&wavehand(2, 100)).unwrap();
1149        assert_eq!(outputs.len(), 1);
1150        let bytes = match &outputs[0] {
1151            HandshakeOutput::Send(b) => b.clone(),
1152            other => panic!("expected Send, got {other:?}"),
1153        };
1154        let pkt = ControlPacket::parse(&bytes).unwrap();
1155        match pkt {
1156            ControlPacket::Handshake(hp) => {
1157                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1158                assert_eq!(
1159                    hp.extension_field.get() & HS_EXT_FLAG_HSREQ,
1160                    HS_EXT_FLAG_HSREQ
1161                );
1162                let blocks: Vec<_> = hp.extensions.iter().collect();
1163                assert_eq!(blocks.len(), 1);
1164                assert_eq!(blocks[0].ext_type, ExtensionType::HsReq);
1165            }
1166            _ => panic!("expected handshake"),
1167        }
1168    }
1169
1170    #[test]
1171    fn responder_attention_entry_sends_empty_conclusion() {
1172        let mut b = RendezvousHandshake::new(
1173            2,
1174            100,
1175            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1176        );
1177        b.start().unwrap();
1178        let outputs = b.feed(&wavehand(1, 500)).unwrap();
1179        assert_eq!(outputs.len(), 1);
1180        let bytes = match &outputs[0] {
1181            HandshakeOutput::Send(b) => b.clone(),
1182            other => panic!("expected Send, got {other:?}"),
1183        };
1184        let pkt = ControlPacket::parse(&bytes).unwrap();
1185        match pkt {
1186            ControlPacket::Handshake(hp) => {
1187                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1188                assert_eq!(hp.extension_field.get(), 0);
1189                assert_eq!(hp.extensions.iter().count(), 0);
1190            }
1191            _ => panic!("expected handshake"),
1192        }
1193    }
1194
1195    #[test]
1196    fn malformed_extension_mid_flow_is_rejected_not_panicking() {
1197        let mut a = RendezvousHandshake::new(
1198            1,
1199            500,
1200            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1201        );
1202        a.start().unwrap();
1203        a.feed(&wavehand(2, 100)).unwrap();
1204        assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1205
1206        // A CONCLUSION whose extension section declares a block length far
1207        // larger than the bytes present.
1208        let bad = ControlPacket::Handshake(HandshakePacket {
1209            timestamp: SrtTimestamp::ZERO,
1210            dest_socket_id: SocketId::from_wire(1),
1211            version: HANDSHAKE_VERSION_5,
1212            encryption_field: EncryptionField::NoEncryption,
1213            extension_field: HandshakeExtensionFlags::new(HS_EXT_FLAG_HSREQ),
1214            initial_seq_number: 0,
1215            mtu: 1500,
1216            max_flow_window_size: 8192,
1217            handshake_type: HandshakeType::Conclusion,
1218            srt_socket_id: 2,
1219            syn_cookie: 100,
1220            peer_ip: [0; 4],
1221            extensions: HandshakeExtensions(Vec::new()),
1222        });
1223        let mut bad_bytes = alloc::vec![0u8; bad.serialized_len()];
1224        bad.serialize_into(&mut bad_bytes).unwrap();
1225        bad_bytes.extend_from_slice(&[0x00, 0x01, 0xFF, 0xFF]);
1226        assert!(matches!(
1227            a.feed_bytes(&bad_bytes),
1228            Err(Error::ExtensionOverrun { .. })
1229        ));
1230        assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1231    }
1232
1233    #[test]
1234    fn feed_before_start_is_out_of_sequence() {
1235        let mut r = RendezvousHandshake::new(
1236            1,
1237            500,
1238            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1239        );
1240        assert!(matches!(
1241            r.feed(&wavehand(2, 100)),
1242            Err(Error::HandshakeOutOfSequence { .. })
1243        ));
1244    }
1245
1246    #[test]
1247    fn feed_rejects_non_handshake_packets_outside_recovery_case() {
1248        use crate::packet::misc::KeepAlivePacket;
1249        let mut r = RendezvousHandshake::new(
1250            1,
1251            500,
1252            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1253        );
1254        r.start().unwrap();
1255        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
1256            timestamp: SrtTimestamp::ZERO,
1257            dest_socket_id: SocketId::from_wire(0),
1258            libsrt_pad: false,
1259        });
1260        assert!(matches!(
1261            r.feed(&ka),
1262            Err(Error::UnexpectedControlPacket { .. })
1263        ));
1264    }
1265
1266    /// The state machine's internal invariants (a role is resolved before
1267    /// Attention/Initiated, the peer's HSREQ/HSRSP is known before Connected)
1268    /// are errors, not panics, if ever violated.
1269    #[test]
1270    fn broken_internal_invariants_are_errors_not_panics() {
1271        use crate::packet::{EncryptionField, HandshakeExtensionFlags, HandshakeExtensions};
1272        let hp = HandshakePacket {
1273            timestamp: SrtTimestamp::ZERO,
1274            dest_socket_id: SocketId::from_wire(1),
1275            version: 5,
1276            encryption_field: EncryptionField::NoEncryption,
1277            extension_field: HandshakeExtensionFlags::new(0),
1278            initial_seq_number: 0,
1279            mtu: 1500,
1280            max_flow_window_size: 8192,
1281            handshake_type: HandshakeType::Conclusion,
1282            srt_socket_id: 2,
1283            syn_cookie: 0,
1284            peer_ip: [0; 4],
1285            extensions: HandshakeExtensions(Vec::new()),
1286        };
1287        let mut r = RendezvousHandshake::new(
1288            1,
1289            5,
1290            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1291        );
1292        assert!(matches!(
1293            r.on_attention(&hp),
1294            Err(Error::HandshakeOutOfSequence { .. })
1295        ));
1296        assert!(matches!(
1297            r.on_initiated(&hp),
1298            Err(Error::HandshakeOutOfSequence { .. })
1299        ));
1300        assert!(matches!(
1301            r.enter_connected(),
1302            Err(Error::HandshakeOutOfSequence { .. })
1303        ));
1304    }
1305
1306    fn ext_hs_msg() -> HsExtMessage {
1307        HsExtMessage {
1308            srt_version: 0x0105_0000,
1309            srt_flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
1310            receiver_tsbpd_delay: Duration::from_millis(120),
1311            sender_tsbpd_delay: Duration::from_millis(120),
1312        }
1313    }
1314
1315    fn plain_handshake(
1316        handshake_type: HandshakeType,
1317        socket_id: u32,
1318        cookie: u32,
1319    ) -> ControlPacket<'static> {
1320        ControlPacket::Handshake(HandshakePacket {
1321            timestamp: SrtTimestamp::ZERO,
1322            dest_socket_id: SocketId::from_wire(1),
1323            version: HANDSHAKE_VERSION_5,
1324            encryption_field: EncryptionField::NoEncryption,
1325            extension_field: HandshakeExtensionFlags::new(0),
1326            initial_seq_number: 0,
1327            mtu: 1500,
1328            max_flow_window_size: 8192,
1329            handshake_type,
1330            srt_socket_id: socket_id,
1331            syn_cookie: cookie,
1332            peer_ip: [0; 4],
1333            extensions: HandshakeExtensions(Vec::new()),
1334        })
1335    }
1336
1337    fn conclusion_with_hs_ext(
1338        ext_type: ExtensionType,
1339        socket_id: u32,
1340        cookie: u32,
1341    ) -> ControlPacket<'static> {
1342        let contents = handshake_sm::ConclusionExtensionContents::new(ext_hs_msg(), None, None);
1343        let contents: &'static handshake_sm::ConclusionExtensionContents =
1344            alloc::boxed::Box::leak(alloc::boxed::Box::new(contents));
1345        let (extensions, ext_flags) = handshake_sm::build_conclusion_extensions(ext_type, contents);
1346        ControlPacket::Handshake(HandshakePacket {
1347            timestamp: SrtTimestamp::ZERO,
1348            dest_socket_id: SocketId::from_wire(1),
1349            version: HANDSHAKE_VERSION_5,
1350            encryption_field: EncryptionField::NoEncryption,
1351            extension_field: HandshakeExtensionFlags::new(ext_flags),
1352            initial_seq_number: 0,
1353            mtu: 1500,
1354            max_flow_window_size: 8192,
1355            handshake_type: HandshakeType::Conclusion,
1356            srt_socket_id: socket_id,
1357            syn_cookie: cookie,
1358            peer_ip: [0; 4],
1359            extensions,
1360        })
1361    }
1362
1363    fn sent_bytes(outputs: &[HandshakeOutput]) -> Vec<u8> {
1364        outputs
1365            .iter()
1366            .find_map(|o| match o {
1367                HandshakeOutput::Send(b) => Some(b.clone()),
1368                _ => None,
1369            })
1370            .expect("a Send output")
1371    }
1372
1373    /// §4.3.2 serial-flow crossing: an Initiator still in Waving receives a
1374    /// CONCLUSION+HSRSP directly and completes.
1375    #[test]
1376    fn initiator_completes_from_a_crossing_conclusion_with_hsrsp() {
1377        let mut a = RendezvousHandshake::new(
1378            1,
1379            500,
1380            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1381        );
1382        a.start().unwrap();
1383        let outputs = a
1384            .feed(&conclusion_with_hs_ext(ExtensionType::HsRsp, 2, 100))
1385            .unwrap();
1386        assert_eq!(a.role(), Some(RendezvousRole::Initiator));
1387        assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1388        assert!(
1389            outputs
1390                .iter()
1391                .any(|o| matches!(o, HandshakeOutput::Connected(_))),
1392            "{outputs:?}"
1393        );
1394    }
1395
1396    /// Attention + duplicate WAVEAHAND: resend the last message, no state
1397    /// change (neither table defines the duplicate).
1398    #[test]
1399    fn duplicate_wavehand_in_attention_is_resent() {
1400        let mut b = RendezvousHandshake::new(
1401            2,
1402            100,
1403            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1404        );
1405        b.start().unwrap();
1406        let first = b.feed(&wavehand(1, 500)).unwrap();
1407        let first_bytes = sent_bytes(&first);
1408        let again = b.feed(&wavehand(1, 500)).unwrap();
1409        assert_eq!(sent_bytes(&again), first_bytes);
1410        assert_eq!(b.state(), RendezvousHandshakeState::Attention);
1411    }
1412
1413    /// Responder Attention + extension-less CONCLUSION: resend the empty
1414    /// CONCLUSION and stay in Attention (L2357-2360).
1415    #[test]
1416    fn responder_attention_without_extensions_resends_empty_conclusion() {
1417        let mut b = RendezvousHandshake::new(
1418            2,
1419            100,
1420            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1421        );
1422        b.start().unwrap();
1423        b.feed(&wavehand(1, 500)).unwrap();
1424        let outputs = b
1425            .feed(&plain_handshake(HandshakeType::Conclusion, 1, 500))
1426            .unwrap();
1427        let bytes = sent_bytes(&outputs);
1428        let ControlPacket::Handshake(hp) = ControlPacket::parse(&bytes).unwrap() else {
1429            panic!("expected handshake");
1430        };
1431        assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1432        assert_eq!(hp.extensions.iter().count(), 0);
1433        assert_eq!(b.state(), RendezvousHandshakeState::Attention);
1434        assert_eq!(b.role(), Some(RendezvousRole::Responder));
1435    }
1436
1437    /// Responder Initiated + AGREEMENT: enter Connected and answer AGREEMENT.
1438    #[test]
1439    fn responder_initiated_agreement_connects() {
1440        let mut b = RendezvousHandshake::new(
1441            2,
1442            100,
1443            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1444        );
1445        b.start().unwrap();
1446        b.feed(&wavehand(1, 500)).unwrap();
1447        b.feed(&conclusion_with_hs_ext(ExtensionType::HsReq, 1, 500))
1448            .unwrap();
1449        assert_eq!(b.state(), RendezvousHandshakeState::Initiated);
1450        let outputs = b
1451            .feed(&plain_handshake(HandshakeType::Agreement, 1, 500))
1452            .unwrap();
1453        assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1454        let bytes = sent_bytes(&outputs);
1455        let ControlPacket::Handshake(hp) = ControlPacket::parse(&bytes).unwrap() else {
1456            panic!("expected handshake");
1457        };
1458        assert_eq!(hp.handshake_type, HandshakeType::Agreement);
1459    }
1460
1461    /// A Connected engine answers a repeated CONCLUSION with another
1462    /// AGREEMENT (recovery rule 4).
1463    #[test]
1464    fn connected_engine_answers_a_repeated_conclusion() {
1465        let mut a = RendezvousHandshake::new(
1466            1,
1467            500,
1468            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1469        );
1470        a.start().unwrap();
1471        a.feed(&conclusion_with_hs_ext(ExtensionType::HsRsp, 2, 100))
1472            .unwrap();
1473        assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1474        let outputs = a
1475            .feed(&plain_handshake(HandshakeType::Conclusion, 2, 100))
1476            .unwrap();
1477        let bytes = sent_bytes(&outputs);
1478        let ControlPacket::Handshake(hp) = ControlPacket::parse(&bytes).unwrap() else {
1479            panic!("expected handshake");
1480        };
1481        assert_eq!(hp.handshake_type, HandshakeType::Agreement);
1482        assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1483    }
1484
1485    /// `tick` resends the last message once the retransmit period has passed
1486    /// and times out after the retry budget.
1487    #[test]
1488    fn tick_retransmits_and_then_times_out() {
1489        let config = HandshakeConfig::for_profile(broadcast_core::Profile::Server);
1490        let mut r = RendezvousHandshake::new(1, 500, config.clone());
1491        let sent = r.start().unwrap();
1492        let outputs = r.tick(config.retransmit_after);
1493        assert_eq!(sent_bytes(&outputs), sent, "the WAVEAHAND is re-sent");
1494        for _ in 0..=config.max_retries {
1495            let _ = r.tick(config.retransmit_after);
1496        }
1497        assert_eq!(r.state(), RendezvousHandshakeState::TimedOut);
1498    }
1499
1500    /// Recovery rule 3: only a Responder stuck in Initiated is promoted by a
1501    /// non-handshake packet or [`RendezvousHandshake::on_recovery_trigger`];
1502    /// an Initiator in the same state is an error, not a promotion.
1503    #[test]
1504    fn recovery_trigger_promotes_only_a_responder_in_initiated() {
1505        let mut b = RendezvousHandshake::new(
1506            2,
1507            100,
1508            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1509        );
1510        b.start().unwrap();
1511        b.feed(&wavehand(1, 500)).unwrap();
1512        b.feed(&conclusion_with_hs_ext(ExtensionType::HsReq, 1, 500))
1513            .unwrap();
1514        assert_eq!(b.state(), RendezvousHandshakeState::Initiated);
1515        let outputs = b.on_recovery_trigger().unwrap();
1516        assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1517        assert!(
1518            outputs
1519                .iter()
1520                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
1521        );
1522
1523        let mut a = RendezvousHandshake::new(
1524            1,
1525            500,
1526            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1527        );
1528        a.start().unwrap();
1529        a.feed(&wavehand(2, 100)).unwrap();
1530        a.feed(&plain_handshake(HandshakeType::Conclusion, 2, 100))
1531            .unwrap();
1532        assert_eq!(a.state(), RendezvousHandshakeState::Initiated);
1533        assert!(a.on_recovery_trigger().unwrap().is_empty());
1534        assert_eq!(a.state(), RendezvousHandshakeState::Initiated);
1535    }
1536
1537    #[test]
1538    fn recovery_feed_promotes_only_a_responder_in_initiated() {
1539        use crate::packet::misc::KeepAlivePacket;
1540        let keepalive = ControlPacket::KeepAlive(KeepAlivePacket {
1541            timestamp: SrtTimestamp::ZERO,
1542            dest_socket_id: SocketId::from_wire(1),
1543            libsrt_pad: false,
1544        });
1545
1546        let mut b = RendezvousHandshake::new(
1547            2,
1548            100,
1549            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1550        );
1551        b.start().unwrap();
1552        b.feed(&wavehand(1, 500)).unwrap();
1553        b.feed(&conclusion_with_hs_ext(ExtensionType::HsReq, 1, 500))
1554            .unwrap();
1555        let outputs = b.feed(&keepalive).unwrap();
1556        assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1557        assert!(
1558            outputs
1559                .iter()
1560                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
1561        );
1562
1563        let mut a = RendezvousHandshake::new(
1564            1,
1565            500,
1566            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
1567        );
1568        a.start().unwrap();
1569        a.feed(&wavehand(2, 100)).unwrap();
1570        a.feed(&plain_handshake(HandshakeType::Conclusion, 2, 100))
1571            .unwrap();
1572        assert!(matches!(
1573            a.feed(&keepalive),
1574            Err(Error::UnexpectedControlPacket { .. })
1575        ));
1576        assert_eq!(a.state(), RendezvousHandshakeState::Initiated);
1577    }
1578
1579    /// The libsrt-port tie-break across the sign boundary: the cases where
1580    /// the bit-31 test differs from an XOR of the sign bit.
1581    #[test]
1582    fn cookie_contest_signed_boundary_cases() {
1583        assert_eq!(cookie_contest(1, 0x8000_0000), RendezvousRole::Responder);
1584        assert_eq!(cookie_contest(0x8000_0000, 1), RendezvousRole::Initiator);
1585        assert_eq!(
1586            cookie_contest(0x7FFF_FFFF, 0x8000_0000),
1587            RendezvousRole::Responder
1588        );
1589        assert_eq!(
1590            cookie_contest(0x8000_0000, 0x7FFF_FFFF),
1591            RendezvousRole::Initiator
1592        );
1593        assert_eq!(cookie_contest(0x8000_0001, 1), RendezvousRole::Responder);
1594        assert_eq!(cookie_contest(1, 0x8000_0001), RendezvousRole::Initiator);
1595    }
1596
1597    /// §3.2.1.1 (reused by §4.3.2): rendezvous flags are the intersection of
1598    /// both sides' advertised sets, exactly as in the Caller-Listener flow.
1599    #[test]
1600    fn negotiated_flags_are_the_intersection_of_both_sides() {
1601        use crate::packet::handshake::{
1602            HS_MSG_FLAG_REXMITFLG, HS_MSG_FLAG_TLPKTDROP, HS_MSG_FLAG_TSBPDRCV,
1603            HS_MSG_FLAG_TSBPDSND, HandshakeExtensionMessageFlags,
1604        };
1605        let local = HandshakeExtensionMessageFlags::new(
1606            HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV | HS_MSG_FLAG_TLPKTDROP,
1607        );
1608        let peer = HandshakeExtensionMessageFlags::new(
1609            HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV | HS_MSG_FLAG_REXMITFLG,
1610        );
1611        let config = HandshakeConfig {
1612            flags: local,
1613            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
1614        };
1615        let mut r = RendezvousHandshake::new(1, 500, config);
1616        r.start().unwrap();
1617        r.role = Some(RendezvousRole::Initiator);
1618        r.peer_hs_msg = Some(HsExtMessage {
1619            srt_version: 0x0105_0000,
1620            srt_flags: peer,
1621            receiver_tsbpd_delay: Duration::from_millis(120),
1622            sender_tsbpd_delay: Duration::from_millis(120),
1623        });
1624        r.peer_limits = Some((1500, 8192));
1625        assert_eq!(
1626            r.build_negotiated().expect("negotiated").flags,
1627            HandshakeExtensionMessageFlags::new(HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV)
1628        );
1629    }
1630
1631    #[test]
1632    fn state_and_role_labels_match_the_diagram() {
1633        assert_eq!(RendezvousHandshakeState::Idle.name(), "Idle");
1634        assert_eq!(RendezvousHandshakeState::Waving.name(), "Waving");
1635        assert_eq!(RendezvousHandshakeState::Attention.name(), "Attention");
1636        assert_eq!(RendezvousHandshakeState::Initiated.name(), "Initiated");
1637        assert_eq!(RendezvousHandshakeState::Connected.name(), "Connected");
1638        assert_eq!(RendezvousHandshakeState::Rejected.name(), "Rejected");
1639        assert_eq!(RendezvousHandshakeState::TimedOut.name(), "TimedOut");
1640        assert_eq!(RendezvousRole::Initiator.name(), "Initiator");
1641        assert_eq!(RendezvousRole::Responder.name(), "Responder");
1642    }
1643}
1644
1645#[cfg(test)]
1646#[cfg(feature = "crypto")]
1647mod crypto_echo_tests {
1648    use super::super::*;
1649    #[cfg(feature = "crypto")]
1650    use crate::handshake_sm::{CryptoConfig, HANDSHAKE_VERSION_5};
1651    #[cfg(feature = "crypto")]
1652    use crate::packet::{
1653        ControlPacket, EncryptionField, ExtensionType, HandshakeExtensionFlags, HandshakePacket,
1654        HandshakeType, HsExtMessage, SocketId, SrtTimestamp,
1655    };
1656    #[cfg(feature = "crypto")]
1657    use core::time::Duration;
1658
1659    #[cfg(feature = "crypto")]
1660    #[test]
1661    fn rendezvous_initiator_rejects_a_tampered_km_echo() {
1662        use crate::packet::{ControlPacket, EncryptionField};
1663
1664        const PEER_A_SOCKET_ID: u32 = 0x1111_1111;
1665        const PEER_B_SOCKET_ID: u32 = 0x2222_2222;
1666        const PEER_A_COOKIE: u32 = 0xAAAA_0002;
1667        const PEER_B_COOKIE: u32 = 0x1111_0001;
1668
1669        let passphrase = b"passphrase".to_vec();
1670        let crypto = CryptoConfig {
1671            passphrase: passphrase.clone(),
1672            salt: [0x11u8; 16],
1673            sek: vec![0x22u8; 16],
1674        };
1675        let config_a = HandshakeConfig {
1676            encryption_field: EncryptionField::Aes128,
1677            crypto: Some(crypto.clone()),
1678            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
1679        };
1680        let config_b = HandshakeConfig {
1681            encryption_field: EncryptionField::Aes128,
1682            crypto: Some(crypto),
1683            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
1684        };
1685
1686        // Untampered run must complete.
1687        {
1688            let mut a = RendezvousHandshake::new(PEER_A_SOCKET_ID, PEER_A_COOKIE, config_a.clone());
1689            let mut b = RendezvousHandshake::new(PEER_B_SOCKET_ID, PEER_B_COOKIE, config_b.clone());
1690            let mut to_a = vec![b.start().expect("b start")];
1691            let mut to_b = vec![a.start().expect("a start")];
1692            for _ in 0..20 {
1693                if a.state() == RendezvousHandshakeState::Connected
1694                    && b.state() == RendezvousHandshakeState::Connected
1695                {
1696                    break;
1697                }
1698                let mut next_to_a = Vec::new();
1699                let mut next_to_b = Vec::new();
1700                for msg in to_a.drain(..) {
1701                    if a.state() == RendezvousHandshakeState::Rejected {
1702                        continue;
1703                    }
1704                    let pkt = ControlPacket::parse(&msg).expect("valid");
1705                    for out in a.feed(&pkt).expect("a.feed") {
1706                        if let HandshakeOutput::Send(bytes) = out {
1707                            next_to_b.push(bytes);
1708                        }
1709                    }
1710                }
1711                for msg in to_b.drain(..) {
1712                    let pkt = ControlPacket::parse(&msg).expect("valid");
1713                    for out in b.feed(&pkt).expect("b.feed") {
1714                        if let HandshakeOutput::Send(bytes) = out {
1715                            next_to_a.push(bytes);
1716                        }
1717                    }
1718                }
1719                to_a = next_to_a;
1720                to_b = next_to_b;
1721                if to_a.is_empty() && to_b.is_empty() {
1722                    break;
1723                }
1724            }
1725            assert_eq!(a.state(), RendezvousHandshakeState::Connected);
1726            assert_eq!(b.state(), RendezvousHandshakeState::Connected);
1727        }
1728
1729        // Tampered run: flip a byte in the Responder's key-material echo.
1730        let mut a = RendezvousHandshake::new(PEER_A_SOCKET_ID, PEER_A_COOKIE, config_a);
1731        let mut b = RendezvousHandshake::new(PEER_B_SOCKET_ID, PEER_B_COOKIE, config_b);
1732        let mut to_a = vec![b.start().expect("b start")];
1733        let mut to_b = vec![a.start().expect("a start")];
1734        let mut tampered = false;
1735        let mut rejected = false;
1736        for _ in 0..20 {
1737            if rejected {
1738                break;
1739            }
1740            if a.state() == RendezvousHandshakeState::Connected
1741                && b.state() == RendezvousHandshakeState::Connected
1742            {
1743                break;
1744            }
1745            let mut next_to_a = Vec::new();
1746            let mut next_to_b = Vec::new();
1747            for msg in to_a.drain(..) {
1748                let pkt = ControlPacket::parse(&msg).expect("valid");
1749                for out in a.feed(&pkt).expect("a.feed") {
1750                    if let HandshakeOutput::Send(bytes) = out {
1751                        next_to_b.push(bytes);
1752                    }
1753                }
1754            }
1755            for msg in to_b.drain(..) {
1756                let mut msg = msg;
1757                if !tampered && msg.windows(2).any(|w| w == [0, 4]) {
1758                    if let Some(last) = msg.last_mut() {
1759                        *last ^= 0xFF;
1760                    }
1761                    tampered = true;
1762                }
1763                if b.state() == RendezvousHandshakeState::Rejected {
1764                    continue;
1765                }
1766                let pkt = ControlPacket::parse(&msg).expect("valid");
1767                for out in b.feed(&pkt).expect("b.feed") {
1768                    match out {
1769                        HandshakeOutput::Send(bytes) => next_to_a.push(bytes),
1770                        HandshakeOutput::Rejected(reason) => {
1771                            assert_eq!(reason, RejectionReason::BadSecret);
1772                            rejected = true;
1773                        }
1774                        _ => {}
1775                    }
1776                }
1777            }
1778            to_a = next_to_a;
1779            to_b = next_to_b;
1780            if to_a.is_empty() && to_b.is_empty() {
1781                break;
1782            }
1783        }
1784        assert!(tampered, "never found a key-material echo to tamper");
1785        assert!(rejected, "initiator did not reject the tampered echo");
1786        assert_eq!(b.state(), RendezvousHandshakeState::Rejected);
1787    }
1788
1789    fn test_crypto() -> CryptoConfig {
1790        CryptoConfig::new(
1791            b"rendezvous-crypto-passphrase".to_vec(),
1792            [0x11u8; 16],
1793            vec![0x22u8; 16],
1794        )
1795    }
1796
1797    fn test_hs_msg() -> HsExtMessage {
1798        HsExtMessage {
1799            srt_version: 0x0105_0000,
1800            srt_flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
1801            receiver_tsbpd_delay: Duration::from_millis(120),
1802            sender_tsbpd_delay: Duration::from_millis(120),
1803        }
1804    }
1805
1806    fn crossing_conclusion(
1807        hs_msg: HsExtMessage,
1808        km: Option<Vec<u8>>,
1809        socket_id: u32,
1810        cookie: u32,
1811    ) -> ControlPacket<'static> {
1812        let mut contents = handshake_sm::ConclusionExtensionContents::new(hs_msg, None, None);
1813        if let Some(bytes) = km {
1814            contents.set_key_material(ExtensionType::KmRsp, bytes);
1815        }
1816        let contents: &'static handshake_sm::ConclusionExtensionContents =
1817            alloc::boxed::Box::leak(alloc::boxed::Box::new(contents));
1818        let (extensions, ext_flags) =
1819            handshake_sm::build_conclusion_extensions(ExtensionType::HsRsp, contents);
1820        ControlPacket::Handshake(HandshakePacket {
1821            timestamp: SrtTimestamp::ZERO,
1822            dest_socket_id: SocketId::from_wire(1),
1823            version: HANDSHAKE_VERSION_5,
1824            encryption_field: EncryptionField::Aes128,
1825            extension_field: HandshakeExtensionFlags::new(ext_flags),
1826            initial_seq_number: 0,
1827            mtu: 1500,
1828            max_flow_window_size: 8192,
1829            handshake_type: HandshakeType::Conclusion,
1830            srt_socket_id: socket_id,
1831            syn_cookie: cookie,
1832            peer_ip: [0; 4],
1833            extensions,
1834        })
1835    }
1836
1837    fn crossing_initiator(crypto: Option<CryptoConfig>) -> RendezvousHandshake {
1838        let config = HandshakeConfig {
1839            encryption_field: EncryptionField::Aes128,
1840            crypto,
1841            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
1842        };
1843        let mut r = RendezvousHandshake::new(1, 500, config);
1844        r.start().unwrap();
1845        r
1846    }
1847
1848    /// The serial-crossing Initiator (Waving -> a CONCLUSION+HSRSP directly)
1849    /// verifies the Key Material echo before it may use the SEK.
1850    #[test]
1851    fn crossing_initiator_verifies_a_matching_km_echo() {
1852        let crypto = test_crypto();
1853        let km = handshake_sm::build_key_material_contents(&crypto).expect("key material");
1854        let mut r = crossing_initiator(Some(crypto.clone()));
1855        let outputs = r
1856            .feed(&crossing_conclusion(test_hs_msg(), Some(km), 2, 100))
1857            .expect("complete");
1858        assert_eq!(r.state(), RendezvousHandshakeState::Connected);
1859        assert!(
1860            outputs
1861                .iter()
1862                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
1863        );
1864        let negotiated = r.negotiated().expect("negotiated");
1865        assert_eq!(
1866            negotiated.sek.as_ref().map(|s| &s[..]),
1867            Some(crypto.sek.as_slice())
1868        );
1869        assert_eq!(negotiated.salt, Some(crypto.salt));
1870    }
1871
1872    #[test]
1873    fn crossing_initiator_rejects_a_tampered_km_echo() {
1874        let crypto = test_crypto();
1875        let mut km = handshake_sm::build_key_material_contents(&crypto).expect("key material");
1876        let last = km.len() - 1;
1877        km[last] ^= 0xFF;
1878        let mut r = crossing_initiator(Some(crypto));
1879        let outputs = r
1880            .feed(&crossing_conclusion(test_hs_msg(), Some(km), 2, 100))
1881            .expect("feed");
1882        assert!(
1883            outputs.contains(&HandshakeOutput::Rejected(RejectionReason::BadSecret)),
1884            "{outputs:?}"
1885        );
1886        assert_eq!(r.state(), RendezvousHandshakeState::Rejected);
1887    }
1888
1889    #[test]
1890    fn crossing_initiator_without_crypto_rejects_a_km_echo() {
1891        let km = handshake_sm::build_key_material_contents(&test_crypto()).expect("key material");
1892        let mut r = crossing_initiator(None);
1893        let outputs = r
1894            .feed(&crossing_conclusion(test_hs_msg(), Some(km), 2, 100))
1895            .expect("feed");
1896        assert!(
1897            outputs.contains(&HandshakeOutput::Rejected(RejectionReason::Unsecure)),
1898            "{outputs:?}"
1899        );
1900    }
1901
1902    #[test]
1903    fn crossing_initiator_with_crypto_rejects_a_missing_km_echo() {
1904        let mut r = crossing_initiator(Some(test_crypto()));
1905        let outputs = r
1906            .feed(&crossing_conclusion(test_hs_msg(), None, 2, 100))
1907            .expect("feed");
1908        assert!(
1909            outputs.contains(&HandshakeOutput::Rejected(RejectionReason::Unsecure)),
1910            "{outputs:?}"
1911        );
1912    }
1913
1914    /// SEK and Salt are only handed to a connection whose KM echo was
1915    /// verified (the `crypto_verified` conjunction).
1916    #[test]
1917    fn negotiated_secrets_require_a_verified_km_echo() {
1918        let crypto = test_crypto();
1919        let config = HandshakeConfig {
1920            encryption_field: EncryptionField::Aes128,
1921            crypto: Some(crypto.clone()),
1922            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
1923        };
1924        let mut r = RendezvousHandshake::new(1, 500, config);
1925        r.start().unwrap();
1926        r.role = Some(RendezvousRole::Initiator);
1927        r.peer_hs_msg = Some(test_hs_msg());
1928        r.peer_limits = Some((1500, 8192));
1929        r.crypto_verified = false;
1930        let unverified = r.build_negotiated().expect("negotiated");
1931        assert!(unverified.sek.is_none());
1932        assert!(unverified.salt.is_none());
1933
1934        r.crypto_verified = true;
1935        let verified = r.build_negotiated().expect("negotiated");
1936        assert_eq!(
1937            verified.sek.as_ref().map(|s| &s[..]),
1938            Some(crypto.sek.as_slice())
1939        );
1940        assert_eq!(verified.salt, Some(crypto.salt));
1941    }
1942}