use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::time::{Duration, Instant};
use super::wire::{
self, CLASS_ANY, CLASS_IN, CLASS_TOP_BIT, FLAGS_QUERY, FLAGS_RESPONSE, InRecord, Inbound,
MAX_INBOUND_MESSAGE, MAX_OUTBOUND_MESSAGE, OutQuestion, OutRecord, TYPE_ANY,
};
use super::{MAX_LOCAL_NAMES, MDNS_DEST_ADDR, MDNS_PORT, Mdns, MdnsEvent, When};
use crate::config::{MdnsProbePolicy, RESPONSE_TTL};
const PROBE_COUNT: u8 = 3;
const PROBE_INTERVAL: Duration = Duration::from_millis(250);
const ANNOUNCE_GAP: Duration = Duration::from_secs(1);
const RECORD_GAP: Duration = Duration::from_secs(1);
const DEFENCE_GAP: Duration = Duration::from_millis(250);
const QUARTER_TTL: Duration = Duration::from_secs(RESPONSE_TTL as u64 / 4);
const LEGACY_TTL: u32 = 10;
const TIEBREAK_WAIT: Duration = Duration::from_secs(1);
pub(super) const CONFLICT_LIMIT: usize = 15;
const CONFLICT_WINDOW: Duration = Duration::from_secs(10);
const CONFLICT_BACKOFF: Duration = Duration::from_secs(5);
#[derive(Debug)]
pub(super) struct Announce {
left: u8,
next: When,
gap: Duration,
}
#[derive(Debug)]
pub(super) enum Phase {
Probing { sent: u8, next: When },
Live { announce: Option<Announce> },
}
#[derive(Debug)]
pub(super) struct Planned {
due: Instant,
defensive: bool,
tc_from: Option<IpAddr>,
}
#[derive(Debug)]
pub(super) struct LocalRecord {
pub(super) name: String,
pub(super) key: String,
pub(super) ip: IpAddr,
pub(super) registered: bool,
pub(super) phase: Phase,
published: bool,
last_multicast: Option<Instant>,
last_negative: Option<Instant>,
answer: Option<Planned>,
negative: Option<Planned>,
}
#[derive(Debug)]
pub(super) struct Goodbye {
name: String,
pub(super) key: String,
pub(super) ip: IpAddr,
pub(super) due: When,
not_before: Option<Instant>,
}
fn from_ip(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V4(_) => ip,
IpAddr::V6(_) => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
}
}
fn grouped(items: &[usize], key: impl Fn(usize) -> IpAddr) -> Vec<(IpAddr, Vec<usize>)> {
let mut groups: Vec<(IpAddr, Vec<usize>)> = Vec::new();
for &item in items {
let from = key(item);
match groups.iter_mut().find(|(ip, _)| *ip == from) {
Some((_, group)) => group.push(item),
None => groups.push((from, vec![item])),
}
}
groups
}
fn is_uuid_local(key: &str) -> bool {
let Some(label) = key.strip_suffix(".local.") else {
return false;
};
label.len() == 36
&& label.bytes().enumerate().all(|(i, b)| match i {
8 | 13 | 18 | 23 => b == b'-',
_ => b.is_ascii_hexdigit(),
})
}
fn merge(slot: &mut Option<Planned>, new: Planned) {
match slot {
None => *slot = Some(new),
Some(old) => {
if old.tc_from.is_some() && old.tc_from == new.tc_from {
old.due = new.due;
} else {
old.due = old.due.min(new.due);
old.tc_from = None;
}
old.defensive |= new.defensive;
}
}
}
impl LocalRecord {
fn typ(&self) -> u16 {
wire::addr_type(self.ip)
}
pub(super) fn is_live(&self) -> bool {
matches!(self.phase, Phase::Live { .. })
}
fn is_probing(&self) -> bool {
matches!(self.phase, Phase::Probing { sent, .. } if sent > 0)
}
fn rdata(&self) -> Vec<u8> {
match self.ip {
IpAddr::V4(ip) => ip.octets().to_vec(),
IpAddr::V6(ip) => ip.octets().to_vec(),
}
}
fn out(&self, nsec: bool, flush: bool, ttl: u32) -> OutRecord<'_> {
OutRecord {
name: &self.name,
ip: self.ip,
nsec,
flush,
ttl,
}
}
fn nsec_due(&self, now: Instant) -> bool {
self.last_negative.is_none_or(|t| t + RECORD_GAP <= now)
}
fn is_known_to(&self, inbound: &Inbound) -> bool {
inbound.answers.iter().any(|known| {
known.key == self.key
&& known.class == CLASS_IN
&& known.addr() == Some(self.ip)
&& known.ttl >= RESPONSE_TTL / 2
})
}
pub(super) fn deadlines(&self, consider: &mut impl FnMut(When)) {
match &self.phase {
Phase::Probing { next, .. } => consider(*next),
Phase::Live { announce } => {
if let Some(announce) = announce {
consider(announce.next);
}
}
}
for planned in [&self.answer, &self.negative].into_iter().flatten() {
consider(When::At(planned.due));
}
}
fn multicast_sent(&mut self, now: Instant, negative_only: bool, with_nsec: bool) {
self.published = true;
if negative_only {
self.last_negative = Some(now);
self.negative = None;
return;
}
if with_nsec && self.nsec_due(now) {
self.last_negative = Some(now);
self.negative = None;
}
self.last_multicast = Some(now);
self.answer = None;
if let Phase::Live { announce } = &mut self.phase {
let finished = match announce {
Some(a) if a.next.due(now) => {
a.left = a.left.saturating_sub(1);
a.next = When::At(now + a.gap);
a.gap *= 2;
a.left == 0
}
_ => false,
};
if finished {
*announce = None;
}
}
}
}
impl Mdns {
pub(super) fn new_record(
&self,
name: String,
key: String,
ip: IpAddr,
registered: bool,
) -> Option<LocalRecord> {
let probe = OutQuestion {
name: &name,
typ: TYPE_ANY,
class: CLASS_IN,
};
wire::pack(0, FLAGS_QUERY, &[probe], &[], &[], &[])?;
let phase = if self.probes(&key) {
Phase::Probing {
sent: 0,
next: When::Asap,
}
} else {
self.live_phase(When::Asap)
};
Some(LocalRecord {
name,
key,
ip,
registered,
phase,
published: false,
last_multicast: None,
last_negative: None,
answer: None,
negative: None,
})
}
fn live_phase(&self, first: When) -> Phase {
Phase::Live {
announce: Some(Announce {
left: self.config.announce_count,
next: first,
gap: ANNOUNCE_GAP,
}),
}
}
pub(super) fn restart_records(&mut self) {
for index in 0..self.records.len() {
let probes = matches!(self.records[index].phase, Phase::Probing { .. })
|| self.probes(&self.records[index].key);
self.records[index].phase = if probes {
Phase::Probing {
sent: 0,
next: When::Asap,
}
} else {
self.live_phase(When::Asap)
};
}
}
fn probes(&self, key: &str) -> bool {
match self.config.probe_policy {
MdnsProbePolicy::Always => true,
MdnsProbePolicy::Never => false,
MdnsProbePolicy::Auto => !is_uuid_local(key),
}
}
pub(super) fn withdraw(&mut self, record: LocalRecord) {
if !record.published {
return;
}
if self.goodbyes.len() >= MAX_LOCAL_NAMES {
self.goodbyes.remove(0);
}
self.goodbyes.push(Goodbye {
due: When::Asap,
not_before: record.last_multicast.map(|t| t + RECORD_GAP),
name: record.name,
key: record.key,
ip: record.ip,
});
}
fn note_conflict_time(&mut self, now: Instant) {
self.conflicts.push_back(now);
while self.conflicts.len() > CONFLICT_LIMIT {
self.conflicts.pop_front();
}
}
fn probe_start(&mut self, now: Instant) -> Instant {
let flooded = self.conflicts.len() >= CONFLICT_LIMIT
&& self
.conflicts
.front()
.is_some_and(|&first| now.saturating_duration_since(first) <= CONFLICT_WINDOW);
let backoff = if flooded {
CONFLICT_BACKOFF
} else {
Duration::ZERO
};
now + backoff + self.jitter.millis(0, 250)
}
pub(super) fn start_records(&mut self, now: Instant) {
for index in 0..self.records.len() {
match &mut self.records[index].phase {
Phase::Probing {
next: When::Asap, ..
} => {
let at = self.probe_start(now);
self.records[index].phase = Phase::Probing {
sent: 0,
next: When::At(at),
};
}
Phase::Live {
announce: Some(announce),
} if announce.next == When::Asap => announce.next = When::At(now),
_ => {}
}
}
for goodbye in &mut self.goodbyes {
if goodbye.due == When::Asap {
goodbye.due = When::At(goodbye.not_before.map_or(now, |t| t.max(now)));
}
}
}
pub(super) fn process_query(
&mut self,
inbound: &Inbound,
src: SocketAddr,
unicast_arrival: bool,
now: Instant,
) {
let legacy = src.port() != MDNS_PORT;
let on_link = self.is_on_link(src.ip());
let truncated = inbound.header.truncated;
if !legacy {
let again = truncated.then(|| now + self.jitter.millis(400, 500));
for record in &mut self.records {
let known = record.is_known_to(inbound);
if let Some(planned) = &mut record.answer
&& planned.tc_from == Some(src.ip())
{
if known {
record.answer = None;
} else if let Some(due) = again {
planned.due = due;
}
}
if let Some(planned) = &mut record.negative
&& planned.tc_from == Some(src.ip())
&& let Some(due) = again
{
planned.due = due;
}
}
if on_link {
self.break_probe_ties(inbound, now);
if !unicast_arrival {
self.note_duplicate_questions(inbound, src, now);
self.observe_unanswered_questions(inbound, src, now);
}
}
}
if (unicast_arrival || legacy) && !on_link {
return;
}
let mut wanted: Vec<(usize, bool, bool)> = Vec::new();
let mut all_ours = !inbound.questions.is_empty();
for question in &inbound.questions {
let index = (question.class == CLASS_IN || question.class == CLASS_ANY)
.then(|| {
self.records
.iter()
.position(|r| r.is_live() && r.key == question.key)
})
.flatten();
let Some(index) = index else {
all_ours = false;
continue;
};
let record = &self.records[index];
let negative = question.typ != TYPE_ANY && question.typ != record.typ();
if !negative && !legacy && record.is_known_to(inbound) {
continue;
}
match wanted
.iter_mut()
.find(|(i, n, _)| *i == index && *n == negative)
{
Some((_, _, unicast)) => *unicast |= question.unicast,
None => wanted.push((index, negative, question.unicast)),
}
}
if wanted.is_empty() {
return;
}
if legacy {
self.reply_to_legacy(inbound, src, &wanted, now);
return;
}
let delay = if truncated {
Some(self.jitter.millis(400, 500))
} else if all_ours && (inbound.questions.len() == 1 || !self.config.multi_question_delay) {
None
} else {
Some(self.jitter.millis(20, 120))
};
let unicast_replies = self.config.unicast_replies;
let mut by_unicast: Vec<(usize, bool)> = Vec::new();
for &(index, negative, unicast) in &wanted {
let record = &mut self.records[index];
let defensive = inbound.authorities.iter().any(|a| a.key == record.key);
let delay = if defensive { None } else { delay };
let last = if negative {
record.last_negative
} else {
record.last_multicast
};
let recent = last.is_some_and(|t| now.saturating_duration_since(t) < QUARTER_TTL);
if (unicast || unicast_arrival)
&& unicast_replies
&& on_link
&& delay.is_none()
&& (defensive || recent)
{
by_unicast.push((index, negative));
continue;
}
let planned = Planned {
due: now + delay.unwrap_or_default(),
defensive,
tc_from: (truncated && !defensive).then_some(src.ip()),
};
merge(
if negative {
&mut record.negative
} else {
&mut record.answer
},
planned,
);
}
if by_unicast.is_empty() {
return;
}
let positive = |index: usize| by_unicast.contains(&(index, false));
let answers: Vec<OutRecord<'_>> = by_unicast
.iter()
.filter(|&&(index, negative)| !negative || !positive(index))
.map(|&(index, negative)| self.records[index].out(negative, true, RESPONSE_TTL))
.collect();
let additionals: Vec<OutRecord<'_>> = by_unicast
.iter()
.filter(|&&(_, negative)| !negative)
.map(|&(index, _)| self.records[index].out(true, true, RESPONSE_TTL))
.collect();
let bytes = wire::pack(0, FLAGS_RESPONSE, &[], &answers, &[], &additionals)
.filter(|bytes| bytes.len() <= MAX_OUTBOUND_MESSAGE)
.or_else(|| wire::pack(0, FLAGS_RESPONSE, &[], &answers, &[], &[]));
let from = from_ip(self.records[by_unicast[0].0].ip);
if let Some(bytes) = bytes
&& self.emit(now, from, src, &bytes)
{
for (index, _) in by_unicast {
self.records[index].published = true;
}
}
}
fn reply_to_legacy(
&mut self,
inbound: &Inbound,
src: SocketAddr,
wanted: &[(usize, bool, bool)],
now: Instant,
) {
let questions: Vec<OutQuestion<'_>> = inbound
.questions
.iter()
.map(|q| OutQuestion {
name: &q.name,
typ: q.typ,
class: q.class | if q.unicast { CLASS_TOP_BIT } else { 0 },
})
.collect();
let answers: Vec<OutRecord<'_>> = wanted
.iter()
.filter(|&&(_, negative, _)| !negative)
.map(|&(index, _, _)| self.records[index].out(false, false, LEGACY_TTL))
.collect();
let bytes = wire::pack(
inbound.header.id,
FLAGS_RESPONSE,
&questions,
&answers,
&[],
&[],
)
.filter(|bytes| bytes.len() <= MAX_INBOUND_MESSAGE);
let from = from_ip(self.records[wanted[0].0].ip);
if let Some(bytes) = bytes
&& self.emit(now, from, src, &bytes)
{
for &(index, negative, _) in wanted {
self.records[index].published |= !negative;
}
}
}
fn break_probe_ties(&mut self, inbound: &Inbound, now: Instant) {
if inbound.authorities.is_empty() {
return;
}
for record in &mut self.records {
if !record.is_probing() {
continue;
}
let mut theirs: Vec<(u16, u16, Vec<u8>)> = inbound
.authorities
.iter()
.filter(|a| a.key == record.key)
.map(|a| (a.class, a.typ, a.rdata()))
.collect();
theirs.sort();
theirs.dedup();
let Some(first) = theirs.first() else {
continue;
};
let ours = (CLASS_IN, record.typ(), record.rdata());
let lost = match ours.cmp(first) {
std::cmp::Ordering::Less => true,
std::cmp::Ordering::Equal => theirs.len() > 1,
std::cmp::Ordering::Greater => false,
};
if lost {
log::debug!(
"mDNS lost a simultaneous probe for {}: probing again in a second",
record.name
);
record.phase = Phase::Probing {
sent: 0,
next: When::At(now + TIEBREAK_WAIT),
};
}
}
}
pub(super) fn note_conflict(&mut self, theirs: &InRecord, now: Instant) {
let Some(index) = self.records.iter().position(|r| r.key == theirs.key) else {
return;
};
let record = &mut self.records[index];
let same_type = theirs.typ == record.typ();
let identical = same_type && theirs.addr() == Some(record.ip);
match record.phase {
Phase::Probing { sent: 0, .. } => {}
Phase::Probing { .. } => {
if identical {
return;
}
let lost = self.records.remove(index);
log::warn!(
"mDNS gives up the name {}: another host answers for it",
lost.name
);
self.note_conflict_time(now);
let name = lost.name.strip_suffix('.').unwrap_or(&lost.name).to_owned();
self.event_outs
.push_back(MdnsEvent::LocalNameConflict(name));
}
Phase::Live { .. } => {
if !same_type {
return;
}
if identical {
if theirs.ttl < RESPONSE_TTL / 2 {
merge(
&mut record.answer,
Planned {
due: now,
defensive: false,
tc_from: None,
},
);
}
return;
}
log::warn!(
"mDNS probes again for {}: another host gave it a different address",
record.name
);
record.answer = None;
record.negative = None;
self.note_conflict_time(now);
let at = self.probe_start(now);
self.records[index].phase = Phase::Probing {
sent: 0,
next: When::At(at),
};
}
}
}
pub(super) fn flush_probes(&mut self, now: Instant) -> bool {
let mut due = Vec::new();
for index in 0..self.records.len() {
if let Phase::Probing { sent, next } = self.records[index].phase
&& next.due(now)
{
if sent >= PROBE_COUNT {
self.records[index].phase = self.live_phase(When::At(now));
} else {
due.push(index);
}
}
}
for (from, group) in grouped(&due, |i| from_ip(self.records[i].ip)) {
let mut packets = Vec::new();
{
let records = &self.records;
wire::split(
&group,
&|items, _| {
let questions: Vec<OutQuestion<'_>> = items
.iter()
.map(|&i| OutQuestion {
name: &records[i].name,
typ: TYPE_ANY,
class: CLASS_IN | CLASS_TOP_BIT,
})
.collect();
let proposed: Vec<OutRecord<'_>> = items
.iter()
.map(|&i| records[i].out(false, false, RESPONSE_TTL))
.collect();
wire::pack(0, FLAGS_QUERY, &questions, &[], &proposed, &[])
},
&mut packets,
);
}
for packet in packets {
if let Some(bytes) = &packet.bytes
&& !self.emit(now, from, MDNS_DEST_ADDR, bytes)
{
return false;
}
for index in packet.items {
if let Phase::Probing { sent, next } = &mut self.records[index].phase {
*sent += 1;
*next = When::At(now + PROBE_INTERVAL);
}
}
}
}
true
}
pub(super) fn flush_records(&mut self, now: Instant) -> bool {
let mut due = Vec::new();
let mut negative_only = vec![false; self.records.len()];
for (index, record) in self.records.iter_mut().enumerate() {
let Phase::Live { announce } = &mut record.phase else {
record.answer = None;
record.negative = None;
continue;
};
let mut positive = false;
if let Some(announce) = announce
&& announce.next.due(now)
{
match record.last_multicast {
Some(t) if t + RECORD_GAP > now => announce.next = When::At(t + RECORD_GAP),
_ => positive = true,
}
}
if let Some(planned) = &mut record.answer
&& planned.due <= now
{
let gap = if planned.defensive {
DEFENCE_GAP
} else {
RECORD_GAP
};
match record.last_multicast {
Some(t) if t + gap > now => planned.due = t + gap,
_ => positive = true,
}
}
if positive {
due.push(index);
continue;
}
if let Some(planned) = &mut record.negative
&& planned.due <= now
{
let gap = if planned.defensive {
DEFENCE_GAP
} else {
RECORD_GAP
};
match record.last_negative {
Some(t) if t + gap > now => planned.due = t + gap,
_ => {
negative_only[index] = true;
due.push(index);
}
}
}
}
for (from, group) in grouped(&due, |i| from_ip(self.records[i].ip)) {
let mut packets = Vec::new();
{
let records = &self.records;
let negative_only = &negative_only;
wire::split(
&group,
&|items, full| {
let answers: Vec<OutRecord<'_>> = items
.iter()
.map(|&i| records[i].out(negative_only[i], true, RESPONSE_TTL))
.collect();
let additionals: Vec<OutRecord<'_>> = items
.iter()
.filter(|&&i| full && !negative_only[i] && records[i].nsec_due(now))
.map(|&i| records[i].out(true, true, RESPONSE_TTL))
.collect();
wire::pack(0, FLAGS_RESPONSE, &[], &answers, &[], &additionals)
},
&mut packets,
);
}
for packet in packets {
if let Some(bytes) = &packet.bytes
&& !self.emit(now, from, MDNS_DEST_ADDR, bytes)
{
return false;
}
for index in packet.items {
self.records[index].multicast_sent(now, negative_only[index], !packet.trimmed);
}
}
}
true
}
pub(super) fn flush_goodbyes(&mut self, now: Instant) -> bool {
let due: Vec<usize> = (0..self.goodbyes.len())
.filter(|&i| self.goodbyes[i].due.due(now))
.collect();
let mut sent = vec![false; self.goodbyes.len()];
let mut budget_left = true;
'groups: for (from, group) in grouped(&due, |i| from_ip(self.goodbyes[i].ip)) {
let mut packets = Vec::new();
{
let goodbyes = &self.goodbyes;
wire::split(
&group,
&|items, _| {
let answers: Vec<OutRecord<'_>> =
items.iter().map(|&i| goodbyes[i].out()).collect();
wire::pack(0, FLAGS_RESPONSE, &[], &answers, &[], &[])
},
&mut packets,
);
}
for packet in packets {
if let Some(bytes) = &packet.bytes
&& !self.emit(now, from, MDNS_DEST_ADDR, bytes)
{
budget_left = false;
break 'groups;
}
for index in packet.items {
sent[index] = true;
}
}
}
let mut sent = sent.into_iter();
self.goodbyes.retain(|_| !sent.next().unwrap_or(false));
budget_left
}
pub(super) fn queue_closing_goodbyes(&mut self) {
let now = self.last_now;
let mut leaving: Vec<Goodbye> = std::mem::take(&mut self.goodbyes);
for record in std::mem::take(&mut self.records) {
if record.is_live() && record.published {
leaving.push(Goodbye {
due: When::At(now),
not_before: None,
name: record.name,
key: record.key,
ip: record.ip,
});
}
}
let all: Vec<usize> = (0..leaving.len()).collect();
for (from, group) in grouped(&all, |i| from_ip(leaving[i].ip)) {
let mut packets = Vec::new();
wire::split(
&group,
&|items, _| {
let answers: Vec<OutRecord<'_>> =
items.iter().map(|&i| leaving[i].out()).collect();
wire::pack(0, FLAGS_RESPONSE, &[], &answers, &[], &[])
},
&mut packets,
);
for packet in packets {
if let Some(bytes) = &packet.bytes {
self.push_packet(now, from, MDNS_DEST_ADDR, bytes);
}
}
}
}
pub(super) fn probes_for(&self, key: &str) -> bool {
self.records.iter().any(|r| r.key == key && r.is_probing())
}
}
impl Goodbye {
fn out(&self) -> OutRecord<'_> {
OutRecord {
name: &self.name,
ip: self.ip,
nsec: false,
flush: true,
ttl: 0,
}
}
}