/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { Abort, AbortedError, ChannelType, Diagnostic, DnsRecord, DnsRecordType, DnssdName, DnssdNames, Duration, Hours, IpService, Logger, MatterAggregateError, Minutes, ObserverGroup, Seconds, ServerAddressUdp, Time, Timer, Timestamp, UINT8_MAX, } from "@matter/general"; import { VendorId } from "@matter/types"; import { CommissionableDevice, CommissionableDeviceIdentifiers, DiscoveryData, parseTxtDecimal, Scanner, } from "../common/Scanner.js"; import { MATTER_COMMISSION_SERVICE_QNAME, getCommissionableDeviceQname, getCommissioningModeQname, getDeviceTypeQname, getLongDiscriminatorQname, getShortDiscriminatorQname, getVendorQname, } from "./MdnsConsts.js"; const logger = Logger.get("CommissionableMdnsScanner"); interface CachedDevice { device: CommissionableDevice; ipService: IpService; name: DnssdName; observer: (changes: DnssdName.Changes) => void; onAddresses?: () => void; } interface Waiter { notify(device: CommissionableDevice): void; cancel(): void; identifier: CommissionableDeviceIdentifiers; } /** * Discovers commissionable and commissioner Matter devices via DNS-SD using the DnssdNames infrastructure. * * Replaces the legacy MdnsClient for commissionable device scanning. */ const SPECULATIVE_TARGET_TTL = Hours(1); const SPECULATIVE_CLEANUP_INTERVAL = Minutes(30); const SPECULATIVE_TARGET_MAX = 50; // Cap discover() retry backoff so queries stay dense enough to succeed inside a commissioning window const COMMISSIONING_RETRY_INTERVAL = Seconds(30); const MAX_DISCRIMINATOR = 0xfff; export class CommissionableMdnsScanner implements Scanner { readonly type = ChannelType.UDP; readonly #names: DnssdNames; readonly #filter: (record: DnsRecord) => boolean; readonly #observers = new ObserverGroup(); readonly #cache = new Map(); readonly #waiters = new Set(); // Targets materialized by PTR-follow that never received SRV/TXT. Each target gets a child abort driving // its own SRV/TXT discover() loop and a null observer keeping the name alive until we decide to drop it. readonly #speculativeTargets = new Map(); readonly #speculativeObserver = () => undefined; readonly #speculativeCleanupTimer: Timer; readonly #scanAbort = new Abort(); constructor(names: DnssdNames) { this.#names = names; const suffix1 = `._matterc._udp.local`; const base1 = `_matterc._udp.local`; const suffix2 = `._matterd._udp.local`; const base2 = `_matterd._udp.local`; this.#filter = (record: DnsRecord) => { const lower = record.name.toLowerCase(); return lower === base1 || lower.endsWith(suffix1) || lower === base2 || lower.endsWith(suffix2); }; names.filters.add(this.#filter, [base1, base2]); this.#observers.on(names.discovered, this.#onDiscovered.bind(this)); this.#speculativeCleanupTimer = Time.getPeriodicTimer( "Speculative PTR target cleanup", SPECULATIVE_CLEANUP_INTERVAL, this.#pruneSpeculativeTargets.bind(this), ); this.#speculativeCleanupTimer.utility = true; this.#speculativeCleanupTimer.start(); } async close() { // Cancel all active discoveries so their promises resolve for (const waiter of this.#waiters) { waiter.cancel(); } this.#speculativeCleanupTimer.stop(); this.#scanAbort(); for (const qname of this.#speculativeTargets.keys()) { // maybeGet avoids resurrecting a DnssdName that already auto-deleted when records expired this.#names.maybeGet(qname)?.off(this.#speculativeObserver); } this.#speculativeTargets.clear(); this.#names.filters.delete(this.#filter); this.#observers.close(); await MatterAggregateError.allSettled( [...this.#cache.values()].map(({ ipService }) => ipService.close()), "Error closing cached IpServices", ); this.#cache.clear(); } #pruneSpeculativeTargets() { if (this.#speculativeTargets.size === 0) { return; } const cutoff = Time.nowMs - SPECULATIVE_TARGET_TTL; for (const [qname, { abort, createdAt }] of this.#speculativeTargets) { if (createdAt > cutoff) { continue; } this.#speculativeTargets.delete(qname); abort(); this.#names.maybeGet(qname)?.off(this.#speculativeObserver); } } #clearSpeculativeTarget(qname: string, name: DnssdName) { const tracking = this.#speculativeTargets.get(qname); if (tracking === undefined) { return; } this.#speculativeTargets.delete(qname); tracking.abort(); name.off(this.#speculativeObserver); } async findCommissionableDevicesContinuously( identifier: CommissionableDeviceIdentifiers, callback: (device: CommissionableDevice) => void, timeout?: Duration, cancelSignal?: Promise, ): Promise { // Pick up names already discovered before we subscribed (e.g. device broadcasts that arrived // before the scanner was created) for (const name of this.#names.discoveredNames) { this.#onDiscovered(name); } const seen = new Set(); const result: CommissionableDevice[] = []; // Must exist before delivering cached matches so the callback can cancel synchronously let cancelResolve!: () => void; const internalCancel = new Promise(resolve => (cancelResolve = resolve)); // Register waiter for new discoveries const waiter: Waiter = { identifier, cancel: cancelResolve, notify: device => { if (matchesIdentifier(device, identifier) && !seen.has(device.deviceIdentifier)) { seen.add(device.deviceIdentifier); result.push(device); callback(device); } }, }; this.#waiters.add(waiter); // Callback may trigger an async cancel chain that must settle before we start discovery let callbackInvoked = false; for (const cached of this.#cache.values()) { const device = refreshDiscoveredHost(cached); if (!matchesIdentifier(device, identifier)) { continue; } if (device.addresses.length > 0) { seen.add(device.deviceIdentifier); result.push(device); callbackInvoked = true; callback(device); } else { // Cached entry's A/AAAA records expired since the responder's last unsolicited broadcast // (matter commissionable A/AAAA TTL is short). Solicit fresh records and arm onAddresses // so this discovery's waiter is notified if addresses resolve before the timeout fires. this.#solicitAndArmAddresses(cached); } } const sleepTimer = timeout !== undefined ? Time.sleep("commissionable scanner timeout", timeout) : undefined; const signals: Promise[] = [internalCancel]; if (sleepTimer) signals.push(sleepTimer); if (cancelSignal) signals.push(cancelSignal); if (callbackInvoked) { // Macrotask boundary flushes all microtask-based cancel chains before we decide to start discovery const proceed = Symbol(); const settle = Time.sleep("cancel settlement", 0).then(() => proceed); const winner = await Promise.race([ ...signals.map(s => s.then( () => undefined, () => undefined, ), ), settle, ]); if (winner !== proceed) { sleepTimer?.cancel(); this.#waiters.delete(waiter); return result; } } const queryAbort = new Abort(); const discoveries = this.#startDiscovery(identifier, queryAbort); try { await Promise.race([...signals, discoveries]); sleepTimer?.cancel(); } finally { queryAbort(); await discoveries; this.#waiters.delete(waiter); } return result; } getDiscoveredCommissionableDevices(identifier: CommissionableDeviceIdentifiers): CommissionableDevice[] { return [...this.#cache.values()] .map(cached => refreshDiscoveredHost(cached)) .filter(device => matchesIdentifier(device, identifier) && device.addresses.length > 0); } cancelCommissionableDeviceDiscovery(identifier: CommissionableDeviceIdentifiers) { for (const waiter of this.#waiters) { if (matchesWaiterIdentifier(waiter.identifier, identifier)) { waiter.cancel(); } } } #onDiscovered(name: DnssdName) { const lower = name.qname.toLowerCase(); const matterc = lower === "_matterc._udp.local" || lower.endsWith("._matterc._udp.local"); const matterd = lower === "_matterd._udp.local" || lower.endsWith("._matterd._udp.local"); if (!matterc && !matterd) { return; } // Service-type PTRs point at instance qnames — follow targets and solicit only missing record types. // Responders usually include SRV+TXT as additional records, so no follow-up is needed in the common case. if (lower.startsWith("_")) { for (const record of name.records) { if (record.recordType !== DnsRecordType.PTR) { continue; } // Skip malformed PTRs pointing at another service-type qname; only follow pointers to instance names if (record.value.startsWith("_")) { continue; } const target = this.#names.get(record.value); let hasSrv = false; let hasTxt = false; for (const r of target.records) { if (r.recordType === DnsRecordType.SRV) { hasSrv = true; } else if (r.recordType === DnsRecordType.TXT) { hasTxt = true; } if (hasSrv && hasTxt) { break; } } const recordTypes = new Array(); if (!hasSrv) { recordTypes.push(DnsRecordType.SRV); } if (!hasTxt) { recordTypes.push(DnsRecordType.TXT); } if (recordTypes.length) { // Drive a full discover() per target so a lost SRV/TXT response triggers retry on the normal // backoff; solicitor coalesces additional callers for the same name. const targetKey = record.value.toLowerCase(); if ( !this.#speculativeTargets.has(targetKey) && this.#speculativeTargets.size < SPECULATIVE_TARGET_MAX ) { target.on(this.#speculativeObserver); const abort = new Abort({ abort: this.#scanAbort }); this.#speculativeTargets.set(targetKey, { abort, createdAt: Time.nowMs }); void this.#names.solicitor .discover({ name: target, recordTypes, abort: abort.signal, // Match the main PTR discovery cap so retries stay dense within commissioning windows retries: { maximumInterval: COMMISSIONING_RETRY_INTERVAL }, }) .catch(error => { this.#speculativeTargets.delete(targetKey); target.off(this.#speculativeObserver); if (!(error instanceof AbortedError)) { logger.warn(`Speculative discovery for ${target.qname} failed:`, error); } }); } } } return; } this.#clearSpeculativeTarget(lower, name); if (this.#cache.has(lower)) { return; } const ipService = new IpService(name.qname, Diagnostic.via("commissionable-scanner"), this.#names); // Try to build the device immediately. If required TXT fields (D, CM) are not yet available (e.g. TXT // arrives after the initial SRV/PTR), observe the name and retry on subsequent updates. const device = buildCommissionableDevice(name); if (device !== undefined) { this.#cacheDevice(lower, device, ipService, name); return; } // Solicit missing records now so we don't wait for the next PTR retry cycle const hasSrv = [...name.records].some(r => r.recordType === DnsRecordType.SRV); const recordTypes = hasSrv ? [DnsRecordType.TXT] : [DnsRecordType.SRV, DnsRecordType.TXT]; this.#names.solicitor.solicit({ name, recordTypes }); // TXT not yet available — observe for updates until we can build the device or it disappears const pendingObserver = ({ name: changedName }: DnssdName.Changes) => { if (!changedName.isDiscovered) { this.#observers.off(name, pendingObserver); void ipService.close(); return; } const built = buildCommissionableDevice(changedName); if (built !== undefined) { this.#observers.off(name, pendingObserver); this.#cacheDevice(lower, built, ipService, name); } }; this.#observers.on(name, pendingObserver); } #cacheDevice(lower: string, device: CommissionableDevice, ipService: IpService, name: DnssdName) { const observer = ({ name: changedName }: DnssdName.Changes) => { if (!changedName.isDiscovered) { const cached = this.#cache.get(lower); if (cached) { this.#cache.delete(lower); this.#observers.off(name, cached.observer); if (cached.onAddresses) { this.#observers.off(ipService.changed, cached.onAddresses); cached.onAddresses = undefined; } void cached.ipService.close(); } } }; const cached: CachedDevice = { device, ipService, name, observer }; this.#cache.set(lower, cached); this.#observers.on(name, observer); // Only notify waiters once the device has resolved IP addresses. // A/AAAA records may arrive after the initial SRV/TXT discovery; // defer notification until addresses become available. if (!this.#deliverDeviceIfResolved(cached)) { this.#solicitAndArmAddresses(cached); } } /** * Solicit A/AAAA records for the cached device's SRV target hostnames and arm an onAddresses observer * that delivers via {@link #deliverDeviceIfResolved} once addresses resolve. Used both when a device is * first cached without addresses AND when an active discovery encounters a cached entry whose A/AAAA * records have since expired (matter commissionable A/AAAA TTL is short and may lapse between the device's * unsolicited broadcasts). Idempotent: skips re-arming if onAddresses observer already attached. */ #solicitAndArmAddresses(cached: CachedDevice) { // SRV target hostname may have lost its A/AAAA records (TTL expired) while the instance // SRV/TXT was still valid. Solicit address records for all SRV target hostnames so we // don't wait for the next unsolicited broadcast to deliver the device. for (const record of cached.name.records) { if (record.recordType !== DnsRecordType.SRV) { continue; } const hostname = this.#names.get(record.value.target); this.#names.solicitor.solicit({ name: hostname, recordTypes: [DnsRecordType.A, DnsRecordType.AAAA], }); } if (cached.onAddresses !== undefined) { return; } const onAddresses = () => { if (this.#deliverDeviceIfResolved(cached)) { this.#observers.off(cached.ipService.changed, onAddresses); cached.onAddresses = undefined; } }; cached.onAddresses = onAddresses; this.#observers.on(cached.ipService.changed, onAddresses); } #deliverDeviceIfResolved(cached: CachedDevice): boolean { const device = refreshDiscoveredHost(cached); if (device.addresses.length === 0) { return false; } for (const waiter of this.#waiters) { waiter.notify(device); } return true; } async #startDiscovery(identifier: CommissionableDeviceIdentifiers, abort: Abort) { const solicitor = this.#names.solicitor; const qnames = getQueryQnames(identifier); const discoveries = qnames.map(qname => solicitor.discover({ name: this.#names.get(qname), recordTypes: [DnsRecordType.PTR], abort, // Cap backoff for commissioning: short-lived discovery shouldn't drift toward the 1h default retries: { maximumInterval: COMMISSIONING_RETRY_INTERVAL }, }), ); await MatterAggregateError.allSettled(discoveries); } } function buildCommissionableDevice(name: DnssdName): CommissionableDevice | undefined { const params = name.parameters; const D = parseTxtDecimal(params.get("D"), MAX_DISCRIMINATOR); const CM = parseTxtDecimal(params.get("CM"), UINT8_MAX); if (D === undefined || CM === undefined) { return undefined; } // Instance ID is the first label of the qname const instanceId = name.qname.split(".")[0]; const dd = DiscoveryData(params); // Default T and ICD to "none" when absent, matching legacy MdnsClient behavior dd.T ??= { tcpClient: false, tcpServer: false }; dd.ICD ??= 0; return { ...dd, deviceIdentifier: instanceId, D, CM, hostname: hostnameOf(name), addresses: [] as ServerAddressUdp[], } satisfies CommissionableDevice; } /** * The host the name's SRV records agree on, without its domain, or nothing while they disagree. * * A record's key includes its target, so a device that moves host holds two SRV records until the * superseded one is evicted — for the eviction delay where it flushed the cache, for its whole TTL * where it did not. Which of them is current cannot be read off the record set: `installedAt` is a * wall clock, so two records from the same millisecond, or a clock that steps between them, order * wrongly. Reporting nothing while the set is ambiguous keeps the field from ever naming a host the * device has left; the addresses stay authoritative for reaching it. */ function hostnameOf(name: DnssdName): string | undefined { const hosts = new Set(); for (const record of name.records) { if (record.recordType === DnsRecordType.SRV) { hosts.add(record.value.target.split(".")[0]); } } return hosts.size === 1 ? hosts.values().next().value : undefined; } /** * Restamps the facts a cached device holds about where it currently answers. * * A device is cached as soon as its TXT record identifies it, so its SRV may arrive afterwards or name * a different host later; both the addresses and the hostname are therefore read per delivery rather * than once. */ function refreshDiscoveredHost(cached: CachedDevice): CommissionableDevice { // IpService returns transport-agnostic addresses; stamp as UDP since commissionable // devices are always discovered and commissioned via UDP cached.device.addresses = [...cached.ipService.addresses].map(a => ({ ...a, type: "udp" }) as ServerAddressUdp); cached.device.hostname = hostnameOf(cached.name); return cached.device; } function matchesIdentifier(device: CommissionableDevice, identifier: CommissionableDeviceIdentifiers): boolean { if ("instanceId" in identifier) { return device.deviceIdentifier === identifier.instanceId; } if ("longDiscriminator" in identifier) { return device.D === identifier.longDiscriminator; } if ("shortDiscriminator" in identifier) { return ((device.D >> 8) & 0x0f) === identifier.shortDiscriminator; } if ("vendorId" in identifier) { const vp = device.VP?.split("+"); if (!vp) return false; const vendorMatch = VendorId(Number(vp[0])) === identifier.vendorId; if ("productId" in identifier && identifier.productId !== undefined) { return vendorMatch && Number(vp[1]) === identifier.productId; } return vendorMatch; } if ("deviceType" in identifier) { return device.DT === identifier.deviceType; } if ("productId" in identifier) { const vp = device.VP?.split("+"); return vp ? Number(vp[1]) === (identifier as { productId: number }).productId : false; } // Empty identifier — match any commissioning mode return device.CM === 1 || device.CM === 2; } function matchesWaiterIdentifier(a: CommissionableDeviceIdentifiers, b: CommissionableDeviceIdentifiers): boolean { // Both are small flat objects — structural equality suffices const aKeys = Object.keys(a); const bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) return false; for (const key of aKeys) { if ((a as Record)[key] !== (b as Record)[key]) return false; } return true; } function getQueryQnames(identifier: CommissionableDeviceIdentifiers): string[] { const base = [MATTER_COMMISSION_SERVICE_QNAME]; if ("instanceId" in identifier) { return [...base, getCommissionableDeviceQname(identifier.instanceId)]; } if ("longDiscriminator" in identifier) { return [...base, getLongDiscriminatorQname(identifier.longDiscriminator)]; } if ("shortDiscriminator" in identifier) { return [...base, getShortDiscriminatorQname(identifier.shortDiscriminator)]; } if ("vendorId" in identifier) { return [...base, getVendorQname(identifier.vendorId)]; } if ("deviceType" in identifier) { return [...base, getDeviceTypeQname(identifier.deviceType)]; } return [...base, getCommissioningModeQname()]; }