use std::cell::{Cell, RefCell};
use std::ffi::{CStr, CString, c_char, c_int, c_short, c_void};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::ptr::{null, null_mut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use super::system::{Registrations, Registry, resolved};
use super::{Advert, Adverts, Found, POLL, Responder, txt_record};
const REFRESH: Duration = Duration::from_secs(1);
const RESOLVE_WINDOW: Duration = Duration::from_secs(1);
const DOMAIN: &CStr = c"local.";
type ServiceRef = *mut c_void;
type Flags = u32;
type ErrorType = i32;
const NO_ERROR: ErrorType = 0;
const FLAGS_MORE_COMING: Flags = 0x1;
const FLAGS_ADD: Flags = 0x2;
const PROTOCOL_IPV4: u32 = 0x1;
const AF_INET: u8 = 2;
const POLLIN: c_short = 0x1;
#[repr(C)]
struct PollFd {
fd: c_int,
events: c_short,
revents: c_short,
}
type RegisterReply = unsafe extern "C" fn(
ServiceRef,
Flags,
ErrorType,
*const c_char,
*const c_char,
*const c_char,
*mut c_void,
);
type BrowseReply = unsafe extern "C" fn(
ServiceRef,
Flags,
u32,
ErrorType,
*const c_char,
*const c_char,
*const c_char,
*mut c_void,
);
type ResolveReply = unsafe extern "C" fn(
ServiceRef,
Flags,
u32,
ErrorType,
*const c_char,
*const c_char,
u16,
u16,
*const u8,
*mut c_void,
);
type AddrInfoReply = unsafe extern "C" fn(
ServiceRef,
Flags,
u32,
ErrorType,
*const c_char,
*const c_void,
u32,
*mut c_void,
);
unsafe extern "C" {
fn DNSServiceRegister(
sd_ref: *mut ServiceRef,
flags: Flags,
interface_index: u32,
name: *const c_char,
regtype: *const c_char,
domain: *const c_char,
host: *const c_char,
port: u16,
txt_len: u16,
txt_record: *const c_void,
callback: Option<RegisterReply>,
context: *mut c_void,
) -> ErrorType;
fn DNSServiceBrowse(
sd_ref: *mut ServiceRef,
flags: Flags,
interface_index: u32,
regtype: *const c_char,
domain: *const c_char,
callback: Option<BrowseReply>,
context: *mut c_void,
) -> ErrorType;
fn DNSServiceResolve(
sd_ref: *mut ServiceRef,
flags: Flags,
interface_index: u32,
name: *const c_char,
regtype: *const c_char,
domain: *const c_char,
callback: Option<ResolveReply>,
context: *mut c_void,
) -> ErrorType;
fn DNSServiceGetAddrInfo(
sd_ref: *mut ServiceRef,
flags: Flags,
interface_index: u32,
protocol: u32,
hostname: *const c_char,
callback: Option<AddrInfoReply>,
context: *mut c_void,
) -> ErrorType;
fn DNSServiceRefSockFD(sd_ref: ServiceRef) -> c_int;
fn DNSServiceProcessResult(sd_ref: ServiceRef) -> ErrorType;
fn DNSServiceRefDeallocate(sd_ref: ServiceRef);
fn poll(fds: *mut PollFd, nfds: u32, timeout: c_int) -> c_int;
}
struct Connection(ServiceRef);
impl Connection {
fn open(what: &str, start: impl FnOnce(*mut ServiceRef) -> ErrorType) -> Result<Self> {
let mut sd_ref: ServiceRef = null_mut();
let error = start(&mut sd_ref);
if error != NO_ERROR || sd_ref.is_null() {
bail!("{what}: the system's DNS-SD service answered error {error}");
}
Ok(Self(sd_ref))
}
fn readable(&self) -> PollFd {
PollFd {
fd: unsafe { DNSServiceRefSockFD(self.0) },
events: POLLIN,
revents: 0,
}
}
fn process(&self) -> Result<()> {
let error = unsafe { DNSServiceProcessResult(self.0) };
if error != NO_ERROR {
bail!("the system's DNS-SD service answered error {error}");
}
Ok(())
}
fn run_until(&self, deadline: Instant, done: impl Fn() -> bool) -> Result<()> {
while !done() {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
break;
}
let mut fds = [self.readable()];
if wait(&mut fds, left.min(POLL))? > 0 {
self.process()?;
}
}
Ok(())
}
}
impl Drop for Connection {
fn drop(&mut self) {
unsafe { DNSServiceRefDeallocate(self.0) }
}
}
fn wait(fds: &mut [PollFd], timeout: Duration) -> Result<usize> {
let ms = c_int::try_from(timeout.as_millis()).unwrap_or(c_int::MAX);
let count = u32::try_from(fds.len()).context("too many DNS-SD connections")?;
let ready = unsafe { poll(fds.as_mut_ptr(), count, ms) };
if ready < 0 {
let e = std::io::Error::last_os_error();
if e.kind() == std::io::ErrorKind::Interrupted {
return Ok(0);
}
return Err(e).context("waiting on the system's DNS-SD service");
}
Ok(ready as usize)
}
fn context<T>(value: &T) -> *mut c_void {
(value as *const T).cast_mut().cast()
}
pub(super) fn responder(adverts: Adverts) -> Result<Responder> {
Responder::running(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)), move |stop| {
serve(stop, adverts.as_ref())
})
}
fn serve(stop: &AtomicBool, adverts: &(dyn Fn() -> Vec<Advert> + Send + Sync)) {
let mut registrations = Registrations::new(DnsSd);
let mut refreshed: Option<Instant> = None;
while !stop.load(Ordering::SeqCst) {
if refreshed.is_none_or(|at| at.elapsed() >= REFRESH) {
registrations.update(&adverts());
refreshed = Some(Instant::now());
}
let mut fds: Vec<PollFd> = registrations.handles().map(Connection::readable).collect();
if fds.is_empty() {
std::thread::sleep(POLL);
continue;
}
if let Err(e) = wait(&mut fds, POLL) {
tracing::warn!("the mDNS responder cannot wait on its registrations: {e:#}");
std::thread::sleep(POLL);
continue;
}
let mut ready = fds.iter().map(|fd| fd.revents != 0);
registrations.retain(|connection| {
if ready.next() != Some(true) {
return true;
}
match connection.process() {
Ok(()) => true,
Err(e) => {
tracing::warn!("an mDNS registration ended: {e:#}");
false
}
}
});
}
}
struct DnsSd;
impl Registry for DnsSd {
type Handle = Connection;
fn register(&mut self, advert: &Advert) -> Result<Connection> {
let name = CString::new(advert.instance.as_str()).context("an instance name with a NUL")?;
let regtype = CString::new(advert.service).context("a service name with a NUL")?;
let txt = txt_record(advert);
let txt_len = u16::try_from(txt.len()).context("a TXT record over 64 KiB")?;
Connection::open("registering an mDNS advert", |sd_ref| unsafe {
DNSServiceRegister(
sd_ref,
0,
0,
name.as_ptr(),
regtype.as_ptr(),
DOMAIN.as_ptr(),
null(),
advert.port.to_be(),
txt_len,
txt.as_ptr().cast(),
Some(on_registered),
null_mut(),
)
})
}
}
unsafe extern "C" fn on_registered(
_: ServiceRef,
_: Flags,
error: ErrorType,
_: *const c_char,
_: *const c_char,
_: *const c_char,
_: *mut c_void,
) {
if error != NO_ERROR {
tracing::warn!("the system's DNS-SD service dropped an mDNS advert: error {error}");
}
}
#[derive(PartialEq, Eq)]
struct Seen {
name: CString,
regtype: CString,
domain: CString,
interface: u32,
}
pub(super) fn browse(service: &str, window: Duration) -> Result<Vec<Found>> {
let regtype = CString::new(service).context("a service name with a NUL")?;
let seen: RefCell<Vec<Seen>> = RefCell::new(Vec::new());
let browser = Connection::open("browsing for mDNS adverts", |sd_ref| unsafe {
DNSServiceBrowse(
sd_ref,
0,
0,
regtype.as_ptr(),
DOMAIN.as_ptr(),
Some(on_browsed),
context(&seen),
)
})?;
browser.run_until(Instant::now() + window, || false)?;
drop(browser);
let deadline = Instant::now() + window;
let mut found: Vec<Found> = Vec::new();
for instance in seen.into_inner() {
let until = deadline.min(Instant::now() + RESOLVE_WINDOW);
match resolve(&instance, until) {
Ok(instances) => {
for one in instances {
if !found.contains(&one) {
found.push(one);
}
}
}
Err(e) => tracing::debug!("cannot resolve an mDNS advert: {e:#}"),
}
}
Ok(found)
}
unsafe extern "C" fn on_browsed(
_: ServiceRef,
flags: Flags,
interface: u32,
error: ErrorType,
name: *const c_char,
regtype: *const c_char,
domain: *const c_char,
context: *mut c_void,
) {
if error != NO_ERROR || name.is_null() || regtype.is_null() || domain.is_null() {
return;
}
let seen = unsafe { &*context.cast::<RefCell<Vec<Seen>>>() };
let instance = unsafe {
Seen {
name: CStr::from_ptr(name).to_owned(),
regtype: CStr::from_ptr(regtype).to_owned(),
domain: CStr::from_ptr(domain).to_owned(),
interface,
}
};
let mut seen = seen.borrow_mut();
if flags & FLAGS_ADD == 0 {
seen.retain(|held| *held != instance);
} else if !seen.contains(&instance) {
seen.push(instance);
}
}
struct Target {
host: CString,
port: u16,
txt: Vec<u8>,
}
#[derive(Default)]
struct Addresses {
found: RefCell<Vec<IpAddr>>,
settled: Cell<bool>,
}
fn resolve(instance: &Seen, deadline: Instant) -> Result<Vec<Found>> {
let target: RefCell<Option<Target>> = RefCell::new(None);
let resolver = Connection::open("resolving an mDNS advert", |sd_ref| unsafe {
DNSServiceResolve(
sd_ref,
0,
instance.interface,
instance.name.as_ptr(),
instance.regtype.as_ptr(),
instance.domain.as_ptr(),
Some(on_resolved),
context(&target),
)
})?;
resolver.run_until(deadline, || target.borrow().is_some())?;
drop(resolver);
let Some(target) = target.into_inner() else {
return Ok(Vec::new());
};
let addresses = Addresses::default();
let lookup = Connection::open("looking up an mDNS host", |sd_ref| unsafe {
DNSServiceGetAddrInfo(
sd_ref,
0,
instance.interface,
PROTOCOL_IPV4,
target.host.as_ptr(),
Some(on_address),
context(&addresses),
)
})?;
lookup.run_until(deadline, || addresses.settled.get())?;
drop(lookup);
Ok(resolved(
&instance.name.to_string_lossy(),
target.port,
&target.txt,
&addresses.found.into_inner(),
))
}
unsafe extern "C" fn on_resolved(
_: ServiceRef,
_: Flags,
_: u32,
error: ErrorType,
_: *const c_char,
host: *const c_char,
port: u16,
txt_len: u16,
txt: *const u8,
context: *mut c_void,
) {
if error != NO_ERROR || host.is_null() {
return;
}
let target = unsafe { &*context.cast::<RefCell<Option<Target>>>() };
let txt = if txt.is_null() {
Vec::new()
} else {
unsafe { std::slice::from_raw_parts(txt, usize::from(txt_len)) }.to_vec()
};
let host = unsafe { CStr::from_ptr(host) }.to_owned();
target.borrow_mut().get_or_insert(Target {
host,
port: u16::from_be(port),
txt,
});
}
unsafe extern "C" fn on_address(
_: ServiceRef,
flags: Flags,
_: u32,
error: ErrorType,
_: *const c_char,
address: *const c_void,
_: u32,
context: *mut c_void,
) {
let addresses = unsafe { &*context.cast::<Addresses>() };
if error == NO_ERROR
&& flags & FLAGS_ADD != 0
&& let Some(ip) = unsafe { ipv4_of(address) }
{
addresses.found.borrow_mut().push(ip);
}
if flags & FLAGS_MORE_COMING == 0 && !addresses.found.borrow().is_empty() {
addresses.settled.set(true);
}
}
unsafe fn ipv4_of(address: *const c_void) -> Option<IpAddr> {
if address.is_null() {
return None;
}
let bytes = unsafe { std::slice::from_raw_parts(address.cast::<u8>(), 8) };
(bytes[1] == AF_INET).then(|| IpAddr::V4(Ipv4Addr::new(bytes[4], bytes[5], bytes[6], bytes[7])))
}