Resolve mDNS host candidates
Browsers and other libwebrtc builds hide their host addresses behind mDNS names (<uuid>.local) unless they have camera or microphone permission; the official client may do the same. str0m takes only IP addresses, so such candidates were dropped (in the SDP silently, trickled with a debug line), and a LAN connection worked only if the hiding side happened to start the checks. Candidates with an mDNS name, in a remote offer or answer or trickled, are now resolved in the background by a multicast DNS query (voelin_stream::mdns) and added as plain candidates; ICE takes whichever pair works. The query goes out from port 5353, shared with the system's responder, because Chromium's responder ignores queries from other ports (tried: none answered from an ephemeral port, every one from 5353); where 5353 cannot be shared it goes out from a port of our own. browser_mdns_candidates_connect runs headless Chromium with the names on and keeps our candidates from it, so it cannot start the checks: both as streamer and as viewer the connection comes up and the media flows (with resolution switched off for a control run it timed out). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ad7267e60e
commit
cbaaab1957
6 files changed
+292
-12
No files matched your search
@@ -14,6 +14,7 @@ pub mod dtls;
|
||||
pub mod feedback;
|
||||
pub mod h264;
|
||||
pub mod layer;
|
||||
pub mod mdns;
|
||||
pub mod peer;
|
||||
pub mod proto;
|
||||
pub mod session;
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Host candidates behind mDNS names (`<uuid>.local`): browsers and other
|
||||
//! libwebrtc builds hide their host addresses this way, and str0m takes
|
||||
//! only IP addresses. [`resolve`] asks with a multicast DNS query
|
||||
//! (RFC 6762) for the name's IPv4 address.
|
||||
//!
|
||||
//! The query goes out from port 5353, shared with the system's responder
|
||||
//! (`SO_REUSEADDR`), and the answer is read from the multicast group:
|
||||
//! Chromium's responder answers only such queries, not "legacy" ones from
|
||||
//! another port (checked against Chromium 152). Where 5353 cannot be
|
||||
//! shared, the query goes out from a port of our own, which responders
|
||||
//! that follow RFC 6762 answer directly.
|
||||
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::time::Duration;
|
||||
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::time::Instant;
|
||||
|
||||
const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 0, 251);
|
||||
const PORT: u16 = 5353;
|
||||
|
||||
/// The mDNS name of a candidate line (`candidate:...`, `a=` prefix
|
||||
/// optional), if its address is one.
|
||||
pub fn candidate_name(line: &str) -> Option<&str> {
|
||||
let line = line.trim();
|
||||
if !line.trim_start_matches("a=").starts_with("candidate:") {
|
||||
return None;
|
||||
}
|
||||
let address = line.split_whitespace().nth(4)?;
|
||||
address.to_ascii_lowercase().ends_with(".local").then_some(address)
|
||||
}
|
||||
|
||||
/// The IPv4 address of `name` (`<uuid>.local`), asked on the local network
|
||||
/// for up to `timeout`; `None` if nobody answered.
|
||||
pub async fn resolve(name: &str, timeout: Duration) -> Option<Ipv4Addr> {
|
||||
let query = query(name)?;
|
||||
let socket = multicast_socket(PORT).or_else(|_| multicast_socket(0)).ok()?;
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut buf = vec![0; 1500];
|
||||
// Asked again after 0.5 s and 1.5 s: a first query may go unanswered.
|
||||
let mut again = [Duration::from_millis(500), Duration::from_secs(1)].into_iter();
|
||||
loop {
|
||||
socket.send_to(&query, (GROUP, PORT)).await.ok()?;
|
||||
let wait = again.next().map_or(deadline, |d| (Instant::now() + d).min(deadline));
|
||||
while let Ok(received) = tokio::time::timeout_at(wait, socket.recv_from(&mut buf)).await {
|
||||
let (n, _) = received.ok()?;
|
||||
if let Some(ip) = answer(&buf[..n], name) {
|
||||
return Some(ip);
|
||||
}
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A UDP socket on `port` (shared) that receives the mDNS group.
|
||||
fn multicast_socket(port: u16) -> std::io::Result<UdpSocket> {
|
||||
let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
|
||||
socket.set_reuse_address(true)?;
|
||||
socket.set_nonblocking(true)?;
|
||||
socket.bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, port)).into())?;
|
||||
socket.join_multicast_v4(&GROUP, &Ipv4Addr::UNSPECIFIED)?;
|
||||
socket.set_multicast_ttl_v4(255)?;
|
||||
UdpSocket::from_std(socket.into())
|
||||
}
|
||||
|
||||
/// A query for the A record of `name`; `None` for a name DNS cannot carry.
|
||||
fn query(name: &str) -> Option<Vec<u8>> {
|
||||
// Id 0, no flags, one question.
|
||||
let mut packet = vec![0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0];
|
||||
for label in name.trim_end_matches('.').split('.') {
|
||||
let len = u8::try_from(label.len()).ok().filter(|l| (1..64).contains(l))?;
|
||||
packet.push(len);
|
||||
packet.extend_from_slice(label.as_bytes());
|
||||
}
|
||||
// Root, type A, class IN.
|
||||
packet.extend_from_slice(&[0, 0, 1, 0, 1]);
|
||||
Some(packet)
|
||||
}
|
||||
|
||||
/// The address an mDNS response gives `name` (an A record in any
|
||||
/// section), if it does.
|
||||
fn answer(packet: &[u8], name: &str) -> Option<Ipv4Addr> {
|
||||
let u16_at = |at: usize| Some(u16::from_be_bytes([*packet.get(at)?, *packet.get(at + 1)?]));
|
||||
// A response.
|
||||
if packet.get(2)? & 0x80 == 0 {
|
||||
return None;
|
||||
}
|
||||
let questions = u16_at(4)?;
|
||||
let records = u16_at(6)? as usize + u16_at(8)? as usize + u16_at(10)? as usize;
|
||||
let mut at = 12;
|
||||
for _ in 0..questions {
|
||||
at = read_name(packet, at)?.1 + 4;
|
||||
}
|
||||
for _ in 0..records {
|
||||
let (owner, end) = read_name(packet, at)?;
|
||||
let (kind, len) = (u16_at(end)?, usize::from(u16_at(end + 8)?));
|
||||
let data = packet.get(end + 10..end + 10 + len)?;
|
||||
if kind == 1 && len == 4 && owner.eq_ignore_ascii_case(name.trim_end_matches('.')) {
|
||||
return Some(Ipv4Addr::new(data[0], data[1], data[2], data[3]));
|
||||
}
|
||||
at = end + 10 + len;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The (dotted) name at `at`, following compression pointers, and where
|
||||
/// the record goes on after it.
|
||||
fn read_name(packet: &[u8], mut at: usize) -> Option<(String, usize)> {
|
||||
let mut name = String::new();
|
||||
let mut end = None;
|
||||
// Pointers only go back, but a crafted packet could loop.
|
||||
for _ in 0..64 {
|
||||
let len = *packet.get(at)?;
|
||||
match len {
|
||||
0 => return Some((name, end.unwrap_or(at + 1))),
|
||||
_ if len & 0xc0 == 0xc0 => {
|
||||
end.get_or_insert(at + 2);
|
||||
at = usize::from(u16::from_be_bytes([len & 0x3f, *packet.get(at + 1)?]));
|
||||
}
|
||||
_ => {
|
||||
let label = packet.get(at + 1..at + 1 + usize::from(len))?;
|
||||
if !name.is_empty() {
|
||||
name.push('.');
|
||||
}
|
||||
name.push_str(&String::from_utf8_lossy(label));
|
||||
at += 1 + usize::from(len);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_in_candidates() {
|
||||
let line = "a=candidate:2387469048 1 udp 2113937151 6e2d1f23-173c-492f-bfef-16577595fc11.local \
|
||||
39386 typ host generation 0";
|
||||
assert_eq!(candidate_name(line), Some("6e2d1f23-173c-492f-bfef-16577595fc11.local"));
|
||||
assert_eq!(candidate_name("candidate:1 1 udp 2130706431 10.0.0.2 50000 typ host"), None);
|
||||
assert_eq!(candidate_name("a=mid:0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_and_answer() {
|
||||
let name = "abc-1.local";
|
||||
let q = query(name).unwrap();
|
||||
assert_eq!(&q[12..], b"\x05abc-1\x05local\x00\x00\x01\x00\x01");
|
||||
assert_eq!(query(&"x".repeat(64)), None);
|
||||
// A response as Chromium sends it: the question repeated, the A
|
||||
// record with the cache-flush class, its owner a pointer to the
|
||||
// question's name; another record first.
|
||||
let mut r = vec![0, 0, 0x84, 0, 0, 1, 0, 2, 0, 0, 0, 0];
|
||||
r.extend_from_slice(&q[12..]);
|
||||
r.extend_from_slice(b"\xc0\x0c\x00\x10\x80\x01\x00\x00\x00\x78\x00\x02\x01x");
|
||||
r.extend_from_slice(b"\xc0\x0c\x00\x01\x80\x01\x00\x00\x00\x78\x00\x04\xc0\xa8\x01\x07");
|
||||
assert_eq!(answer(&r, "ABC-1.local."), Some(Ipv4Addr::new(192, 168, 1, 7)));
|
||||
assert_eq!(answer(&r, "other.local"), None);
|
||||
// A query is not an answer; truncated or looping packets are none.
|
||||
assert_eq!(answer(&q, name), None);
|
||||
assert_eq!(answer(&r[..r.len() - 2], name), None);
|
||||
let mut looped = r.clone();
|
||||
looped[12] = 0xc0;
|
||||
looped[13] = 12;
|
||||
assert_eq!(answer(&looped, name), None);
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ use tracing::{debug, trace, warn};
|
||||
use crate::dtls::{self, NegotiatedProfile, SrtpProfile};
|
||||
use crate::h264::{self, H264Profile};
|
||||
use crate::layer::LayerSpec;
|
||||
use crate::stun;
|
||||
use crate::{mdns, stun};
|
||||
|
||||
/// Initial bandwidth estimate of a streamer's peer without
|
||||
/// [`OfferOptions::start_bitrate`].
|
||||
@@ -43,6 +43,9 @@ pub const DEFAULT_START_BITRATE: u64 = 1_000_000;
|
||||
/// Socket buffers a peer asks for by default ([`PeerConfig::udp_buffer`]).
|
||||
pub const DEFAULT_UDP_BUFFER: usize = 4 << 20;
|
||||
|
||||
/// How long an mDNS candidate's name is asked for.
|
||||
const MDNS_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
/// How long a connected viewer waits for video by default
|
||||
/// ([`PeerConfig::stall_timeout`]): a streamer sends a keyframe as soon as
|
||||
/// a viewer connects.
|
||||
@@ -444,14 +447,37 @@ impl Peer {
|
||||
codecs.push(*c);
|
||||
}
|
||||
}
|
||||
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
|
||||
let parsed = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
|
||||
let (mut rtc, srtp_profile) = build_rtc(config, &codecs, false, None);
|
||||
let net = Net::bind(config, &mut rtc)?;
|
||||
let answer = rtc.sdp_api().accept_offer(offer)?;
|
||||
let answer = rtc.sdp_api().accept_offer(parsed)?;
|
||||
let peer = Self::spawn(rtc, net, config, None, Vec::new(), srtp_profile);
|
||||
peer.resolve_mdns(offer);
|
||||
Ok((peer, answer.to_sdp_string()))
|
||||
}
|
||||
|
||||
/// Resolve the mDNS names of the candidates in `sdp` (a whole SDP or one
|
||||
/// candidate line) in the background and add them as plain candidates:
|
||||
/// peers that hide their host addresses (browsers, other libwebrtc
|
||||
/// builds) can then still connect on a LAN. ICE takes whichever pair
|
||||
/// works, these or the others.
|
||||
fn resolve_mdns(&self, sdp: &str) {
|
||||
for line in sdp.lines() {
|
||||
let Some(name) = mdns::candidate_name(line) else { continue };
|
||||
let (name, line, cmd) = (name.to_owned(), line.to_owned(), self.cmd.clone());
|
||||
tokio::spawn(async move {
|
||||
match mdns::resolve(&name, MDNS_TIMEOUT).await {
|
||||
Some(ip) => {
|
||||
debug!(name, %ip, "mDNS candidate resolved");
|
||||
let _ =
|
||||
cmd.send(Cmd::RemoteCandidate(line.replace(&name, &ip.to_string())));
|
||||
}
|
||||
None => debug!(name, "mDNS candidate not resolved"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn(
|
||||
rtc: Rtc,
|
||||
net: Net,
|
||||
@@ -483,7 +509,9 @@ impl Peer {
|
||||
pub async fn accept_answer(&self, sdp: &str) -> Result<(), PeerError> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.cmd.send(Cmd::Answer(sdp.to_owned(), tx)).map_err(|_| PeerError::Closed)?;
|
||||
rx.await.map_err(|_| PeerError::Closed)?
|
||||
rx.await.map_err(|_| PeerError::Closed)??;
|
||||
self.resolve_mdns(sdp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Viewer side: answer a new offer of the streamer on this connection
|
||||
@@ -493,12 +521,19 @@ impl Peer {
|
||||
pub async fn renegotiate(&self, offer: &str) -> Result<String, PeerError> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.cmd.send(Cmd::Offer(offer.to_owned(), tx)).map_err(|_| PeerError::Closed)?;
|
||||
rx.await.map_err(|_| PeerError::Closed)?
|
||||
let answer = rx.await.map_err(|_| PeerError::Closed)??;
|
||||
self.resolve_mdns(offer);
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// Add a trickled remote candidate (`candidate:...`, `a=` prefix optional).
|
||||
/// Add a trickled remote candidate (`candidate:...`, `a=` prefix
|
||||
/// optional); one with an mDNS name once it is resolved.
|
||||
pub fn add_remote_candidate(&self, candidate: &str) {
|
||||
let _ = self.cmd.send(Cmd::RemoteCandidate(candidate.to_owned()));
|
||||
if mdns::candidate_name(candidate).is_some() {
|
||||
self.resolve_mdns(candidate);
|
||||
} else {
|
||||
let _ = self.cmd.send(Cmd::RemoteCandidate(candidate.to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Send one encoded frame (streamer). Dropped until connected.
|
||||
|
||||
@@ -315,6 +315,63 @@ async fn browser_renegotiates_with_rust() {
|
||||
browser.quit().await;
|
||||
}
|
||||
|
||||
/// Chromium with its host addresses behind mDNS names (`<uuid>.local`, as
|
||||
/// without camera or microphone permission) and no STUN: the names are
|
||||
/// its only candidates. Our candidates are kept from it, so it cannot
|
||||
/// start the checks itself (and learn our address from them): the
|
||||
/// connection comes up only if our peers resolve its names by a multicast
|
||||
/// DNS query and reach it, as streamer (the names in the browser's answer)
|
||||
/// and as viewer (in its offer). Then the media flows.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn browser_mdns_candidates_connect() {
|
||||
if !enabled() {
|
||||
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
|
||||
return;
|
||||
}
|
||||
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
|
||||
let mut browser = Browser::start_with_mdns().await;
|
||||
let only_mdns = |sdp: &str| {
|
||||
let candidates: Vec<&str> = sdp.lines().filter(|l| l.starts_with("a=candidate:")).collect();
|
||||
!candidates.is_empty() && candidates.iter().all(|l| l.contains(".local "))
|
||||
};
|
||||
let without_candidates = |sdp: &str| -> String {
|
||||
sdp.split_inclusive('\n').filter(|l| !l.starts_with("a=candidate:")).collect()
|
||||
};
|
||||
let config = PeerConfig::loopback();
|
||||
|
||||
// Our streamer, the browser's answer with mDNS names.
|
||||
let (mut peer, offer) = Peer::offer(&config, "mdns").await.unwrap();
|
||||
let offer = without_candidates(&offer);
|
||||
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
|
||||
let answer = answer["sdp"].as_str().unwrap();
|
||||
assert!(only_mdns(answer), "the browser's answer:\n{answer}");
|
||||
peer.accept_answer(answer).await.unwrap();
|
||||
wait_connected(&mut peer).await;
|
||||
let mut source = SyntheticSource::new(30, 3000, false);
|
||||
let mut frames = Vec::new();
|
||||
let end = Instant::now() + Duration::from_secs(2);
|
||||
while Instant::now() < end {
|
||||
source.poll_frames(Instant::now(), &mut frames);
|
||||
for f in frames.drain(..) {
|
||||
peer.write(f.kind, f.time, f.data);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let stats = browser.call(json!({ "op": "stats" })).await;
|
||||
assert!(stats["inbound"]["video"]["framesDecoded"].as_u64().unwrap() > 20, "{stats:#}");
|
||||
|
||||
// The browser streams, its offer with mDNS names; our viewer answers.
|
||||
let offer = browser.call(json!({ "op": "offer", "codec": "VP8", "trickle": false })).await;
|
||||
let offer = offer["sdp"].as_str().unwrap();
|
||||
assert!(only_mdns(offer), "the browser's offer:\n{offer}");
|
||||
let (mut peer, answer) = Peer::answer(&config, offer).await.unwrap();
|
||||
browser.call(json!({ "op": "accept", "sdp": without_candidates(&answer) })).await;
|
||||
wait_connected(&mut peer).await;
|
||||
let received = receive(&mut peer, Duration::from_secs(5), 20).await;
|
||||
assert!(received.video.get(Codec::Vp8) >= 20, "{:?}", received.video);
|
||||
browser.quit().await;
|
||||
}
|
||||
|
||||
/// Our streamer peer to Chromium through a relay that passes the handshake
|
||||
/// and drops SRTP once AES-GCM was selected, as an official viewer whose
|
||||
/// SRTP fails after the handshake: synthetic media for `seconds`; whether
|
||||
|
||||
@@ -190,14 +190,16 @@ window.peer = {
|
||||
`;
|
||||
|
||||
async function main() {
|
||||
const args = ['--autoplay-policy=no-user-gesture-required'];
|
||||
// Real host candidates instead of mDNS names (no getUserMedia permission
|
||||
// here), unless the test is about mDNS names (VOELIN_BROWSER_MDNS=1).
|
||||
if (process.env.VOELIN_BROWSER_MDNS !== '1') {
|
||||
args.push('--disable-features=WebRtcHideLocalIpsWithMdns');
|
||||
}
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.VOELIN_CHROMIUM || undefined,
|
||||
args: [
|
||||
// Real host candidates instead of mDNS names (no getUserMedia permission here).
|
||||
'--disable-features=WebRtcHideLocalIpsWithMdns',
|
||||
'--autoplay-policy=no-user-gesture-required',
|
||||
],
|
||||
args,
|
||||
});
|
||||
const page = await browser.newPage();
|
||||
page.on('console', (m) => process.stderr.write('[page] ' + m.text() + '\n'));
|
||||
|
||||
@@ -25,6 +25,18 @@ pub struct Browser {
|
||||
|
||||
impl Browser {
|
||||
pub async fn start() -> Self {
|
||||
Self::launch(false).await
|
||||
}
|
||||
|
||||
/// A browser that hides its host addresses behind mDNS names
|
||||
/// (`<uuid>.local`), as Chromium does without camera or microphone
|
||||
/// permission.
|
||||
#[allow(dead_code, reason = "not every test uses it")]
|
||||
pub async fn start_with_mdns() -> Self {
|
||||
Self::launch(true).await
|
||||
}
|
||||
|
||||
async fn launch(mdns: bool) -> Self {
|
||||
let script = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../tests/interop/browser-peer.cjs")
|
||||
.canonicalize()
|
||||
@@ -36,6 +48,7 @@ impl Browser {
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.env("VOELIN_BROWSER_MDNS", if mdns { "1" } else { "0" })
|
||||
.kill_on_drop(true);
|
||||
// Playwright is usually installed globally.
|
||||
if std::env::var_os("NODE_PATH").is_none()
|
||||
|
||||
Reference in new issue
Block a user