srt_runtime/rendezvous.rs
1//! Rendezvous handshake engine — `draft-sharabayko-srt-01` §4.3.2 (Rendezvous
2//! Handshake), curated at `specs/rules/srt-rendezvous.md`. Line cites below
3//! (`LNNNN`) are the source draft's line numbers, exactly as recorded in that
4//! curation.
5//!
6//! [`RendezvousHandshake`] is symmetric: both peers run the *same* engine
7//! (unlike [`crate::caller::CallerHandshake`] / [`crate::listener::ListenerHandshake`],
8//! which run different code for different roles). Which of the two logical
9//! roles — **Initiator** or **Responder** — a given instance ends up playing
10//! is decided at runtime by the **cookie contest** (§4.3.2, L2107-2135):
11//! each side supplies its own 32-bit cookie to [`RendezvousHandshake::new`]
12//! (this crate never reads a clock or a socket address — see
13//! [`crate::handshake_sm::derive_cookie`] for a ready-made, non-standardized
14//! derivation helper, exactly as for [`crate::listener::ListenerHandshake`]),
15//! and the greater cookie value wins ("becomes Initiator", L2133-2135).
16//!
17//! # State machine
18//!
19//! States are named exactly as the draft's Parallel Handshake Flow diagram
20//! (§4.3.2.2, L2280, quoted verbatim): **Waving → Attention → Initiated →
21//! Connected** (plus `Idle` before [`RendezvousHandshake::start`] is called —
22//! not spec-named, mirrors [`crate::caller::CallerHandshakeState::Idle`] — and
23//! `Rejected`/`TimedOut` terminal states, also not spec-named). Every
24//! transition below is the Initiator table (L2301-2334) or Responder table
25//! (L2336-2382), or a missing-packet recovery rule (L2383-2432).
26//!
27//! ## Serial vs Parallel flow: one engine, not two
28//!
29//! The draft narrates two "flows" (§4.3.2.1 Serial, L2140-2269; §4.3.2.2
30//! Parallel, L2270-2432) that differ only in *message interleaving*, not in
31//! any new transition rule: the Parallel flow's Initiator/Responder tables are
32//! complete state × received-message tables, driven purely by message
33//! content — so they already cover the Serial flow's crossing case. That case
34//! is: a peer still in `Waving` (having sent its own WAVEAHAND but never
35//! having received the other side's) receives a **CONCLUSION** directly
36//! instead of a WAVEAHAND (§4.3.2.1 step 3, L2203-2219 — the draft calls the
37//! resulting state "fine"). Tracing the draft's own worked example confirms
38//! the action taken is identical to applying the Parallel Attention row to
39//! that CONCLUSION: an Initiator receiving an extension-less CONCLUSION here
40//! behaves exactly like the Initiator-Attention-row "no extensions" case
41//! (L2312-2318); a Responder receiving a CONCLUSION+HSREQ here behaves
42//! exactly like the Responder-Attention-row HSREQ case (L2360-2364) — because
43//! by this point in the exchange the peer's role-appropriate first CONCLUSION
44//! already carries whatever extension its role dictates (Initiator: HSREQ
45//! immediately, L2286-2287; Responder: none until it has seen HSREQ,
46//! L2357-2360/L2287-2288). This implementation therefore has **no separate
47//! "Fine" state** — a received CONCLUSION while still in `Waving` dispatches
48//! straight into the same Attention-row logic used when genuinely in
49//! `Attention`, rather than inventing a fourth, behaviourally-divergent state
50//! the tables do not define.
51//!
52//! ## Resolved ambiguities (not explicit in the curated rules)
53//!
54//! - **Cookie collision → rejection.** The draft says only "the connection
55//! will not be made until new, unique cookies are generated" (L2119-2124),
56//! describing an out-of-band retry, not a wire action. This engine surfaces
57//! it as [`RejectionReason::RdvCookie`] (Table 7 code `1009`, "rendezvous
58//! cookie collision" — an exact fit) rather than blocking or retrying
59//! internally; a driver that wants the "regenerate and retry" behaviour
60//! builds a fresh [`RendezvousHandshake`] with a new cookie.
61//! - **CONCLUSION `SYN Cookie` field.** The draft specifies WAVEAHAND's SYN
62//! Cookie (L2156-2165) but not what later CONCLUSION/AGREEMENT messages
63//! carry in that field. Every message this engine sends after WAVEAHAND
64//! continues to carry *this side's own* cookie (never an echo of the peer's,
65//! unlike the Caller-Listener flood-protection cookie) — consistent with
66//! the cookie's role here being mutual identification/contest, not a
67//! flood-protection echo-token.
68//! - **No Stream ID / Group Membership exchange.** Neither extension is
69//! mentioned anywhere in §4.3.2; unlike
70//! [`crate::handshake_sm::NegotiatedParams`] from the Caller-Listener flow,
71//! this engine never sends them and always reports `stream_id: None`,
72//! `group: None` — flagged rather than fabricated.
73//! - **Latency/flags reconciliation.** §4.3.2 does not restate the
74//! greater-latency / AND-flags rule from §4.3.1.2, but it is a property of
75//! the Handshake Extension Message itself (§3.2.1.1), not of the flow that
76//! carried it, so the same shared `handshake_sm` reconciliation helper used
77//! by the Caller-Listener flow is reused unchanged.
78//! - **Duplicate WAVEAHAND while already `Attention`.** Not covered by either
79//! table (which only fire on the *first* WAVEAHAND). Treated as a benign
80//! duplicate: resend the last message, no state change.
81//! - **Recovery rule 3 (data packet promotes a stuck Responder, L2413-2422)**
82//! is exposed as [`RendezvousHandshake::on_recovery_trigger`], since this
83//! engine's `feed` takes a [`ControlPacket`] (matching
84//! [`crate::caller::CallerHandshake`] / [`crate::listener::ListenerHandshake`]),
85//! not the data-plane [`crate::packet::SrtPacket`]; a driver that receives a
86//! `SrtPacket::Data` (or any Control packet normally only sent between
87//! connected parties — [`RendezvousHandshake::feed`] already treats any
88//! *inbound* non-Handshake `ControlPacket` this way for exactly this
89//! reason) calls it directly.
90//!
91//! Explicit non-goals of THIS module (the sans-IO engine): ARQ/loss, TSBPD
92//! delivery, congestion control, AES key-wrap/unwrap crypto, and the Version-4
93//! legacy Rendezvous path (L2101-2105, out of
94//! scope of the draft excerpt this crate implements against). The `tokio`
95//! socket adapter drives this engine as `io::SrtSocket::rendezvous`.
96
97use alloc::vec;
98use alloc::vec::Vec;
99
100use crate::error::{Error, Result};
101use crate::handshake_sm::{
102 self, HANDSHAKE_VERSION_5, HandshakeConfig, HandshakeOutput, NegotiatedParams, RejectionReason,
103};
104use crate::packet::{
105 ControlPacket, EncryptionField, ExtensionType, HandshakeExtensionFlags,
106 HandshakeExtensionMessageFlags, HandshakeExtensions, HandshakePacket, HandshakeType,
107 HsExtMessage,
108};
109
110/// Rendezvous handshake lifecycle state (`draft-sharabayko-srt-01` §4.3.2).
111/// State names are exactly the Parallel Handshake Flow diagram (§4.3.2.2,
112/// L2280): `Waving -> Attention -> Initiated -> Connected`. See the module
113/// doc "Serial vs Parallel flow" note for why there is no separate state for
114/// the Serial flow's "fine".
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116#[cfg_attr(feature = "serde", derive(serde::Serialize))]
117#[non_exhaustive]
118pub enum RendezvousHandshakeState {
119 /// No handshake message sent yet. Not spec-named — mirrors
120 /// [`crate::caller::CallerHandshakeState::Idle`].
121 Idle,
122 /// L2100/L2153/L2280 "waving"/"Waving": both parties' initial state.
123 Waving,
124 /// L2172/L2280 "attention"/"Attention": a WAVEAHAND was received, the
125 /// cookie contest is resolved, awaiting the peer's CONCLUSION.
126 Attention,
127 /// L2234/L2280 "initiated"/"Initiated": role-appropriate extension
128 /// content has been seen at least once; awaiting the peer's confirmation.
129 Initiated,
130 /// L2224/L2251/L2280 "connected"/"Connected": the handshake completed;
131 /// [`NegotiatedParams`] are available.
132 Connected,
133 /// The handshake was rejected (locally, or by an explicit peer Table 7
134 /// code). Not spec-named.
135 Rejected,
136 /// No response arrived after the configured retry budget. Not spec-named.
137 TimedOut,
138}
139
140impl RendezvousHandshakeState {
141 /// A short label for this state.
142 pub fn name(&self) -> &'static str {
143 match self {
144 RendezvousHandshakeState::Idle => "Idle",
145 RendezvousHandshakeState::Waving => "Waving",
146 RendezvousHandshakeState::Attention => "Attention",
147 RendezvousHandshakeState::Initiated => "Initiated",
148 RendezvousHandshakeState::Connected => "Connected",
149 RendezvousHandshakeState::Rejected => "Rejected",
150 RendezvousHandshakeState::TimedOut => "TimedOut",
151 }
152 }
153}
154
155impl core::fmt::Display for RendezvousHandshakeState {
156 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
157 f.write_str(self.name())
158 }
159}
160
161/// The role a [`RendezvousHandshake`] plays, resolved by the cookie contest
162/// (`draft-sharabayko-srt-01` §4.3.2, L2107-2135): "When one party's cookie
163/// value is greater than its peer's, it wins the cookie contest and becomes
164/// Initiator (the other party becomes the Responder)."
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
166#[cfg_attr(feature = "serde", derive(serde::Serialize))]
167#[non_exhaustive]
168pub enum RendezvousRole {
169 /// Wins the cookie contest (the greater cookie value, L2133-2135). MUST
170 /// attach the HSREQ extension (L2286-2287).
171 Initiator,
172 /// Loses the cookie contest. MUST attach the HSRSP extension
173 /// (L2287-2288).
174 Responder,
175}
176
177impl RendezvousRole {
178 /// A short label for this role.
179 pub fn name(&self) -> &'static str {
180 match self {
181 RendezvousRole::Initiator => "Initiator",
182 RendezvousRole::Responder => "Responder",
183 }
184 }
185}
186
187broadcast_common::impl_spec_display!(RendezvousRole);
188
189/// Bit 31 (the sign bit of a 32-bit value), used to test the sign of a
190/// 32-bit quantity carried in a wider (`i64`) type without it having been
191/// sign-extended into that width — see [`cookie_contest`].
192const SIGN_BIT_32: i64 = 0x8000_0000;
193
194/// The cookie contest tie-break (issue #1064): given two cookies (this
195/// side's and the peer's, both already known not to be equal — see
196/// [`RendezvousHandshake::resolve_role`]), decide which side is
197/// [`RendezvousRole::Initiator`].
198///
199/// A direct port of libsrt's own `CUDT::backwardCompatibleCookieContest`
200/// (`srtcore/core.cpp`, v1.5.5, as published at
201/// <https://github.com/Haivision/srt/blob/v1.5.5/srtcore/core.cpp#L4262-L4286>):
202///
203/// ```c
204/// enum HandshakeSide srt::CUDT::backwardCompatibleCookieContest(int32_t req, int32_t res)
205/// {
206/// const int64_t xreq = int64_t(req);
207/// const int64_t xres = int64_t(res);
208/// const int64_t contest = xreq - xres;
209///
210/// if ((contest & 0xFFFFFFFF) == 0)
211/// {
212/// return HSD_DRAW;
213/// }
214/// if (contest & 0x80000000)
215/// {
216/// const int64_t revert = xres - xreq;
217/// if (revert & 0x80000000 && req > res)
218/// return HSD_INITIATOR;
219/// return HSD_RESPONDER;
220/// }
221///
222/// return HSD_INITIATOR;
223/// }
224/// ```
225///
226/// `req`/`res` there are `int32_t` — the raw cookie bit pattern *reinterpreted
227/// as signed* — and `xreq`/`xres` sign-*extend* that signed value into
228/// `int64_t` (so a cookie with the top bit set becomes a large-magnitude
229/// *negative* `i64`, not the same positive value an unsigned widen would
230/// give). This is why a plain unsigned `own_cookie > peer_cookie` compare
231/// (this function's pre-fix behavior) disagrees with libsrt for roughly a
232/// quarter of all cookie pairs: whenever exactly one of the two cookies has
233/// its top bit set, the sign-extending widen and the unsigned widen order
234/// the pair differently.
235///
236/// The `HSD_DRAW` arm is unreachable here (the caller already handles
237/// `own_cookie == peer_cookie` before this is called) and is not
238/// reproduced — this function always returns a role.
239fn cookie_contest(own_cookie: u32, peer_cookie: u32) -> RendezvousRole {
240 // libsrt reads each cookie as a signed 32-bit integer: the same bits,
241 // reinterpreted (not converted).
242 let req = i32::from_ne_bytes(own_cookie.to_ne_bytes());
243 let res = i32::from_ne_bytes(peer_cookie.to_ne_bytes());
244 let xreq = i64::from(req);
245 let xres = i64::from(res);
246 let contest = xreq - xres;
247
248 if contest & SIGN_BIT_32 != 0 {
249 let revert = xres - xreq;
250 if revert & SIGN_BIT_32 != 0 && req > res {
251 return RendezvousRole::Initiator;
252 }
253 return RendezvousRole::Responder;
254 }
255
256 RendezvousRole::Initiator
257}
258
259/// The Handshake Extension content found on one received CONCLUSION, keyed by
260/// which side sends which (§4.3.2.2, L2282-2288). Internal to this module —
261/// [`crate::handshake_sm::parse_peer_extensions`] does not distinguish
262/// HSREQ from HSRSP, which the Rendezvous tables need to.
263enum PeerHsExt {
264 /// No Handshake Extension block present.
265 None,
266 /// An `HSREQ` block was present (only an Initiator sends this).
267 HsReq(HsExtMessage),
268 /// An `HSRSP` block was present (only a Responder sends this).
269 HsRsp(HsExtMessage),
270}
271
272/// Walks `hp`'s extension blocks looking for an HSREQ or HSRSP Handshake
273/// Extension Message. Returns [`Error::InvalidField`] on any malformed block
274/// or malformed HSREQ/HSRSP contents — never panics on untrusted input.
275fn parse_peer_hs_ext(hp: &HandshakePacket<'_>) -> Result<PeerHsExt> {
276 let mut found = PeerHsExt::None;
277 for block in hp.extensions.iter() {
278 let block = block.map_err(|_| Error::InvalidField {
279 what: "rendezvous handshake extensions",
280 reason: "malformed extension block",
281 })?;
282 match block.ext_type {
283 ExtensionType::HsReq => {
284 let msg = block.as_hs_ext_message().map_err(|_| Error::InvalidField {
285 what: "HSREQ extension message",
286 reason: "malformed contents",
287 })?;
288 found = PeerHsExt::HsReq(msg);
289 }
290 ExtensionType::HsRsp => {
291 let msg = block.as_hs_ext_message().map_err(|_| Error::InvalidField {
292 what: "HSRSP extension message",
293 reason: "malformed contents",
294 })?;
295 found = PeerHsExt::HsRsp(msg);
296 }
297 _ => {}
298 }
299 }
300 Ok(found)
301}
302
303/// A driveable, symmetric SRT Rendezvous handshake
304/// (`draft-sharabayko-srt-01` §4.3.2). See the module docs for the state
305/// machine and the design decisions not explicit in the curated rules.
306#[derive(Debug)]
307pub struct RendezvousHandshake {
308 own_socket_id: u32,
309 own_cookie: u32,
310 config: HandshakeConfig,
311 state: RendezvousHandshakeState,
312 role: Option<RendezvousRole>,
313 peer_socket_id: u32,
314 peer_cookie: u32,
315 peer_hs_msg: Option<HsExtMessage>,
316 /// The peer's `MTU` and `Maximum Flow Window Size` (§3.2.1), from the
317 /// packet that carried its Handshake Extension Message.
318 peer_limits: Option<(u32, u32)>,
319 last_sent: Option<Vec<u8>>,
320 ticks_since_send: u32,
321 retries: u32,
322 negotiated: Option<NegotiatedParams>,
323}
324
325impl RendezvousHandshake {
326 /// Creates a fresh Rendezvous handshake in
327 /// [`RendezvousHandshakeState::Idle`], with the 32-bit cookie this side
328 /// will offer in the cookie contest (§4.3.2, L2107-2135). This crate never
329 /// reads a clock or a socket address — see
330 /// [`crate::handshake_sm::derive_cookie`] for a ready-made,
331 /// non-standardized derivation helper.
332 pub fn new(own_socket_id: u32, own_cookie: u32, config: HandshakeConfig) -> Self {
333 RendezvousHandshake {
334 own_socket_id,
335 own_cookie,
336 config,
337 state: RendezvousHandshakeState::Idle,
338 role: None,
339 peer_socket_id: 0,
340 peer_cookie: 0,
341 peer_hs_msg: None,
342 peer_limits: None,
343 last_sent: None,
344 ticks_since_send: 0,
345 retries: 0,
346 negotiated: None,
347 }
348 }
349
350 /// The current state.
351 pub fn state(&self) -> RendezvousHandshakeState {
352 self.state
353 }
354
355 /// The role resolved by the cookie contest, once past
356 /// [`RendezvousHandshakeState::Waving`].
357 pub fn role(&self) -> Option<RendezvousRole> {
358 self.role
359 }
360
361 /// The negotiated parameters, once [`RendezvousHandshakeState::Connected`].
362 pub fn negotiated(&self) -> Option<&NegotiatedParams> {
363 self.negotiated.as_ref()
364 }
365
366 /// Builds the initial WAVEAHAND handshake (§4.3.2, L2100/L2153-2170:
367 /// Version 5, this side's own cookie, no extensions) and transitions to
368 /// [`RendezvousHandshakeState::Waving`].
369 ///
370 /// # Errors
371 /// [`Error::HandshakeOutOfSequence`] if called more than once.
372 pub fn start(&mut self) -> Result<Vec<u8>> {
373 if self.state != RendezvousHandshakeState::Idle {
374 return Err(Error::HandshakeOutOfSequence {
375 state: self.state.name(),
376 reason: "start() called after the handshake already began",
377 });
378 }
379 let hp = HandshakePacket {
380 timestamp: 0,
381 dest_socket_id: 0, // Unknown yet — mirrors CallerHandshake::start's INDUCTION.
382 version: HANDSHAKE_VERSION_5,
383 encryption_field: self.config.encryption_field,
384 extension_field: HandshakeExtensionFlags(0),
385 initial_seq_number: self.config.initial_seq_number,
386 mtu: self.config.mtu,
387 max_flow_window_size: self.config.max_flow_window_size,
388 handshake_type: HandshakeType::Wavehand,
389 srt_socket_id: self.own_socket_id,
390 syn_cookie: self.own_cookie,
391 peer_ip: self.config.local_ip,
392 extensions: HandshakeExtensions(&[]),
393 };
394 let bytes = handshake_sm::build_bytes(hp)?;
395 self.last_sent = Some(bytes.clone());
396 self.ticks_since_send = 0;
397 self.state = RendezvousHandshakeState::Waving;
398 Ok(bytes)
399 }
400
401 /// Feeds an inbound control packet.
402 ///
403 /// A non-Handshake `ControlPacket` fed while this side is a Responder
404 /// stuck in [`RendezvousHandshakeState::Initiated`] is treated as
405 /// missing-packet recovery rule 3 (L2413-2422: "any control packet
406 /// normally only sent between connected parties") rather than an error —
407 /// see [`Self::on_recovery_trigger`] for the data-packet analogue.
408 ///
409 /// # Errors
410 /// [`Error::UnexpectedControlPacket`] for a non-Handshake packet outside
411 /// that one recovery case; [`Error::HandshakeOutOfSequence`] if fed before
412 /// [`Self::start`] or after a terminal state (a driver bug, not a peer
413 /// protocol failure).
414 pub fn feed(&mut self, packet: &ControlPacket<'_>) -> Result<Vec<HandshakeOutput>> {
415 let hp = match packet {
416 ControlPacket::Handshake(hp) => hp,
417 other => {
418 if self.state == RendezvousHandshakeState::Initiated
419 && self.role == Some(RendezvousRole::Responder)
420 {
421 return self.enter_connected();
422 }
423 return Err(Error::UnexpectedControlPacket {
424 actual: other.control_type().name(),
425 });
426 }
427 };
428 if let Some(reason) = RejectionReason::from_handshake_type(hp.handshake_type) {
429 return Ok(self.reject(reason));
430 }
431 if hp.version != HANDSHAKE_VERSION_5 {
432 // §4.3.2, L2101-2105: Version-4 legacy Rendezvous is out of scope.
433 return Ok(self.reject(RejectionReason::Version));
434 }
435 match self.state {
436 RendezvousHandshakeState::Idle => Err(Error::HandshakeOutOfSequence {
437 state: self.state.name(),
438 reason: "feed() called before start()",
439 }),
440 RendezvousHandshakeState::Waving => self.on_waving(hp),
441 RendezvousHandshakeState::Attention => self.on_attention(hp),
442 RendezvousHandshakeState::Initiated => self.on_initiated(hp),
443 RendezvousHandshakeState::Connected => self.on_connected(hp),
444 RendezvousHandshakeState::Rejected | RendezvousHandshakeState::TimedOut => {
445 Err(Error::HandshakeOutOfSequence {
446 state: self.state.name(),
447 reason: "handshake already reached a terminal state",
448 })
449 }
450 }
451 }
452
453 /// Convenience wrapper: parses `bytes` as a [`ControlPacket`] then
454 /// [`Self::feed`]s it.
455 pub fn feed_bytes(&mut self, bytes: &[u8]) -> Result<Vec<HandshakeOutput>> {
456 let packet = ControlPacket::parse(bytes)?;
457 self.feed(&packet)
458 }
459
460 /// Missing-packet recovery rule 3 (§4.3.2.2, L2413-2422): call this when
461 /// the driver receives a data packet (`SrtPacket::Data`) while this side
462 /// has not yet reached [`RendezvousHandshakeState::Connected`]. A no-op
463 /// (`Ok(Vec::new())`) unless this side is a Responder stuck in
464 /// [`RendezvousHandshakeState::Initiated`] — the one case the draft says
465 /// is "exceptionally allowed" to promote to Connected "as if it had
466 /// received AGREEMENT".
467 pub fn on_recovery_trigger(&mut self) -> Result<Vec<HandshakeOutput>> {
468 if self.state == RendezvousHandshakeState::Initiated
469 && self.role == Some(RendezvousRole::Responder)
470 {
471 self.enter_connected()
472 } else {
473 Ok(Vec::new())
474 }
475 }
476
477 /// Advances retransmit timing by one caller-defined tick, mirroring
478 /// [`crate::caller::CallerHandshake::tick`] /
479 /// [`crate::listener::ListenerHandshake::tick`].
480 pub fn tick(&mut self) -> Vec<HandshakeOutput> {
481 if matches!(
482 self.state,
483 RendezvousHandshakeState::Idle
484 | RendezvousHandshakeState::Connected
485 | RendezvousHandshakeState::Rejected
486 | RendezvousHandshakeState::TimedOut
487 ) {
488 return Vec::new();
489 }
490 self.ticks_since_send += 1;
491 if self.ticks_since_send < self.config.retransmit_after_ticks {
492 return Vec::new();
493 }
494 self.ticks_since_send = 0;
495 self.retries += 1;
496 if self.retries > self.config.max_retries {
497 self.state = RendezvousHandshakeState::TimedOut;
498 return vec![HandshakeOutput::TimedOut];
499 }
500 match self.last_sent.clone() {
501 Some(bytes) => vec![HandshakeOutput::Send(bytes)],
502 None => Vec::new(),
503 }
504 }
505
506 /// [`RendezvousHandshakeState::Waving`]: the first message ever received
507 /// from the peer — either a genuine WAVEAHAND (§4.3.2.2 Waving row,
508 /// L2301-2306 Initiator / L2336-2342 Responder) or, in the Serial flow's
509 /// crossing case, a CONCLUSION directly (see module docs). Either way the
510 /// cookie contest is resolved here, from `hp.syn_cookie`.
511 fn on_waving(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
512 if !matches!(
513 hp.handshake_type,
514 HandshakeType::Wavehand | HandshakeType::Conclusion
515 ) {
516 return Ok(self.reject(RejectionReason::Rogue));
517 }
518 self.peer_socket_id = hp.srt_socket_id;
519 let role = match self.resolve_role(hp.syn_cookie) {
520 Ok(r) => r,
521 Err(_) => return Ok(self.reject(RejectionReason::RdvCookie)),
522 };
523 self.peer_cookie = hp.syn_cookie;
524 self.role = Some(role);
525
526 if hp.handshake_type == HandshakeType::Wavehand {
527 self.state = RendezvousHandshakeState::Attention;
528 match role {
529 // Initiator Waving row (L2301-2306): send CONCLUSION+HSREQ.
530 RendezvousRole::Initiator => self.send_conclusion(Some(ExtensionType::HsReq)),
531 // Responder Waving row (L2336-2342): send CONCLUSION, no
532 // extensions (it has not seen the peer's HSREQ yet).
533 RendezvousRole::Responder => self.send_conclusion(None),
534 }
535 } else {
536 // Serial-flow crossing (§4.3.2.1 step 3, L2203-2219): apply the
537 // same content-driven Attention-row logic (module docs).
538 self.on_attention_conclusion(hp, role)
539 }
540 }
541
542 /// [`RendezvousHandshakeState::Attention`]: a WAVEAHAND was already seen
543 /// and processed; only a CONCLUSION (Attention row) or a duplicate
544 /// WAVEAHAND (not covered by either table — treated as a benign resend,
545 /// module docs) is expected here.
546 fn on_attention(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
547 let role = self.role.ok_or(Error::HandshakeOutOfSequence {
548 state: self.state.name(),
549 reason: "no role was resolved before the Attention state",
550 })?;
551 if hp.handshake_type == HandshakeType::Conclusion {
552 return self.on_attention_conclusion(hp, role);
553 }
554 if hp.handshake_type == HandshakeType::Wavehand {
555 return Ok(self.resend());
556 }
557 Ok(self.reject(RejectionReason::Rogue))
558 }
559
560 /// The Attention row's CONCLUSION-handling logic (§4.3.2.2, L2307-2320
561 /// Initiator / L2343-2364 Responder), shared between a genuine
562 /// [`RendezvousHandshakeState::Attention`] and the Serial-flow crossing
563 /// case fed straight from [`RendezvousHandshakeState::Waving`].
564 fn on_attention_conclusion(
565 &mut self,
566 hp: &HandshakePacket<'_>,
567 role: RendezvousRole,
568 ) -> Result<Vec<HandshakeOutput>> {
569 self.peer_socket_id = hp.srt_socket_id;
570 let ext = match parse_peer_hs_ext(hp) {
571 Ok(e) => e,
572 Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
573 };
574 match (role, ext) {
575 (RendezvousRole::Initiator, PeerHsExt::None) => {
576 // L2312-2318: no extensions -> Initiated, still send
577 // CONCLUSION+HSREQ.
578 self.state = RendezvousHandshakeState::Initiated;
579 self.send_conclusion(Some(ExtensionType::HsReq))
580 }
581 (RendezvousRole::Initiator, PeerHsExt::HsRsp(msg)) => {
582 // L2318-2320: contains HSRSP -> Connected, send AGREEMENT.
583 self.peer_hs_msg = Some(msg);
584 self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
585 self.enter_connected()
586 }
587 (RendezvousRole::Responder, PeerHsExt::None) => {
588 // L2357-2360: no extensions yet -> resend the empty
589 // CONCLUSION, remain in Attention.
590 self.state = RendezvousHandshakeState::Attention;
591 self.send_conclusion(None)
592 }
593 (RendezvousRole::Responder, PeerHsExt::HsReq(msg)) => {
594 // L2360-2364: HSREQ present -> Initiated, send
595 // CONCLUSION+HSRSP.
596 self.peer_hs_msg = Some(msg);
597 self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
598 self.state = RendezvousHandshakeState::Initiated;
599 self.send_conclusion(Some(ExtensionType::HsRsp))
600 }
601 // A peer sending the extension kind only its own role should ever
602 // send (HSREQ into an Initiator, HSRSP into a Responder) is not a
603 // transition either table defines — reject rather than guess.
604 _ => Ok(self.reject(RejectionReason::Rogue)),
605 }
606 }
607
608 /// [`RendezvousHandshakeState::Initiated`] (§4.3.2.2, L2321-2334 Initiator
609 /// / L2365-2382 Responder), including the idempotent-resend recovery
610 /// rules (L2383-2422).
611 fn on_initiated(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
612 let role = self.role.ok_or(Error::HandshakeOutOfSequence {
613 state: self.state.name(),
614 reason: "no role was resolved before the Initiated state",
615 })?;
616 match role {
617 RendezvousRole::Initiator => {
618 if hp.handshake_type != HandshakeType::Conclusion {
619 return Ok(self.reject(RejectionReason::Rogue));
620 }
621 let ext = match parse_peer_hs_ext(hp) {
622 Ok(e) => e,
623 Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
624 };
625 match ext {
626 // L2325: "REMAINS IN THIS STATE" — still resend
627 // CONCLUSION+HSREQ.
628 PeerHsExt::None => self.send_conclusion(Some(ExtensionType::HsReq)),
629 // L2325-2334ish: contains HSRSP -> Connected, AGREEMENT.
630 PeerHsExt::HsRsp(msg) => {
631 self.peer_hs_msg = Some(msg);
632 self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
633 self.enter_connected()
634 }
635 PeerHsExt::HsReq(_) => Ok(self.reject(RejectionReason::Rogue)),
636 }
637 }
638 RendezvousRole::Responder => {
639 if hp.handshake_type == HandshakeType::Agreement {
640 // Responder Initiated row: AGREEMENT -> respond AGREEMENT,
641 // switch to Connected.
642 return self.enter_connected();
643 }
644 if hp.handshake_type != HandshakeType::Conclusion {
645 return Ok(self.reject(RejectionReason::Rogue));
646 }
647 let ext = match parse_peer_hs_ext(hp) {
648 Ok(e) => e,
649 Err(_) => return Ok(self.reject(RejectionReason::Rogue)),
650 };
651 match ext {
652 // Recovery rule 2 (L2391-2395): MUST always resend HSRSP,
653 // even if this HSREQ was already seen and processed once.
654 PeerHsExt::HsReq(msg) => {
655 self.peer_hs_msg = Some(msg);
656 self.peer_limits = Some((hp.mtu, hp.max_flow_window_size));
657 self.send_conclusion(Some(ExtensionType::HsRsp))
658 }
659 _ => Ok(self.reject(RejectionReason::Rogue)),
660 }
661 }
662 }
663 }
664
665 /// [`RendezvousHandshakeState::Connected`] (Initiator row item 4,
666 /// L2331-2334; Responder row item 4, L2377-2381): normally no more
667 /// handshake traffic, but a repeated CONCLUSION is answered with another
668 /// AGREEMENT (recovery rule 4, L2424-2432, from the other side's point of
669 /// view); anything else is disregarded rather than regressing a completed
670 /// handshake.
671 fn on_connected(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
672 if hp.handshake_type == HandshakeType::Conclusion {
673 return self.send_agreement();
674 }
675 Ok(Vec::new())
676 }
677
678 /// The cookie contest (§4.3.2, L2107-2135). Identical cookies are a
679 /// collision the draft says must not connect (L2119-2124) — surfaced by
680 /// the caller as [`RejectionReason::RdvCookie`].
681 ///
682 /// The draft's prose ("cookie value is greater than its peer's") reads
683 /// like a plain unsigned comparison, but a cookie is derived from a hash
684 /// (`derive_cookie`) and is effectively a uniformly random 32-bit value
685 /// — a plain `own_cookie > peer_cookie` unsigned compare gives the wrong
686 /// answer for roughly a quarter of all cookie pairs relative to a real
687 /// libsrt peer (whose own comparison is signed, not unsigned), which
688 /// shows up as an intermittent rendezvous failure against libsrt with no
689 /// pattern visible from either side alone (issue #1064). Ported from
690 /// libsrt's own tie-break (`srtcore/core.cpp`,
691 /// `CUDT::backwardCompatibleCookieContest`, v1.5.5): see
692 /// [`cookie_contest`].
693 fn resolve_role(&self, peer_cookie: u32) -> Result<RendezvousRole> {
694 if peer_cookie == self.own_cookie {
695 return Err(Error::InvalidField {
696 what: "rendezvous cookie",
697 reason: "identical to the peer's cookie (collision, L2119-2124)",
698 });
699 }
700 Ok(cookie_contest(self.own_cookie, peer_cookie))
701 }
702
703 fn reject(&mut self, reason: RejectionReason) -> Vec<HandshakeOutput> {
704 self.state = RendezvousHandshakeState::Rejected;
705 vec![HandshakeOutput::Rejected(reason)]
706 }
707
708 fn resend(&mut self) -> Vec<HandshakeOutput> {
709 match &self.last_sent {
710 Some(bytes) => vec![HandshakeOutput::Send(bytes.clone())],
711 None => Vec::new(),
712 }
713 }
714
715 /// Builds and sends a CONCLUSION: `ext_type` picks HSREQ/HSRSP, or `None`
716 /// for the extension-less greeting (§4.3.2.2, L2286-2288: no Stream ID /
717 /// Group Membership is ever attached — see module docs).
718 fn send_conclusion(&mut self, ext_type: Option<ExtensionType>) -> Result<Vec<HandshakeOutput>> {
719 let (ext_bytes, ext_flags): (Vec<u8>, u16) = match ext_type {
720 None => (Vec::new(), 0),
721 Some(t) => {
722 let hs_msg = HsExtMessage {
723 srt_version: self.config.srt_version,
724 srt_flags: self.config.flags,
725 receiver_tsbpd_delay_ms: self.config.latency_ms,
726 sender_tsbpd_delay_ms: self.config.latency_ms,
727 };
728 handshake_sm::build_conclusion_extensions(t, &hs_msg, None, None)?
729 }
730 };
731 let hp = HandshakePacket {
732 timestamp: 0,
733 dest_socket_id: self.peer_socket_id,
734 version: HANDSHAKE_VERSION_5,
735 encryption_field: self.config.encryption_field,
736 extension_field: HandshakeExtensionFlags(ext_flags),
737 initial_seq_number: self.config.initial_seq_number,
738 mtu: self.config.mtu,
739 max_flow_window_size: self.config.max_flow_window_size,
740 handshake_type: HandshakeType::Conclusion,
741 srt_socket_id: self.own_socket_id,
742 syn_cookie: self.own_cookie,
743 peer_ip: self.config.local_ip,
744 extensions: HandshakeExtensions(&ext_bytes),
745 };
746 let bytes = handshake_sm::build_bytes(hp)?;
747 self.last_sent = Some(bytes.clone());
748 self.ticks_since_send = 0;
749 self.retries = 0;
750 Ok(vec![HandshakeOutput::Send(bytes)])
751 }
752
753 /// Builds and sends an AGREEMENT: no extensions (§4.3.2.1, L2224-2230).
754 fn send_agreement(&mut self) -> Result<Vec<HandshakeOutput>> {
755 let hp = HandshakePacket {
756 timestamp: 0,
757 dest_socket_id: self.peer_socket_id,
758 version: HANDSHAKE_VERSION_5,
759 encryption_field: EncryptionField::NoEncryption,
760 extension_field: HandshakeExtensionFlags(0),
761 initial_seq_number: self.config.initial_seq_number,
762 mtu: self.config.mtu,
763 max_flow_window_size: self.config.max_flow_window_size,
764 handshake_type: HandshakeType::Agreement,
765 srt_socket_id: self.own_socket_id,
766 syn_cookie: self.own_cookie,
767 peer_ip: self.config.local_ip,
768 extensions: HandshakeExtensions(&[]),
769 };
770 let bytes = handshake_sm::build_bytes(hp)?;
771 self.last_sent = Some(bytes.clone());
772 self.ticks_since_send = 0;
773 self.retries = 0;
774 Ok(vec![HandshakeOutput::Send(bytes)])
775 }
776
777 /// Reaches [`RendezvousHandshakeState::Connected`]: builds
778 /// [`NegotiatedParams`] from `self.peer_hs_msg` (always captured by every
779 /// caller of this method before it is called) and sends the AGREEMENT
780 /// every documented transition into Connected requires.
781 fn enter_connected(&mut self) -> Result<Vec<HandshakeOutput>> {
782 let negotiated = self.build_negotiated()?;
783 self.negotiated = Some(negotiated.clone());
784 self.state = RendezvousHandshakeState::Connected;
785 let mut out = self.send_agreement()?;
786 out.push(HandshakeOutput::Connected(negotiated));
787 Ok(out)
788 }
789
790 fn build_negotiated(&self) -> Result<NegotiatedParams> {
791 let (Some(peer_msg), Some((peer_mtu, peer_mfw))) = (self.peer_hs_msg, self.peer_limits)
792 else {
793 return Err(Error::HandshakeOutOfSequence {
794 state: self.state.name(),
795 reason: "reached Connected without the peer's Handshake Extension Message",
796 });
797 };
798 Ok(NegotiatedParams {
799 version: HANDSHAKE_VERSION_5,
800 flags: HandshakeExtensionMessageFlags(self.config.flags.0 & peer_msg.srt_flags.0),
801 latency_ms: handshake_sm::negotiate_latency_ms(self.config.latency_ms, &peer_msg),
802 own_socket_id: self.own_socket_id,
803 peer_socket_id: self.peer_socket_id,
804 mtu: self.config.mtu.min(peer_mtu),
805 max_flow_window_size: self.config.max_flow_window_size.min(peer_mfw),
806 // §4.3.2 never mentions a Stream ID / Group Membership exchange —
807 // module docs "Resolved ambiguities". The same applies to §6.1.5
808 // Key Material Exchange: this engine does not implement it (see
809 // the crate root docs' explicit-follow-ups list), so encryption
810 // is never negotiated over Rendezvous.
811 stream_id: None,
812 group: None,
813 #[cfg(feature = "crypto")]
814 sek: None,
815 #[cfg(feature = "crypto")]
816 salt: None,
817 })
818 }
819}
820
821#[cfg(test)]
822mod tests {
823 use super::*;
824 use crate::packet::handshake::HS_EXT_FLAG_HSREQ;
825
826 #[test]
827 fn start_is_idempotent_guard() {
828 let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
829 assert!(r.start().is_ok());
830 assert!(r.start().is_err());
831 }
832
833 #[test]
834 fn wavehand_wire_values_match_draft_4_3_2() {
835 let mut r = RendezvousHandshake::new(0xAAAA_BBBB, 0xC0FF_EE00, HandshakeConfig::default());
836 let bytes = r.start().unwrap();
837 let pkt = ControlPacket::parse(&bytes).unwrap();
838 match pkt {
839 ControlPacket::Handshake(hp) => {
840 assert_eq!(hp.version, HANDSHAKE_VERSION_5);
841 assert_eq!(hp.handshake_type, HandshakeType::Wavehand);
842 assert_eq!(hp.srt_socket_id, 0xAAAA_BBBB);
843 assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
844 assert_eq!(hp.extension_field.0, 0);
845 }
846 _ => panic!("expected handshake"),
847 }
848 assert_eq!(r.state(), RendezvousHandshakeState::Waving);
849 }
850
851 fn wavehand(socket_id: u32, cookie: u32) -> ControlPacket<'static> {
852 ControlPacket::Handshake(HandshakePacket {
853 timestamp: 0,
854 dest_socket_id: 0,
855 version: HANDSHAKE_VERSION_5,
856 encryption_field: EncryptionField::NoEncryption,
857 extension_field: HandshakeExtensionFlags(0),
858 initial_seq_number: 0,
859 mtu: 1500,
860 max_flow_window_size: 8192,
861 handshake_type: HandshakeType::Wavehand,
862 srt_socket_id: socket_id,
863 syn_cookie: cookie,
864 peer_ip: [0; 4],
865 extensions: HandshakeExtensions(&[]),
866 })
867 }
868
869 #[test]
870 fn greater_cookie_wins_initiator() {
871 let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
872 let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
873 a.start().unwrap();
874 b.start().unwrap();
875
876 a.feed(&wavehand(2, 100)).unwrap();
877 b.feed(&wavehand(1, 500)).unwrap();
878
879 assert_eq!(a.role(), Some(RendezvousRole::Initiator));
880 assert_eq!(b.role(), Some(RendezvousRole::Responder));
881 assert_eq!(a.state(), RendezvousHandshakeState::Attention);
882 assert_eq!(b.state(), RendezvousHandshakeState::Attention);
883 }
884
885 /// Sign-boundary cookie-contest table (issue #1064). Every case here
886 /// pins `cookie_contest`'s result against the libsrt algorithm it ports
887 /// — hand-traced from `CUDT::backwardCompatibleCookieContest`, not
888 /// re-derived from this crate's own implementation (the point is
889 /// catching a misport, not just re-checking `contest > 0`).
890 ///
891 /// A plain unsigned `own_cookie > peer_cookie` compare (this function's
892 /// pre-#1064 behavior) gives the OPPOSITE answer to several of these —
893 /// marked below — because it doesn't reinterpret either cookie as
894 /// signed before comparing.
895 #[test]
896 fn cookie_contest_sign_boundary_table() {
897 let cases: &[(u32, u32, RendezvousRole, &str)] = &[
898 // Both positive as i32 (top bit clear): signed and unsigned
899 // agree — the ordinary case.
900 (
901 500,
902 100,
903 RendezvousRole::Initiator,
904 "both positive, own > peer",
905 ),
906 (
907 100,
908 500,
909 RendezvousRole::Responder,
910 "both positive, own < peer",
911 ),
912 // Exactly one cookie has the top bit set: signed and unsigned
913 // DISAGREE. libsrt's signed compare makes the negative
914 // (top-bit-set) one lose regardless of its unsigned magnitude.
915 (
916 0xAAAA_0002,
917 0x1111_0001,
918 RendezvousRole::Responder,
919 "own top-bit-set (negative), peer positive — unsigned would say Initiator",
920 ),
921 (
922 0x1111_0001,
923 0xAAAA_0002,
924 RendezvousRole::Initiator,
925 "own positive, peer top-bit-set (negative) — unsigned would say Responder",
926 ),
927 // Both top-bit-set (both negative as i32): signed compare among
928 // two negatives, still needs to agree with libsrt, not just
929 // "unsigned compare of the raw bit pattern" (which happens to
930 // still hold here since the *relative* order of two same-signed
931 // values is the same either way — included as a same-sign
932 // sanity check, not a disagreement case).
933 (
934 0xFFFF_FFFF,
935 0x8000_0000,
936 RendezvousRole::Initiator,
937 "both negative, own > peer",
938 ),
939 (
940 0x8000_0000,
941 0xFFFF_FFFF,
942 RendezvousRole::Responder,
943 "both negative, own < peer",
944 ),
945 // The exact halfway point (`own - peer == i32::MIN`, `0x8000_0000`
946 // as the wrapping 32-bit difference): libsrt's own tie-break for
947 // this specific case falls back to a raw signed `req > res`
948 // comparison of the two cookies themselves (see `cookie_contest`'s
949 // doc) rather than the contest direction.
950 (
951 0x8000_0000,
952 0,
953 RendezvousRole::Responder,
954 "halfway point, own negative vs peer zero: raw signed own(<0) > peer(0) is false",
955 ),
956 (
957 0,
958 0x8000_0000,
959 RendezvousRole::Initiator,
960 "halfway point, own zero vs peer negative: raw signed own(0) > peer(<0) is true",
961 ),
962 ];
963 for &(own, peer, expected, why) in cases {
964 let got = cookie_contest(own, peer);
965 assert_eq!(
966 got, expected,
967 "own={own:#010x} peer={peer:#010x}: expected {expected:?}, got {got:?} ({why})"
968 );
969 }
970 }
971
972 #[test]
973 fn identical_cookies_are_rejected_as_a_collision() {
974 let mut a = RendezvousHandshake::new(1, 0x00C0_FFEE, HandshakeConfig::default());
975 a.start().unwrap();
976 let outputs = a.feed(&wavehand(2, 0x00C0_FFEE)).unwrap();
977 assert_eq!(
978 outputs,
979 vec![HandshakeOutput::Rejected(RejectionReason::RdvCookie)]
980 );
981 assert_eq!(a.state(), RendezvousHandshakeState::Rejected);
982 }
983
984 #[test]
985 fn initiator_attention_entry_sends_hsreq() {
986 let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
987 a.start().unwrap();
988 let outputs = a.feed(&wavehand(2, 100)).unwrap();
989 assert_eq!(outputs.len(), 1);
990 let bytes = match &outputs[0] {
991 HandshakeOutput::Send(b) => b.clone(),
992 other => panic!("expected Send, got {other:?}"),
993 };
994 let pkt = ControlPacket::parse(&bytes).unwrap();
995 match pkt {
996 ControlPacket::Handshake(hp) => {
997 assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
998 assert_eq!(hp.extension_field.0 & HS_EXT_FLAG_HSREQ, HS_EXT_FLAG_HSREQ);
999 let blocks: Vec<_> = hp.extensions.iter().map(|b| b.unwrap()).collect();
1000 assert_eq!(blocks.len(), 1);
1001 assert_eq!(blocks[0].ext_type, ExtensionType::HsReq);
1002 }
1003 _ => panic!("expected handshake"),
1004 }
1005 }
1006
1007 #[test]
1008 fn responder_attention_entry_sends_empty_conclusion() {
1009 let mut b = RendezvousHandshake::new(2, 100, HandshakeConfig::default());
1010 b.start().unwrap();
1011 let outputs = b.feed(&wavehand(1, 500)).unwrap();
1012 assert_eq!(outputs.len(), 1);
1013 let bytes = match &outputs[0] {
1014 HandshakeOutput::Send(b) => b.clone(),
1015 other => panic!("expected Send, got {other:?}"),
1016 };
1017 let pkt = ControlPacket::parse(&bytes).unwrap();
1018 match pkt {
1019 ControlPacket::Handshake(hp) => {
1020 assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
1021 assert_eq!(hp.extension_field.0, 0);
1022 assert_eq!(hp.extensions.iter().count(), 0);
1023 }
1024 _ => panic!("expected handshake"),
1025 }
1026 }
1027
1028 #[test]
1029 fn malformed_extension_mid_flow_is_rejected_not_panicking() {
1030 let mut a = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1031 a.start().unwrap();
1032 a.feed(&wavehand(2, 100)).unwrap();
1033 assert_eq!(a.state(), RendezvousHandshakeState::Attention);
1034
1035 // A CONCLUSION whose extension block declares a length far larger
1036 // than the bytes actually present.
1037 let bad_ext: &'static [u8] = &[0x00, 0x01, 0xFF, 0xFF];
1038 let bad = ControlPacket::Handshake(HandshakePacket {
1039 timestamp: 0,
1040 dest_socket_id: 1,
1041 version: HANDSHAKE_VERSION_5,
1042 encryption_field: EncryptionField::NoEncryption,
1043 extension_field: HandshakeExtensionFlags(HS_EXT_FLAG_HSREQ),
1044 initial_seq_number: 0,
1045 mtu: 1500,
1046 max_flow_window_size: 8192,
1047 handshake_type: HandshakeType::Conclusion,
1048 srt_socket_id: 2,
1049 syn_cookie: 100,
1050 peer_ip: [0; 4],
1051 extensions: HandshakeExtensions(bad_ext),
1052 });
1053 let outputs = a.feed(&bad).unwrap();
1054 assert_eq!(
1055 outputs,
1056 vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]
1057 );
1058 assert_eq!(a.state(), RendezvousHandshakeState::Rejected);
1059 }
1060
1061 #[test]
1062 fn feed_before_start_is_out_of_sequence() {
1063 let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1064 assert!(matches!(
1065 r.feed(&wavehand(2, 100)),
1066 Err(Error::HandshakeOutOfSequence { .. })
1067 ));
1068 }
1069
1070 #[test]
1071 fn feed_rejects_non_handshake_packets_outside_recovery_case() {
1072 use crate::packet::misc::KeepAlivePacket;
1073 let mut r = RendezvousHandshake::new(1, 500, HandshakeConfig::default());
1074 r.start().unwrap();
1075 let ka = ControlPacket::KeepAlive(KeepAlivePacket {
1076 timestamp: 0,
1077 dest_socket_id: 0,
1078 libsrt_pad: false,
1079 });
1080 assert!(matches!(
1081 r.feed(&ka),
1082 Err(Error::UnexpectedControlPacket { .. })
1083 ));
1084 }
1085
1086 /// The state machine's internal invariants (a role is resolved before
1087 /// Attention/Initiated, the peer's HSREQ/HSRSP is known before Connected)
1088 /// are errors, not panics, if ever violated.
1089 #[test]
1090 fn broken_internal_invariants_are_errors_not_panics() {
1091 use crate::packet::{EncryptionField, HandshakeExtensionFlags, HandshakeExtensions};
1092 let hp = HandshakePacket {
1093 timestamp: 0,
1094 dest_socket_id: 1,
1095 version: 5,
1096 encryption_field: EncryptionField::NoEncryption,
1097 extension_field: HandshakeExtensionFlags(0),
1098 initial_seq_number: 0,
1099 mtu: 1500,
1100 max_flow_window_size: 8192,
1101 handshake_type: HandshakeType::Conclusion,
1102 srt_socket_id: 2,
1103 syn_cookie: 0,
1104 peer_ip: [0; 4],
1105 extensions: HandshakeExtensions(&[]),
1106 };
1107 let mut r = RendezvousHandshake::new(1, 5, HandshakeConfig::default());
1108 assert!(matches!(
1109 r.on_attention(&hp),
1110 Err(Error::HandshakeOutOfSequence { .. })
1111 ));
1112 assert!(matches!(
1113 r.on_initiated(&hp),
1114 Err(Error::HandshakeOutOfSequence { .. })
1115 ));
1116 assert!(matches!(
1117 r.enter_connected(),
1118 Err(Error::HandshakeOutOfSequence { .. })
1119 ));
1120 }
1121}