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_core::impl_spec_display!(SrtMode);
84broadcast_core::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 pub fn parse_endpoint(addr: &str) -> Result<Self, UrlRejection> {
212 if addr.contains(['/', '?', '#', '@']) {
213 return Err(UrlRejection::Authority);
214 }
215 let parsed_url = url::Url::parse(&alloc::format!("srt://{addr}"))
216 .map_err(|_| UrlRejection::Authority)?;
217 if parsed_url.port().is_none() {
218 return Err(UrlRejection::Authority);
219 }
220 Self::parse(parsed_url.as_str())
221 }
222
223 #[must_use]
226 pub fn dial_addr(&self) -> String {
227 match self.host.parse::<IpAddr>() {
228 Ok(ip) => SocketAddr::new(ip, self.port).to_string(),
229 Err(_) => format!("{}:{}", self.host, self.port),
230 }
231 }
232}
233
234fn parse_url(input: &str) -> Option<url::Url> {
245 let escaped = escape_query_fragments(input);
246 if has_srt_scheme(&escaped) {
247 url::Url::parse(&escaped).ok()
248 } else {
249 url::Url::parse(&alloc::format!("srt://{escaped}")).ok()
250 }
251}
252
253fn has_srt_scheme(input: &str) -> bool {
258 input
259 .get(.."srt://".len())
260 .is_some_and(|prefix| prefix.eq_ignore_ascii_case("srt://"))
261}
262
263const PERCENT_ESCAPE_SLACK: usize = 8;
267
268fn escape_query_fragments(input: &str) -> alloc::string::String {
269 match input.split_once('?') {
270 Some((head, query)) => {
271 let mut out = alloc::string::String::with_capacity(input.len() + PERCENT_ESCAPE_SLACK);
272 out.push_str(head);
273 out.push('?');
274 for ch in query.chars() {
275 if ch == '#' {
276 out.push_str("%23");
277 } else {
278 out.push(ch);
279 }
280 }
281 out
282 }
283 None => input.into(),
284 }
285}
286
287fn bracketed_host(url: &url::Url) -> Option<String> {
290 url.host_str().map(alloc::string::ToString::to_string)
291}
292
293fn parse_latency(value: &str) -> Result<Duration, UrlRejection> {
295 let ms = value
296 .parse::<u16>()
297 .map_err(|_| UrlRejection::LatencyNotANumber)?;
298 if ms > MAX_LATENCY_MS {
299 return Err(UrlRejection::LatencyTooLarge);
300 }
301 Ok(Duration::from_millis(u64::from(ms)))
302}
303
304fn parse_mode(value: &str) -> Option<SrtMode> {
306 match value {
307 "caller" => Some(SrtMode::Caller),
308 "listener" => Some(SrtMode::Listener),
309 _ => None,
310 }
311}
312
313fn percent_decode(value: &str) -> Result<String, UrlRejection> {
316 let bytes: alloc::vec::Vec<u8> = percent_encoding::percent_decode_str(value).collect();
317 String::from_utf8(bytes).map_err(|_| UrlRejection::InvalidUtf8)
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323
324 #[test]
325 fn debug_redacts_the_passphrase() {
326 let url = SrtUrl::parse("srt://h?passphrase=SECRET").expect("passphrase");
327 let rendered = format!("{url:?}");
328 assert!(!rendered.contains("SECRET"), "{rendered}");
329 assert!(rendered.contains("<redacted>"), "{rendered}");
330 }
331
332 #[test]
333 fn parse_endpoint_accepts_only_a_bare_host_and_port() {
334 for ok in ["example.com:9000", "127.0.0.1:9000", "[::1]:9000"] {
335 let url = SrtUrl::parse_endpoint(ok).expect(ok);
336 assert_eq!(url.port, 9000, "{ok}");
337 }
338 for bad in [
339 "nonsense",
340 ":9000",
341 "example.com:notaport",
342 "example.com:70000",
343 "host:9000/path",
344 "host:9000?x=1",
345 "host:9000#frag",
346 "user@host:9000",
347 "::1:9000",
348 ] {
349 assert_eq!(
350 SrtUrl::parse_endpoint(bad),
351 Err(UrlRejection::Authority),
352 "{bad}"
353 );
354 }
355 }
356
357 #[test]
358 fn srt_mode_labels() {
359 assert_eq!(SrtMode::Caller.name(), "caller");
360 assert_eq!(SrtMode::Listener.name(), "listener");
361 }
362
363 #[test]
364 fn url_rejection_labels() {
365 assert_eq!(UrlRejection::Authority.name(), "authority");
366 assert_eq!(
367 UrlRejection::LatencyNotANumber.name(),
368 "latency-not-a-number"
369 );
370 assert_eq!(UrlRejection::LatencyTooLarge.name(), "latency-too-large");
371 assert_eq!(UrlRejection::Mode.name(), "mode");
372 assert_eq!(UrlRejection::InvalidUtf8.name(), "invalid-utf8");
373 assert_eq!(UrlRejection::DuplicateKey.name(), "duplicate-key");
374 }
375
376 #[test]
377 fn host_only_takes_the_default_port() {
378 let url = SrtUrl::parse("srt://example.com").expect("host only");
379 assert_eq!(url.host, "example.com");
380 assert_eq!(url.port, DEFAULT_PORT);
381 assert_eq!(url.mode, SrtMode::Caller);
382 }
383
384 #[test]
385 fn bracketed_ipv6_keeps_its_brackets_off_the_host() {
386 let url = SrtUrl::parse("srt://[::1]:9001").expect("bracketed v6");
387 assert_eq!(url.host, "[::1]");
388 assert_eq!(url.dial_addr(), "[::1]:9001");
389 }
390
391 #[test]
392 fn a_bare_ipv6_literal_is_ambiguous_not_guessed() {
393 assert_eq!(SrtUrl::parse("::1:9000"), Err(UrlRejection::Authority));
394 }
395
396 #[test]
397 fn the_latency_cap_is_the_drafts() {
398 assert!(SrtUrl::parse("srt://h?latency=8000").is_ok());
399 assert_eq!(
400 SrtUrl::parse("srt://h?latency=8001"),
401 Err(UrlRejection::LatencyTooLarge)
402 );
403 assert_eq!(
404 SrtUrl::parse("srt://h?latency=late"),
405 Err(UrlRejection::LatencyNotANumber)
406 );
407 }
408 #[test]
409 fn invalid_utf8_percent_decode_is_rejected() {
410 assert_eq!(
411 SrtUrl::parse("srt://h:9000?streamid=%FF"),
412 Err(UrlRejection::InvalidUtf8)
413 );
414 assert_eq!(
415 SrtUrl::parse("srt://h:9000?passphrase=%C3%28extra"),
416 Err(UrlRejection::InvalidUtf8)
417 );
418 }
419
420 #[test]
421 fn duplicate_query_key_is_rejected() {
422 assert_eq!(
423 SrtUrl::parse("srt://h:9000?latency=10&latency=20"),
424 Err(UrlRejection::DuplicateKey)
425 );
426 }
427
428 #[test]
429 fn duplicate_query_key_decoded_is_rejected() {
430 assert_eq!(
431 SrtUrl::parse("srt://h:9000?%6Catency=10&latency=20"),
432 Err(UrlRejection::DuplicateKey)
433 );
434 }
435
436 #[test]
437 fn unknown_key_with_invalid_utf8_is_ignored() {
438 let url = SrtUrl::parse("srt://h:9000?%ff=1&latency=120").expect("ignored key");
439 assert_eq!(url.latency, Some(Duration::from_millis(120)));
440 }
441
442 #[test]
443 fn repeated_unknown_query_key_is_ignored() {
444 assert!(SrtUrl::parse("srt://h:9000?foo=1&foo=2").is_ok());
445 }
446
447 #[test]
448 fn valid_percent_encoded_utf8_streamid_decodes() {
449 let url = SrtUrl::parse("srt://h:9000?streamid=%C3%A9").expect("valid utf8");
450 assert_eq!(url.stream_id.as_deref(), Some("é"));
451 }
452
453 #[test]
454 fn the_srt_scheme_is_case_insensitive() {
455 let url = SrtUrl::parse("SRT://h:9000").expect("uppercase scheme names the same endpoint");
459 assert_eq!(url.host, "h");
460 assert_eq!(url.port, 9000);
461 }
462
463 #[test]
464 fn a_hash_inside_a_streamid_value_is_kept_whole() {
465 let url = SrtUrl::parse("srt://h:9000?streamid=#!::r=live/cam,m=publish")
468 .expect("hash-bearing streamid");
469 assert_eq!(url.stream_id.as_deref(), Some("#!::r=live/cam,m=publish"));
470 }
471}