Skip to main content

matter_kit/clusters/
icd_management.rs

1//! ICD Management, cluster `0x0046` (Core §9.16).
2//!
3//! A device on a coin cell is asleep for almost all of its life. A client that wants to hear
4//! from one registers here, and the device sends it a [Check-In
5//! message](crate::icd::checkin) when it wakes and finds nobody subscribed.
6//!
7//! > ICD Management Cluster enables configuration of the ICD's behavior and ensuring that
8//! > listed clients can be notified when an intermittently connected device, ICD, is available
9//! > for communication.
10//!
11//! # Two node ids, and they are not the same thing
12//!
13//! §9.16.5.3's registration has both a `CheckInNodeID` and a `MonitoredSubject`, and the
14//! difference is the point of the design. The **monitored subject** is what the device watches
15//! for: if any subscription on this fabric matches it, the client is present and no check-in is
16//! due. The **check-in node id** is where the message goes when it is. A phone app might be
17//! monitored as a CAT shared by every phone in the household while check-ins go to one hub.
18//!
19//! Matching the monitored subject is not an equality test — "Matching SHALL be determined using
20//! the subject_matches function defined in the Access Control Privilege Granting Algorithm", so
21//! a CAT subject matches a subscriber holding that tag at an equal or higher version, exactly as
22//! [`acl`](crate::acl) decides it. [`Registration::matches_subscriber`](crate::clusters::icd_management::Registration::matches_subscriber) is that function.
23//!
24//! # The verification key is what stops one manager evicting another's client
25//!
26//! `RegisterClient` and `UnregisterClient` both carry an optional `VerificationKey`, and
27//! §9.16.7.1 makes it conditional on privilege rather than optional in practice:
28//!
29//! > The verification key SHALL be provided for clients with manage permissions. The
30//! > verification key SHOULD NOT be provided by clients with administrator permissions for the
31//! > server cluster. The verification key SHALL be ignored by the server if it is provided by
32//! > a client with administrator permissions.
33//!
34//! So a manager may only touch a registration whose stored key it already knows — it must
35//! prove it is the client it claims to be replacing. Without that check, any node with Manage
36//! on this cluster could point another client's check-ins at itself, or simply delete them, and
37//! the client would go silently unnotified: the symptom is a battery device that appears to
38//! work and a client that never hears from it.
39//!
40//! # What this holds and what it does not
41//!
42//! The table, the timings, and the counter. **Not** the sleep schedule: when a device idles,
43//! when it wakes, and what it does with `StayActiveRequest` are the application's and the
44//! radio's, because nothing here can know a power budget.
45
46use core::cell::RefCell;
47use core::marker::PhantomData;
48
49use crate::config::Config;
50use crate::crypto::{SYMMETRIC_KEY_LENGTH_BYTES, SymmetricKey, ct_eq};
51use crate::dm::spec::{Conforming, Optional};
52use crate::dm::{Privilege, Resolved, ResolvedCommand};
53use crate::im::{
54    AttributeId, ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb,
55};
56use crate::msg::{FabricIndex, NodeId};
57use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
58
59use super::Cluster;
60
61/// `0x0046` (§9.16.3).
62pub const ID: ClusterId = 0x0046;
63
64/// The revision §9.16.1's table ends on.
65pub const REVISION: u16 = 3;
66
67/// `IdleModeDuration` (§9.16.6.1) — `uint32`, seconds, `RV F`, mandatory.
68pub const IDLE_MODE_DURATION: AttributeId = 0x0000;
69/// `ActiveModeDuration` (§9.16.6.2) — `uint32`, milliseconds, `RV F`, mandatory.
70pub const ACTIVE_MODE_DURATION: AttributeId = 0x0001;
71/// `ActiveModeThreshold` (§9.16.6.3) — `uint16`, milliseconds, `RV F`, mandatory.
72pub const ACTIVE_MODE_THRESHOLD: AttributeId = 0x0002;
73/// `RegisteredClients` (§9.16.6.4) — `list[MonitoringRegistrationStruct]`, `RAF N`.
74pub const REGISTERED_CLIENTS: AttributeId = 0x0003;
75/// `ICDCounter` (§9.16.6.5) — `uint32`, `RA CN`.
76pub const ICD_COUNTER: AttributeId = 0x0004;
77/// `ClientsSupportedPerFabric` (§9.16.6.6) — `uint16`, `RV F`, min 1.
78pub const CLIENTS_SUPPORTED_PER_FABRIC: AttributeId = 0x0005;
79/// `UserActiveModeTriggerHint` (§9.16.6.7) — `UserActiveModeTriggerBitmap`, `RV F`.
80pub const USER_ACTIVE_MODE_TRIGGER_HINT: AttributeId = 0x0006;
81/// `UserActiveModeTriggerInstruction` (§9.16.6) — `string`, max 128, `RV F`.
82pub const USER_ACTIVE_MODE_TRIGGER_INSTRUCTION: AttributeId = 0x0007;
83/// `OperatingMode` (§9.16.6) — `OperatingModeEnum`, `RV`.
84pub const OPERATING_MODE: AttributeId = 0x0008;
85/// `MaximumCheckInBackoff` (§9.16.6) — `uint32`, seconds, `RV F`.
86pub const MAXIMUM_CHECK_IN_BACKOFF: AttributeId = 0x0009;
87
88/// `RegisterClient` (§9.16.7.1) — `MF`.
89pub const REGISTER_CLIENT: CommandId = 0x00;
90/// `RegisterClientResponse` (§9.16.7.2).
91pub const REGISTER_CLIENT_RESPONSE: CommandId = 0x01;
92/// `UnregisterClient` (§9.16.7.3) — `MF`.
93pub const UNREGISTER_CLIENT: CommandId = 0x02;
94/// `StayActiveRequest` (§9.16.7.4).
95pub const STAY_ACTIVE_REQUEST: CommandId = 0x03;
96/// `StayActiveResponse` (§9.16.7.5).
97pub const STAY_ACTIVE_RESPONSE: CommandId = 0x04;
98
99/// The global `FabricIndex` field of a fabric-scoped struct (§7.19.1.9).
100pub const FABRIC_INDEX_FIELD: u8 = 254;
101
102/// `IdleModeDuration`'s upper bound, 64800 seconds — eighteen hours (§9.16.6).
103pub const IDLE_MODE_DURATION_MAX: u32 = 64_800;
104
105bitflags::bitflags! {
106    /// §9.16.5.1's `UserActiveModeTriggerBitmap`: how a person wakes the device.
107    ///
108    /// A client shows this to a user who is waiting for a sleepy device to answer, so the
109    /// value is a *user interface* rather than a capability — which is why several bits carry
110    /// a dependency on `UserActiveModeTriggerInstruction`: "Press the reset button for N
111    /// seconds" is useless without N.
112    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
113    pub struct UserActiveModeTrigger: u32 {
114        /// Power-cycling the device wakes it.
115        const POWER_CYCLE = 1 << 0;
116        /// The device's own settings menu explains how.
117        const SETTINGS_MENU = 1 << 1;
118        /// `UserActiveModeTriggerInstruction` describes a custom way. Requires it.
119        const CUSTOM_INSTRUCTION = 1 << 2;
120        /// The device manual explains how.
121        const DEVICE_MANUAL = 1 << 3;
122        /// Actuating the sensor wakes it — opening the door, for a door sensor.
123        const ACTUATE_SENSOR = 1 << 4;
124        /// Actuating the sensor for N seconds. Requires the instruction.
125        const ACTUATE_SENSOR_SECONDS = 1 << 5;
126        /// Actuating the sensor N times. Requires the instruction.
127        const ACTUATE_SENSOR_TIMES = 1 << 6;
128        /// Actuating the sensor until a light blinks.
129        const ACTUATE_SENSOR_LIGHTS_BLINK = 1 << 7;
130        /// Pressing the reset button.
131        const RESET_BUTTON = 1 << 8;
132        /// Pressing the reset button until a light blinks.
133        const RESET_BUTTON_LIGHTS_BLINK = 1 << 9;
134        /// Pressing the reset button for N seconds. Requires the instruction.
135        const RESET_BUTTON_SECONDS = 1 << 10;
136        /// Pressing the reset button N times. Requires the instruction.
137        const RESET_BUTTON_TIMES = 1 << 11;
138        /// Pressing the setup button.
139        const SETUP_BUTTON = 1 << 12;
140        /// Pressing the setup button for N seconds. Requires the instruction.
141        const SETUP_BUTTON_SECONDS = 1 << 13;
142        /// Pressing the setup button until a light blinks.
143        const SETUP_BUTTON_LIGHTS_BLINK = 1 << 14;
144        /// Pressing the setup button N times. Requires the instruction.
145        const SETUP_BUTTON_TIMES = 1 << 15;
146        /// Pressing an application-defined button. Requires the instruction.
147        const APP_DEFINED_BUTTON = 1 << 16;
148    }
149}
150
151impl UserActiveModeTrigger {
152    /// The bits §9.16.6.7 says require `UserActiveModeTriggerInstruction` to be present.
153    ///
154    /// Three bits that *depend* on the instruction do not *require* it —
155    /// "ActuateSensorLightsBlink, ResetButtonLightsBlink and SetupButtonLightsBlink (i.e. bits
156    /// 7, 9 and 14) have a dependency on the UserActiveModeTriggerInstruction attribute but do
157    /// not require the attribute to be present" — because the instruction only adds the colour
158    /// of the light. They are excluded here.
159    pub const REQUIRE_INSTRUCTION: Self = Self::from_bits_truncate(
160        Self::CUSTOM_INSTRUCTION.bits()
161            | Self::ACTUATE_SENSOR_SECONDS.bits()
162            | Self::ACTUATE_SENSOR_TIMES.bits()
163            | Self::RESET_BUTTON_SECONDS.bits()
164            | Self::RESET_BUTTON_TIMES.bits()
165            | Self::SETUP_BUTTON_SECONDS.bits()
166            | Self::SETUP_BUTTON_TIMES.bits()
167            | Self::APP_DEFINED_BUTTON.bits(),
168    );
169
170    /// Whether this hint obliges the device to publish an instruction string.
171    #[must_use]
172    pub const fn needs_instruction(self) -> bool {
173        self.intersects(Self::REQUIRE_INSTRUCTION)
174    }
175}
176
177bitflags::bitflags! {
178    /// §9.16.4's features.
179    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
180    pub struct Feature: u32 {
181        /// `CIP` — the Check-In Protocol's attributes and commands.
182        const CHECK_IN_PROTOCOL_SUPPORT = 1 << 0;
183        /// `UAT` — "supported if and only if the device has a user active mode trigger".
184        const USER_ACTIVE_MODE_TRIGGER = 1 << 1;
185        /// `LITS` — the device can operate as a Long Idle Time ICD.
186        const LONG_IDLE_TIME_SUPPORT = 1 << 2;
187        /// `DSLS` — it can switch between SIT and LIT while a client is registered.
188        const DYNAMIC_SIT_LIT_SUPPORT = 1 << 3;
189    }
190}
191
192/// §9.16.5's `ClientTypeEnum` — how available the registered client is.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
194#[repr(u8)]
195pub enum ClientType {
196    /// "typically resident, always-on, fixed infrastructure in the home" — a hub.
197    #[default]
198    Permanent = 0,
199    /// "mobile or non-resident or not always-on" — a phone that leaves the house.
200    Ephemeral = 1,
201}
202
203impl ClientType {
204    /// Reads a wire value; anything else is `CONSTRAINT_ERROR`.
205    pub const fn from_value(value: u64) -> Result<Self, Status> {
206        match value {
207            0 => Ok(Self::Permanent),
208            1 => Ok(Self::Ephemeral),
209            _ => Err(Status::ConstraintError),
210        }
211    }
212}
213
214/// §9.16.5.2's `OperatingModeEnum`.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
216#[repr(u8)]
217pub enum OperatingMode {
218    /// Short Idle Time: the device is reachable often enough for ordinary interaction.
219    #[default]
220    Sit = 0,
221    /// Long Idle Time: it is not, and a client must expect to wait for a check-in.
222    Lit = 1,
223}
224
225/// One registered client (§9.16.5.3's `MonitoringRegistrationStruct`), fabric-scoped.
226///
227/// The `Key` field of that struct is deprecated and never leaves the device — §9.16.5.3 marks
228/// it `D`, and it is the shared secret [`checkin`](crate::icd::checkin) encrypts with. Reading
229/// the list gives back everything *except* it, which is what makes the verification-key rule
230/// mean anything: a client that could read the key would not have to prove it knew it.
231#[derive(Debug, Clone)]
232pub struct Registration {
233    /// Where a Check-In message goes.
234    pub check_in_node_id: NodeId,
235    /// The subject whose subscription counts as "this client is present" (§6.6.6.2's
236    /// `subject_matches`), so a Node ID or a CAT.
237    pub monitored_subject: u64,
238    /// How available the client says it is.
239    pub client_type: ClientType,
240    /// Which fabric registered it.
241    pub fabric_index: FabricIndex,
242    /// The ICDToken — "a 128-bit symmetric key shared by the ICD and the ICD Client, used to
243    /// encrypt Check-In messages from this ICD to the MonitoredSubject".
244    key: SymmetricKey,
245}
246
247/// A CAT subject: the operational node id range §6.6.2.1.2 reserves for them.
248const CAT_PREFIX: u64 = 0xFFFF_FFFD_0000_0000;
249const CAT_MASK: u64 = 0xFFFF_FFFF_0000_0000;
250
251impl Registration {
252    /// Records a client.
253    #[must_use]
254    pub const fn new(
255        check_in_node_id: NodeId,
256        monitored_subject: u64,
257        client_type: ClientType,
258        fabric_index: FabricIndex,
259        key: SymmetricKey,
260    ) -> Self {
261        Self {
262            check_in_node_id,
263            monitored_subject,
264            client_type,
265            fabric_index,
266            key,
267        }
268    }
269
270    /// The key Check-In messages to this client are encrypted with.
271    #[must_use]
272    pub const fn key(&self) -> &SymmetricKey {
273        &self.key
274    }
275
276    /// Whether a subscriber on this fabric satisfies the monitored subject.
277    ///
278    /// §9.16.5.3 defers to §6.6.6.2's `subject_matches`, and the CAT half is the part a
279    /// direct comparison gets wrong:
280    ///
281    /// > if the MonitoredSubject has the value 0xFFFF_FFFD_AA12_0002, and one of the
282    /// > subscribers … bears the CASE Authenticated TAG value 0xAA12 and the version 0x0002
283    /// > **or higher** within its NOC, then the entry matches.
284    ///
285    /// Comparing CATs for equality instead makes every client appear absent the moment its
286    /// tag version is bumped — and the device starts sending check-ins to a client that is
287    /// sitting there subscribed.
288    #[must_use]
289    pub fn matches_subscriber(&self, node: NodeId, cats: &[u32]) -> bool {
290        if self.monitored_subject & CAT_MASK != CAT_PREFIX {
291            return self.monitored_subject == node.0;
292        }
293        let wanted = self.monitored_subject as u32;
294        let (wanted_tag, wanted_version) = (wanted >> 16, wanted & 0xFFFF);
295        cats.iter().any(|&cat| {
296            let (tag, version) = (cat >> 16, cat & 0xFFFF);
297            tag == wanted_tag && version >= wanted_version
298        })
299    }
300
301    /// Writes the struct as §9.16.5.3 defines it, without the deprecated `Key`.
302    fn encode(&self, w: &mut TlvWriter<'_>) -> crate::error::Result<()> {
303        w.start_structure(Tag::Anonymous)?;
304        w.unsigned(Tag::Context(1), self.check_in_node_id.0)?;
305        w.unsigned(Tag::Context(2), self.monitored_subject)?;
306        w.unsigned(Tag::Context(4), self.client_type as u64)?;
307        w.unsigned(
308            Tag::Context(FABRIC_INDEX_FIELD),
309            u64::from(self.fabric_index.0),
310        )?;
311        w.end_container()
312    }
313}
314
315/// The fields of `RegisterClient` (§9.16.7.1).
316#[derive(Debug, Clone)]
317struct RegisterFields {
318    check_in_node_id: NodeId,
319    monitored_subject: u64,
320    key: SymmetricKey,
321    verification_key: Option<SymmetricKey>,
322    client_type: ClientType,
323}
324
325/// Reads a 16-octet key field, refusing any other length.
326///
327/// §9.16.7.1 constrains both `Key` and `VerificationKey` to exactly 16. A shorter one padded
328/// to length would be a weaker key that still worked.
329fn key_field(bytes: &[u8]) -> Result<SymmetricKey, Status> {
330    if bytes.len() != SYMMETRIC_KEY_LENGTH_BYTES {
331        return Err(Status::ConstraintError);
332    }
333    SymmetricKey::from_slice(bytes).map_err(|_| Status::ConstraintError)
334}
335
336fn decode_register(fields: &[u8]) -> Result<RegisterFields, Status> {
337    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
338    let element = reader
339        .next_element()
340        .map_err(|_| Status::InvalidAction)?
341        .ok_or(Status::InvalidAction)?;
342    if element.value.container() != Some(ContainerKind::Structure) {
343        return Err(Status::InvalidAction);
344    }
345
346    let mut check_in_node_id = None;
347    let mut monitored_subject = None;
348    let mut key = None;
349    let mut verification_key = None;
350    let mut client_type = None;
351    loop {
352        let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
353            return Err(Status::InvalidAction);
354        };
355        if field.value == Value::EndOfContainer {
356            break;
357        }
358        match field.tag.context() {
359            Some(0) => {
360                check_in_node_id = Some(NodeId(
361                    field.unsigned().map_err(|_| Status::ConstraintError)?,
362                ));
363            }
364            Some(1) => {
365                monitored_subject = Some(field.unsigned().map_err(|_| Status::ConstraintError)?);
366            }
367            Some(2) => {
368                key = Some(key_field(
369                    field.octets().map_err(|_| Status::ConstraintError)?,
370                )?);
371            }
372            Some(3) => {
373                verification_key = Some(key_field(
374                    field.octets().map_err(|_| Status::ConstraintError)?,
375                )?);
376            }
377            Some(4) => {
378                client_type = Some(ClientType::from_value(
379                    field.unsigned().map_err(|_| Status::ConstraintError)?,
380                )?);
381            }
382            _ => {
383                reader
384                    .skip_value(&field)
385                    .map_err(|_| Status::InvalidAction)?;
386            }
387        }
388    }
389
390    let (Some(check_in_node_id), Some(monitored_subject), Some(key), Some(client_type)) =
391        (check_in_node_id, monitored_subject, key, client_type)
392    else {
393        // §8.8.2.3: a command missing a mandatory field is not a command.
394        return Err(Status::InvalidCommand);
395    };
396    Ok(RegisterFields {
397        check_in_node_id,
398        monitored_subject,
399        key,
400        verification_key,
401        client_type,
402    })
403}
404
405/// The fields of `UnregisterClient` (§9.16.7.3).
406fn decode_unregister(fields: &[u8]) -> Result<(NodeId, Option<SymmetricKey>), Status> {
407    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
408    let element = reader
409        .next_element()
410        .map_err(|_| Status::InvalidAction)?
411        .ok_or(Status::InvalidAction)?;
412    if element.value.container() != Some(ContainerKind::Structure) {
413        return Err(Status::InvalidAction);
414    }
415    let mut node = None;
416    let mut verification_key = None;
417    loop {
418        let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
419            return Err(Status::InvalidAction);
420        };
421        if field.value == Value::EndOfContainer {
422            break;
423        }
424        match field.tag.context() {
425            Some(0) => {
426                node = Some(NodeId(
427                    field.unsigned().map_err(|_| Status::ConstraintError)?,
428                ))
429            }
430            Some(1) => {
431                verification_key = Some(key_field(
432                    field.octets().map_err(|_| Status::ConstraintError)?,
433                )?);
434            }
435            _ => {
436                reader
437                    .skip_value(&field)
438                    .map_err(|_| Status::InvalidAction)?;
439            }
440        }
441    }
442    node.map(|n| (n, verification_key))
443        .ok_or(Status::InvalidCommand)
444}
445
446/// Reads `StayActiveRequest`'s single field (§9.16.7.4).
447fn decode_stay_active(fields: &[u8]) -> Result<u32, Status> {
448    let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
449    let element = reader
450        .next_element()
451        .map_err(|_| Status::InvalidAction)?
452        .ok_or(Status::InvalidAction)?;
453    if element.value.container() != Some(ContainerKind::Structure) {
454        return Err(Status::InvalidAction);
455    }
456    let mut duration = None;
457    loop {
458        let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
459            return Err(Status::InvalidAction);
460        };
461        if field.value == Value::EndOfContainer {
462            break;
463        }
464        if field.tag.context() == Some(0) {
465            duration = Some(
466                u32::try_from(field.unsigned().map_err(|_| Status::ConstraintError)?)
467                    .map_err(|_| Status::ConstraintError)?,
468            );
469        } else {
470            reader
471                .skip_value(&field)
472                .map_err(|_| Status::InvalidAction)?;
473        }
474    }
475    duration.ok_or(Status::InvalidCommand)
476}
477
478/// The timings a device publishes about its own sleep (§9.16.6.1–9.16.6.3).
479#[derive(Debug, Clone, Copy, PartialEq, Eq)]
480pub struct Timings {
481    /// `IdleModeDuration`, in **seconds**: "the maximum interval in seconds the server can
482    /// stay in idle mode".
483    pub idle_mode_duration: u32,
484    /// `ActiveModeDuration`, in **milliseconds**: "the minimum interval in milliseconds the
485    /// server typically will stay in active mode after initial transition out of idle mode".
486    pub active_mode_duration: u32,
487    /// `ActiveModeThreshold`, in **milliseconds**: how long it stays active after traffic.
488    pub active_mode_threshold: u16,
489    /// `MaximumCheckInBackoff`, in seconds, at least `IdleModeDuration`.
490    pub maximum_check_in_backoff: u32,
491}
492
493impl Default for Timings {
494    /// §9.16.6's fallbacks: one second idle, 300 ms active, 300 ms threshold.
495    fn default() -> Self {
496        Self {
497            idle_mode_duration: 1,
498            active_mode_duration: 300,
499            active_mode_threshold: 300,
500            maximum_check_in_backoff: 1,
501        }
502    }
503}
504
505impl Timings {
506    /// Whether the four values satisfy §9.16.6's constraints.
507    ///
508    /// The units are the trap. `IdleModeDuration` is seconds and `ActiveModeDuration` is
509    /// milliseconds, and "The IdleModeDuration SHALL NOT be smaller than the
510    /// ActiveModeDuration" compares them as *durations* — so a device advertising one second
511    /// idle and five seconds active is describing something impossible, and a check that
512    /// compared the two numbers directly would pass it.
513    #[must_use]
514    pub const fn is_valid(&self) -> bool {
515        if self.idle_mode_duration == 0 || self.idle_mode_duration > IDLE_MODE_DURATION_MAX {
516            return false;
517        }
518        if self.maximum_check_in_backoff < self.idle_mode_duration
519            || self.maximum_check_in_backoff > IDLE_MODE_DURATION_MAX
520        {
521            return false;
522        }
523        // Compare in milliseconds; `idle_mode_duration` is at most 64800, so this cannot
524        // overflow a u32.
525        self.idle_mode_duration.saturating_mul(1000) >= self.active_mode_duration
526    }
527}
528
529/// The descriptor for an instance with these features.
530///
531/// Derived from the specification's own tables rather than written out, because the element
532/// set *moves with the feature map*: without `UAT` there is no `UserActiveModeTriggerHint`,
533/// without `LITS` no `OperatingMode` and no `StayActiveRequest`. A fixed list would advertise
534/// all of them whatever the device claimed, and a client reading `AttributeList` would believe
535/// it — then read an attribute the device answers `UNSUPPORTED_ATTRIBUTE` for.
536///
537/// `Optional` names the elements §9.16.6 leaves to the product. The storage lives in the
538/// returned value, so a device holds one per cluster instance for as long as its node exists.
539///
540/// Returns [`ErrorCode::InvalidArgument`](crate::ErrorCode) for a feature this revision does
541/// not define.
542pub fn conforming(
543    features: Feature,
544    optional: &Optional<'_>,
545) -> crate::error::Result<Conforming<12, 4, 2, 0>> {
546    Conforming::new(
547        &crate::clusters::generated::icd_management::CLUSTER,
548        features.bits(),
549        optional,
550    )
551}
552
553/// What a device must do when `StayActiveRequest` arrives.
554///
555/// §9.16.7.4 makes the answer the device's, not the cluster's: the `PromisedActiveDuration`
556/// is "the greater of" what the client asked for and "the server's planned remaining active
557/// time based on the ActiveModeThreshold and **its internal resources and power budget**".
558/// Nothing here knows a power budget, so the device supplies this and the cluster reports it.
559pub trait StayActive {
560    /// The duration in milliseconds this device promises to remain reachable, having been
561    /// asked for `requested`.
562    fn promise(&self, requested: u32) -> u32;
563}
564
565/// A device that simply grants what it is asked for.
566///
567/// Correct for a mains-powered node and a reasonable starting point for a battery one, since
568/// §9.16.7.4 permits a server to "replace StayActiveDuration with Minimum Active Duration" —
569/// but a device with a real power budget should say so rather than promise what it cannot keep.
570#[derive(Debug, Clone, Copy, Default)]
571pub struct GrantRequested;
572
573impl StayActive for GrantRequested {
574    fn promise(&self, requested: u32) -> u32 {
575        requested
576    }
577}
578
579/// The ICD Management cluster's state (§9.16.6).
580///
581/// `N` is the total number of registrations across every fabric; `clients_per_fabric` is what
582/// §9.16.6.6 publishes and what any one fabric may use, so that the first fabric to register
583/// cannot leave a later one unable to.
584#[derive(Debug)]
585pub struct IcdManagement<'a, C: Config, const N: usize, A: StayActive = GrantRequested> {
586    clients: RefCell<heapless::Vec<Registration, N>>,
587    counter: RefCell<u32>,
588    clients_per_fabric: u16,
589    timings: Timings,
590    features: Feature,
591    operating_mode: RefCell<OperatingMode>,
592    trigger_hint: UserActiveModeTrigger,
593    trigger_instruction: &'a str,
594    stay_active: A,
595    _config: PhantomData<C>,
596}
597
598impl<'a, C: Config, const N: usize> IcdManagement<'a, C, N, GrantRequested> {
599    /// A cluster for a device that grants every `StayActiveRequest` in full.
600    #[must_use]
601    pub const fn new(features: Feature, timings: Timings, clients_per_fabric: u16) -> Self {
602        Self::with_stay_active(features, timings, clients_per_fabric, GrantRequested)
603    }
604}
605
606impl<'a, C: Config, const N: usize, A: StayActive> IcdManagement<'a, C, N, A> {
607    /// A cluster whose device decides how long it can stay awake.
608    #[must_use]
609    pub const fn with_stay_active(
610        features: Feature,
611        timings: Timings,
612        clients_per_fabric: u16,
613        stay_active: A,
614    ) -> Self {
615        Self {
616            clients: RefCell::new(heapless::Vec::new()),
617            counter: RefCell::new(0),
618            clients_per_fabric,
619            timings,
620            features,
621            // §9.16.6: a device that does not support LIT is always SIT.
622            operating_mode: RefCell::new(OperatingMode::Sit),
623            trigger_hint: UserActiveModeTrigger::empty(),
624            trigger_instruction: "",
625            stay_active,
626            _config: PhantomData,
627        }
628    }
629
630    /// Declares how a person wakes this device (§9.16.6.7).
631    ///
632    /// Returns [`ErrorCode::InvalidArgument`](crate::ErrorCode) when the hint names a trigger
633    /// that needs an instruction and none is given: "If the attribute indicates support for a
634    /// trigger that is dependent on the UserActiveModeTriggerInstruction … the
635    /// UserActiveModeTriggerInstruction attribute SHALL be implemented and SHALL provide the
636    /// required information." A hint reading "press the button for N seconds" with no N is
637    /// worse than no hint, because a client will display it.
638    pub fn with_trigger(
639        mut self,
640        hint: UserActiveModeTrigger,
641        instruction: &'a str,
642    ) -> crate::error::Result<Self> {
643        if instruction.len() > 128 {
644            crate::error::bail!(InvalidArgument)
645        }
646        if hint.needs_instruction() && instruction.is_empty() {
647            crate::error::bail!(InvalidArgument)
648        }
649        self.trigger_hint = hint;
650        self.trigger_instruction = instruction;
651        Ok(self)
652    }
653
654    /// The timings this device publishes.
655    #[must_use]
656    pub const fn timings(&self) -> Timings {
657        self.timings
658    }
659
660    /// The current operating mode (§9.16.5.2).
661    #[must_use]
662    pub fn operating_mode(&self) -> OperatingMode {
663        *self.operating_mode.borrow()
664    }
665
666    /// Switches between Short and Long Idle Time.
667    ///
668    /// §9.16.4.4: a device may do this while a client is registered only with `DSLS`. Without
669    /// that feature a registered client has been promised the mode it saw, and changing it
670    /// underneath means the client's polling assumptions are silently wrong.
671    pub fn set_operating_mode(&self, mode: OperatingMode) -> Result<(), Status> {
672        if !self.features.contains(Feature::LONG_IDLE_TIME_SUPPORT) {
673            return Err(Status::UnsupportedAttribute);
674        }
675        if mode == OperatingMode::Lit
676            && !self.features.contains(Feature::DYNAMIC_SIT_LIT_SUPPORT)
677            && !self.clients.borrow().is_empty()
678        {
679            return Err(Status::InvalidInState);
680        }
681        *self.operating_mode.borrow_mut() = mode;
682        Ok(())
683    }
684
685    /// The `ICDCounter` (§9.16.6.5) — the Check-In Counter for the next message.
686    #[must_use]
687    pub fn counter(&self) -> u32 {
688        *self.counter.borrow()
689    }
690
691    /// Advances the counter and returns the value the next Check-In message must be
692    /// encrypted with.
693    ///
694    /// It advances **first**, and that order is forced by §4.22.3.3 rather than chosen. A
695    /// client stores the `ICDCounter` it was handed at registration as its *starting* value,
696    /// and validation is `stored offset < received − start`: a check-in bearing the very
697    /// value that was reported has an offset of zero and is rejected as a replay. Appendix
698    /// F.4's Test 3 is exactly that message, and it decrypts perfectly — so a device that
699    /// reported N and then checked in with N would look, from the client's side, like an
700    /// attacker replaying an old message, with nothing anywhere explaining why.
701    ///
702    /// Each value is used once besides: reusing one reuses the nonce it derives
703    /// ([`checkin`](crate::icd::checkin)), so this both advances and reads rather than
704    /// offering the two separately.
705    pub fn next_check_in_counter(&self) -> u32 {
706        let mut counter = self.counter.borrow_mut();
707        *counter = counter.wrapping_add(1);
708        *counter
709    }
710
711    /// Restores the counter after a reboot, at exactly the value given.
712    ///
713    /// §4.6.3: "Nodes are required to persist the Check-In Counter in durable storage", and a
714    /// counter that rewinds reuses a nonce. A device persisting this should store *ahead* of
715    /// where it is — §4.6.3 describes the strategy — exactly as the message counters do.
716    pub fn restore_counter(&self, value: u32) {
717        *self.counter.borrow_mut() = value;
718    }
719
720    /// §4.6.3's factory-reset initialisation, from a full-width random word.
721    ///
722    /// "The device SHALL randomize the initial value of the counter on factory reset per
723    /// Section 4.6.1.1" — the same `Crypto_DRBG(len = 28) + 1` as every other counter in the
724    /// specification, so this goes through the same
725    /// [`initial_counter`](crate::msg::initial_counter).
726    ///
727    /// A factory-fresh cluster starts at zero, because a `const fn` constructor has no
728    /// randomness to draw on and inventing one would be worse than asking. Call this once, when
729    /// the device has no persisted counter to restore; on every boot after that, call
730    /// [`restore_counter`](Self::restore_counter) with what was stored. Starting from zero
731    /// every time is what §4.6.3 forbids: the client validates a check-in as
732    /// `stored offset < received − start`, so a counter that rewinds past a registered client's
733    /// starting value makes every later check-in look like a replay, and the client stops
734    /// waking for a device that is calling it.
735    pub fn randomize_counter(&self, randomness: u32) {
736        *self.counter.borrow_mut() = crate::msg::initial_counter(randomness);
737    }
738
739    /// Every registration, for a device about to persist them or send a check-in.
740    #[must_use]
741    pub fn clients(&self) -> core::cell::Ref<'_, heapless::Vec<Registration, N>> {
742        self.clients.borrow()
743    }
744
745    /// How many registrations one fabric holds.
746    #[must_use]
747    pub fn len_of_fabric(&self, fabric: FabricIndex) -> usize {
748        self.clients
749            .borrow()
750            .iter()
751            .filter(|c| c.fabric_index == fabric)
752            .count()
753    }
754
755    /// Removes every registration of one fabric — what `RemoveFabric` must do.
756    pub fn remove_fabric(&self, fabric: FabricIndex) {
757        self.clients
758            .borrow_mut()
759            .retain(|c| c.fabric_index != fabric);
760    }
761
762    /// §9.16.7.1's steps 1–5.
763    fn register(
764        &self,
765        fields: RegisterFields,
766        fabric: FabricIndex,
767        administrator: bool,
768    ) -> Result<(), StatusIb> {
769        let mut clients = self.clients.borrow_mut();
770        let existing = clients.iter().position(|c| {
771            c.fabric_index == fabric && c.check_in_node_id == fields.check_in_node_id
772        });
773
774        match existing {
775            // Step 1a → 2: an entry for this CheckInNodeID already exists, so this is a
776            // *modification* and the verification key decides whether it is allowed.
777            Some(position) => {
778                let Some(entry) = clients.get_mut(position) else {
779                    return Err(Status::Failure.into());
780                };
781                if !administrator {
782                    // Steps 3a and 3b. `ct_eq` because a comparison that stops at the first
783                    // differing octet tells an attacker how much of the key it has guessed.
784                    let Some(verification) = fields.verification_key else {
785                        return Err(Status::Failure.into());
786                    };
787                    if !ct_eq(verification.as_bytes(), entry.key.as_bytes()) {
788                        return Err(Status::Failure.into());
789                    }
790                }
791                // Step 4.
792                entry.monitored_subject = fields.monitored_subject;
793                entry.client_type = fields.client_type;
794                entry.key = fields.key;
795                Ok(())
796            }
797            // Step 1b, or 1c. Counted from the borrow already held: reaching for a second one
798            // here is a panic, not a compile error, and `RefCell` is the only thing in this
799            // crate that can still do that.
800            None => {
801                let used = clients.iter().filter(|c| c.fabric_index == fabric).count();
802                if used >= usize::from(self.clients_per_fabric) {
803                    return Err(Status::ResourceExhausted.into());
804                }
805                clients
806                    .push(Registration::new(
807                        fields.check_in_node_id,
808                        fields.monitored_subject,
809                        fields.client_type,
810                        fabric,
811                        fields.key,
812                    ))
813                    .map_err(|_| StatusIb::from(Status::ResourceExhausted))
814            }
815        }
816    }
817
818    /// §9.16.7.3's steps 1–5.
819    fn unregister(
820        &self,
821        node: NodeId,
822        verification_key: Option<SymmetricKey>,
823        fabric: FabricIndex,
824        administrator: bool,
825    ) -> Result<(), StatusIb> {
826        let mut clients = self.clients.borrow_mut();
827        let Some(position) = clients
828            .iter()
829            .position(|c| c.fabric_index == fabric && c.check_in_node_id == node)
830        else {
831            // Steps 1a and 2a are the same outcome from a client's point of view, and giving
832            // them different ones would tell an unprivileged caller which node ids are
833            // registered on a fabric it cannot read.
834            return Err(Status::NotFound.into());
835        };
836        if !administrator {
837            let Some(entry) = clients.get(position) else {
838                return Err(Status::Failure.into());
839            };
840            let Some(verification) = verification_key else {
841                return Err(Status::Failure.into());
842            };
843            if !ct_eq(verification.as_bytes(), entry.key.as_bytes()) {
844                return Err(Status::Failure.into());
845            }
846        }
847        clients.remove(position);
848        Ok(())
849    }
850
851    /// Whether a fabric's entries belong in this read (§7.19.1.8.2).
852    fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
853        !ctx.fabric_filtered || ctx.fabric_index == Some(index)
854    }
855
856    /// Whether the caller holds Administer over this cluster (§9.16.7.1 step 2).
857    ///
858    /// An unknown privilege is treated as *not* administrator, which is the cautious reading:
859    /// the consequence is a manager-shaped rule applied to an administrator, which refuses a
860    /// modification that had no verification key. The other default would let anyone who
861    /// reached the command bypass the key check entirely.
862    fn is_administrator(ctx: &InteractionContext<'_>) -> bool {
863        ctx.privilege
864            .is_some_and(|p| p.grants(Privilege::Administer))
865    }
866}
867
868impl<C: Config, const N: usize, A: StayActive> ClusterHandler for IcdManagement<'_, C, N, A> {
869    /// §9.16.6.4: registrations are per fabric, and each one holds a shared key. A
870    /// registration that outlives its fabric is key material for somebody who has left.
871    fn on_lifecycle(&self, event: crate::im::Lifecycle) {
872        if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
873            self.remove_fabric(fabric);
874        }
875    }
876    fn read(
877        &self,
878        resolved: &Resolved<'_>,
879        ctx: &InteractionContext<'_>,
880        w: &mut TlvWriter<'_>,
881        tag: Tag,
882    ) -> Result<(), Status> {
883        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
884        match resolved.attribute {
885            IDLE_MODE_DURATION => full(w.unsigned(tag, u64::from(self.timings.idle_mode_duration))),
886            ACTIVE_MODE_DURATION => {
887                full(w.unsigned(tag, u64::from(self.timings.active_mode_duration)))
888            }
889            ACTIVE_MODE_THRESHOLD => {
890                full(w.unsigned(tag, u64::from(self.timings.active_mode_threshold)))
891            }
892            REGISTERED_CLIENTS => {
893                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
894                    return Err(Status::UnsupportedAttribute);
895                }
896                let clients = self.clients.borrow();
897                full(w.start_array(tag))?;
898                for client in clients
899                    .iter()
900                    .filter(|c| Self::visible(ctx, c.fabric_index))
901                {
902                    full(client.encode(w))?;
903                }
904                full(w.end_container())
905            }
906            ICD_COUNTER => {
907                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
908                    return Err(Status::UnsupportedAttribute);
909                }
910                full(w.unsigned(tag, u64::from(self.counter())))
911            }
912            CLIENTS_SUPPORTED_PER_FABRIC => {
913                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
914                    return Err(Status::UnsupportedAttribute);
915                }
916                full(w.unsigned(tag, u64::from(self.clients_per_fabric)))
917            }
918            USER_ACTIVE_MODE_TRIGGER_HINT => {
919                if !self.features.contains(Feature::USER_ACTIVE_MODE_TRIGGER) {
920                    return Err(Status::UnsupportedAttribute);
921                }
922                full(w.unsigned(tag, u64::from(self.trigger_hint.bits())))
923            }
924            USER_ACTIVE_MODE_TRIGGER_INSTRUCTION => {
925                if !self.features.contains(Feature::USER_ACTIVE_MODE_TRIGGER) {
926                    return Err(Status::UnsupportedAttribute);
927                }
928                full(w.utf8(tag, self.trigger_instruction))
929            }
930            OPERATING_MODE => {
931                if !self.features.contains(Feature::LONG_IDLE_TIME_SUPPORT) {
932                    return Err(Status::UnsupportedAttribute);
933                }
934                full(w.unsigned(tag, self.operating_mode() as u64))
935            }
936            MAXIMUM_CHECK_IN_BACKOFF => {
937                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
938                    return Err(Status::UnsupportedAttribute);
939                }
940                full(w.unsigned(tag, u64::from(self.timings.maximum_check_in_backoff)))
941            }
942            _ => Err(Status::UnsupportedAttribute),
943        }
944    }
945
946    fn invoke(
947        &self,
948        resolved: &ResolvedCommand<'_>,
949        fields: Option<&[u8]>,
950        ctx: &InteractionContext<'_>,
951        w: &mut TlvWriter<'_>,
952        tag: Tag,
953    ) -> Result<Option<CommandId>, StatusIb> {
954        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
955        match resolved.command.id {
956            REGISTER_CLIENT => {
957                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
958                    return Err(Status::UnsupportedCommand.into());
959                }
960                // §8.8.2.3 step b.v: a fabric-scoped command with no accessing fabric has
961                // nowhere to put its entry. A PASE session during commissioning is exactly
962                // that case.
963                let Some(fabric) = ctx.fabric_index else {
964                    return Err(Status::UnsupportedAccess.into());
965                };
966                let fields =
967                    decode_register(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
968                self.register(fields, fabric, Self::is_administrator(ctx))?;
969
970                // §9.16.7.2: "The ICDCounter field SHALL be set to the ICDCounter attribute of
971                // the server." The client stores it as the starting value its replay window is
972                // measured from (§4.22.1.2), so it must be the counter the *next* check-in
973                // will exceed rather than one already spent.
974                full(w.start_structure(tag))?;
975                full(w.unsigned(Tag::Context(0), u64::from(self.counter())))?;
976                full(w.end_container())?;
977                Ok(Some(REGISTER_CLIENT_RESPONSE))
978            }
979            UNREGISTER_CLIENT => {
980                if !self.features.contains(Feature::CHECK_IN_PROTOCOL_SUPPORT) {
981                    return Err(Status::UnsupportedCommand.into());
982                }
983                let Some(fabric) = ctx.fabric_index else {
984                    return Err(Status::UnsupportedAccess.into());
985                };
986                let (node, verification_key) =
987                    decode_unregister(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
988                self.unregister(node, verification_key, fabric, Self::is_administrator(ctx))?;
989                Ok(None)
990            }
991            STAY_ACTIVE_REQUEST => {
992                if !self.features.contains(Feature::LONG_IDLE_TIME_SUPPORT) {
993                    return Err(Status::UnsupportedCommand.into());
994                }
995                let requested =
996                    decode_stay_active(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
997                let promised = self.stay_active.promise(requested);
998                full(w.start_structure(tag))?;
999                full(w.unsigned(Tag::Context(0), u64::from(promised)))?;
1000                full(w.end_container())?;
1001                Ok(Some(STAY_ACTIVE_RESPONSE))
1002            }
1003            _ => Err(Status::UnsupportedCommand.into()),
1004        }
1005    }
1006}
1007
1008/// So a tuple of clusters can dispatch to it by id.
1009impl<C: Config, const N: usize, A: StayActive> Cluster for IcdManagement<'_, C, N, A> {
1010    const ID: ClusterId = ID;
1011}