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 dns;
87pub mod responder;
88pub mod schedule;
89pub mod txt;
90
91pub use dns::{Name, ReadData, ReadRecord, RecordType, ResourceRecords};
92pub use responder::{Advertisement, Responder};
93pub use schedule::{Action, Phase, Schedule};
94pub use txt::{CommissionableTxt, CommissioningMode, MrpAdvertisement, OperationalTxt, TxtWriter};
95
96use heapless::String;
97
98use crate::error::{Error, ErrorCode, Result};
99
100/// `_matterc._udp` — Commissionable Node Discovery (§4.3.1).
101pub const COMMISSIONABLE_SERVICE: [&str; 2] = ["_matterc", "_udp"];
102
103/// `_matter._tcp` — Operational Discovery (§4.3.2.3).
104pub const OPERATIONAL_SERVICE: [&str; 2] = ["_matter", "_tcp"];
105
106/// `_matterd._udp` — Commissioner Discovery (§4.3.3).
107pub const COMMISSIONER_SERVICE: [&str; 2] = ["_matterd", "_udp"];
108
109/// `local` — "For link-local Multicast DNS the service domain SHALL be local" (§4.3.1).
110pub const LOCAL_DOMAIN: &str = "local";
111
112/// `_sub` — RFC 6763 §7.1's subtype label.
113pub const SUBTYPE_LABEL: &str = "_sub";
114
115/// The port Multicast DNS runs on (RFC 6762 §5).
116pub const MDNS_PORT: u16 = 5353;
117
118/// `ff02::fb` — RFC 6762's link-local IPv6 multicast group.
119///
120/// IPv6 only: §4.3 asks that "announcements and answers for this service need only be
121/// performed over IPv6", and "A Matter device that only supports IPv6 gets these
122/// optimizations automatically, simply by virtue of not supporting IPv4 at all."
123pub const MDNS_IPV6_GROUP: [u8; 16] = [0xFF, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFB];
124
125/// RFC 6762 §10's TTL for records that contain a host name — A, AAAA, SRV.
126///
127/// Two minutes, "so that stale data is quickly purged" when a device moves or its address
128/// changes.
129pub const HOST_RECORD_TTL: u32 = 120;
130
131/// RFC 6762 §10's TTL for everything else — PTR, TXT.
132///
133/// Seventy-five minutes. These records do not go stale when an address changes, and a longer
134/// TTL is what keeps a quiet network quiet.
135pub const OTHER_RECORD_TTL: u32 = 4500;
136
137/// The length of the hexadecimal instance name §4.3.1 and §4.3.2.1 both use.
138///
139/// Sixteen characters for commissionable discovery's 64-bit random value; thirty-three for
140/// operational discovery's `<16>-<16>`.
141pub const INSTANCE_NAME_LEN: usize = 16;
142
143/// The longest instance name: operational discovery's `<compressed>-<node>`.
144pub const INSTANCE_NAME_MAX: usize = 33;
145
146/// The longest host name: §4.3.1.1's sixteen-character form, for a 64-bit MAC Extended
147/// Address.
148pub const HOST_NAME_MAX: usize = 16;
149
150/// A commissionable node's instance name — §4.3.1's "dynamic, pseudo-randomly selected,
151/// 64-bit temporary unique identifier, expressed as a fixed-length sixteen-character
152/// hexadecimal string, encoded as ASCII (UTF-8) text using **capital letters**".
153///
154/// The randomness is a parameter rather than something this crate draws, for the same reason
155/// every other source of entropy is: it comes from the one [`Rng`](crate::platform::Rng) the
156/// integrator installed.
157#[must_use]
158pub fn commissionable_instance_name(random: u64) -> String<INSTANCE_NAME_LEN> {
159 let mut out = String::new();
160 push_hex(&mut out, &random.to_be_bytes());
161 out
162}
163
164/// A node's host name — §4.3.1.1's "fixed-length twelve-character (or sixteen-character)
165/// hexadecimal string" built from a link-layer address.
166///
167/// > In the event that a device performs MAC address randomization for privacy, then the
168/// > target host name SHALL use the privacy-preserving randomized version and the hostname
169/// > SHALL be updated in the record every time the underlying link-layer address rotates.
170///
171/// Accepts a 6-octet MAC (Ethernet, Wi-Fi) or an 8-octet MAC Extended Address (Thread).
172pub fn host_name(link_layer_address: &[u8]) -> Result<String<HOST_NAME_MAX>> {
173 if !matches!(link_layer_address.len(), 6 | 8) {
174 return Err(Error::new(ErrorCode::InvalidArgument));
175 }
176 let mut out = String::new();
177 push_hex(&mut out, link_layer_address);
178 Ok(out)
179}
180
181/// Appends octets as uppercase hexadecimal.
182pub(crate) fn push_hex<const N: usize>(out: &mut String<N>, bytes: &[u8]) {
183 const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
184 for byte in bytes {
185 let hi = DIGITS.get(usize::from(byte >> 4)).copied().unwrap_or(b'0');
186 let lo = DIGITS
187 .get(usize::from(byte & 0x0F))
188 .copied()
189 .unwrap_or(b'0');
190 let _ = out.push(hi as char);
191 let _ = out.push(lo as char);
192 }
193}
194
195/// A DNS-SD subtype label, as §4.3.1.3 and §4.3.2.3 define them.
196///
197/// | Subtype | Meaning | Encoding |
198/// |---|---|---|
199/// | `_L<dddd>` | the full 12-bit discriminator | decimal, no leading zeroes |
200/// | `_S<dd>` | its upper four bits | decimal, no leading zeroes |
201/// | `_V<ddddd>` | the 16-bit Vendor ID | decimal, no leading zeroes |
202/// | `_T<ddd>` | the primary device type | decimal, no leading zeroes |
203/// | `_CM` | "currently in Commissioning Mode" | no value |
204/// | `_I<hhhh>` | the Compressed Fabric Identifier | **exactly 16 uppercase hex** |
205///
206/// The two encodings are not interchangeable, and the difference is easy to miss: every
207/// commissionable subtype is *decimal with leading zeroes omitted*, while the operational one
208/// is *fixed-width hexadecimal*. A subtype in the wrong form is a name nobody browses for, and
209/// the device is simply never found.
210pub const SUBTYPE_MAX: usize = 18;
211
212/// `_L<dddd>` — the long discriminator subtype (§4.3.1.3).
213#[must_use]
214pub fn long_discriminator_subtype(discriminator: u16) -> String<SUBTYPE_MAX> {
215 decimal_subtype('L', u32::from(discriminator & 0x0FFF))
216}
217
218/// `_S<dd>` — the short discriminator subtype: "the upper 4 bits of the discriminator".
219#[must_use]
220pub fn short_discriminator_subtype(discriminator: u16) -> String<SUBTYPE_MAX> {
221 decimal_subtype('S', u32::from((discriminator & 0x0FFF) >> 8))
222}
223
224/// `_V<ddddd>` — the Vendor ID subtype.
225#[must_use]
226pub fn vendor_subtype(vendor_id: crate::msg::VendorId) -> String<SUBTYPE_MAX> {
227 decimal_subtype('V', u32::from(vendor_id.0))
228}
229
230/// `_T<ddd>` — the primary device type subtype.
231#[must_use]
232pub fn device_type_subtype(device_type: u32) -> String<SUBTYPE_MAX> {
233 decimal_subtype('T', device_type)
234}
235
236/// `_CM` — "currently in Commissioning Mode".
237///
238/// §4.3.1.3: "the subtype is `_CM` regardless of whether the TXT record for commissioning mode
239/// is set to 1 (CM=1), 2 (CM=2) or 3 (CM=3). A Commissionee that is not in commissioning mode
240/// (CM=0) SHALL NOT publish this subtype."
241pub const COMMISSIONING_MODE_SUBTYPE: &str = "_CM";
242
243/// `_IC` — Incomplete Commissioning (§4.3.2.5), for NFC-based commissioning.
244pub const INCOMPLETE_COMMISSIONING_SUBTYPE: &str = "_IC";
245
246fn decimal_subtype(letter: char, value: u32) -> String<SUBTYPE_MAX> {
247 let mut out = String::new();
248 let _ = out.push('_');
249 let _ = out.push(letter);
250 push_decimal(&mut out, value);
251 out
252}
253
254/// Appends a decimal number "omitting any leading zeroes" — which for zero means the single
255/// digit `0`, not the empty string.
256pub(crate) fn push_decimal<const N: usize>(out: &mut String<N>, value: u32) {
257 if value == 0 {
258 let _ = out.push('0');
259 return;
260 }
261 let mut digits = [0u8; 10];
262 let mut at = digits.len();
263 let mut rest = value;
264 while rest > 0 {
265 at = at.saturating_sub(1);
266 if let Some(slot) = digits.get_mut(at) {
267 *slot = b'0'.saturating_add(u8::try_from(rest % 10).unwrap_or(0));
268 }
269 rest /= 10;
270 }
271 for digit in digits.get(at..).unwrap_or(&[]) {
272 let _ = out.push(*digit as char);
273 }
274}
275
276/// Builds a commissionable advertisement's subtypes from what §4.3.1.3 says to publish.
277///
278/// The five subtypes are not independent: `_CM` appears only in commissioning mode, `_V` and
279/// `_T` only if the device chooses to publish them at all ("a vendor MAY choose not to include
280/// it at all, for privacy reasons"), and the two discriminator subtypes always. Assembling
281/// them in one place is what keeps a device from publishing `_CM` while advertising `CM=0`,
282/// which §4.3.1.3 forbids and which nothing else would catch.
283#[derive(Debug, Clone)]
284pub struct CommissionableSubtypes {
285 long: String<SUBTYPE_MAX>,
286 short: String<SUBTYPE_MAX>,
287 vendor: Option<String<SUBTYPE_MAX>>,
288 device_type: Option<String<SUBTYPE_MAX>>,
289 commissioning_mode: bool,
290}
291
292impl CommissionableSubtypes {
293 /// The subtypes for a device with this discriminator and commissioning mode.
294 #[must_use]
295 pub fn new(discriminator: u16, mode: txt::CommissioningMode) -> Self {
296 Self {
297 long: long_discriminator_subtype(discriminator),
298 short: short_discriminator_subtype(discriminator),
299 vendor: None,
300 device_type: None,
301 commissioning_mode: mode.publishes_subtype(),
302 }
303 }
304
305 /// Also publish `_V<vendor>`.
306 #[must_use]
307 pub fn with_vendor(mut self, vendor_id: crate::msg::VendorId) -> Self {
308 self.vendor = Some(vendor_subtype(vendor_id));
309 self
310 }
311
312 /// Also publish `_T<device-type>`.
313 ///
314 /// "In case the device combines multiple device types, the manufacturer SHOULD choose the
315 /// device type identifier of the primary function of the device."
316 #[must_use]
317 pub fn with_device_type(mut self, device_type: u32) -> Self {
318 self.device_type = Some(device_type_subtype(device_type));
319 self
320 }
321
322 /// The subtype labels, in §4.3.1.14's order: `_S`, `_L`, `_V`, `_CM`, `_T`.
323 pub fn labels(&self) -> impl Iterator<Item = &str> {
324 core::iter::once(self.short.as_str())
325 .chain(core::iter::once(self.long.as_str()))
326 .chain(self.vendor.as_deref())
327 .chain(
328 self.commissioning_mode
329 .then_some(COMMISSIONING_MODE_SUBTYPE),
330 )
331 .chain(self.device_type.as_deref())
332 }
333}
334
335/// The operational subtype for a fabric — `_I<hhhh>`, "exactly 16 uppercase hexadecimal
336/// characters" (§4.3.2.3).
337///
338/// Not decimal, unlike every commissionable subtype, and not variable-width. A subtype in the
339/// wrong form is a name nobody browses for, and the node is simply never found on its fabric.
340///
341/// [`CompressedFabricId::subtype`](crate::fabric::CompressedFabricId::subtype) is the same
342/// value; this is here so the two naming conventions sit side by side, where the difference
343/// between them is visible.
344#[cfg(feature = "rustcrypto")]
345#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
346#[must_use]
347pub fn compressed_fabric_subtype(
348 compressed: crate::fabric::CompressedFabricId,
349) -> String<SUBTYPE_MAX> {
350 compressed.subtype()
351}