Skip to main content

srt_runtime/
url.rs

1//! The `srt://` URL a caller dials (draft-sharabayko-srt-01 §3.2.1.3 Stream
2//! ID; the scheme itself is SRT's registered URL form).
3//!
4//! An SRT endpoint is a `host:port` plus the query overrides the Stream ID
5//! handshake extension carries: `streamid` (opaque, passed through to the
6//! handshake), `latency`, `mode` and `passphrase`. This module parses that
7//! form into a typed [`SrtUrl`]; *which* values an endpoint accepts is policy
8//! and belongs to the caller (the `multimux` push, for one, dials only in
9//! Caller mode and rejects a passphrase).
10//!
11//! `std` only: the authority and query are parsed with the `url` crate and
12//! `streamid` values are percent-decoded with `percent_encoding`.
13//!
14//! # Accepted shapes
15//!
16//! Both `srt://host:port?…` and a scheme-less `host:port?…` are accepted (an
17//! operator's configured remote is often just `host:port`). An authority may
18//! be `host`, `host:port`, `[v6]` or `[v6]:port`; a userinfo prefix is
19//! rejected rather than silently dropped, because an SRT authority has no
20//! credentials and a stream key written after `@` must not vanish into a bare
21//! `host:port`. A bare, unbracketed IPv6 literal is rejected: `::1:9000` is
22//! ambiguous (is `9000` a port or the last group?), so the operator brackets
23//! it.
24//!
25//! The query is split off the raw text rather than read through
26//! `Url::query_pairs`, a documented exception to the workspace's de-hand-roll
27//! rule (spec §9): a Haivision `streamid=#!::r=…` value contains a `#` that a
28//! `Url` treats as a fragment delimiter, which would cut the value short
29//! unless it were percent-encoded. Splitting first keeps the whole value.
30
31use alloc::string::{String, ToString};
32use core::net::{IpAddr, SocketAddr};
33
34/// SRT's registered default port, so a URL that omits the port still names a
35/// dialable endpoint.
36pub const DEFAULT_PORT: u16 = 9000;
37
38/// The largest `latency` the draft treats as practical
39/// (draft-sharabayko-srt-01 §3.2.1.1), in milliseconds. A larger value is
40/// rejected rather than clamped: a wrong latency is a real misconfiguration.
41pub const MAX_LATENCY_MS: u16 = 8000;
42
43/// Which side opens the SRT handshake (`draft-sharabayko-srt-01` §4.3).
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45#[non_exhaustive]
46pub enum SrtMode {
47    /// The caller dials a listener.
48    #[default]
49    Caller,
50    /// The endpoint binds and accepts inbound callers.
51    Listener,
52}
53
54impl UrlRejection {
55    /// The `name()` label convention (#204).
56    #[must_use]
57    pub fn name(&self) -> &'static str {
58        match self {
59            UrlRejection::Authority => "authority",
60            UrlRejection::LatencyNotANumber => "latency-not-a-number",
61            UrlRejection::LatencyTooLarge => "latency-too-large",
62            UrlRejection::Mode => "mode",
63            UrlRejection::InvalidUtf8 => "invalid-utf8",
64            UrlRejection::DuplicateKey => "duplicate-key",
65        }
66    }
67}
68
69impl SrtMode {
70    /// The `name()` label convention (#204).
71    #[must_use]
72    pub fn name(&self) -> &'static str {
73        match self {
74            SrtMode::Caller => "caller",
75            SrtMode::Listener => "listener",
76        }
77    }
78}
79
80broadcast_common::impl_spec_display!(SrtMode);
81broadcast_common::impl_spec_display!(UrlRejection);
82
83/// A parsed `srt://` URL: the endpoint to dial and its Stream ID overrides.
84#[derive(Clone, PartialEq, Eq)]
85#[non_exhaustive]
86pub struct SrtUrl {
87    /// The endpoint's host (a domain name or a bracketed IP literal).
88    pub host: String,
89    /// The endpoint's port, [`DEFAULT_PORT`] when the URL omits it.
90    pub port: u16,
91    /// The opaque `streamid` value, percent-decoded.
92    pub stream_id: Option<String>,
93    /// The `latency` value in milliseconds, at most [`MAX_LATENCY_MS`].
94    pub latency_ms: Option<u16>,
95    /// The `mode` value; [`SrtMode::Caller`] when absent.
96    pub mode: SrtMode,
97    /// The `passphrase` value (payload encryption).
98    pub passphrase: Option<String>,
99}
100
101/// Why an `srt://` URL was rejected: the failing part of the grammar, so a
102/// caller can word its own error while the grammar stays in one place.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum UrlRejection {
106    /// The authority is not a `host[:port]` — no host, a bad port, a userinfo
107    /// prefix, or an ambiguous bare IPv6 literal.
108    Authority,
109    /// A `latency` that is not whole milliseconds.
110    LatencyNotANumber,
111    /// A `latency` above [`MAX_LATENCY_MS`].
112    LatencyTooLarge,
113    /// A `mode` other than `caller` or `listener`.
114    Mode,
115    /// A percent-decoded value was not valid UTF-8.
116    InvalidUtf8,
117    /// The same query key appeared more than once.
118    DuplicateKey,
119}
120
121/// Manual `Debug`: a `passphrase` is a secret and never renders.
122impl core::fmt::Debug for SrtUrl {
123    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
124        f.debug_struct("SrtUrl")
125            .field("host", &self.host)
126            .field("port", &self.port)
127            .field("stream_id", &self.stream_id)
128            .field("latency_ms", &self.latency_ms)
129            .field("mode", &self.mode)
130            .field(
131                "passphrase",
132                &self.passphrase.as_ref().map(|_| "<redacted>"),
133            )
134            .finish()
135    }
136}
137
138impl SrtUrl {
139    /// Parse an `srt://` URL; see this module's own doc for the accepted
140    /// shapes.
141    ///
142    /// An absent `latency`, `mode` or `passphrase` leaves the corresponding
143    /// field unset, so the caller keeps whatever its handshake config already
144    /// holds. Unknown query keys are ignored.
145    ///
146    /// # Errors
147    ///
148    /// [`UrlRejection::Authority`] for a bad authority,
149    /// [`UrlRejection::LatencyNotANumber`]/[`UrlRejection::LatencyTooLarge`]
150    /// for a `latency`, and [`UrlRejection::Mode`] for an unknown `mode`.
151    pub fn parse(url: &str) -> Result<Self, UrlRejection> {
152        let (authority, query) = match url.split_once("srt://") {
153            Some(("", rest)) => match rest.split_once('?') {
154                Some((authority, query)) => (authority, Some(query)),
155                None => (rest, None),
156            },
157            _ => match url.split_once('?') {
158                Some((authority, query)) => (authority, Some(query)),
159                None => (url, None),
160            },
161        };
162        let (host, port) = parse_authority(authority).ok_or(UrlRejection::Authority)?;
163
164        let mut parsed = Self {
165            host,
166            port,
167            stream_id: None,
168            latency_ms: None,
169            mode: SrtMode::Caller,
170            passphrase: None,
171        };
172        if let Some(query) = query {
173            let mut seen: alloc::vec::Vec<String> = alloc::vec::Vec::new();
174            for pair in query.split('&') {
175                if pair.is_empty() {
176                    continue;
177                }
178                let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
179                let Ok(key) = percent_decode(key) else {
180                    continue;
181                };
182                let recognised =
183                    matches!(key.as_str(), "streamid" | "latency" | "mode" | "passphrase");
184                if recognised {
185                    if seen.contains(&key) {
186                        return Err(UrlRejection::DuplicateKey);
187                    }
188                    seen.push(key.clone());
189                }
190                match key.as_str() {
191                    "streamid" => parsed.stream_id = Some(percent_decode(value)?),
192                    "latency" => {
193                        parsed.latency_ms = Some(parse_latency(value)?);
194                    }
195                    "mode" => parsed.mode = parse_mode(value).ok_or(UrlRejection::Mode)?,
196                    "passphrase" => parsed.passphrase = Some(percent_decode(value)?),
197                    _ => {}
198                }
199            }
200        }
201        Ok(parsed)
202    }
203
204    /// The handshake's dial address: `host:port`, or the literal socket
205    /// address when the host already is an IP.
206    #[must_use]
207    pub fn dial_addr(&self) -> String {
208        match self.host.parse::<IpAddr>() {
209            Ok(ip) => SocketAddr::new(ip, self.port).to_string(),
210            Err(_) => format!("{}:{}", self.host, self.port),
211        }
212    }
213}
214
215/// Parse an SRT authority into `(host, port)`, or `None` when it is not one.
216fn parse_authority(authority: &str) -> Option<(String, u16)> {
217    let authority = authority.trim_end_matches('/');
218    if authority.is_empty() {
219        return None;
220    }
221    let url = url::Url::parse(&format!("srt://{authority}")).ok()?;
222    if !url.username().is_empty() || url.password().is_some() {
223        return None;
224    }
225    let host = url.host_str()?.to_string();
226    Some((host, url.port().unwrap_or(DEFAULT_PORT)))
227}
228
229/// Parse a `latency` value: whole milliseconds, at most [`MAX_LATENCY_MS`].
230fn parse_latency(value: &str) -> Result<u16, UrlRejection> {
231    let ms = value
232        .parse::<u16>()
233        .map_err(|_| UrlRejection::LatencyNotANumber)?;
234    if ms > MAX_LATENCY_MS {
235        return Err(UrlRejection::LatencyTooLarge);
236    }
237    Ok(ms)
238}
239
240/// Parse a `mode` value.
241fn parse_mode(value: &str) -> Option<SrtMode> {
242    match value {
243        "caller" => Some(SrtMode::Caller),
244        "listener" => Some(SrtMode::Listener),
245        _ => None,
246    }
247}
248
249/// Percent-decode a query value. A stray `%` with no valid hex pair is kept
250/// literally rather than dropped.
251fn percent_decode(value: &str) -> Result<String, UrlRejection> {
252    let bytes: alloc::vec::Vec<u8> = percent_encoding::percent_decode_str(value).collect();
253    String::from_utf8(bytes).map_err(|_| UrlRejection::InvalidUtf8)
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    #[test]
261    fn debug_redacts_the_passphrase() {
262        let url = SrtUrl::parse("srt://h?passphrase=SECRET").expect("passphrase");
263        let rendered = format!("{url:?}");
264        assert!(!rendered.contains("SECRET"), "{rendered}");
265        assert!(rendered.contains("<redacted>"), "{rendered}");
266    }
267
268    #[test]
269    fn host_only_takes_the_default_port() {
270        let url = SrtUrl::parse("srt://example.com").expect("host only");
271        assert_eq!(url.host, "example.com");
272        assert_eq!(url.port, DEFAULT_PORT);
273        assert_eq!(url.mode, SrtMode::Caller);
274    }
275
276    #[test]
277    fn bracketed_ipv6_keeps_its_brackets_off_the_host() {
278        let url = SrtUrl::parse("srt://[::1]:9001").expect("bracketed v6");
279        assert_eq!(url.host, "[::1]");
280        assert_eq!(url.dial_addr(), "[::1]:9001");
281    }
282
283    #[test]
284    fn a_bare_ipv6_literal_is_ambiguous_not_guessed() {
285        assert_eq!(SrtUrl::parse("::1:9000"), Err(UrlRejection::Authority));
286    }
287
288    #[test]
289    fn the_latency_cap_is_the_drafts() {
290        assert!(SrtUrl::parse("srt://h?latency=8000").is_ok());
291        assert_eq!(
292            SrtUrl::parse("srt://h?latency=8001"),
293            Err(UrlRejection::LatencyTooLarge)
294        );
295        assert_eq!(
296            SrtUrl::parse("srt://h?latency=late"),
297            Err(UrlRejection::LatencyNotANumber)
298        );
299    }
300    #[test]
301    fn invalid_utf8_percent_decode_is_rejected() {
302        assert_eq!(
303            SrtUrl::parse("srt://h:9000?streamid=%FF"),
304            Err(UrlRejection::InvalidUtf8)
305        );
306        assert_eq!(
307            SrtUrl::parse("srt://h:9000?passphrase=%C3%28extra"),
308            Err(UrlRejection::InvalidUtf8)
309        );
310    }
311
312    #[test]
313    fn duplicate_query_key_is_rejected() {
314        assert_eq!(
315            SrtUrl::parse("srt://h:9000?latency=10&latency=20"),
316            Err(UrlRejection::DuplicateKey)
317        );
318    }
319
320    #[test]
321    fn duplicate_query_key_decoded_is_rejected() {
322        assert_eq!(
323            SrtUrl::parse("srt://h:9000?%6Catency=10&latency=20"),
324            Err(UrlRejection::DuplicateKey)
325        );
326    }
327
328    #[test]
329    fn unknown_key_with_invalid_utf8_is_ignored() {
330        let url = SrtUrl::parse("srt://h:9000?%ff=1&latency=120").expect("ignored key");
331        assert_eq!(url.latency_ms, Some(120));
332    }
333
334    #[test]
335    fn repeated_unknown_query_key_is_ignored() {
336        assert!(SrtUrl::parse("srt://h:9000?foo=1&foo=2").is_ok());
337    }
338
339    #[test]
340    fn valid_percent_encoded_utf8_streamid_decodes() {
341        let url = SrtUrl::parse("srt://h:9000?streamid=%C3%A9").expect("valid utf8");
342        assert_eq!(url.stream_id.as_deref(), Some("é"));
343    }
344}