rtmp-runtime 0.13.1

Sans-IO RTMP 1.0 (Adobe Real-Time Messaging Protocol) publish engine for both ends: a driveable ingest server state machine and a publish client over the handshake, chunk stream, AMF0, and message layers; optional tokio socket adapter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! `rtmp[s]://host[:port]/app/stream-key` -> typed target, built with the `url` crate.
//! Replaces `format!("rtmp://{host}:{port}/{app}")`, which produces `rtmp://::1:1935/live`
//! for an IPv6 address (defect 8) and leaks userinfo/query into `tcUrl`.

#[cfg(feature = "tokio")]
use std::net::{IpAddr, SocketAddr};

use url::{Host, Url};

/// IANA-assigned RTMP port, used when the URL names none.
pub const RTMP_DEFAULT_PORT: u16 = 1935;
/// Port an `rtmps://` URL without one connects to: RTMP over TLS is carried on
/// the HTTPS port (443), the de-facto deployment (no IANA assignment exists).
pub const RTMPS_DEFAULT_PORT: u16 = 443;
/// URL scheme of plain RTMP.
pub const SCHEME_RTMP: &str = "rtmp";
/// URL scheme of RTMP over TLS.
pub const SCHEME_RTMPS: &str = "rtmps";

/// A parsed RTMP publish target.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RtmpTarget {
    /// Host, never a pre-formatted string. `rtmp` is a non-special URL scheme, so
    /// the `url` crate reports an IPv4 literal as `Host::Domain("127.0.0.1")`
    /// (`resolve` handles it, `lookup_host` accepts literals); only a bracketed IPv6
    /// literal becomes `Host::Ipv6`.
    pub host: Host<String>,
    /// TCP port; 1935 (`rtmp`) or 443 (`rtmps`) when the URL has none.
    pub port: u16,
    /// Whether the scheme is `rtmps`: the connection must run over TLS, which
    /// the caller supplies (the tokio adapter's [`AsyncRtmpClient::connect`]
    /// opens plain TCP and refuses a TLS target).
    ///
    /// [`AsyncRtmpClient::connect`]: crate::io::AsyncRtmpClient::connect
    pub tls: bool,
    /// The RTMP `app`, percent-decoded (RFC 3986 §2.1).
    pub app: String,
    /// The path remainder, percent-decoded (RFC 3986 §2.1), plus `?query` kept
    /// as written: the query is an opaque string the origin parses itself.
    pub stream_key: String,
    /// `rtmp[s]://host[:port]/app`, IPv6 bracketed, userinfo/query/fragment removed.
    /// Derived from `host`/`port`/`tls`/`app`, so it is read-only (see
    /// [`RtmpTarget::tc_url`]) and can never disagree with `app`.
    tc_url: String,
}

/// Manual `Debug`: the stream key (path remainder plus query) is the publish
/// secret and never renders (issue #1142).
impl core::fmt::Debug for RtmpTarget {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("RtmpTarget")
            .field("host", &self.host)
            .field("port", &self.port)
            .field("app", &self.app)
            .field("stream_key", &"<redacted>")
            .field("tc_url", &self.tc_url)
            .finish()
    }
}

/// An RTMP URL scheme: [`SCHEME_RTMP`] or [`SCHEME_RTMPS`].
///
/// Data-carrying (`Other(String)`), so like every other `Other(_)` discriminant
/// in the workspace it has no fixed label set and no `name()`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Scheme {
    /// `rtmp://`.
    Rtmp,
    /// `rtmps://`.
    Rtmps,
    /// Any other scheme, as written.
    Other(String),
}

impl Scheme {
    /// The scheme this URL text carries; an unknown one is kept verbatim.
    fn parse(text: &str) -> Self {
        match text {
            SCHEME_RTMP => Scheme::Rtmp,
            SCHEME_RTMPS => Scheme::Rtmps,
            other => Scheme::Other(other.to_string()),
        }
    }
}

impl core::fmt::Display for Scheme {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Scheme::Rtmp => f.write_str(SCHEME_RTMP),
            Scheme::Rtmps => f.write_str(SCHEME_RTMPS),
            Scheme::Other(text) => f.write_str(text),
        }
    }
}

