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