Skip to main content

srt_runtime/packet/
handshake.rs

1//! Handshake control packet — `draft-sharabayko-srt-01` §3.2.1, Figure 5, and
2//! its extension messages: Handshake Extension Message (§3.2.1.1 / Figure 6,
3//! flags in §3.2.1.1.1 / Table 6), Key Material Extension (§3.2.1.2, content
4//! is a [`super::KeyMaterial`] — §3.2.2), Stream ID Extension (§3.2.1.3 /
5//! Figure 7), and Group Membership Extension (§3.2.1.4 / Figures 8-9).
6//!
7//! ```text
8//! word0..0   Version (32)
9//! word1      Encryption Field (16) | Extension Field (16)
10//! word2      Initial Packet Sequence Number (32)
11//! word3      Maximum Transmission Unit Size (32)
12//! word4      Maximum Flow Window Size (32)
13//! word5      Handshake Type (32)
14//! word6      SRT Socket ID (32)
15//! word7      SYN Cookie (32)
16//! word8..11  Peer IP Address (128)
17//! ── repeated ──
18//!            Extension Type (16) | Extension Length (16, in 4-byte blocks)
19//!            Extension Contents (Extension Length * 4 bytes)
20//! ```
21//!
22//! This module covers *structure* only: parsing the fixed CIF fields and
23//! walking/decoding extension blocks. The handshake *exchange* (caller /
24//! listener / rendezvous state machine, §4.3) is an explicit follow-up.
25
26use alloc::string::String;
27use alloc::vec::Vec;
28use broadcast_core::error::InvalidField;
29use broadcast_core::error::{BufferTooShort, OutputBufferTooSmall};
30use broadcast_core::len::need_in;
31
32use super::key_material::KeyMaterial;
33use super::number::{SocketId, SrtTimestamp};
34use super::{Error, Result, put_be16, put_be32};
35use core::time::Duration;
36
37/// Length in bytes of the fixed Handshake CIF core (Version through Peer IP
38/// Address, §3.2.1 Figure 5) — 12 header words.
39pub const HANDSHAKE_CIF_FIXED_LEN: usize = 48;
40
41/// `Extension Type (16) | Extension Length (16)` — the header of one
42/// Handshake Extension block (§3.2.1 Figure 5).
43pub const HANDSHAKE_EXT_BLOCK_HEADER_LEN: usize = 4;
44
45/// Bytes of `Extension Contents` per `Extension Length` unit (§3.2.1: the
46/// length is "in a number of 32-bit words").
47pub const HANDSHAKE_EXT_WORD_LEN: usize = 4;
48
49/// Byte offset of the `Extension Length` field inside an extension block's
50/// header (§3.2.1, Figure 4).
51const HS_EXT_BLOCK_LEN_OFFSET: usize = 2;
52
53/// Byte offsets of the Handshake CIF fields (§3.2.1, Figure 5).
54const CIF_ENCRYPTION_OFFSET: usize = 4;
55const CIF_INITIAL_SEQ_OFFSET: usize = 8;
56const CIF_MTU_OFFSET: usize = 12;
57const CIF_FLOW_WINDOW_OFFSET: usize = 16;
58const CIF_HANDSHAKE_TYPE_OFFSET: usize = 20;
59const CIF_SOCKET_ID_OFFSET: usize = 24;
60const CIF_SYN_COOKIE_OFFSET: usize = 28;
61const CIF_PEER_IP_OFFSET: usize = 32;
62
63/// Bytes in one IPv4 address word of the peer-IP array.
64const IPV4_ADDR_LEN: usize = 4;
65/// IPv4 address words a Handshake CIF's `SRTPeerIP` field carries
66/// (`draft-sharabayko-srt-01` §3.2.1, Figure 5).
67pub const PEER_IP_WORDS: usize = 4;
68
69/// Shifts and mask of the Handshake CIF's second word: `Encryption Field`
70/// above `Extension Field` (§3.2.1, Figure 5).
71const CIF_ENCRYPTION_SHIFT: u32 = 16;
72const CIF_EXTENSION_MASK: u32 = 0xFFFF;
73
74/// Byte offsets of the Handshake Extension Message fields (§3.2.1.1,
75/// Figure 6).
76const HS_EXT_FLAGS_OFFSET: usize = 4;
77const HS_EXT_RECEIVER_DELAY_OFFSET: usize = 8;
78const HS_EXT_SENDER_DELAY_OFFSET: usize = 10;
79
80/// Byte offset of a group membership extension's second word, and the shifts
81/// and mask of the fields packed into it (§3.2.1.4, Figure 10).
82const GROUP_MEMBERSHIP_FIELDS_OFFSET: usize = 4;
83const GROUP_TYPE_SHIFT: u32 = 24;
84const GROUP_FLAGS_SHIFT: u32 = 16;
85const GROUP_WEIGHT_MASK: u32 = 0xFFFF;
86
87/// `Encryption Field` wire values (§3.2.1, Table 2). Crate-private: they back
88/// [`EncryptionField`]'s conversions, which the enum exposes.
89pub(crate) const ENCRYPTION_FIELD_NONE: u16 = 0;
90/// AES-128.
91pub(crate) const ENCRYPTION_FIELD_AES_128: u16 = 2;
92/// AES-192.
93pub(crate) const ENCRYPTION_FIELD_AES_192: u16 = 3;
94/// AES-256.
95pub(crate) const ENCRYPTION_FIELD_AES_256: u16 = 4;
96
97/// `Encryption Field`: block cipher family and key size advertised in the
98/// handshake (`draft-sharabayko-srt-01` §3.2.1, Table 2).
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100#[cfg_attr(feature = "serde", derive(serde::Serialize))]
101#[non_exhaustive]
102pub enum EncryptionField {
103    /// `0`: no encryption advertised.
104    NoEncryption,
105    /// `2`: AES-128 (the default).
106    Aes128,
107    /// `3`: AES-192.
108    Aes192,
109    /// `4`: AES-256.
110    Aes256,
111    /// A value Table 2 does not define (includes `1`).
112    Reserved(u16),
113}
114
115impl EncryptionField {
116    /// Decode the 16-bit `Encryption Field`.
117    pub fn from_bits(v: u16) -> Self {
118        match v {
119            ENCRYPTION_FIELD_NONE => EncryptionField::NoEncryption,
120            ENCRYPTION_FIELD_AES_128 => EncryptionField::Aes128,
121            ENCRYPTION_FIELD_AES_192 => EncryptionField::Aes192,
122            ENCRYPTION_FIELD_AES_256 => EncryptionField::Aes256,
123            other => EncryptionField::Reserved(other),
124        }
125    }
126
127    /// The wire value.
128    pub fn to_bits(self) -> u16 {
129        match self {
130            EncryptionField::NoEncryption => ENCRYPTION_FIELD_NONE,
131            EncryptionField::Aes128 => ENCRYPTION_FIELD_AES_128,
132            EncryptionField::Aes192 => ENCRYPTION_FIELD_AES_192,
133            EncryptionField::Aes256 => ENCRYPTION_FIELD_AES_256,
134            EncryptionField::Reserved(v) => v,
135        }
136    }
137
138    /// Spec label.
139    pub fn name(&self) -> &'static str {
140        match self {
141            EncryptionField::NoEncryption => "no encryption advertised",
142            EncryptionField::Aes128 => "AES-128",
143            EncryptionField::Aes192 => "AES-192",
144            EncryptionField::Aes256 => "AES-256",
145            EncryptionField::Reserved(_) => "reserved",
146        }
147    }
148}
149
150broadcast_core::impl_spec_display!(EncryptionField, Reserved);
151
152/// `Handshake Type` wire values (§3.2.1, Table 4). Crate-private: they back
153/// [`HandshakeType`]'s conversions, which the enum exposes.
154pub(crate) const HANDSHAKE_TYPE_DONE: u32 = 0xFFFF_FFFD;
155/// AGREEMENT.
156pub(crate) const HANDSHAKE_TYPE_AGREEMENT: u32 = 0xFFFF_FFFE;
157/// CONCLUSION.
158pub(crate) const HANDSHAKE_TYPE_CONCLUSION: u32 = 0xFFFF_FFFF;
159/// WAVEHAND.
160pub(crate) const HANDSHAKE_TYPE_WAVEHAND: u32 = 0x0000_0000;
161/// INDUCTION.
162pub(crate) const HANDSHAKE_TYPE_INDUCTION: u32 = 0x0000_0001;
163
164/// `Handshake Type` (`draft-sharabayko-srt-01` §3.2.1, Table 4).
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
166#[cfg_attr(feature = "serde", derive(serde::Serialize))]
167#[non_exhaustive]
168pub enum HandshakeType {
169    /// `0xFFFFFFFD`.
170    Done,
171    /// `0xFFFFFFFE`.
172    Agreement,
173    /// `0xFFFFFFFF`.
174    Conclusion,
175    /// `0x00000000`.
176    Wavehand,
177    /// `0x00000001`.
178    Induction,
179    /// A value Table 4 does not define (real SRT implementations also use
180    /// this range for `REJ_*` rejection-reason codes, not standardised here).
181    Reserved(u32),
182}
183
184impl HandshakeType {
185    /// Decode the 32-bit `Handshake Type`.
186    pub fn from_bits(v: u32) -> Self {
187        match v {
188            HANDSHAKE_TYPE_DONE => HandshakeType::Done,
189            HANDSHAKE_TYPE_AGREEMENT => HandshakeType::Agreement,
190            HANDSHAKE_TYPE_CONCLUSION => HandshakeType::Conclusion,
191            HANDSHAKE_TYPE_WAVEHAND => HandshakeType::Wavehand,
192            HANDSHAKE_TYPE_INDUCTION => HandshakeType::Induction,
193            other => HandshakeType::Reserved(other),
194        }
195    }
196
197    /// The wire value.
198    pub fn to_bits(self) -> u32 {
199        match self {
200            HandshakeType::Done => HANDSHAKE_TYPE_DONE,
201            HandshakeType::Agreement => HANDSHAKE_TYPE_AGREEMENT,
202            HandshakeType::Conclusion => HANDSHAKE_TYPE_CONCLUSION,
203            HandshakeType::Wavehand => HANDSHAKE_TYPE_WAVEHAND,
204            HandshakeType::Induction => HANDSHAKE_TYPE_INDUCTION,
205            HandshakeType::Reserved(v) => v,
206        }
207    }
208
209    /// Spec label.
210    pub fn name(&self) -> &'static str {
211        match self {
212            HandshakeType::Done => "DONE",
213            HandshakeType::Agreement => "AGREEMENT",
214            HandshakeType::Conclusion => "CONCLUSION",
215            HandshakeType::Wavehand => "WAVEHAND",
216            HandshakeType::Induction => "INDUCTION",
217            HandshakeType::Reserved(_) => "reserved",
218        }
219    }
220}
221
222broadcast_core::impl_spec_display!(HandshakeType, Reserved);
223
224/// `Extension Field` bitmask values (§3.2.1, Table 3). Only meaningful on a
225/// CONCLUSION handshake; on an INDUCTION response this 16-bit field is
226/// instead echoed back opaquely by the Listener.
227pub const HS_EXT_FLAG_HSREQ: u16 = 0x0001;
228/// KMREQ.
229pub const HS_EXT_FLAG_KMREQ: u16 = 0x0002;
230/// CONFIG.
231pub const HS_EXT_FLAG_CONFIG: u16 = 0x0004;
232
233/// The `Extension Field` (§3.2.1, Table 3) — a 16-bit bitmask on a CONCLUSION
234/// handshake, or an opaque echoed value on an INDUCTION response.
235#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
236#[cfg_attr(feature = "serde", derive(serde::Serialize))]
237pub struct HandshakeExtensionFlags(u16);
238
239impl HandshakeExtensionFlags {
240    /// The extension field with the wire value `bits`.
241    #[must_use]
242    pub const fn new(bits: u16) -> Self {
243        Self(bits)
244    }
245
246    /// The wire value.
247    #[must_use]
248    pub const fn get(self) -> u16 {
249        self.0
250    }
251
252    /// `HSREQ` bit set.
253    pub fn hsreq(self) -> bool {
254        self.0 & HS_EXT_FLAG_HSREQ != 0
255    }
256    /// `KMREQ` bit set.
257    pub fn kmreq(self) -> bool {
258        self.0 & HS_EXT_FLAG_KMREQ != 0
259    }
260    /// `CONFIG` bit set.
261    pub fn config(self) -> bool {
262        self.0 & HS_EXT_FLAG_CONFIG != 0
263    }
264}
265
266/// `Extension Type` wire values (§3.2.1, Table 5).
267pub const EXT_TYPE_HSREQ: u16 = 1;
268/// `SRT_CMD_HSRSP`.
269pub const EXT_TYPE_HSRSP: u16 = 2;
270/// `SRT_CMD_KMREQ` — also used as the control-packet `Subtype` for a Key
271/// Material message delivered as a User-Defined control packet (§3.2.2).
272pub const EXT_TYPE_KMREQ: u16 = 3;
273/// `SRT_CMD_KMRSP`.
274pub const EXT_TYPE_KMRSP: u16 = 4;
275/// `SRT_CMD_SID`.
276pub const EXT_TYPE_SID: u16 = 5;
277/// `SRT_CMD_CONGESTION`.
278pub const EXT_TYPE_CONGESTION: u16 = 6;
279/// `SRT_CMD_FILTER`.
280pub const EXT_TYPE_FILTER: u16 = 7;
281/// `SRT_CMD_GROUP`.
282pub const EXT_TYPE_GROUP: u16 = 8;
283
284/// Handshake Extension `Extension Type` (`draft-sharabayko-srt-01` §3.2.1,
285/// Table 5).
286#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
287#[cfg_attr(feature = "serde", derive(serde::Serialize))]
288#[non_exhaustive]
289pub enum ExtensionType {
290    /// `1`: `SRT_CMD_HSREQ` — Handshake Extension request (§3.2.1.1).
291    HsReq,
292    /// `2`: `SRT_CMD_HSRSP` — Handshake Extension response (§3.2.1.1).
293    HsRsp,
294    /// `3`: `SRT_CMD_KMREQ` — Key Material request (§3.2.1.2).
295    KmReq,
296    /// `4`: `SRT_CMD_KMRSP` — Key Material response (§3.2.1.2).
297    KmRsp,
298    /// `5`: `SRT_CMD_SID` — Stream ID (§3.2.1.3).
299    Sid,
300    /// `6`: `SRT_CMD_CONGESTION`.
301    Congestion,
302    /// `7`: `SRT_CMD_FILTER`.
303    Filter,
304    /// `8`: `SRT_CMD_GROUP` — Group Membership (§3.2.1.4).
305    Group,
306    /// A value Table 5 does not define.
307    Reserved(u16),
308}
309
310impl ExtensionType {
311    /// Decode the 16-bit `Extension Type`.
312    pub fn from_bits(v: u16) -> Self {
313        match v {
314            EXT_TYPE_HSREQ => ExtensionType::HsReq,
315            EXT_TYPE_HSRSP => ExtensionType::HsRsp,
316            EXT_TYPE_KMREQ => ExtensionType::KmReq,
317            EXT_TYPE_KMRSP => ExtensionType::KmRsp,
318            EXT_TYPE_SID => ExtensionType::Sid,
319            EXT_TYPE_CONGESTION => ExtensionType::Congestion,
320            EXT_TYPE_FILTER => ExtensionType::Filter,
321            EXT_TYPE_GROUP => ExtensionType::Group,
322            other => ExtensionType::Reserved(other),
323        }
324    }
325
326    /// The wire value.
327    pub fn to_bits(self) -> u16 {
328        match self {
329            ExtensionType::HsReq => EXT_TYPE_HSREQ,
330            ExtensionType::HsRsp => EXT_TYPE_HSRSP,
331            ExtensionType::KmReq => EXT_TYPE_KMREQ,
332            ExtensionType::KmRsp => EXT_TYPE_KMRSP,
333            ExtensionType::Sid => EXT_TYPE_SID,
334            ExtensionType::Congestion => EXT_TYPE_CONGESTION,
335            ExtensionType::Filter => EXT_TYPE_FILTER,
336            ExtensionType::Group => EXT_TYPE_GROUP,
337            ExtensionType::Reserved(v) => v,
338        }
339    }
340
341    /// Spec label.
342    pub fn name(&self) -> &'static str {
343        match self {
344            ExtensionType::HsReq => "SRT_CMD_HSREQ",
345            ExtensionType::HsRsp => "SRT_CMD_HSRSP",
346            ExtensionType::KmReq => "SRT_CMD_KMREQ",
347            ExtensionType::KmRsp => "SRT_CMD_KMRSP",
348            ExtensionType::Sid => "SRT_CMD_SID",
349            ExtensionType::Congestion => "SRT_CMD_CONGESTION",
350            ExtensionType::Filter => "SRT_CMD_FILTER",
351            ExtensionType::Group => "SRT_CMD_GROUP",
352            ExtensionType::Reserved(_) => "reserved",
353        }
354    }
355}
356
357broadcast_core::impl_spec_display!(ExtensionType, Reserved);
358
359/// `SRT Flags` bitmask values of the Handshake Extension Message (§3.2.1.1.1,
360/// Table 6).
361pub const HS_MSG_FLAG_TSBPDSND: u32 = 0x0000_0001;
362/// TSBPDRCV.
363pub const HS_MSG_FLAG_TSBPDRCV: u32 = 0x0000_0002;
364/// CRYPT.
365pub const HS_MSG_FLAG_CRYPT: u32 = 0x0000_0004;
366/// TLPKTDROP.
367pub const HS_MSG_FLAG_TLPKTDROP: u32 = 0x0000_0008;
368/// PERIODICNAK.
369pub const HS_MSG_FLAG_PERIODICNAK: u32 = 0x0000_0010;
370/// REXMITFLG.
371pub const HS_MSG_FLAG_REXMITFLG: u32 = 0x0000_0020;
372/// STREAM.
373pub const HS_MSG_FLAG_STREAM: u32 = 0x0000_0040;
374/// PACKET_FILTER.
375pub const HS_MSG_FLAG_PACKET_FILTER: u32 = 0x0000_0080;
376
377/// `SRT Flags` of a Handshake Extension Message (§3.2.1.1.1, Table 6).
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
379#[cfg_attr(feature = "serde", derive(serde::Serialize))]
380pub struct HandshakeExtensionMessageFlags(u32);
381
382impl HandshakeExtensionMessageFlags {
383    /// The SRT flags with the wire value `bits`.
384    #[must_use]
385    pub const fn new(bits: u32) -> Self {
386        Self(bits)
387    }
388
389    /// The wire value.
390    #[must_use]
391    pub const fn get(self) -> u32 {
392        self.0
393    }
394
395    /// `TSBPDSND`: TSBPD is used for sending.
396    pub fn tsbpdsnd(self) -> bool {
397        self.0 & HS_MSG_FLAG_TSBPDSND != 0
398    }
399    /// `TSBPDRCV`: TSBPD is used for receiving.
400    pub fn tsbpdrcv(self) -> bool {
401        self.0 & HS_MSG_FLAG_TSBPDRCV != 0
402    }
403    /// Legacy flag: peer understands the data packet `KK` field. MUST be set.
404    pub fn crypt(self) -> bool {
405        self.0 & HS_MSG_FLAG_CRYPT != 0
406    }
407    /// Too-late packet drop will be used.
408    pub fn tlpktdrop(self) -> bool {
409        self.0 & HS_MSG_FLAG_TLPKTDROP != 0
410    }
411    /// `PERIODICNAK`: the peer will send periodic NAK packets.
412    pub fn periodicnak(self) -> bool {
413        self.0 & HS_MSG_FLAG_PERIODICNAK != 0
414    }
415    /// Legacy flag: peer understands the data packet `R` field. MUST be set.
416    pub fn rexmitflg(self) -> bool {
417        self.0 & HS_MSG_FLAG_REXMITFLG != 0
418    }
419    /// Buffer mode (`true`) vs message mode (`false`).
420    pub fn stream(self) -> bool {
421        self.0 & HS_MSG_FLAG_STREAM != 0
422    }
423    /// `PACKET_FILTER`: the peer supports packet filter.
424    pub fn packet_filter(self) -> bool {
425        self.0 & HS_MSG_FLAG_PACKET_FILTER != 0
426    }
427}
428
429/// Handshake Extension Message contents (§3.2.1.1, Figure 6) — the payload of
430/// an [`ExtensionType::HsReq`] / [`ExtensionType::HsRsp`] block.
431#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
432#[cfg_attr(feature = "serde", derive(serde::Serialize))]
433pub struct HsExtMessage {
434    /// SRT library version: `major * 0x10000 + minor * 0x100 + patch`.
435    pub srt_version: u32,
436    /// SRT configuration flags.
437    pub srt_flags: HandshakeExtensionMessageFlags,
438    /// Receiver TSBPD Delay (the wire field is whole milliseconds).
439    pub receiver_tsbpd_delay: Duration,
440    /// Sender TSBPD Delay (the wire field is whole milliseconds).
441    pub sender_tsbpd_delay: Duration,
442}
443
444/// Wire length of a Handshake Extension Message (Figure 6).
445pub const HS_EXT_MESSAGE_LEN: usize = 12;
446
447/// A TSBPD delay as the whole milliseconds its `u16` wire field carries; a
448/// sub-millisecond remainder is dropped and anything past `u16::MAX` ms
449/// saturates.
450fn wire_delay_ms(delay: Duration) -> u16 {
451    u16::try_from(delay.as_millis()).unwrap_or(u16::MAX)
452}
453
454impl HsExtMessage {
455    /// Parse a Handshake Extension Message from an extension block's
456    /// contents (must be exactly 12 bytes).
457    pub fn parse(bytes: &[u8]) -> Result<Self> {
458        if bytes.len() != HS_EXT_MESSAGE_LEN {
459            return Err(Error::BufferTooShort(BufferTooShort::new(
460                HS_EXT_MESSAGE_LEN,
461                bytes.len(),
462                "handshake extension message",
463            )));
464        }
465        Ok(HsExtMessage {
466            srt_version: broadcast_core::wire::Reader::at(bytes, 0).u32("srt_version")?,
467            srt_flags: HandshakeExtensionMessageFlags::new(
468                broadcast_core::wire::Reader::at(bytes, HS_EXT_FLAGS_OFFSET).u32("srt_flags")?,
469            ),
470            receiver_tsbpd_delay: Duration::from_millis(u64::from(
471                broadcast_core::wire::Reader::at(bytes, HS_EXT_RECEIVER_DELAY_OFFSET)
472                    .u16("receiver_tsbpd_delay")?,
473            )),
474            sender_tsbpd_delay: Duration::from_millis(u64::from(
475                broadcast_core::wire::Reader::at(bytes, HS_EXT_SENDER_DELAY_OFFSET)
476                    .u16("sender_tsbpd_delay")?,
477            )),
478        })
479    }
480
481    /// Serialize into a fresh 12-byte buffer.
482    pub fn to_bytes(&self) -> [u8; HS_EXT_MESSAGE_LEN] {
483        let mut buf = [0u8; HS_EXT_MESSAGE_LEN];
484        put_be32(&mut buf, 0, self.srt_version);
485        put_be32(&mut buf, HS_EXT_FLAGS_OFFSET, self.srt_flags.0);
486        put_be16(
487            &mut buf,
488            HS_EXT_RECEIVER_DELAY_OFFSET,
489            wire_delay_ms(self.receiver_tsbpd_delay),
490        );
491        put_be16(
492            &mut buf,
493            HS_EXT_SENDER_DELAY_OFFSET,
494            wire_delay_ms(self.sender_tsbpd_delay),
495        );
496        buf
497    }
498}
499
500impl<'a> broadcast_core::Parse<'a> for HsExtMessage {
501    type Error = crate::Error;
502
503    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
504        HsExtMessage::parse(bytes)
505    }
506}
507
508impl broadcast_core::Serialize for HsExtMessage {
509    type Error = crate::Error;
510
511    fn serialized_len(&self) -> usize {
512        HS_EXT_MESSAGE_LEN
513    }
514
515    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
516        if buf.len() < HS_EXT_MESSAGE_LEN {
517            return Err(crate::Error::OutputBufferTooSmall(
518                OutputBufferTooSmall::new(HS_EXT_MESSAGE_LEN, buf.len(), "HsExtMessage"),
519            ));
520        }
521        buf[..HS_EXT_MESSAGE_LEN].copy_from_slice(&self.to_bytes());
522        Ok(HS_EXT_MESSAGE_LEN)
523    }
524}
525
526/// `Type` (Group Type) wire values of the Group Membership Extension
527/// (§3.2.1.4).
528pub const GROUP_TYPE_UNDEFINED: u8 = 0;
529/// Broadcast.
530pub const GROUP_TYPE_BROADCAST: u8 = 1;
531/// Main/backup.
532pub const GROUP_TYPE_MAIN_BACKUP: u8 = 2;
533/// Balancing.
534pub const GROUP_TYPE_BALANCING: u8 = 3;
535/// Multicast (reserved for future use).
536pub const GROUP_TYPE_MULTICAST: u8 = 4;
537
538/// Group Membership Extension `Type` (`draft-sharabayko-srt-01` §3.2.1.4,
539/// `SRT_GTYPE_*`).
540#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
541#[cfg_attr(feature = "serde", derive(serde::Serialize))]
542#[non_exhaustive]
543pub enum GroupType {
544    /// `0`: undefined group type.
545    Undefined,
546    /// `1`: broadcast group type.
547    Broadcast,
548    /// `2`: main/backup group type.
549    MainBackup,
550    /// `3`: balancing group type.
551    Balancing,
552    /// `4`: multicast group type (reserved for future use).
553    Multicast,
554    /// A value not defined above.
555    Reserved(u8),
556}
557
558impl GroupType {
559    /// Decode the 8-bit `Type`.
560    pub fn from_bits(v: u8) -> Self {
561        match v {
562            GROUP_TYPE_UNDEFINED => GroupType::Undefined,
563            GROUP_TYPE_BROADCAST => GroupType::Broadcast,
564            GROUP_TYPE_MAIN_BACKUP => GroupType::MainBackup,
565            GROUP_TYPE_BALANCING => GroupType::Balancing,
566            GROUP_TYPE_MULTICAST => GroupType::Multicast,
567            other => GroupType::Reserved(other),
568        }
569    }
570
571    /// The wire value.
572    pub fn to_bits(self) -> u8 {
573        match self {
574            GroupType::Undefined => GROUP_TYPE_UNDEFINED,
575            GroupType::Broadcast => GROUP_TYPE_BROADCAST,
576            GroupType::MainBackup => GROUP_TYPE_MAIN_BACKUP,
577            GroupType::Balancing => GROUP_TYPE_BALANCING,
578            GroupType::Multicast => GROUP_TYPE_MULTICAST,
579            GroupType::Reserved(v) => v,
580        }
581    }
582
583    /// Spec label.
584    pub fn name(&self) -> &'static str {
585        match self {
586            GroupType::Undefined => "undefined",
587            GroupType::Broadcast => "broadcast",
588            GroupType::MainBackup => "main/backup",
589            GroupType::Balancing => "balancing",
590            GroupType::Multicast => "multicast",
591            GroupType::Reserved(_) => "reserved",
592        }
593    }
594}
595
596broadcast_core::impl_spec_display!(GroupType, Reserved);
597
598/// Group Membership Extension `Flags` (§3.2.1.4, Figure 9): only the `M` bit
599/// is defined.
600#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
601#[cfg_attr(feature = "serde", derive(serde::Serialize))]
602pub struct GroupFlags(u8);
603
604impl GroupFlags {
605    /// The flags with the wire value `value`.
606    #[must_use]
607    pub const fn new(value: u8) -> Self {
608        Self(value)
609    }
610
611    /// The wrapped value.
612    #[must_use]
613    pub const fn get(self) -> u8 {
614        self.0
615    }
616}
617
618impl GroupFlags {
619    const M_BIT: u8 = 0x01;
620
621    /// `M`: synchronize on message numbers (`true`) vs sequence numbers
622    /// (`false`).
623    pub fn message_number_sync(self) -> bool {
624        self.0 & Self::M_BIT != 0
625    }
626}
627
628/// Group Membership Extension (§3.2.1.4, Figure 8) — the payload of an
629/// [`ExtensionType::Group`] block.
630#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
631#[cfg_attr(feature = "serde", derive(serde::Serialize))]
632pub struct GroupMembershipExtension {
633    /// Group ID.
634    pub group_id: u32,
635    /// Group Type.
636    pub group_type: GroupType,
637    /// Flags.
638    pub flags: GroupFlags,
639    /// Link priority (main/backup) or otherwise reserved.
640    pub weight: u16,
641}
642
643/// Wire length of a Group Membership Extension (Figure 8).
644pub const GROUP_MEMBERSHIP_EXT_LEN: usize = 8;
645
646impl GroupMembershipExtension {
647    /// Parse from an extension block's contents (must be exactly 8 bytes).
648    pub fn parse(bytes: &[u8]) -> Result<Self> {
649        if bytes.len() != GROUP_MEMBERSHIP_EXT_LEN {
650            return Err(Error::BufferTooShort(BufferTooShort::new(
651                GROUP_MEMBERSHIP_EXT_LEN,
652                bytes.len(),
653                "group membership extension",
654            )));
655        }
656        let group_id = broadcast_core::wire::Reader::at(bytes, 0).u32("group_id")?;
657        let word1 =
658            broadcast_core::wire::Reader::at(bytes, GROUP_MEMBERSHIP_FIELDS_OFFSET).u32("word1")?;
659        Ok(GroupMembershipExtension {
660            group_id,
661            group_type: GroupType::from_bits((word1 >> GROUP_TYPE_SHIFT) as u8),
662            flags: GroupFlags::new((word1 >> GROUP_FLAGS_SHIFT) as u8),
663            weight: (word1 & GROUP_WEIGHT_MASK) as u16,
664        })
665    }
666
667    /// Serialize into a fresh 8-byte buffer.
668    pub fn to_bytes(&self) -> [u8; GROUP_MEMBERSHIP_EXT_LEN] {
669        let mut buf = [0u8; GROUP_MEMBERSHIP_EXT_LEN];
670        let word1 = (u32::from(self.group_type.to_bits()) << GROUP_TYPE_SHIFT)
671            | (u32::from(self.flags.0) << GROUP_FLAGS_SHIFT)
672            | u32::from(self.weight);
673        put_be32(&mut buf, 0, self.group_id);
674        put_be32(&mut buf, GROUP_MEMBERSHIP_FIELDS_OFFSET, word1);
675        buf
676    }
677}
678
679impl<'a> broadcast_core::Parse<'a> for GroupMembershipExtension {
680    type Error = crate::Error;
681
682    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
683        GroupMembershipExtension::parse(bytes)
684    }
685}
686
687impl broadcast_core::Serialize for GroupMembershipExtension {
688    type Error = crate::Error;
689
690    fn serialized_len(&self) -> usize {
691        GROUP_MEMBERSHIP_EXT_LEN
692    }
693
694    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
695        if buf.len() < GROUP_MEMBERSHIP_EXT_LEN {
696            return Err(crate::Error::OutputBufferTooSmall(
697                OutputBufferTooSmall::new(
698                    GROUP_MEMBERSHIP_EXT_LEN,
699                    buf.len(),
700                    "GroupMembershipExtension",
701                ),
702            ));
703        }
704        buf[..GROUP_MEMBERSHIP_EXT_LEN].copy_from_slice(&self.to_bytes());
705        Ok(GROUP_MEMBERSHIP_EXT_LEN)
706    }
707}
708
709/// One decoded Handshake Extension block (§3.2.1): `Extension Type` /
710/// `Extension Length` / `Extension Contents`. Serialization writes any length,
711/// so [`build_extension_block`] is the checked path for a block assembled from
712/// scratch. Serialization writes any length,
713/// so [`build_extension_block`] is the checked path for a block assembled from
714/// scratch. Data-carrying (borrows the raw
715/// contents) — decode the contents with [`Self::as_hs_ext_message`],
716/// [`Self::as_key_material`], [`Self::as_stream_id`], or
717/// [`Self::as_group_membership`] as appropriate for [`Self::ext_type`].
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
719#[cfg_attr(feature = "serde", derive(serde::Serialize))]
720pub struct HandshakeExtensionBlock<'a> {
721    /// The extension's type.
722    pub ext_type: ExtensionType,
723    /// The raw contents (`Extension Length * 4` bytes).
724    pub contents: &'a [u8],
725}
726
727impl<'a> HandshakeExtensionBlock<'a> {
728    /// Decode [`Self::contents`] as a Handshake Extension Message (§3.2.1.1)
729    /// — valid for [`ExtensionType::HsReq`] / [`ExtensionType::HsRsp`].
730    pub fn as_hs_ext_message(&self) -> Result<HsExtMessage> {
731        HsExtMessage::parse(self.contents)
732    }
733
734    /// Decode [`Self::contents`] as a Key Material message (§3.2.2) — valid
735    /// for [`ExtensionType::KmReq`] / [`ExtensionType::KmRsp`].
736    pub fn as_key_material(&self) -> Result<KeyMaterial<'a>> {
737        KeyMaterial::parse(self.contents)
738    }
739
740    /// Decode [`Self::contents`] as the Stream ID extension (§3.2.1.3) —
741    /// valid for [`ExtensionType::Sid`].
742    ///
743    /// Per §3.2.1.3 "The content is stored as 32-bit little endian words":
744    /// each 4-byte word of `contents` is byte-reversed before concatenation,
745    /// trailing NUL padding is trimmed, and the result is validated as UTF-8.
746    pub fn as_stream_id(&self) -> Result<String> {
747        if !self.contents.len().is_multiple_of(HANDSHAKE_EXT_WORD_LEN) {
748            return Err(Error::BufferTooShort(BufferTooShort::new(
749                self.contents.len().div_ceil(HANDSHAKE_EXT_WORD_LEN) * HANDSHAKE_EXT_WORD_LEN,
750                self.contents.len(),
751                "stream ID extension (not a whole number of 4-byte words)",
752            )));
753        }
754        let mut bytes = Vec::with_capacity(self.contents.len());
755        for word in self.contents.chunks_exact(HANDSHAKE_EXT_WORD_LEN) {
756            bytes.extend(word.iter().rev());
757        }
758        while bytes.last() == Some(&0u8) {
759            bytes.pop();
760        }
761        String::from_utf8(bytes).map_err(|_| Error::InvalidStreamIdUtf8)
762    }
763
764    /// Decode [`Self::contents`] as a Group Membership Extension (§3.2.1.4) —
765    /// valid for [`ExtensionType::Group`].
766    pub fn as_group_membership(&self) -> Result<GroupMembershipExtension> {
767        GroupMembershipExtension::parse(self.contents)
768    }
769}
770
771/// Encode the Stream ID extension's 32-bit-little-endian-word storage
772/// (§3.2.1.3) from a plain UTF-8 stream id string, padding with `0x00` up to
773/// the next 4-byte boundary. Inverse of [`HandshakeExtensionBlock::as_stream_id`].
774pub fn encode_stream_id(id: &str) -> Vec<u8> {
775    let mut bytes = Vec::from(id.as_bytes());
776    while bytes.len() % HANDSHAKE_EXT_WORD_LEN != 0 {
777        bytes.push(0);
778    }
779    let mut out = Vec::with_capacity(bytes.len());
780    for word in bytes.chunks_exact(HANDSHAKE_EXT_WORD_LEN) {
781        out.extend(word.iter().rev());
782    }
783    out
784}
785
786/// Build one Handshake Extension block's raw bytes (`Extension Type` +
787/// `Extension Length` + `Extension Contents`, §3.2.1) — append the result of
788/// repeated calls to chain multiple blocks.
789///
790/// # Errors
791/// [`Error::FieldOverflow`] if `contents` is not a whole number of 4-byte
792/// words, or has more than `0xFFFF` such words.
793pub fn build_extension_block(ext_type: ExtensionType, contents: &[u8]) -> Result<Vec<u8>> {
794    if !contents.len().is_multiple_of(HANDSHAKE_EXT_WORD_LEN) {
795        return Err(Error::InvalidField(InvalidField::new(
796            "Extension Contents",
797            "length must be a whole number of 4-byte words",
798        )));
799    }
800    let words = contents.len() / HANDSHAKE_EXT_WORD_LEN;
801    let words_u16 = broadcast_core::len::fit_u16(words, "Extension Length")?;
802    let mut out = Vec::with_capacity(HANDSHAKE_EXT_BLOCK_HEADER_LEN + contents.len());
803    out.extend_from_slice(&ext_type.to_bits().to_be_bytes());
804    out.extend_from_slice(&words_u16.to_be_bytes());
805    out.extend_from_slice(contents);
806    Ok(out)
807}
808
809/// The decoded Handshake Extension blocks (§3.2.1). Each block's contents
810/// borrow the packet's cipher-independent extension section, so a parsed
811/// handshake costs one decode at the edge and a hand-built one is checked when
812/// it is built (see [`build_extension_block`]).
813#[derive(Debug, Clone, PartialEq, Eq, Hash)]
814#[cfg_attr(feature = "serde", derive(serde::Serialize))]
815pub struct HandshakeExtensions<'a>(pub Vec<HandshakeExtensionBlock<'a>>);
816
817impl<'a> HandshakeExtensions<'a> {
818    /// The blocks.
819    pub fn iter(&self) -> core::slice::Iter<'_, HandshakeExtensionBlock<'a>> {
820        self.0.iter()
821    }
822
823    /// Decode the extension section of a Handshake CIF, one block per
824    /// `Extension Type (16) | Extension Length (16) | Extension Contents`.
825    ///
826    /// # Errors
827    /// [`Error::BufferTooShort`] for a trailing partial block header, and
828    /// [`Error::ExtensionOverrun`] for a block whose declared length runs past
829    /// the bytes present.
830    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
831        let mut rest = bytes;
832        let mut blocks = Vec::with_capacity(rest.len() / HANDSHAKE_EXT_BLOCK_HEADER_LEN);
833        while !rest.is_empty() {
834            if rest.len() < HANDSHAKE_EXT_BLOCK_HEADER_LEN {
835                return Err(Error::BufferTooShort(BufferTooShort::new(
836                    HANDSHAKE_EXT_BLOCK_HEADER_LEN,
837                    rest.len(),
838                    "handshake extension block header",
839                )));
840            }
841            let ext_type_bits = broadcast_core::wire::Reader::at(rest, 0).u16("ext_type_bits")?;
842            let ext_len_words = broadcast_core::wire::Reader::at(rest, HS_EXT_BLOCK_LEN_OFFSET)
843                .u16("ext_len_words")?;
844            let ext_len_bytes = usize::from(ext_len_words) * HANDSHAKE_EXT_WORD_LEN;
845            if rest.len() < HANDSHAKE_EXT_BLOCK_HEADER_LEN + ext_len_bytes {
846                return Err(Error::ExtensionOverrun {
847                    declared: ext_len_words,
848                    remaining: rest.len() - HANDSHAKE_EXT_BLOCK_HEADER_LEN,
849                });
850            }
851            blocks.push(HandshakeExtensionBlock {
852                ext_type: ExtensionType::from_bits(ext_type_bits),
853                contents: &rest[HANDSHAKE_EXT_BLOCK_HEADER_LEN
854                    ..HANDSHAKE_EXT_BLOCK_HEADER_LEN + ext_len_bytes],
855            });
856            rest = &rest[HANDSHAKE_EXT_BLOCK_HEADER_LEN + ext_len_bytes..];
857        }
858        Ok(HandshakeExtensions(blocks))
859    }
860}
861
862/// Handshake control packet (§3.2.1, Figure 5).
863#[derive(Debug, Clone, PartialEq, Eq, Hash)]
864#[cfg_attr(feature = "serde", derive(serde::Serialize))]
865pub struct HandshakePacket<'a> {
866    /// Timestamp (§3).
867    pub timestamp: SrtTimestamp,
868    /// Destination Socket ID (§3).
869    pub dest_socket_id: SocketId,
870    /// A base protocol version number (`4` or `5`; `>5` reserved).
871    pub version: u32,
872    /// Block cipher family and key size (Table 2).
873    pub encryption_field: EncryptionField,
874    /// Message-specific extension flags/echo (Table 3, or opaque on
875    /// INDUCTION).
876    pub extension_field: HandshakeExtensionFlags,
877    /// The sequence number of the very first data packet to be sent.
878    pub initial_seq_number: u32,
879    /// Typically `1500` (Ethernet MTU) or less.
880    pub mtu: u32,
881    /// Maximum number of data packets allowed in flight.
882    pub max_flow_window_size: u32,
883    /// The handshake packet type (Table 4).
884    pub handshake_type: HandshakeType,
885    /// The ID of the source SRT socket issuing this handshake packet.
886    pub srt_socket_id: u32,
887    /// Randomized value for processing the handshake.
888    pub syn_cookie: u32,
889    /// IPv4 or IPv6 address of the packet's sender, as 4 wire words (IPv4:
890    /// only the first word is non-zero).
891    pub peer_ip: [u32; PEER_IP_WORDS],
892    /// The trailing Handshake Extension blocks (possibly empty).
893    pub extensions: HandshakeExtensions<'a>,
894}
895
896impl<'a> HandshakePacket<'a> {
897    pub(crate) fn parse_cif(
898        timestamp: SrtTimestamp,
899        dest_socket_id: SocketId,
900        cif: &'a [u8],
901    ) -> Result<Self> {
902        need_in(cif, HANDSHAKE_CIF_FIXED_LEN, "handshake CIF")?;
903        let version = broadcast_core::wire::Reader::at(cif, 0).u32("version")?;
904        let word1 = broadcast_core::wire::Reader::at(cif, CIF_ENCRYPTION_OFFSET).u32("word1")?;
905        let encryption_field = EncryptionField::from_bits((word1 >> CIF_ENCRYPTION_SHIFT) as u16);
906        let extension_field = HandshakeExtensionFlags::new((word1 & CIF_EXTENSION_MASK) as u16);
907        let initial_seq_number = broadcast_core::wire::Reader::at(cif, CIF_INITIAL_SEQ_OFFSET)
908            .u32("initial_seq_number")?;
909        let mtu = broadcast_core::wire::Reader::at(cif, CIF_MTU_OFFSET).u32("mtu")?;
910        let max_flow_window_size = broadcast_core::wire::Reader::at(cif, CIF_FLOW_WINDOW_OFFSET)
911            .u32("max_flow_window_size")?;
912        let handshake_type = HandshakeType::from_bits(
913            broadcast_core::wire::Reader::at(cif, CIF_HANDSHAKE_TYPE_OFFSET)
914                .u32("HandshakeType")?,
915        );
916        let srt_socket_id =
917            broadcast_core::wire::Reader::at(cif, CIF_SOCKET_ID_OFFSET).u32("srt_socket_id")?;
918        let syn_cookie =
919            broadcast_core::wire::Reader::at(cif, CIF_SYN_COOKIE_OFFSET).u32("syn_cookie")?;
920        let mut peer_ip = [0u32; PEER_IP_WORDS];
921        for (word, slot) in peer_ip.iter_mut().enumerate() {
922            *slot =
923                broadcast_core::wire::Reader::at(cif, CIF_PEER_IP_OFFSET + word * IPV4_ADDR_LEN)
924                    .u32("parse_cif")?;
925        }
926        let extensions = HandshakeExtensions::parse(&cif[HANDSHAKE_CIF_FIXED_LEN..])?;
927        Ok(HandshakePacket {
928            timestamp,
929            dest_socket_id,
930            version,
931            encryption_field,
932            extension_field,
933            initial_seq_number,
934            mtu,
935            max_flow_window_size,
936            handshake_type,
937            srt_socket_id,
938            syn_cookie,
939            peer_ip,
940            extensions,
941        })
942    }
943
944    pub(crate) fn cif_len(&self) -> usize {
945        HANDSHAKE_CIF_FIXED_LEN
946            + self
947                .extensions
948                .0
949                .iter()
950                .map(|b| HANDSHAKE_EXT_BLOCK_HEADER_LEN + b.contents.len())
951                .sum::<usize>()
952    }
953
954    pub(crate) fn write_cif(&self, buf: &mut [u8]) -> Result<()> {
955        let word1 = (u32::from(self.encryption_field.to_bits()) << CIF_ENCRYPTION_SHIFT)
956            | u32::from(self.extension_field.0);
957        put_be32(buf, 0, self.version);
958        put_be32(buf, CIF_ENCRYPTION_OFFSET, word1);
959        put_be32(buf, CIF_INITIAL_SEQ_OFFSET, self.initial_seq_number);
960        put_be32(buf, CIF_MTU_OFFSET, self.mtu);
961        put_be32(buf, CIF_FLOW_WINDOW_OFFSET, self.max_flow_window_size);
962        put_be32(
963            buf,
964            CIF_HANDSHAKE_TYPE_OFFSET,
965            self.handshake_type.to_bits(),
966        );
967        put_be32(buf, CIF_SOCKET_ID_OFFSET, self.srt_socket_id);
968        put_be32(buf, CIF_SYN_COOKIE_OFFSET, self.syn_cookie);
969        for (word, value) in self.peer_ip.iter().enumerate() {
970            put_be32(buf, CIF_PEER_IP_OFFSET + word * IPV4_ADDR_LEN, *value);
971        }
972        let mut off = HANDSHAKE_CIF_FIXED_LEN;
973        for block in &self.extensions.0 {
974            let words = broadcast_core::len::fit_u16(
975                block.contents.len() / HANDSHAKE_EXT_WORD_LEN,
976                "Extension Length",
977            )?;
978            put_be16(buf, off, block.ext_type.to_bits());
979            put_be16(buf, off + HS_EXT_BLOCK_LEN_OFFSET, words);
980            off += HANDSHAKE_EXT_BLOCK_HEADER_LEN;
981            buf[off..off + block.contents.len()].copy_from_slice(block.contents);
982            off += block.contents.len();
983        }
984        Ok(())
985    }
986}
987
988#[cfg(test)]
989mod tests {
990    use super::super::SRT_HEADER_LEN;
991    use super::super::control::ControlPacket;
992    use super::*;
993
994    fn sample_no_ext() -> HandshakePacket<'static> {
995        HandshakePacket {
996            timestamp: SrtTimestamp::from_wire(111),
997            dest_socket_id: SocketId::from_wire(222),
998            version: 5,
999            encryption_field: EncryptionField::Aes128,
1000            extension_field: HandshakeExtensionFlags::new(0),
1001            initial_seq_number: 1000,
1002            mtu: 1500,
1003            max_flow_window_size: 8192,
1004            handshake_type: HandshakeType::Induction,
1005            srt_socket_id: 0xABCD_EF01,
1006            syn_cookie: 0x1234_5678,
1007            peer_ip: [0x0A00_0001, 0, 0, 0],
1008            extensions: HandshakeExtensions(Vec::new()),
1009        }
1010    }
1011
1012    #[test]
1013    fn round_trips_hand_computed_bytes_no_extensions() {
1014        let pkt = ControlPacket::Handshake(sample_no_ext());
1015        let mut buf = [0u8; 16 + HANDSHAKE_CIF_FIXED_LEN];
1016        let n = pkt.serialize_into(&mut buf).unwrap();
1017        assert_eq!(n, buf.len());
1018        assert_eq!(&buf[0..4], &0x8000_0000u32.to_be_bytes()); // control type 0
1019        assert_eq!(&buf[16..20], &5u32.to_be_bytes()); // Version
1020        // Extension Field is 0 (no extensions on this sample).
1021        let expected_word1 = u32::from(ENCRYPTION_FIELD_AES_128) << 16;
1022        assert_eq!(&buf[20..24], &expected_word1.to_be_bytes());
1023        assert_eq!(&buf[36..40], &HANDSHAKE_TYPE_INDUCTION.to_be_bytes());
1024        assert_eq!(ControlPacket::parse(&buf).unwrap(), pkt);
1025    }
1026
1027    /// The TSBPD delays travel as whole milliseconds in their `u16` wire
1028    /// field: a sub-millisecond remainder is dropped, never rounded up into a
1029    /// longer peer-side buffer.
1030    #[test]
1031    fn the_tsbpd_delays_are_whole_wire_milliseconds() {
1032        let msg = HsExtMessage {
1033            srt_version: 0x0105_0000,
1034            srt_flags: HandshakeExtensionMessageFlags::new(0),
1035            receiver_tsbpd_delay: Duration::from_micros(120_999),
1036            sender_tsbpd_delay: Duration::from_millis(250),
1037        };
1038        let bytes = msg.to_bytes();
1039        assert_eq!(&bytes[8..10], &120u16.to_be_bytes());
1040        assert_eq!(&bytes[10..12], &250u16.to_be_bytes());
1041        let parsed = HsExtMessage::parse(&bytes).unwrap();
1042        assert_eq!(parsed.receiver_tsbpd_delay, Duration::from_millis(120));
1043        assert_eq!(parsed.sender_tsbpd_delay, Duration::from_millis(250));
1044    }
1045
1046    #[test]
1047    fn round_trips_with_hsreq_and_sid_extensions() {
1048        let hs_msg = HsExtMessage {
1049            srt_version: 0x0105_0000,
1050            srt_flags: HandshakeExtensionMessageFlags::new(
1051                HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV | HS_MSG_FLAG_CRYPT,
1052            ),
1053            receiver_tsbpd_delay: Duration::from_millis(120),
1054            sender_tsbpd_delay: Duration::from_millis(120),
1055        };
1056        let hsreq_block = build_extension_block(ExtensionType::HsReq, &hs_msg.to_bytes()).unwrap();
1057
1058        let sid_contents = encode_stream_id("live/stream1");
1059        let sid_block = build_extension_block(ExtensionType::Sid, &sid_contents).unwrap();
1060
1061        let mut ext_bytes = Vec::new();
1062        ext_bytes.extend_from_slice(&hsreq_block);
1063        ext_bytes.extend_from_slice(&sid_block);
1064
1065        // The typed blocks must encode to exactly the bytes
1066        // `build_extension_block` produced above.
1067        let wire_blocks = HandshakeExtensions::parse(&ext_bytes).unwrap();
1068        let mut hp = sample_no_ext();
1069        hp.handshake_type = HandshakeType::Conclusion;
1070        hp.extension_field = HandshakeExtensionFlags::new(HS_EXT_FLAG_HSREQ);
1071        hp.extensions = wire_blocks;
1072
1073        let pkt = ControlPacket::Handshake(hp.clone());
1074        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
1075        pkt.serialize_into(&mut buf).unwrap();
1076        assert_eq!(
1077            &buf[SRT_HEADER_LEN + HANDSHAKE_CIF_FIXED_LEN..],
1078            &ext_bytes[..]
1079        );
1080        let parsed = ControlPacket::parse(&buf).unwrap();
1081        assert_eq!(parsed, pkt);
1082
1083        if let ControlPacket::Handshake(h) = parsed {
1084            let blocks: Vec<_> = h.extensions.iter().collect();
1085            assert_eq!(blocks.len(), 2);
1086            assert_eq!(blocks[0].ext_type, ExtensionType::HsReq);
1087            assert_eq!(blocks[0].as_hs_ext_message().unwrap(), hs_msg);
1088            assert_eq!(blocks[1].ext_type, ExtensionType::Sid);
1089            assert_eq!(blocks[1].as_stream_id().unwrap(), "live/stream1");
1090        } else {
1091            panic!("expected handshake");
1092        }
1093    }
1094
1095    #[test]
1096    fn stream_id_padding_is_trimmed() {
1097        // "abc" is not a multiple of 4 bytes; encode_stream_id pads with a
1098        // NUL, and as_stream_id must trim it back off.
1099        let contents = encode_stream_id("abc");
1100        assert_eq!(contents.len(), 4);
1101        let block = HandshakeExtensionBlock {
1102            ext_type: ExtensionType::Sid,
1103            contents: &contents,
1104        };
1105        assert_eq!(block.as_stream_id().unwrap(), "abc");
1106    }
1107
1108    #[test]
1109    fn group_membership_extension_round_trips() {
1110        let g = GroupMembershipExtension {
1111            group_id: 42,
1112            group_type: GroupType::MainBackup,
1113            flags: GroupFlags::new(0x01),
1114            weight: 7,
1115        };
1116        let bytes = g.to_bytes();
1117        assert_eq!(GroupMembershipExtension::parse(&bytes).unwrap(), g);
1118        assert!(g.flags.message_number_sync());
1119    }
1120
1121    #[test]
1122    fn extension_overrun_does_not_panic() {
1123        // Declares 0xFFFF words (huge) but supplies none.
1124        let bytes = [0x00, 0x05, 0xFF, 0xFF];
1125        assert!(matches!(
1126            HandshakeExtensions::parse(&bytes),
1127            Err(Error::ExtensionOverrun { .. })
1128        ));
1129    }
1130
1131    /// The lossy-bytes shape is gone: a handshake whose extension section
1132    /// declares a length it does not carry is rejected by the control-packet
1133    /// parser, not handed out as a packet whose later walk fails.
1134    #[test]
1135    fn the_dispatcher_rejects_a_malformed_extension_section() {
1136        let mut hp = sample_no_ext();
1137        let mut buf = alloc::vec![0u8; SRT_HEADER_LEN + HANDSHAKE_CIF_FIXED_LEN];
1138        ControlPacket::Handshake(hp.clone())
1139            .serialize_into(&mut buf)
1140            .unwrap();
1141        hp.extension_field = HandshakeExtensionFlags::new(HS_EXT_FLAG_HSREQ);
1142        buf.extend_from_slice(&[0x00, 0x01, 0xFF, 0xFF]);
1143        assert!(matches!(
1144            ControlPacket::parse(&buf),
1145            Err(Error::ExtensionOverrun { .. })
1146        ));
1147    }
1148
1149    #[test]
1150    fn truncated_extension_header_reports_available_bytes() {
1151        let bytes = [0x00, 0x05, 0x00];
1152        match HandshakeExtensions::parse(&bytes) {
1153            Err(Error::BufferTooShort(b)) => {
1154                assert_eq!(b.need, 4);
1155                assert_eq!(b.have, 3);
1156            }
1157            other => panic!("expected BufferTooShort, got {other:?}"),
1158        }
1159    }
1160
1161    #[test]
1162    fn all_encryption_fields_and_types_round_trip() {
1163        for e in [
1164            EncryptionField::NoEncryption,
1165            EncryptionField::Aes128,
1166            EncryptionField::Aes192,
1167            EncryptionField::Aes256,
1168        ] {
1169            assert_eq!(EncryptionField::from_bits(e.to_bits()), e);
1170        }
1171        for t in [
1172            HandshakeType::Done,
1173            HandshakeType::Agreement,
1174            HandshakeType::Conclusion,
1175            HandshakeType::Wavehand,
1176            HandshakeType::Induction,
1177        ] {
1178            assert_eq!(HandshakeType::from_bits(t.to_bits()), t);
1179        }
1180    }
1181
1182    #[test]
1183    fn every_flag_accessor_reads_only_its_own_bit() {
1184        assert!(HandshakeExtensionFlags::new(HS_EXT_FLAG_HSREQ).hsreq());
1185        assert!(!HandshakeExtensionFlags::new(HS_EXT_FLAG_KMREQ | HS_EXT_FLAG_CONFIG).hsreq());
1186
1187        type Accessor = fn(HandshakeExtensionMessageFlags) -> bool;
1188        let accessors: [(u32, Accessor); 8] = [
1189            (
1190                HS_MSG_FLAG_TSBPDSND,
1191                HandshakeExtensionMessageFlags::tsbpdsnd,
1192            ),
1193            (
1194                HS_MSG_FLAG_TSBPDRCV,
1195                HandshakeExtensionMessageFlags::tsbpdrcv,
1196            ),
1197            (HS_MSG_FLAG_CRYPT, HandshakeExtensionMessageFlags::crypt),
1198            (
1199                HS_MSG_FLAG_TLPKTDROP,
1200                HandshakeExtensionMessageFlags::tlpktdrop,
1201            ),
1202            (
1203                HS_MSG_FLAG_PERIODICNAK,
1204                HandshakeExtensionMessageFlags::periodicnak,
1205            ),
1206            (
1207                HS_MSG_FLAG_REXMITFLG,
1208                HandshakeExtensionMessageFlags::rexmitflg,
1209            ),
1210            (HS_MSG_FLAG_STREAM, HandshakeExtensionMessageFlags::stream),
1211            (
1212                HS_MSG_FLAG_PACKET_FILTER,
1213                HandshakeExtensionMessageFlags::packet_filter,
1214            ),
1215        ];
1216        for (i, (bit, accessor)) in accessors.iter().enumerate() {
1217            assert_eq!(*bit, 1 << i, "Table 6 assigns bit {i}");
1218            for (j, (_, other)) in accessors.iter().enumerate() {
1219                assert_eq!(
1220                    other(HandshakeExtensionMessageFlags::new(*bit)),
1221                    i == j,
1222                    "flag {i} read by accessor {j}"
1223                );
1224            }
1225            assert!(!accessor(HandshakeExtensionMessageFlags::new(!*bit)));
1226            assert!(accessor(HandshakeExtensionMessageFlags::new(u32::MAX)));
1227        }
1228    }
1229}
1230
1231#[cfg(test)]
1232mod enum_tests {
1233    use super::*;
1234
1235    #[test]
1236    fn every_encryption_field_round_trips_its_table_2_wire_value() {
1237        for (field, value) in [
1238            (EncryptionField::NoEncryption, 0u16),
1239            (EncryptionField::Aes128, 2),
1240            (EncryptionField::Aes192, 3),
1241            (EncryptionField::Aes256, 4),
1242        ] {
1243            assert_eq!(field.to_bits(), value, "{}", field.name());
1244            assert_eq!(EncryptionField::from_bits(value), field);
1245        }
1246        // 1 is not assigned by Table 2.
1247        assert_eq!(EncryptionField::from_bits(1), EncryptionField::Reserved(1));
1248    }
1249
1250    #[test]
1251    fn every_handshake_type_round_trips_its_table_4_wire_value() {
1252        for (ty, value) in [
1253            (HandshakeType::Done, 0xFFFF_FFFD),
1254            (HandshakeType::Agreement, 0xFFFF_FFFE),
1255            (HandshakeType::Conclusion, 0xFFFF_FFFF),
1256            (HandshakeType::Wavehand, 0x0000_0000),
1257            (HandshakeType::Induction, 0x0000_0001),
1258        ] {
1259            assert_eq!(ty.to_bits(), value, "{}", ty.name());
1260            assert_eq!(HandshakeType::from_bits(value), ty);
1261        }
1262        assert_eq!(
1263            HandshakeType::from_bits(2),
1264            HandshakeType::Reserved(2),
1265            "2 is not assigned by Table 4"
1266        );
1267    }
1268}