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