1use alloc::string::{String, ToString};
34use core::net::{IpAddr, SocketAddr};
35use core::time::Duration;
36
37pub const DEFAULT_PORT: u16 = 9000;
40
41pub const MAX_LATENCY_MS: u16 = 8000;
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
48#[non_exhaustive]
49pub enum SrtMode {
50 #[default]
52 Caller,
53 Listener,
55}
56
57impl UrlRejection {
58 #[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 #[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#[derive(Clone, PartialEq, Eq)]
88#[non_exhaustive]
89pub struct SrtUrl {
90 pub host: String,
92 pub port: u16,
94 pub stream_id: Option<String>,
96 pub latency: Option<Duration>,
98 pub mode: SrtMode,
100 pub passphrase: Option<String>,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107#[non_exhaustive]
108pub enum UrlRejection {
109 Authority,
112 LatencyNotANumber,
114 LatencyTooLarge,
116 Mode,
118 InvalidUtf8,
120 DuplicateKey,
122}
123
124impl 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 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 #[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
213fn 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
232fn 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
242fn 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
263fn bracketed_host(url: &url::Url) -> Option<String> {
266 url.host_str().map(alloc::string::ToString::to_string)
267}
268
269fn 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
280fn parse_mode(value: &str) -> Option<SrtMode> {
282 match value {
283 "caller" => Some(SrtMode::Caller),
284 "listener" => Some(SrtMode::Listener),
285 _ => None,
286 }
287}
288
289fn 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 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 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}