Skip to main content

matter_kit/discovery/
mod.rs

1//! Service advertising and discovery (Core §4.3) — how a Matter node is found.
2//!
3//! > Service Advertising and Discovery for Matter uses IETF Standard DNS-Based Service
4//! > Discovery (DNS-SD) [RFC 6763]. **Matter requires no modifications to IETF Standard
5//! > DNS-SD.**
6//!
7//! That sentence is the shape of this module: everything here is ordinary DNS-SD, and what
8//! Matter adds is a naming convention and a set of TXT keys.
9//!
10//! | Context | Service type | Instance name |
11//! |---|---|---|
12//! | Commissionable Node (§4.3.1) | `_matterc._udp` | a random 64-bit value, 16 hex digits |
13//! | Operational (§4.3.2) | `_matter._tcp` | `<compressed-fabric>-<node-id>` |
14//! | Commissioner (§4.3.3) | `_matterd._udp` | vendor's choice |
15//!
16//! `_matter._tcp` is not a mistake: "the string `_tcp` is boilerplate text inherited from the
17//! original DNS SRV specification … and doesn't necessarily mean that the advertised
18//! application-layer protocol runs only over TCP" (§4.3.2.3). Matter's operational transport
19//! is UDP with MRP.
20//!
21//! # Why the instance name is random, and why it changes
22//!
23//! §4.3.1: "the DNS-SD instance name SHALL be a dynamic, pseudo-randomly selected, 64-bit
24//! temporary unique identifier … A new instance name SHALL be selected when the Node boots. A
25//! new instance name SHALL be selected whenever the Node enters Commissioning mode."
26//!
27//! A stable name would be a tracking identifier — a device advertising the same sixteen hex
28//! digits on every network it ever joins. The rule that it "SHALL NOT change while the Node is
29//! in commissioning mode" is the other half: a commissioner that found the device must still
30//! be able to reach it.
31//!
32//! # What is here and what is not
33//!
34//! The record model, the TXT keys, the DNS wire format, a responder that turns a query into a
35//! response, and the *schedule* that says when anything may be sent at all — RFC 6762 §8's
36//! probing and announcing, §9's conflict resolution and §6's rate limits, in [`schedule`].
37//! [`responder`] decides what a message says; [`schedule`] decides when. Neither owns a socket
38//! or a clock: the caller polls, sends, and sleeps until [`Schedule::wake_at`].
39//!
40//! What is not here: the `std` OS backends (Avahi, systemd-resolved, `dns-sd`) and the SRP
41//! client Thread requires — platform code rather than protocol.
42//!
43//! ```
44//! use matter_kit::discovery::{
45//!     self, CommissionableSubtypes, COMMISSIONABLE_SERVICE,
46//! };
47//! use matter_kit::discovery::responder::{Advertisement, Responder};
48//! use matter_kit::discovery::txt::{CommissionableTxt, CommissioningMode};
49//! use matter_kit::msg::VendorId;
50//!
51//! // §4.3.1.14's own example: discriminator 840, in commissioning mode after an
52//! // OpenCommissioningWindow.
53//! let txt = CommissionableTxt {
54//!     discriminator: 840,
55//!     commissioning_mode: CommissioningMode::Enhanced,
56//!     ..CommissionableTxt::default()
57//! }
58//! .encode()?;
59//!
60//! // The instance name is random and changes whenever the node enters commissioning mode;
61//! // the host name comes from a link-layer address.
62//! let instance = discovery::commissionable_instance_name(0xDD20_0C20_D25A_E5F7);
63//! let host = discovery::host_name(&[0xB7, 0x5A, 0xFB, 0x45, 0x8E, 0xCD])?;
64//! assert_eq!(instance.as_str(), "DD200C20D25AE5F7");
65//!
66//! // `_CM` is derived from the same commissioning mode the TXT key is, so the two cannot
67//! // disagree — §4.3.1.3 forbids publishing it when `CM=0`.
68//! let subtypes = CommissionableSubtypes::new(840, CommissioningMode::Enhanced);
69//! let mut advertisement =
70//!     Advertisement::new(&instance, COMMISSIONABLE_SERVICE, &host, 11111, txt.finish());
71//! for subtype in subtypes.labels() {
72//!     advertisement = advertisement.with_subtype(subtype)?;
73//! }
74//! advertisement = advertisement.with_address([
75//!     0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0xF5, 0x15, 0x57, 0x6F, 0x97, 0x83, 0x3F, 0x30,
76//! ])?;
77//!
78//! let advertisements = [advertisement];
79//! let responder = Responder::new(&advertisements);
80//! let mut buf = [0u8; 1024];
81//! let announcement = responder.announce(&mut buf)?;
82//! assert!(!announcement.is_empty());
83//! # Ok::<(), matter_kit::Error>(())
84//! ```
85
86pub mod advertiser;
87pub mod dns;
88pub mod responder;
89pub mod schedule;
90pub mod txt;
91
92pub use advertiser::Advertiser;
93pub use dns::{Name, ReadData, ReadRecord, RecordType, ResourceRecords};
94pub use responder::{Advertisement, Responder};
95pub use schedule::{Action, Phase, Schedule};
96pub use txt::{CommissionableTxt, CommissioningMode, MrpAdvertisement, OperationalTxt, TxtWriter};
97
98use heapless::String;
99
100use crate::error::{Error, ErrorCode, Result};
101
102/// `_matterc._udp` — Commissionable Node Discovery (§4.3.1).
103pub const COMMISSIONABLE_SERVICE: [&str; 2] = ["_matterc", "_udp"];
104
105/// `_matter._tcp` — Operational Discovery (§4.3.2.3).
106pub const OPERATIONAL_SERVICE: [&str; 2] = ["_matter", "_tcp"];
107
108/// `_matterd._udp` — Commissioner Discovery (§4.3.3).
109pub const COMMISSIONER_SERVICE: [&str; 2] = ["_matterd", "_udp"];
110
111/// `local` — "For link-local Multicast DNS the service domain SHALL be local" (§4.3.1).
112pub const LOCAL_DOMAIN: &str = "local";
113
114/// `_sub` — RFC 6763 §7.1's subtype label.
115pub const SUBTYPE_LABEL: &str = "_sub";
116
117/// The port Multicast DNS runs on (RFC 6762 §5).
118pub const MDNS_PORT: u16 = 5353;
119
120/// `ff02::fb` — RFC 6762's link-local IPv6 multicast group.
121///
122/// IPv6 only: §4.3 asks that "announcements and answers for this service need only be
123/// performed over IPv6", and "A Matter device that only supports IPv6 gets these
124/// optimizations automatically, simply by virtue of not supporting IPv4 at all."
125pub const MDNS_IPV6_GROUP: [u8; 16] = [0xFF, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFB];
126
127/// RFC 6762 §10's TTL for records that contain a host name — A, AAAA, SRV.
128///
129/// Two minutes, "so that stale data is quickly purged" when a device moves or its address
130/// changes.
131pub const HOST_RECORD_TTL: u32 = 120;
132
133/// RFC 6762 §10's TTL for everything else — PTR, TXT.
134///
135/// Seventy-five minutes. These records do not go stale when an address changes, and a longer
136/// TTL is what keeps a quiet network quiet.
137pub const OTHER_RECORD_TTL: u32 = 4500;
138
139/// The length of the hexadecimal instance name §4.3.1 and §4.3.2.1 both use.
140///
141/// Sixteen characters for commissionable discovery's 64-bit random value; thirty-three for
142/// operational discovery's `<16>-<16>`.
143pub const INSTANCE_NAME_LEN: usize = 16;
144
145/// The longest instance name: operational discovery's `<compressed>-<node>`.
146pub const INSTANCE_NAME_MAX: usize = 33;
147
148/// The longest host name: §4.3.1.1's sixteen-character form, for a 64-bit MAC Extended
149/// Address.
150pub const HOST_NAME_MAX: usize = 16;
151
152/// A commissionable node's instance name — §4.3.1's "dynamic, pseudo-randomly selected,
153/// 64-bit temporary unique identifier, expressed as a fixed-length sixteen-character
154/// hexadecimal string, encoded as ASCII (UTF-8) text using **capital letters**".
155///
156/// The randomness is a parameter rather than something this crate draws, for the same reason
157/// every other source of entropy is: it comes from the one [`Rng`](crate::platform::Rng) the
158/// integrator installed.
159#[must_use]
160pub fn commissionable_instance_name(random: u64) -> String<INSTANCE_NAME_LEN> {
161    let mut out = String::new();
162    push_hex(&mut out, &random.to_be_bytes());
163    out
164}
165
166/// A node's host name — §4.3.1.1's "fixed-length twelve-character (or sixteen-character)
167/// hexadecimal string" built from a link-layer address.
168///
169/// > In the event that a device performs MAC address randomization for privacy, then the
170/// > target host name SHALL use the privacy-preserving randomized version and the hostname
171/// > SHALL be updated in the record every time the underlying link-layer address rotates.
172///
173/// Accepts a 6-octet MAC (Ethernet, Wi-Fi) or an 8-octet MAC Extended Address (Thread).
174pub fn host_name(link_layer_address: &[u8]) -> Result<String<HOST_NAME_MAX>> {
175    if !matches!(link_layer_address.len(), 6 | 8) {
176        return Err(Error::new(ErrorCode::InvalidArgument));
177    }
178    let mut out = String::new();
179    push_hex(&mut out, link_layer_address);
180    Ok(out)
181}
182
183/// Appends octets as uppercase hexadecimal.
184pub(crate) fn push_hex<const N: usize>(out: &mut String<N>, bytes: &[u8]) {
185    const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
186    for byte in bytes {
187        let hi = DIGITS.get(usize::from(byte >> 4)).copied().unwrap_or(b'0');
188        let lo = DIGITS
189            .get(usize::from(byte & 0x0F))
190            .copied()
191            .unwrap_or(b'0');
192        let _ = out.push(hi as char);
193        let _ = out.push(lo as char);
194    }
195}
196
197/// A DNS-SD subtype label, as §4.3.1.3 and §4.3.2.3 define them.
198///
199/// | Subtype | Meaning | Encoding |
200/// |---|---|---|
201/// | `_L<dddd>` | the full 12-bit discriminator | decimal, no leading zeroes |
202/// | `_S<dd>` | its upper four bits | decimal, no leading zeroes |
203/// | `_V<ddddd>` | the 16-bit Vendor ID | decimal, no leading zeroes |
204/// | `_T<ddd>` | the primary device type | decimal, no leading zeroes |
205/// | `_CM` | "currently in Commissioning Mode" | no value |
206/// | `_I<hhhh>` | the Compressed Fabric Identifier | **exactly 16 uppercase hex** |
207///
208/// The two encodings are not interchangeable, and the difference is easy to miss: every
209/// commissionable subtype is *decimal with leading zeroes omitted*, while the operational one
210/// is *fixed-width hexadecimal*. A subtype in the wrong form is a name nobody browses for, and
211/// the device is simply never found.
212pub const SUBTYPE_MAX: usize = 18;
213
214/// `_L<dddd>` — the long discriminator subtype (§4.3.1.3).
215#[must_use]
216pub fn long_discriminator_subtype(discriminator: u16) -> String<SUBTYPE_MAX> {
217    decimal_subtype('L', u32::from(discriminator & 0x0FFF))
218}
219
220/// `_S<dd>` — the short discriminator subtype: "the upper 4 bits of the discriminator".
221#[must_use]
222pub fn short_discriminator_subtype(discriminator: u16) -> String<SUBTYPE_MAX> {
223    decimal_subtype('S', u32::from((discriminator & 0x0FFF) >> 8))
224}
225
226/// `_V<ddddd>` — the Vendor ID subtype.
227#[must_use]
228pub fn vendor_subtype(vendor_id: crate::msg::VendorId) -> String<SUBTYPE_MAX> {
229    decimal_subtype('V', u32::from(vendor_id.0))
230}
231
232/// `_T<ddd>` — the primary device type subtype.
233#[must_use]
234pub fn device_type_subtype(device_type: u32) -> String<SUBTYPE_MAX> {
235    decimal_subtype('T', device_type)
236}
237
238/// `_CM` — "currently in Commissioning Mode".
239///
240/// §4.3.1.3: "the subtype is `_CM` regardless of whether the TXT record for commissioning mode
241/// is set to 1 (CM=1), 2 (CM=2) or 3 (CM=3). A Commissionee that is not in commissioning mode
242/// (CM=0) SHALL NOT publish this subtype."
243pub const COMMISSIONING_MODE_SUBTYPE: &str = "_CM";
244
245/// `_IC` — Incomplete Commissioning (§4.3.2.5), for NFC-based commissioning.
246pub const INCOMPLETE_COMMISSIONING_SUBTYPE: &str = "_IC";
247
248fn decimal_subtype(letter: char, value: u32) -> String<SUBTYPE_MAX> {
249    let mut out = String::new();
250    let _ = out.push('_');
251    let _ = out.push(letter);
252    push_decimal(&mut out, value);
253    out
254}
255
256/// Appends a decimal number "omitting any leading zeroes" — which for zero means the single
257/// digit `0`, not the empty string.
258pub(crate) fn push_decimal<const N: usize>(out: &mut String<N>, value: u32) {
259    if value == 0 {
260        let _ = out.push('0');
261        return;
262    }
263    let mut digits = [0u8; 10];
264    let mut at = digits.len();
265    let mut rest = value;
266    while rest > 0 {
267        at = at.saturating_sub(1);
268        if let Some(slot) = digits.get_mut(at) {
269            *slot = b'0'.saturating_add(u8::try_from(rest % 10).unwrap_or(0));
270        }
271        rest /= 10;
272    }
273    for digit in digits.get(at..).unwrap_or(&[]) {
274        let _ = out.push(*digit as char);
275    }
276}
277
278/// Builds a commissionable advertisement's subtypes from what §4.3.1.3 says to publish.
279///
280/// The five subtypes are not independent: `_CM` appears only in commissioning mode, `_V` and
281/// `_T` only if the device chooses to publish them at all ("a vendor MAY choose not to include
282/// it at all, for privacy reasons"), and the two discriminator subtypes always. Assembling
283/// them in one place is what keeps a device from publishing `_CM` while advertising `CM=0`,
284/// which §4.3.1.3 forbids and which nothing else would catch.
285#[derive(Debug, Clone)]
286pub struct CommissionableSubtypes {
287    long: String<SUBTYPE_MAX>,
288    short: String<SUBTYPE_MAX>,
289    vendor: Option<String<SUBTYPE_MAX>>,
290    device_type: Option<String<SUBTYPE_MAX>>,
291    commissioning_mode: bool,
292}
293
294impl CommissionableSubtypes {
295    /// The subtypes for a device with this discriminator and commissioning mode.
296    #[must_use]
297    pub fn new(discriminator: u16, mode: txt::CommissioningMode) -> Self {
298        Self {
299            long: long_discriminator_subtype(discriminator),
300            short: short_discriminator_subtype(discriminator),
301            vendor: None,
302            device_type: None,
303            commissioning_mode: mode.publishes_subtype(),
304        }
305    }
306
307    /// Also publish `_V<vendor>`.
308    #[must_use]
309    pub fn with_vendor(mut self, vendor_id: crate::msg::VendorId) -> Self {
310        self.vendor = Some(vendor_subtype(vendor_id));
311        self
312    }
313
314    /// Also publish `_T<device-type>`.
315    ///
316    /// "In case the device combines multiple device types, the manufacturer SHOULD choose the
317    /// device type identifier of the primary function of the device."
318    #[must_use]
319    pub fn with_device_type(mut self, device_type: u32) -> Self {
320        self.device_type = Some(device_type_subtype(device_type));
321        self
322    }
323
324    /// The subtype labels, in §4.3.1.14's order: `_S`, `_L`, `_V`, `_CM`, `_T`.
325    pub fn labels(&self) -> impl Iterator<Item = &str> {
326        core::iter::once(self.short.as_str())
327            .chain(core::iter::once(self.long.as_str()))
328            .chain(self.vendor.as_deref())
329            .chain(
330                self.commissioning_mode
331                    .then_some(COMMISSIONING_MODE_SUBTYPE),
332            )
333            .chain(self.device_type.as_deref())
334    }
335}
336
337/// The operational subtype for a fabric — `_I<hhhh>`, "exactly 16 uppercase hexadecimal
338/// characters" (§4.3.2.3).
339///
340/// Not decimal, unlike every commissionable subtype, and not variable-width. A subtype in the
341/// wrong form is a name nobody browses for, and the node is simply never found on its fabric.
342///
343/// [`CompressedFabricId::subtype`](crate::fabric::CompressedFabricId::subtype) is the same
344/// value; this is here so the two naming conventions sit side by side, where the difference
345/// between them is visible.
346#[cfg(feature = "rustcrypto")]
347#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
348#[must_use]
349pub fn compressed_fabric_subtype(
350    compressed: crate::fabric::CompressedFabricId,
351) -> String<SUBTYPE_MAX> {
352    compressed.subtype()
353}