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