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 whole string is parsed with `url::Url` (so the scheme is matched
26//! case-insensitively and the authority is read by the `url` crate, not by a
27//! hand-rolled split). A Haivision `streamid=#!::r=…` value contains a `#` that
28//! a `Url` treats as a fragment delimiter, which would cut the value short
29//! unless it were percent-encoded; every `#` after the query separator is
30//! escaped to `%23` before parsing and the query is then split on `&` and
31//! percent-decoded value-by-value, restoring it.
32
33use alloc::string::{String, ToString};
34use core::net::{IpAddr, SocketAddr};
35use core::time::Duration;
36
37/// SRT's registered default port, so a URL that omits the port still names a
38/// dialable endpoint.
39pub const DEFAULT_PORT: u16 = 9000;
40
41/// The largest `latency` the draft treats as practical
42/// (draft-sharabayko-srt-01 §3.2.1.1), in milliseconds. A larger value is
43/// rejected rather than clamped: a wrong latency is a real misconfiguration.
44pub const MAX_LATENCY_MS: u16 = 8000;
45
46/// Which side opens the SRT handshake (`draft-sharabayko-srt-01` §4.3).
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
48#[non_exhaustive]
49pub enum SrtMode {
50    /// The caller dials a listener.
51    #[default]
52    Caller,
53    /// The endpoint binds and accepts inbound callers.
54    Listener,
55}
56
57impl UrlRejection {
58    /// The `name()` label convention (#204).
59    #[must_use]
60    pub fn name(&self) -> &'static str {
61        match self {
62            UrlRejection::Authority => "authority",
63            UrlRejection::LatencyNotANumber => "latency-not-a-number",
64            UrlRejection::LatencyTooLarge => "latency-too-large",
65            UrlRejection::Mode => "mode",
66            UrlRejection::InvalidUtf8 => "invalid-utf8",
67            UrlRejection::DuplicateKey => "duplicate-key",
68        }
69    }
70}
71
72impl SrtMode {
73    /// The `name()` label convention (#204).
74    #[must_use]
75    pub fn name(&self) -> &'static str {
76        match self {
77            SrtMode::Caller => "caller",
78            SrtMode::Listener => "listener",
79        }
80    }
81}
82
83broadcast_common::impl_spec_display!(SrtMode);
84broadcast_common::impl_spec_display!(UrlRejection);
85
86/// A parsed `srt://` URL: the endpoint to dial and its Stream ID overrides.
87#[derive(Clone, PartialEq, Eq)]
88#[non_exhaustive]
89pub struct SrtUrl {
90    /// The endpoint's host (a domain name or a bracketed IP literal).
91    pub host: String,
92    /// The endpoint's port, [`DEFAULT_PORT`] when the URL omits it.
93    pub port: u16,
94    /// The opaque `streamid` value, percent-decoded.
95    pub stream_id: Option<String>,
96    /// The `latency` value, at most [`MAX_LATENCY_MS`].
97    pub latency: Option<Duration>,
98    /// The `mode` value; [`SrtMode::Caller`] when absent.
99    pub mode: SrtMode,
100    /// The `passphrase` value (payload encryption).
101    pub passphrase: Option<String>,
102}
103
104/// Why an `srt://` URL was rejected: the failing part of the grammar, so a
105/// caller can word its own error while the grammar stays in one place.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107#[non_exhaustive]
108pub enum UrlRejection {
109    /// The authority is not a `host[:port]` — no host, a bad port, a userinfo
110    /// prefix, or an ambiguous bare IPv6 literal.
111    Authority,
112    /// A `latency` that is not whole milliseconds.
113    LatencyNotANumber,
114    /// A `latency` above [`MAX_LATENCY_MS`].
115    LatencyTooLarge,
116    /// A `mode` other than `caller` or `listener`.
117    Mode,
118    /// A percent-decoded value was not valid UTF-8.
119    InvalidUtf8,
120    /// The same query key appeared more than once.
121    DuplicateKey,
122}
123
124/// Manual `Debug`: a `passphrase` is a secret and never renders.
125impl core::fmt::Debug for SrtUrl {
126    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
127        f.debug_struct("SrtUrl")
128            .field("host", &self.host)
129            .field("port", &self.port)
130            .field("stream_id", &self.stream_id)
131            .field("latency", &self.latency)
132            .field("mode", &self.mode)
133            .field(
134                "passphrase",
135                &self.passphrase.as_ref().map(|_| "<redacted>"),
136            )
137            .finish()
138    }
139}
140
141impl SrtUrl {
142    /// Parse an `srt://` URL; see this module's own doc for the accepted
143    /// shapes.
144    ///
145    /// An absent `latency`, `mode` or `passphrase` leaves the corresponding
146    /// field unset, so the caller keeps whatever its handshake config already
147    /// holds. Unknown query keys are ignored.
148    ///
149    /// # Errors
150    ///
151    /// [`UrlRejection::Authority`] for a bad authority,
152    /// [`UrlRejection::LatencyNotANumber`]/[`UrlRejection::LatencyTooLarge`]
153    /// for a `latency`, and [`UrlRejection::Mode`] for an unknown `mode`.
154    pub fn parse(url: &str) -> Result<Self, UrlRejection> {
155        let parsed_url = parse_url(url).ok_or(UrlRejection::Authority)?;
156        if !parsed_url.username().is_empty() || parsed_url.password().is_some() {
157            return Err(UrlRejection::Authority);
158        }
159        let host = bracketed_host(&parsed_url).ok_or(UrlRejection::Authority)?;
160        let port = parsed_url.port().unwrap_or(DEFAULT_PORT);
161
162        let mut parsed = Self {
163            host,
164            port,
165            stream_id: None,
166            latency: None,
167            mode: SrtMode::Caller,
168            passphrase: None,
169        };
170        if let Some(query) = parsed_url.query() {
171            let mut seen: alloc::vec::Vec<String> = alloc::vec::Vec::new();
172            for pair in query.split('&') {
173                if pair.is_empty() {
174                    continue;
175                }
176                let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
177                let Ok(key) = percent_decode(key) else {
178                    continue;
179                };
180                let recognised =
181                    matches!(key.as_str(), "streamid" | "latency" | "mode" | "passphrase");
182                if recognised {
183                    if seen.contains(&key) {
184                        return Err(UrlRejection::DuplicateKey);
185                    }
186                    seen.push(key.clone());
187                }
188                match key.as_str() {
189                    "streamid" => parsed.stream_id = Some(percent_decode(value)?),
190                    "latency" => {
191                        parsed.latency = Some(parse_latency(value)?);
192                    }
193                    "mode" => parsed.mode = parse_mode(value).ok_or(UrlRejection::Mode)?,
194                    "passphrase" => parsed.passphrase = Some(percent_decode(value)?),
195                    _ => {}
196                }
197            }
198        }
199        Ok(parsed)
200    }
201
202    /// The handshake's dial address: `host:port`, or the literal socket
203    /// address when the host already is an IP.
204    #[must_use]
205    pub fn dial_addr(&self) -> String {
206        match self.host.parse::<IpAddr>() {
207            Ok(ip) => SocketAddr::new(ip, self.port).to_string(),
208            Err(_) => format!("{}:{}", self.host, self.port),
209        }
210    }
211}
212
213/// Parse the whole `srt://host[:port][?query]` or scheme-less `host[:port][?query]`
214/// string into a `url::Url`, or `None` when it is not one.
215///
216/// A Haivision `streamid=#!::r=…` value contains a `#` that a `Url` treats as
217/// a fragment delimiter (cutting the value short) unless it is percent-encoded,
218/// so every `#` after the query separator is escaped to `%23` before parsing;
219/// the query is then percent-decoded value-by-value, restoring it. The SRT
220/// scheme is matched case-insensitively by [`has_srt_scheme`], so `SRT://` names
221/// the same endpoint as `srt://`; a string with no explicit SRT scheme is an
222/// operator's bare `host:port` and is prefixed with `srt://` before parsing.
223fn parse_url(input: &str) -> Option<url::Url> {
224    let escaped = escape_query_fragments(input);
225    if has_srt_scheme(&escaped) {
226        url::Url::parse(&escaped).ok()
227    } else {
228        url::Url::parse(&alloc::format!("srt://{escaped}")).ok()
229    }
230}
231
232/// Whether `input` opens with an explicit `srt://` scheme, matched
233/// case-insensitively. An explicit scheme is parsed as an absolute URL (and a
234/// malformed one is rejected), never re-prefixed: that keeps a bad authority
235/// like `srt://::1` an error instead of turning into a host named `srt`.
236fn has_srt_scheme(input: &str) -> bool {
237    input
238        .get(.."srt://".len())
239        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("srt://"))
240}
241
242/// Percent-encode every `#` that occurs after the first `?`, so a `#` inside a
243/// query value is not read as a fragment delimiter (see [`parse_url`]).
244fn escape_query_fragments(input: &str) -> alloc::string::String {
245    match input.split_once('?') {
246        Some((head, query)) => {
247            let mut out = alloc::string::String::with_capacity(input.len() + 8);
248            out.push_str(head);
249            out.push('?');
250            for ch in query.chars() {
251                if ch == '#' {
252                    out.push_str("%23");
253                } else {
254                    out.push(ch);
255                }
256            }
257            out
258        }
259        None => input.into(),
260    }
261}
262
263/// The host as `SrtUrl` exposes it: a bracketed IPv6 literal keeps its
264/// brackets (`[::1]`), matching [`SrtUrl::dial_addr`]'s output.
265fn bracketed_host(url: &url::Url) -> Option<String> {
266    url.host_str().map(alloc::string::ToString::to_string)
267}
268
269/// Parse a `latency` value: whole milliseconds, at most [`MAX_LATENCY_MS`].
270fn parse_latency(value: &str) -> Result<Duration, UrlRejection> {
271    let ms = value
272        .parse::<u16>()
273        .map_err(|_| UrlRejection::LatencyNotANumber)?;
274    if ms > MAX_LATENCY_MS {
275        return Err(UrlRejection::LatencyTooLarge);
276    }
277    Ok(Duration::from_millis(u64::from(ms)))
278}
279
280/// Parse a `mode` value.
281fn parse_mode(value: &str) -> Option<SrtMode> {
282    match value {
283        "caller" => Some(SrtMode::Caller),
284        "listener" => Some(SrtMode::Listener),
285        _ => None,
286    }
287}
288
289/// Percent-decode a query value. A stray `%` with no valid hex pair is kept
290/// literally rather than dropped.
291fn percent_decode(value: &str) -> Result<String, UrlRejection> {
292    let bytes: alloc::vec::Vec<u8> = percent_encoding::percent_decode_str(value).collect();
293    String::from_utf8(bytes).map_err(|_| UrlRejection::InvalidUtf8)
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    #[test]
301    fn debug_redacts_the_passphrase() {
302        let url = SrtUrl::parse("srt://h?passphrase=SECRET").expect("passphrase");
303        let rendered = format!("{url:?}");
304        assert!(!rendered.contains("SECRET"), "{rendered}");
305        assert!(rendered.contains("<redacted>"), "{rendered}");
306    }
307
308    #[test]
309    fn host_only_takes_the_default_port() {
310        let url = SrtUrl::parse("srt://example.com").expect("host only");
311        assert_eq!(url.host, "example.com");
312        assert_eq!(url.port, DEFAULT_PORT);
313        assert_eq!(url.mode, SrtMode::Caller);
314    }
315
316    #[test]
317    fn bracketed_ipv6_keeps_its_brackets_off_the_host() {
318        let url = SrtUrl::parse("srt://[::1]:9001").expect("bracketed v6");
319        assert_eq!(url.host, "[::1]");
320        assert_eq!(url.dial_addr(), "[::1]:9001");
321    }
322
323    #[test]
324    fn a_bare_ipv6_literal_is_ambiguous_not_guessed() {
325        assert_eq!(SrtUrl::parse("::1:9000"), Err(UrlRejection::Authority));
326    }
327
328    #[test]
329    fn the_latency_cap_is_the_drafts() {
330        assert!(SrtUrl::parse("srt://h?latency=8000").is_ok());
331        assert_eq!(
332            SrtUrl::parse("srt://h?latency=8001"),
333            Err(UrlRejection::LatencyTooLarge)
334        );
335        assert_eq!(
336            SrtUrl::parse("srt://h?latency=late"),
337            Err(UrlRejection::LatencyNotANumber)
338        );
339    }
340    #[test]
341    fn invalid_utf8_percent_decode_is_rejected() {
342        assert_eq!(
343            SrtUrl::parse("srt://h:9000?streamid=%FF"),
344            Err(UrlRejection::InvalidUtf8)
345        );
346        assert_eq!(
347            SrtUrl::parse("srt://h:9000?passphrase=%C3%28extra"),
348            Err(UrlRejection::InvalidUtf8)
349        );
350    }
351
352    #[test]
353    fn duplicate_query_key_is_rejected() {
354        assert_eq!(
355            SrtUrl::parse("srt://h:9000?latency=10&latency=20"),
356            Err(UrlRejection::DuplicateKey)
357        );
358    }
359
360    #[test]
361    fn duplicate_query_key_decoded_is_rejected() {
362        assert_eq!(
363            SrtUrl::parse("srt://h:9000?%6Catency=10&latency=20"),
364            Err(UrlRejection::DuplicateKey)
365        );
366    }
367
368    #[test]
369    fn unknown_key_with_invalid_utf8_is_ignored() {
370        let url = SrtUrl::parse("srt://h:9000?%ff=1&latency=120").expect("ignored key");
371        assert_eq!(url.latency, Some(Duration::from_millis(120)));
372    }
373
374    #[test]
375    fn repeated_unknown_query_key_is_ignored() {
376        assert!(SrtUrl::parse("srt://h:9000?foo=1&foo=2").is_ok());
377    }
378
379    #[test]
380    fn valid_percent_encoded_utf8_streamid_decodes() {
381        let url = SrtUrl::parse("srt://h:9000?streamid=%C3%A9").expect("valid utf8");
382        assert_eq!(url.stream_id.as_deref(), Some("é"));
383    }
384
385    #[test]
386    fn the_srt_scheme_is_case_insensitive() {
387        // Before this parsed through `url::Url`, the scheme was matched by a
388        // case-sensitive `split_once("srt://")`, so `SRT://` fell through to
389        // the scheme-less branch and became a host literally named `SRT://h`.
390        let url = SrtUrl::parse("SRT://h:9000").expect("uppercase scheme names the same endpoint");
391        assert_eq!(url.host, "h");
392        assert_eq!(url.port, 9000);
393    }
394
395    #[test]
396    fn a_hash_inside_a_streamid_value_is_kept_whole() {
397        // A Haivision streamid value carries a `#`; a naive `Url` parse would
398        // treat it as a fragment delimiter and cut the value short.
399        let url = SrtUrl::parse("srt://h:9000?streamid=#!::r=live/cam,m=publish")
400            .expect("hash-bearing streamid");
401        assert_eq!(url.stream_id.as_deref(), Some("#!::r=live/cam,m=publish"));
402    }
403}