Skip to main content

rtmp_runtime/
target.rs

1//! `rtmp[s]://host[:port]/app/stream-key` -> typed target, built with the `url` crate.
2//! Replaces `format!("rtmp://{host}:{port}/{app}")`, which produces `rtmp://::1:1935/live`
3//! for an IPv6 address (defect 8) and leaks userinfo/query into `tcUrl`.
4
5#[cfg(feature = "tokio")]
6use std::net::{IpAddr, SocketAddr};
7
8use url::{Host, Url};
9
10/// IANA-assigned RTMP port, used when the URL names none.
11pub const RTMP_DEFAULT_PORT: u16 = 1935;
12/// Port an `rtmps://` URL without one connects to: RTMP over TLS is carried on
13/// the HTTPS port (443), the de-facto deployment (no IANA assignment exists).
14pub const RTMPS_DEFAULT_PORT: u16 = 443;
15/// URL scheme of plain RTMP.
16pub const SCHEME_RTMP: &str = "rtmp";
17/// URL scheme of RTMP over TLS.
18pub const SCHEME_RTMPS: &str = "rtmps";
19
20/// A parsed RTMP publish target.
21#[derive(Clone, PartialEq, Eq)]
22#[non_exhaustive]
23pub struct RtmpTarget {
24    /// Host, never a pre-formatted string. `rtmp` is a non-special URL scheme, so
25    /// the `url` crate reports an IPv4 literal as `Host::Domain("127.0.0.1")`
26    /// (`resolve` handles it, `lookup_host` accepts literals); only a bracketed IPv6
27    /// literal becomes `Host::Ipv6`.
28    pub host: Host<String>,
29    /// TCP port; 1935 (`rtmp`) or 443 (`rtmps`) when the URL has none.
30    pub port: u16,
31    /// Whether the scheme is `rtmps`: the connection must run over TLS, which
32    /// the caller supplies (the tokio adapter's [`AsyncRtmpClient::connect`]
33    /// opens plain TCP and refuses a TLS target).
34    ///
35    /// [`AsyncRtmpClient::connect`]: crate::io::AsyncRtmpClient::connect
36    pub tls: bool,
37    /// The RTMP `app`, percent-decoded (RFC 3986 §2.1).
38    pub app: String,
39    /// The path remainder, percent-decoded (RFC 3986 §2.1), plus `?query` kept
40    /// as written: the query is an opaque string the origin parses itself.
41    pub stream_key: String,
42    /// `rtmp[s]://host[:port]/app`, IPv6 bracketed, userinfo/query/fragment removed.
43    /// Derived from `host`/`port`/`tls`/`app`, so it is read-only (see
44    /// [`RtmpTarget::tc_url`]) and can never disagree with `app`.
45    tc_url: String,
46}
47
48/// Manual `Debug`: the stream key (path remainder plus query) is the publish
49/// secret and never renders (issue #1142).
50impl core::fmt::Debug for RtmpTarget {
51    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
52        f.debug_struct("RtmpTarget")
53            .field("host", &self.host)
54            .field("port", &self.port)
55            .field("app", &self.app)
56            .field("stream_key", &"<redacted>")
57            .field("tc_url", &self.tc_url)
58            .finish()
59    }
60}
61
62/// An RTMP URL scheme: [`SCHEME_RTMP`] or [`SCHEME_RTMPS`].
63///
64/// Data-carrying (`Other(String)`), so like every other `Other(_)` discriminant
65/// in the workspace it has no fixed label set and no `name()`.
66#[derive(Debug, Clone, PartialEq, Eq)]
67#[non_exhaustive]
68pub enum Scheme {
69    /// `rtmp://`.
70    Rtmp,
71    /// `rtmps://`.
72    Rtmps,
73    /// Any other scheme, as written.
74    Other(String),
75}
76
77impl Scheme {
78    /// The scheme this URL text carries; an unknown one is kept verbatim.
79    fn parse(text: &str) -> Self {
80        match text {
81            SCHEME_RTMP => Scheme::Rtmp,
82            SCHEME_RTMPS => Scheme::Rtmps,
83            other => Scheme::Other(other.to_string()),
84        }
85    }
86}
87
88impl core::fmt::Display for Scheme {
89    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
90        match self {
91            Scheme::Rtmp => f.write_str(SCHEME_RTMP),
92            Scheme::Rtmps => f.write_str(SCHEME_RTMPS),
93            Scheme::Other(text) => f.write_str(text),
94        }
95    }
96}
97
98/// Why an RTMP URL was rejected.
99#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
100#[non_exhaustive]
101pub enum RtmpUrlError {
102    /// The text is not a URL (RFC 3986 §3).
103    #[error("invalid URL: {0}")]
104    Parse(#[from] url::ParseError),
105    /// The URL's scheme is not `rtmp` or `rtmps`.
106    #[error("unsupported scheme {0} (only rtmp and rtmps)")]
107    Scheme(Scheme),
108    /// A percent-decoded path segment is not valid UTF-8.
109    #[error("percent-decoded path is not valid UTF-8")]
110    PathNotUtf8,
111    /// The URL has no host.
112    #[error("URL has no host")]
113    NoHost,
114    /// The URL has no app segment.
115    #[error("URL has no app segment")]
116    NoApp,
117    /// The URL has no stream key after the app.
118    #[error("URL has no stream key")]
119    NoStreamKey,
120}
121
122impl RtmpTarget {
123    /// Parses `rtmp[s]://host[:port]/app/stream-key[?query]` by the
124    /// nginx-rtmp convention, shared by publish and play: the **first** path
125    /// segment is the app, and every later segment is part of the stream key.
126    /// Non-empty segments are percent-decoded individually (RFC 3986 §2.1:
127    /// `b%20c` names `b c`), joined with `/`, and the query is appended as
128    /// written. Empty segments and a trailing slash are ignored, so
129    /// `rtmp://h/app/inst/key` names app `app` and key `inst/key`, and
130    /// `rtmp://h/live/a/b%20c?token=x` names app `live` and key
131    /// `a/b c?token=x`. A path of one segment names only an app.
132    pub fn parse(url: &str) -> Result<Self, RtmpUrlError> {
133        let base = parse_base(url)?;
134        let (app, key) = split_path(&base)?;
135        let key = key.ok_or(RtmpUrlError::NoStreamKey)?;
136        Self::build(&base, &app, &key)
137    }
138
139    /// The app a URL names, without requiring a stream key: used by a caller
140    /// that can publish with a configured default key.
141    pub fn parse_app(url: &str) -> Result<String, RtmpUrlError> {
142        let base = parse_base(url)?;
143        Ok(split_path(&base)?.0)
144    }
145
146    /// Parse a URL, substituting a caller's `app` when it names none and
147    /// `stream_key` when it names no key. Other errors are returned unchanged
148    /// so the caller can report or skip the output.
149    pub fn parse_or_default(url: &str, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
150        match Self::parse(url) {
151            Ok(target) => Ok(target),
152            Err(RtmpUrlError::NoApp) => Self::from_parts(url, app, stream_key),
153            Err(RtmpUrlError::NoStreamKey) => {
154                let base = parse_base(url)?;
155                let parsed_app = split_path(&base)?.0;
156                Self::build(&base, &parsed_app, stream_key)
157            }
158            Err(err) => Err(err),
159        }
160    }
161
162    /// Host and port from `base` (any path/query is ignored), `app` and
163    /// `stream_key` given separately.
164    pub fn from_parts(base: &str, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
165        Self::build(&parse_base(base)?, app, stream_key)
166    }
167
168    /// The RTMP `tcUrl` to send in the `connect` command:
169    /// `rtmp[s]://host[:port]/app`, IPv6 bracketed, userinfo/query/fragment
170    /// removed. Derived from `host`/`port`/`tls`/`app`, so it can never
171    /// disagree with them.
172    pub fn tc_url(&self) -> &str {
173        &self.tc_url
174    }
175
176    fn build(base: &Url, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
177        let host = base.host().ok_or(RtmpUrlError::NoHost)?.to_owned();
178        let tls = base.scheme() == SCHEME_RTMPS;
179        let mut tc = base.clone();
180        tc.set_path(&format!("/{app}"));
181        tc.set_query(None);
182        tc.set_fragment(None);
183        let _ = tc.set_username("");
184        let _ = tc.set_password(None);
185        Ok(RtmpTarget {
186            host,
187            port: base.port().unwrap_or(if tls {
188                RTMPS_DEFAULT_PORT
189            } else {
190                RTMP_DEFAULT_PORT
191            }),
192            tls,
193            app: app.to_string(),
194            stream_key: stream_key.to_string(),
195            tc_url: tc.to_string(),
196        })
197    }
198
199    /// Resolved socket addresses (DNS only for `Host::Domain`).
200    #[cfg(feature = "tokio")]
201    pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
202        match &self.host {
203            Host::Ipv4(a) => Ok(vec![SocketAddr::new(IpAddr::V4(*a), self.port)]),
204            Host::Ipv6(a) => Ok(vec![SocketAddr::new(IpAddr::V6(*a), self.port)]),
205            Host::Domain(d) => Ok(tokio::net::lookup_host((d.as_str(), self.port))
206                .await?
207                .collect()),
208        }
209    }
210}
211
212fn parse_base(url: &str) -> Result<Url, RtmpUrlError> {
213    let u = Url::parse(url)?;
214    if u.scheme() != SCHEME_RTMP && u.scheme() != SCHEME_RTMPS {
215        return Err(RtmpUrlError::Scheme(Scheme::parse(u.scheme())));
216    }
217    Ok(u)
218}
219
220/// The app and optional stream key a URL's path names, by the rule documented
221/// on [`RtmpTarget::parse`].
222fn split_path(base: &Url) -> Result<(String, Option<String>), RtmpUrlError> {
223    let mut raw = base.path_segments().ok_or(RtmpUrlError::NoApp)?;
224    let app = decode(
225        raw.next()
226            .filter(|s| !s.is_empty())
227            .ok_or(RtmpUrlError::NoApp)?,
228    )?;
229    let mut parts = Vec::new();
230    for segment in raw.filter(|s| !s.is_empty()) {
231        parts.push(decode(segment)?);
232    }
233    if parts.is_empty() {
234        return Ok((app, None));
235    }
236    let mut key = parts.join("/");
237    if let Some(query) = base.query() {
238        key.push('?');
239        key.push_str(query);
240    }
241    Ok((app, Some(key)))
242}
243
244fn decode(raw: &str) -> Result<String, RtmpUrlError> {
245    percent_encoding::percent_decode_str(raw)
246        .decode_utf8()
247        .map(std::borrow::Cow::into_owned)
248        .map_err(|_| RtmpUrlError::PathNotUtf8)
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn plain_host_default_port() {
257        let t = RtmpTarget::parse("rtmp://example.test/live/key").unwrap();
258        assert_eq!(
259            (t.port, t.app.as_str(), t.stream_key.as_str()),
260            (1935, "live", "key")
261        );
262        assert_eq!(t.tc_url(), "rtmp://example.test/live");
263    }
264
265    /// Defect 8: an IPv6 host must stay bracketed in tcUrl; building it from a bare
266    /// `IpAddr` + port (`format!("rtmp://{ip}:{port}/{app}")`) yields `rtmp://::1:1935/live`.
267    #[test]
268    fn ipv6_host_is_bracketed_in_tc_url() {
269        let t = RtmpTarget::parse("rtmp://[::1]:1935/live/key").unwrap();
270        assert_eq!(t.host, url::Host::<String>::Ipv6("::1".parse().unwrap()));
271        assert_eq!(t.tc_url(), "rtmp://[::1]:1935/live");
272        let t = RtmpTarget::parse("rtmp://[2001:db8::7]/live/key").unwrap();
273        assert_eq!(t.tc_url(), "rtmp://[2001:db8::7]/live");
274        assert_eq!(t.port, 1935);
275    }
276
277    #[test]
278    fn ipv4_literal_is_a_domain_host_for_this_non_special_scheme() {
279        let t = RtmpTarget::parse("rtmp://127.0.0.1:1936/live/k").unwrap();
280        assert_eq!(t.host, url::Host::<String>::Domain("127.0.0.1".into()));
281        assert_eq!(t.tc_url(), "rtmp://127.0.0.1:1936/live");
282    }
283
284    #[test]
285    fn userinfo_query_and_fragment_never_reach_tc_url() {
286        let t = RtmpTarget::parse("rtmp://user:s3cret@host:1936/live/key?token=a/b#frag").unwrap();
287        assert_eq!(t.tc_url(), "rtmp://host:1936/live");
288        assert_eq!(t.stream_key, "key?token=a/b");
289        assert!(!t.tc_url().contains("s3cret"));
290    }
291
292    #[test]
293    fn every_segment_after_the_app_is_the_stream_key() {
294        let t = RtmpTarget::parse("rtmp://h/live/a/b/c").unwrap();
295        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("live", "a/b/c"));
296        let t = RtmpTarget::parse("rtmp://h/app/inst/key").unwrap();
297        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("app", "inst/key"));
298        assert_eq!(t.tc_url(), "rtmp://h/app");
299        let t = RtmpTarget::parse("rtmp://h/a/b/c/d").unwrap();
300        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("a", "b/c/d"));
301        assert_eq!(t.tc_url(), "rtmp://h/a");
302    }
303
304    #[test]
305    fn empty_segments_and_a_trailing_slash_are_ignored() {
306        let t = RtmpTarget::parse("rtmp://h/app/inst/key/").unwrap();
307        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("app", "inst/key"));
308        let t = RtmpTarget::parse("rtmp://h/app/inst//key").unwrap();
309        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("app", "inst/key"));
310    }
311
312    #[test]
313    fn key_segments_are_percent_decoded_and_the_query_is_kept_raw() {
314        let t = RtmpTarget::parse("rtmp://h/app/my%20inst/key").unwrap();
315        assert_eq!(
316            (t.app.as_str(), t.stream_key.as_str()),
317            ("app", "my inst/key")
318        );
319        assert!(matches!(
320            RtmpTarget::parse("rtmp://h/app/in%FFst/key"),
321            Err(RtmpUrlError::PathNotUtf8)
322        ));
323    }
324
325    #[test]
326    fn parse_or_default_keeps_the_named_app_and_fills_only_the_missing_piece() {
327        let t = RtmpTarget::parse_or_default("rtmp://h/myapp", "live", "default").unwrap();
328        assert_eq!(
329            (t.app.as_str(), t.stream_key.as_str()),
330            ("myapp", "default")
331        );
332        let t = RtmpTarget::parse_or_default("rtmp://h/", "live", "default").unwrap();
333        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("live", "default"));
334        assert!(matches!(
335            RtmpTarget::parse_or_default("rtmp://h/app/%FF", "live", "default"),
336            Err(RtmpUrlError::PathNotUtf8)
337        ));
338    }
339
340    #[test]
341    fn parse_app_keeps_the_app_when_no_stream_key_is_named() {
342        assert_eq!(
343            RtmpTarget::parse_app("rtmp://h/myapp").expect("an app is named"),
344            "myapp"
345        );
346        assert_eq!(
347            RtmpTarget::parse_app("rtmp://h/app/inst/key").expect("an app is named"),
348            "app"
349        );
350        assert!(matches!(
351            RtmpTarget::parse_app("rtmp://h/"),
352            Err(RtmpUrlError::NoApp)
353        ));
354    }
355
356    #[test]
357    fn missing_pieces_and_wrong_scheme_are_errors() {
358        assert!(matches!(
359            RtmpTarget::parse("rtmp://h/"),
360            Err(RtmpUrlError::NoApp)
361        ));
362        assert!(matches!(
363            RtmpTarget::parse("rtmp://h/live"),
364            Err(RtmpUrlError::NoStreamKey)
365        ));
366        assert!(matches!(
367            RtmpTarget::parse("http://h/live/k"),
368            Err(RtmpUrlError::Scheme(Scheme::Other(_)))
369        ));
370        assert!(matches!(
371            RtmpTarget::parse("not a url"),
372            Err(RtmpUrlError::Parse(_))
373        ));
374    }
375
376    #[test]
377    fn from_parts_takes_host_and_port_from_base_only() {
378        let t = RtmpTarget::from_parts("rtmp://[::1]:1940/ignored/path", "live", "k").unwrap();
379        assert_eq!(t.tc_url(), "rtmp://[::1]:1940/live");
380        assert_eq!(
381            (t.app.as_str(), t.stream_key.as_str(), t.port),
382            ("live", "k", 1940)
383        );
384    }
385
386    #[cfg(feature = "tokio")]
387    #[tokio::test]
388    async fn resolve_uses_the_literal_address_without_dns() {
389        let t = RtmpTarget::parse("rtmp://[::1]:1935/live/key").unwrap();
390        assert_eq!(
391            t.resolve().await.unwrap(),
392            vec!["[::1]:1935".parse::<SocketAddr>().unwrap()]
393        );
394        let t = RtmpTarget::parse("rtmp://127.0.0.1:1/live/key").unwrap();
395        assert_eq!(
396            t.resolve().await.unwrap(),
397            vec!["127.0.0.1:1".parse::<SocketAddr>().unwrap()]
398        );
399    }
400
401    /// `rtmps` is a real scheme (RTMP over TLS, default port 443).
402    #[test]
403    fn rtmps_is_accepted_with_the_tls_default_port() {
404        let t = RtmpTarget::parse("rtmps://h.example/live/key").unwrap();
405        assert!(t.tls);
406        assert_eq!(t.port, RTMPS_DEFAULT_PORT);
407        assert_eq!(t.tc_url(), "rtmps://h.example/live");
408        let t = RtmpTarget::parse("rtmps://h.example:8443/live/key").unwrap();
409        assert_eq!(t.port, 8443);
410        assert!(!RtmpTarget::parse("rtmp://h.example/live/key").unwrap().tls);
411    }
412
413    /// RFC 3986 §2.1: percent-encoded path octets are decoded; the query stays
414    /// as written. A key that is only a query is no key.
415    #[test]
416    fn path_text_is_percent_decoded_and_the_query_is_kept_raw() {
417        let t = RtmpTarget::parse("rtmp://h/li%20ve/a/b%20c?token=a%26b").unwrap();
418        assert_eq!(t.app, "li ve");
419        assert_eq!(t.stream_key, "a/b c?token=a%26b");
420        assert!(matches!(
421            RtmpTarget::parse("rtmp://h/live/?token=x"),
422            Err(RtmpUrlError::NoStreamKey)
423        ));
424        assert!(matches!(
425            RtmpTarget::parse("rtmp://h/live/%FF"),
426            Err(RtmpUrlError::PathNotUtf8)
427        ));
428    }
429
430    #[cfg(feature = "tokio")]
431    #[tokio::test]
432    async fn the_plain_tcp_adapter_refuses_a_tls_target() {
433        let t = RtmpTarget::parse("rtmps://127.0.0.1:1/live/key").unwrap();
434        let timeouts = broadcast_net::timeouts::Timeouts::new(
435            core::time::Duration::from_secs(10),
436            core::time::Duration::from_secs(10),
437            core::time::Duration::from_secs(30),
438            core::time::Duration::from_secs(10),
439        );
440        let refused = crate::io::AsyncRtmpClient::connect(crate::io::RtmpClientConfig::new(
441            t,
442            crate::client::RtmpClientConfig::default(),
443            timeouts,
444        ))
445        .await;
446        assert!(matches!(refused, Err(e) if e.kind() == std::io::ErrorKind::Unsupported));
447    }
448}