Skip to main content

matter_kit/discovery/
dns.rs

1//! DNS messages, as much of them as Matter's DNS-SD needs (RFC 1035, RFC 6762).
2//!
3//! Matter "requires no modifications to IETF Standard DNS-SD" (§4.3), so this is ordinary
4//! DNS on the wire: a header, questions, and resource records, with names as sequences of
5//! length-prefixed labels.
6//!
7//! # Names are slices of labels, not strings
8//!
9//! `DD200C20D25AE5F7._matterc._udp.local.` is four labels, and nothing here ever joins them
10//! into a string. That is not only to avoid allocating: the wire format is label-by-label,
11//! compression points *at* a label boundary, and a dotted string would have to be split again
12//! at every one of those points — reintroducing the question of what a dot inside a label
13//! means. A DNS-SD instance name may legitimately contain dots.
14//!
15//! # Compression is what makes a response fit
16//!
17//! A Matter commissionable advertisement is four PTR records, an SRV, a TXT and an AAAA, all
18//! naming `…_matterc._udp.local.` I RFC 1035 §4.1.4's pointers turn every repeat of that
19//! suffix into two octets. [`DnsWriter`] remembers the names it has written and emits the
20//! longest suffix match it can, which is the difference between a response that fits one
21//! datagram and one that does not.
22//!
23//! # Reading is hostile-input territory
24//!
25//! A compression pointer can point anywhere, including backwards into itself — the classic
26//! decompression loop. [`Name`] follows pointers with a hard bound and refuses any pointer
27//! that does not point strictly backwards, which makes a cycle impossible rather than merely
28//! bounded.
29
30use heapless::Vec;
31
32use crate::error::{Error, ErrorCode, Result, bail};
33
34/// The IANA record types Matter's DNS-SD uses.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36#[repr(u16)]
37#[non_exhaustive]
38pub enum RecordType {
39    /// `A` — an IPv4 address. Matter does not use IPv4, but a query may still ask.
40    A = 1,
41    /// `PTR` — a service instance, or a subtype's member.
42    Ptr = 12,
43    /// `TXT` — the key/value pairs of §4.3.4.
44    Txt = 16,
45    /// `AAAA` — an IPv6 address. "Matter software discovering other Matter instances SHALL
46    /// process DNS AAAA (IPv6 address) records" (§4.3).
47    Aaaa = 28,
48    /// `SRV` — priority, weight, port and target host.
49    Srv = 33,
50    /// `NSEC` — "this name has these types and no others", RFC 6762 §6.1's way of saying
51    /// "there is no AAAA here" without silence.
52    Nsec = 47,
53    /// `ANY` — only ever a *question* type. RFC 6762 §6 makes it the ordinary way to ask for
54    /// everything a responder knows about one name.
55    Any = 255,
56}
57
58impl RecordType {
59    /// The wire value.
60    #[must_use]
61    pub const fn value(self) -> u16 {
62        self as u16
63    }
64
65    /// Decodes a wire value, or `None` for a type this crate does not model.
66    ///
67    /// An unknown type is not an error: a responder simply has no records of it, and RFC 6762
68    /// §6 says "if the responder has no records that answer the question, it MUST NOT send
69    /// any response".
70    #[must_use]
71    pub const fn from_value(value: u16) -> Option<Self> {
72        match value {
73            1 => Some(Self::A),
74            12 => Some(Self::Ptr),
75            16 => Some(Self::Txt),
76            28 => Some(Self::Aaaa),
77            33 => Some(Self::Srv),
78            47 => Some(Self::Nsec),
79            255 => Some(Self::Any),
80            _ => None,
81        }
82    }
83
84    /// Whether a record of this type answers a question of `asked`.
85    ///
86    /// `ANY` matches everything; otherwise the types must be equal.
87    #[must_use]
88    pub const fn answers(self, asked: Self) -> bool {
89        matches!(asked, Self::Any) || (self as u16) == (asked as u16)
90    }
91}
92
93/// `IN` — the Internet class, the only one Matter uses.
94pub const CLASS_IN: u16 = 1;
95
96/// RFC 6762 §10.2's cache-flush bit, the top bit of a resource record's class.
97///
98/// "the most significant bit of the rrclass for a record in a Multicast DNS response message
99/// is the cache-flush bit" — it tells a receiver to discard everything it already had for
100/// this name and type. A responder sets it on records it is authoritative for, which for a
101/// Matter node is all of them except the shared PTRs.
102pub const CACHE_FLUSH: u16 = 0x8000;
103
104/// RFC 6762 §5.4's unicast-response bit, the top bit of a question's class.
105///
106/// "a special bit in the rrclass field of the question … indicating that the querier is
107/// willing to accept unicast replies". A responder that honours it sends one datagram back to
108/// the asker rather than to the whole link.
109pub const UNICAST_RESPONSE: u16 = 0x8000;
110
111/// The longest label RFC 1035 §2.3.4 admits.
112pub const LABEL_MAX: usize = 63;
113
114/// How many labels a name may have here.
115///
116/// `<instance>._matterc._udp.local.` is four. Eight leaves room for a subtype's extra
117/// `_S3._sub`, and refuses anything a Matter responder would never emit.
118pub const LABELS_MAX: usize = 8;
119
120/// How many compression pointers may be followed before the message is declared malformed.
121///
122/// Each pointer must go strictly backwards, so a cycle is already impossible; this bounds the
123/// *work* a hostile message can cause.
124const POINTER_LIMIT: usize = 16;
125
126/// A domain name, as the sequence of labels it is on the wire.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Name {
129    labels: Vec<Vec<u8, LABEL_MAX>, LABELS_MAX>,
130}
131
132impl Name {
133    /// An empty name — the root.
134    #[must_use]
135    pub const fn root() -> Self {
136        Self { labels: Vec::new() }
137    }
138
139    /// A name from its labels.
140    pub fn from_labels(labels: &[&[u8]]) -> Result<Self> {
141        let mut name = Self::root();
142        for label in labels {
143            name.push(label)?;
144        }
145        Ok(name)
146    }
147
148    /// A name from its labels, given as strings.
149    pub fn from_strs(labels: &[&str]) -> Result<Self> {
150        let mut name = Self::root();
151        for label in labels {
152            name.push(label.as_bytes())?;
153        }
154        Ok(name)
155    }
156
157    /// Appends a label.
158    pub fn push(&mut self, label: &[u8]) -> Result<()> {
159        if label.is_empty() || label.len() > LABEL_MAX {
160            bail!(InvalidArgument)
161        }
162        let stored = Vec::from_slice(label).map_err(|_| Error::new(ErrorCode::NoSpace))?;
163        self.labels
164            .push(stored)
165            .map_err(|_| Error::new(ErrorCode::NoSpace))
166    }
167
168    /// The labels, outermost first.
169    pub fn labels(&self) -> impl Iterator<Item = &[u8]> {
170        self.labels.iter().map(|label| label.as_slice())
171    }
172
173    /// How many labels the name has.
174    #[must_use]
175    pub fn len(&self) -> usize {
176        self.labels.len()
177    }
178
179    /// Whether this is the root name.
180    #[must_use]
181    pub fn is_empty(&self) -> bool {
182        self.labels.is_empty()
183    }
184
185    /// Whether two names are the same.
186    ///
187    /// **Case-insensitively**, because DNS is: RFC 1035 §2.3.3, and RFC 6762 §16 repeats it
188    /// for Multicast DNS. A responder that compared bytes would miss a query for
189    /// `_MATTERC._UDP.local.` — which a conforming querier is entitled to send, and which some
190    /// stacks do send.
191    #[must_use]
192    pub fn eq_ignore_case(&self, other: &Self) -> bool {
193        self.len() == other.len()
194            && self
195                .labels()
196                .zip(other.labels())
197                .all(|(a, b)| a.eq_ignore_ascii_case(b))
198    }
199
200    /// Whether this name matches `labels`, case-insensitively.
201    #[must_use]
202    pub fn matches(&self, labels: &[&[u8]]) -> bool {
203        self.len() == labels.len()
204            && self
205                .labels()
206                .zip(labels.iter())
207                .all(|(a, b)| a.eq_ignore_ascii_case(b))
208    }
209
210    /// Reads a name from `buf` starting at `at`, following compression pointers.
211    ///
212    /// Returns the name and the offset just past it *in the original stream* — which is not
213    /// where the name ended if a pointer was followed, so the two are tracked separately.
214    pub fn decode(buf: &[u8], at: usize) -> Result<(Self, usize)> {
215        let mut name = Self::root();
216        let mut cursor = at;
217        let mut end: Option<usize> = None;
218        let mut jumps = 0usize;
219
220        loop {
221            let length = *buf.get(cursor).ok_or_else(truncated)?;
222            match length & 0xC0 {
223                0x00 => {
224                    let next = cursor.checked_add(1).ok_or_else(malformed)?;
225                    if length == 0 {
226                        // The root label ends the name.
227                        return Ok((name, end.unwrap_or(next)));
228                    }
229                    let stop = next
230                        .checked_add(usize::from(length))
231                        .ok_or_else(malformed)?;
232                    let label = buf.get(next..stop).ok_or_else(truncated)?;
233                    name.push(label)?;
234                    cursor = stop;
235                }
236                0xC0 => {
237                    // RFC 1035 §4.1.4: a two-octet pointer, fourteen bits of offset.
238                    let low = *buf
239                        .get(cursor.checked_add(1).ok_or_else(malformed)?)
240                        .ok_or_else(truncated)?;
241                    let target = (usize::from(length & 0x3F) << 8) | usize::from(low);
242                    // A pointer must go strictly backwards. That is not merely conventional —
243                    // it is what makes a decompression loop impossible rather than merely
244                    // bounded, because each jump reaches a strictly smaller offset.
245                    if target >= cursor {
246                        bail!(DnsMalformed)
247                    }
248                    jumps = jumps.saturating_add(1);
249                    if jumps > POINTER_LIMIT {
250                        bail!(DnsMalformed)
251                    }
252                    if end.is_none() {
253                        end = Some(cursor.checked_add(2).ok_or_else(malformed)?);
254                    }
255                    cursor = target;
256                }
257                // 0x40 and 0x80 are reserved (RFC 6891 retired the one that used 0x40).
258                _ => bail!(DnsMalformed),
259            }
260        }
261    }
262}
263
264fn truncated() -> Error {
265    Error::new(ErrorCode::DnsTruncated)
266}
267
268fn malformed() -> Error {
269    Error::new(ErrorCode::DnsMalformed)
270}
271
272/// One resource record, as a responder holds it before encoding.
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub struct Record<'a> {
275    /// The owner name, as labels.
276    pub name: &'a [&'a str],
277    /// The record type.
278    pub kind: RecordType,
279    /// Seconds. RFC 6762 §10: 120 for host records, 4500 for the rest.
280    pub ttl: u32,
281    /// RFC 6762 §10.2's cache-flush bit.
282    ///
283    /// Set for records a responder is uniquely authoritative for — its SRV, TXT and AAAA —
284    /// and **clear** for the shared PTRs, where several devices legitimately own the same
285    /// name. Setting it on a PTR would tell every receiver to forget the other devices on the
286    /// link.
287    pub cache_flush: bool,
288    /// The record's data.
289    pub data: RecordData<'a>,
290}
291
292/// The RDATA of the record types Matter's DNS-SD uses.
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub enum RecordData<'a> {
295    /// `PTR` — a target name.
296    Ptr(&'a [&'a str]),
297    /// `SRV` — priority, weight, port, target. Matter always uses priority 0 and weight 0.
298    Srv {
299        /// The port the service listens on. §4.3.1.14: "services are not constrained to use a
300        /// single predetermined well-known port."
301        port: u16,
302        /// The target host name.
303        target: &'a [&'a str],
304    },
305    /// `TXT` — the encoded key/value strings.
306    Txt(&'a [u8]),
307    /// `AAAA` — a 128-bit address.
308    Aaaa([u8; 16]),
309    /// `A` — a 32-bit address. Matter never publishes one; it is here so a reader can skip it.
310    A([u8; 4]),
311}
312
313impl RecordData<'_> {
314    /// Writes the RDATA **uncompressed**, as RFC 6762 §8.2's tiebreak compares it.
315    ///
316    /// "In the case of resource records containing rdata that is subject to name compression,
317    /// the names MUST be uncompressed before comparison. (The details of how a particular name
318    /// is compressed is an artifact of how and where the record is written into the DNS
319    /// message; it is not an intrinsic property of the resource record itself.)" Comparing the
320    /// bytes as they appear in a message would make the winner depend on which record happened
321    /// to be written first.
322    ///
323    /// [`RDATA_MAX`] is always enough.
324    pub fn write_rdata<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
325        let mut cursor = Cursor::new(buf);
326        match self {
327            Self::Ptr(target) => cursor.put_labels(target.iter().map(|l| l.as_bytes()))?,
328            Self::Srv { port, target } => {
329                // Matter always uses priority 0 and weight 0 (§4.3.1.14).
330                cursor.put_u16(0)?;
331                cursor.put_u16(0)?;
332                cursor.put_u16(*port)?;
333                cursor.put_labels(target.iter().map(|l| l.as_bytes()))?;
334            }
335            Self::Txt(bytes) => cursor.put(bytes)?,
336            Self::Aaaa(address) => cursor.put(address)?,
337            Self::A(address) => cursor.put(address)?,
338        }
339        cursor.finish()
340    }
341
342    /// The record type this data belongs to.
343    #[must_use]
344    pub const fn kind(&self) -> RecordType {
345        match self {
346            Self::Ptr(_) => RecordType::Ptr,
347            Self::Srv { .. } => RecordType::Srv,
348            Self::Txt(_) => RecordType::Txt,
349            Self::Aaaa(_) => RecordType::Aaaa,
350            Self::A(_) => RecordType::A,
351        }
352    }
353}
354
355/// The longest RDATA this crate writes uncompressed: an SRV's six fixed octets plus a name.
356///
357/// A name is at most [`LABELS_MAX`] labels of [`LABEL_MAX`] octets, each with a length octet,
358/// plus the root.
359pub const RDATA_MAX: usize = 6 + LABELS_MAX * (LABEL_MAX + 1) + 1;
360
361/// Writes bytes into a fixed buffer, refusing rather than truncating.
362struct Cursor<'a> {
363    buf: &'a mut [u8],
364    at: usize,
365}
366
367impl<'a> Cursor<'a> {
368    const fn new(buf: &'a mut [u8]) -> Self {
369        Self { buf, at: 0 }
370    }
371
372    fn put(&mut self, bytes: &[u8]) -> Result<()> {
373        let end = self.at.checked_add(bytes.len()).ok_or_else(no_space)?;
374        let slot = self.buf.get_mut(self.at..end).ok_or_else(no_space)?;
375        slot.copy_from_slice(bytes);
376        self.at = end;
377        Ok(())
378    }
379
380    fn put_u16(&mut self, value: u16) -> Result<()> {
381        self.put(&value.to_be_bytes())
382    }
383
384    /// An uncompressed name: each label length-prefixed, terminated by the root's zero octet.
385    fn put_labels<'l>(&mut self, labels: impl Iterator<Item = &'l [u8]>) -> Result<()> {
386        for label in labels {
387            let length = u8::try_from(label.len()).map_err(|_| Error::new(ErrorCode::NoSpace))?;
388            if usize::from(length) > LABEL_MAX {
389                bail!(NoSpace)
390            }
391            self.put(&[length])?;
392            self.put(label)?;
393        }
394        self.put(&[0])
395    }
396
397    fn finish(self) -> Result<&'a [u8]> {
398        self.buf.get(..self.at).ok_or_else(no_space)
399    }
400}
401
402/// How many distinct names a writer remembers for compression.
403///
404/// A Matter response has an instance name, a service name, a domain, a host name and up to
405/// five subtype names — and compression only pays for a name that repeats, which in practice
406/// is the last three. Sixteen is comfortably more than enough and costs a few hundred bytes of
407/// stack.
408const COMPRESSION_SLOTS: usize = 16;
409
410/// Writes a DNS message, compressing names as it goes.
411///
412/// The compression is RFC 1035 §4.1.4's: a name whose *suffix* has already been written is
413/// emitted as its own leading labels followed by a two-octet pointer to that suffix. For a
414/// Matter commissionable response — four PTRs, an SRV, a TXT and an AAAA, all ending in
415/// `_matterc._udp.local.` — that is the difference between fitting one datagram and not.
416pub struct DnsWriter<'a, 'n> {
417    buf: &'a mut [u8],
418    at: usize,
419    /// `(offset, labels)` for every name suffix written so far.
420    seen: Vec<(u16, &'n [&'n str]), COMPRESSION_SLOTS>,
421    counts: [u16; 4],
422}
423
424impl<'a, 'n> DnsWriter<'a, 'n> {
425    /// Starts a message with a twelve-octet header, to be filled in by [`DnsWriter::finish`].
426    pub fn new(buf: &'a mut [u8]) -> Result<Self> {
427        if buf.len() < HEADER_LEN {
428            bail!(NoSpace)
429        }
430        let mut writer = Self {
431            buf,
432            at: 0,
433            seen: Vec::new(),
434            counts: [0; 4],
435        };
436        // The header is written last, once the counts are known — but the space has to be
437        // reserved first, because every compression offset is relative to the message start.
438        writer.at = HEADER_LEN;
439        Ok(writer)
440    }
441
442    /// Writes a question.
443    ///
444    /// Questions come before answers; a writer that has already written an answer refuses,
445    /// because the header's counts would no longer describe the message.
446    pub fn question(&mut self, name: &'n [&'n str], kind: RecordType, unicast: bool) -> Result<()> {
447        if self.counts.get(1).copied().unwrap_or(0) != 0 {
448            bail!(InvalidState)
449        }
450        self.name(name)?;
451        self.u16(kind.value())?;
452        self.u16(if unicast {
453            CLASS_IN | UNICAST_RESPONSE
454        } else {
455            CLASS_IN
456        })?;
457        self.bump(0)
458    }
459
460    /// Writes a record into the Answer section.
461    pub fn answer(&mut self, record: &Record<'n>) -> Result<()> {
462        self.record(record)?;
463        self.bump(1)
464    }
465
466    /// Writes a record into the Authority section.
467    ///
468    /// RFC 6762 §8.2: a probe query "populates the query message's Authority Section with the
469    /// record or records with the rdata that it would be proposing to use, should its probing
470    /// be successful … for tiebreaking to work correctly in all cases, the Authority Section
471    /// must contain *all* the records and proposed rdata being probed for uniqueness". It is
472    /// also what lets a receiver tell a probe from an ordinary query (§6).
473    pub fn authority(&mut self, record: &Record<'n>) -> Result<()> {
474        self.record(record)?;
475        self.bump(2)
476    }
477
478    /// Writes a record into the Additional section.
479    ///
480    /// RFC 6762 §6.2: a responder "SHOULD include in the Additional Section" the records a
481    /// querier will need next — the SRV and TXT for a PTR it answered, the AAAA for an SRV.
482    /// Doing so is what turns a three-round-trip discovery into one.
483    pub fn additional(&mut self, record: &Record<'n>) -> Result<()> {
484        self.record(record)?;
485        self.bump(3)
486    }
487
488    /// How many records are in each section: questions, answers, authority, additional.
489    #[must_use]
490    pub const fn counts(&self) -> [u16; 4] {
491        self.counts
492    }
493
494    /// Fills in the header and returns the message.
495    ///
496    /// `id` is the transaction id, which RFC 6762 §18.1 makes zero for an unsolicited
497    /// announcement and the query's id for a response to one.
498    pub fn finish(self, id: u16, flags: u16) -> Result<&'a [u8]> {
499        let header = [
500            id.to_be_bytes(),
501            flags.to_be_bytes(),
502            self.counts.first().copied().unwrap_or(0).to_be_bytes(),
503            self.counts.get(1).copied().unwrap_or(0).to_be_bytes(),
504            self.counts.get(2).copied().unwrap_or(0).to_be_bytes(),
505            self.counts.get(3).copied().unwrap_or(0).to_be_bytes(),
506        ];
507        let slot = self.buf.get_mut(..HEADER_LEN).ok_or_else(no_space)?;
508        for (index, pair) in header.iter().enumerate() {
509            let start = index.saturating_mul(2);
510            let end = start.saturating_add(2);
511            if let Some(target) = slot.get_mut(start..end) {
512                target.copy_from_slice(pair);
513            }
514        }
515        self.buf.get(..self.at).ok_or_else(no_space)
516    }
517
518    fn bump(&mut self, section: usize) -> Result<()> {
519        let slot = self.counts.get_mut(section).ok_or_else(malformed)?;
520        *slot = slot.checked_add(1).ok_or_else(no_space)?;
521        Ok(())
522    }
523
524    fn record(&mut self, record: &Record<'n>) -> Result<()> {
525        self.name(record.name)?;
526        self.u16(record.data.kind().value())?;
527        self.u16(if record.cache_flush {
528            CLASS_IN | CACHE_FLUSH
529        } else {
530            CLASS_IN
531        })?;
532        self.u32(record.ttl)?;
533        // RDLENGTH is not known until the RDATA is written, and the RDATA may itself contain a
534        // compressed name — so the length is written as a placeholder and patched.
535        let length_at = self.at;
536        self.u16(0)?;
537        let start = self.at;
538        match record.data {
539            RecordData::Ptr(target) => self.name(target)?,
540            RecordData::Srv { port, target } => {
541                // Priority and weight are both zero: Matter advertises one instance per
542                // service, so there is nothing to prioritise between.
543                self.u16(0)?;
544                self.u16(0)?;
545                self.u16(port)?;
546                // RFC 2782 says an SRV target must not be compressed; RFC 6762 §18.14 says
547                // Multicast DNS responders MAY compress it, and every deployed one does.
548                self.name(target)?;
549            }
550            RecordData::Txt(bytes) => self.bytes(bytes)?,
551            RecordData::Aaaa(address) => self.bytes(&address)?,
552            RecordData::A(address) => self.bytes(&address)?,
553        }
554        let length = self.at.checked_sub(start).ok_or_else(malformed)?;
555        let length = u16::try_from(length).map_err(|_| no_space())?;
556        if let Some(slot) = self.buf.get_mut(length_at..length_at.saturating_add(2)) {
557            slot.copy_from_slice(&length.to_be_bytes());
558        }
559        Ok(())
560    }
561
562    /// Writes a name, compressing against the longest suffix already written.
563    ///
564    /// Label by label: at each position, ask whether the *remaining* suffix has been written
565    /// before. If it has, emit a pointer to it and stop — the labels before it are already on
566    /// the wire, because this loop put them there. Writing them again is the mistake that
567    /// makes a message decode to a name with every label doubled.
568    fn name(&mut self, labels: &'n [&'n str]) -> Result<()> {
569        for skip in 0..labels.len() {
570            let tail = labels.get(skip..).unwrap_or(&[]);
571            if let Some(offset) = self.find(tail) {
572                return self.u16(0xC000 | offset);
573            }
574            // Not found: remember where this suffix will start, then write its first label.
575            let offset = u16::try_from(self.at).ok();
576            // RFC 1035's pointer is fourteen bits, so a name past 0x3FFF cannot be pointed at.
577            // Recording it anyway would emit a pointer with the top bits truncated.
578            if let Some(offset) = offset.filter(|value| *value < 0x4000) {
579                let _ = self.seen.push((offset, tail));
580            }
581            let label = labels.get(skip).ok_or_else(malformed)?;
582            self.label(label)?;
583        }
584        self.byte(0)
585    }
586
587    fn find(&self, tail: &[&str]) -> Option<u16> {
588        self.seen
589            .iter()
590            .find(|(_, seen)| {
591                seen.len() == tail.len()
592                    && seen
593                        .iter()
594                        .zip(tail.iter())
595                        .all(|(a, b)| a.as_bytes().eq_ignore_ascii_case(b.as_bytes()))
596            })
597            .map(|(offset, _)| *offset)
598    }
599
600    fn label(&mut self, label: &str) -> Result<()> {
601        let bytes = label.as_bytes();
602        if bytes.is_empty() || bytes.len() > LABEL_MAX {
603            bail!(InvalidArgument)
604        }
605        self.byte(u8::try_from(bytes.len()).map_err(|_| no_space())?)?;
606        self.bytes(bytes)
607    }
608
609    fn byte(&mut self, value: u8) -> Result<()> {
610        self.bytes(&[value])
611    }
612
613    fn u16(&mut self, value: u16) -> Result<()> {
614        self.bytes(&value.to_be_bytes())
615    }
616
617    fn u32(&mut self, value: u32) -> Result<()> {
618        self.bytes(&value.to_be_bytes())
619    }
620
621    fn bytes(&mut self, value: &[u8]) -> Result<()> {
622        let end = self.at.checked_add(value.len()).ok_or_else(no_space)?;
623        let slot = self.buf.get_mut(self.at..end).ok_or_else(no_space)?;
624        slot.copy_from_slice(value);
625        self.at = end;
626        Ok(())
627    }
628}
629
630/// The twelve-octet DNS header (RFC 1035 §4.1.1).
631pub const HEADER_LEN: usize = 12;
632
633/// `QR | AA` — the flags on a Multicast DNS response (RFC 6762 §18.2, §18.4).
634///
635/// "In response messages the Authoritative Answer bit MUST be set to one", and multicast DNS
636/// has no notion of a non-authoritative answer.
637pub const FLAGS_RESPONSE: u16 = 0x8400;
638
639/// The flags on a Multicast DNS query: all zero (RFC 6762 §18.1–18.11).
640pub const FLAGS_QUERY: u16 = 0x0000;
641
642fn no_space() -> Error {
643    Error::new(ErrorCode::NoSpace)
644}
645
646/// One question read from a message.
647#[derive(Debug, Clone, PartialEq, Eq)]
648pub struct Question {
649    /// The name asked about.
650    pub name: Name,
651    /// The type asked for. `ANY` is ordinary in Multicast DNS.
652    pub kind: RecordType,
653    /// RFC 6762 §5.4's unicast-response bit.
654    pub unicast: bool,
655}
656
657/// Reads the questions from a DNS message.
658///
659/// Only the questions: a responder has no use for another responder's answers beyond RFC
660/// 6762 §7.1's known-answer suppression, which needs a cache this module does not have.
661#[derive(Debug, Clone)]
662pub struct Questions<'a> {
663    buf: &'a [u8],
664    at: usize,
665    left: u16,
666}
667
668impl<'a> Questions<'a> {
669    /// Reads a message's header and positions at its first question.
670    pub fn decode(buf: &'a [u8]) -> Result<Self> {
671        let header = buf.get(..HEADER_LEN).ok_or_else(truncated)?;
672        let count = u16::from_be_bytes([
673            header.get(4).copied().ok_or_else(truncated)?,
674            header.get(5).copied().ok_or_else(truncated)?,
675        ]);
676        Ok(Self {
677            buf,
678            at: HEADER_LEN,
679            left: count,
680        })
681    }
682
683    /// The message's transaction id.
684    #[must_use]
685    pub fn id(&self) -> u16 {
686        u16::from_be_bytes([
687            self.buf.first().copied().unwrap_or(0),
688            self.buf.get(1).copied().unwrap_or(0),
689        ])
690    }
691
692    /// Whether this message is a response — RFC 1035's `QR` bit.
693    ///
694    /// A responder ignores responses: RFC 6762 §6 has it answer queries only, and answering a
695    /// response would be an easy way to make two devices talk to each other forever.
696    #[must_use]
697    pub fn is_response(&self) -> bool {
698        self.buf.get(2).copied().unwrap_or(0) & 0x80 != 0
699    }
700}
701
702impl Iterator for Questions<'_> {
703    type Item = Result<Question>;
704
705    fn next(&mut self) -> Option<Self::Item> {
706        if self.left == 0 {
707            return None;
708        }
709        self.left = self.left.saturating_sub(1);
710        Some(self.read())
711    }
712}
713
714impl Questions<'_> {
715    fn read(&mut self) -> Result<Question> {
716        let (name, after) = Name::decode(self.buf, self.at)?;
717        let kind_at = after;
718        let class_at = kind_at.checked_add(2).ok_or_else(malformed)?;
719        let end = class_at.checked_add(2).ok_or_else(malformed)?;
720        let kind = u16::from_be_bytes([
721            self.buf.get(kind_at).copied().ok_or_else(truncated)?,
722            self.buf
723                .get(kind_at.saturating_add(1))
724                .copied()
725                .ok_or_else(truncated)?,
726        ]);
727        let class = u16::from_be_bytes([
728            self.buf.get(class_at).copied().ok_or_else(truncated)?,
729            self.buf
730                .get(class_at.saturating_add(1))
731                .copied()
732                .ok_or_else(truncated)?,
733        ]);
734        self.at = end;
735        // A question for a class other than IN is not for us. It is not an error either —
736        // "if the responder has no records that answer the question, it MUST NOT send any
737        // response" — so it decodes as a type nothing matches.
738        let kind = if class & !UNICAST_RESPONSE == CLASS_IN {
739            RecordType::from_value(kind)
740        } else {
741            None
742        };
743        Ok(Question {
744            name,
745            kind: kind.unwrap_or(RecordType::Nsec),
746            unicast: class & UNICAST_RESPONSE != 0,
747        })
748    }
749}
750
751/// Which section of a message a record was read from.
752///
753/// It matters: RFC 6762 §8.2's tiebreaker records live in the **Authority** section and are a
754/// *proposal*, while a conflicting record in any other section is a *claim* — §9's conflict
755/// resolution and §8.2's tiebreak are different rules with different outcomes, and telling
756/// them apart starts here.
757#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758#[non_exhaustive]
759pub enum Section {
760    /// Answer — what the message asserts.
761    Answer,
762    /// Authority — for a probe query, the rdata the prober proposes to use (§8.2).
763    Authority,
764    /// Additional — what the sender thinks the receiver will want next (§6.2).
765    Additional,
766}
767
768/// One resource record read from a message.
769///
770/// The RDATA is borrowed from the message, and a name inside it — a PTR's target, an SRV's
771/// host — has already been decompressed into a [`Name`], because a pointer is meaningless
772/// once separated from the message it points into.
773#[derive(Debug, Clone, PartialEq, Eq)]
774pub struct ReadRecord<'a> {
775    /// Which section the record came from.
776    pub section: Section,
777    /// The record class, with RFC 6762 §10.2's cache-flush bit masked off.
778    ///
779    /// §8.2 compares "the record class (excluding the cache-flush bit …)" first, so the bit has
780    /// to be gone before a comparison rather than after it.
781    pub class: u16,
782    /// The owner name.
783    pub name: Name,
784    /// The record type, or `None` for one this crate does not model.
785    ///
786    /// Not an error: "Nodes SHALL silently ignore TXT record keys that they do not recognize"
787    /// is the same spirit as ignoring a record type, and a responder on the link may publish
788    /// anything.
789    pub kind: Option<RecordType>,
790    /// Seconds. Zero is RFC 6762 §10.1's goodbye — "this record is going away".
791    pub ttl: u32,
792    /// RFC 6762 §10.2's cache-flush bit.
793    pub cache_flush: bool,
794    /// The decoded data, for the types this crate models.
795    pub data: Option<ReadData<'a>>,
796}
797
798/// The decoded RDATA of a read record.
799#[derive(Debug, Clone, PartialEq, Eq)]
800pub enum ReadData<'a> {
801    /// `PTR` — the target name, decompressed.
802    Ptr(Name),
803    /// `SRV` — the port and the target host, decompressed.
804    Srv {
805        /// The advertised port.
806        port: u16,
807        /// The target host name.
808        target: Name,
809    },
810    /// `TXT` — the raw key/value strings, to be read with
811    /// [`TxtReader`](crate::discovery::txt::TxtReader).
812    Txt(&'a [u8]),
813    /// `AAAA` — an IPv6 address.
814    Aaaa([u8; 16]),
815    /// `A` — an IPv4 address. Matter "does not use IPv4"; a reader still has to step over one.
816    A([u8; 4]),
817}
818
819impl ReadData<'_> {
820    /// Writes the RDATA **uncompressed**, the form RFC 6762 §8.2's tiebreak compares.
821    ///
822    /// The mirror of [`RecordData::write_rdata`], for a record that arrived on the wire: the
823    /// names here were decompressed on decode, so this re-serialises them in the canonical
824    /// form both sides of a tiebreak must be in.
825    ///
826    /// [`RDATA_MAX`] is always enough.
827    pub fn write_rdata<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
828        let mut cursor = Cursor::new(buf);
829        match self {
830            Self::Ptr(target) => cursor.put_labels(target.labels())?,
831            Self::Srv { port, target } => {
832                cursor.put_u16(0)?;
833                cursor.put_u16(0)?;
834                cursor.put_u16(*port)?;
835                cursor.put_labels(target.labels())?;
836            }
837            Self::Txt(bytes) => cursor.put(bytes)?,
838            Self::Aaaa(address) => cursor.put(address)?,
839            Self::A(address) => cursor.put(address)?,
840        }
841        cursor.finish()
842    }
843}
844
845/// Reads the resource records of a message, in wire order across all three sections.
846///
847/// A Matter commissioner needs this: a `_matterc._udp` browse answers with a PTR, and the
848/// Additional section carries the SRV, TXT and AAAA that turn it into an address and a port.
849#[derive(Debug, Clone)]
850pub struct ResourceRecords<'a> {
851    buf: &'a [u8],
852    at: usize,
853    /// How many records remain in each of Answer, Authority and Additional, in wire order.
854    left: [u32; 3],
855    /// Set once a record failed to decode: the cursor is no longer at a record boundary, so
856    /// everything after it is noise.
857    stopped: bool,
858}
859
860impl<'a> ResourceRecords<'a> {
861    /// Positions at the first record, skipping the questions.
862    pub fn decode(buf: &'a [u8]) -> Result<Self> {
863        let header = buf.get(..HEADER_LEN).ok_or_else(truncated)?;
864        let count_at = |index: usize| -> Result<u16> {
865            let start = index.saturating_mul(2);
866            Ok(u16::from_be_bytes([
867                header.get(start).copied().ok_or_else(truncated)?,
868                header
869                    .get(start.saturating_add(1))
870                    .copied()
871                    .ok_or_else(truncated)?,
872            ]))
873        };
874        let questions = count_at(2)?;
875        let left = [
876            u32::from(count_at(3)?),
877            u32::from(count_at(4)?),
878            u32::from(count_at(5)?),
879        ];
880
881        // Step over the questions: each is a name plus four octets.
882        let mut at = HEADER_LEN;
883        for _ in 0..questions {
884            let (_, after) = Name::decode(buf, at)?;
885            at = after.checked_add(4).ok_or_else(malformed)?;
886        }
887        Ok(Self {
888            buf,
889            at,
890            left,
891            stopped: false,
892        })
893    }
894
895    /// Only the records of one section.
896    ///
897    /// Errors are **kept**, not filtered out. A caller reading the Authority section of a
898    /// hostile message to tiebreak against it must be able to tell "there was no tiebreaker"
899    /// from "the message was malformed"; silently dropping the error turns the second into the
900    /// first, and the second is the one where a name gets claimed that should not have been.
901    /// The underlying iteration stops at its first error, so at most one arrives.
902    pub fn section(self, section: Section) -> impl Iterator<Item = Result<ReadRecord<'a>>> {
903        self.filter(move |record| !matches!(record, Ok(record) if record.section != section))
904    }
905}
906
907impl<'a> Iterator for ResourceRecords<'a> {
908    type Item = Result<ReadRecord<'a>>;
909
910    fn next(&mut self) -> Option<Self::Item> {
911        if self.stopped {
912            return None;
913        }
914        let index = self.left.iter().position(|left| *left != 0)?;
915        if let Some(left) = self.left.get_mut(index) {
916            *left = left.saturating_sub(1);
917        }
918        let section = match index {
919            0 => Section::Answer,
920            1 => Section::Authority,
921            _ => Section::Additional,
922        };
923        // One error ends the iteration. After a record that did not decode, `at` is no longer
924        // at a record boundary, so every further "record" is an arbitrary reading of whatever
925        // follows — and a header claiming 65535 records would otherwise buy 65535 of them.
926        let record = self.read(section);
927        self.stopped = record.is_err();
928        Some(record)
929    }
930}
931
932impl<'a> ResourceRecords<'a> {
933    fn read(&mut self, section: Section) -> Result<ReadRecord<'a>> {
934        let (name, after) = Name::decode(self.buf, self.at)?;
935        let be16 = |at: usize| -> Result<u16> {
936            Ok(u16::from_be_bytes([
937                self.buf.get(at).copied().ok_or_else(truncated)?,
938                self.buf
939                    .get(at.saturating_add(1))
940                    .copied()
941                    .ok_or_else(truncated)?,
942            ]))
943        };
944        let kind_value = be16(after)?;
945        let class = be16(after.checked_add(2).ok_or_else(malformed)?)?;
946        let ttl_at = after.checked_add(4).ok_or_else(malformed)?;
947        let ttl = u32::from_be_bytes([
948            self.buf.get(ttl_at).copied().ok_or_else(truncated)?,
949            self.buf
950                .get(ttl_at.saturating_add(1))
951                .copied()
952                .ok_or_else(truncated)?,
953            self.buf
954                .get(ttl_at.saturating_add(2))
955                .copied()
956                .ok_or_else(truncated)?,
957            self.buf
958                .get(ttl_at.saturating_add(3))
959                .copied()
960                .ok_or_else(truncated)?,
961        ]);
962        let length_at = ttl_at.checked_add(4).ok_or_else(malformed)?;
963        let length = usize::from(be16(length_at)?);
964        let start = length_at.checked_add(2).ok_or_else(malformed)?;
965        let end = start.checked_add(length).ok_or_else(malformed)?;
966        let rdata = self.buf.get(start..end).ok_or_else(truncated)?;
967        self.at = end;
968
969        let kind = RecordType::from_value(kind_value);
970        let data = match kind {
971            // A name inside RDATA may point anywhere in the message, so it is decoded against
972            // the whole buffer rather than against the RDATA slice.
973            Some(RecordType::Ptr) => Some(ReadData::Ptr(Name::decode(self.buf, start)?.0)),
974            Some(RecordType::Srv) => {
975                let port = be16(start.checked_add(4).ok_or_else(malformed)?)?;
976                let target = Name::decode(self.buf, start.checked_add(6).ok_or_else(malformed)?)?.0;
977                Some(ReadData::Srv { port, target })
978            }
979            Some(RecordType::Txt) => Some(ReadData::Txt(rdata)),
980            Some(RecordType::Aaaa) => {
981                let address: [u8; 16] = rdata.try_into().map_err(|_| malformed())?;
982                Some(ReadData::Aaaa(address))
983            }
984            Some(RecordType::A) => {
985                let address: [u8; 4] = rdata.try_into().map_err(|_| malformed())?;
986                Some(ReadData::A(address))
987            }
988            _ => None,
989        };
990
991        Ok(ReadRecord {
992            section,
993            class: class & !CACHE_FLUSH,
994            name,
995            kind,
996            ttl,
997            cache_flush: class & CACHE_FLUSH != 0,
998            data,
999        })
1000    }
1001}