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    pub tc_url: String,
44}
45
46/// Manual `Debug`: the stream key (path remainder plus query) is the publish
47/// secret and never renders (issue #1142).
48impl core::fmt::Debug for RtmpTarget {
49    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
50        f.debug_struct("RtmpTarget")
51            .field("host", &self.host)
52            .field("port", &self.port)
53            .field("app", &self.app)
54            .field("stream_key", &"<redacted>")
55            .field("tc_url", &self.tc_url)
56            .finish()
57    }
58}
59
60/// Why an RTMP URL was rejected.
61#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
62#[non_exhaustive]
63pub enum RtmpUrlError {
64    /// The text is not a URL.
65    #[error("invalid URL: {0}")]
66    Parse(String),
67    /// The scheme is not `rtmp`.
68    #[error("unsupported scheme {0:?} (only rtmp and rtmps)")]
69    Scheme(String),
70    /// A percent-decoded path segment is not valid UTF-8.
71    #[error("percent-decoded path is not valid UTF-8")]
72    PathNotUtf8,
73    /// The URL has no host.
74    #[error("URL has no host")]
75    NoHost,
76    /// The URL has no app segment.
77    #[error("URL has no app segment")]
78    NoApp,
79    /// The URL has no stream key after the app.
80    #[error("URL has no stream key")]
81    NoStreamKey,
82}
83
84impl RtmpTarget {
85    /// Parses `rtmp[s]://host[:port]/app/stream-key[?query]`. The app is the
86    /// first path segment; the stream key is the rest of the path, with the
87    /// query appended as written. Path text is percent-decoded (RFC 3986
88    /// §2.1: `a%20b` names `a b`); a key that is only a query is no key.
89    pub fn parse(url: &str) -> Result<Self, RtmpUrlError> {
90        let base = parse_base(url)?;
91        let mut segs = base.path_segments().ok_or(RtmpUrlError::NoApp)?;
92        let app = decode(
93            segs.next()
94                .filter(|s| !s.is_empty())
95                .ok_or(RtmpUrlError::NoApp)?,
96        )?;
97        let rest: Vec<&str> = segs.collect();
98        let mut key = decode(&rest.join("/"))?;
99        if key.is_empty() {
100            return Err(RtmpUrlError::NoStreamKey);
101        }
102        if let Some(q) = base.query() {
103            key.push('?');
104            key.push_str(q);
105        }
106        Self::build(&base, &app, &key)
107    }
108
109    /// Host and port from `base` (any path/query is ignored), `app` and
110    /// `stream_key` given separately.
111    pub fn from_parts(base: &str, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
112        Self::build(&parse_base(base)?, app, stream_key)
113    }
114
115    fn build(base: &Url, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
116        let host = base.host().ok_or(RtmpUrlError::NoHost)?.to_owned();
117        let tls = base.scheme() == SCHEME_RTMPS;
118        let mut tc = base.clone();
119        tc.set_path(&format!("/{app}"));
120        tc.set_query(None);
121        tc.set_fragment(None);
122        let _ = tc.set_username("");
123        let _ = tc.set_password(None);
124        Ok(RtmpTarget {
125            host,
126            port: base.port().unwrap_or(if tls {
127                RTMPS_DEFAULT_PORT
128            } else {
129                RTMP_DEFAULT_PORT
130            }),
131            tls,
132            app: app.to_string(),
133            stream_key: stream_key.to_string(),
134            tc_url: tc.to_string(),
135        })
136    }
137
138    /// Resolved socket addresses (DNS only for `Host::Domain`).
139    #[cfg(feature = "tokio")]
140    pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
141        match &self.host {
142            Host::Ipv4(a) => Ok(vec![SocketAddr::new(IpAddr::V4(*a), self.port)]),
143            Host::Ipv6(a) => Ok(vec![SocketAddr::new(IpAddr::V6(*a), self.port)]),
144            Host::Domain(d) => Ok(tokio::net::lookup_host((d.as_str(), self.port))
145                .await?
146                .collect()),
147        }
148    }
149}
150
151fn parse_base(url: &str) -> Result<Url, RtmpUrlError> {
152    let u = Url::parse(url).map_err(|e| RtmpUrlError::Parse(e.to_string()))?;
153    if u.scheme() != SCHEME_RTMP && u.scheme() != SCHEME_RTMPS {
154        return Err(RtmpUrlError::Scheme(u.scheme().to_string()));
155    }
156    Ok(u)
157}
158
159fn decode(raw: &str) -> Result<String, RtmpUrlError> {
160    percent_encoding::percent_decode_str(raw)
161        .decode_utf8()
162        .map(std::borrow::Cow::into_owned)
163        .map_err(|_| RtmpUrlError::PathNotUtf8)
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn plain_host_default_port() {
172        let t = RtmpTarget::parse("rtmp://example.test/live/key").unwrap();
173        assert_eq!(
174            (t.port, t.app.as_str(), t.stream_key.as_str()),
175            (1935, "live", "key")
176        );
177        assert_eq!(t.tc_url, "rtmp://example.test/live");
178    }
179
180    /// Defect 8: an IPv6 host must stay bracketed in tcUrl; building it from a bare
181    /// `IpAddr` + port (`format!("rtmp://{ip}:{port}/{app}")`) yields `rtmp://::1:1935/live`.
182    #[test]
183    fn ipv6_host_is_bracketed_in_tc_url() {
184        let t = RtmpTarget::parse("rtmp://[::1]:1935/live/key").unwrap();
185        assert_eq!(t.host, url::Host::<String>::Ipv6("::1".parse().unwrap()));
186        assert_eq!(t.tc_url, "rtmp://[::1]:1935/live");
187        let t = RtmpTarget::parse("rtmp://[2001:db8::7]/live/key").unwrap();
188        assert_eq!(t.tc_url, "rtmp://[2001:db8::7]/live");
189        assert_eq!(t.port, 1935);
190    }
191
192    #[test]
193    fn ipv4_literal_is_a_domain_host_for_this_non_special_scheme() {
194        let t = RtmpTarget::parse("rtmp://127.0.0.1:1936/live/k").unwrap();
195        assert_eq!(t.host, url::Host::<String>::Domain("127.0.0.1".into()));
196        assert_eq!(t.tc_url, "rtmp://127.0.0.1:1936/live");
197    }
198
199    #[test]
200    fn userinfo_query_and_fragment_never_reach_tc_url() {
201        let t = RtmpTarget::parse("rtmp://user:s3cret@host:1936/live/key?token=a/b#frag").unwrap();
202        assert_eq!(t.tc_url, "rtmp://host:1936/live");
203        assert_eq!(t.stream_key, "key?token=a/b");
204        assert!(!t.tc_url.contains("s3cret"));
205    }
206
207    #[test]
208    fn stream_key_keeps_extra_path_segments_and_trailing_slash_is_tolerated() {
209        assert_eq!(
210            RtmpTarget::parse("rtmp://h/live/a/b/c").unwrap().stream_key,
211            "a/b/c"
212        );
213        assert_eq!(
214            RtmpTarget::parse("rtmp://h/live/key/").unwrap().stream_key,
215            "key/"
216        );
217    }
218
219    #[test]
220    fn missing_pieces_and_wrong_scheme_are_errors() {
221        assert!(matches!(
222            RtmpTarget::parse("rtmp://h/"),
223            Err(RtmpUrlError::NoApp)
224        ));
225        assert!(matches!(
226            RtmpTarget::parse("rtmp://h/live"),
227            Err(RtmpUrlError::NoStreamKey)
228        ));
229        assert!(matches!(
230            RtmpTarget::parse("http://h/live/k"),
231            Err(RtmpUrlError::Scheme(_))
232        ));
233        assert!(matches!(
234            RtmpTarget::parse("not a url"),
235            Err(RtmpUrlError::Parse(_))
236        ));
237    }
238
239    #[test]
240    fn from_parts_takes_host_and_port_from_base_only() {
241        let t = RtmpTarget::from_parts("rtmp://[::1]:1940/ignored/path", "live", "k").unwrap();
242        assert_eq!(t.tc_url, "rtmp://[::1]:1940/live");
243        assert_eq!(
244            (t.app.as_str(), t.stream_key.as_str(), t.port),
245            ("live", "k", 1940)
246        );
247    }
248
249    #[cfg(feature = "tokio")]
250    #[tokio::test]
251    async fn resolve_uses_the_literal_address_without_dns() {
252        let t = RtmpTarget::parse("rtmp://[::1]:1935/live/key").unwrap();
253        assert_eq!(
254            t.resolve().await.unwrap(),
255            vec!["[::1]:1935".parse::<SocketAddr>().unwrap()]
256        );
257        let t = RtmpTarget::parse("rtmp://127.0.0.1:1/live/key").unwrap();
258        assert_eq!(
259            t.resolve().await.unwrap(),
260            vec!["127.0.0.1:1".parse::<SocketAddr>().unwrap()]
261        );
262    }
263
264    /// `rtmps` is a real scheme (RTMP over TLS, default port 443).
265    #[test]
266    fn rtmps_is_accepted_with_the_tls_default_port() {
267        let t = RtmpTarget::parse("rtmps://h.example/live/key").unwrap();
268        assert!(t.tls);
269        assert_eq!(t.port, RTMPS_DEFAULT_PORT);
270        assert_eq!(t.tc_url, "rtmps://h.example/live");
271        let t = RtmpTarget::parse("rtmps://h.example:8443/live/key").unwrap();
272        assert_eq!(t.port, 8443);
273        assert!(!RtmpTarget::parse("rtmp://h.example/live/key").unwrap().tls);
274    }
275
276    /// RFC 3986 §2.1: percent-encoded path octets are decoded; the query stays
277    /// as written. A key that is only a query is no key.
278    #[test]
279    fn path_text_is_percent_decoded_and_the_query_is_kept_raw() {
280        let t = RtmpTarget::parse("rtmp://h/li%20ve/a/b%20c?token=a%26b").unwrap();
281        assert_eq!(t.app, "li ve");
282        assert_eq!(t.stream_key, "a/b c?token=a%26b");
283        assert!(matches!(
284            RtmpTarget::parse("rtmp://h/live/?token=x"),
285            Err(RtmpUrlError::NoStreamKey)
286        ));
287        assert!(matches!(
288            RtmpTarget::parse("rtmp://h/live/%FF"),
289            Err(RtmpUrlError::PathNotUtf8)
290        ));
291    }
292
293    #[cfg(feature = "tokio")]
294    #[tokio::test]
295    async fn the_plain_tcp_adapter_refuses_a_tls_target() {
296        let t = RtmpTarget::parse("rtmps://127.0.0.1:1/live/key").unwrap();
297        let refused = crate::io::AsyncRtmpClient::connect(
298            &t,
299            broadcast_common::timeouts::Timeouts::default(),
300        )
301        .await;
302        assert!(matches!(refused, Err(e) if e.kind() == std::io::ErrorKind::Unsupported));
303    }
304}