Skip to main content

srt_runtime/
caller.rs

1//! Caller-side handshake engine — `draft-sharabayko-srt-01` §4.3.1
2//! (Caller-Listener Handshake), Caller role.
3//!
4//! [`CallerHandshake`] is a driveable, sans-IO state machine:
5//! [`CallerHandshake::start`] returns the INDUCTION handshake bytes to send;
6//! [`CallerHandshake::feed`] consumes an inbound (already-parsed)
7//! [`ControlPacket`] and returns the [`HandshakeOutput`]s produced — further
8//! bytes to send, the negotiated parameters on success, or a rejection. No
9//! sockets, no clock: retransmit timing is driven by
10//! [`CallerHandshake::tick`] calls from the caller.
11//!
12//! Flow implemented (§4.3.1.1 / §4.3.1.2):
13//!
14//! 1. `start()`: send INDUCTION (Version 4, Encryption Field 0, Extension
15//!    Field 2, SYN Cookie 0).
16//! 2. `feed()` the Listener's INDUCTION response: validate Version 5 and the
17//!    SRT magic code `0x4A17`, capture the cookie and Listener's Socket ID,
18//!    then send CONCLUSION (Version 5, the captured cookie, HSREQ + optional
19//!    Stream ID / Group extensions).
20//! 3. `feed()` the Listener's CONCLUSION response: validate it, decode its
21//!    Handshake Extension Message, and reach [`CallerHandshakeState::Connected`]
22//!    with [`NegotiatedParams`] — or [`CallerHandshakeState::Rejected`] on any
23//!    validation failure or explicit peer rejection.
24
25use alloc::vec;
26use alloc::vec::Vec;
27use core::time::Duration;
28
29use crate::error::{Error, Result};
30use crate::handshake_sm::{
31    self, HANDSHAKE_VERSION_4, HANDSHAKE_VERSION_5, HandshakeConfig, HandshakeOutput,
32    INDUCTION_LEGACY_SOCKET_TYPE, NegotiatedParams, RejectionReason, Retransmit, RetransmitStep,
33    SRT_MAGIC_CODE, WireClock,
34};
35use crate::packet::number::{SocketId, SrtTimestamp};
36use crate::packet::{
37    ControlPacket, EncryptionField, ExtensionType, HandshakeExtensionFlags, HandshakeExtensions,
38    HandshakePacket, HandshakeType, HsExtMessage,
39};
40
41/// Caller-side handshake lifecycle state (`draft-sharabayko-srt-01` §4.3.1).
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43#[cfg_attr(feature = "serde", derive(serde::Serialize))]
44#[non_exhaustive]
45pub enum CallerHandshakeState {
46    /// No handshake message sent yet.
47    Idle,
48    /// INDUCTION sent; awaiting the Listener's INDUCTION response.
49    AwaitingInductionResponse,
50    /// CONCLUSION sent; awaiting the Listener's CONCLUSION response.
51    AwaitingConclusionResponse,
52    /// The handshake completed; [`NegotiatedParams`] are available.
53    Connected,
54    /// The handshake was rejected (locally, or by the peer).
55    Rejected,
56    /// No response arrived after the configured retry budget.
57    TimedOut,
58}
59
60impl CallerHandshakeState {
61    /// A short label for this state.
62    pub fn name(&self) -> &'static str {
63        match self {
64            CallerHandshakeState::Idle => "Idle",
65            CallerHandshakeState::AwaitingInductionResponse => "AwaitingInductionResponse",
66            CallerHandshakeState::AwaitingConclusionResponse => "AwaitingConclusionResponse",
67            CallerHandshakeState::Connected => "Connected",
68            CallerHandshakeState::Rejected => "Rejected",
69            CallerHandshakeState::TimedOut => "TimedOut",
70        }
71    }
72}
73
74broadcast_core::impl_spec_display!(CallerHandshakeState);
75
76/// A driveable Caller-side SRT handshake (`draft-sharabayko-srt-01` §4.3.1).
77#[derive(Debug)]
78pub struct CallerHandshake {
79    own_socket_id: u32,
80    config: HandshakeConfig,
81    state: CallerHandshakeState,
82    peer_socket_id: u32,
83    syn_cookie: u32,
84    retransmit: Retransmit,
85    clock: WireClock,
86    negotiated: Option<NegotiatedParams>,
87}
88
89impl CallerHandshake {
90    /// Creates a fresh Caller handshake in [`CallerHandshakeState::Idle`].
91    pub fn new(own_socket_id: u32, config: HandshakeConfig) -> Self {
92        CallerHandshake {
93            own_socket_id,
94            config,
95            state: CallerHandshakeState::Idle,
96            peer_socket_id: 0,
97            syn_cookie: 0,
98            retransmit: Retransmit::default(),
99            clock: WireClock::default(),
100            negotiated: None,
101        }
102    }
103
104    /// Sets the time elapsed since the connection started; every packet built
105    /// from here on carries it as its wire timestamp (§3.2.1). The machine reads
106    /// no clock, so the driver calls this before each `start`, `feed` and `tick`.
107    pub fn set_elapsed(&mut self, elapsed: core::time::Duration) {
108        self.clock.set(elapsed);
109    }
110
111    /// The current state.
112    pub fn state(&self) -> CallerHandshakeState {
113        self.state
114    }
115
116    /// The negotiated parameters, once [`CallerHandshakeState::Connected`].
117    pub fn negotiated(&self) -> Option<&NegotiatedParams> {
118        self.negotiated.as_ref()
119    }
120
121    /// Builds the initial INDUCTION handshake (§4.3.1.1) and transitions to
122    /// [`CallerHandshakeState::AwaitingInductionResponse`].
123    ///
124    /// # Errors
125    /// [`Error::HandshakeOutOfSequence`] if called more than once.
126    pub fn start(&mut self) -> Result<Vec<u8>> {
127        if self.state != CallerHandshakeState::Idle {
128            return Err(Error::HandshakeOutOfSequence {
129                state: self.state.name(),
130                reason: "start() called after the handshake already began",
131            });
132        }
133        let hp = HandshakePacket {
134            timestamp: SrtTimestamp::from_wire(self.clock.now()),
135            dest_socket_id: SocketId::CONNECTION_REQUEST, // §4.3.1.1: 0 is interpreted as a connection request.
136            version: HANDSHAKE_VERSION_4,
137            encryption_field: EncryptionField::NoEncryption,
138            extension_field: HandshakeExtensionFlags::new(INDUCTION_LEGACY_SOCKET_TYPE),
139            initial_seq_number: self.config.initial_seq_number,
140            mtu: self.config.mtu,
141            max_flow_window_size: self.config.max_flow_window_size,
142            handshake_type: HandshakeType::Induction,
143            srt_socket_id: self.own_socket_id,
144            syn_cookie: 0,
145            peer_ip: self.config.local_ip,
146            extensions: HandshakeExtensions(Vec::new()),
147        };
148        let bytes = handshake_sm::build_bytes(hp)?;
149        self.retransmit.arm(&bytes);
150        self.state = CallerHandshakeState::AwaitingInductionResponse;
151        Ok(bytes)
152    }
153
154    /// Feeds an inbound control packet. Only meaningful while awaiting the
155    /// Listener's INDUCTION or CONCLUSION response.
156    ///
157    /// A duplicate INDUCTION response while awaiting the CONCLUSION response
158    /// is ignored (no output, no state change).
159    ///
160    /// # Errors
161    /// [`Error::UnexpectedControlPacket`] if `packet` is not a Handshake
162    /// packet; [`Error::HandshakeOutOfSequence`] if fed outside those two
163    /// states (a driver bug, not a peer failure).
164    pub fn feed(&mut self, packet: &ControlPacket<'_>) -> Result<Vec<HandshakeOutput>> {
165        let hp = match packet {
166            ControlPacket::Handshake(hp) => hp,
167            other => {
168                return Err(Error::UnexpectedControlPacket {
169                    actual: other.control_type().name(),
170                });
171            }
172        };
173        match self.state {
174            CallerHandshakeState::AwaitingInductionResponse => self.on_induction_response(hp),
175            // A duplicate INDUCTION response (the Listener answers every
176            // retransmitted INDUCTION, and a delayed first answer can arrive
177            // after the second) is not a protocol violation once the
178            // CONCLUSION is out: ignore it, keep waiting for the CONCLUSION
179            // response. It used to be judged Rogue and abort the handshake.
180            CallerHandshakeState::AwaitingConclusionResponse
181                if hp.handshake_type == HandshakeType::Induction =>
182            {
183                Ok(Vec::new())
184            }
185            CallerHandshakeState::AwaitingConclusionResponse => self.on_conclusion_response(hp),
186            _ => Err(Error::HandshakeOutOfSequence {
187                state: self.state.name(),
188                reason: "not awaiting a handshake response",
189            }),
190        }
191    }
192
193    /// Convenience wrapper: parses `bytes` as an [`ControlPacket`] then
194    /// [`Self::feed`]s it.
195    pub fn feed_bytes(&mut self, bytes: &[u8]) -> Result<Vec<HandshakeOutput>> {
196        let packet = ControlPacket::parse(bytes)?;
197        self.feed(&packet)
198    }
199
200    /// Advances retransmit timing by `elapsed` of the caller's own clock. If
201    /// the handshake is waiting on a peer response and
202    /// [`HandshakeConfig::retransmit_after`] has passed with none arriving,
203    /// re-emits the last sent packet; after [`HandshakeConfig::max_retries`]
204    /// such retransmissions, transitions to
205    /// [`CallerHandshakeState::TimedOut`].
206    pub fn tick(&mut self, elapsed: Duration) -> Vec<HandshakeOutput> {
207        if !matches!(
208            self.state,
209            CallerHandshakeState::AwaitingInductionResponse
210                | CallerHandshakeState::AwaitingConclusionResponse
211        ) {
212            return Vec::new();
213        }
214        let step = self.retransmit.tick(elapsed, &self.config);
215        if matches!(step, RetransmitStep::TimedOut) {
216            self.state = CallerHandshakeState::TimedOut;
217        }
218        step.into_outputs()
219    }
220
221    fn on_induction_response(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
222        if let Some(reason) = RejectionReason::from_handshake_type(hp.handshake_type) {
223            self.state = CallerHandshakeState::Rejected;
224            return Ok(vec![HandshakeOutput::Rejected(reason)]);
225        }
226        if hp.handshake_type != HandshakeType::Induction {
227            self.state = CallerHandshakeState::Rejected;
228            return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
229        }
230        if hp.version != HANDSHAKE_VERSION_5 {
231            // Not an SRT party (or an incompatible version) — §4.3.1.1.
232            self.state = CallerHandshakeState::Rejected;
233            return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Version)]);
234        }
235        if hp.extension_field.get() != SRT_MAGIC_CODE {
236            // §4.3.1.1: "whether the Extension Flags contains the magic
237            // value 0x4A17; otherwise the connection is rejected."
238            self.state = CallerHandshakeState::Rejected;
239            return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
240        }
241
242        self.peer_socket_id = hp.srt_socket_id;
243        self.syn_cookie = hp.syn_cookie;
244
245        let hs_msg = HsExtMessage {
246            srt_version: self.config.srt_version,
247            srt_flags: self.config.flags,
248            receiver_tsbpd_delay: self.config.latency,
249            sender_tsbpd_delay: self.config.latency,
250        };
251        let ext_contents = handshake_sm::ConclusionExtensionContents::new(
252            hs_msg,
253            self.config.stream_id.as_deref(),
254            self.config.group,
255        );
256        // §6.1.5: the connection initiator (Caller) is the one that sends
257        // the Key Material request, piggybacked on this same CONCLUSION.
258        #[cfg(feature = "crypto")]
259        let mut ext_contents = ext_contents;
260        #[cfg(feature = "crypto")]
261        if let Some(crypto) = &self.config.crypto {
262            ext_contents.set_key_material(
263                crate::packet::ExtensionType::KmReq,
264                handshake_sm::build_key_material_contents(crypto)?,
265            );
266        }
267        let (extensions, ext_flags) =
268            handshake_sm::build_conclusion_extensions(ExtensionType::HsReq, &ext_contents);
269
270        let hp_out = HandshakePacket {
271            timestamp: SrtTimestamp::from_wire(self.clock.now()),
272            // 0, not the captured Listener Socket ID: draft §4.3.1, and a real SRT listener only accepts it (`tests/it/libsrt_*`).
273            dest_socket_id: SocketId::CONNECTION_REQUEST,
274            version: HANDSHAKE_VERSION_5,
275            encryption_field: self.config.encryption_field,
276            extension_field: HandshakeExtensionFlags::new(ext_flags),
277            initial_seq_number: self.config.initial_seq_number,
278            mtu: self.config.mtu,
279            max_flow_window_size: self.config.max_flow_window_size,
280            handshake_type: HandshakeType::Conclusion,
281            srt_socket_id: self.own_socket_id,
282            syn_cookie: self.syn_cookie,
283            peer_ip: self.config.local_ip,
284            extensions,
285        };
286        let bytes = handshake_sm::build_bytes(hp_out)?;
287        self.retransmit.arm_fresh(&bytes);
288        self.state = CallerHandshakeState::AwaitingConclusionResponse;
289        Ok(vec![HandshakeOutput::Send(bytes)])
290    }
291
292    fn on_conclusion_response(&mut self, hp: &HandshakePacket<'_>) -> Result<Vec<HandshakeOutput>> {
293        if let Some(reason) = RejectionReason::from_handshake_type(hp.handshake_type) {
294            self.state = CallerHandshakeState::Rejected;
295            return Ok(vec![HandshakeOutput::Rejected(reason)]);
296        }
297        if hp.handshake_type != HandshakeType::Conclusion {
298            self.state = CallerHandshakeState::Rejected;
299            return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
300        }
301        if hp.version != HANDSHAKE_VERSION_5 {
302            self.state = CallerHandshakeState::Rejected;
303            return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Version)]);
304        }
305
306        if hp.initial_seq_number > crate::packet::SEQ_NUMBER_MASK {
307            // Not a 31-bit sequence number (§3.1): it would seed the receive
308            // side out of range and stall the connection.
309            self.state = CallerHandshakeState::Rejected;
310            return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
311        }
312
313        if hp.mtu == 0 || hp.max_flow_window_size == 0 {
314            self.state = CallerHandshakeState::Rejected;
315            return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
316        }
317
318        // Re-capture the Listener's Socket ID from the CONCLUSION itself, not the stale INDUCTION one — draft §4.3.1; libsrt interop.
319        self.peer_socket_id = hp.srt_socket_id;
320
321        let parsed = match handshake_sm::parse_peer_extensions(hp) {
322            Ok(p) => p,
323            Err(_) => {
324                self.state = CallerHandshakeState::Rejected;
325                return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
326            }
327        };
328        let peer_msg = match parsed.hs_msg {
329            Some(m) => m,
330            None => {
331                self.state = CallerHandshakeState::Rejected;
332                return Ok(vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
333            }
334        };
335
336        // §6.1.5: this Caller (the initiator) already holds the plaintext
337        // SEK/Salt it generated itself — it does not need to unwrap
338        // anything. It only needs the Listener's echo to *confirm* the
339        // Listener derived the same SEK (§6.1.5, "the responder echoes the
340        // same KM message back to prove it derived the same SEK"); a
341        // missing or mismatched echo means the Listener does not have (or
342        // never confirmed) the SEK.
343        #[cfg(feature = "crypto")]
344        let crypto_cfg = self.config.crypto.clone();
345        #[cfg(feature = "crypto")]
346        let crypto_result: Option<handshake_sm::RecoveredSek> = match &crypto_cfg {
347            Some(crypto) => match &parsed.km {
348                Some(echoed) if handshake_sm::verify_km_echo(crypto, echoed) => Some((
349                    handshake_sm::SecretBytes::new(crypto.sek.clone()),
350                    crypto.salt,
351                )),
352                _ => {
353                    self.state = CallerHandshakeState::Rejected;
354                    return Ok(vec![HandshakeOutput::Rejected(RejectionReason::BadSecret)]);
355                }
356            },
357            None => None,
358        };
359
360        let negotiated = NegotiatedParams {
361            version: HANDSHAKE_VERSION_5,
362            flags: crate::packet::HandshakeExtensionMessageFlags::new(
363                self.config.flags.get() & peer_msg.srt_flags.get(),
364            ),
365            latency: handshake_sm::negotiate_latency(self.config.latency, &peer_msg),
366            own_socket_id: self.own_socket_id,
367            peer_socket_id: self.peer_socket_id,
368            mtu: self.config.mtu.min(hp.mtu),
369            max_flow_window_size: self
370                .config
371                .max_flow_window_size
372                .min(hp.max_flow_window_size),
373            stream_id: self.config.stream_id.clone(),
374            group: self.config.group,
375            #[cfg(feature = "crypto")]
376            sek: crypto_result.as_ref().map(|(sek, _)| sek.clone()),
377            #[cfg(feature = "crypto")]
378            salt: crypto_result.as_ref().map(|(_, salt)| *salt),
379        };
380        self.negotiated = Some(negotiated.clone());
381        self.state = CallerHandshakeState::Connected;
382        Ok(vec![HandshakeOutput::Connected(negotiated)])
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use crate::packet::handshake::{HS_EXT_FLAG_HSREQ, HandshakeType};
390
391    #[test]
392    fn start_is_idempotent_guard() {
393        let mut c = CallerHandshake::new(
394            1,
395            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
396        );
397        assert!(c.start().is_ok());
398        assert!(matches!(
399            c.start(),
400            Err(crate::error::Error::HandshakeOutOfSequence { .. })
401        ));
402    }
403
404    /// `peer_socket_id` must come from the CONCLUSION response, not a stale INDUCTION one (draft §4.3.1).
405    #[test]
406    fn conclusion_response_socket_id_overrides_induction_one() {
407        use crate::packet::handshake::build_extension_block;
408
409        const INDUCTION_LISTENER_ID: u32 = 0x1111_2222;
410        const CONCLUSION_LISTENER_ID: u32 = 0x3333_4444;
411
412        let mut c = CallerHandshake::new(
413            0xAAAA_BBBB,
414            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
415        );
416        c.start().unwrap();
417        c.feed(&induction_response(0xC0FF_EE00, INDUCTION_LISTENER_ID))
418            .unwrap();
419
420        let hs_msg = HsExtMessage {
421            srt_version: 0x0105_0000,
422            srt_flags: HandshakeConfig::for_profile(broadcast_core::Profile::Server).flags,
423            receiver_tsbpd_delay: Duration::from_millis(120),
424            sender_tsbpd_delay: Duration::from_millis(120),
425        };
426        let ext = build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap();
427        let conclusion_response = ControlPacket::Handshake(HandshakePacket {
428            timestamp: SrtTimestamp::ZERO,
429            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
430            version: HANDSHAKE_VERSION_5,
431            encryption_field: EncryptionField::NoEncryption,
432            extension_field: HandshakeExtensionFlags::new(0x0001),
433            initial_seq_number: 0,
434            mtu: 1500,
435            max_flow_window_size: 8192,
436            handshake_type: HandshakeType::Conclusion,
437            srt_socket_id: CONCLUSION_LISTENER_ID,
438            syn_cookie: 0xC0FF_EE00,
439            peer_ip: [0; 4],
440            extensions: HandshakeExtensions::parse(&ext).expect("test extension bytes"),
441        });
442        let outputs = c.feed(&conclusion_response).unwrap();
443        assert!(
444            outputs
445                .iter()
446                .any(|o| matches!(o, HandshakeOutput::Connected(_))),
447            "expected Connected, got {outputs:?}"
448        );
449        assert_eq!(c.state(), CallerHandshakeState::Connected);
450        assert_eq!(
451            c.negotiated().unwrap().peer_socket_id,
452            CONCLUSION_LISTENER_ID,
453            "peer_socket_id must come from the CONCLUSION response, not the stale INDUCTION one"
454        );
455    }
456
457    #[test]
458    fn induction_wire_values_match_draft_4_3_1_1() {
459        let mut c = CallerHandshake::new(
460            0xAAAA_BBBB,
461            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
462        );
463        let bytes = c.start().unwrap();
464        let pkt = ControlPacket::parse(&bytes).unwrap();
465        match pkt {
466            ControlPacket::Handshake(hp) => {
467                assert_eq!(hp.version, HANDSHAKE_VERSION_4);
468                assert_eq!(hp.encryption_field, EncryptionField::NoEncryption);
469                assert_eq!(hp.extension_field.get(), INDUCTION_LEGACY_SOCKET_TYPE);
470                assert_eq!(hp.handshake_type, HandshakeType::Induction);
471                assert_eq!(hp.srt_socket_id, 0xAAAA_BBBB);
472                assert_eq!(hp.syn_cookie, 0);
473                assert_eq!(hp.dest_socket_id, SocketId::CONNECTION_REQUEST);
474            }
475            _ => panic!("expected handshake"),
476        }
477        assert_eq!(c.state(), CallerHandshakeState::AwaitingInductionResponse);
478    }
479
480    fn induction_response(cookie: u32, listener_id: u32) -> ControlPacket<'static> {
481        ControlPacket::Handshake(HandshakePacket {
482            timestamp: SrtTimestamp::ZERO,
483            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
484            version: HANDSHAKE_VERSION_5,
485            encryption_field: EncryptionField::NoEncryption,
486            extension_field: HandshakeExtensionFlags::new(SRT_MAGIC_CODE),
487            initial_seq_number: 0,
488            mtu: 1500,
489            max_flow_window_size: 8192,
490            handshake_type: HandshakeType::Induction,
491            srt_socket_id: listener_id,
492            syn_cookie: cookie,
493            peer_ip: [0; 4],
494            extensions: HandshakeExtensions(Vec::new()),
495        })
496    }
497
498    #[test]
499    fn conclusion_carries_the_captured_cookie_and_hsreq() {
500        let mut c = CallerHandshake::new(
501            0xAAAA_BBBB,
502            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
503        );
504        c.start().unwrap();
505        let outputs = c
506            .feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
507            .unwrap();
508        assert_eq!(outputs.len(), 1);
509        let bytes = match &outputs[0] {
510            HandshakeOutput::Send(b) => b.clone(),
511            other => panic!("expected Send, got {other:?}"),
512        };
513        let pkt = ControlPacket::parse(&bytes).unwrap();
514        match pkt {
515            ControlPacket::Handshake(hp) => {
516                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
517                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
518                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
519                // See `on_induction_response`.
520                assert_eq!(hp.dest_socket_id, SocketId::CONNECTION_REQUEST);
521                assert_eq!(
522                    hp.extension_field.get() & HS_EXT_FLAG_HSREQ,
523                    HS_EXT_FLAG_HSREQ
524                );
525                let blocks: Vec<_> = hp.extensions.iter().collect();
526                assert_eq!(blocks.len(), 1);
527                assert_eq!(blocks[0].ext_type, ExtensionType::HsReq);
528            }
529            _ => panic!("expected handshake"),
530        }
531        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
532    }
533
534    #[test]
535    fn induction_response_bad_magic_is_rejected() {
536        let mut c = CallerHandshake::new(
537            1,
538            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
539        );
540        c.start().unwrap();
541        let mut bad = induction_response(1, 2);
542        if let ControlPacket::Handshake(hp) = &mut bad {
543            hp.extension_field = HandshakeExtensionFlags::new(0x0000);
544        }
545        let outputs = c.feed(&bad).unwrap();
546        assert_eq!(
547            outputs,
548            vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]
549        );
550        assert_eq!(c.state(), CallerHandshakeState::Rejected);
551    }
552
553    #[test]
554    fn induction_response_bad_version_is_rejected() {
555        let mut c = CallerHandshake::new(
556            1,
557            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
558        );
559        c.start().unwrap();
560        let mut bad = induction_response(1, 2);
561        if let ControlPacket::Handshake(hp) = &mut bad {
562            hp.version = HANDSHAKE_VERSION_4;
563        }
564        let outputs = c.feed(&bad).unwrap();
565        assert_eq!(
566            outputs,
567            vec![HandshakeOutput::Rejected(RejectionReason::Version)]
568        );
569        assert_eq!(c.state(), CallerHandshakeState::Rejected);
570    }
571
572    #[test]
573    fn explicit_peer_rejection_is_surfaced() {
574        let mut c = CallerHandshake::new(
575            1,
576            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
577        );
578        c.start().unwrap();
579        let mut rejected = induction_response(1, 2);
580        if let ControlPacket::Handshake(hp) = &mut rejected {
581            hp.handshake_type = RejectionReason::Backlog.to_handshake_type();
582        }
583        let outputs = c.feed(&rejected).unwrap();
584        assert_eq!(
585            outputs,
586            vec![HandshakeOutput::Rejected(RejectionReason::Backlog)]
587        );
588        assert_eq!(c.state(), CallerHandshakeState::Rejected);
589    }
590
591    #[test]
592    fn feed_before_start_is_out_of_sequence() {
593        let mut c = CallerHandshake::new(
594            1,
595            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
596        );
597        let resp = induction_response(1, 2);
598        assert!(matches!(
599            c.feed(&resp),
600            Err(Error::HandshakeOutOfSequence { .. })
601        ));
602    }
603
604    #[test]
605    fn feed_rejects_non_handshake_packets() {
606        use crate::packet::misc::KeepAlivePacket;
607        let mut c = CallerHandshake::new(
608            1,
609            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
610        );
611        c.start().unwrap();
612        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
613            timestamp: SrtTimestamp::ZERO,
614            dest_socket_id: SocketId::CONNECTION_REQUEST,
615            libsrt_pad: false,
616        });
617        assert!(matches!(
618            c.feed(&ka),
619            Err(Error::UnexpectedControlPacket { .. })
620        ));
621    }
622
623    #[test]
624    fn tick_retransmits_then_times_out() {
625        let config = HandshakeConfig {
626            retransmit_after: Duration::from_millis(500),
627            max_retries: 1,
628            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
629        };
630        let mut c = CallerHandshake::new(1, config);
631        let first = c.start().unwrap();
632
633        let step = Duration::from_millis(250);
634        assert_eq!(c.tick(step), Vec::new()); // 250 ms, under the 500 ms floor
635        let out = c.tick(step); // 500 ms: retransmit #1
636        assert_eq!(out, vec![HandshakeOutput::Send(first.clone())]);
637
638        assert_eq!(c.tick(step), Vec::new());
639        let out = c.tick(step); // retransmit #2 exceeds max_retries=1
640        assert_eq!(out, vec![HandshakeOutput::TimedOut]);
641        assert_eq!(c.state(), CallerHandshakeState::TimedOut);
642    }
643
644    #[test]
645    fn a_tick_elapsed_past_the_period_is_measured_not_counted() {
646        let config = HandshakeConfig {
647            retransmit_after: Duration::from_millis(500),
648            max_retries: 2,
649            ..HandshakeConfig::for_profile(broadcast_core::Profile::Server)
650        };
651        let mut c = CallerHandshake::new(1, config);
652        let first = c.start().unwrap();
653        let out = c.tick(Duration::from_millis(600));
654        assert_eq!(
655            out,
656            vec![HandshakeOutput::Send(first)],
657            "one 600 ms step is past the 500 ms period: one retransmit, not zero"
658        );
659    }
660
661    /// r08-SRT-W10: a duplicate INDUCTION response after the CONCLUSION has
662    /// been sent is ignored; the handshake still completes on the real
663    /// CONCLUSION response (it used to be judged Rogue and abort).
664    #[test]
665    fn duplicate_induction_response_while_awaiting_conclusion_is_ignored() {
666        use crate::packet::handshake::build_extension_block;
667        let mut c = CallerHandshake::new(
668            0xAAAA_BBBB,
669            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
670        );
671        c.start().unwrap();
672        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
673            .unwrap();
674        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
675
676        let out = c
677            .feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
678            .unwrap();
679        assert_eq!(out, Vec::new());
680        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
681
682        let hs_msg = HsExtMessage {
683            srt_version: 0x0105_0000,
684            srt_flags: HandshakeConfig::for_profile(broadcast_core::Profile::Server).flags,
685            receiver_tsbpd_delay: Duration::from_millis(120),
686            sender_tsbpd_delay: Duration::from_millis(120),
687        };
688        let ext = build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap();
689        let response = ControlPacket::Handshake(HandshakePacket {
690            timestamp: SrtTimestamp::ZERO,
691            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
692            version: HANDSHAKE_VERSION_5,
693            encryption_field: EncryptionField::NoEncryption,
694            extension_field: HandshakeExtensionFlags::new(0x0001),
695            initial_seq_number: 0,
696            mtu: 1500,
697            max_flow_window_size: 8192,
698            handshake_type: HandshakeType::Conclusion,
699            srt_socket_id: 0x1111_2222,
700            syn_cookie: 0xC0FF_EE00,
701            peer_ip: [0; 4],
702            extensions: HandshakeExtensions::parse(&ext).expect("test extension bytes"),
703        });
704        let out = c.feed(&response).unwrap();
705        assert!(
706            out.iter()
707                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
708        );
709        assert_eq!(c.state(), CallerHandshakeState::Connected);
710    }
711
712    fn conclusion_response_with(mtu: u32, mfw: u32, isn: u32) -> Vec<u8> {
713        use crate::packet::handshake::build_extension_block;
714        let hs_msg = HsExtMessage {
715            srt_version: 0x0105_0000,
716            srt_flags: HandshakeConfig::for_profile(broadcast_core::Profile::Server).flags,
717            receiver_tsbpd_delay: Duration::from_millis(120),
718            sender_tsbpd_delay: Duration::from_millis(120),
719        };
720        let ext = build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap();
721        let pkt = ControlPacket::Handshake(HandshakePacket {
722            timestamp: SrtTimestamp::ZERO,
723            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
724            version: HANDSHAKE_VERSION_5,
725            encryption_field: EncryptionField::NoEncryption,
726            extension_field: HandshakeExtensionFlags::new(0x0001),
727            initial_seq_number: isn,
728            mtu,
729            max_flow_window_size: mfw,
730            handshake_type: HandshakeType::Conclusion,
731            srt_socket_id: 0x3333_4444,
732            syn_cookie: 0xC0FF_EE00,
733            peer_ip: [0; 4],
734            extensions: HandshakeExtensions::parse(&ext).expect("test extension bytes"),
735        });
736        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
737        pkt.serialize_into(&mut buf).unwrap();
738        buf
739    }
740
741    fn caller_awaiting_conclusion() -> CallerHandshake {
742        let mut c = CallerHandshake::new(
743            0xAAAA_BBBB,
744            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
745        );
746        c.start().unwrap();
747        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
748            .unwrap();
749        c
750    }
751
752    /// §3.2.1: the smaller of both sides' MTU and Maximum Flow Window Size.
753    #[test]
754    fn negotiated_mtu_and_flow_window_are_the_smaller_of_both() {
755        for (peer_mtu, peer_mfw, want_mtu, want_mfw) in [
756            (576, 64, 576, 64),
757            (9000, 65_536, 1500, 8192),
758            (1500, 64, 1500, 64),
759        ] {
760            let mut c = caller_awaiting_conclusion();
761            c.feed_bytes(&conclusion_response_with(peer_mtu, peer_mfw, 5))
762                .unwrap();
763            let n = c.negotiated().expect("connected");
764            assert_eq!((n.mtu, n.max_flow_window_size), (want_mtu, want_mfw));
765        }
766    }
767
768    /// A listener ISN that is not a 31-bit sequence number is refused.
769    #[test]
770    fn a_peer_isn_wider_than_31_bits_is_rejected() {
771        let mut c = caller_awaiting_conclusion();
772        let out = c
773            .feed_bytes(&conclusion_response_with(1500, 8192, 0x8000_0000))
774            .unwrap();
775        assert_eq!(out, vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
776        assert_eq!(c.state(), CallerHandshakeState::Rejected);
777        let mut c = caller_awaiting_conclusion();
778        c.feed_bytes(&conclusion_response_with(1500, 8192, 0x7FFF_FFFF))
779            .unwrap();
780        assert_eq!(c.state(), CallerHandshakeState::Connected);
781    }
782
783    fn conclusion_with_peer_flags(peer_flags: u32) -> ControlPacket<'static> {
784        use crate::packet::handshake::{HandshakeExtensionMessageFlags, build_extension_block};
785        let hs_msg = HsExtMessage {
786            srt_version: 0x0105_0000,
787            srt_flags: HandshakeExtensionMessageFlags::new(peer_flags),
788            receiver_tsbpd_delay: Duration::from_millis(120),
789            sender_tsbpd_delay: Duration::from_millis(120),
790        };
791        let ext: &'static [u8] = alloc::vec::Vec::leak(
792            build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap(),
793        );
794        ControlPacket::Handshake(HandshakePacket {
795            timestamp: SrtTimestamp::ZERO,
796            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
797            version: HANDSHAKE_VERSION_5,
798            encryption_field: EncryptionField::NoEncryption,
799            extension_field: HandshakeExtensionFlags::new(0x0001),
800            initial_seq_number: 0,
801            mtu: 1500,
802            max_flow_window_size: 8192,
803            handshake_type: HandshakeType::Conclusion,
804            srt_socket_id: 0x3333_4444,
805            syn_cookie: 0xC0FF_EE00,
806            peer_ip: [0; 4],
807            extensions: HandshakeExtensions::parse(ext).expect("test extension bytes"),
808        })
809    }
810
811    /// §3.2.1.1: the connection's flags are the bitwise intersection of both
812    /// sides' advertised sets, never a union or a symmetric difference.
813    #[test]
814    fn negotiated_flags_are_the_intersection_of_both_sides() {
815        use crate::packet::handshake::{
816            HS_MSG_FLAG_PERIODICNAK, HS_MSG_FLAG_REXMITFLG, HS_MSG_FLAG_TLPKTDROP,
817            HS_MSG_FLAG_TSBPDRCV, HS_MSG_FLAG_TSBPDSND, HandshakeExtensionMessageFlags,
818        };
819        let local = HS_MSG_FLAG_TSBPDSND
820            | HS_MSG_FLAG_TSBPDRCV
821            | HS_MSG_FLAG_TLPKTDROP
822            | HS_MSG_FLAG_PERIODICNAK
823            | HS_MSG_FLAG_REXMITFLG;
824        let peer = HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV | HS_MSG_FLAG_REXMITFLG;
825        let config = HandshakeConfig::for_profile(broadcast_core::Profile::Server)
826            .with_flags(HandshakeExtensionMessageFlags::new(local));
827        let mut c = CallerHandshake::new(0xAAAA_BBBB, config);
828        c.start().unwrap();
829        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
830            .unwrap();
831        c.feed(&conclusion_with_peer_flags(peer)).unwrap();
832        assert_eq!(
833            c.negotiated().expect("connected").flags,
834            HandshakeExtensionMessageFlags::new(peer)
835        );
836    }
837
838    #[test]
839    fn negotiated_flags_drop_a_flag_only_the_peer_advertises() {
840        use crate::packet::handshake::{
841            HS_MSG_FLAG_TLPKTDROP, HS_MSG_FLAG_TSBPDSND, HandshakeExtensionMessageFlags,
842        };
843        let config = HandshakeConfig::for_profile(broadcast_core::Profile::Server)
844            .with_flags(HandshakeExtensionMessageFlags::new(HS_MSG_FLAG_TSBPDSND));
845        let mut c = CallerHandshake::new(0xAAAA_BBBB, config);
846        c.start().unwrap();
847        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
848            .unwrap();
849        c.feed(&conclusion_with_peer_flags(
850            HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TLPKTDROP,
851        ))
852        .unwrap();
853        assert_eq!(
854            c.negotiated().expect("connected").flags,
855            HandshakeExtensionMessageFlags::new(HS_MSG_FLAG_TSBPDSND)
856        );
857    }
858
859    /// The configured SRT version, flags and local IP are the ones the
860    /// CONCLUSION's HSREQ and CIF actually advertise.
861    #[test]
862    fn configured_handshake_values_are_carried_on_the_wire() {
863        use crate::packet::handshake::HandshakeExtensionMessageFlags;
864        let config = HandshakeConfig::for_profile(broadcast_core::Profile::Server)
865            .with_srt_version(0x0105_0003)
866            .with_flags(HandshakeExtensionMessageFlags::new(0x0000_0063))
867            .with_local_ip([10, 0, 0, 7]);
868        let mut c = CallerHandshake::new(0xAAAA_BBBB, config);
869        c.start().unwrap();
870        let outputs = c
871            .feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
872            .unwrap();
873        let bytes = match &outputs[0] {
874            HandshakeOutput::Send(b) => b.clone(),
875            other => panic!("expected Send, got {other:?}"),
876        };
877        let ControlPacket::Handshake(hp) = ControlPacket::parse(&bytes).unwrap() else {
878            panic!("expected handshake");
879        };
880        assert_eq!(hp.peer_ip, [10, 0, 0, 7]);
881        let parsed = crate::handshake_sm::parse_peer_extensions(&hp).expect("extensions");
882        let msg = parsed.hs_msg.expect("HSREQ");
883        assert_eq!(msg.srt_version, 0x0105_0003);
884        assert_eq!(msg.srt_flags.get(), 0x0000_0063);
885    }
886
887    #[test]
888    fn state_labels_match_the_diagram_names() {
889        assert_eq!(CallerHandshakeState::Idle.name(), "Idle");
890        assert_eq!(
891            CallerHandshakeState::AwaitingInductionResponse.name(),
892            "AwaitingInductionResponse"
893        );
894        assert_eq!(
895            CallerHandshakeState::AwaitingConclusionResponse.name(),
896            "AwaitingConclusionResponse"
897        );
898        assert_eq!(CallerHandshakeState::Connected.name(), "Connected");
899        assert_eq!(CallerHandshakeState::Rejected.name(), "Rejected");
900        assert_eq!(CallerHandshakeState::TimedOut.name(), "TimedOut");
901    }
902}