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