Skip to main content

srt_runtime/
handshake_sm.rs

1//! Shared types for the sans-IO HSv5 handshake state machine —
2//! `draft-sharabayko-srt-01` §4.3 (Handshake Messages) / §4.3.1
3//! (Caller-Listener Handshake).
4//!
5//! This module holds the pieces [`crate::caller::CallerHandshake`] and
6//! [`crate::listener::ListenerHandshake`] share: the negotiation input
7//! ([`HandshakeConfig`]), the negotiation output ([`NegotiatedParams`]), the
8//! event type both engines emit ([`HandshakeOutput`]), and the Handshake
9//! Rejection Reason codes (§4.3, Table 7) as a typed [`RejectionReason`].
10//!
11//! This module also holds the `crypto`-feature-gated §6.1.5 Key Material
12//! Exchange helpers ([`CryptoConfig`], `build_key_material_extension`,
13//! `recover_sek`, `verify_km_echo`) shared
14//! by [`crate::caller::CallerHandshake`] / [`crate::listener::ListenerHandshake`]
15//! — see [`CryptoConfig`]'s doc and `private/specs-verified/rules/srt-crypto.md`. Congestion
16//! control beyond LiveCC packet pacing is an explicit follow-up — see the
17//! crate root docs.
18
19#[cfg(feature = "crypto")]
20use alloc::borrow::Cow;
21use alloc::string::String;
22use alloc::vec;
23use alloc::vec::Vec;
24use broadcast_core::error::InvalidField;
25use core::time::Duration;
26#[cfg(feature = "crypto")]
27use subtle::ConstantTimeEq;
28#[cfg(feature = "crypto")]
29use zeroize::Zeroize;
30
31use crate::error::{Error, Result};
32#[cfg(feature = "crypto")]
33use crate::packet::KeyMaterial;
34use crate::packet::handshake::{HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_HSREQ};
35#[cfg(feature = "crypto")]
36use crate::packet::{Cipher, KmAuth, KmKeyFlag, StreamEncapsulation};
37use crate::packet::{
38    ControlPacket, EncryptionField, GroupMembershipExtension, HandshakeExtensionBlock,
39    HandshakeExtensionMessageFlags, HandshakeExtensions, HandshakePacket, HandshakeType,
40    HsExtMessage,
41};
42
43/// A base protocol version number of `4` — the value the Caller's INDUCTION
44/// handshake MUST always carry (`draft-sharabayko-srt-01` §4.3.1.1), kept for
45/// UDT compatibility.
46pub const HANDSHAKE_VERSION_4: u32 = 4;
47/// A base protocol version number of `5` — HSv5, used by every handshake
48/// message from the Listener's INDUCTION response onward (§4.3.1.1/§4.3.1.2).
49pub const HANDSHAKE_VERSION_5: u32 = 5;
50
51/// The `Extension Field` value the Listener echoes on its INDUCTION response
52/// so the Caller can recognise it as an SRT (not legacy UDT) party
53/// (`draft-sharabayko-srt-01` §4.3.1.1: "SRT magic code 0x4A17").
54pub const SRT_MAGIC_CODE: u16 = 0x4A17;
55
56/// The `Extension Field` value the Caller sets on its very first INDUCTION
57/// handshake (§4.3.1.1: "Extension Field: 2"). This is *not* the §3.2.1
58/// Table 3 `Extension Flags` bitmask (whose `KMREQ` bit happens to share the
59/// same numeric value) — it is a legacy UDT socket-type field (`UDT_DGRAM`)
60/// carried over because the INDUCTION handshake is version-4-shaped for UDT
61/// compatibility.
62pub const INDUCTION_LEGACY_SOCKET_TYPE: u16 = 2;
63
64/// The base wire value of the Handshake Rejection Reason codes
65/// (`draft-sharabayko-srt-01` §4.3, Table 7): a rejected connection's
66/// `Handshake Type` field carries `1000 + <code>`.
67pub const REJECTION_CODE_BASE: u32 = 1000;
68
69/// One past the largest `Handshake Type` value read as a rejection: libsrt's
70/// request type is a signed 32-bit integer, so everything from `2^31` up is
71/// the negative `URQ_*` range, never a rejection reason (see
72/// [`RejectionReason::from_handshake_type`]).
73pub const REJECTION_CODE_LIMIT: u32 = 0x8000_0000;
74
75/// Handshake Rejection Reason (`draft-sharabayko-srt-01` §4.3, Table 7). Sent
76/// in place of a normal `Handshake Type` value (`1000 + code`, decoded via
77/// [`HandshakeType::Reserved`]) when a connection attempt is refused.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79#[cfg_attr(feature = "serde", derive(serde::Serialize))]
80#[non_exhaustive]
81pub enum RejectionReason {
82    /// `1000`: unknown reason.
83    Unknown,
84    /// `1001`: system function error.
85    System,
86    /// `1002`: rejected by peer.
87    Peer,
88    /// `1003`: resource allocation problem.
89    Resource,
90    /// `1004`: incorrect data in handshake.
91    Rogue,
92    /// `1005`: listener's backlog exceeded.
93    Backlog,
94    /// `1006`: internal program error.
95    Ipe,
96    /// `1007`: socket is closing.
97    Close,
98    /// `1008`: peer is an older version than the agent's minimum.
99    Version,
100    /// `1009`: rendezvous cookie collision.
101    RdvCookie,
102    /// `1010`: wrong password.
103    BadSecret,
104    /// `1011`: password required or unexpected.
105    Unsecure,
106    /// `1012`: stream flag collision.
107    MessageApi,
108    /// `1013`: incompatible congestion-controller type.
109    Congestion,
110    /// `1014`: incompatible packet filter.
111    Filter,
112    /// `1015`: incompatible group.
113    Group,
114    /// A `1000 + code` value Table 7 does not define.
115    Reserved(u32),
116}
117
118impl RejectionReason {
119    /// Decode a Table 7 wire code (the value carried in `Handshake Type`,
120    /// i.e. already `1000 + code`).
121    pub fn from_bits(v: u32) -> Self {
122        match v {
123            1000 => RejectionReason::Unknown,
124            1001 => RejectionReason::System,
125            1002 => RejectionReason::Peer,
126            1003 => RejectionReason::Resource,
127            1004 => RejectionReason::Rogue,
128            1005 => RejectionReason::Backlog,
129            1006 => RejectionReason::Ipe,
130            1007 => RejectionReason::Close,
131            1008 => RejectionReason::Version,
132            1009 => RejectionReason::RdvCookie,
133            1010 => RejectionReason::BadSecret,
134            1011 => RejectionReason::Unsecure,
135            1012 => RejectionReason::MessageApi,
136            1013 => RejectionReason::Congestion,
137            1014 => RejectionReason::Filter,
138            1015 => RejectionReason::Group,
139            other => RejectionReason::Reserved(other),
140        }
141    }
142
143    /// The wire code (`1000 + code`), as carried in `Handshake Type`.
144    pub fn to_bits(self) -> u32 {
145        match self {
146            RejectionReason::Unknown => 1000,
147            RejectionReason::System => 1001,
148            RejectionReason::Peer => 1002,
149            RejectionReason::Resource => 1003,
150            RejectionReason::Rogue => 1004,
151            RejectionReason::Backlog => 1005,
152            RejectionReason::Ipe => 1006,
153            RejectionReason::Close => 1007,
154            RejectionReason::Version => 1008,
155            RejectionReason::RdvCookie => 1009,
156            RejectionReason::BadSecret => 1010,
157            RejectionReason::Unsecure => 1011,
158            RejectionReason::MessageApi => 1012,
159            RejectionReason::Congestion => 1013,
160            RejectionReason::Filter => 1014,
161            RejectionReason::Group => 1015,
162            RejectionReason::Reserved(v) => v,
163        }
164    }
165
166    /// Spec label (Table 7).
167    pub fn name(&self) -> &'static str {
168        match self {
169            RejectionReason::Unknown => "REJ_UNKNOWN",
170            RejectionReason::System => "REJ_SYSTEM",
171            RejectionReason::Peer => "REJ_PEER",
172            RejectionReason::Resource => "REJ_RESOURCE",
173            RejectionReason::Rogue => "REJ_ROGUE",
174            RejectionReason::Backlog => "REJ_BACKLOG",
175            RejectionReason::Ipe => "REJ_IPE",
176            RejectionReason::Close => "REJ_CLOSE",
177            RejectionReason::Version => "REJ_VERSION",
178            RejectionReason::RdvCookie => "REJ_RDVCOOKIE",
179            RejectionReason::BadSecret => "REJ_BADSECRET",
180            RejectionReason::Unsecure => "REJ_UNSECURE",
181            RejectionReason::MessageApi => "REJ_MESSAGEAPI",
182            RejectionReason::Congestion => "REJ_CONGESTION",
183            RejectionReason::Filter => "REJ_FILTER",
184            RejectionReason::Group => "REJ_GROUP",
185            RejectionReason::Reserved(_) => "reserved",
186        }
187    }
188
189    /// Recover the [`RejectionReason`] a peer sent back as a `Handshake
190    /// Type`, or `None` if `ht` is a normal (non-rejection) handshake type.
191    ///
192    /// Only `1000..`[`REJECTION_CODE_LIMIT`] is a rejection: libsrt carries the
193    /// handshake request type as a *signed* 32-bit integer whose negative
194    /// values (the `URQ_*` family, e.g. `CONCLUSION` = -1 = `0xFFFF_FFFF`)
195    /// are handshake types, not reasons, so an undefined value such as
196    /// `0xFFFF_FFFC` is not a rejection.
197    pub fn from_handshake_type(ht: HandshakeType) -> Option<Self> {
198        match ht {
199            HandshakeType::Reserved(v)
200                if (REJECTION_CODE_BASE..REJECTION_CODE_LIMIT).contains(&v) =>
201            {
202                Some(RejectionReason::from_bits(v))
203            }
204            _ => None,
205        }
206    }
207
208    /// Encode as the `Handshake Type` value a rejection packet carries.
209    pub fn to_handshake_type(self) -> HandshakeType {
210        HandshakeType::from_bits(self.to_bits())
211    }
212}
213
214broadcast_core::impl_spec_display!(RejectionReason, Reserved);
215
216/// Opt-in §6 payload-encryption config for one side of a Caller-Listener
217/// handshake (`draft-sharabayko-srt-01` §6.1.5, Key Material Exchange —
218/// curated at `private/specs-verified/rules/srt-crypto.md`). `None` on
219/// [`HandshakeConfig::crypto`] (the default) disables the encryption path
220/// entirely: no Key Material extension is sent, and a peer that sends one
221/// unexpectedly is rejected ([`RejectionReason::Unsecure`]).
222///
223/// This crate's sans-IO core never reads OS randomness — the same design
224/// choice as `cookie::derive_cookie`'s caller-supplied `time_bucket`/`secret`
225/// inputs, or [`crate::io`]'s OS-random SYN Cookie key.
226/// [`Self::salt`] and, on the initiator, [`Self::sek`] must be freshly
227/// generated by the caller/driver (e.g. a `tokio` adapter with access to a
228/// real CSPRNG) for **every new connection** (§6.2.1: `Salt = PRNG(128)`,
229/// `SEK = PRNG(KLen)`) and never reused across connections.
230///
231/// # Secret hygiene (issue #1142)
232/// The passphrase and SEK never appear in [`core::fmt::Debug`] output (it
233/// prints only their lengths), [`PartialEq`] compares them in constant time,
234/// and dropping a `CryptoConfig` (or calling [`Zeroize::zeroize`]) wipes them.
235#[cfg(feature = "crypto")]
236#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
237#[derive(Clone)]
238#[non_exhaustive]
239pub struct CryptoConfig {
240    /// The pre-shared secret (§6.1.4). Must be identical on both peers, or
241    /// the responder's KEK derivation recovers the wrong SEK and the RFC
242    /// 3394 wrap's integrity check fails
243    /// ([`RejectionReason::BadSecret`] on the Listener side).
244    pub passphrase: Vec<u8>,
245    /// A fresh, cryptographically random 128-bit Salt for **this
246    /// connection** (§6.2.1: `Salt = PRNG(128)`). See the struct doc for why
247    /// this crate does not generate it internally.
248    pub salt: [u8; crate::crypto::SALT_LEN],
249    /// This side's plaintext Stream Encrypting Key. **Only meaningful on the
250    /// connection initiator** (the Caller — §6.1.5: "sent by the connection
251    /// initiator ... to the responder"). Must be a fresh, cryptographically
252    /// random 16/24/32-byte value (§6.2.1: `SEK = PRNG(KLen)`) matching
253    /// [`HandshakeConfig::encryption_field`]'s advertised cipher. Ignored on
254    /// the Listener/responder side (which instead recovers the SEK by
255    /// unwrapping the initiator's Key Material) — may be left empty there.
256    pub sek: Vec<u8>,
257}
258
259#[cfg(feature = "crypto")]
260impl core::fmt::Debug for CryptoConfig {
261    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
262        f.debug_struct("CryptoConfig")
263            .field(
264                "passphrase",
265                &format_args!("<redacted, {} bytes>", self.passphrase.len()),
266            )
267            .field(
268                "salt",
269                &format_args!("<redacted, {} bytes>", self.salt.len()),
270            )
271            .field("sek", &format_args!("<redacted, {} bytes>", self.sek.len()))
272            .finish()
273    }
274}
275
276#[cfg(feature = "crypto")]
277impl PartialEq for CryptoConfig {
278    /// Constant-time in the secret contents (the lengths are not secret).
279    fn eq(&self, other: &Self) -> bool {
280        let passphrase = self
281            .passphrase
282            .as_slice()
283            .ct_eq(other.passphrase.as_slice());
284        let salt = self.salt.as_slice().ct_eq(other.salt.as_slice());
285        let sek = self.sek.as_slice().ct_eq(other.sek.as_slice());
286        bool::from(passphrase & salt & sek)
287    }
288}
289
290#[cfg(feature = "crypto")]
291impl Zeroize for CryptoConfig {
292    fn zeroize(&mut self) {
293        self.passphrase.zeroize();
294        self.salt.zeroize();
295        self.sek.zeroize();
296    }
297}
298
299#[cfg(feature = "crypto")]
300impl Drop for CryptoConfig {
301    fn drop(&mut self) {
302        self.zeroize();
303    }
304}
305
306#[cfg(feature = "crypto")]
307impl zeroize::ZeroizeOnDrop for CryptoConfig {}
308
309#[cfg(feature = "crypto")]
310impl CryptoConfig {
311    /// Build the crypto parameters for one connection's handshake (encryption
312    /// preamble §6.1). Every field is a secret or a per-connection nonce, so
313    /// there is no `Default`; the caller supplies all three.
314    #[must_use]
315    pub fn new(passphrase: Vec<u8>, salt: [u8; crate::crypto::SALT_LEN], sek: Vec<u8>) -> Self {
316        Self {
317            passphrase,
318            salt,
319            sek,
320        }
321    }
322}
323
324/// Secret key bytes — a negotiated Stream Encrypting Key.
325///
326/// Derefs to `&[u8]` for use with [`crate::crypto::aes_ctr_apply`], but is
327/// deliberately not a plain `Vec<u8>`: [`core::fmt::Debug`] prints only the
328/// length, serde never serializes it (it is skipped where it is a field),
329/// [`PartialEq`] is constant-time, and it is wiped when dropped (issue #1142).
330#[cfg(feature = "crypto")]
331#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
332#[derive(Clone)]
333pub struct SecretBytes(Vec<u8>);
334
335#[cfg(feature = "crypto")]
336impl SecretBytes {
337    /// Wrap `bytes`.
338    pub fn new(bytes: Vec<u8>) -> Self {
339        SecretBytes(bytes)
340    }
341}
342
343#[cfg(feature = "crypto")]
344impl From<Vec<u8>> for SecretBytes {
345    fn from(bytes: Vec<u8>) -> Self {
346        SecretBytes(bytes)
347    }
348}
349
350#[cfg(feature = "crypto")]
351impl core::ops::Deref for SecretBytes {
352    type Target = [u8];
353    fn deref(&self) -> &[u8] {
354        &self.0
355    }
356}
357
358#[cfg(feature = "crypto")]
359impl core::fmt::Debug for SecretBytes {
360    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
361        write!(f, "SecretBytes(<redacted, {} bytes>)", self.0.len())
362    }
363}
364
365#[cfg(feature = "crypto")]
366impl PartialEq for SecretBytes {
367    /// Constant-time in the contents (the length is not secret).
368    fn eq(&self, other: &Self) -> bool {
369        bool::from(self.0.as_slice().ct_eq(other.0.as_slice()))
370    }
371}
372
373#[cfg(feature = "crypto")]
374impl Eq for SecretBytes {}
375
376#[cfg(feature = "crypto")]
377impl Zeroize for SecretBytes {
378    fn zeroize(&mut self) {
379        self.0.zeroize();
380    }
381}
382
383#[cfg(feature = "crypto")]
384impl Drop for SecretBytes {
385    fn drop(&mut self) {
386        self.zeroize();
387    }
388}
389
390#[cfg(feature = "crypto")]
391impl zeroize::ZeroizeOnDrop for SecretBytes {}
392
393/// Local configuration for one side of a Caller-Listener handshake — the
394/// values *this* engine advertises (`draft-sharabayko-srt-01` §3.2.1,
395/// §3.2.1.1, §3.2.1.3, §3.2.1.4).
396#[derive(Debug, Clone, PartialEq)]
397#[non_exhaustive]
398pub struct HandshakeConfig {
399    /// TSBPD delay this side requests, sent as both the Receiver and Sender
400    /// TSBPD Delay of its Handshake Extension Message (§3.2.1.1, Figure 6),
401    /// in whole milliseconds on the wire. The negotiated value is the greater
402    /// of the two parties' requests (§4.3.1.2).
403    pub latency: Duration,
404    /// Maximum Transmission Unit Size (§3.2.1).
405    pub mtu: u32,
406    /// Maximum Flow Window Size (§3.2.1).
407    pub max_flow_window_size: u32,
408    /// Initial Packet Sequence Number this side will use for its first data
409    /// packet (§3.2.1). No data plane exists yet in this crate; callers of a
410    /// later data-plane PR are expected to set this to a real ISN.
411    pub initial_seq_number: u32,
412    /// The `SRT Version` this side reports in its Handshake Extension
413    /// Message (`major * 0x10000 + minor * 0x100 + patch`, §3.2.1.1).
414    pub srt_version: u32,
415    /// `SRT Flags` this side advertises (§3.2.1.1.1, Table 6).
416    pub flags: HandshakeExtensionMessageFlags,
417    /// Advertised cipher family and block size (§3.2.1, Table 2). Actual
418    /// key-wrap/unwrap crypto is an explicit follow-up; this field is
419    /// negotiated but not acted on in this release.
420    pub encryption_field: EncryptionField,
421    /// Stream ID to advertise (Caller only — §3.2.1.3); `None` sends no
422    /// Stream ID extension.
423    pub stream_id: Option<String>,
424    /// Group Membership to advertise (§3.2.1.4); `None` sends no Group
425    /// extension.
426    pub group: Option<GroupMembershipExtension>,
427    /// This side's own IP address, reported in every outgoing handshake
428    /// packet's `Peer IP Address` field (§3.2.1: "IPv4 or IPv6 address of
429    /// the packet's *sender*" — despite the field's name, each party reports
430    /// its own address, not its peer's).
431    pub local_ip: [u32; IPV4_ADDR_WORDS],
432    /// Longest silence from the peer before the last-sent handshake packet is
433    /// retransmitted: a [`crate::caller::CallerHandshake::tick`] /
434    /// [`crate::listener::ListenerHandshake::tick`] call is the caller's own
435    /// time step, and the engine resends once that much of it has passed with
436    /// no reply. No wall-clock lives in this crate.
437    pub retransmit_after: Duration,
438    /// Maximum number of retransmissions before the handshake gives up
439    /// ([`HandshakeOutput::TimedOut`]).
440    pub max_retries: u32,
441    /// Opt-in §6 payload-encryption negotiation (`crypto` feature only).
442    /// `None` (the default) means this side neither offers nor requires
443    /// encryption. See [`CryptoConfig`] for the caller-supplied Salt/SEK
444    /// contract.
445    #[cfg(feature = "crypto")]
446    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
447    pub crypto: Option<CryptoConfig>,
448}
449
450impl HandshakeConfig {
451    /// Sets [`latency`](Self::latency).
452    #[must_use]
453    pub fn with_latency(mut self, latency: Duration) -> Self {
454        self.latency = latency;
455        self
456    }
457
458    /// Sets [`mtu`](Self::mtu).
459    #[must_use]
460    pub fn with_mtu(mut self, mtu: u32) -> Self {
461        self.mtu = mtu;
462        self
463    }
464
465    /// Sets [`max_flow_window_size`](Self::max_flow_window_size).
466    #[must_use]
467    pub fn with_max_flow_window_size(mut self, max_flow_window_size: u32) -> Self {
468        self.max_flow_window_size = max_flow_window_size;
469        self
470    }
471
472    /// Sets [`initial_seq_number`](Self::initial_seq_number).
473    #[must_use]
474    pub fn with_initial_seq_number(mut self, initial_seq_number: u32) -> Self {
475        self.initial_seq_number = initial_seq_number;
476        self
477    }
478
479    /// Sets [`srt_version`](Self::srt_version).
480    #[must_use]
481    pub fn with_srt_version(mut self, srt_version: u32) -> Self {
482        self.srt_version = srt_version;
483        self
484    }
485
486    /// Sets [`flags`](Self::flags).
487    #[must_use]
488    pub fn with_flags(mut self, flags: HandshakeExtensionMessageFlags) -> Self {
489        self.flags = flags;
490        self
491    }
492
493    /// Sets [`encryption_field`](Self::encryption_field).
494    #[must_use]
495    pub fn with_encryption_field(mut self, encryption_field: EncryptionField) -> Self {
496        self.encryption_field = encryption_field;
497        self
498    }
499
500    /// Sets [`stream_id`](Self::stream_id).
501    #[must_use]
502    pub fn with_stream_id(mut self, stream_id: Option<String>) -> Self {
503        self.stream_id = stream_id;
504        self
505    }
506
507    /// Sets [`group`](Self::group).
508    #[must_use]
509    pub fn with_group(mut self, group: Option<GroupMembershipExtension>) -> Self {
510        self.group = group;
511        self
512    }
513
514    /// Sets [`local_ip`](Self::local_ip).
515    #[must_use]
516    pub fn with_local_ip(mut self, local_ip: [u32; IPV4_ADDR_WORDS]) -> Self {
517        self.local_ip = local_ip;
518        self
519    }
520
521    /// Sets [`retransmit_after`](Self::retransmit_after).
522    #[must_use]
523    pub fn with_retransmit_after(mut self, retransmit_after: Duration) -> Self {
524        self.retransmit_after = retransmit_after;
525        self
526    }
527
528    /// Sets [`max_retries`](Self::max_retries).
529    #[must_use]
530    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
531        self.max_retries = max_retries;
532        self
533    }
534
535    /// Sets [`crypto`](Self::crypto).
536    #[cfg(feature = "crypto")]
537    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
538    #[must_use]
539    pub fn with_crypto(mut self, crypto: Option<CryptoConfig>) -> Self {
540        self.crypto = crypto;
541        self
542    }
543}
544
545/// The `SRT Version` this crate announces in its Handshake Extension Message (§3.2.1.1,
546/// `major * 0x10000 + minor * 0x100 + patch`): 1.5.0, the protocol revision it implements.
547const SRT_VERSION: u32 = 0x0105_0000;
548
549/// Words in an IPv4 address as the handshake carries it (§3.2.1).
550pub const IPV4_ADDR_WORDS: usize = 4;
551
552impl HandshakeConfig {
553    /// A configuration advertising `latency`, `mtu` and `max_flow_window_size`, retransmitting
554    /// an unanswered handshake packet every `retransmit_after` and giving up after
555    /// `max_retries` retransmissions. Every number is the caller's: the crate supplies none.
556    /// The rest starts as this crate's feature set with no stream id, group or encryption.
557    #[must_use]
558    pub fn new(
559        latency: Duration,
560        mtu: u32,
561        max_flow_window_size: u32,
562        retransmit_after: Duration,
563        max_retries: u32,
564    ) -> Self {
565        HandshakeConfig {
566            latency,
567            mtu,
568            max_flow_window_size,
569            initial_seq_number: 0,
570            srt_version: SRT_VERSION,
571            flags: HandshakeExtensionMessageFlags::new(
572                crate::packet::handshake::HS_MSG_FLAG_TSBPDSND
573                    | crate::packet::handshake::HS_MSG_FLAG_TSBPDRCV
574                    | crate::packet::handshake::HS_MSG_FLAG_CRYPT
575                    | crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP
576                    | crate::packet::handshake::HS_MSG_FLAG_PERIODICNAK
577                    | crate::packet::handshake::HS_MSG_FLAG_REXMITFLG,
578            ),
579            encryption_field: EncryptionField::NoEncryption,
580            stream_id: None,
581            group: None,
582            local_ip: [0, 0, 0, 0],
583            retransmit_after,
584            max_retries,
585            #[cfg(feature = "crypto")]
586            crypto: None,
587        }
588    }
589}
590
591/// The outcome of a Caller-Listener handshake, once both TSBPD delays and
592/// flags have been reconciled per `draft-sharabayko-srt-01` §4.3.1.2 ("The
593/// value for latency is always agreed to be the greater of those reported by
594/// each party").
595#[derive(Debug, Clone, PartialEq)]
596#[cfg_attr(feature = "serde", derive(serde::Serialize))]
597#[non_exhaustive]
598pub struct NegotiatedParams {
599    /// The negotiated base protocol version — always `5` (HSv5) for a
600    /// completed handshake in this crate.
601    pub version: u32,
602    /// The flags both sides advertised, ANDed together (only mutually
603    /// supported capabilities are considered agreed).
604    pub flags: HandshakeExtensionMessageFlags,
605    /// The agreed TSBPD latency, rounded down to the whole milliseconds the
606    /// wire carries: the greater of this side's configured
607    /// [`HandshakeConfig::latency`] and the peer's reported Receiver/Sender
608    /// TSBPD Delay (§4.3.1.2).
609    pub latency: Duration,
610    /// This side's own SRT Socket ID.
611    pub own_socket_id: u32,
612    /// The peer's SRT Socket ID.
613    pub peer_socket_id: u32,
614    /// The agreed Maximum Transmission Unit Size (§3.2.1): the smaller of the
615    /// two parties' advertised values, so neither is sent a datagram larger
616    /// than it said it could carry.
617    pub mtu: u32,
618    /// The agreed Maximum Flow Window Size (§3.2.1): the smaller of the two
619    /// parties' advertised values — how many packets may be unacknowledged in
620    /// flight (the sender's window) and how far ahead of its ack point a
621    /// receiver tracks (the receiver's window).
622    pub max_flow_window_size: u32,
623    /// The negotiated Stream ID (§3.2.1.3), if one was advertised.
624    pub stream_id: Option<String>,
625    /// The negotiated Group Membership (§3.2.1.4), if one was advertised.
626    pub group: Option<GroupMembershipExtension>,
627    /// The negotiated Stream Encrypting Key (§6.1.5), if
628    /// [`HandshakeConfig::crypto`] was set on this side and the Key Material
629    /// exchange succeeded. `None` if encryption was not negotiated.
630    ///
631    /// A [`SecretBytes`]: redacted in `Debug`, constant-time in `==`, wiped on
632    /// drop, and never serialized.
633    #[cfg(feature = "crypto")]
634    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
635    #[cfg_attr(feature = "serde", serde(skip))]
636    pub sek: Option<SecretBytes>,
637    /// The Salt paired with [`Self::sek`] — both are required by
638    /// [`crate::crypto::aes_ctr_apply`] to encrypt/decrypt a data packet's
639    /// payload (§6.1.2/§6.2.2/§6.3.2).
640    #[cfg(feature = "crypto")]
641    #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
642    pub salt: Option<[u8; crate::crypto::SALT_LEN]>,
643}
644
645/// An event produced by [`crate::caller::CallerHandshake::feed`] /
646/// [`crate::caller::CallerHandshake::start`] /
647/// [`crate::listener::ListenerHandshake::feed`] / either engine's `tick`.
648#[derive(Debug, Clone, PartialEq)]
649#[cfg_attr(feature = "serde", derive(serde::Serialize))]
650#[non_exhaustive]
651pub enum HandshakeOutput {
652    /// Send these bytes (one serialized Handshake control packet, built from
653    /// the existing [`crate::packet`] codecs) to the peer.
654    Send(Vec<u8>),
655    /// The handshake completed; here are the negotiated parameters.
656    Connected(NegotiatedParams),
657    /// The handshake was rejected — either the peer sent back an explicit
658    /// [`RejectionReason`], or a local validation check failed (in which
659    /// case a matching `Send` rejection packet is also emitted, in the same
660    /// output batch, for the Listener side).
661    Rejected(RejectionReason),
662    /// No reply arrived after [`HandshakeConfig::max_retries`]
663    /// retransmissions.
664    TimedOut,
665}
666
667/// What a retransmit tick asks of the handshake machine that owns it.
668pub(crate) enum RetransmitStep {
669    Idle,
670    Resend(Vec<u8>),
671    TimedOut,
672}
673
674impl RetransmitStep {
675    pub(crate) fn into_outputs(self) -> Vec<HandshakeOutput> {
676        match self {
677            Self::Idle => Vec::new(),
678            Self::Resend(bytes) => vec![HandshakeOutput::Send(bytes)],
679            Self::TimedOut => vec![HandshakeOutput::TimedOut],
680        }
681    }
682}
683
684/// The connection-relative wire timestamp (§3.2.1, microseconds since the
685/// connection started) the handshake machines stamp on every packet they build.
686/// The machines read no clock: the driver feeds the elapsed time in.
687#[derive(Debug, Default, Clone, Copy)]
688pub(crate) struct WireClock {
689    us: u32,
690}
691
692impl WireClock {
693    pub(crate) fn set(&mut self, elapsed: core::time::Duration) {
694        self.us = crate::arq::duration_to_wire_us(elapsed);
695    }
696
697    pub(crate) fn now(&self) -> u32 {
698        self.us
699    }
700}
701
702/// The retransmit bookkeeping every handshake machine (caller, listener,
703/// rendezvous) shares: the last packet sent, the caller's time advanced since
704/// it was sent, and the retransmissions spent on it.
705#[derive(Debug, Default)]
706pub(crate) struct Retransmit {
707    last_sent: Option<Vec<u8>>,
708    silent: Duration,
709    retries: u32,
710}
711
712impl Retransmit {
713    pub(crate) fn remember(&mut self, bytes: &[u8]) {
714        self.last_sent = Some(bytes.to_vec());
715    }
716
717    pub(crate) fn arm(&mut self, bytes: &[u8]) {
718        self.remember(bytes);
719        self.silent = Duration::ZERO;
720    }
721
722    pub(crate) fn arm_fresh(&mut self, bytes: &[u8]) {
723        self.arm(bytes);
724        self.retries = 0;
725    }
726
727    pub(crate) fn last_sent(&self) -> Option<&[u8]> {
728        self.last_sent.as_deref()
729    }
730
731    /// Advance the caller's own clock by `elapsed` with no reply: once
732    /// [`HandshakeConfig::retransmit_after`] has passed the last packet is
733    /// resent, and once [`HandshakeConfig::max_retries`] resends are spent the
734    /// handshake times out.
735    pub(crate) fn tick(&mut self, elapsed: Duration, config: &HandshakeConfig) -> RetransmitStep {
736        self.silent = self.silent.saturating_add(elapsed);
737        if self.silent < config.retransmit_after {
738            return RetransmitStep::Idle;
739        }
740        self.silent = Duration::ZERO;
741        self.retries += 1;
742        if self.retries > config.max_retries {
743            return RetransmitStep::TimedOut;
744        }
745        self.last_sent
746            .clone()
747            .map_or(RetransmitStep::Idle, RetransmitStep::Resend)
748    }
749}
750
751/// Serializes one [`HandshakePacket`] using the existing [`ControlPacket`]
752/// codec — never hand-rolled.
753pub(crate) fn build_bytes(hp: HandshakePacket<'_>) -> Result<Vec<u8>> {
754    let pkt = ControlPacket::Handshake(hp);
755    let mut buf = alloc::vec![0u8; pkt.serialized_len()];
756    pkt.serialize_into(&mut buf)?;
757    Ok(buf)
758}
759
760/// Builds the extensions payload for a CONCLUSION-phase handshake carrying a
761/// Handshake Extension Message plus optional Stream ID / Group Membership,
762/// returning `(bytes, Extension Field flags)`.
763pub(crate) fn build_conclusion_extensions<'a>(
764    hs_ext_type: crate::packet::ExtensionType,
765    contents: &'a ConclusionExtensionContents,
766) -> (HandshakeExtensions<'a>, u16) {
767    let mut blocks = alloc::vec![HandshakeExtensionBlock {
768        ext_type: hs_ext_type,
769        contents: &contents.hs_msg,
770    }];
771    let mut ext_flags = HS_EXT_FLAG_HSREQ;
772    if let Some(sid) = contents.stream_id.as_ref() {
773        blocks.push(HandshakeExtensionBlock {
774            ext_type: crate::packet::ExtensionType::Sid,
775            contents: sid,
776        });
777        ext_flags |= HS_EXT_FLAG_CONFIG;
778    }
779    if let Some(group) = contents.group.as_ref() {
780        blocks.push(HandshakeExtensionBlock {
781            ext_type: crate::packet::ExtensionType::Group,
782            contents: group,
783        });
784        ext_flags |= HS_EXT_FLAG_CONFIG;
785    }
786    if let Some((ext_type, km)) = contents.km.as_ref() {
787        blocks.push(HandshakeExtensionBlock {
788            ext_type: *ext_type,
789            contents: km,
790        });
791        ext_flags |= crate::packet::handshake::HS_EXT_FLAG_KMREQ;
792    }
793    (HandshakeExtensions(blocks), ext_flags)
794}
795
796/// The extension contents a CONCLUSION carries, encoded once and owned by the
797/// handshake that sends it (the packet borrows them).
798pub(crate) struct ConclusionExtensionContents {
799    hs_msg: Vec<u8>,
800    stream_id: Option<Vec<u8>>,
801    group: Option<Vec<u8>>,
802    km: Option<(crate::packet::ExtensionType, Vec<u8>)>,
803}
804
805impl ConclusionExtensionContents {
806    /// Encode a Handshake Extension Message plus optional Stream ID and Group
807    /// Membership (§3.2.1.1, §3.2.1.3, §3.2.1.4).
808    pub(crate) fn new(
809        hs_msg: HsExtMessage,
810        stream_id: Option<&str>,
811        group: Option<GroupMembershipExtension>,
812    ) -> Self {
813        use crate::packet::handshake::encode_stream_id;
814        ConclusionExtensionContents {
815            hs_msg: Vec::from(hs_msg.to_bytes()),
816            stream_id: stream_id.map(encode_stream_id),
817            group: group.map(|g| Vec::from(g.to_bytes())),
818            km: None,
819        }
820    }
821
822    /// Add an `SRT_CMD_KMREQ` Key Material message (§6.1.5) — the Caller's
823    /// request, or the Listener's `SRT_CMD_KMRSP` echo.
824    #[cfg(feature = "crypto")]
825    pub(crate) fn set_key_material(
826        &mut self,
827        ext_type: crate::packet::ExtensionType,
828        contents: Vec<u8>,
829    ) {
830        self.km = Some((ext_type, contents));
831    }
832}
833
834/// A parsed peer extension payload relevant to the Caller-Listener handshake:
835/// the mandatory Handshake Extension Message plus any optional Stream ID /
836/// Group Membership / Key Material.
837#[derive(Debug, Default)]
838pub(crate) struct ParsedPeerExtensions<'a> {
839    pub hs_msg: Option<HsExtMessage>,
840    pub stream_id: Option<String>,
841    pub group: Option<GroupMembershipExtension>,
842    /// The Key Material extension (§3.2.1.2/§3.2.2, `SRT_CMD_KMREQ` on the
843    /// Caller's CONCLUSION / `SRT_CMD_KMRSP` on the Listener's) — decoded
844    /// regardless of the `crypto` feature (wire-structure decode only,
845    /// [`KeyMaterial`] has no crypto dependency); only *acted on*
846    /// (KEK derive/unwrap/wrap) when `crypto` is enabled, see
847    /// [`crate::caller::CallerHandshake`]/[`crate::listener::ListenerHandshake`].
848    #[cfg(feature = "crypto")]
849    pub km: Option<KeyMaterial<'a>>,
850    /// Keeps the `'a` lifetime parameter meaningful when the `crypto`
851    /// feature (and with it, [`Self::km`]) is compiled out.
852    #[cfg(not(feature = "crypto"))]
853    _phantom: core::marker::PhantomData<&'a ()>,
854}
855
856/// Walks a handshake packet's extension blocks, decoding the ones this crate
857/// understands. Returns [`Error::InvalidField`] (mapped by the caller to a
858/// [`RejectionReason::Rogue`] rejection) on any decode failure, rather than
859/// panicking — extension content is untrusted peer input.
860pub(crate) fn parse_peer_extensions<'a>(
861    hp: &HandshakePacket<'a>,
862) -> Result<ParsedPeerExtensions<'a>> {
863    use crate::packet::ExtensionType;
864
865    let mut out = ParsedPeerExtensions::default();
866    for block in hp.extensions.iter() {
867        match block.ext_type {
868            ExtensionType::HsReq | ExtensionType::HsRsp => {
869                let msg = block.as_hs_ext_message().map_err(|_| {
870                    Error::InvalidField(InvalidField::new(
871                        "handshake extension message",
872                        "malformed HSREQ/HSRSP contents",
873                    ))
874                })?;
875                out.hs_msg = Some(msg);
876            }
877            ExtensionType::Sid => {
878                let sid = block.as_stream_id().map_err(|_| {
879                    Error::InvalidField(InvalidField::new(
880                        "stream ID extension",
881                        "malformed or non-UTF-8 contents",
882                    ))
883                })?;
884                out.stream_id = Some(sid);
885            }
886            ExtensionType::Group => {
887                let g = block.as_group_membership().map_err(|_| {
888                    Error::InvalidField(InvalidField::new(
889                        "group membership extension",
890                        "malformed contents",
891                    ))
892                })?;
893                out.group = Some(g);
894            }
895            #[cfg(feature = "crypto")]
896            ExtensionType::KmReq | ExtensionType::KmRsp => {
897                let km = block.as_key_material().map_err(|_| {
898                    Error::InvalidField(InvalidField::new(
899                        "key material extension",
900                        "malformed contents",
901                    ))
902                })?;
903                out.km = Some(km);
904            }
905            _ => {}
906        }
907    }
908    Ok(out)
909}
910
911// ---------------------------------------------------------------------------
912// §6.1.5 Key Material Exchange — piggybacked on the CONCLUSION extensions.
913// ---------------------------------------------------------------------------
914
915/// Build the Key Material handshake extension block (`Extension Type` +
916/// `Extension Length` + contents — ready to append after the mandatory
917/// HSREQ block) offering `crypto.sek`, wrapped under a KEK derived from
918/// `crypto.passphrase`/`crypto.salt` (`draft-sharabayko-srt-01` §6.1.5 "sent
919/// by the connection initiator ... to the responder", §6.2.1's `Wrap =
920/// AESkw(KEK, SEK)`). Always encodes `KK = Even` — this crate's convention
921/// for the handshake-negotiated initial SEK; §6.1.6's odd/even alternation
922/// only matters from the first KM Refresh onward (see [`crate::km_refresh`]).
923#[cfg(feature = "crypto")]
924pub(crate) fn build_key_material_extension(crypto: &CryptoConfig) -> Result<Vec<u8>> {
925    let kek = crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len())?;
926    let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &crypto.sek)?;
927    let km = KeyMaterial {
928        kk: KmKeyFlag::Even,
929        keki: 0,
930        cipher: Cipher::AesCtr,
931        auth: KmAuth::None,
932        se: StreamEncapsulation::MpegTsSrt,
933        salt: &crypto.salt,
934        icv,
935        x_sek: &wrapped,
936        o_sek: None,
937    };
938    let mut buf = alloc::vec![0u8; km.serialized_len()];
939    km.serialize_into(&mut buf)?;
940    crate::packet::handshake::build_extension_block(crate::packet::ExtensionType::KmReq, &buf)
941}
942
943/// The `SRT_CMD_KMREQ` Key Material message itself (§3.2.1.2/§3.2.2) —
944/// [`build_key_material_extension`] without its block header, ready to be a
945/// packet's extension contents.
946#[cfg(feature = "crypto")]
947pub(crate) fn build_key_material_contents(crypto: &CryptoConfig) -> Result<Vec<u8>> {
948    let block = build_key_material_extension(crypto)?;
949    Ok(block[crate::packet::handshake::HANDSHAKE_EXT_BLOCK_HEADER_LEN..].to_vec())
950}
951
952/// The `SRT_CMD_KMRSP` contents echoing a peer's Key Material message: its
953/// own bytes when we have them (a parsed block), else a re-serialization of
954/// the decoded message (§6.1.5).
955#[cfg(feature = "crypto")]
956pub(crate) fn echo_key_material_contents<'a>(
957    hp: &'a HandshakePacket<'a>,
958    km: &KeyMaterial<'_>,
959) -> Result<Cow<'a, [u8]>> {
960    for block in hp.extensions.iter() {
961        if matches!(
962            block.ext_type,
963            crate::packet::ExtensionType::KmReq | crate::packet::ExtensionType::KmRsp
964        ) {
965            return Ok(Cow::Borrowed(block.contents));
966        }
967    }
968    let mut contents = alloc::vec![0u8; km.serialized_len()];
969    km.serialize_into(&mut contents)?;
970    Ok(Cow::Owned(contents))
971}
972
973/// A recovered/negotiated `(SEK, Salt)` pair.
974#[cfg(feature = "crypto")]
975pub(crate) type RecoveredSek = (SecretBytes, [u8; crate::crypto::SALT_LEN]);
976
977/// Recover the SEK a peer's Key Material offered, given this side's shared
978/// passphrase (§6.1.5/§6.3.1: "the responder MUST know the passphrase ...
979/// everything else needed is extracted from the Keying Material message").
980/// Returns the recovered SEK bytes and the 16-byte Salt — both required by
981/// [`crate::crypto::aes_ctr_apply`].
982///
983/// # Errors
984/// [`Error::InvalidField`] if the Salt is not 16 bytes (the only Salt length
985/// this crate's Key Material codec accepts); otherwise propagates
986/// [`crate::crypto::unwrap_sek`]'s error (RFC 3394 wrap-integrity failure —
987/// wrong passphrase, §6.1.5's "it does not have the SEK" case).
988#[cfg(feature = "crypto")]
989pub(crate) fn recover_sek(
990    passphrase: &[u8],
991    km: &KeyMaterial<'_>,
992    kek_cache: &mut crate::crypto::KekCache,
993) -> Result<RecoveredSek> {
994    if km.salt.len() != crate::crypto::SALT_LEN {
995        return Err(Error::InvalidField(InvalidField::new(
996            "Key Material Salt",
997            "must be 16 bytes (the only Salt length this crate's codec accepts)",
998        )));
999    }
1000    let mut salt = [0u8; crate::crypto::SALT_LEN];
1001    salt.copy_from_slice(km.salt);
1002    let kek = kek_cache.derive(passphrase, &salt, km.x_sek.len())?;
1003    let sek = SecretBytes::new(crate::crypto::unwrap_sek(&kek, &km.icv, km.x_sek)?.to_vec());
1004    Ok((sek, salt))
1005}
1006
1007/// Recover the `(even, odd, salt)` triple a `KK = Both` Key Material message
1008/// carries: §6.1.6 wraps `even SEK || odd SEK` as one RFC 3394 block under a
1009/// single ICV.
1010///
1011/// # Errors
1012/// [`Error::InvalidField`] if the message is not `KK = Both`, the Salt is not
1013/// 16 bytes, or the RFC 3394 integrity check fails.
1014#[cfg(feature = "link")]
1015pub(crate) fn recover_both_seks(
1016    passphrase: &[u8],
1017    km: &KeyMaterial<'_>,
1018    kek_cache: &mut crate::crypto::KekCache,
1019) -> Result<(SecretBytes, SecretBytes, [u8; crate::crypto::SALT_LEN])> {
1020    let Some(o_sek) = km.o_sek.filter(|_| km.kk == KmKeyFlag::Both) else {
1021        return Err(Error::InvalidField(InvalidField::new(
1022            "Key Material KK",
1023            "expected both an even and an odd SEK",
1024        )));
1025    };
1026    if km.salt.len() != crate::crypto::SALT_LEN {
1027        return Err(Error::InvalidField(InvalidField::new(
1028            "Key Material Salt",
1029            "must be 16 bytes (the only Salt length this crate's codec accepts)",
1030        )));
1031    }
1032    let mut salt = [0u8; crate::crypto::SALT_LEN];
1033    salt.copy_from_slice(km.salt);
1034    let kek = kek_cache.derive(passphrase, &salt, km.x_sek.len())?;
1035    let mut wrapped = Vec::with_capacity(km.x_sek.len() + o_sek.len());
1036    wrapped.extend_from_slice(km.x_sek);
1037    wrapped.extend_from_slice(o_sek);
1038    let keys = crate::crypto::unwrap_sek(&kek, &km.icv, &wrapped)?;
1039    let (even, odd) = keys.split_at(km.x_sek.len());
1040    Ok((
1041        SecretBytes::new(even.to_vec()),
1042        SecretBytes::new(odd.to_vec()),
1043        salt,
1044    ))
1045}
1046
1047/// Verify a Listener's echoed Key Material matches what this Caller sent.
1048/// Recomputed deterministically from `crypto` (the same passphrase/salt/sek
1049/// always wraps to the same bytes, §6.2.1) rather than requiring the Caller
1050/// to keep the original wrap bytes around.
1051#[cfg(feature = "crypto")]
1052pub(crate) fn verify_km_echo(crypto: &CryptoConfig, echoed: &KeyMaterial<'_>) -> bool {
1053    let kek = match crate::crypto::derive_kek(&crypto.passphrase, &crypto.salt, crypto.sek.len()) {
1054        Ok(k) => k,
1055        Err(_) => return false,
1056    };
1057    let (icv, wrapped) = match crate::crypto::wrap_sek(&kek, &crypto.sek) {
1058        Ok(v) => v,
1059        Err(_) => return false,
1060    };
1061    // The wrapped key is derived from the secret: compare it in constant time.
1062    let salt = echoed.salt.ct_eq(crypto.salt.as_slice());
1063    let icv = echoed.icv.as_slice().ct_eq(icv.as_slice());
1064    let wrapped = echoed.x_sek.ct_eq(wrapped.as_slice());
1065    bool::from(salt & icv & wrapped)
1066}
1067
1068/// The greater-of-both-parties TSBPD latency rule (§4.3.1.2), rounded down to
1069/// the whole milliseconds the wire carries.
1070pub(crate) fn negotiate_latency(local: Duration, peer_msg: &HsExtMessage) -> Duration {
1071    local
1072        .max(peer_msg.receiver_tsbpd_delay)
1073        .max(peer_msg.sender_tsbpd_delay)
1074}
1075
1076#[cfg(test)]
1077impl Default for HandshakeConfig {
1078    fn default() -> Self {
1079        HandshakeConfig::new(
1080            Duration::from_millis(120),
1081            1500,
1082            8192,
1083            Duration::from_micros(83_333),
1084            12,
1085        )
1086    }
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092
1093    #[test]
1094    fn rejection_reason_round_trips_table_7() {
1095        let all = [
1096            RejectionReason::Unknown,
1097            RejectionReason::System,
1098            RejectionReason::Peer,
1099            RejectionReason::Resource,
1100            RejectionReason::Rogue,
1101            RejectionReason::Backlog,
1102            RejectionReason::Ipe,
1103            RejectionReason::Close,
1104            RejectionReason::Version,
1105            RejectionReason::RdvCookie,
1106            RejectionReason::BadSecret,
1107            RejectionReason::Unsecure,
1108            RejectionReason::MessageApi,
1109            RejectionReason::Congestion,
1110            RejectionReason::Filter,
1111            RejectionReason::Group,
1112        ];
1113        for (i, r) in all.iter().enumerate() {
1114            assert_eq!(r.to_bits(), 1000 + i as u32);
1115            assert_eq!(RejectionReason::from_bits(r.to_bits()), *r);
1116            assert_eq!(
1117                RejectionReason::from_handshake_type(r.to_handshake_type()),
1118                Some(*r)
1119            );
1120        }
1121    }
1122
1123    #[test]
1124    fn non_rejection_handshake_types_are_not_a_rejection() {
1125        for ht in [
1126            HandshakeType::Induction,
1127            HandshakeType::Conclusion,
1128            HandshakeType::Wavehand,
1129            HandshakeType::Agreement,
1130            HandshakeType::Done,
1131        ] {
1132            assert_eq!(RejectionReason::from_handshake_type(ht), None);
1133        }
1134    }
1135
1136    /// r08-SRT-W14: only `1000..2^31` is a rejection. `0xFFFF_FFFC` (libsrt's
1137    /// negative URQ range) and `2^31` itself used to be reported as
1138    /// `Rejected(Reserved(..))`.
1139    #[test]
1140    fn only_the_positive_rejection_range_counts_as_a_rejection() {
1141        let is_rejection =
1142            |v: u32| RejectionReason::from_handshake_type(HandshakeType::from_bits(v)).is_some();
1143        assert!(!is_rejection(0xFFFF_FFFC));
1144        assert!(!is_rejection(0xFFFF_FFFE)); // AGREEMENT is its own type
1145        assert!(!is_rejection(REJECTION_CODE_LIMIT));
1146        assert!(!is_rejection(REJECTION_CODE_BASE - 1));
1147        assert!(is_rejection(REJECTION_CODE_BASE));
1148        assert!(is_rejection(REJECTION_CODE_LIMIT - 1));
1149        // A predefined reason, a reason the table does not define, and a
1150        // user-defined (2000+) reason all decode.
1151        assert_eq!(
1152            RejectionReason::from_handshake_type(HandshakeType::from_bits(1010)),
1153            Some(RejectionReason::BadSecret)
1154        );
1155        assert_eq!(
1156            RejectionReason::from_handshake_type(HandshakeType::from_bits(1500)),
1157            Some(RejectionReason::Reserved(1500))
1158        );
1159        assert_eq!(
1160            RejectionReason::from_handshake_type(HandshakeType::from_bits(2001)),
1161            Some(RejectionReason::Reserved(2001))
1162        );
1163    }
1164
1165    /// r08-SRT-W7: the Caller's KMREQ carries `SE` = 2 (MPEG-TS/SRT), the
1166    /// value a real SRT listener requires: it rejects `SE` = 0 as a bad KM
1167    /// (`tests/it/libsrt_crypto_interop.rs`).
1168    #[cfg(feature = "crypto")]
1169    #[test]
1170    fn caller_kmreq_declares_the_mpeg_ts_srt_encapsulation() {
1171        let crypto = CryptoConfig {
1172            passphrase: b"0123456789abcdef".to_vec(),
1173            salt: [0x33; crate::crypto::SALT_LEN],
1174            sek: alloc::vec![0x44; 16],
1175        };
1176        let ext = build_key_material_extension(&crypto).unwrap();
1177        // Extension block: type(16) length(16, words) then the KM message.
1178        let km = KeyMaterial::parse(&ext[4..]).unwrap();
1179        assert_eq!(km.se, StreamEncapsulation::MpegTsSrt);
1180        assert_eq!(km.se.to_bits(), 2);
1181        // Wire byte: word 2 of the KM is Cipher(8) Auth(8) SE(8) Resv2(8).
1182        assert_eq!(ext[4 + 10], 2);
1183    }
1184
1185    // ---- #1142: secrets stay out of Debug / serde, are compared in constant
1186    // time and wiped on drop ------------------------------------------------
1187
1188    /// A non-repeating pseudo-random run, so a needle cut from it cannot occur
1189    /// by chance in unrelated numbers.
1190    #[cfg(feature = "crypto")]
1191    fn distinctive(seed: u32, len: usize) -> Vec<u8> {
1192        let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(12_345);
1193        (0..len)
1194            .map(|_| {
1195                x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1196                u8::try_from(x >> 24).unwrap()
1197            })
1198            .collect()
1199    }
1200
1201    /// Every spelling a leak of the first six bytes of `bytes` could take.
1202    #[cfg(feature = "crypto")]
1203    fn needles(bytes: &[u8]) -> Vec<String> {
1204        let head = &bytes[..6];
1205        let dec = |sep: &str| {
1206            head.iter()
1207                .map(|b| alloc::format!("{b}"))
1208                .collect::<Vec<_>>()
1209                .join(sep)
1210        };
1211        alloc::vec![
1212            dec(", "),
1213            dec(","),
1214            head.iter()
1215                .map(|b| alloc::format!("{b:x}"))
1216                .collect::<Vec<_>>()
1217                .join(", "),
1218            head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
1219        ]
1220    }
1221
1222    #[cfg(feature = "crypto")]
1223    fn secret_config() -> CryptoConfig {
1224        CryptoConfig {
1225            passphrase: distinctive(1, 15),
1226            salt: distinctive(2, crate::crypto::SALT_LEN).try_into().unwrap(),
1227            sek: distinctive(3, 16),
1228        }
1229    }
1230
1231    /// `{:?}` and `{:#?}` of a config (alone or inside a `HandshakeConfig`)
1232    /// carry no passphrase, salt or key bytes — only their lengths.
1233    #[cfg(feature = "crypto")]
1234    #[test]
1235    fn crypto_config_debug_never_shows_secret_bytes() {
1236        let config = HandshakeConfig {
1237            crypto: Some(secret_config()),
1238            ..HandshakeConfig::default()
1239        };
1240        for dump in [
1241            alloc::format!("{:?}", secret_config()),
1242            alloc::format!("{:#?}", secret_config()),
1243            alloc::format!("{:?}", config),
1244            alloc::format!("{:#?}", config),
1245            alloc::format!("{:x?}", config),
1246        ] {
1247            let secret = secret_config();
1248            for (name, bytes) in [
1249                ("passphrase", &secret.passphrase[..]),
1250                ("salt", &secret.salt[..]),
1251                ("sek", &secret.sek[..]),
1252            ] {
1253                for needle in needles(bytes) {
1254                    assert!(
1255                        !dump.contains(&needle),
1256                        "{name} leaked as {needle:?}: {dump}"
1257                    );
1258                }
1259            }
1260            assert!(dump.contains("redacted"), "{dump}");
1261        }
1262        assert!(alloc::format!("{:?}", secret_config()).contains("15 bytes"));
1263    }
1264
1265    /// A negotiated key is redacted in `Debug` — also when it rides inside a
1266    /// [`HandshakeOutput`] — and is not serialized.
1267    #[cfg(feature = "crypto")]
1268    #[test]
1269    fn negotiated_sek_is_redacted_in_debug_and_absent_from_serde() {
1270        let sek_bytes = distinctive(9, 16);
1271        let params = NegotiatedParams {
1272            version: HANDSHAKE_VERSION_5,
1273            flags: HandshakeExtensionMessageFlags::new(0),
1274            latency: Duration::from_millis(120),
1275            own_socket_id: 1,
1276            peer_socket_id: 2,
1277            mtu: 1500,
1278            max_flow_window_size: 8192,
1279            stream_id: None,
1280            group: None,
1281            sek: Some(SecretBytes::new(sek_bytes.clone())),
1282            salt: Some([0x11; crate::crypto::SALT_LEN]),
1283        };
1284        for dump in [
1285            alloc::format!("{params:?}"),
1286            alloc::format!("{:#?}", HandshakeOutput::Connected(params.clone())),
1287            alloc::format!("{:x?}", HandshakeOutput::Connected(params.clone())),
1288        ] {
1289            for needle in needles(&sek_bytes) {
1290                assert!(!dump.contains(&needle), "SEK leaked as {needle:?}: {dump}");
1291            }
1292            assert!(dump.contains("redacted"), "{dump}");
1293        }
1294        #[cfg(feature = "serde")]
1295        {
1296            let json = serde_json::to_string(&params).expect("serialize");
1297            assert!(!json.contains("sek"), "the SEK was serialized: {json}");
1298            for needle in needles(&sek_bytes) {
1299                assert!(!json.contains(&needle), "SEK leaked as {needle:?}: {json}");
1300            }
1301        }
1302    }
1303
1304    /// Secret comparison and wiping: `==` distinguishes contents (and
1305    /// lengths) correctly through the constant-time path, and `zeroize`
1306    /// clears the key and the passphrase.
1307    #[cfg(feature = "crypto")]
1308    #[test]
1309    fn secrets_compare_correctly_and_wipe_on_zeroize() {
1310        let a = SecretBytes::new(alloc::vec![1, 2, 3, 4]);
1311        assert!(a == SecretBytes::new(alloc::vec![1, 2, 3, 4]));
1312        assert!(a != SecretBytes::new(alloc::vec![1, 2, 3, 5]));
1313        assert!(a != SecretBytes::new(alloc::vec![1, 2, 3]));
1314        assert_eq!(&*a, &[1u8, 2, 3, 4][..]);
1315
1316        let mut sek = SecretBytes::new(alloc::vec![9; 16]);
1317        sek.zeroize();
1318        assert!(sek.is_empty(), "zeroize must clear the key");
1319
1320        let mut config = secret_config();
1321        assert!(config == secret_config());
1322        let mut other = secret_config();
1323        other.sek[0] ^= 1;
1324        assert!(config != other);
1325        config.zeroize();
1326        assert!(config.passphrase.is_empty() && config.sek.is_empty());
1327        assert_eq!(config.salt, [0u8; crate::crypto::SALT_LEN]);
1328    }
1329
1330    /// Compile-time guard: both secret holders wipe themselves on drop.
1331    #[cfg(feature = "crypto")]
1332    #[test]
1333    fn secret_holders_are_zeroize_on_drop() {
1334        fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
1335        assert_zeroize_on_drop::<CryptoConfig>();
1336        assert_zeroize_on_drop::<SecretBytes>();
1337    }
1338
1339    #[test]
1340    fn config_builders_store_each_field() {
1341        use crate::packet::HandshakeExtensionMessageFlags;
1342        let flags = HandshakeExtensionMessageFlags::new(0x0000_0023);
1343        let config = HandshakeConfig::default()
1344            .with_srt_version(0x0105_0003)
1345            .with_flags(flags)
1346            .with_local_ip([1, 2, 3, 4])
1347            .with_retransmit_after(Duration::from_millis(7))
1348            .with_max_retries(3);
1349        assert_eq!(config.srt_version, 0x0105_0003);
1350        assert_eq!(config.flags, flags);
1351        assert_eq!(config.local_ip, [1, 2, 3, 4]);
1352        assert_eq!(config.retransmit_after, Duration::from_millis(7));
1353        assert_eq!(config.max_retries, 3);
1354    }
1355
1356    fn example_hs_msg() -> HsExtMessage {
1357        HsExtMessage {
1358            srt_version: 0x0105_0000,
1359            srt_flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
1360            receiver_tsbpd_delay: Duration::from_millis(120),
1361            sender_tsbpd_delay: Duration::from_millis(120),
1362        }
1363    }
1364
1365    #[test]
1366    fn conclusion_extension_flags_advertise_a_present_stream_id() {
1367        use crate::packet::handshake::HS_EXT_FLAG_CONFIG;
1368        let contents = ConclusionExtensionContents::new(example_hs_msg(), Some("sid"), None);
1369        let (_, flags) =
1370            build_conclusion_extensions(crate::packet::ExtensionType::HsReq, &contents);
1371        assert_eq!(flags & HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_CONFIG);
1372    }
1373
1374    #[test]
1375    fn conclusion_extension_flags_advertise_a_present_group() {
1376        use crate::packet::handshake::HS_EXT_FLAG_CONFIG;
1377        use crate::packet::{GroupFlags, GroupMembershipExtension, GroupType};
1378        let group = GroupMembershipExtension {
1379            group_id: 7,
1380            group_type: GroupType::from_bits(0),
1381            flags: GroupFlags::new(0),
1382            weight: 0,
1383        };
1384        let contents = ConclusionExtensionContents::new(example_hs_msg(), None, Some(group));
1385        let (_, flags) =
1386            build_conclusion_extensions(crate::packet::ExtensionType::HsReq, &contents);
1387        assert_eq!(flags & HS_EXT_FLAG_CONFIG, HS_EXT_FLAG_CONFIG);
1388    }
1389
1390    #[test]
1391    fn arm_fresh_resets_the_retry_budget_and_the_silence() {
1392        let config = HandshakeConfig::default();
1393        let mut retransmit = Retransmit::default();
1394        retransmit.arm_fresh(b"packet");
1395        assert!(matches!(
1396            retransmit.tick(config.retransmit_after - Duration::from_micros(1), &config),
1397            RetransmitStep::Idle
1398        ));
1399        for _ in 0..=config.max_retries {
1400            let _ = retransmit.tick(config.retransmit_after, &config);
1401        }
1402        assert!(matches!(
1403            retransmit.tick(config.retransmit_after, &config),
1404            RetransmitStep::TimedOut
1405        ));
1406        retransmit.arm_fresh(b"packet");
1407        assert!(
1408            matches!(
1409                retransmit.tick(config.retransmit_after, &config),
1410                RetransmitStep::Resend(ref bytes) if bytes.as_slice() == b"packet"
1411            ),
1412            "arm_fresh must restore the retry budget and resend"
1413        );
1414    }
1415
1416    #[test]
1417    fn rejection_reason_labels_match_table_7() {
1418        let cases: &[(RejectionReason, &str)] = &[
1419            (RejectionReason::Unknown, "REJ_UNKNOWN"),
1420            (RejectionReason::System, "REJ_SYSTEM"),
1421            (RejectionReason::Peer, "REJ_PEER"),
1422            (RejectionReason::Resource, "REJ_RESOURCE"),
1423            (RejectionReason::Rogue, "REJ_ROGUE"),
1424            (RejectionReason::Backlog, "REJ_BACKLOG"),
1425            (RejectionReason::Ipe, "REJ_IPE"),
1426            (RejectionReason::Close, "REJ_CLOSE"),
1427            (RejectionReason::Version, "REJ_VERSION"),
1428            (RejectionReason::RdvCookie, "REJ_RDVCOOKIE"),
1429            (RejectionReason::BadSecret, "REJ_BADSECRET"),
1430            (RejectionReason::Unsecure, "REJ_UNSECURE"),
1431            (RejectionReason::MessageApi, "REJ_MESSAGEAPI"),
1432            (RejectionReason::Congestion, "REJ_CONGESTION"),
1433            (RejectionReason::Filter, "REJ_FILTER"),
1434            (RejectionReason::Group, "REJ_GROUP"),
1435        ];
1436        for &(reason, label) in cases {
1437            assert_eq!(reason.name(), label);
1438        }
1439        assert_eq!(RejectionReason::Reserved(1500).name(), "reserved");
1440    }
1441}