Skip to main content

smb_server/discovery/
mod.rs

1//! Network discovery: announcing the server over mDNS and DNS-SD, and
2//! to Windows over WS-Discovery.
3
4use std::net::SocketAddr;
5use std::sync::Arc;
6use std::time::Duration;
7
8use async_trait::async_trait;
9use tokio::net::TcpListener;
10use tokio::sync::oneshot;
11use tokio::task::JoinHandle;
12use tracing::{Instrument, debug, info, warn};
13use uuid::Uuid;
14
15use crate::builder::BuildError;
16
17#[cfg(target_os = "linux")]
18mod avahi;
19#[cfg(target_vendor = "apple")]
20mod dns_sd;
21#[cfg(windows)]
22mod dnsapi;
23#[cfg(all(unix, not(target_vendor = "apple")))]
24mod responder;
25pub(crate) mod target;
26#[cfg(unix)]
27pub(crate) mod wsd;
28
29use target::{Scope, WsSkip};
30
31/// Most renames tried in a row when the name is taken.
32#[cfg_attr(any(target_vendor = "apple", not(unix)), allow(dead_code))]
33const MAX_RENAMES: usize = 16;
34
35/// Announces the server on the local network through multicast DNS and
36/// DNS service discovery (RFC 6762, RFC 6763). Clients that browse
37/// DNS-SD, such as the Finder, GNOME Files and Dolphin, list it. Pass it
38/// to [`SmbServerBuilder::discovery`](crate::SmbServerBuilder::discovery).
39///
40/// While [`SmbServer::serve`](crate::SmbServer::serve) runs, the server is
41/// announced as `<name>._smb._tcp.local` with the port it listens on and
42/// an empty TXT record. With a [`model`](Self::model),
43/// `<name>._device-info._tcp.local` carries TXT `model=<model>` as well.
44/// When `serve` stops, the records are withdrawn before it returns,
45/// waiting at most 2 seconds for that.
46///
47/// On Linux, the server registers with Avahi when avahi-daemon is on the
48/// system D-Bus, registers again when avahi-daemon restarts, and moves to
49/// Avahi when avahi-daemon reaches the bus after `serve` started. The SRV
50/// record then points at Avahi's host name, which Avahi announces with
51/// the host's addresses on the interfaces it uses, sending AAAA records
52/// over IPv4 too in its default configuration. The listen address picks
53/// where the service records go: over IPv4 for `0.0.0.0`, over IPv6 for
54/// an IPv6-only `[::]`, over both for a dual-stack `[::]`, and on the
55/// address's interface for any other address. Once the server uses Avahi,
56/// it is not announced while avahi-daemon is gone, until it returns.
57///
58/// Without Avahi, and on Unix systems other than Apple's, the server
59/// answers mDNS queries itself on UDP port 5353. The SRV record points at
60/// `<host>.local`, where `<host>` is the first label of the host name,
61/// announced with the addresses the listener accepts connections on: IPv4
62/// for `0.0.0.0`; IPv6 for `[::]`, and IPv4 too when that socket also
63/// accepts IPv4; the one address for any other listen address. Loopback,
64/// point-to-point and down interfaces are left out. A name that contains a
65/// dot is not announced. When another program holds UDP port 5353, the
66/// server is not announced.
67///
68/// On Apple platforms, the server registers with mDNSResponder, which
69/// renames it on a conflict and withdraws the records when the server
70/// stops or exits. The SRV record points at the host name, which
71/// mDNSResponder announces with the host's IPv4 and IPv6 addresses,
72/// whatever addresses the listener accepts. A wildcard listen address
73/// registers the service on every interface, any other address on that
74/// address's interface only. When mDNSResponder restarts, the server
75/// registers again.
76///
77/// On Windows, the server registers with the DNS client service, which
78/// picks a new name when the name is taken, and withdraws the records
79/// when the server stops or its process exits. The SRV record points at
80/// the computer's DNS host name, which the DNS client announces with the
81/// host's IPv4 and IPv6 addresses, whatever addresses the listener
82/// accepts; a listen address other than a wildcard registers the service
83/// on that address's interface only. The device-info record carries port
84/// 9. A name that contains a dot is not announced. A restart of the DNS
85/// Client service drops the registration until the server is restarted.
86///
87/// On other platforms nothing is announced over mDNS.
88///
89/// On hosts other than Windows, a server listening on port 445 is also
90/// announced to Windows, which lists computers in its Network folder
91/// through WS-Discovery and opens them on port 445. The server answers
92/// probes on UDP port 3702, sends Hello when it starts or gains an address
93/// and Bye when it stops, and serves its metadata over HTTP on TCP port
94/// 5357, or on a free port, with a warning, when another program has 5357.
95/// Windows lists it under its NetBIOS name, in workgroup
96/// [`workgroup`](Self::workgroup), and opens it by resolving that name, so
97/// the server is announced to Windows only when its NetBIOS name is the
98/// first label of the host name, ignoring case; otherwise a warning says to
99/// set [`netbios_name`](crate::SmbServerBuilder::netbios_name) to the host
100/// name. The NetBIOS name must also be 1 to 15 characters without control
101/// characters or any of `"/\[]:|<>+=;,?*`. Listen on `[::]:445`: Windows
102/// may resolve the name to an IPv6 address too and then connect over IPv6
103/// alone, so it lists a server that listens on IPv4 only but cannot open
104/// it, and such a server logs a warning. The server answers on each
105/// interface that is up, has an address the listener accepts, and is not
106/// loopback, point-to-point, a VPN tunnel
107/// (`tun*`, `utun*`, `wg*`), a container network (`docker*`, `br-*`,
108/// `veth*`, `cni*`, `flannel*`, `cali*`) or one of Apple's peer-to-peer
109/// links (`awdl*`, `llw*`, `anpi*`). It answers senders with a link-local
110/// address or an address on one of that interface's networks, and follows
111/// interface changes within 5 seconds. Its endpoint address is derived
112/// from [`server_guid`](crate::SmbServerBuilder::server_guid) when that is
113/// set, otherwise from the host name and the NetBIOS name, and from the
114/// port, so it stays the same across restarts. On macOS, run the server as
115/// root for WS-Discovery: as a non-root user, macOS may refuse to send its
116/// messages, which is logged as a warning, or not deliver the probes to
117/// it, and Windows then does not list the server. On Windows, which
118/// announces the computer itself, and on other ports, nothing is announced
119/// over WS-Discovery.
120///
121/// Each of these cases, and any failure to announce, is logged; `serve`
122/// runs on either way.
123#[derive(Debug, Clone, Default)]
124#[non_exhaustive]
125pub struct Discovery {
126    name: Option<String>,
127    model: Option<String>,
128    ws_discovery: Option<bool>,
129    workgroup: Option<String>,
130    manufacturer: Option<String>,
131    model_name: Option<String>,
132    firmware_version: Option<String>,
133}
134
135impl Discovery {
136    /// Discovery under the default name, without a model.
137    pub fn new() -> Self {
138        Self::default()
139    }
140
141    /// Instance name: the name file managers list the server under. 1 to
142    /// 63 bytes of UTF-8 without control characters, used as given, so
143    /// pass it in Unicode normalization form C. Defaults to the NetBIOS
144    /// name in upper case. On Apple platforms with neither a name nor a
145    /// model set, the server is registered under the computer name
146    /// instead, and macOS announces the Mac's own model for it. When
147    /// another service on the network has the name, the server is renamed
148    /// with a number added, and the new name is logged. On Windows, and
149    /// with the built-in responder, a name that contains a dot is not
150    /// announced.
151    pub fn name(mut self, name: impl Into<String>) -> Self {
152        self.name = Some(name.into());
153        self
154    }
155
156    /// Model code announced in `<name>._device-info._tcp.local`. The
157    /// Finder picks the icon it shows for the server by this code. 1 to
158    /// 249 printable ASCII characters. Not announced unless set.
159    pub fn model(mut self, model: impl Into<String>) -> Self {
160        self.model = Some(model.into());
161        self
162    }
163
164    /// Whether to announce the server to Windows over WS-Discovery. By
165    /// default it is announced when it listens on port 445 on a host other
166    /// than Windows, and the reason is logged when it is not. With `true`,
167    /// [`build`](crate::SmbServerBuilder::build) fails when the listen
168    /// port is set to one other than 445 or the NetBIOS name is not one
169    /// Windows accepts, and a skipped announcement is logged as a warning.
170    pub fn ws_discovery(mut self, enabled: bool) -> Self {
171        self.ws_discovery = Some(enabled);
172        self
173    }
174
175    /// Workgroup Windows lists the server in. 1 to 15 characters without
176    /// control characters or any of `"/\[]:|<>+=;,?*`, sent in upper
177    /// case. Defaults to `WORKGROUP`.
178    pub fn workgroup(mut self, workgroup: impl Into<String>) -> Self {
179        self.workgroup = Some(workgroup.into());
180        self
181    }
182
183    /// Manufacturer Windows shows in the server's properties. 1 to 255
184    /// characters without control characters. Defaults to `smb-server`.
185    pub fn manufacturer(mut self, manufacturer: impl Into<String>) -> Self {
186        self.manufacturer = Some(manufacturer.into());
187        self
188    }
189
190    /// Model name Windows shows in the server's properties, apart from
191    /// the [`model`](Self::model) code the Finder reads. 1 to 255
192    /// characters without control characters. Defaults to `smb-server`.
193    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
194        self.model_name = Some(model_name.into());
195        self
196    }
197
198    /// Firmware version Windows shows in the server's properties. 1 to
199    /// 255 characters without control characters. Defaults to the version
200    /// of this crate.
201    pub fn firmware_version(mut self, version: impl Into<String>) -> Self {
202        self.firmware_version = Some(version.into());
203        self
204    }
205
206    /// Checks the options against the listen address and fills in the
207    /// defaults.
208    pub(crate) fn settings(
209        self,
210        listen: SocketAddr,
211        netbios_name: &str,
212        server_guid: Option<Uuid>,
213    ) -> Result<Settings, BuildError> {
214        if listen.ip().to_canonical().is_loopback() {
215            return Err(BuildError::DiscoveryOnLoopback(listen));
216        }
217        if self.ws_discovery == Some(true) && !matches!(listen.port(), 0 | target::SMB_PORT) {
218            return Err(BuildError::WsDiscoveryPort(listen.port()));
219        }
220        let default_name = self.name.is_none();
221        let name = self.name.unwrap_or_else(|| netbios_name.to_uppercase());
222        if !target::valid_name(&name) {
223            return Err(BuildError::DiscoveryName(name));
224        }
225        if let Some(model) = self.model.as_ref().filter(|m| !target::valid_model(m)) {
226            return Err(BuildError::DiscoveryModel(model.clone()));
227        }
228        let workgroup = self
229            .workgroup
230            .unwrap_or_else(|| DEFAULT_WORKGROUP.to_string());
231        if !target::valid_netbios_name(&workgroup.to_uppercase()) {
232            return Err(BuildError::DiscoveryWorkgroup(workgroup));
233        }
234        let computer = netbios_name.to_uppercase();
235        if self.ws_discovery == Some(true) && !target::valid_netbios_name(&computer) {
236            return Err(BuildError::WsDiscoveryNetbiosName(netbios_name.to_string()));
237        }
238        let field = |setting: &'static str, value: Option<String>, default: &str| match value {
239            Some(value) if !target::valid_field(&value) => {
240                Err(BuildError::DiscoveryMetadata { setting, value })
241            }
242            value => Ok(value.unwrap_or_else(|| default.to_string())),
243        };
244        let info = DeviceInfo {
245            computer,
246            workgroup: workgroup.to_uppercase(),
247            manufacturer: field("manufacturer", self.manufacturer, env!("CARGO_PKG_NAME"))?,
248            model_name: field("model_name", self.model_name, env!("CARGO_PKG_NAME"))?,
249            firmware_version: field(
250                "firmware_version",
251                self.firmware_version,
252                env!("CARGO_PKG_VERSION"),
253            )?,
254        };
255        Ok(Settings {
256            name,
257            default_name,
258            model: self.model,
259            ws_discovery: self.ws_discovery,
260            server_guid,
261            info,
262        })
263    }
264}
265
266/// Workgroup announced unless set: the name Windows gives a new
267/// workgroup.
268const DEFAULT_WORKGROUP: &str = "WORKGROUP";
269
270/// [`Discovery`] as checked by the builder.
271#[derive(Debug, Clone)]
272pub(crate) struct Settings {
273    pub(crate) name: String,
274    /// `name` is the default, not one set through [`Discovery::name`].
275    pub(crate) default_name: bool,
276    pub(crate) model: Option<String>,
277    /// Set through [`Discovery::ws_discovery`].
278    pub(crate) ws_discovery: Option<bool>,
279    /// Set through [`SmbServerBuilder::server_guid`](crate::SmbServerBuilder::server_guid).
280    pub(crate) server_guid: Option<Uuid>,
281    pub(crate) info: DeviceInfo,
282}
283
284/// What Windows shows for the server, from its WS-Discovery metadata.
285#[derive(Debug, Clone, PartialEq, Eq)]
286#[cfg_attr(not(unix), allow(dead_code))]
287pub(crate) struct DeviceInfo {
288    /// NetBIOS name, in upper case.
289    pub(crate) computer: String,
290    /// In upper case.
291    pub(crate) workgroup: String,
292    pub(crate) manufacturer: String,
293    pub(crate) model_name: String,
294    pub(crate) firmware_version: String,
295}
296
297/// The server as a WS-Discovery device.
298#[derive(Debug, Clone, PartialEq, Eq)]
299#[cfg_attr(not(unix), allow(dead_code))]
300pub(crate) struct Device {
301    /// Endpoint address, sent as `urn:uuid:<endpoint>`.
302    pub(crate) endpoint: Uuid,
303    pub(crate) info: DeviceInfo,
304}
305
306/// What a backend announces.
307#[derive(Debug, Clone)]
308#[cfg_attr(any(target_vendor = "apple", not(unix)), allow(dead_code))]
309pub(crate) struct Service {
310    pub(crate) name: String,
311    /// `name` is the default, not one set through [`Discovery::name`].
312    #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
313    pub(crate) default_name: bool,
314    pub(crate) model: Option<String>,
315    pub(crate) port: u16,
316    pub(crate) scope: Scope,
317    /// First label of the host name, the SRV target when the server
318    /// answers mDNS itself.
319    pub(crate) host: String,
320    /// Announced over WS-Discovery when set.
321    pub(crate) device: Option<Device>,
322}
323
324/// Resolves when the backend is to withdraw the service.
325pub(crate) type Stop = oneshot::Receiver<()>;
326
327/// A way to announce the service.
328#[async_trait]
329pub(crate) trait Backend: Send + Sync {
330    /// Announces `service` until `stop` resolves, then withdraws it.
331    /// Returns early when it cannot announce.
332    async fn run(&self, service: Service, stop: Stop);
333}
334
335/// Avahi on Linux when it runs, otherwise the built-in responder where
336/// there is one, and WS-Discovery beside it.
337pub(crate) struct System;
338
339#[async_trait]
340impl Backend for System {
341    async fn run(&self, mut service: Service, stop: Stop) {
342        let device = service.device.take();
343        let scope = service.scope;
344        let (mdns_stop, mdns_stopped) = oneshot::channel();
345        let (wsd_stop, wsd_stopped) = oneshot::channel::<()>();
346        tokio::join!(
347            async move {
348                let _ = stop.await;
349                drop((mdns_stop, wsd_stop));
350            },
351            mdns(service, mdns_stopped),
352            async move {
353                #[cfg(unix)]
354                if let Some(device) = device {
355                    wsd::run(device, scope, wsd_stopped).await;
356                }
357                #[cfg(not(unix))]
358                drop((device, scope, wsd_stopped));
359            },
360        );
361    }
362}
363
364/// Announces `service` over mDNS until `stop` resolves.
365async fn mdns(service: Service, stop: Stop) {
366    #[cfg(target_os = "linux")]
367    if let Some(bus) = avahi::Bus::connect().await {
368        return bus.run(service, stop).await;
369    }
370    #[cfg(all(unix, not(target_vendor = "apple")))]
371    responder::run(service, async {
372        let _ = stop.await;
373        responder::Leave::Withdraw
374    })
375    .await;
376    #[cfg(target_vendor = "apple")]
377    dns_sd::run(service, stop).await;
378    #[cfg(windows)]
379    dnsapi::run(service, stop).await;
380    #[cfg(not(any(unix, windows)))]
381    {
382        drop((service, stop));
383        warn!("network discovery is not supported on this platform; the server is not announced");
384    }
385}
386
387/// Longest wait for a backend to withdraw the service when `serve` stops.
388const STOP_TIMEOUT: Duration = Duration::from_secs(2);
389
390/// A backend announcing the server, from `serve` until [`Announcer::stop`].
391/// Dropping it cancels the backend.
392pub(crate) struct Announcer {
393    stop: Option<oneshot::Sender<()>>,
394    task: JoinHandle<()>,
395}
396
397impl Announcer {
398    /// Starts `backend` on the address `listener` is bound to.
399    pub(crate) fn start(
400        settings: &Settings,
401        listener: &TcpListener,
402        backend: Arc<dyn Backend>,
403    ) -> Option<Self> {
404        let local = match listener.local_addr() {
405            Ok(local) => local,
406            Err(e) => {
407                warn!(error = %e, "no listen address to announce; the server is not announced");
408                return None;
409            }
410        };
411        let v6_only =
412            local.is_ipv6() && socket2::SockRef::from(listener).only_v6().unwrap_or(false);
413        let host = host_label().unwrap_or_else(|| "smbserver".to_string());
414        let service = Service {
415            name: settings.name.clone(),
416            default_name: settings.default_name,
417            model: settings.model.clone(),
418            port: local.port(),
419            scope: Scope::new(local.ip(), v6_only),
420            device: ws_device(
421                settings,
422                local.port(),
423                &host,
424                Scope::new(local.ip(), v6_only),
425            ),
426            host,
427        };
428        let (stop, stopped) = oneshot::channel();
429        let task =
430            tokio::spawn(async move { backend.run(service, stopped).await }.in_current_span());
431        Some(Self {
432            stop: Some(stop),
433            task,
434        })
435    }
436
437    /// Has the backend withdraw the service, and waits for it, at most
438    /// [`STOP_TIMEOUT`].
439    pub(crate) async fn stop(mut self) {
440        self.stop.take();
441        if tokio::time::timeout(STOP_TIMEOUT, &mut self.task)
442            .await
443            .is_err()
444        {
445            warn!(timeout = ?STOP_TIMEOUT, "network discovery did not stop in time");
446        }
447    }
448}
449
450impl Drop for Announcer {
451    fn drop(&mut self) {
452        self.task.abort();
453    }
454}
455
456/// The device to announce over WS-Discovery for a server on `port` on
457/// host `host`, listening on `scope`, or `None`, with the reason logged,
458/// when WS-Discovery does not run.
459pub(crate) fn ws_device(
460    settings: &Settings,
461    port: u16,
462    host: &str,
463    scope: Scope,
464) -> Option<Device> {
465    let computer = &settings.info.computer;
466    let skip =
467        target::ws_discovery_skip(settings.ws_discovery, port, computer, host, cfg!(windows));
468    let reason = match skip {
469        None => {
470            if matches!(scope, Scope::V4 | Scope::Addr(std::net::IpAddr::V4(_))) {
471                warn!(
472                    "the listener accepts IPv4 only: Windows may resolve the server's name to \
473                     an IPv6 address too and then connect over IPv6 alone, so it lists the \
474                     server but cannot open it; listen on [::]:445 instead"
475                );
476            }
477            return Some(Device {
478                endpoint: target::endpoint_uuid(settings.server_guid, host, computer, port),
479                info: settings.info.clone(),
480            });
481        }
482        Some(WsSkip::Off) => {
483            debug!("WS-Discovery is off");
484            return None;
485        }
486        Some(WsSkip::Windows) => "Windows announces the computer itself",
487        Some(WsSkip::Port) => "Windows opens servers it finds that way on port 445 only",
488        Some(WsSkip::Host) => {
489            warn!(
490                name = %computer,
491                %host,
492                "the server is not announced over WS-Discovery: Windows opens it by its NetBIOS \
493                 name, which reaches this host only when it is the host name; set netbios_name \
494                 to the host name"
495            );
496            return None;
497        }
498        Some(WsSkip::Name) => {
499            warn!(
500                name = %computer,
501                "the server is not announced over WS-Discovery: the NetBIOS name must be 1 to 15 \
502                 characters without control characters or any of \"/\\[]:|<>+=;,?*"
503            );
504            return None;
505        }
506    };
507    if settings.ws_discovery == Some(true) {
508        warn!(
509            port,
510            "the server is not announced over WS-Discovery: {reason}"
511        );
512    } else {
513        info!(
514            port,
515            "the server is not announced over WS-Discovery: {reason}"
516        );
517    }
518    None
519}
520
521/// First label of the host name.
522fn host_label() -> Option<String> {
523    let host = crate::builder::host_name()?;
524    let label = host.split('.').next()?;
525    (!label.is_empty()).then(|| label.to_string())
526}