Skip to main content

rtci_mdns/proto/
mod.rs

1//! The Sans-I/O mDNS connection.
2//!
3//! This module is private; [`Mdns`] is re-exported as [`crate::Mdns`], where its
4//! documentation and examples live so that rustdoc renders them and their doctests run.
5//!
6//! The connection is a resolver (`resolver.rs`: query series, the address cache) and a
7//! responder for unique host-name records (`responder.rs`: probing, announcing, answering,
8//! goodbyes), over the message reader and writer of `wire.rs` and the message budget of
9//! `rate.rs`. Every decision is made against the instant the caller supplied.
10
11mod rate;
12mod reconfirm;
13mod resolver;
14mod responder;
15pub(crate) mod wire;
16
17use std::collections::VecDeque;
18use std::net::{IpAddr, Ipv4Addr, SocketAddr};
19use std::time::{Duration, Instant};
20
21use bytes::BytesMut;
22use shared::{TaggedBytesMut, TransportContext, TransportMessage, TransportProtocol};
23
24use crate::config::{DEFAULT_QUERY_INTERVAL, MdnsConfig};
25use crate::message::RCode;
26use rate::Jitter;
27use reconfirm::Reconfirm;
28use resolver::{Cached, Query};
29use responder::{Goodbye, LocalRecord};
30use shared::error::{Error, Result};
31
32pub use rate::MdnsRateLimit;
33
34/// The mDNS multicast group address (224.0.0.251).
35pub const MDNS_MULTICAST_IPV4: Ipv4Addr = Ipv4Addr::new(224, 0, 0, 251);
36
37/// The standard mDNS port (5353).
38pub const MDNS_PORT: u16 = 5353;
39
40/// mDNS multicast destination address (224.0.0.251:5353).
41///
42/// All mDNS queries and multicast responses are sent to this address.
43///
44/// # Example
45///
46/// ```rust
47/// use rtci_mdns::MDNS_DEST_ADDR;
48///
49/// assert_eq!(MDNS_DEST_ADDR.to_string(), "224.0.0.251:5353");
50/// ```
51pub const MDNS_DEST_ADDR: SocketAddr = SocketAddr::new(IpAddr::V4(MDNS_MULTICAST_IPV4), MDNS_PORT);
52
53/// The most names [`Mdns::add_local_name`] registers: one per local address is the use, and a
54/// host has a handful.
55pub const MAX_LOCAL_NAMES: usize = 64;
56
57/// The most addresses the resolver's cache holds. Any host on the link can offer records, so
58/// the cache is bounded: when it is full, the entry nearest its expiry gives way to one that
59/// lives longer.
60pub const MAX_CACHED_ADDRESSES: usize = 256;
61
62/// The longest a cached address is kept, whatever TTL it came with: 75 minutes, the TTL
63/// RFC 6762 section 10 recommends for records that are not host names.
64const CACHE_TTL_CAP: u32 = 75 * 60;
65
66/// Query intervals double up to one hour (RFC 6762 section 5.2).
67const MAX_QUERY_INTERVAL: Duration = Duration::from_secs(60 * 60);
68
69/// Packets waiting for `poll_write`. With this many unsent, nothing more is queued until the
70/// caller drains them.
71const MAX_QUEUED_PACKETS: usize = 256;
72
73/// How long sending is put off when the write queue is full.
74const QUEUE_FULL_RETRY: Duration = Duration::from_secs(1);
75
76/// Unique identifier for tracking mDNS queries.
77///
78/// Each call to [`Mdns::query_now()`] returns a unique ID that can be used to:
79/// - Track which query was answered in [`MdnsEvent::QueryAnswered`]
80/// - Cancel a pending query with [`Mdns::cancel_query()`]
81/// - Check if a query is still pending with [`Mdns::is_query_pending()`]
82pub type QueryId = u64;
83
84/// When something is to be done: at an instant, or as soon as the caller next gives the time
85/// (what a method that takes no `now` leaves behind).
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub(crate) enum When {
88    Asap,
89    At(Instant),
90}
91
92impl When {
93    fn due(self, now: Instant) -> bool {
94        matches!(self, When::At(at) if at <= now)
95    }
96}
97
98/// Events emitted by the mDNS connection.
99///
100/// Poll for events using [`poll_event()`](sansio::Protocol::poll_event) after
101/// calling [`handle_read()`](sansio::Protocol::handle_read) or
102/// [`handle_timeout()`](sansio::Protocol::handle_timeout).
103///
104/// # Example
105///
106/// ```rust,ignore
107/// while let Some(event) = mdns.poll_event() {
108///     match event {
109///         MdnsEvent::QueryAnswered(query_id, addr) => {
110///             println!("Query {} resolved to {}", query_id, addr);
111///         }
112///         MdnsEvent::QueryTimeout(query_id) => {
113///             println!("Query {} timed out", query_id);
114///         }
115///         _ => {}
116///     }
117/// }
118/// ```
119#[derive(Debug)]
120#[non_exhaustive]
121pub enum MdnsEvent {
122    /// A query was successfully answered.
123    ///
124    /// Contains the query ID and the resolved IP address.
125    /// The query is automatically removed from the pending list.
126    QueryAnswered(QueryId, IpAddr),
127
128    /// A query ended without an address.
129    ///
130    /// Emitted when the query's timeout passed
131    /// ([`MdnsConfig::query_timeout`](crate::MdnsConfig::query_timeout), 30 seconds unless
132    /// changed), when a response gave the name more than one address and
133    /// [`MdnsConfig::with_multiple_addresses`](crate::MdnsConfig::with_multiple_addresses) is
134    /// off, or when the name's owner said it has no address record. The query is removed from
135    /// the pending list when this event is emitted.
136    ///
137    /// ```rust
138    /// use rtci_mdns::MdnsConfig;
139    /// use std::time::Duration;
140    ///
141    /// let config = MdnsConfig::default()
142    ///     .with_query_timeout(Duration::from_secs(5));
143    /// ```
144    QueryTimeout(QueryId),
145
146    /// A name of ours is in use by another host and has been given up (RFC 6762 section 9):
147    /// probing for it met a defender. The name is no longer answered; it is given as it was
148    /// registered. Register another name in its place.
149    LocalNameConflict(String),
150}
151
152/// Sans-I/O mDNS Connection.
153///
154/// This implements a sans-I/O mDNS resolver and host-name responder (RFC 6762, as far as
155/// draft-ietf-mmusic-mdns-ice-candidates uses it):
156///
157/// - **Resolver**: a query asks for a name's A and AAAA records, one question a message, and is
158///   retried at doubling intervals until it is answered or times out. Answers are cached for their TTL, so a name
159///   seen in an announcement or resolved before answers at once.
160/// - **Responder**: each local name owns one address record. A name is probed for unless it is
161///   a random `<uuid>.local` name, announced twice, answered (by multicast at most once a
162///   second per record, or by unicast where the querier asked), defended against probes, and
163///   withdrawn with a goodbye when it is removed or the connection closes.
164/// - Every message sent draws on one budget ([`MdnsRateLimit`]).
165///
166/// # Sans-I/O Pattern
167///
168/// This struct implements [`sansio::Protocol`], which means it doesn't perform
169/// any I/O itself. Instead, the caller is responsible for:
170///
171/// 1. Calling [`handle_read()`](sansio::Protocol::handle_read) when packets arrive
172/// 2. Sending packets from [`poll_write()`](sansio::Protocol::poll_write)
173/// 3. Calling [`handle_timeout()`](sansio::Protocol::handle_timeout) on schedule
174/// 4. Processing events from [`poll_event()`](sansio::Protocol::poll_event)
175///
176/// The socket is the application's: bound to port 5353, joined to 224.0.0.251
177/// ([`MulticastSocket`](crate::MulticastSocket)). Give `handle_read` each datagram with its
178/// source in `peer_addr`. Every datagram is taken to have arrived on the group, unless the
179/// application reports destinations
180/// ([`MdnsConfig::with_destination_reported`]): then `local_addr` is the datagram's
181/// destination address, and one sent to the host by unicast is treated as RFC 6762 treats
182/// unicast queries and responses.
183///
184/// # Example: Complete Event Loop
185///
186/// ```rust
187/// use rtci_mdns::{MdnsConfig, Mdns, MdnsEvent};
188/// use sansio::Protocol;
189/// use std::time::{Duration, Instant};
190///
191/// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
192///
193/// // Start a query
194/// let query_id = mdns.query_now(Instant::now(), "device.local");
195///
196/// // Simulate an event loop iteration
197/// let now = Instant::now();
198///
199/// // 1. Send queued packets (would go to network in real code)
200/// while let Some(packet) = mdns.poll_write() {
201///     println!("Would send {} bytes to {}", packet.message.len(), packet.transport.peer_addr);
202/// }
203///
204/// // 2. Handle timeout if due
205/// if let Some(deadline) = mdns.poll_timeout() {
206///     if deadline <= now {
207///         mdns.handle_timeout(now).ok();
208///     }
209/// }
210///
211/// // 3. Process any events
212/// while let Some(event) = mdns.poll_event() {
213///     match event {
214///         MdnsEvent::QueryAnswered(query_id, addr) => {
215///             println!("Query {} answered: {}", query_id, addr);
216///         }
217///         MdnsEvent::QueryTimeout(id) => {
218///             println!("Query {} timed out", id);
219///         }
220///         // MdnsEvent is #[non_exhaustive]: a wildcard arm is required.
221///         _ => {}
222///     }
223/// }
224/// ```
225///
226/// # Example: Multiple Concurrent Queries
227///
228/// ```rust
229/// # use std::time::Instant;
230/// use rtci_mdns::{MdnsConfig, Mdns};
231/// use sansio::Protocol;
232///
233/// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
234///
235/// // Start multiple queries - each gets a unique ID
236/// let id1 = mdns.query_now(Instant::now(), "printer.local");
237/// let id2 = mdns.query_now(Instant::now(), "server.local");
238/// let id3 = mdns.query_now(Instant::now(), "nas.local");
239///
240/// assert_eq!(mdns.pending_query_count(), 3);
241/// assert!(mdns.is_query_pending(id1));
242/// assert!(mdns.is_query_pending(id2));
243/// assert!(mdns.is_query_pending(id3));
244///
245/// // Cancel one query
246/// mdns.cancel_query(id2);
247/// assert_eq!(mdns.pending_query_count(), 2);
248/// assert!(!mdns.is_query_pending(id2));
249/// ```
250///
251/// # Query Lifecycle
252///
253/// 1. Call [`Mdns::query_now()`] (sent at once) or [`Mdns::schedule_query()`] (sent from the
254///    next `handle_timeout`; after a random 20 to 120 ms with
255///    [`MdnsConfig::with_first_query_delay`]) with the hostname to resolve
256/// 2. Retrieve the query packets (the A question, then the AAAA question) from
257///    [`poll_write()`](sansio::Protocol::poll_write)
258/// 3. Send the packets to the mDNS multicast address
259/// 4. When responses arrive, pass them to [`handle_read()`](sansio::Protocol::handle_read)
260/// 5. Check [`poll_event()`](sansio::Protocol::poll_event) for [`MdnsEvent::QueryAnswered`]
261/// 6. Call [`handle_timeout()`](sansio::Protocol::handle_timeout) when
262///    [`poll_timeout()`](sansio::Protocol::poll_timeout) says so: retries go out after 1, 2,
263///    4, ... seconds, and the query ends with [`MdnsEvent::QueryTimeout`] at its timeout
264///
265/// # Name Lifecycle
266///
267/// A name given in [`MdnsConfig::with_local_names`] or to [`Mdns::add_local_name`] starts at
268/// the next `handle_timeout`: three probes 250 ms apart unless the name is exempt
269/// ([`MdnsProbePolicy`](crate::MdnsProbePolicy)), then two announcements one second apart. A
270/// name that is not probed for is answered from the moment it is registered.
271/// [`Mdns::remove_local_name`] and [`close()`](sansio::Protocol::close) send goodbyes;
272/// [`Mdns::network_changed`] starts every name over.
273pub struct Mdns {
274    config: MdnsConfig,
275
276    /// The configured local names with trailing dots, as given.
277    local_names: Vec<String>,
278
279    /// The records this connection owns: the configured names (when a local IP is configured)
280    /// and those registered with [`Mdns::add_local_name`].
281    records: Vec<LocalRecord>,
282
283    /// Goodbyes still to send for removed names. At most [`MAX_LOCAL_NAMES`].
284    goodbyes: Vec<Goodbye>,
285
286    /// The times of the latest name conflicts, at most [`responder::CONFLICT_LIMIT`].
287    conflicts: VecDeque<Instant>,
288
289    /// Pending queries.
290    queries: Vec<Query>,
291
292    /// Addresses learned from responses. At most [`MAX_CACHED_ADDRESSES`].
293    cache: Vec<Cached>,
294
295    /// Cached names being reconfirmed (RFC 6762 section 10.4).
296    reconfirms: Vec<Reconfirm>,
297
298    /// Next query ID to assign
299    next_query_id: QueryId,
300
301    /// The interval between the first two queries of a series.
302    query_interval: Duration,
303
304    /// Query timeout (None = no automatic timeout)
305    query_timeout: Option<Duration>,
306
307    limiter: MdnsRateLimit,
308    jitter: Jitter,
309
310    /// Set by a flush that could not send: when sending can go on.
311    blocked_until: Option<Instant>,
312
313    /// Outgoing packet queue
314    write_outs: VecDeque<TaggedBytesMut>,
315
316    /// Event queue
317    event_outs: VecDeque<MdnsEvent>,
318
319    /// The next instant anything is due.
320    next_timeout: Option<Instant>,
321
322    /// Whether anything waits for the caller to give the time.
323    asap: bool,
324
325    last_now: Instant,
326
327    /// Whether the connection is closed
328    closed: bool,
329}
330
331/// `name` with a trailing dot, and that in ASCII lower case: DNS names compare without regard
332/// to ASCII case (RFC 1035 section 2.3.3).
333fn normalize(name: &str) -> (String, String) {
334    let name = if name.ends_with('.') {
335        name.to_owned()
336    } else {
337        format!("{name}.")
338    };
339    let key = name.to_ascii_lowercase();
340    (name, key)
341}
342
343impl Mdns {
344    /// Feeds a received datagram together with the destination address of its IP header, as
345    /// the driver reads it (`IP_PKTINFO`, `IPV6_PKTINFO`, `IP_RECVDSTADDR`). With it the RFC
346    /// 6762 rules that turn on the destination apply exactly:
347    ///
348    /// - section 6: a response that arrived by unicast is taken only for a recent question
349    ///   asked with the QU bit; others are ignored;
350    /// - section 11: a response that arrived at the mDNS multicast address (224.0.0.251 or
351    ///   FF02::FB) "originated on the local link, regardless of source IP address"; one that
352    ///   arrived by unicast is held to the on-link test.
353    ///
354    /// [`handle_read`](sansio::Protocol::handle_read) is the same without a known
355    /// destination: then the address scope of the source decides (see
356    /// [`MdnsConfig::with_on_link_subnets`]).
357    ///
358    /// # Errors
359    ///
360    /// As `handle_read`.
361    pub fn handle_datagram(&mut self, msg: TaggedBytesMut, destination: IpAddr) -> Result<()> {
362        if self.closed {
363            return Err(Error::ErrConnectionClosed);
364        }
365        self.last_now = msg.now;
366        self.process_message(&msg, Some(destination));
367        self.flush(msg.now);
368        self.update_next_timeout();
369        Ok(())
370    }
371
372    /// Create a new mDNS connection with the given configuration.
373    ///
374    /// # Arguments
375    ///
376    /// * `now` - The current time
377    /// * `config` - MdnsConfiguration for the connection
378    ///
379    /// # Example
380    ///
381    /// ```rust
382    /// use rtci_mdns::{MdnsConfig, Mdns};
383    /// use std::time::{Duration, Instant};
384    ///
385    /// // Client-only configuration
386    /// let client = Mdns::new(Instant::now(), MdnsConfig::default());
387    ///
388    /// // Server configuration
389    /// use std::net::{IpAddr, Ipv4Addr};
390    /// let server = Mdns::new(
391    ///     Instant::now(),
392    ///     MdnsConfig::default()
393    ///         .with_local_names(vec!["myhost.local".to_string()])
394    ///         .with_local_ip(
395    ///             IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)),
396    ///         )
397    /// );
398    /// ```
399    pub fn new(now: Instant, config: MdnsConfig) -> Self {
400        let query_interval = if config.query_interval == Duration::ZERO {
401            DEFAULT_QUERY_INTERVAL
402        } else {
403            // RFC 6762 section 5.2: at least one second between the first two queries, and
404            // no need for more than an hour.
405            config
406                .query_interval
407                .clamp(DEFAULT_QUERY_INTERVAL, MAX_QUERY_INTERVAL)
408        };
409
410        let mut mdns = Self {
411            local_names: Vec::new(),
412            records: Vec::new(),
413            goodbyes: Vec::new(),
414            conflicts: VecDeque::new(),
415            queries: Vec::new(),
416            cache: Vec::new(),
417            reconfirms: Vec::new(),
418            next_query_id: 1,
419            query_interval,
420            query_timeout: config.query_timeout,
421            limiter: config.rate_limit.clone().unwrap_or_default(),
422            jitter: Jitter::new(config.jitter_seed),
423            blocked_until: None,
424            write_outs: VecDeque::new(),
425            event_outs: VecDeque::new(),
426            next_timeout: None,
427            asap: false,
428            last_now: now,
429            closed: false,
430            config,
431        };
432
433        if !mdns.config.local_names.is_empty() && mdns.config.local_ip.is_none() {
434            log::warn!("mDNS local names are configured without a local IP: they are not answered");
435        }
436        for name in mdns.config.local_names.clone() {
437            let (name, key) = normalize(&name);
438            mdns.local_names.push(name.clone());
439            if let Some(ip) = mdns.config.local_ip
440                && !mdns.records.iter().any(|r| r.key == key)
441            {
442                match mdns.new_record(name, key, ip, false) {
443                    Some(record) => mdns.records.push(record),
444                    None => log::warn!("mDNS cannot publish a configured name: not a DNS name"),
445                }
446            }
447        }
448        mdns.update_next_timeout();
449        mdns
450    }
451
452    /// Answers queries for `name` with `ip` from now on: an A record for an IPv4 address, an
453    /// AAAA record for an IPv6 one. Unlike [`MdnsConfig::with_local_names`], whose names all
454    /// answer with the one [`MdnsConfig::local_ip`], each name registered here has its own
455    /// address, so a host can publish one name per interface address (what WebRTC's mDNS host
456    /// candidates do).
457    ///
458    /// The name is announced from the next
459    /// [`handle_timeout`](sansio::Protocol::handle_timeout) (RFC 6762 section 8.3). A name that
460    /// is not `<uuid>.local` is probed for first
461    /// ([`MdnsProbePolicy`](crate::MdnsProbePolicy)) and answered only once probing has met no
462    /// defender.
463    ///
464    /// Returns `false`, registering nothing, when `name` is already registered,
465    /// [`MAX_LOCAL_NAMES`] are, or `name` is not a DNS name (an empty label, a label over 63
466    /// bytes, over 255 bytes in all).
467    ///
468    /// # Example
469    ///
470    /// ```rust
471    /// # use std::time::Instant;
472    /// use rtci_mdns::{Mdns, MdnsConfig};
473    /// use std::net::IpAddr;
474    ///
475    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
476    /// assert!(mdns.add_local_name("v4-name.local", "192.168.1.10".parse::<IpAddr>().unwrap()));
477    /// assert!(mdns.add_local_name("v6-name.local", "2001:db8::10".parse::<IpAddr>().unwrap()));
478    /// ```
479    pub fn add_local_name(&mut self, name: &str, ip: IpAddr) -> bool {
480        let (name, key) = normalize(name);
481        if self.closed
482            || self.records.iter().filter(|r| r.registered).count() >= MAX_LOCAL_NAMES
483            || self.records.iter().any(|r| r.key == key)
484        {
485            return false;
486        }
487        let Some(record) = self.new_record(name, key, ip, true) else {
488            return false;
489        };
490        // The name is back: the goodbye its removal left behind would withdraw it again.
491        self.goodbyes
492            .retain(|g| !(g.key == record.key && g.ip == record.ip));
493        self.records.push(record);
494        self.update_next_timeout();
495        true
496    }
497
498    /// Stops answering for `name` and withdraws it: when the name was ever sent to the link,
499    /// a goodbye (its record with TTL 0, RFC 6762 section 10.1) goes out from the next
500    /// [`handle_timeout`](sansio::Protocol::handle_timeout), so that neighbours drop it from
501    /// their caches.
502    ///
503    /// Returns `false` when `name` is not one of this connection's names.
504    ///
505    /// # Example
506    ///
507    /// ```rust
508    /// # use std::time::Instant;
509    /// use rtci_mdns::{Mdns, MdnsConfig};
510    /// use std::net::IpAddr;
511    ///
512    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
513    /// let ip: IpAddr = "192.168.1.10".parse().unwrap();
514    /// assert!(mdns.add_local_name("a-name.local", ip));
515    /// assert!(mdns.remove_local_name("A-Name.local"));
516    /// assert!(!mdns.remove_local_name("a-name.local"));
517    /// ```
518    pub fn remove_local_name(&mut self, name: &str) -> bool {
519        let (_, key) = normalize(name);
520        let Some(index) = self.records.iter().position(|r| r.key == key) else {
521            return false;
522        };
523        let record = self.records.remove(index);
524        self.withdraw(record);
525        self.update_next_timeout();
526        true
527    }
528
529    /// Tells the connection that the host's network may have changed: it woke from sleep, a
530    /// link came up, an address changed.
531    ///
532    /// What was learned on the old link is dropped (the address cache, RFC 6762 section 10.3),
533    /// and every local name starts over as a new one does, from the next
534    /// [`handle_timeout`](sansio::Protocol::handle_timeout): probed for unless exempt, then
535    /// announced (RFC 6762 sections 8, 10.2). Pending queries carry on.
536    ///
537    /// Announcements are sent only when a name is registered and when this is called: there
538    /// are no periodic ones (RFC 6762 section 8.3).
539    pub fn network_changed(&mut self) {
540        if self.closed {
541            return;
542        }
543        self.cache.clear();
544        self.reconfirms.clear();
545        self.restart_records();
546        self.update_next_timeout();
547    }
548
549    /// Start a new mDNS query for the given name, sending it at once.
550    ///
551    /// The query asks for the name's A and AAAA records, each question in a message of its own
552    /// (Chromium's mDNS responder ignores a message of more than one question). It is retried after the configured
553    /// interval, then at doubling intervals (RFC 6762 section 5.2), until either:
554    /// - An answer is received (emits [`MdnsEvent::QueryAnswered`])
555    /// - The query times out (emits [`MdnsEvent::QueryTimeout`])
556    /// - The query is cancelled with [`cancel_query()`](Self::cancel_query)
557    /// - The connection is closed
558    ///
559    /// A name whose address is in the cache (answered before, or announced by its owner, and
560    /// not past its TTL) is answered at once: the event is queued, no packet is, and the query
561    /// is never pending.
562    ///
563    /// # Arguments
564    ///
565    /// * `now` - The current time
566    /// * `name` - The hostname to query (e.g., `"mydevice.local"`)
567    ///
568    /// # Returns
569    ///
570    /// A unique [`QueryId`] that can be used to track this query.
571    ///
572    /// # Example
573    ///
574    /// ```rust
575    /// # use std::time::Instant;
576    /// use rtci_mdns::{MdnsConfig, Mdns, MdnsEvent};
577    /// use sansio::Protocol;
578    ///
579    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
580    ///
581    /// // Start a query
582    /// let query_id = mdns.query_now(Instant::now(), "printer.local");
583    ///
584    /// // The query packets are now queued: the A question, then the AAAA question
585    /// let a = mdns.poll_write().expect("query packet should be queued");
586    /// assert_eq!(a.transport.peer_addr.to_string(), "224.0.0.251:5353");
587    /// let aaaa = mdns.poll_write().expect("query packet should be queued");
588    /// assert_eq!(aaaa.transport.peer_addr.to_string(), "224.0.0.251:5353");
589    /// assert!(mdns.poll_write().is_none());
590    ///
591    /// // Track the query
592    /// assert!(mdns.is_query_pending(query_id));
593    /// ```
594    pub fn query_now(&mut self, now: Instant, name: &str) -> QueryId {
595        let id = self.new_query(name, When::At(now), Some(now));
596        if !self.closed {
597            self.last_now = now;
598            self.answer_from_cache(now);
599            self.flush(now);
600            self.update_next_timeout();
601        }
602        id
603    }
604
605    /// Start a query for `name` from the next
606    /// [`handle_timeout`](sansio::Protocol::handle_timeout): its first packet goes out in that
607    /// call, or, with [`MdnsConfig::with_first_query_delay`], a random 20 to 120 ms after it
608    /// (RFC 6762 section 5.2); not at all when the name's address is in the cache. Otherwise
609    /// as [`query_now`](Self::query_now).
610    pub fn schedule_query(&mut self, name: &str) -> QueryId {
611        let id = self.new_query(name, When::Asap, None);
612        self.update_next_timeout();
613        id
614    }
615
616    /// Cancel a pending query.
617    ///
618    /// Removes the query from the pending list. No more retry packets will
619    /// be sent and no events will be emitted for this query.
620    ///
621    /// # Arguments
622    ///
623    /// * `query_id` - The ID returned by [`query_now()`](Self::query_now)
624    ///
625    /// # Example
626    ///
627    /// ```rust
628    /// # use std::time::Instant;
629    /// use rtci_mdns::{MdnsConfig, Mdns};
630    ///
631    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
632    /// let query_id = mdns.query_now(Instant::now(), "device.local");
633    ///
634    /// assert!(mdns.is_query_pending(query_id));
635    /// mdns.cancel_query(query_id);
636    /// assert!(!mdns.is_query_pending(query_id));
637    /// ```
638    pub fn cancel_query(&mut self, query_id: QueryId) {
639        self.queries.retain(|q| q.id != query_id);
640        self.update_next_timeout();
641    }
642
643    /// Check if a query is still pending.
644    ///
645    /// A query is pending until it is answered, times out or is cancelled.
646    ///
647    /// # Arguments
648    ///
649    /// * `query_id` - The ID returned by [`query_now()`](Self::query_now)
650    ///
651    /// # Returns
652    ///
653    /// `true` if the query is still waiting for an answer, `false` otherwise.
654    ///
655    /// # Example
656    ///
657    /// ```rust
658    /// # use std::time::Instant;
659    /// use rtci_mdns::{MdnsConfig, Mdns};
660    ///
661    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
662    /// let query_id = mdns.query_now(Instant::now(), "device.local");
663    ///
664    /// // Query is pending until answered or cancelled
665    /// assert!(mdns.is_query_pending(query_id));
666    /// ```
667    pub fn is_query_pending(&self, query_id: QueryId) -> bool {
668        self.queries.iter().any(|q| q.id == query_id)
669    }
670
671    /// Get the number of pending queries.
672    ///
673    /// # Returns
674    ///
675    /// The count of queries that are still waiting for answers.
676    ///
677    /// # Example
678    ///
679    /// ```rust
680    /// # use std::time::Instant;
681    /// use rtci_mdns::{MdnsConfig, Mdns};
682    ///
683    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
684    /// assert_eq!(mdns.pending_query_count(), 0);
685    ///
686    /// mdns.query_now(Instant::now(), "device1.local");
687    /// mdns.query_now(Instant::now(), "device2.local");
688    /// assert_eq!(mdns.pending_query_count(), 2);
689    /// ```
690    pub fn pending_query_count(&self) -> usize {
691        self.queries.len()
692    }
693
694    /// Declares, from now on, whether the caller of
695    /// [`handle_read`](sansio::Protocol::handle_read) puts each datagram's destination address
696    /// in `local_addr` ([`MdnsConfig::with_destination_reported`]).
697    pub fn set_destination_reported(&mut self, reported: bool) {
698        self.config.destination_reported = reported;
699    }
700
701    /// Sets, from now on, the subnets of the link the mDNS socket is on, as (address, prefix
702    /// length) pairs: what [`MdnsConfig::with_on_link_subnets`] sets at the start, for a
703    /// driver that learns its interfaces' prefixes later or sees them change. RFC 6762
704    /// section 5.5 checks "that the source address in the query packet matches the local
705    /// subnet for that link (or, in the case of IPv6, the source address has an on-link
706    /// prefix)", and section 11 holds unicast answers to the same test: only the driver,
707    /// which enumerates the interfaces, knows those prefixes. An empty list goes back to the
708    /// scope of the source address.
709    pub fn set_on_link_subnets(&mut self, subnets: Vec<(IpAddr, u8)>) {
710        self.config.on_link_subnets = subnets;
711    }
712
713    /// Whether `ip` may be on the local link (RFC 6762 section 11): in one of the configured
714    /// subnets, or, with none configured, by the scope of the address.
715    fn is_on_link(&self, ip: IpAddr) -> bool {
716        if self.config.on_link_subnets.is_empty() {
717            return is_on_link_source(ip);
718        }
719        let ip = ip.to_canonical();
720        self.config
721            .on_link_subnets
722            .iter()
723            .any(|&(net, prefix)| in_subnet(ip, net.to_canonical(), prefix))
724    }
725
726    /// Whether an answer naming `addr` is believed from `src`: see
727    /// [`answer_is_from_its_owner`]. `on_link` overrides the scope test: a response the
728    /// driver says arrived at the mDNS multicast address originated on the link (RFC 6762
729    /// section 11). An A record must still name its sender (the fork's hardening).
730    fn trusts(&self, addr: IpAddr, src: IpAddr, on_link: bool) -> bool {
731        let (addr, src) = (addr.to_canonical(), src.to_canonical());
732        let on_link = on_link || self.is_on_link(src);
733        match addr {
734            IpAddr::V4(_) => addr == src && on_link,
735            IpAddr::V6(_) => addr == src || on_link,
736        }
737    }
738
739    /// Whether `ip` is an address this connection publishes: a datagram from it is our own,
740    /// looped back, or another responder of this host.
741    fn is_own_address(&self, ip: IpAddr) -> bool {
742        let ip = ip.to_canonical();
743        self.config.local_ip.map(|own| own.to_canonical()) == Some(ip)
744            || self.records.iter().any(|r| r.ip.to_canonical() == ip)
745    }
746
747    /// Queues `bytes` for `to`, taking one message of the budget. `false`, queuing nothing,
748    /// when the budget or the queue has no room; `blocked_until` then says when to try again.
749    fn emit(&mut self, now: Instant, from: IpAddr, to: SocketAddr, bytes: &[u8]) -> bool {
750        if self.write_outs.len() >= MAX_QUEUED_PACKETS {
751            self.blocked_until = Some(now + QUEUE_FULL_RETRY);
752            return false;
753        }
754        if !self.limiter.take(now) {
755            self.blocked_until = Some(self.limiter.ready_at(now));
756            return false;
757        }
758        self.push_packet(now, from, to, bytes);
759        true
760    }
761
762    fn push_packet(&mut self, now: Instant, from: IpAddr, to: SocketAddr, bytes: &[u8]) {
763        self.write_outs.push_back(TransportMessage {
764            now,
765            transport: TransportContext {
766                local_addr: SocketAddr::new(from, MDNS_PORT),
767                peer_addr: to,
768                transport_protocol: TransportProtocol::UDP,
769                ecn: None,
770            },
771            message: BytesMut::from(bytes),
772        });
773    }
774
775    /// Sends everything that is due and allowed at `now`, in this order: probes, records
776    /// (answers and announcements), goodbyes, queries. Stops at the first message the budget
777    /// refuses; what was not sent stays due.
778    fn flush(&mut self, now: Instant) {
779        if self.closed {
780            return;
781        }
782        self.blocked_until = None;
783        let _ = self.flush_probes(now)
784            && self.flush_records(now)
785            && self.flush_goodbyes(now)
786            && self.flush_queries(now)
787            && self.flush_reconfirms(now);
788    }
789
790    fn update_next_timeout(&mut self) {
791        let mut next: Option<Instant> = None;
792        let mut asap = false;
793        let mut consider = |when: When| match when {
794            When::Asap => asap = true,
795            When::At(at) => next = Some(next.map_or(at, |n: Instant| n.min(at))),
796        };
797        for record in &self.records {
798            record.deadlines(&mut consider);
799        }
800        for goodbye in &self.goodbyes {
801            consider(goodbye.due);
802        }
803        for query in &self.queries {
804            consider(query.next);
805            if let (Some(started), Some(timeout)) = (query.started, self.query_timeout)
806                && let Some(at) = started.checked_add(timeout)
807            {
808                consider(When::At(at));
809            }
810        }
811        self.stale_deadlines(&mut consider);
812        // What is due but could not be sent waits for the budget.
813        if let (Some(at), Some(blocked)) = (next, self.blocked_until) {
814            next = Some(at.max(blocked));
815        }
816        self.next_timeout = next;
817        self.asap = asap;
818    }
819
820    fn process_message(&mut self, msg: &TaggedBytesMut, destination: Option<IpAddr>) {
821        let Some(inbound) = wire::parse(&msg.message) else {
822            log::debug!("mDNS ignores a datagram that is not a DNS message");
823            return;
824        };
825        // RFC 6762 sections 18.3 and 18.11: a message with another OPCODE or a non-zero RCODE
826        // is silently ignored.
827        if inbound.header.op_code != 0 || inbound.header.rcode != RCode::Success {
828            return;
829        }
830        let src = msg.transport.peer_addr;
831        // The destination, where the caller reports it: a unicast arrival is held to stricter
832        // rules (RFC 6762 sections 5.5, 6, 11).
833        // A destination the driver read from the IP header (`handle_datagram`) is believed
834        // as given; otherwise the datagram's `local_addr` is, where the configuration says
835        // the driver puts the destination there.
836        let (unicast_arrival, multicast_arrival) = match destination {
837            Some(dst) => (!dst.is_multicast(), dst.is_multicast()),
838            // RFC 6762 section 11: "All responses received with a destination address in the
839            // IP header that is the mDNS IPv4 link-local multicast address 224.0.0.251 or the
840            // mDNS IPv6 link-local multicast address FF02::FB are necessarily deemed to have
841            // originated on the local link, regardless of source IP address."
842            None if self.config.destination_reported => {
843                let dst = msg.transport.local_addr.ip();
844                (
845                    !(dst.is_unspecified() || dst.is_multicast()),
846                    dst.is_multicast(),
847                )
848            }
849            None => (false, false),
850        };
851
852        if inbound.header.response {
853            // RFC 6762 section 6: a response from another source port is silently ignored.
854            // Its questions, if it has any, are too.
855            if src.port() == MDNS_PORT {
856                self.process_response(&inbound, src, unicast_arrival, multicast_arrival, msg.now);
857            }
858        } else {
859            // The Answer section of a query is its sender's known answers: it resolves
860            // nothing and is never cached (RFC 6762 section 7.1).
861            self.process_query(&inbound, src, unicast_arrival, msg.now);
862        }
863    }
864}
865
866/// Whether `ip` is in the subnet `net`/`prefix`.
867fn in_subnet(ip: IpAddr, net: IpAddr, prefix: u8) -> bool {
868    fn bits(ip: IpAddr) -> (u128, u32) {
869        match ip {
870            IpAddr::V4(v4) => (u128::from(u32::from(v4)), 32),
871            IpAddr::V6(v6) => (u128::from(v6), 128),
872        }
873    }
874    let ((ip, width), (net, net_width)) = (bits(ip), bits(net));
875    if width != net_width {
876        return false;
877    }
878    let prefix = u32::from(prefix).min(width);
879    if prefix == 0 {
880        return true;
881    }
882    (ip ^ net) >> (width - prefix) == 0
883}
884
885/// Whether `src` may be on the local link (RFC 6762 ยง11: mDNS is link-local; responses from
886/// elsewhere are not to be trusted). The receiver sees no TTL or interface here, so this is the
887/// address's scope: private, shared, link-local and loopback IPv4; link-local, unique-local and
888/// loopback IPv6.
889pub(crate) fn is_on_link_source(src: IpAddr) -> bool {
890    match src.to_canonical() {
891        IpAddr::V4(v4) => {
892            let [a, b, ..] = v4.octets();
893            v4.is_private()
894                || v4.is_link_local()
895                || v4.is_loopback()
896                // 100.64.0.0/10, shared address space (RFC 6598).
897                || (a == 100 && (64..128).contains(&b))
898        }
899        IpAddr::V6(v6) => {
900            v6.is_unicast_link_local() || v6.is_loopback() || (v6.segments()[0] & 0xfe00) == 0xfc00
901        }
902    }
903}
904
905/// Whether an answer naming `addr` is believed from `src`: the sender must be on-link, and an
906/// A record must name the sender's own address. A host answers for its IPv6 names over the IPv4
907/// group too, so an AAAA record is not compared with an IPv4 source (an IPv6 source that names
908/// itself is accepted whatever its scope).
909pub(crate) fn answer_is_from_its_owner(addr: IpAddr, src: IpAddr) -> bool {
910    let (addr, src) = (addr.to_canonical(), src.to_canonical());
911    match addr {
912        IpAddr::V4(_) => addr == src && is_on_link_source(src),
913        IpAddr::V6(_) => addr == src || is_on_link_source(src),
914    }
915}
916
917impl sansio::Protocol<TaggedBytesMut, (), ()> for Mdns {
918    type Rout = ();
919    type Wout = TaggedBytesMut;
920    type Eout = MdnsEvent;
921    type Error = Error;
922    type Time = Instant;
923
924    /// Process an incoming mDNS packet.
925    ///
926    /// Call this method when a UDP packet is received on the mDNS socket (port 5353, joined
927    /// to 224.0.0.251).
928    ///
929    /// The connection will:
930    /// - Parse the packet as an mDNS message; one with a non-zero OPCODE or RCODE, or over
931    ///   9000 bytes, is ignored
932    /// - For a query: answer the questions for its names (at once, or after the delay RFC 6762
933    ///   section 6 asks for), by multicast, by unicast when asked, or as a conventional DNS
934    ///   reply to a querier that is not on port 5353
935    /// - For a response (taken only from source port 5353): resolve pending queries, cache
936    ///   the addresses, and check its records against the names it owns (a conflicting record
937    ///   sends the name back to probing)
938    ///
939    /// # Arguments
940    ///
941    /// * `msg` - The received packet with transport context: the sender in `peer_addr`, and,
942    ///   with [`MdnsConfig::with_destination_reported`], the datagram's destination address
943    ///   in `local_addr`
944    ///
945    /// # Errors
946    ///
947    /// Returns [`Error::ErrConnectionClosed`] if the connection has been closed.
948    ///
949    /// # Example
950    ///
951    /// ```rust,ignore
952    /// use bytes::BytesMut;
953    /// use shared::{TaggedBytesMut, TransportContext, TransportProtocol};
954    /// use std::time::Instant;
955    ///
956    /// // When a packet arrives from the network:
957    /// let msg = TaggedBytesMut {
958    ///     now: Instant::now(),
959    ///     transport: TransportContext {
960    ///         local_addr: "224.0.0.251:5353".parse().unwrap(),
961    ///         peer_addr: src_addr,
962    ///         transport_protocol: TransportProtocol::UDP,
963    ///         ecn: None,
964    ///     },
965    ///     message: BytesMut::from(&packet_data[..]),
966    /// };
967    /// mdns.handle_read(msg)?;
968    ///
969    /// // Check for events
970    /// while let Some(event) = mdns.poll_event() {
971    ///     // handle event
972    /// }
973    /// ```
974    fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<()> {
975        if self.closed {
976            return Err(Error::ErrConnectionClosed);
977        }
978        self.last_now = msg.now;
979        self.process_message(&msg, None);
980        self.flush(msg.now);
981        self.update_next_timeout();
982        Ok(())
983    }
984
985    /// mDNS doesn't produce read outputs.
986    ///
987    /// Answers to queries are delivered via `poll_event()`
988    /// as [`MdnsEvent::QueryAnswered`] events instead.
989    ///
990    /// # Returns
991    ///
992    /// Always returns `None`.
993    fn poll_read(&mut self) -> Option<Self::Rout> {
994        None
995    }
996
997    /// Handle write requests (not used).
998    ///
999    /// Queries are initiated via the [`query_now()`](Mdns::query_now) method instead
1000    /// of through this interface.
1001    fn handle_write(&mut self, _msg: ()) -> Result<()> {
1002        Ok(())
1003    }
1004
1005    /// Get the next packet to send.
1006    ///
1007    /// Call this method repeatedly until it returns `None` to retrieve all
1008    /// queued packets. Packets should be sent via UDP, from port 5353, to the address
1009    /// specified in `packet.transport.peer_addr`: 224.0.0.251:5353, or a querier's own address
1010    /// for a unicast reply. Responses should leave with IP TTL 255 (RFC 6762 section 11;
1011    /// [`MulticastSocket`](crate::MulticastSocket) sets it).
1012    ///
1013    /// Packets are queued when:
1014    /// - A query is started with [`query_now()`](Mdns::query_now)
1015    /// - `handle_timeout()` reaches a query's first packet or retry, a probe, an
1016    ///   announcement, a delayed response or a goodbye
1017    /// - A response is generated for a matching question
1018    /// - The connection is closed while it has published names (their goodbyes)
1019    ///
1020    /// # Returns
1021    ///
1022    /// The next packet to send, or `None` if the queue is empty.
1023    ///
1024    /// # Example
1025    ///
1026    /// ```rust
1027    /// # use std::time::Instant;
1028    /// use rtci_mdns::{MdnsConfig, Mdns};
1029    /// use sansio::Protocol;
1030    ///
1031    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
1032    /// mdns.query_now(Instant::now(), "device.local");
1033    ///
1034    /// // Send all queued packets
1035    /// while let Some(packet) = mdns.poll_write() {
1036    ///     // socket.send_to(&packet.message, packet.transport.peer_addr).await?;
1037    ///     println!("Send to {}", packet.transport.peer_addr);
1038    /// }
1039    /// ```
1040    fn poll_write(&mut self) -> Option<Self::Wout> {
1041        self.write_outs.pop_front()
1042    }
1043
1044    /// Handle external events (not used).
1045    ///
1046    /// mDNS does not use external events. This method does nothing.
1047    fn handle_event(&mut self, _evt: ()) -> Result<()> {
1048        Ok(())
1049    }
1050
1051    /// Get the next event.
1052    ///
1053    /// Call this method repeatedly until it returns `None` to process all
1054    /// queued events. Events are generated when:
1055    /// - An mDNS answer matches a pending query ([`MdnsEvent::QueryAnswered`])
1056    /// - A query ends without an address ([`MdnsEvent::QueryTimeout`])
1057    /// - A local name is lost to another host ([`MdnsEvent::LocalNameConflict`])
1058    ///
1059    /// # Returns
1060    ///
1061    /// The next event, or `None` if the queue is empty.
1062    ///
1063    /// # Example
1064    ///
1065    /// ```rust,ignore
1066    /// while let Some(event) = mdns.poll_event() {
1067    ///     match event {
1068    ///         MdnsEvent::QueryAnswered(query_id, addr) => {
1069    ///             println!("Query {} resolved to {}", query_id, addr);
1070    ///         }
1071    ///         MdnsEvent::QueryTimeout(id) => {
1072    ///             println!("Query {} timed out", id);
1073    ///         }
1074    ///         _ => {}
1075    ///     }
1076    /// }
1077    /// ```
1078    fn poll_event(&mut self) -> Option<Self::Eout> {
1079        self.event_outs.pop_front()
1080    }
1081
1082    /// Handle timeout: send what is due.
1083    ///
1084    /// Call this method when the deadline from `poll_timeout()`
1085    /// is reached. It starts what was registered or scheduled since the last call, ends the
1086    /// queries whose timeout has passed, and queues the packets that are due: query packets
1087    /// and retries, probes, announcements, delayed responses, goodbyes. They can be retrieved
1088    /// with `poll_write()`.
1089    ///
1090    /// # Arguments
1091    ///
1092    /// * `now` - The current time
1093    ///
1094    /// # Errors
1095    ///
1096    /// Returns [`Error::ErrConnectionClosed`] if the connection has been closed.
1097    ///
1098    /// # Example
1099    ///
1100    /// ```rust
1101    /// use rtci_mdns::{MdnsConfig, Mdns};
1102    /// use sansio::Protocol;
1103    /// use std::time::{Duration, Instant};
1104    ///
1105    /// let start = Instant::now();
1106    /// let mut mdns = Mdns::new(start, MdnsConfig::default());
1107    /// mdns.query_now(start, "device.local");
1108    ///
1109    /// // Consume the initial packets (A and AAAA)
1110    /// while mdns.poll_write().is_some() {}
1111    ///
1112    /// // The first retry is due one second after the query
1113    /// assert_eq!(mdns.poll_timeout(), Some(start + Duration::from_secs(1)));
1114    /// mdns.handle_timeout(start + Duration::from_secs(1)).unwrap();
1115    ///
1116    /// // The retry packets should be queued
1117    /// assert!(mdns.poll_write().is_some());
1118    /// assert!(mdns.poll_write().is_some());
1119    /// assert!(mdns.poll_write().is_none());
1120    /// ```
1121    fn handle_timeout(&mut self, now: Self::Time) -> Result<()> {
1122        if self.closed {
1123            return Err(Error::ErrConnectionClosed);
1124        }
1125        self.last_now = now;
1126
1127        self.start_records(now);
1128        self.start_queries(now);
1129        self.expire_queries(now);
1130        self.cache.retain(|cached| cached.expires > now);
1131        self.expire_stale(now);
1132
1133        self.flush(now);
1134        self.update_next_timeout();
1135        Ok(())
1136    }
1137
1138    /// Get the next timeout deadline.
1139    ///
1140    /// Returns the time at which `handle_timeout()` should
1141    /// be called next. Use this to schedule your event loop's sleep/wait.
1142    ///
1143    /// # Returns
1144    ///
1145    /// - `Some(instant)` when something is due then: a query's packet or timeout, a probe, an
1146    ///   announcement, a delayed response, a goodbye. An instant that is not in the future
1147    ///   means "call `handle_timeout` now".
1148    /// - `None` if nothing is pending
1149    ///
1150    /// # Example
1151    ///
1152    /// ```rust
1153    /// # use std::time::Instant;
1154    /// use rtci_mdns::{MdnsConfig, Mdns};
1155    /// use sansio::Protocol;
1156    ///
1157    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
1158    ///
1159    /// // No queries, no timeout
1160    /// assert!(mdns.poll_timeout().is_none());
1161    ///
1162    /// // Start a query
1163    /// mdns.query_now(Instant::now(), "device.local");
1164    ///
1165    /// // Now there's a timeout scheduled
1166    /// assert!(mdns.poll_timeout().is_some());
1167    /// ```
1168    fn poll_timeout(&mut self) -> Option<Self::Time> {
1169        if self.closed {
1170            None
1171        } else if self.asap {
1172            // Something waits for the time: handle it at once.
1173            Some(self.last_now)
1174        } else {
1175            self.next_timeout
1176        }
1177    }
1178
1179    /// Close the connection.
1180    ///
1181    /// This clears all pending queries and queued packets/events, then queues a goodbye (TTL
1182    /// 0, RFC 6762 section 10.1) for every name that was sent to the link: drain
1183    /// `poll_write()` once more after closing so that neighbours drop the names at once.
1184    /// After closing, `handle_read()` and
1185    /// `handle_timeout()` will return
1186    /// [`Error::ErrConnectionClosed`].
1187    ///
1188    /// # Example
1189    ///
1190    /// ```rust
1191    /// # use std::time::Instant;
1192    /// use rtci_mdns::{MdnsConfig, Mdns};
1193    /// use sansio::Protocol;
1194    ///
1195    /// let mut mdns = Mdns::new(Instant::now(), MdnsConfig::default());
1196    /// mdns.query_now(Instant::now(), "device.local");
1197    ///
1198    /// assert_eq!(mdns.pending_query_count(), 1);
1199    ///
1200    /// mdns.close().unwrap();
1201    ///
1202    /// // All state is cleared
1203    /// assert_eq!(mdns.pending_query_count(), 0);
1204    /// assert!(mdns.poll_write().is_none());
1205    /// assert!(mdns.poll_timeout().is_none());
1206    /// ```
1207    fn close(&mut self) -> Result<()> {
1208        if self.closed {
1209            return Ok(());
1210        }
1211        self.closed = true;
1212        self.queries.clear();
1213        self.cache.clear();
1214        self.reconfirms.clear();
1215        self.write_outs.clear();
1216        self.event_outs.clear();
1217        self.queue_closing_goodbyes();
1218        self.records.clear();
1219        self.goodbyes.clear();
1220        self.next_timeout = None;
1221        self.asap = false;
1222        Ok(())
1223    }
1224}
1225
1226#[cfg(test)]
1227mod mdns_answer_trust_test;
1228#[cfg(test)]
1229mod mdns_resolver_test;
1230#[cfg(test)]
1231mod mdns_responder_test;
1232#[cfg(test)]
1233mod mdns_stale_test;
1234#[cfg(test)]
1235mod mdns_test;
1236#[cfg(test)]
1237mod mdns_timeout_test;
1238#[cfg(test)]
1239mod testkit;
1240#[cfg(test)]
1241mod wire_test;