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(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::new(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.get(), 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::new(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                // See `on_induction_response`.
508                assert_eq!(hp.dest_socket_id, SocketId::CONNECTION_REQUEST);
509                assert_eq!(
510                    hp.extension_field.get() & HS_EXT_FLAG_HSREQ,
511                    HS_EXT_FLAG_HSREQ
512                );
513                let blocks: Vec<_> = hp.extensions.iter().collect();
514                assert_eq!(blocks.len(), 1);
515                assert_eq!(blocks[0].ext_type, ExtensionType::HsReq);
516            }
517            _ => panic!("expected handshake"),
518        }
519        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
520    }
521
522    #[test]
523    fn induction_response_bad_magic_is_rejected() {
524        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
525        c.start().unwrap();
526        let mut bad = induction_response(1, 2);
527        if let ControlPacket::Handshake(hp) = &mut bad {
528            hp.extension_field = HandshakeExtensionFlags::new(0x0000);
529        }
530        let outputs = c.feed(&bad).unwrap();
531        assert_eq!(
532            outputs,
533            vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]
534        );
535        assert_eq!(c.state(), CallerHandshakeState::Rejected);
536    }
537
538    #[test]
539    fn induction_response_bad_version_is_rejected() {
540        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
541        c.start().unwrap();
542        let mut bad = induction_response(1, 2);
543        if let ControlPacket::Handshake(hp) = &mut bad {
544            hp.version = HANDSHAKE_VERSION_4;
545        }
546        let outputs = c.feed(&bad).unwrap();
547        assert_eq!(
548            outputs,
549            vec![HandshakeOutput::Rejected(RejectionReason::Version)]
550        );
551        assert_eq!(c.state(), CallerHandshakeState::Rejected);
552    }
553
554    #[test]
555    fn explicit_peer_rejection_is_surfaced() {
556        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
557        c.start().unwrap();
558        let mut rejected = induction_response(1, 2);
559        if let ControlPacket::Handshake(hp) = &mut rejected {
560            hp.handshake_type = RejectionReason::Backlog.to_handshake_type();
561        }
562        let outputs = c.feed(&rejected).unwrap();
563        assert_eq!(
564            outputs,
565            vec![HandshakeOutput::Rejected(RejectionReason::Backlog)]
566        );
567        assert_eq!(c.state(), CallerHandshakeState::Rejected);
568    }
569
570    #[test]
571    fn feed_before_start_is_out_of_sequence() {
572        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
573        let resp = induction_response(1, 2);
574        assert!(matches!(
575            c.feed(&resp),
576            Err(Error::HandshakeOutOfSequence { .. })
577        ));
578    }
579
580    #[test]
581    fn feed_rejects_non_handshake_packets() {
582        use crate::packet::misc::KeepAlivePacket;
583        let mut c = CallerHandshake::new(1, HandshakeConfig::default());
584        c.start().unwrap();
585        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
586            timestamp: SrtTimestamp::ZERO,
587            dest_socket_id: SocketId::CONNECTION_REQUEST,
588            libsrt_pad: false,
589        });
590        assert!(matches!(
591            c.feed(&ka),
592            Err(Error::UnexpectedControlPacket { .. })
593        ));
594    }
595
596    #[test]
597    fn tick_retransmits_then_times_out() {
598        let config = HandshakeConfig {
599            retransmit_after: Duration::from_millis(500),
600            max_retries: 1,
601            ..HandshakeConfig::default()
602        };
603        let mut c = CallerHandshake::new(1, config);
604        let first = c.start().unwrap();
605
606        let step = Duration::from_millis(250);
607        assert_eq!(c.tick(step), Vec::new()); // 250 ms, under the 500 ms floor
608        let out = c.tick(step); // 500 ms: retransmit #1
609        assert_eq!(out, vec![HandshakeOutput::Send(first.clone())]);
610
611        assert_eq!(c.tick(step), Vec::new());
612        let out = c.tick(step); // retransmit #2 exceeds max_retries=1
613        assert_eq!(out, vec![HandshakeOutput::TimedOut]);
614        assert_eq!(c.state(), CallerHandshakeState::TimedOut);
615    }
616
617    #[test]
618    fn a_tick_elapsed_past_the_period_is_measured_not_counted() {
619        let config = HandshakeConfig {
620            retransmit_after: Duration::from_millis(500),
621            max_retries: 2,
622            ..HandshakeConfig::default()
623        };
624        let mut c = CallerHandshake::new(1, config);
625        let first = c.start().unwrap();
626        let out = c.tick(Duration::from_millis(600));
627        assert_eq!(
628            out,
629            vec![HandshakeOutput::Send(first)],
630            "one 600 ms step is past the 500 ms period: one retransmit, not zero"
631        );
632    }
633
634    /// r08-SRT-W10: a duplicate INDUCTION response after the CONCLUSION has
635    /// been sent is ignored; the handshake still completes on the real
636    /// CONCLUSION response (it used to be judged Rogue and abort).
637    #[test]
638    fn duplicate_induction_response_while_awaiting_conclusion_is_ignored() {
639        use crate::packet::handshake::build_extension_block;
640        let mut c = CallerHandshake::new(0xAAAA_BBBB, HandshakeConfig::default());
641        c.start().unwrap();
642        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
643            .unwrap();
644        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
645
646        let out = c
647            .feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
648            .unwrap();
649        assert_eq!(out, Vec::new());
650        assert_eq!(c.state(), CallerHandshakeState::AwaitingConclusionResponse);
651
652        let hs_msg = HsExtMessage {
653            srt_version: 0x0105_0000,
654            srt_flags: HandshakeConfig::default().flags,
655            receiver_tsbpd_delay: Duration::from_millis(120),
656            sender_tsbpd_delay: Duration::from_millis(120),
657        };
658        let ext = build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap();
659        let response = ControlPacket::Handshake(HandshakePacket {
660            timestamp: SrtTimestamp::ZERO,
661            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
662            version: HANDSHAKE_VERSION_5,
663            encryption_field: EncryptionField::NoEncryption,
664            extension_field: HandshakeExtensionFlags::new(0x0001),
665            initial_seq_number: 0,
666            mtu: 1500,
667            max_flow_window_size: 8192,
668            handshake_type: HandshakeType::Conclusion,
669            srt_socket_id: 0x1111_2222,
670            syn_cookie: 0xC0FF_EE00,
671            peer_ip: [0; 4],
672            extensions: HandshakeExtensions::parse(&ext).expect("test extension bytes"),
673        });
674        let out = c.feed(&response).unwrap();
675        assert!(
676            out.iter()
677                .any(|o| matches!(o, HandshakeOutput::Connected(_)))
678        );
679        assert_eq!(c.state(), CallerHandshakeState::Connected);
680    }
681
682    fn conclusion_response_with(mtu: u32, mfw: u32, isn: u32) -> Vec<u8> {
683        use crate::packet::handshake::build_extension_block;
684        let hs_msg = HsExtMessage {
685            srt_version: 0x0105_0000,
686            srt_flags: HandshakeConfig::default().flags,
687            receiver_tsbpd_delay: Duration::from_millis(120),
688            sender_tsbpd_delay: Duration::from_millis(120),
689        };
690        let ext = build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap();
691        let pkt = ControlPacket::Handshake(HandshakePacket {
692            timestamp: SrtTimestamp::ZERO,
693            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
694            version: HANDSHAKE_VERSION_5,
695            encryption_field: EncryptionField::NoEncryption,
696            extension_field: HandshakeExtensionFlags::new(0x0001),
697            initial_seq_number: isn,
698            mtu,
699            max_flow_window_size: mfw,
700            handshake_type: HandshakeType::Conclusion,
701            srt_socket_id: 0x3333_4444,
702            syn_cookie: 0xC0FF_EE00,
703            peer_ip: [0; 4],
704            extensions: HandshakeExtensions::parse(&ext).expect("test extension bytes"),
705        });
706        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
707        pkt.serialize_into(&mut buf).unwrap();
708        buf
709    }
710
711    fn caller_awaiting_conclusion() -> CallerHandshake {
712        let mut c = CallerHandshake::new(0xAAAA_BBBB, HandshakeConfig::default());
713        c.start().unwrap();
714        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
715            .unwrap();
716        c
717    }
718
719    /// §3.2.1: the smaller of both sides' MTU and Maximum Flow Window Size.
720    #[test]
721    fn negotiated_mtu_and_flow_window_are_the_smaller_of_both() {
722        for (peer_mtu, peer_mfw, want_mtu, want_mfw) in [
723            (576, 64, 576, 64),
724            (9000, 65_536, 1500, 8192),
725            (1500, 64, 1500, 64),
726        ] {
727            let mut c = caller_awaiting_conclusion();
728            c.feed_bytes(&conclusion_response_with(peer_mtu, peer_mfw, 5))
729                .unwrap();
730            let n = c.negotiated().expect("connected");
731            assert_eq!((n.mtu, n.max_flow_window_size), (want_mtu, want_mfw));
732        }
733    }
734
735    /// A listener ISN that is not a 31-bit sequence number is refused.
736    #[test]
737    fn a_peer_isn_wider_than_31_bits_is_rejected() {
738        let mut c = caller_awaiting_conclusion();
739        let out = c
740            .feed_bytes(&conclusion_response_with(1500, 8192, 0x8000_0000))
741            .unwrap();
742        assert_eq!(out, vec![HandshakeOutput::Rejected(RejectionReason::Rogue)]);
743        assert_eq!(c.state(), CallerHandshakeState::Rejected);
744        let mut c = caller_awaiting_conclusion();
745        c.feed_bytes(&conclusion_response_with(1500, 8192, 0x7FFF_FFFF))
746            .unwrap();
747        assert_eq!(c.state(), CallerHandshakeState::Connected);
748    }
749
750    fn conclusion_with_peer_flags(peer_flags: u32) -> ControlPacket<'static> {
751        use crate::packet::handshake::{HandshakeExtensionMessageFlags, build_extension_block};
752        let hs_msg = HsExtMessage {
753            srt_version: 0x0105_0000,
754            srt_flags: HandshakeExtensionMessageFlags::new(peer_flags),
755            receiver_tsbpd_delay: Duration::from_millis(120),
756            sender_tsbpd_delay: Duration::from_millis(120),
757        };
758        let ext: &'static [u8] = alloc::vec::Vec::leak(
759            build_extension_block(ExtensionType::HsRsp, &hs_msg.to_bytes()).unwrap(),
760        );
761        ControlPacket::Handshake(HandshakePacket {
762            timestamp: SrtTimestamp::ZERO,
763            dest_socket_id: SocketId::from_wire(0xAAAA_BBBB),
764            version: HANDSHAKE_VERSION_5,
765            encryption_field: EncryptionField::NoEncryption,
766            extension_field: HandshakeExtensionFlags::new(0x0001),
767            initial_seq_number: 0,
768            mtu: 1500,
769            max_flow_window_size: 8192,
770            handshake_type: HandshakeType::Conclusion,
771            srt_socket_id: 0x3333_4444,
772            syn_cookie: 0xC0FF_EE00,
773            peer_ip: [0; 4],
774            extensions: HandshakeExtensions::parse(ext).expect("test extension bytes"),
775        })
776    }
777
778    /// §3.2.1.1: the connection's flags are the bitwise intersection of both
779    /// sides' advertised sets, never a union or a symmetric difference.
780    #[test]
781    fn negotiated_flags_are_the_intersection_of_both_sides() {
782        use crate::packet::handshake::{
783            HS_MSG_FLAG_PERIODICNAK, HS_MSG_FLAG_REXMITFLG, HS_MSG_FLAG_TLPKTDROP,
784            HS_MSG_FLAG_TSBPDRCV, HS_MSG_FLAG_TSBPDSND, HandshakeExtensionMessageFlags,
785        };
786        let local = HS_MSG_FLAG_TSBPDSND
787            | HS_MSG_FLAG_TSBPDRCV
788            | HS_MSG_FLAG_TLPKTDROP
789            | HS_MSG_FLAG_PERIODICNAK
790            | HS_MSG_FLAG_REXMITFLG;
791        let peer = HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TSBPDRCV | HS_MSG_FLAG_REXMITFLG;
792        let config =
793            HandshakeConfig::default().with_flags(HandshakeExtensionMessageFlags::new(local));
794        let mut c = CallerHandshake::new(0xAAAA_BBBB, config);
795        c.start().unwrap();
796        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
797            .unwrap();
798        c.feed(&conclusion_with_peer_flags(peer)).unwrap();
799        assert_eq!(
800            c.negotiated().expect("connected").flags,
801            HandshakeExtensionMessageFlags::new(peer)
802        );
803    }
804
805    #[test]
806    fn negotiated_flags_drop_a_flag_only_the_peer_advertises() {
807        use crate::packet::handshake::{
808            HS_MSG_FLAG_TLPKTDROP, HS_MSG_FLAG_TSBPDSND, HandshakeExtensionMessageFlags,
809        };
810        let config = HandshakeConfig::default()
811            .with_flags(HandshakeExtensionMessageFlags::new(HS_MSG_FLAG_TSBPDSND));
812        let mut c = CallerHandshake::new(0xAAAA_BBBB, config);
813        c.start().unwrap();
814        c.feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
815            .unwrap();
816        c.feed(&conclusion_with_peer_flags(
817            HS_MSG_FLAG_TSBPDSND | HS_MSG_FLAG_TLPKTDROP,
818        ))
819        .unwrap();
820        assert_eq!(
821            c.negotiated().expect("connected").flags,
822            HandshakeExtensionMessageFlags::new(HS_MSG_FLAG_TSBPDSND)
823        );
824    }
825
826    /// The configured SRT version, flags and local IP are the ones the
827    /// CONCLUSION's HSREQ and CIF actually advertise.
828    #[test]
829    fn configured_handshake_values_are_carried_on_the_wire() {
830        use crate::packet::handshake::HandshakeExtensionMessageFlags;
831        let config = HandshakeConfig::default()
832            .with_srt_version(0x0105_0003)
833            .with_flags(HandshakeExtensionMessageFlags::new(0x0000_0063))
834            .with_local_ip([10, 0, 0, 7]);
835        let mut c = CallerHandshake::new(0xAAAA_BBBB, config);
836        c.start().unwrap();
837        let outputs = c
838            .feed(&induction_response(0xC0FF_EE00, 0x1111_2222))
839            .unwrap();
840        let bytes = match &outputs[0] {
841            HandshakeOutput::Send(b) => b.clone(),
842            other => panic!("expected Send, got {other:?}"),
843        };
844        let ControlPacket::Handshake(hp) = ControlPacket::parse(&bytes).unwrap() else {
845            panic!("expected handshake");
846        };
847        assert_eq!(hp.peer_ip, [10, 0, 0, 7]);
848        let parsed = crate::handshake_sm::parse_peer_extensions(&hp).expect("extensions");
849        let msg = parsed.hs_msg.expect("HSREQ");
850        assert_eq!(msg.srt_version, 0x0105_0003);
851        assert_eq!(msg.srt_flags.get(), 0x0000_0063);
852    }
853
854    #[test]
855    fn state_labels_match_the_diagram_names() {
856        assert_eq!(CallerHandshakeState::Idle.name(), "Idle");
857        assert_eq!(
858            CallerHandshakeState::AwaitingInductionResponse.name(),
859            "AwaitingInductionResponse"
860        );
861        assert_eq!(
862            CallerHandshakeState::AwaitingConclusionResponse.name(),
863            "AwaitingConclusionResponse"
864        );
865        assert_eq!(CallerHandshakeState::Connected.name(), "Connected");
866        assert_eq!(CallerHandshakeState::Rejected.name(), "Rejected");
867        assert_eq!(CallerHandshakeState::TimedOut.name(), "TimedOut");
868    }
869}