Skip to main content

syncspin_client/discovery/
mdns.rs

1//! The `mdns-sd` backend for [`Discovery`](super::Discovery).
2//!
3//! It is the one place in this crate that opens a socket for discovery: [`MdnsDiscovery::new`]
4//! starts the library's daemon thread, [`advertise`](Discovery::advertise) publishes a record and
5//! [`browse`](Discovery::browse) joins the multicast group for one bounded window. No protocol
6//! code reaches this module; it implements the same trait a fake does, so the tests can drive the
7//! session without multicast.
8//!
9//! The records are the spec's: a client publishes `_sendspin._tcp` with the `path` and `name` TXT
10//! records, a server publishes `_sendspin-server._tcp` with the same keys. Addresses are the
11//! daemon's own: the host record is a process-scoped name and the library fills in the interface
12//! addresses, so no hostname of this machine is written into the source.
13//!
14//! A record that resolves to loopback or an unspecified address is dropped rather than offered to
15//! the caller: the specification says a peer SHOULD only connect to an address that is neither.
16
17use std::collections::HashMap;
18use std::fmt;
19use std::sync::Mutex;
20use std::time::{Duration, Instant};
21
22use anyhow::{Context, Result};
23use mdns_sd::{
24    Receiver, RecvTimeoutError, ResolvedService, ServiceDaemon, ServiceEvent, ServiceInfo,
25};
26
27use super::{DiscoveredServer, Discovery, ServiceAdvertisement};
28
29/// How long one [`Discovery::browse`] waits for resolved records.
30///
31/// mDNS is asynchronous; a browse that returned at once would report only what a previous query
32/// had already cached. One second is long enough for a local answer and short enough to call from
33/// a caller that expects a list.
34const BROWSE_WINDOW: Duration = Duration::from_secs(1);
35
36/// The mDNS implementation of [`Discovery`].
37///
38/// One daemon serves both directions. A host creates it once, passes it to
39/// [`ClientConfig::inbound`](crate::ClientConfig::inbound) or to
40/// [`discover_servers`](super::discover_servers), and keeps it alive for as long as discovery
41/// should work: dropping it shuts the daemon down.
42pub struct MdnsDiscovery {
43    /// The library's daemon, cloned into every call that talks to it.
44    daemon: ServiceDaemon,
45    /// Full names of the records this handle published, keyed by service type.
46    registered: Mutex<HashMap<String, String>>,
47}
48
49impl MdnsDiscovery {
50    /// Starts the mDNS daemon.
51    ///
52    /// # Errors
53    /// Returns an error when the daemon cannot create its sockets. A build that does not use
54    /// discovery never calls this.
55    pub fn new() -> Result<MdnsDiscovery> {
56        let daemon = ServiceDaemon::new().context("failed to start the mDNS daemon")?;
57        Ok(MdnsDiscovery {
58            daemon,
59            registered: Mutex::new(HashMap::new()),
60        })
61    }
62}
63
64impl fmt::Debug for MdnsDiscovery {
65    /// Names the backend without reaching into the daemon.
66    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67        formatter
68            .debug_struct("MdnsDiscovery")
69            .field("registered", &self.registered)
70            .finish_non_exhaustive()
71    }
72}
73
74impl Drop for MdnsDiscovery {
75    /// Ends the daemon thread; a dropped backend must not keep a multicast socket open.
76    fn drop(&mut self) {
77        let _ = self.daemon.shutdown();
78    }
79}
80
81impl Discovery for MdnsDiscovery {
82    fn advertise(&self, service: ServiceAdvertisement) -> Result<()> {
83        let info = service_info(&service)?;
84        let fullname = info.get_fullname().to_owned();
85        self.daemon
86            .register(info)
87            .with_context(|| format!("failed to publish {}", service.service_type))?;
88        let previous = self
89            .registered
90            .lock()
91            .unwrap_or_else(|error| error.into_inner())
92            .insert(service.service_type.clone(), fullname);
93        // One record per service type: publishing a second one under the same type would leave
94        // the first pointing at an endpoint that may no longer exist.
95        if let Some(previous) = previous {
96            let _ = self.daemon.unregister(&previous);
97        }
98        Ok(())
99    }
100
101    fn withdraw(&self, service_type: &str) -> Result<()> {
102        let fullname = self
103            .registered
104            .lock()
105            .unwrap_or_else(|error| error.into_inner())
106            .remove(service_type);
107        if let Some(fullname) = fullname {
108            self.daemon
109                .unregister(&fullname)
110                .with_context(|| format!("failed to withdraw {service_type}"))?;
111        }
112        Ok(())
113    }
114
115    fn browse(&self, service_type: &str) -> Result<Vec<DiscoveredServer>> {
116        let receiver = self
117            .daemon
118            .browse(service_type)
119            .with_context(|| format!("failed to browse {service_type}"))?;
120        let servers = collect(&receiver, BROWSE_WINDOW);
121        // The query is per call; leaving it running would keep the daemon answering a browse the
122        // caller no longer collects.
123        let _ = self.daemon.stop_browse(service_type);
124        Ok(servers)
125    }
126}
127
128/// Collects the resolved records that arrive within `window`.
129fn collect(receiver: &Receiver<ServiceEvent>, window: Duration) -> Vec<DiscoveredServer> {
130    let deadline = Instant::now() + window;
131    let mut found: Vec<DiscoveredServer> = Vec::new();
132    let mut seen: Vec<String> = Vec::new();
133    loop {
134        let remaining = deadline.saturating_duration_since(Instant::now());
135        if remaining.is_zero() {
136            return found;
137        }
138        match receiver.recv_timeout(remaining) {
139            Ok(ServiceEvent::ServiceResolved(resolved)) => {
140                if let Some(server) = discovered(&resolved) {
141                    if seen.iter().any(|name| name == resolved.get_fullname()) {
142                        continue;
143                    }
144                    seen.push(resolved.get_fullname().to_owned());
145                    found.push(server);
146                }
147            }
148            Ok(_) => {}
149            Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => return found,
150        }
151    }
152}
153
154/// Turns one resolved service into the record the protocol can dial.
155///
156/// The `path` TXT record is required; a record without one, or one that resolves to no address
157/// this peer may use, is not offered at all.
158fn discovered(resolved: &ResolvedService) -> Option<DiscoveredServer> {
159    let path = resolved.get_property_val_str("path")?.to_owned();
160    let name = resolved
161        .get_property_val_str("name")
162        .filter(|name| !name.is_empty())
163        .map(str::to_owned);
164    let mut addresses: Vec<String> = resolved
165        .get_addresses()
166        .iter()
167        .map(mdns_sd::ScopedIp::to_ip_addr)
168        .filter(|address| !address.is_loopback() && !address.is_unspecified())
169        .map(|address| std::net::SocketAddr::new(address, resolved.get_port()).to_string())
170        .collect();
171    addresses.sort();
172    if addresses.is_empty() {
173        return None;
174    }
175    Some(DiscoveredServer {
176        addresses,
177        path,
178        name,
179    })
180}
181
182/// Builds the mDNS record a [`ServiceAdvertisement`] describes.
183///
184/// Pure, so the TXT records are testable without a daemon or a socket.
185fn service_info(service: &ServiceAdvertisement) -> Result<ServiceInfo> {
186    let instance = service
187        .name
188        .as_deref()
189        .filter(|name| !name.is_empty())
190        .unwrap_or("Sendspin");
191    let mut properties = HashMap::new();
192    properties.insert("path".to_owned(), service.path.clone());
193    if let Some(name) = &service.name {
194        properties.insert("name".to_owned(), name.clone());
195    }
196    // The host record is process-scoped, so two instances on one machine do not merge their
197    // address sets, and no hostname from this machine enters the source or a log.
198    let host = format!("sendspin-{}.local.", std::process::id());
199    let info = ServiceInfo::new(
200        &service.service_type,
201        instance,
202        &host,
203        "",
204        service.port,
205        properties,
206    )
207    .with_context(|| format!("failed to build the record for {}", service.service_type))?;
208    Ok(info.enable_addr_auto())
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use crate::{CLIENT_SERVICE_TYPE, DEFAULT_SENDSPIN_PATH, SERVER_SERVICE_TYPE};
215
216    /// The client record carries the service type, port, path and name, without a socket.
217    #[test]
218    fn a_client_record_has_the_service_the_port_the_path_and_the_name() {
219        let record = ServiceAdvertisement::client(8928, DEFAULT_SENDSPIN_PATH, "A player");
220        let info = service_info(&record).expect("the record is valid");
221        assert_eq!(info.get_type(), CLIENT_SERVICE_TYPE);
222        assert_eq!(info.get_port(), 8928);
223        assert_eq!(
224            info.get_property_val_str("path"),
225            Some(DEFAULT_SENDSPIN_PATH),
226            "the path TXT record is required"
227        );
228        assert_eq!(
229            info.get_property_val_str("name"),
230            Some("A player"),
231            "the name TXT record repeats the player name"
232        );
233        assert!(info.is_addr_auto(), "the addresses come from the host");
234    }
235
236    /// A record with no name still publishes the path and uses an instance name.
237    #[test]
238    fn a_record_without_a_name_keeps_the_required_path_record() {
239        let record = ServiceAdvertisement {
240            service_type: SERVER_SERVICE_TYPE.to_owned(),
241            port: 8927,
242            path: "/sendspin".to_owned(),
243            name: None,
244        };
245        let info = service_info(&record).expect("the record is valid");
246        assert_eq!(info.get_type(), SERVER_SERVICE_TYPE);
247        assert_eq!(info.get_property_val_str("path"), Some("/sendspin"));
248        assert_eq!(
249            info.get_property_val_str("name"),
250            None,
251            "an optional TXT record is absent, not empty"
252        );
253        assert!(
254            !info.get_fullname().starts_with('.'),
255            "an unnamed record still gets an instance name"
256        );
257    }
258}