1use alloc::string::{String, ToString};
32use core::net::{IpAddr, SocketAddr};
33
34pub const DEFAULT_PORT: u16 = 9000;
37
38pub const MAX_LATENCY_MS: u16 = 8000;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45#[non_exhaustive]
46pub enum SrtMode {
47 #[default]
49 Caller,
50 Listener,
52}
53
54impl UrlRejection {
55 #[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 #[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#[derive(Clone, PartialEq, Eq)]
85#[non_exhaustive]
86pub struct SrtUrl {
87 pub host: String,
89 pub port: u16,
91 pub stream_id: Option<String>,
93 pub latency_ms: Option<u16>,
95 pub mode: SrtMode,
97 pub passphrase: Option<String>,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum UrlRejection {
106 Authority,
109 LatencyNotANumber,
111 LatencyTooLarge,
113 Mode,
115 InvalidUtf8,
117 DuplicateKey,
119}
120
121impl 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 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 #[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
215fn 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
229fn 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
240fn parse_mode(value: &str) -> Option<SrtMode> {
242 match value {
243 "caller" => Some(SrtMode::Caller),
244 "listener" => Some(SrtMode::Listener),
245 _ => None,
246 }
247}
248
249fn 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}