Skip to main content

matter_kit/clusters/
general_commissioning.rs

1//! General Commissioning cluster `0x0030` (Core §11.10) — the commissioning lifecycle.
2//!
3//! > This cluster is used to manage basic commissioning lifecycle.
4//!
5//! Three commands carry the whole of it: `ArmFailSafe` opens a transaction, everything else
6//! a commissioner does happens inside it, and `CommissioningComplete` closes it. If the
7//! commissioner never gets that far, the fail-safe expires and the device goes back to what
8//! it was — [`failsafe`](crate::commissioning::failsafe) is that state machine, and this
9//! cluster is its wire surface.
10//!
11//! # What this cluster does not own
12//!
13//! `ArmFailSafe`'s expiry has eleven cleanup steps, and they touch the fabric table, the
14//! session table, the key store and the network configuration. None of those belong to a
15//! cluster, so expiry hands back a [`Cleanup`] and the device applies it. Two commands
16//! therefore return work to be done rather than doing it:
17//! [`ArmFailSafeOutcome::cleanup`] and [`Completion::cleanup`].
18//!
19//! That is not a limitation of the design — it is what keeps §11.10.7.2.2's eleven steps
20//! auditable against the specification instead of buried across four modules.
21//!
22//! # `SetRegulatoryConfig` writes another cluster's attribute
23//!
24//! §11.10.7.4: the `CountryCode` field "SHALL be used to set the Location attribute reflected
25//! by the Basic Information Cluster". So this cluster holds a reference to the same
26//! [`Location`] cell Basic Information reads, and the two cannot disagree.
27//!
28//! Note the ordering §11.10.7.4 imposes, which reads like a mistake and is not: a country
29//! code the device has no regulatory data for "SHALL still set the Location attribute … but
30//! the SetRegulatoryConfigResponse replied SHALL have the ErrorCode field set to
31//! ValueOutsideRange". The location lands, the error is reported anyway. A mismatched
32//! `NewRegulatoryConfig`, by contrast, leaves `RegulatoryConfig` "unchanged".
33//!
34//! # Revision 2
35//!
36//! | Revision | Change |
37//! |---|---|
38//! | 1 | Initial revision |
39//! | 2 | Add Enhanced Setup Flow |
40
41use core::cell::{Cell, RefCell};
42
43use crate::clusters::basic_information::Location;
44use crate::commissioning::failsafe::{Cleanup, CommissioningError, FailSafe};
45use crate::dm::Resolved;
46use crate::dm::ResolvedCommand;
47use crate::dm::access::{Access, AccessQualities, Privilege};
48use crate::dm::meta::{
49    AttributeDescriptor, AttributeQualities, ClusterDescriptor, CommandDescriptor,
50};
51use crate::im::{
52    AttributeId, ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb,
53    WriteOp,
54};
55use crate::msg::FabricIndex;
56use crate::platform::{Duration, Instant};
57use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, set_once};
58
59use super::Cluster;
60
61/// `0x0030` (§11.10.3).
62pub const ID: ClusterId = 0x0030;
63
64/// The highest revision in §11.10.1's table.
65pub const REVISION: u16 = 2;
66
67/// `TC` (§11.10.4, bit 0) — Enhanced Setup Flow Terms & Conditions.
68pub const FEATURE_TERMS_AND_CONDITIONS: u32 = 1 << 0;
69/// `NR` (§11.10.4, bit 1) — Network Recovery. Provisional.
70pub const FEATURE_NETWORK_RECOVERY: u32 = 1 << 1;
71
72/// `Breadcrumb` (§11.10.6.1) — `uint64`, fallback 0, `RW VA`, mandatory.
73pub const BREADCRUMB: AttributeId = 0x0000;
74/// `BasicCommissioningInfo` (§11.10.6.2) — `F`, `RV`, mandatory.
75pub const BASIC_COMMISSIONING_INFO: AttributeId = 0x0001;
76/// `RegulatoryConfig` (§11.10.6.3) — `RV`, mandatory. Read-only on the wire: only
77/// `SetRegulatoryConfig` changes it.
78pub const REGULATORY_CONFIG: AttributeId = 0x0002;
79/// `LocationCapability` (§11.10.6.4) — `F`, `RV`, mandatory.
80pub const LOCATION_CAPABILITY: AttributeId = 0x0003;
81/// `SupportsConcurrentConnection` (§11.10.6.5) — `F`, `RV`, mandatory.
82pub const SUPPORTS_CONCURRENT_CONNECTION: AttributeId = 0x0004;
83
84/// `RecoveryIdentifier` (§11.10.6.11) — `NR`, and provisional.
85pub const RECOVERY_IDENTIFIER: AttributeId = 0x000A;
86
87/// `NetworkRecoveryReason` (§11.10.6.12) — `NR`, nullable, and provisional.
88pub const NETWORK_RECOVERY_REASON: AttributeId = 0x000B;
89
90/// `ArmFailSafe` (§11.10.7.2) — access `A`.
91pub const ARM_FAIL_SAFE: CommandId = 0x00;
92/// `ArmFailSafeResponse` (§11.10.7.3).
93pub const ARM_FAIL_SAFE_RESPONSE: CommandId = 0x01;
94/// `SetRegulatoryConfig` (§11.10.7.4) — access `A`.
95pub const SET_REGULATORY_CONFIG: CommandId = 0x02;
96/// `SetRegulatoryConfigResponse` (§11.10.7.5).
97pub const SET_REGULATORY_CONFIG_RESPONSE: CommandId = 0x03;
98/// `CommissioningComplete` (§11.10.7.6) — access `AF`: fabric-scoped, and CASE only.
99pub const COMMISSIONING_COMPLETE: CommandId = 0x04;
100/// `CommissioningCompleteResponse` (§11.10.7.7).
101pub const COMMISSIONING_COMPLETE_RESPONSE: CommandId = 0x05;
102
103/// `RegulatoryLocationTypeEnum` (§11.10.5.2) — "possible radio usage".
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105#[repr(u8)]
106pub enum RegulatoryLocation {
107    /// `0` — indoor only.
108    Indoor = 0,
109    /// `1` — outdoor only.
110    Outdoor = 1,
111    /// `2` — indoor/outdoor. "For Nodes without radio network interfaces (e.g. Ethernet-only
112    /// devices), the value IndoorOutdoor SHALL always be used."
113    IndoorOutdoor = 2,
114}
115
116impl RegulatoryLocation {
117    /// The value the enum encodes as.
118    #[must_use]
119    pub const fn value(self) -> u8 {
120        self as u8
121    }
122
123    /// Decodes a wire value, refusing anything §11.10.5.2 does not define.
124    #[must_use]
125    pub const fn from_value(value: u8) -> Option<Self> {
126        match value {
127            0 => Some(Self::Indoor),
128            1 => Some(Self::Outdoor),
129            2 => Some(Self::IndoorOutdoor),
130            _ => None,
131        }
132    }
133}
134
135/// §5.9's Network Recovery state: how a node that has lost its network asks for a new one.
136///
137/// A node whose Wi-Fi password changed underneath it is not broken and not commissionable — it
138/// still holds its fabric, its NOC and its ACL. §5.9 is the way back: advertise over BLE or
139/// Wi-Fi PAF, let an administrator open a *CASE* session over that channel, and take new network
140/// credentials through it.
141///
142/// Three rules carry the flow, and all three are here rather than in the application because
143/// all three are about *timing* and are the ones a device gets wrong by being helpful:
144///
145/// * §5.9.3 step 3: a node "SHALL continue to attempt to connect to the operational network for
146///   a duration of at least 120 seconds using its existing credentials" before it may advertise.
147///   "Given that temporary network outages occur with some frequency, waiting before entering
148///   Network Recovery mode and commencing announcement limits wireless spectrum
149///   pollution/interference and helps to limit attack opportunities."
150/// * §5.9.3 step 10: on the CASE session the node "SHALL autonomously arm the fail-safe timer
151///   for a timeout of 60 seconds", against an administrator that connects and then wanders off.
152/// * §5.9.3 step 16: "The Recovery Node SHALL reject the CommissioningComplete that is not
153///   received over the operational network." Completing over the recovery channel would declare
154///   success at the exact moment nothing had been proved to work.
155#[derive(Debug)]
156pub struct Recovery {
157    /// §11.10.6.11's `RecoveryIdentifier`: "a random 64-bit value, that value SHALL be reset on
158    /// factory reset and SHALL remain unchanged until a next factory reset".
159    ///
160    /// It is what an administrator matches an advertisement against, and §11.10.6.11 says why
161    /// it is not the Node ID: the identifier lets an administrator "establish a Node's identity
162    /// without revealing its Node ID" to everyone in radio range.
163    identifier: u64,
164    /// When connectivity was first lost, or `None` while the network is fine.
165    lost_at: Cell<Option<Instant>>,
166    /// Why, once the node has entered recovery. Null at every other time (§11.10.6.12).
167    reason: Cell<Option<NetworkRecoveryReason>>,
168    /// Whether the node is advertising for recovery.
169    announcing: Cell<bool>,
170}
171
172/// §11.10.6.12's `NetworkRecoveryReasonEnum`: "the primary reason that triggered the Network
173/// Recovery flow".
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175#[repr(u8)]
176pub enum NetworkRecoveryReason {
177    /// "Unspecified / unknown reason of network failure".
178    Unspecified = 0,
179    /// "Credentials for the configured operational network are not valid."
180    Auth = 1,
181    /// "Configured network cannot be found."
182    Visibility = 2,
183}
184
185impl NetworkRecoveryReason {
186    /// The wire value.
187    #[must_use]
188    pub const fn value(self) -> u8 {
189        self as u8
190    }
191}
192
193/// §5.9.3 step 3's floor: "at least 120 seconds using its existing credentials".
194pub const RECOVERY_HOLD_OFF: Duration = Duration::from_secs(120);
195
196/// §5.9.3 step 10's autonomous fail-safe: 60 seconds from the CASE session being established.
197pub const RECOVERY_FAIL_SAFE_SECONDS: u16 = 60;
198
199impl Recovery {
200    /// A node whose network is working, with the identifier it was given at factory reset.
201    #[must_use]
202    pub const fn new(identifier: u64) -> Self {
203        Self {
204            identifier,
205            lost_at: Cell::new(None),
206            reason: Cell::new(None),
207            announcing: Cell::new(false),
208        }
209    }
210
211    /// `RecoveryIdentifier` (§11.10.6.11).
212    #[must_use]
213    pub const fn identifier(&self) -> u64 {
214        self.identifier
215    }
216
217    /// `NetworkRecoveryReason` (§11.10.6.12), null unless the node is in recovery.
218    #[must_use]
219    pub fn reason(&self) -> Option<NetworkRecoveryReason> {
220        self.reason.get()
221    }
222
223    /// Whether the node is advertising for recovery.
224    #[must_use]
225    pub fn is_announcing(&self) -> bool {
226        self.announcing.get()
227    }
228
229    /// The node cannot reach its operational network.
230    ///
231    /// Idempotent: the clock starts at the *first* failure, so a device that calls this on every
232    /// retry does not keep pushing its own hold-off out.
233    pub fn network_lost(&self, now: Instant, reason: NetworkRecoveryReason) {
234        if self.lost_at.get().is_none() {
235            self.lost_at.set(Some(now));
236            self.reason.set(Some(reason));
237        }
238    }
239
240    /// The network came back, or recovery finished.
241    ///
242    /// §11.10.6.12: the reason "SHALL be null when the Node is not undergoing a Network Recovery
243    /// flow", so it goes with the state rather than lingering as a diagnostic.
244    pub fn network_restored(&self) {
245        self.lost_at.set(None);
246        self.reason.set(None);
247        self.announcing.set(false);
248    }
249
250    /// Whether §5.9.3 step 3's hold-off has elapsed, so announcement may begin.
251    #[must_use]
252    pub fn may_announce(&self, now: Instant) -> bool {
253        self.lost_at
254            .get()
255            .is_some_and(|lost| now.saturating_duration_since(lost) >= RECOVERY_HOLD_OFF)
256    }
257
258    /// Begins announcing, if §5.9.3 step 3 allows it yet.
259    ///
260    /// Returns whether it did. A device that announced early would be advertising through every
261    /// brief outage its access point has.
262    pub fn begin_announcing(&self, now: Instant) -> bool {
263        let allowed = self.may_announce(now);
264        if allowed {
265            self.announcing.set(true);
266        }
267        allowed
268    }
269
270    /// Whether a `CommissioningComplete` arriving over `operational_network` may be accepted
271    /// (§5.9.3 step 16).
272    ///
273    /// Outside a recovery flow this is always true — an ordinary commissioning completes over
274    /// whatever channel it ran on.
275    #[must_use]
276    pub fn may_complete(&self, over_operational_network: bool) -> bool {
277        !self.announcing.get() || over_operational_network
278    }
279}
280
281/// The attributes of §11.10.6 that are not gated on a feature.
282///
283/// `Breadcrumb` is the only writable one, at `RW VA`; `RegulatoryConfig` is `RV` even though
284/// a command changes it, which is the specification's way of saying that the change must go
285/// through `SetRegulatoryConfig` and pick up its regulatory checks.
286const ATTRIBUTES: &[AttributeDescriptor] = &[
287    AttributeDescriptor::read_write(BREADCRUMB).with_access(Access::read_write_with(
288        Privilege::View,
289        Privilege::Administer,
290    )),
291    AttributeDescriptor::read_only(BASIC_COMMISSIONING_INFO)
292        .with_qualities(AttributeQualities::FIXED),
293    AttributeDescriptor::read_only(REGULATORY_CONFIG),
294    AttributeDescriptor::read_only(LOCATION_CAPABILITY).with_qualities(AttributeQualities::FIXED),
295    AttributeDescriptor::read_only(SUPPORTS_CONCURRENT_CONNECTION)
296        .with_qualities(AttributeQualities::FIXED),
297];
298
299/// The same list with the two attributes §11.10.6 gates on the `NR` feature.
300///
301/// Everything unconditional is repeated rather than concatenated: a cluster descriptor is a
302/// `const` slice in flash, and §7.3's conformance makes the *whole* list a function of the
303/// feature map — so the two variants are two lists, checked against the specification's own
304/// tables by [`tests/conformance.rs`].
305///
306/// `RecoveryIdentifier` is `F` — "SHALL remain unchanged until a next factory reset" — and both
307/// are `RA`: only an administrator may read them, because together they say "this node has lost
308/// its network, and here is the identifier it is advertising", which is not for everyone with a
309/// session.
310const RECOVERY_ATTRIBUTES: &[AttributeDescriptor] = &[
311    AttributeDescriptor::read_write(BREADCRUMB).with_access(Access::read_write_with(
312        Privilege::View,
313        Privilege::Administer,
314    )),
315    AttributeDescriptor::read_only(BASIC_COMMISSIONING_INFO)
316        .with_qualities(AttributeQualities::FIXED),
317    AttributeDescriptor::read_only(REGULATORY_CONFIG),
318    AttributeDescriptor::read_only(LOCATION_CAPABILITY).with_qualities(AttributeQualities::FIXED),
319    AttributeDescriptor::read_only(SUPPORTS_CONCURRENT_CONNECTION)
320        .with_qualities(AttributeQualities::FIXED),
321    AttributeDescriptor::read_only(RECOVERY_IDENTIFIER)
322        .with_access(Access::read_only(Privilege::Administer))
323        .with_qualities(AttributeQualities::FIXED),
324    AttributeDescriptor::read_only(NETWORK_RECOVERY_REASON)
325        .with_access(Access::read_only(Privilege::Administer))
326        .with_qualities(AttributeQualities::NULLABLE),
327];
328
329/// §11.10.7's command table.
330///
331/// All three are `A` — Administer — because each of them can leave the device in a state it
332/// cannot get out of. `CommissioningComplete` is additionally `F`: it is fabric-scoped, so
333/// §8.8.2.3 step b.v refuses it over a session with no accessing fabric before it reaches
334/// the handler at all.
335const COMMANDS: &[CommandDescriptor] = &[
336    CommandDescriptor::new(ARM_FAIL_SAFE)
337        .with_access(Access::invoke(Privilege::Administer))
338        .with_response(ARM_FAIL_SAFE_RESPONSE),
339    CommandDescriptor::new(SET_REGULATORY_CONFIG)
340        .with_access(Access::invoke(Privilege::Administer))
341        .with_response(SET_REGULATORY_CONFIG_RESPONSE),
342    CommandDescriptor::new(COMMISSIONING_COMPLETE)
343        .with_access(
344            Access::invoke(Privilege::Administer).with_qualities(AccessQualities::FABRIC_SCOPED),
345        )
346        .with_response(COMMISSIONING_COMPLETE_RESPONSE),
347];
348
349/// The cluster descriptor.
350#[must_use]
351pub const fn cluster() -> ClusterDescriptor<'static> {
352    ClusterDescriptor {
353        id: ID,
354        revision: REVISION,
355        feature_map: 0,
356        attributes: ATTRIBUTES,
357        accepted_commands: COMMANDS,
358        generated_commands: &[],
359        events: &[],
360    }
361}
362
363/// The cluster descriptor for a node that implements §5.9's Network Recovery.
364///
365/// The feature bit and the two attributes move together: §7.3's conformance makes
366/// `RecoveryIdentifier` and `NetworkRecoveryReason` mandatory exactly when `NR` is set, so a
367/// descriptor that advertised one without the other would fail
368/// [`dm::spec`](crate::dm::spec)'s own validation.
369#[must_use]
370pub const fn cluster_with_recovery() -> ClusterDescriptor<'static> {
371    ClusterDescriptor {
372        id: ID,
373        revision: REVISION,
374        feature_map: FEATURE_NETWORK_RECOVERY,
375        attributes: RECOVERY_ATTRIBUTES,
376        accepted_commands: COMMANDS,
377        generated_commands: &[],
378        events: &[],
379    }
380}
381
382/// What `ArmFailSafe` produced, beyond its response.
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
384pub struct ArmFailSafeOutcome {
385    /// The `ErrorCode` that went into the `ArmFailSafeResponse`.
386    pub error: CommissioningError,
387    /// The cleanup steps of §11.10.7.2.2, when `ExpiryLengthSeconds` was zero and the
388    /// fail-safe was disarmed on the spot.
389    pub cleanup: Option<Cleanup>,
390}
391
392/// What `CommissioningComplete` produced.
393///
394/// §11.10.7.6's five actions on success: steps 1 and 5 (disarm, reset the breadcrumb) happen
395/// inside the cluster; steps 2, 3 and 4 — close the commissioning window, revoke PASE
396/// privileges, clear PASE sessions — are the device's, and [`Completion::cleanup`] says so.
397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub struct Completion {
399    /// The `ErrorCode` that went into the response.
400    pub error: CommissioningError,
401    /// Set on success: steps 3 and 4 — revoke the temporary administrative privileges granted
402    /// to any open PASE session, and clear its Secure Session Context.
403    pub close_pase_sessions: bool,
404    /// §11.10.7.2.2's cleanup steps, owed to a fail-safe context that had already lapsed when
405    /// the command arrived. A successful completion is not a rollback and produces none.
406    pub cleanup: Option<Cleanup>,
407}
408
409/// What a command left for the device to do, which a cluster cannot do itself.
410///
411/// Both variants touch the session table, the fabric table or the commissioning window — none
412/// of which belong to a cluster. Keeping them as *reported work* rather than hidden effects
413/// is what keeps §11.10.7.2.2's eleven steps auditable against the specification instead of
414/// scattered across four modules.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum Aftermath {
417    /// A fail-safe context ended without completing. Apply §11.10.7.2.2's steps.
418    Rollback(Cleanup),
419    /// `CommissioningComplete` succeeded. §11.10.7.6 steps 2 to 4: the commissioning window
420    /// is closed (this cluster has already recorded that), the temporary administrative
421    /// privileges granted to any open PASE session are revoked, and its Secure Session
422    /// Context is cleared.
423    Commissioned,
424}
425
426/// The General Commissioning cluster.
427///
428/// `location` is shared with [`BasicInformation`](super::BasicInformation) — see the module
429/// documentation.
430#[derive(Debug)]
431pub struct GeneralCommissioning<'a> {
432    /// The `Location` attribute of Basic Information, which `SetRegulatoryConfig` writes.
433    pub location: &'a Location,
434    /// `LocationCapability` (§11.10.6.4) — fixed by the manufacturer.
435    pub location_capability: RegulatoryLocation,
436    /// `SupportsConcurrentConnection` (§11.10.6.5).
437    pub supports_concurrent_connection: bool,
438    /// The node's fail-safe context.
439    ///
440    /// Borrowed, not owned: §11.18's `AddNOC`, `UpdateNOC`, `CSRRequest` and
441    /// `AddTrustedRootCertificate` all consult and record against the *same* context this
442    /// cluster arms, so it is node state that two clusters share — the same arrangement as
443    /// [`Location`], and for the same reason.
444    pub fail_safe: &'a RefCell<FailSafe>,
445    regulatory_config: Cell<RegulatoryLocation>,
446    /// The node's commissioning window, shared with Administrator Commissioning.
447    ///
448    /// §11.10.7.2 consults it to give a PASE commissioner priority over a CASE administrator,
449    /// and §11.10.7.6 step 2 closes it on `CommissioningComplete`. Both are about the *same*
450    /// window §11.19 opens, so it is node state rather than a flag each cluster keeps —
451    /// two copies would be two answers to "is a window open", and the priority rule is
452    /// precisely where they would disagree.
453    pub window: &'a RefCell<crate::commissioning::window::CommissioningWindow>,
454    /// §5.9's Network Recovery state, on a device that implements the `NR` feature.
455    ///
456    /// Optional because the feature is: a node without it has no `RecoveryIdentifier` to
457    /// advertise, and §11.10.6.11's attribute is conformant only when `NR` is set.
458    pub recovery: Option<&'a Recovery>,
459    /// What the last command invoked through the interaction model left for the device.
460    aftermath: Cell<Option<Aftermath>>,
461}
462
463impl<'a> GeneralCommissioning<'a> {
464    /// The cluster for a device.
465    ///
466    /// `location_capability` is also the initial `RegulatoryConfig`: §11.10.6.4 says "The
467    /// default value of the RegulatoryConfig attribute is the value of LocationCapability
468    /// attribute. This means devices always have a safe default value."
469    #[must_use]
470    pub fn new(
471        location: &'a Location,
472        location_capability: RegulatoryLocation,
473        fail_safe: &'a RefCell<FailSafe>,
474        window: &'a RefCell<crate::commissioning::window::CommissioningWindow>,
475    ) -> Self {
476        Self {
477            location,
478            location_capability,
479            supports_concurrent_connection: true,
480            fail_safe,
481            window,
482            regulatory_config: Cell::new(location_capability),
483            recovery: None,
484            aftermath: Cell::new(None),
485        }
486    }
487
488    /// The same cluster on a device that implements §5.9's Network Recovery.
489    #[must_use]
490    pub const fn with_recovery(mut self, recovery: &'a Recovery) -> Self {
491        self.recovery = Some(recovery);
492        self
493    }
494
495    /// The same cluster on a device that only supports the non-concurrent connection flow
496    /// (§5.5).
497    #[must_use]
498    pub fn without_concurrent_connection(mut self) -> Self {
499        self.supports_concurrent_connection = false;
500        self
501    }
502
503    /// The fail-safe state machine, for a device driving expiry from its own timer.
504    ///
505    /// [`FailSafe::next_deadline`] says when to call [`FailSafe::expire`]; the [`Cleanup`] it
506    /// returns is the device's to apply.
507    #[must_use]
508    pub fn fail_safe(&self) -> core::cell::Ref<'_, FailSafe> {
509        self.fail_safe.borrow()
510    }
511
512    /// Mutable access to the fail-safe, for recording `AddNOC`, `UpdateNOC` and the rest
513    /// ([`Progress`](crate::commissioning::failsafe::Progress)).
514    #[must_use]
515    pub fn fail_safe_mut(&self) -> core::cell::RefMut<'_, FailSafe> {
516        self.fail_safe.borrow_mut()
517    }
518
519    /// `RegulatoryConfig` (§11.10.6.3).
520    #[must_use]
521    pub fn regulatory_config(&self) -> RegulatoryLocation {
522        self.regulatory_config.get()
523    }
524
525    /// Whether a commissioning window is open as of `now` (§11.19.7.1).
526    #[must_use]
527    pub fn is_window_open(&self, now: crate::platform::Instant) -> bool {
528        self.window.borrow().open(now).is_some()
529    }
530
531    /// Takes the work the last command invoked through the interaction model left behind.
532    ///
533    /// A device calls this after every invoke against this cluster. Forgetting to means a
534    /// disarmed fail-safe leaves its fabric behind, or a completed commissioning leaves a
535    /// PASE session open with administrative privileges — which is the one that matters:
536    /// §11.10.7.6 steps 3 and 4 exist so that the passcode stops being a key to the device
537    /// the moment commissioning ends.
538    #[must_use]
539    pub fn take_aftermath(&self) -> Option<Aftermath> {
540        self.aftermath.take()
541    }
542
543    /// `ArmFailSafe` (§11.10.7.2).
544    pub fn arm_fail_safe(
545        &self,
546        expiry_length_seconds: u16,
547        breadcrumb: u64,
548        accessing_fabric: Option<FabricIndex>,
549        over_case: bool,
550        now: crate::platform::Instant,
551    ) -> ArmFailSafeOutcome {
552        let result = self.fail_safe.borrow_mut().arm(
553            expiry_length_seconds,
554            breadcrumb,
555            accessing_fabric,
556            now,
557            self.is_window_open(now) && over_case,
558        );
559        ArmFailSafeOutcome {
560            error: result.outcome.error_code(),
561            cleanup: result.cleanup,
562        }
563    }
564
565    /// `SetRegulatoryConfig` (§11.10.7.4).
566    ///
567    /// The two failures are asymmetric on purpose, and the specification is explicit about
568    /// both:
569    ///
570    /// * a `country_code` the device has no regulatory data for still sets `Location`, and
571    ///   the response reports `ValueOutsideRange`;
572    /// * a `new_config` that `LocationCapability` does not admit leaves `RegulatoryConfig`
573    ///   "unchanged".
574    ///
575    /// The `Breadcrumb` "SHALL be used to atomically set the Breadcrumb attribute on success
576    /// of this command … If the command fails, the Breadcrumb attribute SHALL be left
577    /// unchanged."
578    pub fn set_regulatory_config(
579        &self,
580        new_config: RegulatoryLocation,
581        country_code: &str,
582        breadcrumb: u64,
583    ) -> CommissioningError {
584        // "The CountryCode field SHALL … be used to set the Location attribute reflected by
585        // the Basic Information Cluster" — before the capability check, because a device
586        // that refuses the regulatory mode still learns where it is.
587        if self.location.set(country_code).is_err() {
588            return CommissioningError::ValueOutsideRange;
589        }
590
591        // "If the LocationCapability attribute is not Indoor/Outdoor and the
592        // NewRegulatoryConfig value received does not match either the Indoor or Outdoor
593        // fixed value in LocationCapability, then … ValueOutsideRange … and the
594        // RegulatoryConfig attribute … SHALL remain unchanged."
595        if self.location_capability != RegulatoryLocation::IndoorOutdoor
596            && new_config != self.location_capability
597        {
598            return CommissioningError::ValueOutsideRange;
599        }
600
601        self.regulatory_config.set(new_config);
602        self.fail_safe.borrow_mut().set_breadcrumb(breadcrumb);
603        CommissioningError::Ok
604    }
605
606    /// `CommissioningComplete` (§11.10.7.6).
607    pub fn commissioning_complete(
608        &self,
609        over_case: bool,
610        accessing_fabric: Option<FabricIndex>,
611        now: crate::platform::Instant,
612    ) -> Completion {
613        let result = self
614            .fail_safe
615            .borrow_mut()
616            .complete(over_case, accessing_fabric, now);
617        if result.error.is_ok() {
618            // Step 2: "The commissioning window at the Server SHALL be closed." Closing it
619            // here also destroys the ephemeral PAKE verifier §11.19.8.1 installed — "It SHALL
620            // be deleted by the Node at the end of commissioning".
621            self.window.borrow_mut().close();
622        }
623        Completion {
624            error: result.error,
625            close_pase_sessions: result.error.is_ok(),
626            cleanup: result.cleanup,
627        }
628    }
629}
630
631impl ClusterHandler for GeneralCommissioning<'_> {
632    fn read(
633        &self,
634        resolved: &Resolved<'_>,
635        _ctx: &InteractionContext<'_>,
636        w: &mut TlvWriter<'_>,
637        tag: Tag,
638    ) -> Result<(), Status> {
639        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
640        match resolved.attribute {
641            BREADCRUMB => full(w.unsigned(tag, self.fail_safe.borrow().breadcrumb())),
642            BASIC_COMMISSIONING_INFO => {
643                let info = self.fail_safe.borrow().info();
644                full(w.start_structure(tag))?;
645                full(w.unsigned(Tag::Context(0), u64::from(info.expiry_length_seconds)))?;
646                full(w.unsigned(Tag::Context(1), u64::from(info.max_cumulative_seconds)))?;
647                full(w.end_container())
648            }
649            REGULATORY_CONFIG => {
650                full(w.unsigned(tag, u64::from(self.regulatory_config.get().value())))
651            }
652            LOCATION_CAPABILITY => {
653                full(w.unsigned(tag, u64::from(self.location_capability.value())))
654            }
655            SUPPORTS_CONCURRENT_CONNECTION => {
656                full(w.bool(tag, self.supports_concurrent_connection))
657            }
658            RECOVERY_IDENTIFIER => {
659                let recovery = self.recovery.ok_or(Status::UnsupportedAttribute)?;
660                full(w.unsigned(tag, recovery.identifier()))
661            }
662            NETWORK_RECOVERY_REASON => {
663                let recovery = self.recovery.ok_or(Status::UnsupportedAttribute)?;
664                match recovery.reason() {
665                    Some(reason) => full(w.unsigned(tag, u64::from(reason.value()))),
666                    // §11.10.6.12: "This attribute SHALL be null when the Node is not
667                    // undergoing a Network Recovery flow."
668                    None => full(w.null(tag)),
669                }
670            }
671            _ => Err(Status::UnsupportedAttribute),
672        }
673    }
674
675    fn write(
676        &self,
677        resolved: &Resolved<'_>,
678        data: &[u8],
679        _op: WriteOp,
680        _ctx: &InteractionContext<'_>,
681    ) -> Result<(), Status> {
682        match resolved.attribute {
683            BREADCRUMB => {
684                // `Data` is the `AttributeDataIB`'s context-2 member, so it arrives tagged.
685                let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
686                let value = reader
687                    .next_element()
688                    .ok()
689                    .flatten()
690                    .and_then(|element| element.unsigned().ok())
691                    .ok_or(Status::InvalidDataType)?;
692                self.fail_safe.borrow_mut().set_breadcrumb(value);
693                Ok(())
694            }
695            _ => Err(Status::UnsupportedWrite),
696        }
697    }
698
699    fn invoke(
700        &self,
701        resolved: &ResolvedCommand<'_>,
702        fields: Option<&[u8]>,
703        ctx: &InteractionContext<'_>,
704        w: &mut TlvWriter<'_>,
705        tag: Tag,
706    ) -> Result<Option<CommandId>, StatusIb> {
707        match resolved.command.id {
708            ARM_FAIL_SAFE => {
709                let request = ArmFailSafeRequest::decode(fields)?;
710                let outcome = self.arm_fail_safe(
711                    request.expiry_length_seconds,
712                    request.breadcrumb,
713                    ctx.fabric_index,
714                    // §11.10.7.2's window rule turns on "the command was received over a CASE
715                    // session". An accessing fabric is exactly what a CASE session has and a
716                    // PASE session does not (§6.6.6.3).
717                    ctx.fabric_index.is_some(),
718                    ctx.now,
719                );
720                if let Some(cleanup) = outcome.cleanup {
721                    self.aftermath.set(Some(Aftermath::Rollback(cleanup)));
722                }
723                write_error_response(w, tag, outcome.error)?;
724                Ok(Some(ARM_FAIL_SAFE_RESPONSE))
725            }
726            SET_REGULATORY_CONFIG => {
727                let request = SetRegulatoryConfigRequest::decode(fields)?;
728                let error = self.set_regulatory_config(
729                    request.new_config,
730                    request.country_code,
731                    request.breadcrumb,
732                );
733                write_error_response(w, tag, error)?;
734                Ok(Some(SET_REGULATORY_CONFIG_RESPONSE))
735            }
736            COMMISSIONING_COMPLETE => {
737                let completion = self.commissioning_complete(
738                    // §8.8.2.3 step b.v has already refused this fabric-scoped command over a
739                    // session with no accessing fabric, so reaching here with one means CASE.
740                    ctx.fabric_index.is_some(),
741                    ctx.fabric_index,
742                    ctx.now,
743                );
744                match completion.cleanup {
745                    Some(cleanup) => self.aftermath.set(Some(Aftermath::Rollback(cleanup))),
746                    None if completion.close_pase_sessions => {
747                        self.aftermath.set(Some(Aftermath::Commissioned));
748                    }
749                    None => {}
750                }
751                write_error_response(w, tag, completion.error)?;
752                Ok(Some(COMMISSIONING_COMPLETE_RESPONSE))
753            }
754            _ => Err(Status::UnsupportedCommand.into()),
755        }
756    }
757}
758
759/// `ArmFailSafe`'s fields (§11.10.7.2).
760#[derive(Debug, Clone, Copy, PartialEq, Eq)]
761struct ArmFailSafeRequest {
762    expiry_length_seconds: u16,
763    breadcrumb: u64,
764}
765
766impl ArmFailSafeRequest {
767    fn decode(fields: Option<&[u8]>) -> Result<Self, Status> {
768        let fields = fields.ok_or(Status::InvalidCommand)?;
769        // `CommandFields` is §10.6.11's context-2 member of the `CommandDataIB`, so it
770        // arrives tagged — read it as the fragment it is, not as a whole TLV document.
771        let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
772        let element = reader
773            .next_element()
774            .map_err(|_| Status::InvalidCommand)?
775            .ok_or(Status::InvalidCommand)?;
776        if element.value.container() != Some(ContainerKind::Structure) {
777            return Err(Status::InvalidCommand);
778        }
779        // Both fields are mandatory, but `ExpiryLengthSeconds` has a fallback of 900 — a
780        // client that omits it is asking for the default, not making a malformed request.
781        let mut expiry: Option<u16> = None;
782        let mut breadcrumb: Option<u64> = None;
783        let start_depth = reader.depth();
784        loop {
785            // Two ways this loop must *not* end: a decode failure, and the buffer running
786            // out before the structure closes. Either treated as an end of input would
787            // accept a truncated ArmFailSafe and silently apply `ExpiryLengthSeconds`'
788            // fallback of 900 — arming the fail-safe for fifteen minutes on garbage.
789            let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
790                return Err(Status::InvalidCommand);
791            };
792            if reader.depth() < start_depth {
793                break;
794            }
795            match field.tag {
796                Tag::Context(0) => {
797                    let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
798                    set_once(
799                        &mut expiry,
800                        u16::try_from(value).map_err(|_| Status::ConstraintError)?,
801                    )
802                    .map_err(|_| Status::InvalidCommand)?;
803                }
804                Tag::Context(1) => {
805                    let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
806                    set_once(&mut breadcrumb, value).map_err(|_| Status::InvalidCommand)?;
807                }
808                _ => reader
809                    .skip_value(&field)
810                    .map_err(|_| Status::InvalidCommand)?,
811            }
812        }
813        Ok(Self {
814            expiry_length_seconds: expiry
815                .unwrap_or(crate::commissioning::failsafe::DEFAULT_EXPIRY_SECONDS),
816            breadcrumb: breadcrumb.ok_or(Status::InvalidCommand)?,
817        })
818    }
819}
820
821/// `SetRegulatoryConfig`'s fields (§11.10.7.4).
822#[derive(Debug, Clone, Copy, PartialEq, Eq)]
823struct SetRegulatoryConfigRequest<'a> {
824    new_config: RegulatoryLocation,
825    country_code: &'a str,
826    breadcrumb: u64,
827}
828
829impl<'a> SetRegulatoryConfigRequest<'a> {
830    fn decode(fields: Option<&'a [u8]>) -> Result<Self, Status> {
831        let fields = fields.ok_or(Status::InvalidCommand)?;
832        // `CommandFields` is §10.6.11's context-2 member of the `CommandDataIB`, so it
833        // arrives tagged — read it as the fragment it is, not as a whole TLV document.
834        let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
835        let element = reader
836            .next_element()
837            .map_err(|_| Status::InvalidCommand)?
838            .ok_or(Status::InvalidCommand)?;
839        if element.value.container() != Some(ContainerKind::Structure) {
840            return Err(Status::InvalidCommand);
841        }
842        let mut new_config: Option<RegulatoryLocation> = None;
843        let mut country_code: Option<&str> = None;
844        let mut breadcrumb: Option<u64> = None;
845        let start_depth = reader.depth();
846        loop {
847            // As above: a malformed or truncated remainder fails the command, and only the
848            // structure's own end-of-container ends the loop.
849            let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
850                return Err(Status::InvalidCommand);
851            };
852            if reader.depth() < start_depth {
853                break;
854            }
855            match field.tag {
856                Tag::Context(0) => {
857                    let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
858                    let value = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
859                    // §11.10.5.2 defines three values; anything else is a constraint error
860                    // rather than a silently-clamped mode.
861                    let location =
862                        RegulatoryLocation::from_value(value).ok_or(Status::ConstraintError)?;
863                    set_once(&mut new_config, location).map_err(|_| Status::InvalidCommand)?;
864                }
865                Tag::Context(1) => {
866                    let text = field.utf8().map_err(|_| Status::InvalidCommand)?;
867                    set_once(&mut country_code, text).map_err(|_| Status::InvalidCommand)?;
868                }
869                Tag::Context(2) => {
870                    let value = field.unsigned().map_err(|_| Status::InvalidCommand)?;
871                    set_once(&mut breadcrumb, value).map_err(|_| Status::InvalidCommand)?;
872                }
873                _ => reader
874                    .skip_value(&field)
875                    .map_err(|_| Status::InvalidCommand)?,
876            }
877        }
878        Ok(Self {
879            new_config: new_config.ok_or(Status::InvalidCommand)?,
880            country_code: country_code.ok_or(Status::InvalidCommand)?,
881            breadcrumb: breadcrumb.ok_or(Status::InvalidCommand)?,
882        })
883    }
884}
885
886/// The response shape all three commands share: `ErrorCode [0]`, `DebugText [1]`.
887///
888/// §11.10.7.1: `DebugText` "SHOULD NOT be presented directly in user interfaces. Its purpose
889/// is to help developers in troubleshooting errors." It is mandatory with a fallback of `""`,
890/// and a device that filled it would be leaking its internals to anyone who can invoke the
891/// command — so this always writes the empty string.
892fn write_error_response(
893    w: &mut TlvWriter<'_>,
894    tag: Tag,
895    error: CommissioningError,
896) -> Result<(), Status> {
897    let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
898    full(w.start_structure(tag))?;
899    full(w.unsigned(Tag::Context(0), u64::from(error.value())))?;
900    full(w.utf8(Tag::Context(1), ""))?;
901    full(w.end_container())
902}
903
904impl Cluster for GeneralCommissioning<'_> {
905    const ID: ClusterId = ID;
906}