mod links;
mod mdns;
mod targets;
pub use links::{LinkError, for_listening, for_listening_on};
pub use targets::{
DiscoveryTargets, for_discovery, for_discovery_with, for_exclusion, for_exclusion_with,
resolve_names, to_set, to_target_map,
};
use std::fmt;
use std::net::IpAddr;
use std::time::Duration;
use hickory_resolver::TokioResolver;
use crate::warn;
const DEFAULT_MDNS_TIMEOUT: Duration = Duration::from_secs(1);
const MIN_MDNS_TIMEOUT: Duration = Duration::from_millis(500);
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub struct ResolveConfig {
pub mdns: bool,
pub mdns_timeout: Duration,
}
impl Default for ResolveConfig {
fn default() -> Self {
Self {
mdns: true,
mdns_timeout: DEFAULT_MDNS_TIMEOUT,
}
}
}
#[derive(Clone)]
pub struct Resolver {
unicast: Option<TokioResolver>,
config: ResolveConfig,
}
impl Resolver {
pub fn from_system() -> Self {
Self::with_config(ResolveConfig::default())
}
pub fn with_config(config: ResolveConfig) -> Self {
Self {
unicast: build_unicast(),
config,
}
}
pub async fn resolve(&self, name: &str) -> Vec<IpAddr> {
let name = name.trim_end_matches('.');
if is_multicast_local(name) {
return self.resolve_mdns(name).await;
}
let unicast = self.resolve_unicast(name).await;
if !unicast.is_empty() || !is_single_label(name) {
return unicast;
}
self.resolve_mdns(&format!("{name}.local")).await
}
async fn resolve_unicast(&self, name: &str) -> Vec<IpAddr> {
let Some(resolver) = &self.unicast else {
return Vec::new();
};
match resolver.lookup_ip(name).await {
Ok(lookup) => lookup.iter().collect(),
Err(_) => Vec::new(),
}
}
async fn resolve_mdns(&self, name: &str) -> Vec<IpAddr> {
if !self.config.mdns {
return Vec::new();
}
let window = self.config.mdns_timeout.max(MIN_MDNS_TIMEOUT);
mdns::resolve(name, window).await
}
}
impl fmt::Debug for Resolver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Resolver")
.field("unicast", &self.unicast.is_some())
.field("config", &self.config)
.finish()
}
}
fn build_unicast() -> Option<TokioResolver> {
let Ok(builder) = TokioResolver::builder_tokio() else {
warn!("no system resolver configuration found; global names will not resolve");
return None;
};
let Ok(resolver) = builder.build() else {
warn!("could not build the system resolver; global names will not resolve");
return None;
};
Some(resolver)
}
fn is_multicast_local(name: &str) -> bool {
name.contains('.')
&& name
.rsplit('.')
.next()
.is_some_and(|tld| tld.eq_ignore_ascii_case("local"))
}
fn is_single_label(name: &str) -> bool {
!name.is_empty() && !name.contains('.')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_dotted_local_name_is_a_multicast_name() {
assert!(is_multicast_local("raspberrypi.local"));
assert!(is_multicast_local("Printer.LOCAL"));
assert!(is_multicast_local("host.sub.local"));
assert!(!is_multicast_local("example.com"));
assert!(!is_multicast_local("localhost"));
assert!(!is_multicast_local("local"));
}
#[test]
fn a_window_shorter_than_the_protocol_allows_is_raised_to_it() {
for asked in [Duration::ZERO, Duration::from_millis(1), MIN_MDNS_TIMEOUT] {
assert_eq!(asked.max(MIN_MDNS_TIMEOUT), MIN_MDNS_TIMEOUT);
}
let generous = Duration::from_secs(5);
assert_eq!(generous.max(MIN_MDNS_TIMEOUT), generous);
assert_eq!(
DEFAULT_MDNS_TIMEOUT.max(MIN_MDNS_TIMEOUT),
DEFAULT_MDNS_TIMEOUT,
"the default is above the floor, or the floor is the default"
);
}
#[test]
fn a_resolver_reports_the_two_facts_that_decide_where_a_name_goes() {
let rendered = format!("{:?}", Resolver::with_config(ResolveConfig::default()));
assert!(rendered.starts_with("Resolver"), "{rendered}");
assert!(rendered.contains("unicast"), "{rendered}");
assert!(rendered.contains("mdns: true"), "{rendered}");
}
#[test]
fn a_single_label_is_a_fallback_candidate_and_a_dotted_name_is_not() {
assert!(is_single_label("nas"));
assert!(!is_single_label("nas.local"));
assert!(!is_single_label("example.com"));
assert!(!is_single_label(""));
}
}