/// Why an RTMP URL was rejected.
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RtmpUrlError {
    /// The text is not a URL (RFC 3986 §3).
    #[error("invalid URL: {0}")]
    Parse(#[from] url::ParseError),
    /// The URL's scheme is not `rtmp` or `rtmps`.
    #[error("unsupported scheme {0} (only rtmp and rtmps)")]
    Scheme(Scheme),
    /// A percent-decoded path segment is not valid UTF-8.
    #[error("percent-decoded path is not valid UTF-8")]
    PathNotUtf8,
    /// The URL has no host.
    #[error("URL has no host")]
    NoHost,
    /// The URL has no app segment.
    #[error("URL has no app segment")]
    NoApp,
    /// The URL has no stream key after the app.
    #[error("URL has no stream key")]
    NoStreamKey,
}

impl RtmpTarget {
    /// Parses `rtmp[s]://host[:port]/app/stream-key[?query]` by the
    /// nginx-rtmp convention, shared by publish and play: the **first** path
    /// segment is the app, and every later segment is part of the stream key.
    /// Non-empty segments are percent-decoded individually (RFC 3986 §2.1:
    /// `b%20c` names `b c`), joined with `/`, and the query is appended as
    /// written. Empty segments and a trailing slash are ignored, so
    /// `rtmp://h/app/inst/key` names app `app` and key `inst/key`, and
    /// `rtmp://h/live/a/b%20c?token=x` names app `live` and key
    /// `a/b c?token=x`. A path of one segment names only an app.
    pub fn parse(url: &str) -> Result<Self, RtmpUrlError> {
        let base = parse_base(url)?;
        let (app, key) = split_path(&base)?;
        let key = key.ok_or(RtmpUrlError::NoStreamKey)?;
        Self::build(&base, &app, &key)
    }

    /// The app a URL names, without requiring a stream key: used by a caller
    /// that can publish with a configured default key.
    pub fn parse_app(url: &str) -> Result<String, RtmpUrlError> {
        let base = parse_base(url)?;
        Ok(split_path(&base)?.0)
    }

    /// Parse a URL, substituting a caller's `app` when it names none and
    /// `stream_key` when it names no key. Other errors are returned unchanged
    /// so the caller can report or skip the output.
    pub fn parse_or_default(url: &str, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
        match Self::parse(url) {
            Ok(target) => Ok(target),
            Err(RtmpUrlError::NoApp) => Self::from_parts(url, app, stream_key),
            Err(RtmpUrlError::NoStreamKey) => {
                let base = parse_base(url)?;
                let parsed_app = split_path(&base)?.0;
                Self::build(&base, &parsed_app, stream_key)
            }
            Err(err) => Err(err),
        }
    }

    /// Host and port from `base` (any path/query is ignored), `app` and
    /// `stream_key` given separately.
    pub fn from_parts(base: &str, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
        Self::build(&parse_base(base)?, app, stream_key)
    }

    /// The RTMP `tcUrl` to send in the `connect` command:
    /// `rtmp[s]://host[:port]/app`, IPv6 bracketed, userinfo/query/fragment
    /// removed. Derived from `host`/`port`/`tls`/`app`, so it can never
    /// disagree with them.
    pub fn tc_url(&self) -> &str {
        &self.tc_url
    }

    fn build(base: &Url, app: &str, stream_key: &str) -> Result<Self, RtmpUrlError> {
        let host = base.host().ok_or(RtmpUrlError::NoHost)?.to_owned();
        let tls = base.scheme() == SCHEME_RTMPS;
        let mut tc = base.clone();
        tc.set_path(&format!("/{app}"));
        tc.set_query(None);
        tc.set_fragment(None);
        let _ = tc.set_username("");
        let _ = tc.set_password(None);
        Ok(RtmpTarget {
            host,
            port: base.port().unwrap_or(if tls {
                RTMPS_DEFAULT_PORT
            } else {
                RTMP_DEFAULT_PORT
            }),
            tls,
            app: app.to_string(),
            stream_key: stream_key.to_string(),
            tc_url: tc.to_string(),
        })
    }

    /// Resolved socket addresses (DNS only for `Host::Domain`).
    #[cfg(feature = "tokio")]
    pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
        match &self.host {
            Host::Ipv4(a) => Ok(vec![SocketAddr::new(IpAddr::V4(*a), self.port)]),
            Host::Ipv6(a) => Ok(vec![SocketAddr::new(IpAddr::V6(*a), self.port)]),
            Host::Domain(d) => Ok(tokio::net::lookup_host((d.as_str(), self.port))
                .await?
                .collect()),
        }
    }
}

fn parse_base(url: &str) -> Result<Url, RtmpUrlError> {
    let u = Url::parse(url)?;
    if u.scheme() != SCHEME_RTMP && u.scheme() != SCHEME_RTMPS {
        return Err(RtmpUrlError::Scheme(Scheme::parse(u.scheme())));
    }
    Ok(u)
}

