use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use tracing::{Instrument, debug, info, warn};
use uuid::Uuid;
use crate::builder::BuildError;
#[cfg(target_os = "linux")]
mod avahi;
#[cfg(target_vendor = "apple")]
mod dns_sd;
#[cfg(windows)]
mod dnsapi;
#[cfg(all(unix, not(target_vendor = "apple")))]
mod responder;
pub(crate) mod target;
#[cfg(unix)]
pub(crate) mod wsd;
use target::{Scope, WsSkip};
#[cfg_attr(any(target_vendor = "apple", not(unix)), allow(dead_code))]
const MAX_RENAMES: usize = 16;
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Discovery {
name: Option<String>,
model: Option<String>,
ws_discovery: Option<bool>,
workgroup: Option<String>,
manufacturer: Option<String>,
model_name: Option<String>,
firmware_version: Option<String>,
}
impl Discovery {
pub fn new() -> Self {
Self::default()
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
pub fn ws_discovery(mut self, enabled: bool) -> Self {
self.ws_discovery = Some(enabled);
self
}
pub fn workgroup(mut self, workgroup: impl Into<String>) -> Self {
self.workgroup = Some(workgroup.into());
self
}
pub fn manufacturer(mut self, manufacturer: impl Into<String>) -> Self {
self.manufacturer = Some(manufacturer.into());
self
}
pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
self.model_name = Some(model_name.into());
self
}
pub fn firmware_version(mut self, version: impl Into<String>) -> Self {
self.firmware_version = Some(version.into());
self
}
pub(crate) fn settings(
self,
listen: SocketAddr,
netbios_name: &str,
server_guid: Option<Uuid>,
) -> Result<Settings, BuildError> {
if listen.ip().to_canonical().is_loopback() {
return Err(BuildError::DiscoveryOnLoopback(listen));
}
if self.ws_discovery == Some(true) && !matches!(listen.port(), 0 | target::SMB_PORT) {
return Err(BuildError::WsDiscoveryPort(listen.port()));
}
let default_name = self.name.is_none();
let name = self.name.unwrap_or_else(|| netbios_name.to_uppercase());
if !target::valid_name(&name) {
return Err(BuildError::DiscoveryName(name));
}
if let Some(model) = self.model.as_ref().filter(|m| !target::valid_model(m)) {
return Err(BuildError::DiscoveryModel(model.clone()));
}
let workgroup = self
.workgroup
.unwrap_or_else(|| DEFAULT_WORKGROUP.to_string());
if !target::valid_netbios_name(&workgroup.to_uppercase()) {
return Err(BuildError::DiscoveryWorkgroup(workgroup));
}
let computer = netbios_name.to_uppercase();
if self.ws_discovery == Some(true) && !target::valid_netbios_name(&computer) {
return Err(BuildError::WsDiscoveryNetbiosName(netbios_name.to_string()));
}
let field = |setting: &'static str, value: Option<String>, default: &str| match value {
Some(value) if !target::valid_field(&value) => {
Err(BuildError::DiscoveryMetadata { setting, value })
}
value => Ok(value.unwrap_or_else(|| default.to_string())),
};
let info = DeviceInfo {
computer,
workgroup: workgroup.to_uppercase(),
manufacturer: field("manufacturer", self.manufacturer, env!("CARGO_PKG_NAME"))?,
model_name: field("model_name", self.model_name, env!("CARGO_PKG_NAME"))?,
firmware_version: field(
"firmware_version",
self.firmware_version,
env!("CARGO_PKG_VERSION"),
)?,
};
Ok(Settings {
name,
default_name,
model: self.model,
ws_discovery: self.ws_discovery,
server_guid,
info,
})
}
}
const DEFAULT_WORKGROUP: &str = "WORKGROUP";
#[derive(Debug, Clone)]
pub(crate) struct Settings {
pub(crate) name: String,
pub(crate) default_name: bool,
pub(crate) model: Option<String>,
pub(crate) ws_discovery: Option<bool>,
pub(crate) server_guid: Option<Uuid>,
pub(crate) info: DeviceInfo,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(not(unix), allow(dead_code))]
pub(crate) struct DeviceInfo {
pub(crate) computer: String,
pub(crate) workgroup: String,
pub(crate) manufacturer: String,
pub(crate) model_name: String,
pub(crate) firmware_version: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(not(unix), allow(dead_code))]
pub(crate) struct Device {
pub(crate) endpoint: Uuid,
pub(crate) info: DeviceInfo,
}
#[derive(Debug, Clone)]
#[cfg_attr(any(target_vendor = "apple", not(unix)), allow(dead_code))]
pub(crate) struct Service {
pub(crate) name: String,
#[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
pub(crate) default_name: bool,
pub(crate) model: Option<String>,
pub(crate) port: u16,
pub(crate) scope: Scope,
pub(crate) host: String,
pub(crate) device: Option<Device>,
}
pub(crate) type Stop = oneshot::Receiver<()>;
#[async_trait]
pub(crate) trait Backend: Send + Sync {
async fn run(&self, service: Service, stop: Stop);
}
pub(crate) struct System;
#[async_trait]
impl Backend for System {
async fn run(&self, mut service: Service, stop: Stop) {
let device = service.device.take();
let scope = service.scope;
let (mdns_stop, mdns_stopped) = oneshot::channel();
let (wsd_stop, wsd_stopped) = oneshot::channel::<()>();
tokio::join!(
async move {
let _ = stop.await;
drop((mdns_stop, wsd_stop));
},
mdns(service, mdns_stopped),
async move {
#[cfg(unix)]
if let Some(device) = device {
wsd::run(device, scope, wsd_stopped).await;
}
#[cfg(not(unix))]
drop((device, scope, wsd_stopped));
},
);
}
}
async fn mdns(service: Service, stop: Stop) {
#[cfg(target_os = "linux")]
if let Some(bus) = avahi::Bus::connect().await {
return bus.run(service, stop).await;
}
#[cfg(all(unix, not(target_vendor = "apple")))]
responder::run(service, async {
let _ = stop.await;
responder::Leave::Withdraw
})
.await;
#[cfg(target_vendor = "apple")]
dns_sd::run(service, stop).await;
#[cfg(windows)]
dnsapi::run(service, stop).await;
#[cfg(not(any(unix, windows)))]
{
drop((service, stop));
warn!("network discovery is not supported on this platform; the server is not announced");
}
}
const STOP_TIMEOUT: Duration = Duration::from_secs(2);
pub(crate) struct Announcer {
stop: Option<oneshot::Sender<()>>,
task: JoinHandle<()>,
}
impl Announcer {
pub(crate) fn start(
settings: &Settings,
listener: &TcpListener,
backend: Arc<dyn Backend>,
) -> Option<Self> {
let local = match listener.local_addr() {
Ok(local) => local,
Err(e) => {
warn!(error = %e, "no listen address to announce; the server is not announced");
return None;
}
};
let v6_only =
local.is_ipv6() && socket2::SockRef::from(listener).only_v6().unwrap_or(false);
let host = host_label().unwrap_or_else(|| "smbserver".to_string());
let service = Service {
name: settings.name.clone(),
default_name: settings.default_name,
model: settings.model.clone(),
port: local.port(),
scope: Scope::new(local.ip(), v6_only),
device: ws_device(
settings,
local.port(),
&host,
Scope::new(local.ip(), v6_only),
),
host,
};
let (stop, stopped) = oneshot::channel();
let task =
tokio::spawn(async move { backend.run(service, stopped).await }.in_current_span());
Some(Self {
stop: Some(stop),
task,
})
}
pub(crate) async fn stop(mut self) {
self.stop.take();
if tokio::time::timeout(STOP_TIMEOUT, &mut self.task)
.await
.is_err()
{
warn!(timeout = ?STOP_TIMEOUT, "network discovery did not stop in time");
}
}
}
impl Drop for Announcer {
fn drop(&mut self) {
self.task.abort();
}
}
pub(crate) fn ws_device(
settings: &Settings,
port: u16,
host: &str,
scope: Scope,
) -> Option<Device> {
let computer = &settings.info.computer;
let skip =
target::ws_discovery_skip(settings.ws_discovery, port, computer, host, cfg!(windows));
let reason = match skip {
None => {
if matches!(scope, Scope::V4 | Scope::Addr(std::net::IpAddr::V4(_))) {
warn!(
"the listener accepts IPv4 only: Windows may resolve the server's name to \
an IPv6 address too and then connect over IPv6 alone, so it lists the \
server but cannot open it; listen on [::]:445 instead"
);
}
return Some(Device {
endpoint: target::endpoint_uuid(settings.server_guid, host, computer, port),
info: settings.info.clone(),
});
}
Some(WsSkip::Off) => {
debug!("WS-Discovery is off");
return None;
}
Some(WsSkip::Windows) => "Windows announces the computer itself",
Some(WsSkip::Port) => "Windows opens servers it finds that way on port 445 only",
Some(WsSkip::Host) => {
warn!(
name = %computer,
%host,
"the server is not announced over WS-Discovery: Windows opens it by its NetBIOS \
name, which reaches this host only when it is the host name; set netbios_name \
to the host name"
);
return None;
}
Some(WsSkip::Name) => {
warn!(
name = %computer,
"the server is not announced over WS-Discovery: the NetBIOS name must be 1 to 15 \
characters without control characters or any of \"/\\[]:|<>+=;,?*"
);
return None;
}
};
if settings.ws_discovery == Some(true) {
warn!(
port,
"the server is not announced over WS-Discovery: {reason}"
);
} else {
info!(
port,
"the server is not announced over WS-Discovery: {reason}"
);
}
None
}
fn host_label() -> Option<String> {
let host = crate::builder::host_name()?;
let label = host.split('.').next()?;
(!label.is_empty()).then(|| label.to_string())
}