diff --git a/doc/bin/webrtc.md b/doc/bin/webrtc.md index 75466928250..11fe8530128 100644 --- a/doc/bin/webrtc.md +++ b/doc/bin/webrtc.md @@ -29,8 +29,11 @@ the highest-bitrate enabled Opus rendition (then sample rate, then channels). It follows the catalog: a peer whose rendition is disabled moves to the next best at that rendition's first keyframe, a better one that re-enables wins the peer back, and with none enabled the peer receives nothing until one is. `--cors-origin` -opens the endpoint to browsers on other origins, and `--udp-bind` plus -`--public-addr` pin one media port for firewalls. The listener is plain HTTP; +opens the endpoint to browsers on other origins. Every session shares one UDP +media port, `--udp-bind` (OS-picked by default), bound at startup so a taken port +fails before the listener reports ready. Behind NAT, `--public-addr` advertises +the public address as written, so `--public-addr 203.0.113.1:5000` reaches a port +the NAT forwards to `--udp-bind`; port 0 advertises the bound port. The listener is plain HTTP; put a TLS-terminating proxy in front for WHIP clients that require HTTPS. A fresh WHEP peer joins at the current group, so it starts at a keyframe without waiting for the next one. `DELETE` on the resource URL tears a session down per the RFC. Each WHIP session publishes diff --git a/quest/m2/README.md b/quest/m2/README.md index 63918d0d967..8396c33a229 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -60,7 +60,6 @@ removal, a rename, or a wire, catalog, or format change that is free until [device and cursor](/quest/m2/native-media-config.md), [sink names](/quest/m2/audio-sink-names.md), [moq-vaapi's exports](/quest/m2/vaapi-exports.md), - [the WebRTC bind](/quest/m2/webrtc-bind.md), [the WHEP pull's announcement](/quest/m2/whep-pull-announce.md), and [upstream str0m](https://github.com/moq-dev/moq/pull/8963), which reverses the 2026-10-30 vendoring. diff --git a/quest/m2/webrtc-bind.md b/quest/m2/webrtc-bind.md deleted file mode 100644 index 1e18e7904f5..00000000000 --- a/quest/m2/webrtc-bind.md +++ /dev/null @@ -1,79 +0,0 @@ -# [M] moq-webrtc's server binds its UDP socket at startup - -## Goal - -`moq_webrtc::Server::bind(config).await` binds the shared UDP socket and -fails if it cannot, so `moq import|export webrtc --listen` reports a taken -or unbindable `--udp-bind` port at startup, before it says it is ready. -`--public-addr 203.0.113.1:5000` advertises port 5000, as written. The -server's socket shape can take the planned shared-port feed without another -break, and the client config carries no field nothing sets. - -## Plan - -Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): - -- ✅ `Server::bind(config)` binds at construction (rejected: land the m3 - shared-port feed before the cut so the two-variant socket ships; keep the - lazy bind and take a break in the release after). It matches - `moq_rtmp::Server::bind` and `moq_srt::Server::bind`, and a gateway that - logs "serving" with no socket bound fails late, in front of a browser. -- ✅ `--public-addr` honors the port it is given (rejected: change the type - to an IP and rename the flag `--public-ip`; keep and document). The type - is `SocketAddr`, and a mapped port behind a NAT is what the port is for. -- ✅ `client::Config::ice_candidates` is deleted until a caller sets it. - -Facts found by the audit: - -- `Server::new(config) -> Self` binds nothing - (`rs/moq-webrtc/src/server/mod.rs:181`). The socket binds inside `mux()` - on the first accept (`:170`, `:192`-`:196`), "so `Server::new` can stay - synchronous". -- The CLI logs "serving WebRTC" and calls `notify_ready()` with no UDP - socket bound (`rs/moq-cli/src/webrtc.rs:144`-`:147`), so a bad `--udp-bind` - surfaces as an HTTP error on the first WHIP or WHEP request. -- `server::Config` and `server::Socket` derive `Clone` - (`rs/moq-webrtc/src/server/mod.rs:129`, `:149`), and `Socket` has one - variant, `Bind(SocketAddr)` (`:153`). The second is the m3 - [shared-port feed](/quest/m3/one-port/rtc-feed.md), which holds a channel - receiver and cannot be `Clone`; that quest already notes the fed socket - "may belong in the server's constructor rather than the config". Either - answer is a break once the crate is published. -- The session keeps only the IP of each advertised address: - `advertise.iter().map(|addr| SocketAddr::new(addr.ip(), port))` with the - bound port (`rs/moq-webrtc/src/session.rs:715`). -- `client::Config::ice_candidates` - (`rs/moq-webrtc/src/client/mod.rs:21`) is read at - `client/whip.rs:28` and `client/whep.rs:27` and set by nothing: both CLI - call sites pass `client::Config::default()` - (`rs/moq-cli/src/webrtc.rs:103`, `:125`). -- `moq-webrtc` has never been published under this name (the API diff marks - it new), so all of this is free until the cut. - -For the PR: - -- Settle where the socket lives so the feed is additive. Recommended: the - socket is an argument of the constructor, not a field of a `Clone` - config, and the single-variant `Socket` enum is deleted until the feed - adds its own constructor. The alternative, dropping `Clone` from `Config` - and `Socket`, keeps one constructor but freezes a config that cannot be - copied. Write the choice into [the feed quest](/quest/m3/one-port/rtc-feed.md). -- `Server::bind` is async and returns the bind error. Reproduce the late - failure first: a test that binds the UDP port, starts the server on it, - and expects the constructor to fail. -- An advertised candidate is sent exactly as given. Keep the existing - default for an unspecified bind address (loopback with the bound port). - Test that a `--public-addr` with its own port reaches the SDP answer. -- Recommended, not decided by the maintainer: record the crate's version - line in the PR. The manifest reads `0.3.12` - (`rs/moq-webrtc/Cargo.toml:8`), so `just version 0.22.0` moves it onto the - shared line; that is right, since published moq-cli depends on it. -- Update `doc/bin/webrtc.md` and `rs/moq-webrtc/MIGRATE.md`. - -Public API: moq-webrtc breaks (`Server::new` becomes `Server::bind`, the -socket's place, `client::Config::ice_candidates`), free while unpublished. -CLI: `--public-addr` now advertises its port. Wire: none. - -## Related - -- [A WebRTC feed on the shared port](/quest/m3/one-port/rtc-feed.md) - adds the second socket source this leaves room for diff --git a/quest/m3/one-port/rtc-feed.md b/quest/m3/one-port/rtc-feed.md index 36473bd16f6..777aa64c79f 100644 --- a/quest/m3/one-port/rtc-feed.md +++ b/quest/m3/one-port/rtc-feed.md @@ -56,7 +56,8 @@ read loop: moq-webrtc's `ice::Socket`'s `udp: Arc` becomes implements it, so the bound case behaves as today), and a fed mux routes datagrams from the demux hook instead of reading a bound socket. Adapt the sketch above to that: `advertised` is `ice_candidates`, and `recv` feeds -the mux's existing router. Address-family mapping follows the real socket, +the mux's existing router; the `Socket` enum is replaced by a second +constructor (below). Address-family mapping follows the real socket, not the advertisement: a dual-stack socket bound to `[::]` may advertise a public IPv4 address, so the `Transmit` impl owns the IPv4-mapped conversion moq-webrtc's ICE module applies today. Received and pinned addresses use the same @@ -78,13 +79,15 @@ returns a guard that releases the pin on drop. So the fed `Socket` takes a selected pair, dropped when its session ends or ICE moves. A feed's `recv` returns `None` once the listener is gone. -Things to watch: the server config is `Clone` today and a receiver is not, so -the fed socket may belong in the server's constructor rather than the -config. Since 2026-11-16 (maintainer, /quest-plan of the pre-cut audit) -[the bind at startup](/quest/m2/webrtc-bind.md) settles this before the cut: -the server becomes `Server::bind(config)`, and that PR picks where the -socket lives and writes it here, so the feed is an addition, not a break. The fed mux has nothing to bind lazily, and a dropped feed should -fail the server loudly rather than idle. +Settled 2026-11-16 by the bind at startup: the socket is the constructor's, +not the config's. `Server::bind(addr, config).await` binds its own socket, and +`server::Config` holds only `ice_candidates` and stays `Clone`; there is no +`Socket` enum. The feed adds a second constructor, such as +`Server::feed(webrtc, config)`, taking the `WebRtc` handle by value, so it is +an addition, not a break. Its `ice_candidates` are the shared address to +advertise, sent as given (port 0 takes the socket's port). The fed mux has +nothing to bind, and a dropped feed should fail the server loudly rather than +idle. Noted 2026-10-31 from [moq-dev/moq#7095](https://github.com/moq-dev/moq/pull/7095): its demux `Datagram` carries no ECN marks or kernel receive timestamp. If diff --git a/rs/moq-cli/src/args.rs b/rs/moq-cli/src/args.rs index cec1828432a..7c84c985263 100644 --- a/rs/moq-cli/src/args.rs +++ b/rs/moq-cli/src/args.rs @@ -1814,6 +1814,18 @@ mod tests { } } + /// The WebRTC media socket flags configure the listener, so a dialer refuses them. + #[test] + fn webrtc_media_flags_need_the_listener() { + for flag in [["--udp-bind", "[::]:5000"], ["--public-addr", "203.0.113.1:5000"]] { + let listen = [&["webrtc", "--listen", "127.0.0.1:8443"][..], &flag].concat(); + export(&listen).unwrap().validate().unwrap(); + let connect = [&["webrtc", "--connect", "http://remote/whip"][..], &flag].concat(); + let err = export(&connect).err().expect("a dialer took a listener flag"); + assert!(err.to_string().contains("--listen"), "{flag:?}: {err}"); + } + } + /// `--report` and `--echo-path` go where the CLI builds the one catalog they add a section to. #[test] fn catalog_sections_need_a_catalog_the_cli_builds() { diff --git a/rs/moq-cli/src/webrtc.rs b/rs/moq-cli/src/webrtc.rs index 3704adee74f..c860ad697e6 100644 --- a/rs/moq-cli/src/webrtc.rs +++ b/rs/moq-cli/src/webrtc.rs @@ -26,11 +26,12 @@ pub struct Args { #[usage(name = "webrtc-listen", long = "listen", value_name = "ADDR", group = "webrtc-mode")] pub listen: Option, - /// Shared UDP socket for ICE/media (one port for all sessions). + /// Shared UDP socket for ICE/media (one port for all sessions), bound at startup. #[usage(long, requires = "--listen", default = "[::]:0")] pub udp_bind: SocketAddr, - /// Public UDP address(es) advertised as ICE host candidates (repeatable). + /// Public UDP address(es) advertised as ICE host candidates, as given (repeatable). + /// Port 0 advertises the `--udp-bind` port. #[usage(long, requires = "--listen")] pub public_addr: Vec, @@ -57,7 +58,7 @@ pub struct Listen { /// WHIP server: accept incoming WebRTC publishes into the Origin as `target.name` (import). pub async fn listen_import(target: ImportTarget, listen: Listen) -> anyhow::Result<()> { let publisher = scope_producer(&target.origin, &target.name)?; - let server = moq_webrtc::Server::new(server_config(&listen)); + let server = bind(&listen).await?; serve(server.publish_router(publisher, target.ingest), "WHIP", listen).await } @@ -69,7 +70,7 @@ pub async fn listen_export(origin: moq_net::origin::Consumer, name: String, list let subscriber = origin .scope("", &scope) .with_context(|| format!("failed to scope origin to broadcast `{name}`"))?; - let server = moq_webrtc::Server::new(server_config(&listen)); + let server = bind(&listen).await?; serve(server.subscribe_router(subscriber), "WHEP", listen).await } @@ -127,11 +128,13 @@ pub async fn connect_export(origin: moq_net::origin::Consumer, url: Url, name: S Ok(()) } -fn server_config(listen: &Listen) -> moq_webrtc::server::Config { +/// Bind the shared media socket, so a bad `--udp-bind` fails startup. +async fn bind(listen: &Listen) -> anyhow::Result { let mut config = moq_webrtc::server::Config::default(); - config.socket = moq_webrtc::server::Socket::Bind(listen.udp_bind); config.ice_candidates.clone_from(&listen.public_addr); - config + moq_webrtc::Server::bind(listen.udp_bind, config) + .await + .with_context(|| format!("failed to bind --udp-bind {}", listen.udp_bind)) } async fn serve(router: axum::Router, role: &str, listen: Listen) -> anyhow::Result<()> { diff --git a/rs/moq-webrtc/src/client/mod.rs b/rs/moq-webrtc/src/client/mod.rs index 376a02cc5e4..ba18de44886 100644 --- a/rs/moq-webrtc/src/client/mod.rs +++ b/rs/moq-webrtc/src/client/mod.rs @@ -8,18 +8,15 @@ mod whep; mod whip; -use std::net::SocketAddr; - use url::Url; /// Configuration shared by both `client publish` and `client pull`. +/// +/// No options yet; it is where a later one, such as a dial policy, goes without +/// changing [`Client::new`]. #[derive(Clone, Debug, Default)] #[non_exhaustive] -pub struct Config { - /// Public UDP socket addresses to advertise as ICE host candidates in - /// our outbound offer. Same semantics as [`crate::server::Config::ice_candidates`]. - pub ice_candidates: Vec, -} +pub struct Config {} /// Outbound WHIP/WHEP dialer. /// @@ -27,7 +24,6 @@ pub struct Config { /// rustls config survive between resources. #[derive(Clone)] pub struct Client { - config: Config, http: reqwest::Client, } @@ -40,19 +36,16 @@ impl Client { /// Fails with [`Error::UnsupportedCpu`](crate::Error::UnsupportedCpu) on a CPU /// rind can't run on. pub fn new(config: Config) -> crate::Result { + // Destructured so a new option cannot compile without being used. + let Config {} = config; // reqwest reads rustls's process default and panics without one, so install rind's // unless the host already chose a provider. moq_crypto::provider::install_default()?; Ok(Self { - config, http: reqwest::Client::builder().build()?, }) } - pub(crate) fn config(&self) -> &Config { - &self.config - } - pub(crate) fn http(&self) -> &reqwest::Client { &self.http } diff --git a/rs/moq-webrtc/src/client/whep.rs b/rs/moq-webrtc/src/client/whep.rs index 3fcc4c3ca0f..fe58215d65d 100644 --- a/rs/moq-webrtc/src/client/whep.rs +++ b/rs/moq-webrtc/src/client/whep.rs @@ -23,7 +23,7 @@ pub(crate) async fn dial( ) -> Result<()> { let sink = Box::new(IngestSink::new(broadcast, catalog)?); - let socket = session::bind_udp(&client.config().ice_candidates).await?; + let socket = session::bind_udp().await?; let mut rtc = session::rtc_config()?.build(kio::clock::now().into_std()); for addr in socket.locals() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; diff --git a/rs/moq-webrtc/src/client/whip.rs b/rs/moq-webrtc/src/client/whip.rs index 2e34f0b417a..33041e8462e 100644 --- a/rs/moq-webrtc/src/client/whip.rs +++ b/rs/moq-webrtc/src/client/whip.rs @@ -24,7 +24,7 @@ pub(crate) async fn dial(client: &Client, url: Url, source: moq_mux::Source) -> return Err(Error::NoRenditions); } - let socket = session::bind_udp(&client.config().ice_candidates).await?; + let socket = session::bind_udp().await?; // Restrict to codecs the catalog can actually source so the remote // answer doesn't pick a codec we have no rendition for. let mut rtc = session::rtc_with_codecs(&codecs)?; diff --git a/rs/moq-webrtc/src/lib.rs b/rs/moq-webrtc/src/lib.rs index 2468a996da8..f66e992365e 100644 --- a/rs/moq-webrtc/src/lib.rs +++ b/rs/moq-webrtc/src/lib.rs @@ -192,7 +192,9 @@ mod tests { let (old_route, mut old, old_catalog) = publish_opus(&origin, moq_net::Instance::random()); push(&mut *old, 20_000, OPUS_PACKET); - let server = Server::new(server::Config::default()); + let server = Server::bind("127.0.0.1:0".parse().unwrap(), server::Config::default()) + .await + .unwrap(); let whep_origin = origin.consume(); let (sessions_tx, mut sessions) = tokio::sync::mpsc::channel(1); let app = Router::new().route( @@ -258,7 +260,9 @@ mod tests { let (old_route, mut old, old_catalog) = publish_opus(&origin, moq_net::Instance::random()); push(&mut *old, 20_000, OPUS_PACKET); - let server = Server::new(server::Config::default()); + let server = Server::bind("127.0.0.1:0".parse().unwrap(), server::Config::default()) + .await + .unwrap(); let ingest_origin = moq_tokio::origin::spawn(); let whip_origin = ingest_origin.clone(); let app = Router::new().route( @@ -323,7 +327,9 @@ mod tests { tokio::task::JoinHandle<()>, tokio::sync::mpsc::Receiver>>, ) { - let server = Server::new(server::Config::default()); + let server = Server::bind("127.0.0.1:0".parse().unwrap(), server::Config::default()) + .await + .unwrap(); let origin = moq_tokio::origin::spawn(); let (sessions_tx, sessions) = tokio::sync::mpsc::channel(1); let app = Router::new().route( @@ -466,7 +472,9 @@ mod tests { drop(announcements); let server_origin = moq_tokio::origin::spawn(); - let server = Server::new(server::Config::default()); + let server = Server::bind("127.0.0.1:0".parse().unwrap(), server::Config::default()) + .await + .unwrap(); let (sources_tx, mut sources_rx) = tokio::sync::mpsc::channel(2); let whip_server = server.clone(); let whip_origin = server_origin.clone(); diff --git a/rs/moq-webrtc/src/server/mod.rs b/rs/moq-webrtc/src/server/mod.rs index 54a85e81bd3..c243d01e492 100644 --- a/rs/moq-webrtc/src/server/mod.rs +++ b/rs/moq-webrtc/src/server/mod.rs @@ -20,7 +20,7 @@ use std::time::Duration; use axum::Router; #[cfg(feature = "server")] use axum::http::{HeaderValue, StatusCode, Uri}; -use tokio::sync::{OnceCell, oneshot}; +use tokio::sync::oneshot; use crate::Result; use mux::Mux; @@ -129,34 +129,14 @@ pub(crate) fn session_location(uri: &Uri, resource_id: &str) -> Option, - - /// The shared WebRTC media socket. Every WHIP/WHEP session shares this one UDP port - /// (demuxed by ICE ufrag), so a deployment opens exactly one media port in its firewall. - /// Defaults to binding `0.0.0.0:0`, letting the OS pick a port, which is fine for - /// dev/loopback; production pins it. - pub socket: Socket, -} - -/// Where the shared WebRTC media socket comes from. -#[derive(Clone, Debug)] -#[non_exhaustive] -pub enum Socket { - /// Bind a UDP socket at this address on the first accept. - Bind(SocketAddr), -} - -impl Default for Socket { - fn default() -> Self { - Self::Bind(SocketAddr::from(([0, 0, 0, 0], 0))) - } } /// Shared WebRTC media state: the UDP mux and live sessions behind [`whip::accept`] and [`whep::accept`]. @@ -166,10 +146,9 @@ pub struct Server { } struct Inner { - config: Config, - /// The shared media socket + demux, bound lazily on the first accept so - /// `Server::new` can stay synchronous (and an idle server binds no port). - mux: OnceCell, + /// The shared media socket and its demux. Every WHIP/WHEP session shares + /// this one UDP port, demuxed by ICE ufrag. + mux: Mux, /// Live sessions keyed by resource id, each holding a cancel sender the /// session task selects on. Lets [`Server::terminate`] (and the bundled /// `DELETE` route) end a session by its `Location` id. @@ -177,25 +156,30 @@ struct Inner { } impl Server { - /// Build a server with shared ICE and media settings. - pub fn new(config: Config) -> Self { - Self { + /// Bind the shared media socket at `addr` and serve WHIP and WHEP sessions on it. + /// + /// Every session shares this one UDP port, so a deployment opens exactly one + /// media port in its firewall; port 0 lets the OS pick one. Fails if the + /// socket cannot be bound, or an advertised candidate is invalid. Dropping + /// the last clone, and every session it accepted, releases the port. + pub async fn bind(addr: SocketAddr, config: Config) -> Result { + let mux = Mux::bind(addr, &config.ice_candidates).await?; + Ok(Self { inner: Arc::new(Inner { - config, - mux: OnceCell::new(), + mux, sessions: Mutex::new(HashMap::new()), }), - } + }) } - /// The shared media mux, bound (and its demux task spawned) on first use. - pub(crate) async fn mux(&self) -> Result<&Mux> { - self.inner - .mux - .get_or_try_init(|| match self.inner.config.socket { - Socket::Bind(addr) => Mux::bind(addr, &self.inner.config.ice_candidates), - }) - .await + /// The shared media mux. + pub(crate) fn mux(&self) -> &Mux { + &self.inner.mux + } + + /// The address the shared media socket is bound to. + pub fn local_addr(&self) -> SocketAddr { + self.inner.mux.local_addr() } /// Router for `server publish` (WHIP), publishing each session as `ingest` says. Mount @@ -267,27 +251,57 @@ pub(crate) fn delete(server: &Server, path: &str) -> StatusCode { mod tests { use super::*; - fn server() -> Server { - Server::new(Config::default()) + const LOOPBACK: SocketAddr = SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 0); + + async fn server() -> Server { + Server::bind(LOOPBACK, Config::default()).await.unwrap() } - #[test] - fn terminate_unknown_session_is_false() { - assert!(!server().terminate("00000000-0000-0000-0000-000000000000")); + /// A port something else holds fails the constructor, before anything reports + /// the server ready, rather than the first WHIP or WHEP request. + #[tokio::test] + async fn bind_fails_on_a_taken_port() { + let taken = std::net::UdpSocket::bind(LOOPBACK).unwrap(); + let err = Server::bind(taken.local_addr().unwrap(), Config::default()) + .await + .err() + .expect("bound a taken port"); + assert!(matches!(err, crate::Error::Io(_)), "{err}"); } - #[test] - fn terminate_registered_session_once() { - let server = server(); + /// The last clone of a server that accepted nothing releases its port. + #[tokio::test] + async fn dropping_the_server_releases_its_port() { + let server = server().await; + let addr = server.local_addr(); + let clone = server.clone(); + drop(server); + std::net::UdpSocket::bind(addr).expect_err("a live clone keeps the port"); + + drop(clone); + // The abort only schedules the demux task to be dropped; yielding lets this + // current-thread runtime run it, which drops its socket handle. + tokio::task::yield_now().await; + std::net::UdpSocket::bind(addr).expect("the dropped server kept its port"); + } + + #[tokio::test] + async fn terminate_unknown_session_is_false() { + assert!(!server().await.terminate("00000000-0000-0000-0000-000000000000")); + } + + #[tokio::test] + async fn terminate_registered_session_once() { + let server = server().await; let id = "11111111-1111-1111-1111-111111111111"; let _cancel = server.register_session(id.to_string()); assert!(server.terminate(id), "first terminate finds the session"); assert!(!server.terminate(id), "second terminate is a no-op"); } - #[test] - fn unregister_drops_the_entry() { - let server = server(); + #[tokio::test] + async fn unregister_drops_the_entry() { + let server = server().await; let id = "22222222-2222-2222-2222-222222222222"; let _cancel = server.register_session(id.to_string()); server.unregister_session(id); diff --git a/rs/moq-webrtc/src/server/mux.rs b/rs/moq-webrtc/src/server/mux.rs index bb05dc158d9..4c05ac2e39d 100644 --- a/rs/moq-webrtc/src/server/mux.rs +++ b/rs/moq-webrtc/src/server/mux.rs @@ -49,14 +49,24 @@ struct Entry { /// The shared media socket plus its demux routing table. /// -/// One per [`Server`](crate::server::Server), bound lazily on the first -/// WHIP/WHEP accept so `Server::new` can stay synchronous. +/// One per [`Server`](crate::server::Server), bound when the server is. pub(crate) struct Mux { socket: Arc, + /// The address `socket` is bound to. + local: SocketAddr, registry: Arc>, - /// ICE host candidates to advertise: the configured public IP(s) (or the - /// bound address if none) paired with the shared socket's actual port. + /// ICE host candidates to advertise: the configured addresses (or the + /// bound address if none). candidates: Vec, + /// The task reading `socket`, which holds it open until aborted. + demux: tokio::task::JoinHandle<()>, +} + +impl Drop for Mux { + fn drop(&mut self) { + // Release the port once the server and every session it accepted are gone. + self.demux.abort(); + } } /// Removes a session's ufrag entry (and sweeps any dead address entries) when @@ -97,24 +107,32 @@ impl Registry { impl Mux { /// Bind the shared socket to `udp_bind` and spawn the demux task. The - /// advertised candidates are `ice_candidates` (each reusing the socket's - /// real port), or the bound address when none are configured. An unspecified - /// bind falls back to loopback for local testing. + /// advertised candidates are `ice_candidates` as given (a port of 0 taking + /// the bound port), or the bound address when none are configured. An + /// unspecified bind falls back to loopback for local testing. pub(crate) async fn bind(udp_bind: SocketAddr, ice_candidates: &[SocketAddr]) -> Result { let socket = Arc::new(UdpSocket::bind(udp_bind).await?); - let candidates = advertised_candidates(ice_candidates, socket.local_addr()?)?; + let local = socket.local_addr()?; + let candidates = advertised_candidates(ice_candidates, local)?; let registry = Arc::new(Mutex::new(Registry::default())); - tokio::spawn(demux(socket.clone(), registry.clone())); + let demux = tokio::spawn(demux(socket.clone(), registry.clone())); - tracing::info!(?candidates, bound = %socket.local_addr()?, "webrtc media mux listening"); + tracing::info!(?candidates, bound = %local, "webrtc media mux listening"); Ok(Self { socket, + local, registry, candidates, + demux, }) } + /// The address the shared socket is bound to. + pub(crate) fn local_addr(&self) -> SocketAddr { + self.local + } + /// Mint ICE credentials for a new session and register its inbox. Returns /// the credentials (set on the session's [`Rtc`](str0m::Rtc) so the demux's /// ufrag lookup matches), the inbox receiver the session reads from, and a @@ -291,7 +309,7 @@ mod tests { SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 0), ]; let mux = Mux::bind(bind, &advertise).await.expect("dual-stack bind"); - let port = mux.socket.local_addr().unwrap().port(); + let port = mux.local_addr().port(); let (creds, mut rx, registration) = mux.register(); // Dial the mux over IPv4, which a dual-stack socket accepts as v4-mapped. diff --git a/rs/moq-webrtc/src/server/whep.rs b/rs/moq-webrtc/src/server/whep.rs index aa1477ecffc..dea1c9d3bd5 100644 --- a/rs/moq-webrtc/src/server/whep.rs +++ b/rs/moq-webrtc/src/server/whep.rs @@ -170,7 +170,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { // CodecConfig before accept_offer so the answer intersects the peer's offer // with what the catalog actually has, instead of agreeing to a codec we can't // fulfil; set the mux's known ICE credentials on the same config. - let mux = server.mux().await?; + let mux = server.mux(); let (creds, inbound, registration) = mux.register(); let mut rtc = session::rtc_config_with_codecs(&codecs)? .set_local_ice_credentials(creds) @@ -343,7 +343,10 @@ mod tests { .expect("create broadcast"); let (sub_origin, _connection, accept) = lazy_client(pub_origin).await; - let _router = super::router(crate::server::Server::new(Default::default()), sub_origin.consume()); + let server = crate::server::Server::bind("127.0.0.1:0".parse().unwrap(), Default::default()) + .await + .unwrap(); + let _router = super::router(server, sub_origin.consume()); let missing = kio::clock::timeout(TIMEOUT, sub_origin.consume().request("missing", None)) .await .expect("sync timed out"); diff --git a/rs/moq-webrtc/src/server/whip.rs b/rs/moq-webrtc/src/server/whip.rs index 4d4cca99f3b..39cda0b218c 100644 --- a/rs/moq-webrtc/src/server/whip.rs +++ b/rs/moq-webrtc/src/server/whip.rs @@ -172,7 +172,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { // Register a session on the shared media mux: known ICE credentials (so the // demux routes this peer's STUN by ufrag), an inbox to read datagrams from, // and a guard the session task holds for its lifetime (unregisters on exit). - let mux = server.mux().await?; + let mux = server.mux(); let (creds, inbound, registration) = mux.register(); let mut rtc = session::rtc_config()? .set_local_ice_credentials(creds) @@ -266,7 +266,9 @@ mod tests { /// a description str0m still parses, and an uncapped one carries no bandwidth line. #[tokio::test] async fn a_capped_answer_carries_tias() { - let server = Server::new(crate::server::Config::default()); + let server = Server::bind("127.0.0.1:0".parse().unwrap(), crate::server::Config::default()) + .await + .unwrap(); let origin = moq_tokio::origin::spawn(); let cap = moq_net::bandwidth::Cap::new(moq_net::bandwidth::Rate::from_mbps(1)); let offer = offer(); @@ -282,12 +284,37 @@ mod tests { assert!(!uncapped.answer.contains("\r\nb="), "{}", uncapped.answer); } + /// An advertised address reaches the answer as given, its port included, so a NAT can + /// forward another public port to the bound one; a port of 0 takes the bound port. + #[tokio::test] + async fn an_advertised_candidate_keeps_its_port() { + let config = crate::server::Config { + ice_candidates: vec!["203.0.113.1:5000".parse().unwrap(), "[2001:db8::1]:0".parse().unwrap()], + }; + let server = Server::bind("127.0.0.1:0".parse().unwrap(), config).await.unwrap(); + let bound = server.local_addr().port(); + let origin = moq_tokio::origin::spawn(); + let offer = offer(); + let path = moq_net::Path::from_static("live/nat"); + let response = accept(&server, Request::new(&origin, path, &offer)).await.unwrap(); + + let hosts: Vec<_> = response + .answer + .lines() + .filter(|line| line.starts_with("a=candidate:")) + .map(|line| line.split(' ').skip(4).take(2).collect::>().join(" ")) + .collect(); + assert_eq!(hosts, ["203.0.113.1 5000".to_string(), format!("2001:db8::1 {bound}")]); + } + /// A session that ends without a DELETE, here one that never connects, ends its tracks /// with the transport cause, so a reader sees the publisher go rather than a producer /// dropped unfinished. #[tokio::test(start_paused = true)] async fn a_session_ending_without_a_delete_ends_its_tracks() { - let server = Server::new(crate::server::Config::default()); + let server = Server::bind("127.0.0.1:0".parse().unwrap(), crate::server::Config::default()) + .await + .unwrap(); let origin = moq_tokio::origin::spawn(); let consumer = origin.consume(); let session = accept( @@ -321,7 +348,9 @@ mod tests { /// it leaves. #[tokio::test] async fn a_reconnect_replaces_the_stale_session() { - let server = Server::new(crate::server::Config::default()); + let server = Server::bind("127.0.0.1:0".parse().unwrap(), crate::server::Config::default()) + .await + .unwrap(); let origin = moq_tokio::origin::spawn(); let consumer = origin.consume(); let _stale_session = accept( diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index d528b60ef2b..7d2df1489a3 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -685,19 +685,18 @@ pub fn rtc_with_codecs(codecs: &[str0m::format::Codec]) -> Result { } /// Bind an ephemeral UDP socket for a single client session, read by its own -/// [`crate::ice::reader`], with the ICE candidates to advertise. +/// [`crate::ice::reader`], advertising the bound address (loopback when it is +/// unspecified). /// /// The client paths are 1:1 (one socket per dialed session, no demux); the -/// server paths share one socket via `crate::server::mux` instead. `advertise` -/// IPs are used verbatim (reusing the bound port); empty falls back to the -/// bound address, substituting loopback when that address is unspecified. -pub async fn bind_udp(advertise: &[SocketAddr]) -> Result { +/// server paths share one socket via `crate::server::mux` instead. +pub async fn bind_udp() -> Result { let udp = Arc::new(UdpSocket::bind(("0.0.0.0", 0)).await?); - let locals = advertised_candidates(advertise, udp.local_addr()?)?; + let locals = advertised_candidates(&[], udp.local_addr()?)?; Ok(crate::ice::Socket::new(udp.clone(), locals, crate::ice::reader(udp))?) } -/// Pair configured ICE candidates with the bound UDP port and validate them. +/// The ICE host candidates to advertise for a socket bound at `local`, validated. pub(crate) fn advertised_candidates(advertise: &[SocketAddr], local: SocketAddr) -> Result> { let port = local.port(); let candidates = if advertise.is_empty() { @@ -713,9 +712,15 @@ pub(crate) fn advertised_candidates(advertise: &[SocketAddr], local: SocketAddr) } vec![candidate] } else { - // Reuse the bound port across each advertised IP, since str0m's ICE agent - // picks the destination port from the candidate it's pairing against. - advertise.iter().map(|addr| SocketAddr::new(addr.ip(), port)).collect() + // Sent as given: a NAT or load balancer may forward another public port to + // the bound one. Port 0 asks for the bound port. + advertise + .iter() + .map(|addr| match addr.port() { + 0 => SocketAddr::new(addr.ip(), port), + _ => *addr, + }) + .collect() }; for addr in &candidates { @@ -802,17 +807,6 @@ mod tests { assert_eq!(advertised_candidates(&[], local).unwrap(), vec![local]); } - #[test] - fn advertised_candidates_reuse_bound_port_for_configured_addresses() { - let local: SocketAddr = "0.0.0.0:4444".parse().unwrap(); - let advertised = vec!["127.0.0.1:1000".parse().unwrap(), "[::1]:2000".parse().unwrap()]; - - assert_eq!( - advertised_candidates(&advertised, local).unwrap(), - vec!["127.0.0.1:4444".parse().unwrap(), "[::1]:4444".parse().unwrap()] - ); - } - #[test] fn advertised_candidates_reject_configured_unspecified_addresses() { let local: SocketAddr = "127.0.0.1:4444".parse().unwrap();