Skip to main content

second_brain_sync/
mdns.rs

1use std::collections::BTreeMap;
2use std::io::ErrorKind;
3use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::thread::JoinHandle;
7use std::time::{Duration, Instant};
8
9use anyhow::{Context, Result};
10use rand_core::{OsRng, RngCore};
11
12#[cfg(target_os = "macos")]
13mod dnssd;
14#[cfg(not(target_os = "macos"))]
15mod lan;
16#[cfg(target_os = "macos")]
17use dnssd as lan;
18#[cfg(any(target_os = "macos", test))]
19mod system;
20
21/// Every device with an sshd advertises this, its machine id and ssh login
22/// in the TXT record and its sshd port in the SRV record.
23pub const SERVICE: &str = "_second-brain._tcp";
24/// An open `sb pair` listener, its port in the SRV record.
25pub const PAIR_SERVICE: &str = "_second-brain-pair._tcp";
26pub const TXT_ID: &str = "id";
27pub const TXT_LOGIN: &str = "login";
28/// How long a lookup collects answers; responders on a LAN answer within
29/// milliseconds, and the query is sent twice in case one is lost.
30pub const LOOKUP_WINDOW: Duration = Duration::from_millis(1500);
31
32#[cfg(any(not(target_os = "macos"), test))]
33const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 0, 251);
34const MDNS_PORT: u16 = 5353;
35/// Every SRV target is a host name under this prefix, so it never claims a
36/// name avahi or mDNSResponder publishes for the host itself.
37const HOST_PREFIX: &str = "second-brain-";
38const TYPE_A: u16 = 1;
39const TYPE_PTR: u16 = 12;
40const TYPE_TXT: u16 = 16;
41const TYPE_SRV: u16 = 33;
42const TYPE_ANY: u16 = 255;
43const CLASS_IN: u16 = 1;
44const CLASS_MASK: u16 = 0x7fff;
45const CACHE_FLUSH: u16 = 0x8000;
46const UNICAST_RESPONSE: u16 = 0x8000;
47const FLAG_RESPONSE: u16 = 0x8000;
48const FLAG_AUTHORITATIVE: u16 = 0x0400;
49/// RFC 6762 6.7: answers to a legacy unicast query carry a TTL of at most
50/// 10 seconds.
51const UNICAST_TTL: u32 = 10;
52const MULTICAST_TTL: u32 = 120;
53const MAX_LABEL: usize = 63;
54const MAX_NAME: usize = 255;
55const MAX_JUMPS: usize = 16;
56const MAX_PACKET: usize = 9000;
57const POLL: Duration = Duration::from_millis(200);
58const RESEND_AFTER: Duration = Duration::from_millis(500);
59
60/// Where lookups are sent and where a responder listens.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum Net {
63    /// mDNS on the local network. On macOS the system's DNS-SD service
64    /// registers and browses, and nothing here binds port 5353. Elsewhere
65    /// queries go to the 224.0.0.251:5353 group from a port other than 5353,
66    /// so responders answer the asking socket directly.
67    Lan,
68    /// One responder at this address, reached by plain unicast; on a
69    /// loopback address nothing leaves the host.
70    Unicast(SocketAddr),
71}
72
73/// One service instance a responder answers for.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct Advert {
76    pub service: &'static str,
77    pub instance: String,
78    /// The SRV target's first label, answered with the address this host
79    /// sends its reply from; on macOS the system's DNS-SD service targets
80    /// the host's own name instead.
81    pub host: String,
82    pub port: u16,
83    pub txt: Vec<(String, String)>,
84}
85
86/// One instance a lookup found. `address` is where its answer came from,
87/// which on a LAN is the address the device is reachable at.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct Found {
90    pub instance: String,
91    pub address: IpAddr,
92    pub port: u16,
93    pub txt: BTreeMap<String, String>,
94}
95
96impl Found {
97    pub fn get(&self, key: &str) -> Option<&str> {
98        self.txt.get(key).map(String::as_str)
99    }
100}
101
102pub fn device_advert(machine_id: &str, login: &str, ssh_port: u16) -> Advert {
103    Advert {
104        service: SERVICE,
105        instance: label(machine_id),
106        host: host_label(machine_id),
107        port: ssh_port,
108        txt: vec![
109            (TXT_ID.to_string(), machine_id.to_string()),
110            (TXT_LOGIN.to_string(), login.to_string()),
111        ],
112    }
113}
114
115pub fn pairing_advert(name: &str, machine_id: &str, port: u16) -> Advert {
116    Advert {
117        service: PAIR_SERVICE,
118        instance: label(if name.is_empty() { machine_id } else { name }),
119        host: host_label(machine_id),
120        port,
121        txt: vec![(TXT_ID.to_string(), machine_id.to_string())],
122    }
123}
124
125fn host_label(machine_id: &str) -> String {
126    label(&format!("{HOST_PREFIX}{machine_id}"))
127}
128
129/// The first 63 bytes, cut at a character boundary.
130fn label(text: &str) -> String {
131    let mut end = text.len().min(MAX_LABEL);
132    while !text.is_char_boundary(end) {
133        end -= 1;
134    }
135    text[..end].to_string()
136}
137
138/// Read on every query that names one of our services, instances or hosts,
139/// or each second on macOS, where the system's DNS-SD service answers, so
140/// adverts stay current without being pushed.
141pub type Adverts = Arc<dyn Fn() -> Vec<Advert> + Send + Sync>;
142
143/// Answers queries for `Adverts` until dropped.
144pub struct Responder {
145    local: SocketAddr,
146    stop: Arc<AtomicBool>,
147    thread: Option<JoinHandle<()>>,
148}
149
150impl Responder {
151    pub fn spawn(net: &Net, adverts: Adverts) -> Result<Self> {
152        match net {
153            Net::Lan => lan::responder(adverts),
154            Net::Unicast(address) => Self::answering(
155                UdpSocket::bind(address)
156                    .with_context(|| format!("binding the mDNS responder to {address}"))?,
157                None,
158                adverts,
159            ),
160        }
161    }
162
163    /// The address its socket is bound to; unspecified with port 0 when the
164    /// system's DNS-SD service answers in its place.
165    pub fn local_addr(&self) -> SocketAddr {
166        self.local
167    }
168
169    fn answering(socket: UdpSocket, group: Option<SocketAddr>, adverts: Adverts) -> Result<Self> {
170        socket.set_read_timeout(Some(POLL))?;
171        let local = socket.local_addr()?;
172        Self::running(local, move |stop| {
173            serve(&socket, group, stop, adverts.as_ref())
174        })
175    }
176
177    fn running(local: SocketAddr, work: impl FnOnce(&AtomicBool) + Send + 'static) -> Result<Self> {
178        let stop = Arc::new(AtomicBool::new(false));
179        let thread = std::thread::Builder::new()
180            .name("mdns-responder".to_string())
181            .spawn({
182                let stop = stop.clone();
183                move || work(&stop)
184            })
185            .context("spawning the mDNS responder")?;
186        Ok(Self {
187            local,
188            stop,
189            thread: Some(thread),
190        })
191    }
192}
193
194impl Drop for Responder {
195    fn drop(&mut self) {
196        self.stop.store(true, Ordering::SeqCst);
197        if let Some(thread) = self.thread.take()
198            && thread.join().is_err()
199        {
200            tracing::warn!("the mDNS responder panicked");
201        }
202    }
203}
204
205fn serve(
206    socket: &UdpSocket,
207    group: Option<SocketAddr>,
208    stop: &AtomicBool,
209    adverts: &(dyn Fn() -> Vec<Advert> + Send + Sync),
210) {
211    let mut buf = vec![0u8; MAX_PACKET];
212    while !stop.load(Ordering::SeqCst) {
213        let (len, from) = match socket.recv_from(&mut buf) {
214            Ok(received) => received,
215            Err(e) if is_timeout(&e) || e.kind() == ErrorKind::ConnectionRefused => continue,
216            Err(e) => {
217                tracing::warn!("the mDNS responder cannot read: {e}");
218                std::thread::sleep(POLL);
219                continue;
220            }
221        };
222        let Some((reply, to)) = answer(&buf[..len], from, group, adverts) else {
223            continue;
224        };
225        if let Err(e) = socket.send_to(&reply, to) {
226            tracing::debug!("cannot answer an mDNS query from {from}: {e}");
227        }
228    }
229}
230
231fn on_local_network(ip: IpAddr) -> bool {
232    match ip {
233        IpAddr::V4(v4) => v4.is_private() || v4.is_link_local() || v4.is_loopback(),
234        IpAddr::V6(_) => false,
235    }
236}
237
238fn is_timeout(e: &std::io::Error) -> bool {
239    matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut)
240}
241
242/// The reply to `packet` and where it goes, when it asks for a service,
243/// instance or host name `adverts` holds. A query from a port other than
244/// 5353 is a legacy unicast query, answered to its sender with its id and
245/// first answered question; one from 5353 is answered to the group unless
246/// that question asks for a unicast reply. An A record carries the address
247/// the reply leaves from, and a host question goes unanswered without one.
248/// Only queries from a private, link-local or loopback address are
249/// answered, so a host reachable from the internet is no amplifier for a
250/// spoofed sender; a LAN numbered from public or shared address space is
251/// not served.
252fn answer(
253    packet: &[u8],
254    from: SocketAddr,
255    group: Option<SocketAddr>,
256    adverts: &(dyn Fn() -> Vec<Advert> + Send + Sync),
257) -> Option<(Vec<u8>, SocketAddr)> {
258    answer_routed(packet, from, group, adverts, &route_toward)
259}
260
261fn answer_routed(
262    packet: &[u8],
263    from: SocketAddr,
264    group: Option<SocketAddr>,
265    adverts: &(dyn Fn() -> Vec<Advert> + Send + Sync),
266    route: &dyn Fn(IpAddr) -> Option<Ipv4Addr>,
267) -> Option<(Vec<u8>, SocketAddr)> {
268    if !on_local_network(from.ip()) {
269        return None;
270    }
271    let message = Message::parse(packet)?;
272    if message.flags & FLAG_RESPONSE != 0 {
273        return None;
274    }
275    let asked: Vec<&Question> = message
276        .questions
277        .iter()
278        .filter(|q| q.qclass & CLASS_MASK == CLASS_IN && may_be_ours(q))
279        .collect();
280    if asked.is_empty() {
281        return None;
282    }
283    let held = adverts();
284    let mut reply = Reply::default();
285    let mut matched = Vec::new();
286    for question in &asked {
287        let mut records = false;
288        let mut host = false;
289        for advert in &held {
290            let (named, hosted) = reply.answer(question, advert);
291            records |= named;
292            host |= hosted;
293        }
294        matched.push((*question, records, host));
295    }
296    let legacy = from.port() != MDNS_PORT;
297    let destination = |question: &Question| match group {
298        Some(group) if !legacy && question.qclass & UNICAST_RESPONSE == 0 => group,
299        _ => from,
300    };
301    let mut first = matched
302        .iter()
303        .find(|(_, records, host)| *records || *host)?
304        .0;
305    let mut to = destination(first);
306    let mut address = route(to.ip());
307    if address.is_none() {
308        first = matched.iter().find(|(_, records, _)| *records)?.0;
309        to = destination(first);
310        address = route(to.ip());
311    }
312    reply.complete(address);
313    let reply = if legacy {
314        reply.write(message.id, Some(first), UNICAST_TTL, false)
315    } else {
316        reply.write(0, None, MULTICAST_TTL, true)
317    };
318    Some((reply, to))
319}
320
321/// Whether `question` names one of our services, an instance of one, or a
322/// host under `HOST_PREFIX`, checked before any advert is read.
323fn may_be_ours(question: &Question) -> bool {
324    let name = &question.name;
325    let ours = |labels: &[String]| {
326        [SERVICE, PAIR_SERVICE]
327            .iter()
328            .any(|service| same_labels(labels, &service_name(service)))
329    };
330    match question.qtype {
331        TYPE_PTR => ours(name),
332        TYPE_SRV | TYPE_TXT => name.len() > 1 && ours(&name[1..]),
333        TYPE_A => is_our_host(name),
334        TYPE_ANY => ours(name) || (name.len() > 1 && ours(&name[1..])) || is_our_host(name),
335        _ => false,
336    }
337}
338
339fn is_our_host(name: &[String]) -> bool {
340    name.len() == 2
341        && name[1].eq_ignore_ascii_case("local")
342        && name[0]
343            .get(..HOST_PREFIX.len())
344            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(HOST_PREFIX))
345}
346
347/// The IPv4 address this host sends from toward `to`, the group included;
348/// connecting a UDP socket sends nothing.
349fn route_toward(to: IpAddr) -> Option<Ipv4Addr> {
350    let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).ok()?;
351    socket.connect((to, 9)).ok()?;
352    match socket.local_addr().ok()?.ip() {
353        IpAddr::V4(address) if !address.is_unspecified() => Some(address),
354        _ => None,
355    }
356}
357
358#[derive(PartialEq)]
359enum Answer<'a> {
360    Ptr(&'a Advert),
361    Srv(&'a Advert),
362    Txt(&'a Advert),
363    Host(&'a str, Ipv4Addr),
364}
365
366#[derive(Default)]
367struct Reply<'a> {
368    answers: Vec<Answer<'a>>,
369    additional: Vec<Answer<'a>>,
370    hosts_asked: Vec<&'a str>,
371}
372
373impl<'a> Reply<'a> {
374    /// Whether `question` names `advert`'s service or instance, and whether
375    /// it names its host, which `complete` answers once the reply's address
376    /// is known.
377    fn answer(&mut self, question: &Question, advert: &'a Advert) -> (bool, bool) {
378        let any = question.qtype == TYPE_ANY;
379        let name = &question.name;
380        let mut records = Vec::new();
381        if (any || question.qtype == TYPE_PTR) && same_labels(name, &service_name(advert.service)) {
382            records.push(Answer::Ptr(advert));
383        }
384        if same_labels(name, &instance_name(advert)) {
385            if any || question.qtype == TYPE_SRV {
386                records.push(Answer::Srv(advert));
387            }
388            if any || question.qtype == TYPE_TXT {
389                records.push(Answer::Txt(advert));
390            }
391        }
392        let host = (any || question.qtype == TYPE_A) && same_labels(name, &host_name(advert));
393        if host && !self.hosts_asked.contains(&advert.host.as_str()) {
394            self.hosts_asked.push(&advert.host);
395        }
396        let named = !records.is_empty();
397        for record in records {
398            if !self.answers.contains(&record) {
399                self.answers.push(record);
400            }
401        }
402        (named, host)
403    }
404
405    /// RFC 6763 12: a PTR answer brings its SRV and TXT records, and an SRV
406    /// record the address of its target. Without an address no A record is
407    /// written, and a question only for one goes unanswered.
408    fn complete(&mut self, address: Option<Ipv4Addr>) {
409        if let Some(address) = address {
410            for host in std::mem::take(&mut self.hosts_asked) {
411                let record = Answer::Host(host, address);
412                if !self.answers.contains(&record) {
413                    self.answers.push(record);
414                }
415            }
416        }
417        let pointed: Vec<&'a Advert> = self
418            .answers
419            .iter()
420            .filter_map(|record| match record {
421                Answer::Ptr(advert) => Some(*advert),
422                _ => None,
423            })
424            .collect();
425        for advert in pointed {
426            self.add(Answer::Srv(advert));
427            self.add(Answer::Txt(advert));
428        }
429        let targets: Vec<&'a str> = self
430            .answers
431            .iter()
432            .chain(&self.additional)
433            .filter_map(|record| match record {
434                Answer::Srv(advert) => Some(advert.host.as_str()),
435                _ => None,
436            })
437            .collect();
438        if let Some(address) = address {
439            for host in targets {
440                self.add(Answer::Host(host, address));
441            }
442        }
443    }
444
445    fn add(&mut self, record: Answer<'a>) {
446        if !self.answers.contains(&record) && !self.additional.contains(&record) {
447            self.additional.push(record);
448        }
449    }
450
451    fn write(&self, id: u16, question: Option<&Question>, ttl: u32, flush: bool) -> Vec<u8> {
452        let mut out = Vec::with_capacity(512);
453        put_header(
454            &mut out,
455            id,
456            FLAG_RESPONSE | FLAG_AUTHORITATIVE,
457            u16::from(question.is_some()),
458            self.answers.len() as u16,
459            self.additional.len() as u16,
460        );
461        if let Some(question) = question {
462            put_name(&mut out, &question.name);
463            put_u16(&mut out, question.qtype);
464            put_u16(&mut out, CLASS_IN);
465        }
466        let unique = if flush {
467            CLASS_IN | CACHE_FLUSH
468        } else {
469            CLASS_IN
470        };
471        for record in self.answers.iter().chain(&self.additional) {
472            match record {
473                Answer::Ptr(advert) => {
474                    let mut rdata = Vec::new();
475                    put_name(&mut rdata, &instance_name(advert));
476                    let name = service_name(advert.service);
477                    put_record(&mut out, &name, TYPE_PTR, CLASS_IN, ttl, &rdata);
478                }
479                Answer::Srv(advert) => {
480                    let mut srv = Vec::new();
481                    put_u16(&mut srv, 0);
482                    put_u16(&mut srv, 0);
483                    put_u16(&mut srv, advert.port);
484                    put_name(&mut srv, &host_name(advert));
485                    let name = instance_name(advert);
486                    put_record(&mut out, &name, TYPE_SRV, unique, ttl, &srv);
487                }
488                Answer::Txt(advert) => {
489                    let name = instance_name(advert);
490                    put_record(&mut out, &name, TYPE_TXT, unique, ttl, &txt_record(advert));
491                }
492                Answer::Host(host, address) => {
493                    let name = [host.to_string(), "local".to_string()];
494                    put_record(&mut out, &name, TYPE_A, unique, ttl, &address.octets());
495                }
496            }
497        }
498        out
499    }
500}
501
502/// The instances of `service` found within `window`, each at an address
503/// on the local network.
504pub fn browse(net: &Net, service: &str, window: Duration) -> Result<Vec<Found>> {
505    match net {
506        Net::Lan => lan::browse(service, window),
507        Net::Unicast(address) => {
508            let socket =
509                UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).context("opening an mDNS socket")?;
510            ask(&socket, *address, service, window)
511        }
512    }
513}
514
515/// Sends a query for `service` to `to` and collects the instances that
516/// answer within `window`. A legacy unicast reply echoes the query's id, so
517/// a reply with another id, or from outside the local network, is dropped.
518fn ask(socket: &UdpSocket, to: SocketAddr, service: &str, window: Duration) -> Result<Vec<Found>> {
519    let id = OsRng.next_u32() as u16;
520    let query = query(id, service);
521    socket
522        .send_to(&query, to)
523        .with_context(|| format!("sending an mDNS query to {to}"))?;
524    let start = Instant::now();
525    let mut resent = false;
526    let mut found: Vec<Found> = Vec::new();
527    let mut buf = vec![0u8; MAX_PACKET];
528    loop {
529        let elapsed = start.elapsed();
530        if elapsed >= window {
531            break;
532        }
533        if !resent && elapsed >= RESEND_AFTER {
534            resent = true;
535            if let Err(e) = socket.send_to(&query, to) {
536                tracing::debug!("cannot resend an mDNS query to {to}: {e}");
537            }
538        }
539        let until = if resent {
540            window
541        } else {
542            window.min(RESEND_AFTER)
543        };
544        let wait = until.saturating_sub(elapsed);
545        socket.set_read_timeout(Some(wait.max(Duration::from_millis(1))))?;
546        let (len, from) = match socket.recv_from(&mut buf) {
547            Ok(received) => received,
548            Err(e) if is_timeout(&e) || e.kind() == ErrorKind::ConnectionRefused => continue,
549            Err(e) => return Err(e).context("reading mDNS answers"),
550        };
551        if !on_local_network(from.ip()) || Message::id_of(&buf[..len]) != Some(id) {
552            continue;
553        }
554        for instance in found_in(&buf[..len], from, service) {
555            if !found.contains(&instance) {
556                found.push(instance);
557            }
558        }
559    }
560    Ok(found)
561}
562
563/// The instances of `service` a response names, each with its SRV port and
564/// TXT strings; an instance without an SRV record is left out.
565fn found_in(packet: &[u8], from: SocketAddr, service: &str) -> Vec<Found> {
566    let Some(message) = Message::parse(packet) else {
567        return Vec::new();
568    };
569    if message.flags & FLAG_RESPONSE == 0 {
570        return Vec::new();
571    }
572    let wanted = service_name(service);
573    let mut out = Vec::new();
574    for record in &message.records {
575        let Rdata::Ptr(instance) = &record.rdata else {
576            continue;
577        };
578        if !same_labels(&record.name, &wanted) || instance.is_empty() {
579            continue;
580        }
581        let port = message.records.iter().find_map(|r| match &r.rdata {
582            Rdata::Srv { port } if same_labels(&r.name, instance) => Some(*port),
583            _ => None,
584        });
585        let Some(port) = port else {
586            continue;
587        };
588        let strings: Vec<Vec<u8>> = message
589            .records
590            .iter()
591            .filter_map(|r| match &r.rdata {
592                Rdata::Txt(strings) if same_labels(&r.name, instance) => Some(strings.clone()),
593                _ => None,
594            })
595            .flatten()
596            .collect();
597        let txt = txt_map(&strings);
598        let found = Found {
599            instance: instance[0].clone(),
600            address: from.ip(),
601            port,
602            txt,
603        };
604        if !out.contains(&found) {
605            out.push(found);
606        }
607    }
608    out
609}
610
611/// TXT strings as `key=value` pairs, keys lowercased and the first of a
612/// repeated key kept, as RFC 6763 6.4 reads them.
613fn txt_map(strings: &[Vec<u8>]) -> BTreeMap<String, String> {
614    let mut txt = BTreeMap::new();
615    for string in strings {
616        let text = String::from_utf8_lossy(string);
617        let (key, value) = text.split_once('=').unwrap_or((&text, ""));
618        if key.is_empty() {
619            continue;
620        }
621        txt.entry(key.to_ascii_lowercase())
622            .or_insert_with(|| value.to_string());
623    }
624    txt
625}
626
627/// An advert's TXT record data, one length-prefixed string per pair; a
628/// pair too long for one string is left out.
629fn txt_record(advert: &Advert) -> Vec<u8> {
630    let mut txt = Vec::new();
631    for (key, value) in &advert.txt {
632        let string = format!("{key}={value}");
633        if string.len() <= 255 {
634            txt.push(string.len() as u8);
635            txt.extend_from_slice(string.as_bytes());
636        }
637    }
638    if txt.is_empty() {
639        txt.push(0);
640    }
641    txt
642}
643
644fn service_name(service: &str) -> Vec<String> {
645    service
646        .split('.')
647        .chain(["local"])
648        .map(str::to_string)
649        .collect()
650}
651
652fn same_labels(a: &[String], b: &[String]) -> bool {
653    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.eq_ignore_ascii_case(y))
654}
655
656fn query(id: u16, service: &str) -> Vec<u8> {
657    let mut out = Vec::with_capacity(64);
658    put_header(&mut out, id, 0, 1, 0, 0);
659    put_name(&mut out, &service_name(service));
660    put_u16(&mut out, TYPE_PTR);
661    put_u16(&mut out, CLASS_IN);
662    out
663}
664
665fn instance_name(advert: &Advert) -> Vec<String> {
666    let mut name = vec![label(&advert.instance)];
667    name.extend(service_name(advert.service));
668    name
669}
670
671fn host_name(advert: &Advert) -> Vec<String> {
672    vec![label(&advert.host), "local".to_string()]
673}
674
675fn put_header(out: &mut Vec<u8>, id: u16, flags: u16, questions: u16, answers: u16, extra: u16) {
676    for value in [id, flags, questions, answers, 0, extra] {
677        put_u16(out, value);
678    }
679}
680
681fn put_record(out: &mut Vec<u8>, name: &[String], rtype: u16, class: u16, ttl: u32, rdata: &[u8]) {
682    put_name(out, name);
683    put_u16(out, rtype);
684    put_u16(out, class);
685    out.extend_from_slice(&ttl.to_be_bytes());
686    put_u16(out, rdata.len() as u16);
687    out.extend_from_slice(rdata);
688}
689
690fn put_name(out: &mut Vec<u8>, labels: &[String]) {
691    for label in labels {
692        let label = &label.as_bytes()[..label.len().min(MAX_LABEL)];
693        out.push(label.len() as u8);
694        out.extend_from_slice(label);
695    }
696    out.push(0);
697}
698
699fn put_u16(out: &mut Vec<u8>, value: u16) {
700    out.extend_from_slice(&value.to_be_bytes());
701}
702
703struct Question {
704    name: Vec<String>,
705    qtype: u16,
706    qclass: u16,
707}
708
709struct Record {
710    name: Vec<String>,
711    rdata: Rdata,
712}
713
714enum Rdata {
715    Ptr(Vec<String>),
716    Srv { port: u16 },
717    Txt(Vec<Vec<u8>>),
718    Other,
719}
720
721/// A DNS message, read whole or not at all.
722struct Message {
723    id: u16,
724    flags: u16,
725    questions: Vec<Question>,
726    records: Vec<Record>,
727}
728
729impl Message {
730    fn id_of(packet: &[u8]) -> Option<u16> {
731        Some(u16::from_be_bytes([*packet.first()?, *packet.get(1)?]))
732    }
733
734    fn parse(packet: &[u8]) -> Option<Self> {
735        let mut at = 0;
736        let mut header = [0u16; 6];
737        for value in &mut header {
738            *value = read_u16(packet, &mut at)?;
739        }
740        let [id, flags, questions, answers, authority, additional] = header;
741        let mut message = Message {
742            id,
743            flags,
744            questions: Vec::new(),
745            records: Vec::new(),
746        };
747        for _ in 0..questions {
748            let name = read_name(packet, &mut at)?;
749            let qtype = read_u16(packet, &mut at)?;
750            let qclass = read_u16(packet, &mut at)?;
751            message.questions.push(Question {
752                name,
753                qtype,
754                qclass,
755            });
756        }
757        let records = u32::from(answers) + u32::from(authority) + u32::from(additional);
758        for _ in 0..records {
759            let name = read_name(packet, &mut at)?;
760            let rtype = read_u16(packet, &mut at)?;
761            let _class = read_u16(packet, &mut at)?;
762            at = at.checked_add(4)?;
763            let len = usize::from(read_u16(packet, &mut at)?);
764            let end = at.checked_add(len)?;
765            let rdata = packet.get(at..end)?;
766            let rdata = match rtype {
767                TYPE_PTR => {
768                    let mut inner = at;
769                    let target = read_name(packet, &mut inner)?;
770                    if inner > end {
771                        return None;
772                    }
773                    Rdata::Ptr(target)
774                }
775                TYPE_SRV => {
776                    let port = u16::from_be_bytes([*rdata.get(4)?, *rdata.get(5)?]);
777                    Rdata::Srv { port }
778                }
779                TYPE_TXT => Rdata::Txt(read_strings(rdata)?),
780                _ => Rdata::Other,
781            };
782            message.records.push(Record { name, rdata });
783            at = end;
784        }
785        Some(message)
786    }
787}
788
789fn read_u16(packet: &[u8], at: &mut usize) -> Option<u16> {
790    let bytes = packet.get(*at..at.checked_add(2)?)?;
791    *at += 2;
792    Some(u16::from_be_bytes([bytes[0], bytes[1]]))
793}
794
795/// Follows compression pointers, at most `MAX_JUMPS` of them, so a pointer
796/// loop ends; `at` moves past the name where it first appears.
797fn read_name(packet: &[u8], at: &mut usize) -> Option<Vec<String>> {
798    let mut labels = Vec::new();
799    let mut total = 0;
800    let mut pos = *at;
801    let mut jumps = 0;
802    let mut after: Option<usize> = None;
803    loop {
804        let len = *packet.get(pos)?;
805        match len & 0xC0 {
806            0xC0 => {
807                let low = *packet.get(pos + 1)?;
808                after.get_or_insert(pos + 2);
809                jumps += 1;
810                if jumps > MAX_JUMPS {
811                    return None;
812                }
813                pos = usize::from(u16::from_be_bytes([len & 0x3F, low]));
814            }
815            0x00 if len == 0 => {
816                after.get_or_insert(pos + 1);
817                break;
818            }
819            0x00 => {
820                let len = usize::from(len);
821                let bytes = packet.get(pos + 1..pos + 1 + len)?;
822                total += len + 1;
823                if total > MAX_NAME {
824                    return None;
825                }
826                labels.push(String::from_utf8(bytes.to_vec()).ok()?);
827                pos += 1 + len;
828            }
829            _ => return None,
830        }
831    }
832    *at = after?;
833    Some(labels)
834}
835
836fn read_strings(rdata: &[u8]) -> Option<Vec<Vec<u8>>> {
837    let mut strings = Vec::new();
838    let mut at = 0;
839    while at < rdata.len() {
840        let len = usize::from(rdata[at]);
841        let string = rdata.get(at + 1..at + 1 + len)?;
842        if !string.is_empty() {
843            strings.push(string.to_vec());
844        }
845        at += 1 + len;
846    }
847    Some(strings)
848}
849
850#[cfg(test)]
851mod tests {
852    use std::net::{Ipv4Addr, UdpSocket};
853    use std::sync::Mutex;
854    use std::sync::atomic::{AtomicUsize, Ordering};
855
856    use super::*;
857
858    /// Long enough for a loaded host to schedule the responder thread.
859    const FOUND_WINDOW: Duration = Duration::from_secs(3);
860    const NONE_WINDOW: Duration = Duration::from_millis(400);
861
862    fn loopback_responder(adverts: Adverts) -> Responder {
863        Responder::spawn(
864            &Net::Unicast(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))),
865            adverts,
866        )
867        .unwrap()
868    }
869
870    fn fixed(adverts: Vec<Advert>) -> Adverts {
871        Arc::new(move || adverts.clone())
872    }
873
874    fn browse_at(responder: &Responder, service: &str, window: Duration) -> Vec<Found> {
875        browse(&Net::Unicast(responder.local_addr()), service, window).unwrap()
876    }
877
878    #[test]
879    fn a_browse_finds_each_advert_of_its_service_at_the_responders_address() {
880        let responder = loopback_responder(fixed(vec![
881            device_advert("peer-1", "me", 2222),
882            pairing_advert("desk", "peer-1", 7201),
883        ]));
884        let found = browse_at(&responder, SERVICE, FOUND_WINDOW);
885        assert_eq!(found.len(), 1, "{found:?}");
886        assert_eq!(found[0].address, IpAddr::V4(Ipv4Addr::LOCALHOST));
887        assert_eq!(found[0].port, 2222);
888        assert_eq!(found[0].get(TXT_ID), Some("peer-1"));
889        assert_eq!(found[0].get(TXT_LOGIN), Some("me"));
890
891        let pairing = browse_at(&responder, PAIR_SERVICE, FOUND_WINDOW);
892        assert_eq!(pairing.len(), 1, "{pairing:?}");
893        assert_eq!(pairing[0].port, 7201);
894        assert_eq!(pairing[0].instance, "desk");
895        assert_eq!(pairing[0].get(TXT_ID), Some("peer-1"));
896        assert_eq!(pairing[0].get(TXT_LOGIN), None);
897    }
898
899    #[test]
900    fn an_advert_withdrawn_is_no_longer_found() {
901        let held = Arc::new(Mutex::new(vec![device_advert("peer-1", "me", 22)]));
902        let responder = loopback_responder({
903            let held = held.clone();
904            Arc::new(move || held.lock().unwrap().clone())
905        });
906        assert_eq!(browse_at(&responder, SERVICE, FOUND_WINDOW).len(), 1);
907        held.lock().unwrap().clear();
908        assert_eq!(
909            browse_at(&responder, SERVICE, NONE_WINDOW),
910            Vec::<Found>::new()
911        );
912    }
913
914    #[test]
915    fn a_query_for_another_name_is_not_answered_and_reads_no_adverts() {
916        let reads = Arc::new(AtomicUsize::new(0));
917        let responder = loopback_responder({
918            let reads = reads.clone();
919            Arc::new(move || {
920                reads.fetch_add(1, Ordering::SeqCst);
921                vec![device_advert("peer-1", "me", 22)]
922            })
923        });
924        assert_eq!(
925            browse_at(&responder, "_other._tcp", NONE_WINDOW),
926            Vec::<Found>::new()
927        );
928        let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
929        socket.send_to(b"not dns", responder.local_addr()).unwrap();
930        socket
931            .set_read_timeout(Some(Duration::from_millis(200)))
932            .unwrap();
933        assert!(socket.recv_from(&mut [0u8; 512]).is_err());
934        assert_eq!(reads.load(Ordering::SeqCst), 0);
935    }
936
937    #[test]
938    fn only_a_query_from_a_local_network_is_answered() {
939        let adverts = || vec![device_advert("peer-1", "me", 22)];
940        let asked = query(7, SERVICE);
941        let at = |ip: [u8; 4], port: u16| SocketAddr::from((Ipv4Addr::from(ip), port));
942        let group = Some(SocketAddr::from((GROUP, MDNS_PORT)));
943        for local in [
944            [192, 168, 1, 5],
945            [10, 0, 0, 2],
946            [169, 254, 3, 4],
947            [127, 0, 0, 1],
948        ] {
949            let (reply, to) = answer(&asked, at(local, 40000), group, &adverts)
950                .unwrap_or_else(|| panic!("{local:?} was not answered"));
951            assert_eq!(to, at(local, 40000), "a legacy query is answered directly");
952            assert_eq!(Message::id_of(&reply), Some(7));
953            assert_eq!(found_in(&reply, at(local, MDNS_PORT), SERVICE).len(), 1);
954        }
955        let (_, to) = answer(&asked, at([192, 168, 1, 5], MDNS_PORT), group, &adverts).unwrap();
956        assert_eq!(
957            Some(to),
958            group,
959            "a query from 5353 is answered to the group"
960        );
961        for remote in [[198, 51, 100, 7], [8, 8, 8, 8], [100, 64, 0, 1]] {
962            assert!(answer(&asked, at(remote, 40000), group, &adverts).is_none());
963        }
964    }
965
966    /// A responder that answers one query with `id`, or with the query's own
967    /// id when None.
968    fn replying_with_id(id: Option<u16>) -> (SocketAddr, std::thread::JoinHandle<()>) {
969        let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
970        socket
971            .set_read_timeout(Some(Duration::from_secs(10)))
972            .unwrap();
973        let at = socket.local_addr().unwrap();
974        let thread = std::thread::spawn(move || {
975            let mut buf = [0u8; 512];
976            let Ok((len, from)) = socket.recv_from(&mut buf) else {
977                return;
978            };
979            let id = id.unwrap_or_else(|| Message::id_of(&buf[..len]).unwrap());
980            let advert = device_advert("peer-1", "me", 22);
981            let reply = Reply {
982                answers: vec![Answer::Ptr(&advert)],
983                additional: vec![Answer::Srv(&advert), Answer::Txt(&advert)],
984                ..Reply::default()
985            }
986            .write(id, None, UNICAST_TTL, false);
987            socket.send_to(&reply, from).unwrap();
988        });
989        (at, thread)
990    }
991
992    #[test]
993    fn a_reply_without_the_querys_id_is_dropped() {
994        let (at, thread) = replying_with_id(None);
995        assert_eq!(
996            browse(&Net::Unicast(at), SERVICE, FOUND_WINDOW)
997                .unwrap()
998                .len(),
999            1
1000        );
1001        thread.join().unwrap();
1002        let (at, thread) = replying_with_id(Some(0));
1003        assert_eq!(
1004            browse(&Net::Unicast(at), SERVICE, NONE_WINDOW).unwrap(),
1005            Vec::<Found>::new()
1006        );
1007        thread.join().unwrap();
1008    }
1009
1010    #[test]
1011    fn a_machine_id_longer_than_a_label_is_found_whole() {
1012        let id = "m".repeat(128);
1013        let responder = loopback_responder(fixed(vec![device_advert(&id, "me", 22)]));
1014        let found = browse_at(&responder, SERVICE, FOUND_WINDOW);
1015        assert_eq!(found.len(), 1, "{found:?}");
1016        assert_eq!(found[0].get(TXT_ID), Some(id.as_str()));
1017        assert_eq!(found[0].instance.len(), 63);
1018    }
1019
1020    #[test]
1021    fn a_responder_is_stopped_by_dropping_it() {
1022        let responder = loopback_responder(fixed(vec![device_advert("peer-1", "me", 22)]));
1023        let net = Net::Unicast(responder.local_addr());
1024        drop(responder);
1025        assert_eq!(
1026            browse(&net, SERVICE, NONE_WINDOW).unwrap(),
1027            Vec::<Found>::new()
1028        );
1029    }
1030
1031    fn asking(id: u16, questions: &[(Vec<String>, u16, u16)]) -> Vec<u8> {
1032        let mut out = Vec::new();
1033        put_header(&mut out, id, 0, questions.len() as u16, 0, 0);
1034        for (name, qtype, qclass) in questions {
1035            put_name(&mut out, name);
1036            put_u16(&mut out, *qtype);
1037            put_u16(&mut out, *qclass);
1038        }
1039        out
1040    }
1041
1042    fn host_of(advert: &Advert) -> Vec<String> {
1043        vec![advert.host.clone(), "local".to_string()]
1044    }
1045
1046    struct Decoded {
1047        answer: bool,
1048        name: Vec<String>,
1049        rtype: u16,
1050        class: u16,
1051        rdata: std::ops::Range<usize>,
1052    }
1053
1054    /// Every record of a reply with its section, type and class, which
1055    /// `Message::parse` does not keep.
1056    fn decoded(packet: &[u8]) -> Vec<Decoded> {
1057        let mut at = 0;
1058        let mut header = [0u16; 6];
1059        for value in &mut header {
1060            *value = read_u16(packet, &mut at).unwrap();
1061        }
1062        for _ in 0..header[2] {
1063            read_name(packet, &mut at).unwrap();
1064            at += 4;
1065        }
1066        let mut out = Vec::new();
1067        for index in 0..header[3] + header[4] + header[5] {
1068            let name = read_name(packet, &mut at).unwrap();
1069            let rtype = read_u16(packet, &mut at).unwrap();
1070            let class = read_u16(packet, &mut at).unwrap();
1071            at += 4;
1072            let len = usize::from(read_u16(packet, &mut at).unwrap());
1073            out.push(Decoded {
1074                answer: index < header[3],
1075                name,
1076                rtype,
1077                class,
1078                rdata: at..at + len,
1079            });
1080            at += len;
1081        }
1082        assert_eq!(at, packet.len());
1083        out
1084    }
1085
1086    fn srv_targets(packet: &[u8]) -> Vec<Vec<String>> {
1087        decoded(packet)
1088            .into_iter()
1089            .filter(|r| r.rtype == TYPE_SRV)
1090            .map(|r| read_name(packet, &mut (r.rdata.start + 6)).unwrap())
1091            .collect()
1092    }
1093
1094    fn addresses_of(packet: &[u8], host: &[String]) -> Vec<Ipv4Addr> {
1095        decoded(packet)
1096            .into_iter()
1097            .filter(|r| r.rtype == TYPE_A && same_labels(&r.name, host))
1098            .map(|r| <[u8; 4]>::try_from(&packet[r.rdata]).unwrap().into())
1099            .collect()
1100    }
1101
1102    fn types_in(packet: &[u8], answer: bool) -> Vec<u16> {
1103        decoded(packet)
1104            .into_iter()
1105            .filter(|r| r.answer == answer)
1106            .map(|r| r.rtype)
1107            .collect()
1108    }
1109
1110    /// mDNSResponder browses with a PTR query from port 5353, then asks for
1111    /// whichever SRV, TXT or A record its cache lacks; a unicast-response
1112    /// question keeps the replies on loopback here.
1113    #[test]
1114    fn a_mac_shaped_lookup_gets_the_srv_txt_and_address_of_the_srv_target() {
1115        let advert = device_advert("peer-1", "me", 2222);
1116        let adverts = {
1117            let advert = advert.clone();
1118            move || vec![advert.clone()]
1119        };
1120        let group = Some(SocketAddr::from((GROUP, MDNS_PORT)));
1121        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, MDNS_PORT));
1122        let host = host_of(&advert);
1123        let ask = |name: Vec<String>, qtype: u16| {
1124            let query = asking(0, &[(name, qtype, CLASS_IN | UNICAST_RESPONSE)]);
1125            let (reply, to) = answer(&query, from, group, &adverts)
1126                .unwrap_or_else(|| panic!("type {qtype} was not answered"));
1127            assert_eq!(to, from);
1128            for record in decoded(&reply) {
1129                let shared = record.rtype == TYPE_PTR;
1130                assert_eq!(
1131                    record.class,
1132                    if shared {
1133                        CLASS_IN
1134                    } else {
1135                        CLASS_IN | CACHE_FLUSH
1136                    },
1137                    "type {}",
1138                    record.rtype
1139                );
1140            }
1141            reply
1142        };
1143
1144        let browsed = ask(service_name(SERVICE), TYPE_PTR);
1145        assert_eq!(found_in(&browsed, from, SERVICE).len(), 1);
1146        assert_eq!(types_in(&browsed, true), [TYPE_PTR]);
1147        assert_eq!(types_in(&browsed, false), [TYPE_SRV, TYPE_TXT, TYPE_A]);
1148        assert_eq!(srv_targets(&browsed), std::slice::from_ref(&host));
1149        assert_eq!(addresses_of(&browsed, &host), [Ipv4Addr::LOCALHOST]);
1150
1151        let srv = ask(instance_name(&advert), TYPE_SRV);
1152        assert_eq!(types_in(&srv, true), [TYPE_SRV]);
1153        assert_eq!(types_in(&srv, false), [TYPE_A]);
1154        assert_eq!(addresses_of(&srv, &host), [Ipv4Addr::LOCALHOST]);
1155
1156        let txt = ask(instance_name(&advert), TYPE_TXT);
1157        assert_eq!(types_in(&txt, true), [TYPE_TXT]);
1158        let record = decoded(&txt).remove(0);
1159        let strings = read_strings(&txt[record.rdata]).unwrap();
1160        assert_eq!(
1161            txt_map(&strings).get(TXT_ID).map(String::as_str),
1162            Some("peer-1")
1163        );
1164
1165        let any = ask(instance_name(&advert), TYPE_ANY);
1166        assert_eq!(types_in(&any, true), [TYPE_SRV, TYPE_TXT]);
1167        assert_eq!(types_in(&any, false), [TYPE_A]);
1168
1169        let address = ask(host.clone(), TYPE_A);
1170        assert_eq!(types_in(&address, true), [TYPE_A]);
1171        assert_eq!(addresses_of(&address, &host), [Ipv4Addr::LOCALHOST]);
1172    }
1173
1174    #[test]
1175    fn a_reply_to_the_group_carries_the_address_it_leaves_from() {
1176        let advert = device_advert("peer-1", "me", 22);
1177        let adverts = {
1178            let advert = advert.clone();
1179            move || vec![advert.clone()]
1180        };
1181        let group = SocketAddr::from((GROUP, MDNS_PORT));
1182        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, MDNS_PORT));
1183        let query = asking(0, &[(instance_name(&advert), TYPE_SRV, CLASS_IN)]);
1184        let (reply, to) = answer(&query, from, Some(group), &adverts).unwrap();
1185        assert_eq!(to, group);
1186        let toward_group: Vec<Ipv4Addr> = route_toward(group.ip()).into_iter().collect();
1187        assert_eq!(addresses_of(&reply, &host_of(&advert)), toward_group);
1188        assert!(!toward_group.contains(&Ipv4Addr::LOCALHOST));
1189    }
1190
1191    #[test]
1192    fn a_reply_without_an_address_writes_no_a_record() {
1193        let advert = device_advert("peer-1", "me", 22);
1194        let mut reply = Reply::default();
1195        let host = Question {
1196            name: host_of(&advert),
1197            qtype: TYPE_A,
1198            qclass: CLASS_IN,
1199        };
1200        assert_eq!(reply.answer(&host, &advert), (false, true));
1201        let browse = Question {
1202            name: service_name(SERVICE),
1203            qtype: TYPE_PTR,
1204            qclass: CLASS_IN,
1205        };
1206        assert_eq!(reply.answer(&browse, &advert), (true, false));
1207        reply.complete(None);
1208        let written = reply.write(0, None, MULTICAST_TTL, true);
1209        assert_eq!(types_in(&written, true), [TYPE_PTR]);
1210        assert_eq!(types_in(&written, false), [TYPE_SRV, TYPE_TXT]);
1211
1212        let mut host_only = Reply::default();
1213        host_only.answer(&host, &advert);
1214        host_only.complete(None);
1215        assert!(host_only.answers.is_empty());
1216    }
1217
1218    #[test]
1219    fn without_a_route_a_host_question_is_neither_echoed_nor_answered() {
1220        let advert = device_advert("peer-1", "me", 22);
1221        let adverts = {
1222            let advert = advert.clone();
1223            move || vec![advert.clone()]
1224        };
1225        let no_route = |_: IpAddr| None;
1226        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, 40000));
1227        let host = (host_of(&advert), TYPE_A, CLASS_IN);
1228        let browse = (service_name(SERVICE), TYPE_PTR, CLASS_IN);
1229
1230        let query = asking(9, &[host.clone(), browse]);
1231        let (reply, to) = answer_routed(&query, from, None, &adverts, &no_route).unwrap();
1232        assert_eq!(to, from);
1233        let message = Message::parse(&reply).unwrap();
1234        assert!(same_labels(
1235            &message.questions[0].name,
1236            &service_name(SERVICE)
1237        ));
1238        assert_eq!(types_in(&reply, true), [TYPE_PTR]);
1239        assert_eq!(types_in(&reply, false), [TYPE_SRV, TYPE_TXT]);
1240
1241        let query = asking(9, &[host]);
1242        assert!(answer_routed(&query, from, None, &adverts, &no_route).is_none());
1243    }
1244
1245    #[test]
1246    fn a_legacy_query_echoes_its_first_answered_question() {
1247        let advert = device_advert("peer-1", "me", 22);
1248        let adverts = {
1249            let advert = advert.clone();
1250            move || vec![advert.clone()]
1251        };
1252        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, 40000));
1253        let other = device_advert("peer-2", "me", 22);
1254        let query = asking(
1255            9,
1256            &[
1257                (instance_name(&other), TYPE_SRV, CLASS_IN),
1258                (instance_name(&advert), TYPE_SRV, CLASS_IN),
1259            ],
1260        );
1261        let (reply, to) = answer(&query, from, None, &adverts).unwrap();
1262        assert_eq!(to, from);
1263        let message = Message::parse(&reply).unwrap();
1264        assert_eq!(message.id, 9);
1265        assert_eq!(message.questions.len(), 1);
1266        assert!(same_labels(
1267            &message.questions[0].name,
1268            &instance_name(&advert)
1269        ));
1270        assert_eq!(types_in(&reply, true), [TYPE_SRV]);
1271        assert!(decoded(&reply).iter().all(|r| r.class == CLASS_IN));
1272    }
1273
1274    #[test]
1275    fn no_srv_target_is_a_machine_name_another_responder_may_own() {
1276        let pairing = pairing_advert("desk", "peer-1", 7201);
1277        let device = device_advert("peer-1", "me", 22);
1278        assert_eq!(pairing.host, device.host);
1279        assert!(pairing.host.starts_with(HOST_PREFIX), "{}", pairing.host);
1280        assert!(device_advert(&"m".repeat(128), "me", 22).host.len() <= MAX_LABEL);
1281    }
1282
1283    #[test]
1284    fn a_query_for_a_host_name_not_ours_is_not_answered_and_reads_no_adverts() {
1285        let reads = AtomicUsize::new(0);
1286        let adverts = || {
1287            reads.fetch_add(1, Ordering::SeqCst);
1288            vec![pairing_advert("desk", "peer-1", 7201)]
1289        };
1290        let from = SocketAddr::from((Ipv4Addr::LOCALHOST, MDNS_PORT));
1291        for name in [
1292            vec!["desk".to_string(), "local".to_string()],
1293            vec!["peer-1".to_string(), "local".to_string()],
1294            vec![
1295                "desk".to_string(),
1296                "_other._tcp".to_string(),
1297                "local".to_string(),
1298            ],
1299        ] {
1300            for qtype in [TYPE_A, TYPE_SRV, TYPE_TXT, TYPE_ANY] {
1301                let query = asking(0, &[(name.clone(), qtype, CLASS_IN)]);
1302                assert!(answer(&query, from, None, &adverts).is_none());
1303            }
1304        }
1305        assert_eq!(reads.load(Ordering::SeqCst), 0);
1306    }
1307
1308    fn from() -> SocketAddr {
1309        SocketAddr::from((Ipv4Addr::new(192, 0, 2, 7), 5353))
1310    }
1311
1312    fn put_labels(out: &mut Vec<u8>, labels: &[&str]) {
1313        for label in labels {
1314            out.push(label.len() as u8);
1315            out.extend_from_slice(label.as_bytes());
1316        }
1317    }
1318
1319    fn record_header(out: &mut Vec<u8>, rtype: u16, rdata_len: usize) {
1320        out.extend_from_slice(&rtype.to_be_bytes());
1321        out.extend_from_slice(&0x8001u16.to_be_bytes());
1322        out.extend_from_slice(&120u32.to_be_bytes());
1323        out.extend_from_slice(&(rdata_len as u16).to_be_bytes());
1324    }
1325
1326    /// A response the way other responders write it: names compressed
1327    /// against earlier ones, and the SRV and TXT in the answer section.
1328    fn compressed_response() -> Vec<u8> {
1329        let mut out = vec![0, 0, 0x84, 0, 0, 0, 0, 3, 0, 0, 0, 0];
1330        let service_at = out.len() as u16;
1331        put_labels(&mut out, &["_second-brain", "_tcp", "local"]);
1332        out.push(0);
1333        let service_ptr = [0xC0 | (service_at >> 8) as u8, service_at as u8];
1334        record_header(&mut out, 12, 1 + 4 + 2);
1335        let instance_at = out.len() as u16;
1336        put_labels(&mut out, &["peer"]);
1337        out.extend_from_slice(&service_ptr);
1338        let instance_ptr = [0xC0 | (instance_at >> 8) as u8, instance_at as u8];
1339
1340        out.extend_from_slice(&instance_ptr);
1341        let target = {
1342            let mut t = Vec::new();
1343            put_labels(&mut t, &["peer"]);
1344            t.extend_from_slice(&[0xC0, 12 + 1 + 13 + 1 + 4]);
1345            t
1346        };
1347        record_header(&mut out, 33, 6 + target.len());
1348        out.extend_from_slice(&[0, 0, 0, 0]);
1349        out.extend_from_slice(&2222u16.to_be_bytes());
1350        out.extend_from_slice(&target);
1351
1352        out.extend_from_slice(&instance_ptr);
1353        let txt: &[&[u8]] = &[b"id=peer", b"login=me", b"id=shadowed", b"flag"];
1354        record_header(&mut out, 16, txt.iter().map(|s| s.len() + 1).sum());
1355        for string in txt {
1356            out.push(string.len() as u8);
1357            out.extend_from_slice(string);
1358        }
1359        out
1360    }
1361
1362    #[test]
1363    fn a_response_with_compressed_names_is_read() {
1364        let found = found_in(&compressed_response(), from(), SERVICE);
1365        assert_eq!(found.len(), 1, "{found:?}");
1366        assert_eq!(found[0].instance, "peer");
1367        assert_eq!(found[0].address, from().ip());
1368        assert_eq!(found[0].port, 2222);
1369        assert_eq!(found[0].get(TXT_ID), Some("peer"));
1370        assert_eq!(found[0].get(TXT_LOGIN), Some("me"));
1371        assert_eq!(found[0].get("flag"), Some(""));
1372        assert!(found_in(&compressed_response(), from(), PAIR_SERVICE).is_empty());
1373    }
1374
1375    #[test]
1376    fn a_truncated_or_looping_packet_yields_nothing() {
1377        let whole = compressed_response();
1378        for end in 0..whole.len() {
1379            assert!(
1380                found_in(&whole[..end], from(), SERVICE).is_empty(),
1381                "a response cut at {end} bytes was read"
1382            );
1383        }
1384        let mut looping = vec![0, 0, 0x84, 0, 0, 0, 0, 1, 0, 0, 0, 0];
1385        looping.extend_from_slice(&[0xC0, 12]);
1386        record_header(&mut looping, 12, 2);
1387        looping.extend_from_slice(&[0xC0, 12]);
1388        assert!(found_in(&looping, from(), SERVICE).is_empty());
1389        let mut query = compressed_response();
1390        query[2] = 0;
1391        assert!(found_in(&query, from(), SERVICE).is_empty());
1392    }
1393}