Skip to main content

rtci_ice/mdns/
mod.rs

1pub mod exposure;
2#[cfg(test)]
3mod mdns_exposure_test;
4#[cfg(test)]
5mod mdns_local_name_test;
6#[cfg(test)]
7mod mdns_name_test;
8#[cfg(test)]
9mod mdns_test;
10
11pub use exposure::is_global_unicast;
12use mdns::Mdns;
13use mdns::MdnsConfig;
14/// The limit on mDNS messages one or several agents share (`AgentConfig::multicast_dns_rate_limit`).
15pub use mdns::MdnsRateLimit;
16use std::net::IpAddr;
17use std::time::{Duration, Instant};
18use uuid::Uuid;
19
20use shared::error::Result;
21
22/// Represents the different Multicast modes that ICE can run.
23#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
24#[non_exhaustive]
25pub enum MulticastDnsMode {
26    /// Means remote mDNS candidates will be discarded, and local host candidates will use IPs.
27    /// No mDNS message is sent: the mode for an application that wants no mDNS traffic.
28    Disabled,
29
30    /// Means remote mDNS candidates will be accepted, and local host candidates will use IPs.
31    /// The default (draft-ietf-mmusic-mdns-ice-candidates Section 3.2.1 step 3: "Otherwise,
32    /// resolve the candidate using mDNS"): a remote `<uuid>.local` name is queried, and one
33    /// that does not resolve is ignored when its query ends (step 5), logged at debug.
34    #[default]
35    QueryOnly,
36
37    /// Means remote mDNS candidates will be accepted, and local host candidates will use mDNS:
38    /// with `multicast_dns_local_ip` set, the candidates on that IPv4 address are published
39    /// under `multicast_dns_local_name`; without it, every local address (IPv4 and IPv6) under
40    /// a `<uuid>.local` name of its own, as browsers do.
41    QueryAndGather,
42}
43
44/// Whether the application can send the agent's mDNS messages, per address family: an mDNS
45/// socket of that family is open (the agent writes its announcements and answers from port
46/// 5353 to 224.0.0.251 or ff02::fb). Both by default. An application that has none for a
47/// family tells the agent ([`Agent::set_multicast_dns_publishing`](crate::Agent::set_multicast_dns_publishing))
48/// before it adds the host candidates of that family: a name of such an address cannot be
49/// registered on the network (draft-ietf-mmusic-mdns-ice-candidates Section 3.1.1 step 4),
50/// and [`AgentConfig::multicast_dns_fail_closed`](crate::agent::agent_config::AgentConfig::multicast_dns_fail_closed)
51/// says what its candidates become.
52#[derive(Debug, Copy, Clone, PartialEq, Eq)]
53pub struct MulticastDnsPublishing {
54    /// mDNS can be sent over IPv4.
55    pub ipv4: bool,
56    /// mDNS can be sent over IPv6.
57    pub ipv6: bool,
58}
59
60impl Default for MulticastDnsPublishing {
61    fn default() -> Self {
62        Self {
63            ipv4: true,
64            ipv6: true,
65        }
66    }
67}
68
69impl MulticastDnsPublishing {
70    /// Whether a name of `ip` can be published.
71    pub fn covers(&self, ip: IpAddr) -> bool {
72        if ip.is_ipv4() { self.ipv4 } else { self.ipv6 }
73    }
74}
75
76pub(crate) fn generate_multicast_dns_name() -> String {
77    // https://tools.ietf.org/id/draft-ietf-rtcweb-mdns-ice-candidates-02.html#gathering
78    // The unique name MUST consist of a version 4 UUID as defined in [RFC4122], followed by “.local”.
79    // This is a short-lived privacy alias, not a credential. `Uuid::new_v4` obtains randomness
80    // from the UUID crate's secure random source without forcing provider ownership into mDNS.
81    let u = Uuid::new_v4();
82    format!("{u}.local")
83}
84
85/// Whether `name` is an ICE mDNS candidate name: a UUID in its hyphenated form followed by
86/// `.local` (draft-ietf-mmusic-mdns-ice-candidates §3.1.1: "The unique name MUST consist of a
87/// version 4 UUID as defined in [RFC4122], followed by \".local\""). The version nibble is not
88/// checked, and either case is accepted.
89///
90/// A remote candidate's name is resolved only when it has this shape, so a remote description
91/// cannot make the agent look up arbitrary names on the local network (`printer.local`, or the
92/// bare `.local`).
93pub(crate) fn is_ice_mdns_name(name: &str) -> bool {
94    let Some(label) = name.strip_suffix(".local") else {
95        return false;
96    };
97    let bytes = label.as_bytes();
98    bytes.len() == 36
99        && bytes.iter().enumerate().all(|(i, b)| match i {
100            8 | 13 | 18 | 23 => *b == b'-',
101            _ => b.is_ascii_hexdigit(),
102        })
103}
104
105/// Whether `name` can be published as this agent's own mDNS name: exactly one label before
106/// `.local` (RFC 6762 §3: names in the `.local.` domain), the label 1 to 63 letters, digits or
107/// hyphens, not starting or ending with a hyphen (RFC 1123 §2.1). The bare `.local` has an
108/// empty label and is the domain itself, not a host name.
109pub(crate) fn is_valid_local_mdns_name(name: &str) -> bool {
110    let Some(label) = name.strip_suffix(".local") else {
111        return false;
112    };
113    !label.is_empty()
114        && label.len() <= 63
115        && !label.starts_with('-')
116        && !label.ends_with('-')
117        && label
118            .bytes()
119            .all(|b| b.is_ascii_alphanumeric() || b == b'-')
120}
121
122/// What the agent's configuration says about its mDNS connection beyond names and addresses.
123#[derive(Default, Clone)]
124pub(crate) struct MdnsOptions {
125    /// RFC 6762 Section 5.2: the first query of a series waits 20 to 120 ms.
126    pub(crate) first_query_delay: bool,
127    /// RFC 6762 Section 6.3: answers to a multi-question query wait 20 to 120 ms.
128    pub(crate) multi_question_delay: bool,
129    /// The driver reports each datagram's destination address.
130    pub(crate) destination_reported: bool,
131    /// The first query asks for a unicast response (QU).
132    pub(crate) unicast_response: bool,
133    /// A message limit shared with other connections.
134    pub(crate) rate_limit: Option<mdns::MdnsRateLimit>,
135}
136
137pub(crate) fn create_multicast_dns(
138    now: Instant,
139    mdns_mode: MulticastDnsMode,
140    mdns_local_name: &str,
141    mdns_local_ip: &Option<IpAddr>,
142    mdns_query_timeout: &Option<Duration>,
143    options: MdnsOptions,
144) -> Result<Option<Mdns>> {
145    if mdns_mode == MulticastDnsMode::Disabled {
146        return Ok(None);
147    }
148
149    // With a fixed local IP, its one name answers with it. Without one, each local address is
150    // published under a name of its own as its host candidates are added
151    // (`Mdns::add_local_name`), so the responder starts with none.
152    let mut config = match (mdns_mode, mdns_local_ip) {
153        (MulticastDnsMode::QueryAndGather, Some(local_ip)) => {
154            log::info!("mDNS is using {local_ip} as local ip");
155            MdnsConfig::new()
156                .with_local_names(vec![mdns_local_name.to_owned()])
157                .with_local_ip(*local_ip)
158        }
159        _ => MdnsConfig::new(),
160    };
161
162    if let Some(query_timeout) = mdns_query_timeout {
163        config = config.with_query_timeout(*query_timeout);
164    }
165    config = config
166        .with_first_query_delay(options.first_query_delay)
167        .with_multi_question_delay(options.multi_question_delay)
168        .with_destination_reported(options.destination_reported)
169        .with_unicast_response(options.unicast_response);
170    if let Some(rate_limit) = options.rate_limit {
171        config = config.with_rate_limit(rate_limit);
172    }
173
174    let mdns_server = Mdns::new(now, config);
175
176    Ok(Some(mdns_server))
177}