rtci-mdns 0.5.0

Sans-I/O mDNS (RFC 6762) querier and responder, as used for WebRTC mDNS ICE candidates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! The resolver half of [`Mdns`]: query series and the address cache (RFC 6762 sections 5, 7.3,
//! 10, 11).

use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::time::{Duration, Instant};

use super::wire::{
    self, CLASS_ANY, CLASS_IN, CLASS_TOP_BIT, FLAGS_QUERY, InData, Inbound, OutQuestion, TYPE_A,
    TYPE_AAAA, TYPE_ANY,
};
use super::{
    CACHE_TTL_CAP, MAX_CACHED_ADDRESSES, MAX_QUERY_INTERVAL, MDNS_DEST_ADDR, Mdns, MdnsEvent,
    QueryId, When, normalize,
};

/// A unicast response is taken only for a question that asked for one this recently
/// (RFC 6762 section 6).
const UNICAST_WINDOW: Duration = Duration::from_secs(2);

/// A question seen this soon after ours went out is taken to be ours, handed back by the link
/// (multicast loops back to its sender), not another host's.
const OWN_ECHO: Duration = Duration::from_millis(200);

/// A record that says goodbye, or one a cache-flush record replaces, leaves the cache a
/// second later (RFC 6762 sections 10.1, 10.2).
const FLUSH_DELAY: Duration = Duration::from_secs(1);

/// A pending query: one name, asked for as A and AAAA, each question in a message of its own
/// (see [`Mdns::flush_queries`]).
#[derive(Debug)]
pub(super) struct Query {
    pub(super) id: QueryId,
    /// The name with its trailing dot, as asked.
    name: String,
    /// The name in ASCII lower case.
    key: String,
    /// When the series began; `None` until a scheduled query is given the time.
    pub(super) started: Option<Instant>,
    /// The next packet of the series.
    pub(super) next: When,
    /// The wait after the next packet; doubles each time.
    interval: Duration,
    /// Packets sent, or taken as sent.
    sent: u32,
    last_sent: Option<Instant>,
    /// When the series last asked for a unicast response.
    unicast_asked: Option<Instant>,
    /// Another host's question for the A (AAAA) record was seen since our last packet.
    seen_a: bool,
    seen_aaaa: bool,
    /// The A question of the packet under way went out, with this class; its AAAA question
    /// waits for the message budget.
    a_class: Option<u16>,
}

impl Query {
    /// Books a packet of the series as sent at `now`, by us or (a duplicate question,
    /// RFC 6762 section 7.3) by another host.
    fn packet_sent(&mut self, now: Instant, unicast: bool) {
        self.sent += 1;
        self.last_sent = Some(now);
        if unicast {
            self.unicast_asked = Some(now);
        }
        // RFC 6762 section 5.2: the interval at least doubles, up to an hour.
        self.next = When::At(now + self.interval);
        self.interval = (self.interval * 2).min(MAX_QUERY_INTERVAL);
        self.seen_a = false;
        self.seen_aaaa = false;
        self.a_class = None;
    }
}

/// What became of a question handed to [`Mdns::send_question`].
pub(super) enum QuestionSent {
    /// Queued.
    Out,
    /// The message budget or the write queue had no room; nothing was queued.
    Refused,
    /// The name cannot be written; nothing was queued.
    Unwritable,
}

/// An address learned from a response.
#[derive(Debug)]
pub(super) struct Cached {
    pub(super) key: String,
    pub(super) addr: IpAddr,
    pub(super) received: Instant,
    pub(super) expires: Instant,
    /// Other hosts' queries this address would answer, unanswered (RFC 6762 section 10.5).
    pub(super) unanswered: Option<super::reconfirm::Unanswered>,
}

impl Mdns {
    pub(super) fn new_query(
        &mut self,
        name: &str,
        next: When,
        started: Option<Instant>,
    ) -> QueryId {
        let (name, key) = normalize(name);
        let id = self.next_query_id;
        self.next_query_id += 1;
        if !self.closed {
            self.queries.push(Query {
                id,
                name,
                key,
                started,
                next,
                interval: self.query_interval,
                sent: 0,
                last_sent: None,
                unicast_asked: None,
                seen_a: false,
                seen_aaaa: false,
                a_class: None,
            });
        }
        id
    }

    /// The addresses the cache holds for `key` at `now`.
    fn cached(&self, key: &str, now: Instant) -> Vec<IpAddr> {
        self.cache
            .iter()
            .filter(|cached| cached.key == key && cached.expires > now)
            .map(|cached| cached.addr)
            .collect()
    }

    /// How a query ends when `addrs` are what its name resolves to: with the address, or,
    /// when there are several and only one is allowed, without one
    /// (draft-ietf-mmusic-mdns-ice-candidates section 3.2.2). `None` for no address.
    fn outcome(&self, id: QueryId, addrs: &[IpAddr]) -> Option<MdnsEvent> {
        match addrs {
            [] => None,
            [addr] => Some(MdnsEvent::QueryAnswered(id, *addr)),
            [first, ..] if self.config.multiple_addresses => {
                Some(MdnsEvent::QueryAnswered(id, *first))
            }
            _ => {
                // The draft's SHOULD (ignore the candidate), not a fault: debug, like the
                // other ends of a query without an address.
                log::debug!("mDNS query {id} ends: its name has more than one address");
                Some(MdnsEvent::QueryTimeout(id))
            }
        }
    }

    /// Ends the queries that have sent nothing yet and whose name is in the cache.
    pub(super) fn answer_from_cache(&mut self, now: Instant) {
        let mut index = 0;
        while index < self.queries.len() {
            let query = &self.queries[index];
            let event = (query.sent == 0 && query.started.is_some())
                .then(|| self.outcome(query.id, &self.cached(&query.key, now)))
                .flatten();
            match event {
                Some(event) => {
                    self.event_outs.push_back(event);
                    self.queries.remove(index);
                }
                None => index += 1,
            }
        }
    }

    /// Starts the scheduled queries: answered from the cache, or first sent after a random
    /// 20 to 120 ms (RFC 6762 section 5.2).
    pub(super) fn start_queries(&mut self, now: Instant) {
        let delay = self.config.first_query_delay;
        for index in 0..self.queries.len() {
            if self.queries[index].next == When::Asap {
                let wait = if delay {
                    self.jitter.millis(20, 120)
                } else {
                    Duration::ZERO
                };
                let query = &mut self.queries[index];
                query.started = Some(now);
                query.next = When::At(now + wait);
            }
        }
        self.answer_from_cache(now);
    }

    /// Ends the queries whose timeout has passed.
    pub(super) fn expire_queries(&mut self, now: Instant) {
        let Some(timeout) = self.query_timeout else {
            return;
        };
        let events = &mut self.event_outs;
        self.queries.retain(|query| {
            let expired = query
                .started
                .is_some_and(|started| now.saturating_duration_since(started) >= timeout);
            if expired {
                log::debug!("mDNS query {} timed out after {timeout:?}", query.id);
                events.push_back(MdnsEvent::QueryTimeout(query.id));
            }
            !expired
        });
    }

    /// Queues a query message for the group with the one question `name`, `typ`, `class`.
    pub(super) fn send_question(
        &mut self,
        now: Instant,
        name: &str,
        typ: u16,
        class: u16,
    ) -> QuestionSent {
        let question = OutQuestion { name, typ, class };
        match wire::pack(0, FLAGS_QUERY, &[question], &[], &[], &[]) {
            None => QuestionSent::Unwritable,
            Some(bytes) => {
                if self.emit(
                    now,
                    IpAddr::V4(Ipv4Addr::UNSPECIFIED),
                    MDNS_DEST_ADDR,
                    &bytes,
                ) {
                    QuestionSent::Out
                } else {
                    QuestionSent::Refused
                }
            }
        }
    }

    /// Sends the query packets that are due: for each name an A question and then an AAAA
    /// question (a `.local` name carries no hint of which family it resolves to, and a host
    /// publishes its IPv6 addresses under names of their own), each in a message of its own,
    /// on the first packet of a series and on every retry. The first packet asks for a unicast
    /// response when the configuration says so; retries never do (RFC 6762 section 5.4).
    ///
    /// One question a message: RFC 6762 section 5.3 makes several questions in one message
    /// "purely an efficiency optimization", the same as one message per question, and
    /// Chromium's mDNS responder, which answers for the `.local` names in Chrome's ICE
    /// candidates, drops a query whose question count is not one (chromium/src
    /// `net/dns/dns_query.cc` `DnsQuery::Parse`). Every message draws on the message budget;
    /// an AAAA question the budget holds back goes out when it allows, before the series
    /// moves on.
    pub(super) fn flush_queries(&mut self, now: Instant) -> bool {
        let unicast = self.config.unicast_response;
        for index in 0..self.queries.len() {
            let query = &self.queries[index];
            if !query.next.due(now) {
                continue;
            }
            let class = query.a_class.unwrap_or(
                CLASS_IN
                    | if unicast && query.sent == 0 {
                        CLASS_TOP_BIT
                    } else {
                        0
                    },
            );
            let asks_unicast = class & CLASS_TOP_BIT != 0;
            let ask_a = query.a_class.is_none();
            let name = query.name.clone();
            if ask_a {
                match self.send_question(now, &name, TYPE_A, class) {
                    QuestionSent::Refused => return false,
                    QuestionSent::Unwritable => {
                        log::warn!("mDNS cannot ask for {name}: not a DNS name");
                        self.queries[index].packet_sent(now, asks_unicast);
                        continue;
                    }
                    QuestionSent::Out => {
                        let query = &mut self.queries[index];
                        query.a_class = Some(class);
                        query.last_sent = Some(now);
                        if asks_unicast {
                            query.unicast_asked = Some(now);
                        }
                    }
                }
            }
            if let QuestionSent::Refused = self.send_question(now, &name, TYPE_AAAA, class) {
                return false;
            }
            self.queries[index].packet_sent(now, asks_unicast);
        }
        true
    }

    /// RFC 6762 section 7.3: another host multicast a question we are about to send (again),
    /// with no known answers that would keep the answer from us. Ours counts as sent.
    pub(super) fn note_duplicate_questions(
        &mut self,
        inbound: &Inbound,
        src: SocketAddr,
        now: Instant,
    ) {
        if self.queries.is_empty() || self.is_own_address(src.ip()) {
            return;
        }
        for question in &inbound.questions {
            // A question that asks for a unicast response ("QU") brings its answer to the
            // asker alone.
            if question.unicast || !(question.class == CLASS_IN || question.class == CLASS_ANY) {
                continue;
            }
            let (a, aaaa) = match question.typ {
                TYPE_A => (true, false),
                TYPE_AAAA => (false, true),
                TYPE_ANY => (true, true),
                _ => continue,
            };
            if inbound
                .answers
                .iter()
                .any(|known| known.key == question.key)
            {
                continue;
            }
            for query in &mut self.queries {
                if query.key != question.key
                    || query.started.is_none()
                    || query
                        .last_sent
                        .is_some_and(|t| now.saturating_duration_since(t) < OWN_ECHO)
                {
                    continue;
                }
                query.seen_a |= a;
                query.seen_aaaa |= aaaa;
                if query.seen_a && query.seen_aaaa {
                    query.packet_sent(now, false);
                }
            }
        }
    }

    /// Whether a response that arrived by unicast may speak about `key`: a question of ours
    /// for it asked for a unicast response within the last two seconds, or we are probing for
    /// it. Every other unicast response is ignored (RFC 6762 section 6).
    fn expects_unicast(&self, key: &str, now: Instant) -> bool {
        self.queries.iter().any(|query| {
            query.key == key
                && query
                    .unicast_asked
                    .is_some_and(|t| now.saturating_duration_since(t) <= UNICAST_WINDOW)
        }) || self.probes_for(key)
    }

    /// Takes an address into the cache for its TTL (RFC 6762 sections 5.2, 10).
    fn cache_address(&mut self, key: &str, addr: IpAddr, ttl: u32, flush: bool, now: Instant) {
        let soon = now + FLUSH_DELAY;
        if ttl == 0 {
            // RFC 6762 section 10.1: a goodbye is not acted on at once, but a second later.
            for cached in &mut self.cache {
                if cached.key == key && cached.addr == addr {
                    cached.expires = cached.expires.min(soon);
                }
            }
            return;
        }
        if flush {
            // RFC 6762 section 10.2: the cache-flush bit says this is the whole truth for the
            // name and type; what was heard more than a second ago goes in a second.
            for cached in &mut self.cache {
                if cached.key == key
                    && cached.addr != addr
                    && cached.addr.is_ipv4() == addr.is_ipv4()
                    && now.saturating_duration_since(cached.received) > FLUSH_DELAY
                {
                    cached.expires = cached.expires.min(soon);
                }
            }
        }
        let expires = now + Duration::from_secs(u64::from(ttl.min(CACHE_TTL_CAP)));
        if let Some(cached) = self
            .cache
            .iter_mut()
            .find(|cached| cached.key == key && cached.addr == addr)
        {
            cached.received = now;
            cached.expires = expires;
            cached.unanswered = None;
            return;
        }
        if self.cache.len() >= MAX_CACHED_ADDRESSES {
            self.cache.retain(|cached| cached.expires > now);
        }
        if self.cache.len() >= MAX_CACHED_ADDRESSES {
            // Full of live entries: the one nearest its expiry gives way, unless the newcomer
            // would go first.
            let Some((index, soonest)) = self
                .cache
                .iter()
                .enumerate()
                .map(|(i, cached)| (i, cached.expires))
                .min_by_key(|&(_, expires)| expires)
            else {
                return;
            };
            if soonest >= expires {
                return;
            }
            self.cache.swap_remove(index);
        }
        self.cache.push(Cached {
            key: key.to_owned(),
            addr,
            received: now,
            expires,
            unanswered: None,
        });
    }

    /// A response: its records are held against our names (conflicts), cached, and matched
    /// with the pending queries. Whatever is in its Question section is ignored (RFC 6762
    /// section 6), as is its ID (section 18.1).
    pub(super) fn process_response(
        &mut self,
        inbound: &Inbound,
        src: SocketAddr,
        unicast_arrival: bool,
        multicast_arrival: bool,
        now: Instant,
    ) {
        // RFC 6762 section 11: only what originates on the link counts; a response the driver
        // says arrived at the multicast address did, whatever its source.
        let on_link = multicast_arrival || self.is_on_link(src.ip());
        // Addresses this response gives, by name; and the names it says have no address.
        let mut resolved: Vec<(&str, IpAddr)> = Vec::new();
        let mut without_address: Vec<&str> = Vec::new();

        let sections = [
            (&inbound.answers, true),
            (&inbound.authorities, false),
            (&inbound.additionals, true),
        ];
        for (records, resolves) in sections {
            for record in records {
                if record.class != CLASS_IN
                    || (unicast_arrival && !self.expects_unicast(&record.key, now))
                {
                    continue;
                }
                // RFC 6762 section 9: a conflicting record in any section counts.
                if on_link {
                    self.note_conflict(record, now);
                }
                if !resolves {
                    continue;
                }
                match record.data {
                    InData::Addr(addr) => {
                        if !self.trusts(addr, src.ip(), multicast_arrival) {
                            log::warn!(
                                "mDNS ignores an answer for {} with address {} from {}: an answer is taken only from an on-link sender, and an A record only from the address it names",
                                record.key,
                                addr,
                                src.ip()
                            );
                            continue;
                        }
                        self.cache_address(&record.key, addr, record.ttl, record.flush, now);
                        // RFC 6762 section 10.1: a TTL of zero is a goodbye; it resolves
                        // nothing.
                        if record.ttl > 0 && !resolved.contains(&(record.key.as_str(), addr)) {
                            resolved.push((&record.key, addr));
                        }
                    }
                    // RFC 6762 section 6.1: the name's owner says which types exist under it.
                    InData::Nsec(_)
                        if on_link
                            && record.ttl > 0
                            && record.nsec_has(TYPE_A) == Some(false)
                            && record.nsec_has(TYPE_AAAA) == Some(false) =>
                    {
                        without_address.push(&record.key);
                    }
                    _ => {}
                }
            }
        }

        let mut index = 0;
        while index < self.queries.len() {
            let query = &self.queries[index];
            let addrs: Vec<IpAddr> = resolved
                .iter()
                .filter(|(key, _)| *key == query.key)
                .map(|&(_, addr)| addr)
                .collect();
            let event = self.outcome(query.id, &addrs).or_else(|| {
                without_address.contains(&query.key.as_str()).then(|| {
                    log::debug!("mDNS query {} ends: its name has no address", query.id);
                    MdnsEvent::QueryTimeout(query.id)
                })
            });
            match event {
                Some(event) => {
                    self.event_outs.push_back(event);
                    self.queries.remove(index);
                }
                None => index += 1,
            }
        }
    }
}