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]`. The app is the
124    /// first path segment; the stream key is the rest of the path, with the
125    /// query appended as written. Path text is percent-decoded (RFC 3986
126    /// §2.1: `a%20b` names `a b`); a key that is only a query is no key.
127    pub fn parse(url: &str) -> Result<Self, RtmpUrlError> {
128        let base = parse_base(url)?;
129        let mut segs = base.path_segments().ok_or(RtmpUrlError::NoApp)?;
130        let app = decode(
131            segs.next()
132                .filter(|s| !s.is_empty())
133                .ok_or(RtmpUrlError::NoApp)?,
134        )?;
135        let rest: Vec<&str> = segs.collect();
136        let mut key = decode(&rest.join("/"))?;
137        if key.is_empty() {
138            return Err(RtmpUrlError::NoStreamKey);
139        }
140        if let Some(q) = base.query() {
141            key.push('?');
142            key.push_str(q);
143        }
144        Self::build(&base, &app, &key)
145    }
146
147    /// Host and port from `base` (any path/query is ignored), `app` and
148    /// `stream_key` given separately.
149    pub fn from_parts(base: &str, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
150        Self::build(&parse_base(base)?, app, stream_key)
151    }
152
153    /// The RTMP `tcUrl` to send in the `connect` command:
154    /// `rtmp[s]://host[:port]/app`, IPv6 bracketed, userinfo/query/fragment
155    /// removed. Derived from `host`/`port`/`tls`/`app`, so it can never
156    /// disagree with them.
157    pub fn tc_url(&self) -> &str {
158        &self.tc_url
159    }
160
161    fn build(base: &Url, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
162        let host = base.host().ok_or(RtmpUrlError::NoHost)?.to_owned();
163        let tls = base.scheme() == SCHEME_RTMPS;
164        let mut tc = base.clone();
165        tc.set_path(&format!("/{app}"));
166        tc.set_query(None);
167        tc.set_fragment(None);
168        let _ = tc.set_username("");
169        let _ = tc.set_password(None);
170        Ok(RtmpTarget {
171            host,
172            port: base.port().unwrap_or(if tls {
173                RTMPS_DEFAULT_PORT
174            } else {
175                RTMP_DEFAULT_PORT
176            }),
177            tls,
178            app: app.to_string(),
179            stream_key: stream_key.to_string(),
180            tc_url: tc.to_string(),
181        })
182    }
183
184    /// Resolved socket addresses (DNS only for `Host::Domain`).
185    #[cfg(feature = "tokio")]
186    pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
187        match &self.host {
188            Host::Ipv4(a) => Ok(vec![SocketAddr::new(IpAddr::V4(*a), self.port)]),
189            Host::Ipv6(a) => Ok(vec![SocketAddr::new(IpAddr::V6(*a), self.port)]),
190            Host::Domain(d) => Ok(tokio::net::lookup_host((d.as_str(), self.port))
191                .await?
192                .collect()),
193        }
194    }
195}
196
197fn parse_base(url: &str) -> Result<Url, RtmpUrlError> {
198    let u = Url::parse(url)?;
199    if u.scheme() != SCHEME_RTMP && u.scheme() != SCHEME_RTMPS {
200        return Err(RtmpUrlError::Scheme(Scheme::parse(u.scheme())));
201    }
202    Ok(u)
203}
204
205fn decode(raw: &str) -> Result<String, RtmpUrlError> {
206    percent_encoding::percent_decode_str(raw)
207        .decode_utf8()
208        .map(std::borrow::Cow::into_owned)
209        .map_err(|_| RtmpUrlError::PathNotUtf8)
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn plain_host_default_port() {
218        let t = RtmpTarget::parse("rtmp://example.test/live/key").unwrap();
219        assert_eq!(
220            (t.port, t.app.as_str(), t.stream_key.as_str()),
221            (1935, "live", "key")
222        );
223        assert_eq!(t.tc_url(), "rtmp://example.test/live");
224    }
225
226    /// Defect 8: an IPv6 host must stay bracketed in tcUrl; building it from a bare
227    /// `IpAddr` + port (`format!("rtmp://{ip}:{port}/{app}")`) yields `rtmp://::1:1935/live`.
228    #[test]
229    fn ipv6_host_is_bracketed_in_tc_url() {
230        let t = RtmpTarget::parse("rtmp://[::1]:1935/live/key").unwrap();
231        assert_eq!(t.host, url::Host::<String>::Ipv6("::1".parse().unwrap()));
232        assert_eq!(t.tc_url(), "rtmp://[::1]:1935/live");
233        let t = RtmpTarget::parse("rtmp://[2001:db8::7]/live/key").unwrap();
234        assert_eq!(t.tc_url(), "rtmp://[2001:db8::7]/live");
235        assert_eq!(t.port, 1935);
236    }
237
238    #[test]
239    fn ipv4_literal_is_a_domain_host_for_this_non_special_scheme() {
240        let t = RtmpTarget::parse("rtmp://127.0.0.1:1936/live/k").unwrap();
241        assert_eq!(t.host, url::Host::<String>::Domain("127.0.0.1".into()));
242        assert_eq!(t.tc_url(), "rtmp://127.0.0.1:1936/live");
243    }
244
245    #[test]
246    fn userinfo_query_and_fragment_never_reach_tc_url() {
247        let t = RtmpTarget::parse("rtmp://user:s3cret@host:1936/live/key?token=a/b#frag").unwrap();
248        assert_eq!(t.tc_url(), "rtmp://host:1936/live");
249        assert_eq!(t.stream_key, "key?token=a/b");
250        assert!(!t.tc_url().contains("s3cret"));
251    }
252
253    #[test]
254    fn stream_key_keeps_extra_path_segments_and_trailing_slash_is_tolerated() {
255        assert_eq!(
256            RtmpTarget::parse("rtmp://h/live/a/b/c").unwrap().stream_key,
257            "a/b/c"
258        );
259        assert_eq!(
260            RtmpTarget::parse("rtmp://h/live/key/").unwrap().stream_key,
261            "key/"
262        );
263    }
264
265    #[test]
266    fn missing_pieces_and_wrong_scheme_are_errors() {
267        assert!(matches!(
268            RtmpTarget::parse("rtmp://h/"),
269            Err(RtmpUrlError::NoApp)
270        ));
271        assert!(matches!(
272            RtmpTarget::parse("rtmp://h/live"),
273            Err(RtmpUrlError::NoStreamKey)
274        ));
275        assert!(matches!(
276            RtmpTarget::parse("http://h/live/k"),
277            Err(RtmpUrlError::Scheme(Scheme::Other(_)))
278        ));
279        assert!(matches!(
280            RtmpTarget::parse("not a url"),
281            Err(RtmpUrlError::Parse(_))
282        ));
283    }
284
285    #[test]
286    fn from_parts_takes_host_and_port_from_base_only() {
287        let t = RtmpTarget::from_parts("rtmp://[::1]:1940/ignored/path", "live", "k").unwrap();
288        assert_eq!(t.tc_url(), "rtmp://[::1]:1940/live");
289        assert_eq!(
290            (t.app.as_str(), t.stream_key.as_str(), t.port),
291            ("live", "k", 1940)
292        );
293    }
294
295    #[cfg(feature = "tokio")]
296    #[tokio::test]
297    async fn resolve_uses_the_literal_address_without_dns() {
298        let t = RtmpTarget::parse("rtmp://[::1]:1935/live/key").unwrap();
299        assert_eq!(
300            t.resolve().await.unwrap(),
301            vec!["[::1]:1935".parse::<SocketAddr>().unwrap()]
302        );
303        let t = RtmpTarget::parse("rtmp://127.0.0.1:1/live/key").unwrap();
304        assert_eq!(
305            t.resolve().await.unwrap(),
306            vec!["127.0.0.1:1".parse::<SocketAddr>().unwrap()]
307        );
308    }
309
310    /// `rtmps` is a real scheme (RTMP over TLS, default port 443).
311    #[test]
312    fn rtmps_is_accepted_with_the_tls_default_port() {
313        let t = RtmpTarget::parse("rtmps://h.example/live/key").unwrap();
314        assert!(t.tls);
315        assert_eq!(t.port, RTMPS_DEFAULT_PORT);
316        assert_eq!(t.tc_url(), "rtmps://h.example/live");
317        let t = RtmpTarget::parse("rtmps://h.example:8443/live/key").unwrap();
318        assert_eq!(t.port, 8443);
319        assert!(!RtmpTarget::parse("rtmp://h.example/live/key").unwrap().tls);
320    }
321
322    /// RFC 3986 §2.1: percent-encoded path octets are decoded; the query stays
323    /// as written. A key that is only a query is no key.
324    #[test]
325    fn path_text_is_percent_decoded_and_the_query_is_kept_raw() {
326        let t = RtmpTarget::parse("rtmp://h/li%20ve/a/b%20c?token=a%26b").unwrap();
327        assert_eq!(t.app, "li ve");
328        assert_eq!(t.stream_key, "a/b c?token=a%26b");
329        assert!(matches!(
330            RtmpTarget::parse("rtmp://h/live/?token=x"),
331            Err(RtmpUrlError::NoStreamKey)
332        ));
333        assert!(matches!(
334            RtmpTarget::parse("rtmp://h/live/%FF"),
335            Err(RtmpUrlError::PathNotUtf8)
336        ));
337    }
338
339    #[cfg(feature = "tokio")]
340    #[tokio::test]
341    async fn the_plain_tcp_adapter_refuses_a_tls_target() {
342        let t = RtmpTarget::parse("rtmps://127.0.0.1:1/live/key").unwrap();
343        let timeouts = broadcast_net::timeouts::Timeouts::new(
344            core::time::Duration::from_secs(10),
345            core::time::Duration::from_secs(10),
346            core::time::Duration::from_secs(30),
347            core::time::Duration::from_secs(10),
348        );
349        let refused = crate::io::AsyncRtmpClient::connect(crate::io::RtmpClientConfig::new(
350            t,
351            crate::client::RtmpClientConfig::default(),
352            timeouts,
353        ))
354        .await;
355        assert!(matches!(refused, Err(e) if e.kind() == std::io::ErrorKind::Unsupported));
356    }
357}