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_common::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(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.0 != 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 — libsrt `CUDT::processAsyncConnectRequest` (srtcore/core.cpp), draft §4.3.1; libsrt interop.
273            dest_socket_id: SocketId::CONNECTION_REQUEST,
274            version: HANDSHAKE_VERSION_5,
275            encryption_field: self.config.encryption_field,
276            extension_field: HandshakeExtensionFlags(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(
363                self.config.flags.0 & peer_msg.srt_flags.0,
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(1, HandshakeConfig::default());
394        assert!(c.start().is_ok());
395        assert!(matches!(
396            c.start(),
397            Err(crate::error::Error::HandshakeOutOfSequence { .. })
398        ));
399    }
400
401    /// `peer_socket_id` must come from the CONCLUSION response, not a stale INDUCTION one (draft §4.3.1).
402    #[test]
403    fn conclusion_response_socket_id_overrides_induction_one() {
404        use crate::packet::handshake::build_extension_block;
405
406        const INDUCTION_LISTENER_ID: u32 = 0x1111_2222;
407        const CONCLUSION_LISTENER_ID: u32 = 0x3333_4444;
408
409        let mut c = CallerHandshake::new(0xAAAA_BBBB, HandshakeConfig::default());
410        c.start().unwrap();
411        c.feed(&induction_response(0xC0FF_EE00, INDUCTION_LISTENER_ID))
412            .unwrap();
413
414        let hs_msg = HsExtMessage {
415            srt_version: 0x0105_0000,
416            srt_flags: HandshakeConfig::default().flags,
417            receiver_tsbpd_delay: Duration::from_millis(120),
418            sender_tsbpd_delay: Duration::from_millis(120),
419        };
420        let ext = build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap();
421        let conclusion_response = ControlPacket::Handshake(HandshakePacket {
422            timestamp: SrtTimestamp::ZERO,
423            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
424            version: HANDSHAKE_VERSION_5,
425            encryption_field: EncryptionField::NoEncryption,
426            extension_field: HandshakeExtensionFlags(0x0001),
427            initial_seq_number: 0,
428            mtu: 1500,
429            max_flow_window_size: 8192,
430            handshake_type: HandshakeType::Conclusion,
431            srt_socket_id: CONCLUSION_LISTENER_ID,
432            syn_cookie: 0xC0FF_EE00,
433            peer_ip: [0; 4],
434            extensions: HandshakeExtensions::parse(&ext).expect("test extension bytes"),
435        });
436        let outputs = c.feed(&conclusion_response).unwrap();
437        assert!(
438            outputs
439                .iter()
440                .any(|o| matches!(o, HandshakeOutput::Connected(_))),
441            "expected Connected, got {outputs:?}"
442        );
443        assert_eq!(c.state(), CallerHandshakeState::Connected);
444        assert_eq!(
445            c.negotiated().unwrap().peer_socket_id,
446            CONCLUSION_LISTENER_ID,
447            "peer_socket_id must come from the CONCLUSION response, not the stale INDUCTION one"
448        );
449    }
450
451    #[test]
452    fn induction_wire_values_match_draft_4_3_1_1() {
453        let mut c = CallerHandshake::new(0xAAAA_BBBB, HandshakeConfig::default());
454        let bytes = c.start().unwrap();
455        let pkt = ControlPacket::parse(&bytes).unwrap();
456        match pkt {
457            ControlPacket::Handshake(hp) => {
458                assert_eq!(hp.version, HANDSHAKE_VERSION_4);
459                assert_eq!(hp.encryption_field, EncryptionField::NoEncryption);
460                assert_eq!(hp.extension_field.0, INDUCTION_LEGACY_SOCKET_TYPE);
461                assert_eq!(hp.handshake_type, HandshakeType::Induction);
462                assert_eq!(hp.srt_socket_id, 0xAAAA_BBBB);
463                assert_eq!(hp.syn_cookie, 0);
464                assert_eq!(hp.dest_socket_id, SocketId::CONNECTION_REQUEST);
465            }
466            _ => panic!("expected handshake"),
467        }
468        assert_eq!(c.state(), CallerHandshakeState::AwaitingInductionResponse);
469    }
470
471    fn induction_response(cookie: u32, listener_id: u32) -> ControlPacket<'static> {
472        ControlPacket::Handshake(HandshakePacket {
473            timestamp: SrtTimestamp::ZERO,
474            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
475            version: HANDSHAKE_VERSION_5,
476            encryption_field: EncryptionField::NoEncryption,
477            extension_field: HandshakeExtensionFlags(SRT_MAGIC_CODE),
478            initial_seq_number: 0,
479            mtu: 1500,
480            max_flow_window_size: 8192,
481            handshake_type: HandshakeType::Induction,
482            srt_socket_id: listener_id,
483            syn_cookie: cookie,
484            peer_ip: [0; 4],
485            extensions: HandshakeExtensions(Vec::new()),
486        })
487    }
488
489    #[test]
490    fn conclusion_carries_the_captured_cookie_and_hsreq() {
491        let mut c = CallerHandshake::new(0xAAAA_BBBB, HandshakeConfig::default());
492        c.start().unwrap();
493        let outputs = c
494            .feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
495            .unwrap();
496        assert_eq!(outputs.len(), 1);
497        let bytes = match &outputs[0] {
498            HandshakeOutput::Send(b) => b.clone(),
499            other => panic!("expected Send, got {other:?}"),
500        };
501        let pkt = ControlPacket::parse(&bytes).unwrap();
502        match pkt {
503            ControlPacket::Handshake(hp) => {
504                assert_eq!(hp.version, HANDSHAKE_VERSION_5);
505                assert_eq!(hp.handshake_type, HandshakeType::Conclusion);
506                assert_eq!(hp.syn_cookie, 0xC0FF_EE00);
507                // libsrt `CUDT::processAsyncConnectRequest`; see `on_induction_response`.
508                assert_eq!(hp.dest_socket_id, SocketId::CONNECTION_REQUEST);
509                assert_eq!(hp.extension_field.0 & HS_EXT_FLAG_HSREQ, HS_EXT_FLAG_HSREQ);
510                let blocks: Vec<_> = hp.extensions.iter().collect();
511                assert_eq!(blocks.len(), 1);
512                assert_eq!(blocks[0].ext_type, ExtensionType::HsReq);
513            }
514            _ => panic!("expected handshake"),
515        }
516        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
517    }
518
519    #[test]
520    fn induction_response_bad_magic_is_rejected() {
521        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
522        c.start().unwrap();
523        let mut bad = induction_response(1, 2);
524        if let ControlPacket::Handshake(hp) = &mut bad {
525            hp.extension_field = HandshakeExtensionFlags(0x0000);
526        }
527        let outputs = c.feed(&bad).unwrap();
528        assert_eq!(
529            outputs,
530            vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]
531        );
532        assert_eq!(c.state(), CallerHandshakeState::Rejected);
533    }
534
535    #[test]
536    fn induction_response_bad_version_is_rejected() {
537        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
538        c.start().unwrap();
539        let mut bad = induction_response(1, 2);
540        if let ControlPacket::Handshake(hp) = &mut bad {
541            hp.version = HANDSHAKE_VERSION_4;
542        }
543        let outputs = c.feed(&bad).unwrap();
544        assert_eq!(
545            outputs,
546            vec![HandshakeOutput::Rejected(RejectionReason::Version)]
547        );
548        assert_eq!(c.state(), CallerHandshakeState::Rejected);
549    }
550
551    #[test]
552    fn explicit_peer_rejection_is_surfaced() {
553        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
554        c.start().unwrap();
555        let mut rejected = induction_response(1, 2);
556        if let ControlPacket::Handshake(hp) = &mut rejected {
557            hp.handshake_type = RejectionReason::Backlog.to_handshake_type();
558        }
559        let outputs = c.feed(&rejected).unwrap();
560        assert_eq!(
561            outputs,
562            vec![HandshakeOutput::Rejected(RejectionReason::Backlog)]
563        );
564        assert_eq!(c.state(), CallerHandshakeState::Rejected);
565    }
566
567    #[test]
568    fn feed_before_start_is_out_of_sequence() {
569        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
570        let resp = induction_response(1, 2);
571        assert!(matches!(
572            c.feed(&resp),
573            Err(Error::HandshakeOutOfSequence { .. })
574        ));
575    }
576
577    #[test]
578    fn feed_rejects_non_handshake_packets() {
579        use crate::packet::misc::KeepAlivePacket;
580        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
581        c.start().unwrap();
582        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
583            timestamp: SrtTimestamp::ZERO,
584            dest_socket_id: SocketId::CONNECTION_REQUEST,
585            libsrt_pad: false,
586        });
587        assert!(matches!(
588            c.feed(&ka),
589            Err(Error::UnexpectedControlPacket { .. })
590        ));
591    }
592
593    #[test]
594    fn tick_retransmits_then_times_out() {
595        let config = HandshakeConfig {
596            retransmit_after: Duration::from_millis(500),
597            max_retries: 1,
598            ..HandshakeConfig::default()
599        };
600        let mut c = CallerHandshake::new(1, config);
601        let first = c.start().unwrap();
602
603        let step = Duration::from_millis(250);
604        assert_eq!(c.tick(step), Vec::new()); // 250 ms, under the 500 ms floor
605        let out = c.tick(step); // 500 ms: retransmit #1
606        assert_eq!(out, vec![HandshakeOutput::Send(first.clone())]);
607
608        assert_eq!(c.tick(step), Vec::new());
609        let out = c.tick(step); // retransmit #2 exceeds max_retries=1
610        assert_eq!(out, vec![HandshakeOutput::TimedOut]);
611        assert_eq!(c.state(), CallerHandshakeState::TimedOut);
612    }
613
614    #[test]
615    fn a_tick_elapsed_past_the_period_is_measured_not_counted() {
616        let config = HandshakeConfig {
617            retransmit_after: Duration::from_millis(500),
618            max_retries: 2,
619            ..HandshakeConfig::default()
620        };
621        let mut c = CallerHandshake::new(1, config);
622        let first = c.start().unwrap();
623        let out = c.tick(Duration::from_millis(600));
624        assert_eq!(
625            out,
626            vec![HandshakeOutput::Send(first)],
627            "one 600 ms step is past the 500 ms period: one retransmit, not zero"
628        );
629    }
630
631    /// r08-SRT-W10: a duplicate INDUCTION response after the CONCLUSION has
632    /// been sent is ignored; the handshake still completes on the real
633    /// CONCLUSION response (it used to be judged Rogue and abort).
634    #[test]
635    fn duplicate_induction_response_while_awaiting_conclusion_is_ignored() {
636        use crate::packet::handshake::build_extension_block;
637        let mut c = CallerHandshake::new(0xAAAA_BBBB, HandshakeConfig::default());
638        c.start().unwrap();
639        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
640            .unwrap();
641        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
642
643        let out = c
644            .feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
645            .unwrap();
646        assert_eq!(out, Vec::new());
647        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
648
649        let hs_msg = HsExtMessage {
650            srt_version: 0x0105_0000,
651            srt_flags: HandshakeConfig::default().flags,
652            receiver_tsbpd_delay: Duration::from_millis(120),
653            sender_tsbpd_delay: Duration::from_millis(120),
654        };
655        let ext = build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap();
656        let response = ControlPacket::Handshake(HandshakePacket {
657            timestamp: SrtTimestamp::ZERO,
658            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
659            version: HANDSHAKE_VERSION_5,
660            encryption_field: EncryptionField::NoEncryption,
661            extension_field: HandshakeExtensionFlags(0x0001),
662            initial_seq_number: 0,
663            mtu: 1500,
664            max_flow_window_size: 8192,
665            handshake_type: HandshakeType::Conclusion,
666            srt_socket_id: 0x1111_2222,
667            syn_cookie: 0xC0FF_EE00,
668            peer_ip: [0; 4],
669            extensions: HandshakeExtensions::parse(&ext).expect("test extension bytes"),
670        });
671        let out = c.feed(&response).unwrap();
672        assert!(
673            out.iter()
674                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
675        );
676        assert_eq!(c.state(), CallerHandshakeState::Connected);
677    }
678
679    fn conclusion_response_with(mtu: u32, mfw: u32, isn: u32) -> Vec<u8> {
680        use crate::packet::handshake::build_extension_block;
681        let hs_msg = HsExtMessage {
682            srt_version: 0x0105_0000,
683            srt_flags: HandshakeConfig::default().flags,
684            receiver_tsbpd_delay: Duration::from_millis(120),
685            sender_tsbpd_delay: Duration::from_millis(120),
686        };
687        let ext = build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap();
688        let pkt = ControlPacket::Handshake(HandshakePacket {
689            timestamp: SrtTimestamp::ZERO,
690            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
691            version: HANDSHAKE_VERSION_5,
692            encryption_field: EncryptionField::NoEncryption,
693            extension_field: HandshakeExtensionFlags(0x0001),
694            initial_seq_number: isn,
695            mtu,
696            max_flow_window_size: mfw,
697            handshake_type: HandshakeType::Conclusion,
698            srt_socket_id: 0x3333_4444,
699            syn_cookie: 0xC0FF_EE00,
700            peer_ip: [0; 4],
701            extensions: HandshakeExtensions::parse(&ext).expect("test extension bytes"),
702        });
703        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
704        pkt.serialize_into(&mut buf).unwrap();
705        buf
706    }
707
708    fn caller_awaiting_conclusion() -> CallerHandshake {
709        let mut c = CallerHandshake::new(0xAAAA_BBBB, HandshakeConfig::default());
710        c.start().unwrap();
711        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
712            .unwrap();
713        c
714    }
715
716    /// §3.2.1: the smaller of both sides' MTU and Maximum Flow Window Size.
717    #[test]
718    fn negotiated_mtu_and_flow_window_are_the_smaller_of_both() {
719        for (peer_mtu, peer_mfw, want_mtu, want_mfw) in [
720            (576, 64, 576, 64),
721            (9000, 65_536, 1500, 8192),
722            (1500, 64, 1500, 64),
723        ] {
724            let mut c = caller_awaiting_conclusion();
725            c.feed_bytes(&conclusion_response_with(peer_mtu, peer_mfw, 5))
726                .unwrap();
727            let n = c.negotiated().expect("connected");
728            assert_eq!((n.mtu, n.max_flow_window_size), (want_mtu, want_mfw));
729        }
730    }
731
732    /// A listener ISN that is not a 31-bit sequence number is refused.
733    #[test]
734    fn a_peer_isn_wider_than_31_bits_is_rejected() {
735        let mut c = caller_awaiting_conclusion();
736        let out = c
737            .feed_bytes(&conclusion_response_with(1500, 8192, 0x8000_0000))
738            .unwrap();
739        assert_eq!(out, vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
740        assert_eq!(c.state(), CallerHandshakeState::Rejected);
741        let mut c = caller_awaiting_conclusion();
742        c.feed_bytes(&conclusion_response_with(1500, 8192, 0x7FFF_FFFF))
743            .unwrap();
744        assert_eq!(c.state(), CallerHandshakeState::Connected);
745    }
746}