/// The app and optional stream key a URL's path names, by the rule documented
/// on [`RtmpTarget::parse`].
fn split_path(base: &Url) -> Result<(String, Option<String>), RtmpUrlError> {
    let mut raw = base.path_segments().ok_or(RtmpUrlError::NoApp)?;
    let app = decode(
        raw.next()
            .filter(|s| !s.is_empty())
            .ok_or(RtmpUrlError::NoApp)?,
    )?;
    let mut parts = Vec::new();
    for segment in raw.filter(|s| !s.is_empty()) {
        parts.push(decode(segment)?);
    }
    if parts.is_empty() {
        return Ok((app, None));
    }
    let mut key = parts.join("/");
    if let Some(query) = base.query() {
        key.push('?');
        key.push_str(query);
    }
    Ok((app, Some(key)))
}

fn decode(raw: &str) -> Result<String, RtmpUrlError> {
    percent_encoding::percent_decode_str(raw)
        .decode_utf8()
        .map(std::borrow::Cow::into_owned)
        .map_err(|_| RtmpUrlError::PathNotUtf8)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn plain_host_default_port() {
        let t = RtmpTarget::parse("rtmp://example.test/live/key").unwrap();
        assert_eq!(
            (t.port, t.app.as_str(), t.stream_key.as_str()),
            (1935, "live", "key")
        );
        assert_eq!(t.tc_url(), "rtmp://example.test/live");
    }

    /// Defect 8: an IPv6 host must stay bracketed in tcUrl; building it from a bare
    /// `IpAddr` + port (`format!("rtmp://{ip}:{port}/{app}")`) yields `rtmp://::1:1935/live`.
    #[test]
    fn ipv6_host_is_bracketed_in_tc_url() {
        let t = RtmpTarget::parse("rtmp://[::1]:1935/live/key").unwrap();
        assert_eq!(t.host, url::Host::<String>::Ipv6("::1".parse().unwrap()));
        assert_eq!(t.tc_url(), "rtmp://[::1]:1935/live");
        let t = RtmpTarget::parse("rtmp://[2001:db8::7]/live/key").unwrap();
        assert_eq!(t.tc_url(), "rtmp://[2001:db8::7]/live");
        assert_eq!(t.port, 1935);
    }

    #[test]
    fn ipv4_literal_is_a_domain_host_for_this_non_special_scheme() {
        let t = RtmpTarget::parse("rtmp://127.0.0.1:1936/live/k").unwrap();
        assert_eq!(t.host, url::Host::<String>::Domain("127.0.0.1".into()));
        assert_eq!(t.tc_url(), "rtmp://127.0.0.1:1936/live");
    }

    #[test]
    fn userinfo_query_and_fragment_never_reach_tc_url() {
        let t = RtmpTarget::parse("rtmp://user:s3cret@host:1936/live/key?token=a/b#frag").unwrap();
        assert_eq!(t.tc_url(), "rtmp://host:1936/live");
        assert_eq!(t.stream_key, "key?token=a/b");
        assert!(!t.tc_url().contains("s3cret"));
    }

    #[test]
    fn every_segment_after_the_app_is_the_stream_key() {
        let t = RtmpTarget::parse("rtmp://h/live/a/b/c").unwrap();
        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("live", "a/b/c"));
        let t = RtmpTarget::parse("rtmp://h/app/inst/key").unwrap();
        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("app", "inst/key"));
        assert_eq!(t.tc_url(), "rtmp://h/app");
        let t = RtmpTarget::parse("rtmp://h/a/b/c/d").unwrap();
        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("a", "b/c/d"));
        assert_eq!(t.tc_url(), "rtmp://h/a");
    }

    #[test]
    fn empty_segments_and_a_trailing_slash_are_ignored() {
        let t = RtmpTarget::parse("rtmp://h/app/inst/key/").unwrap();
        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("app", "inst/key"));
        let t = RtmpTarget::parse("rtmp://h/app/inst//key").unwrap();
        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("app", "inst/key"));
    }

    #[test]
    fn key_segments_are_percent_decoded_and_the_query_is_kept_raw() {
        let t = RtmpTarget::parse("rtmp://h/app/my%20inst/key").unwrap();
        assert_eq!(
            (t.app.as_str(), t.stream_key.as_str()),
            ("app", "my inst/key")
        );
        assert!(matches!(
            RtmpTarget::parse("rtmp://h/app/in%FFst/key"),
            Err(RtmpUrlError::PathNotUtf8)
        ));
    }

    #[test]
    fn parse_or_default_keeps_the_named_app_and_fills_only_the_missing_piece() {
        let t = RtmpTarget::parse_or_default("rtmp://h/myapp", "live", "default").unwrap();
        assert_eq!(
            (t.app.as_str(), t.stream_key.as_str()),
            ("myapp", "default")
        );
        let t = RtmpTarget::parse_or_default("rtmp://h/", "live", "default").unwrap();
        assert_eq!((t.app.as_str(), t.stream_key.as_str()), ("live", "default"));
        assert!(matches!(
            RtmpTarget::parse_or_default("rtmp://h/app/%FF", "live", "default"),
            Err(RtmpUrlError::PathNotUtf8)
        ));
    }

    #[test]
    fn parse_app_keeps_the_app_when_no_stream_key_is_named() {
        assert_eq!(
            RtmpTarget::parse_app("rtmp://h/myapp").expect("an app is named"),
            "myapp"
        );
        assert_eq!(
            RtmpTarget::parse_app("rtmp://h/app/inst/key").expect("an app is named"),
            "app"
        );
        assert!(matches!(
            RtmpTarget::parse_app("rtmp://h/"),
            Err(RtmpUrlError::NoApp)
        ));
    }

    #[test]
    fn missing_pieces_and_wrong_scheme_are_errors() {
        assert!(matches!(
            RtmpTarget::parse("rtmp://h/"),
            Err(RtmpUrlError::NoApp)
        ));
        assert!(matches!(
            RtmpTarget::parse("rtmp://h/live"),
            Err(RtmpUrlError::NoStreamKey)
        ));
        assert!(matches!(
            RtmpTarget::parse("http://h/live/k"),
            Err(RtmpUrlError::Scheme(Scheme::Other(_)))
        ));
        assert!(matches!(
            RtmpTarget::parse("not a url"),
            Err(RtmpUrlError::Parse(_))
        ));
    }

    #[test]
    fn from_parts_takes_host_and_port_from_base_only() {
        let t = RtmpTarget::from_parts("rtmp://[::1]:1940/ignored/path", "live", "k").unwrap();
        assert_eq!(t.tc_url(), "rtmp://[::1]:1940/live");
        assert_eq!(
            (t.app.as_str(), t.stream_key.as_str(), t.port),
            ("live", "k", 1940)
        );
    }

    #[cfg(feature = "tokio")]
    #[tokio::test]
    async fn resolve_uses_the_literal_address_without_dns() {
        let t = RtmpTarget::parse("rtmp://[::1]:1935/live/key").unwrap();
        assert_eq!(
            t.resolve().await.unwrap(),
            vec!["[::1]:1935".parse::<SocketAddr>().unwrap()]
        );
        let t = RtmpTarget::parse("rtmp://127.0.0.1:1/live/key").unwrap();
        assert_eq!(
            t.resolve().await.unwrap(),
            vec!["127.0.0.1:1".parse::<SocketAddr>().unwrap()]
        );
    }

    /// `rtmps` is a real scheme (RTMP over TLS, default port 443).
    #[test]
    fn rtmps_is_accepted_with_the_tls_default_port() {
        let t = RtmpTarget::parse("rtmps://h.example/live/key").unwrap();
        assert!(t.tls);
        assert_eq!(t.port, RTMPS_DEFAULT_PORT);
        assert_eq!(t.tc_url(), "rtmps://h.example/live");
        let t = RtmpTarget::parse("rtmps://h.example:8443/live/key").unwrap();
        assert_eq!(t.port, 8443);
        assert!(!RtmpTarget::parse("rtmp://h.example/live/key").unwrap().tls);
    }

    /// RFC 3986 §2.1: percent-encoded path octets are decoded; the query stays
    /// as written. A key that is only a query is no key.
    #[test]
    fn path_text_is_percent_decoded_and_the_query_is_kept_raw() {
        let t = RtmpTarget::parse("rtmp://h/li%20ve/a/b%20c?token=a%26b").unwrap();
        assert_eq!(t.app, "li ve");
        assert_eq!(t.stream_key, "a/b c?token=a%26b");
        assert!(matches!(
            RtmpTarget::parse("rtmp://h/live/?token=x"),
            Err(RtmpUrlError::NoStreamKey)
        ));
        assert!(matches!(
            RtmpTarget::parse("rtmp://h/live/%FF"),
            Err(RtmpUrlError::PathNotUtf8)
        ));
    }

    #[cfg(feature = "tokio")]
    #[tokio::test]
    async fn the_plain_tcp_adapter_refuses_a_tls_target() {
        let t = RtmpTarget::parse("rtmps://127.0.0.1:1/live/key").unwrap();
        let timeouts = broadcast_net::timeouts::Timeouts::new(
            core::time::Duration::from_secs(10),
            core::time::Duration::from_secs(10),
            core::time::Duration::from_secs(30),
            core::time::Duration::from_secs(10),
        );
        let refused = crate::io::AsyncRtmpClient::connect(crate::io::RtmpClientConfig::new(
            t,
            crate::client::RtmpClientConfig::default(),
            timeouts,
        ))
        .await;
        assert!(matches!(refused, Err(e) if e.kind() == std::io::ErrorKind::Unsupported));
    }
}