Skip to main content

matter_kit/node/
mod.rs

1//! The node runtime: the sequence every Matter device keeps, owned by a type.
2//!
3//! The rest of this crate is parts — a messaging layer, a secure channel, an interaction-model
4//! server, a subscription table, the commissioning clusters — and each part is correct on its own.
5//! What a device also needs is the *order* in which they are driven, and that order is where
6//! defects live: a report opened while the priming report is still going out, a chunked read
7//! continued on another controller's exchange, a removed fabric whose subscriptions keep
8//! reporting, a fail-safe whose deadline nobody acts on. [`Runtime`] owns that order.
9//!
10//! # Shape
11//!
12//! Sans-I/O, like everything below it. A datagram goes in through [`Runtime::receive`], time goes
13//! in through [`Runtime::poll`], and whatever the node owes the network comes out of
14//! [`Runtime::transmit`]. [`Runtime::next_deadline`] says when `poll` next has work, and
15//! [`Runtime::notice`] reports what happened, as values rather than log lines. A device with
16//! sockets and a timer runs [`Runtime::run`] and writes no loop of its own.
17//!
18//! ```text
19//!   datagram ──► receive ─┐                   ┌─► transmit ──► socket
20//!                         ├─► Runtime ────────┤
21//!   timer ─────► poll ────┘                   └─► notice ────► log
22//! ```
23//!
24//! # What it owns
25//!
26//! - **The messaging stack**, the §5.5 secure channel, the interaction-model dispatcher and the
27//!   §8.5 subscription table.
28//! - **Per-exchange series state** (§10.2.3): a chunked read continues only on the exchange that
29//!   started it, and a reused exchange id starts afresh.
30//! - **The subscribe flow** (§8.5.2): subscription, priming report (chunked if need be), and the
31//!   `SubscribeResponse` only once the subscriber has acknowledged the last chunk.
32//! - **Reports** (§8.5.3): due reports go out with at most one unacknowledged per subscription,
33//!   filtered as the subscriber that created them.
34//! - **Exchange closing** (§4.10.5.3): what "the application layer" decides is closed.
35//! - **Retransmission** (§4.12.2.1): the same bytes again when MRP asks.
36//! - **Cascades**: a closed or evicted session takes its subscriptions, reports and series; a
37//!   removed fabric takes its subscriptions and window, and its sessions after the reply.
38//! - **Commissioning follow-ups**: §11.18.6.8's administrator entry, PASE fabric binding and IPK
39//!   key set; §11.10.7.2.2's rollback (also on the timer) and §11.10.7.6's commit, including
40//!   closing PASE sessions; §9.10.9.1's `AccessControlEntryChanged` events.
41//!
42//! What it does not own is the device: which clusters it has, what their hooks do, and its
43//! sockets. Those arrive as a [`Device`] — a bundle of references the application builds once.
44
45mod followups;
46mod interactions;
47mod outbox;
48mod serve;
49
50mod driver;
51
52pub use driver::Mdns;
53
54use core::cell::RefCell;
55
56use heapless::{Deque, Vec};
57
58use crate::acl::{AclAccess, SubjectDescriptor};
59use crate::clusters::access_control::AccessControl as AccessControlCluster;
60use crate::clusters::general_commissioning::GeneralCommissioning;
61use crate::clusters::group_key_management::GroupTable;
62use crate::clusters::operational_credentials::{OperationalCredentials, max_nocs_len};
63use crate::config::{Config, DefaultConfig, MAX_UDP_MESSAGE, MAX_UDP_PAYLOAD};
64use crate::crypto::{KeyStore, Spake2pVerifierData, SymmetricKey};
65use crate::dm::events::{EventSource, EventStore, NewEvent, RecordError};
66use crate::dm::{DataVersionSource, DataVersions, Node};
67use crate::error::{Error, Result};
68use crate::exchange::{ExchangeKey, Role};
69use crate::fabric::CompressedFabricId;
70use crate::group::{GroupKeySet, GroupKeys, PeerTable};
71use crate::im::{
72    ClusterHandler, ClusterId, Dispatcher, EndpointId, InteractionContext, Status,
73    SubscriptionTable,
74};
75use crate::messaging::{Due, Evicted, Messaging, Received};
76use crate::msg::{FabricIndex, GroupId, NodeId, ProtocolId, SessionId};
77use crate::platform::{Duration, Instant, Peer, PeerAddr, Rng};
78use crate::sc::{Channel, ChannelBuffers, ChannelContext, PbkdfParameters};
79use crate::session::SessionKind;
80
81use interactions::Interactions;
82use outbox::{Outbox, Resend};
83
84/// The scratch a read builds one whole attribute value in, sized for [`DefaultConfig`].
85///
86/// A value, not a message: a non-fabric-filtered read of `NOCs` carries every fabric's NOC and
87/// ICAC, and [`max_nocs_len`] is the library's own bound for it.
88pub const SCRATCH: usize = max_nocs_len(DefaultConfig::FABRICS);
89
90/// How many attributes one report message carries at most, before §10.2.3 chunking.
91const REPORT_LIMIT: usize = 24;
92
93/// How many subscriptions the runtime holds — §8.5's minimum for five fabrics, three each.
94pub const SUBSCRIPTIONS: usize = 15;
95
96/// How many paths one subscription holds — §8.5's minimum of three.
97pub const SUBSCRIPTION_PATHS: usize = 3;
98
99/// The subscription table the runtime keeps.
100pub type Subscriptions<C> = SubscriptionTable<C, SUBSCRIPTIONS, SUBSCRIPTION_PATHS>;
101
102/// How long an established PASE channel may sit unused, with the fail-safe never armed, before
103/// an open window may release it.
104///
105/// §5.5 rule 1 holds the commissioning channel closed "until session establishment fails or the
106/// successfully established PASE session is terminated", which is what stops a second
107/// commissioner stepping into the first one's commissioning. A commissioner is under no
108/// obligation to send `CloseSession`, though: one that gives up before arming the fail-safe
109/// leaves a session the node will never hear from again, and without a way out the node answers
110/// `Busy` for ever. A commissioning that *did* arm the fail-safe ends in a commit or a rollback,
111/// both of which close the PASE session; this is only for the one that never started.
112pub const PASE_ABANDON_GRACE: Duration = Duration::from_secs(30);
113
114mod sealed {
115    pub trait Sealed {}
116}
117
118/// The Access Control cluster, as the runtime reaches it.
119///
120/// Implemented for [`AccessControl`](crate::clusters::access_control::AccessControl) and
121/// nothing else; it exists to keep the list's four const parameters out of [`Device`].
122pub trait AccessList: sealed::Sealed {
123    /// The access check for one subject.
124    type Access<'b>: crate::im::AccessControl
125    where
126        Self: 'b;
127    /// The list, bound to a node and the subject of one interaction.
128    fn access<'b>(&'b self, node: Node<'b>, subject: &'b SubjectDescriptor) -> Self::Access<'b>;
129    /// §11.18.6.8 step 7's administrator entry, recorded as a change like any other.
130    fn grant_admin(
131        &self,
132        fabric: FabricIndex,
133        subject: NodeId,
134        ctx: &InteractionContext<'_>,
135    ) -> Result<()>;
136    /// Every change since the last call, each as an encoded `AccessControlEntryChanged` payload
137    /// and the fabric it belongs to (§9.10.9.1).
138    fn drain_changes(&self, each: &mut dyn FnMut(FabricIndex, Result<&[u8]>));
139}
140
141impl<C: Config, const N: usize, const S: usize, const T: usize> sealed::Sealed
142    for AccessControlCluster<'_, C, N, S, T>
143{
144}
145
146impl<C: Config, const N: usize, const S: usize, const T: usize> AccessList
147    for AccessControlCluster<'_, C, N, S, T>
148{
149    type Access<'b>
150        = AclAccess<'b, C, N, S, T>
151    where
152        Self: 'b;
153
154    fn access<'b>(&'b self, node: Node<'b>, subject: &'b SubjectDescriptor) -> Self::Access<'b> {
155        AclAccess::new(self.acl(), node, subject)
156    }
157
158    fn grant_admin(
159        &self,
160        fabric: FabricIndex,
161        subject: NodeId,
162        ctx: &InteractionContext<'_>,
163    ) -> Result<()> {
164        self.add_admin_for_fabric(fabric, subject, ctx)
165    }
166
167    fn drain_changes(&self, each: &mut dyn FnMut(FabricIndex, Result<&[u8]>)) {
168        for change in self.take_changes() {
169            let mut buf = [0u8; crate::dm::events::EVENT_DATA_MAX];
170            let mut w =
171                crate::tlv::TlvWriter::new_in(&mut buf, crate::tlv::ContainerKind::Structure);
172            let encoded = change
173                .encode(&mut w, crate::tlv::Tag::Context(7))
174                .and_then(|()| w.finish());
175            each(change.fabric_index, encoded);
176        }
177    }
178}
179
180/// The group key store, as the runtime reaches it: `RefCell<GroupKeys<…>>`.
181pub trait GroupKeyStore: sealed::Sealed {
182    /// §11.18.6.8: providing an IPK "is equivalent to a KeySetWrite of group key set 0".
183    fn install_ipk(
184        &self,
185        fabric: FabricIndex,
186        ipk: SymmetricKey,
187    ) -> core::result::Result<(), Status>;
188    /// §4.16.3's receive path: find the key, check the counter, decrypt.
189    fn open<'b>(
190        &self,
191        buf: &'b mut [u8],
192        from: PeerAddr,
193        peers: &mut GroupPeers,
194        compressed: &dyn Fn(FabricIndex) -> Option<CompressedFabricId>,
195        scratch: &mut [u8],
196    ) -> Result<crate::group::wire::Received<'b>>;
197}
198
199/// §4.16.1's group peer table as the runtime sizes it.
200pub type GroupPeers = PeerTable<4, 2>;
201
202impl<C: Config, const K: usize, const M: usize> sealed::Sealed for RefCell<GroupKeys<C, K, M>> {}
203
204impl<C: Config, const K: usize, const M: usize> GroupKeyStore for RefCell<GroupKeys<C, K, M>> {
205    fn install_ipk(
206        &self,
207        fabric: FabricIndex,
208        ipk: SymmetricKey,
209    ) -> core::result::Result<(), Status> {
210        let set = GroupKeySet::single(
211            fabric,
212            crate::group::IPK_KEY_SET,
213            crate::group::GroupKeySecurityPolicy::TrustFirst,
214            ipk,
215            0,
216        );
217        self.borrow_mut().write_key_set(set)
218    }
219
220    fn open<'b>(
221        &self,
222        buf: &'b mut [u8],
223        from: PeerAddr,
224        peers: &mut GroupPeers,
225        compressed: &dyn Fn(FabricIndex) -> Option<CompressedFabricId>,
226        scratch: &mut [u8],
227    ) -> Result<crate::group::wire::Received<'b>> {
228        crate::group::wire::receive(buf, from, &self.borrow(), peers, compressed, scratch)
229    }
230}
231
232/// The event store, as the runtime reaches it: `RefCell<EventStore<…>>`.
233pub trait EventLog: sealed::Sealed {
234    /// Records one event (§7.14).
235    fn record(&self, event: &NewEvent<'_>) -> core::result::Result<u64, RecordError>;
236    /// The store as reads and reports see it.
237    fn source(&self) -> &dyn EventSource;
238}
239
240impl<const A: usize, const B: usize, const D: usize> sealed::Sealed
241    for RefCell<EventStore<A, B, D>>
242{
243}
244
245impl<const A: usize, const B: usize, const D: usize> EventLog for RefCell<EventStore<A, B, D>> {
246    fn record(&self, event: &NewEvent<'_>) -> core::result::Result<u64, RecordError> {
247        self.borrow_mut().record(event)
248    }
249
250    fn source(&self) -> &dyn EventSource {
251        self
252    }
253}
254
255/// §7.10.3's data versions, as the runtime reaches them: [`DataVersions`].
256pub trait ChangeLog: DataVersionSource + sealed::Sealed {
257    /// Every cluster instance whose data changed since the last call.
258    fn drain(&self, each: &mut dyn FnMut(EndpointId, ClusterId));
259}
260
261impl<const N: usize> sealed::Sealed for DataVersions<N> {}
262
263impl<const N: usize> ChangeLog for DataVersions<N> {
264    fn drain(&self, each: &mut dyn FnMut(EndpointId, ClusterId)) {
265        for (endpoint, cluster) in self.drain_changes() {
266            each(endpoint, cluster);
267        }
268    }
269}
270
271/// What the application hands the runtime: its node and the parts the specification makes the
272/// node's to drive.
273///
274/// Built once with a struct literal; every type parameter is inferred, so an application never
275/// spells one. The clusters named here must also be in `handler` — the runtime reaches them
276/// directly only for the follow-ups a cluster cannot perform itself: a cluster reports, the
277/// node acts.
278pub struct Device<'a, C, K, G, H, Ac, Gk, Ev, V, const F: usize>
279where
280    C: Config,
281    K: KeyStore,
282    G: Rng,
283    H: ClusterHandler,
284    Ac: AccessList,
285    Gk: GroupKeyStore,
286    Ev: EventLog,
287    V: ChangeLog,
288{
289    /// The node's endpoints and clusters.
290    pub node: Node<'a>,
291    /// Every cluster instance, routed by endpoint and cluster id.
292    pub handler: &'a H,
293    /// Operational Credentials — and through it the fabric table, the key store, the rng and
294    /// the fail-safe.
295    pub credentials: &'a OperationalCredentials<'a, C, K, G, F>,
296    /// General Commissioning — and through it the fail-safe and the commissioning window.
297    pub commissioning: &'a GeneralCommissioning<'a>,
298    /// Access Control.
299    pub access_control: &'a Ac,
300    /// The group key store Group Key Management serves.
301    pub group_keys: &'a Gk,
302    /// The event log.
303    pub events: &'a Ev,
304    /// The data versions.
305    pub versions: &'a V,
306    /// The SPAKE2+ verifier the passcode was turned into at manufacture.
307    pub verifier: &'a Spake2pVerifierData,
308    /// The PBKDF parameters that go with it.
309    pub parameters: &'a PbkdfParameters,
310    /// Which groups the node's endpoints are in, so the driver can join their multicast
311    /// addresses (§2.5.6.2). `None` for a node with no Groups cluster.
312    pub memberships: Option<&'a dyn GroupTable>,
313}
314
315impl<C, K, G, H, Ac, Gk, Ev, V, const F: usize> core::fmt::Debug
316    for Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>
317where
318    C: Config,
319    K: KeyStore,
320    G: Rng,
321    H: ClusterHandler,
322    Ac: AccessList,
323    Gk: GroupKeyStore,
324    Ev: EventLog,
325    V: ChangeLog,
326{
327    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
328        f.debug_struct("Device")
329            .field("node", &self.node)
330            .field("groups", &self.memberships.is_some())
331            .finish_non_exhaustive()
332    }
333}
334
335/// Something worth knowing that happened, in the order it happened.
336///
337/// Nothing here is an error the caller must handle — the runtime has already done what the
338/// specification asks. Each is something an integrator wants to log, count or assert on; the
339/// runtime keeps the last sixteen and drops the oldest.
340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341#[non_exhaustive]
342pub enum Notice {
343    /// A datagram was dropped before it reached any protocol: unparseable, unauthenticated, a
344    /// replay, or for a session this node does not have.
345    Dropped(Error),
346    /// A message was received and could not be answered.
347    Refused(Error),
348    /// PASE or CASE completed.
349    Established {
350        /// The new session.
351        session: SessionId,
352        /// PASE or CASE.
353        kind: SessionKind,
354        /// The fabric, for CASE; `FabricIndex(0)` for PASE.
355        fabric: FabricIndex,
356    },
357    /// A session closed — by its peer, by eviction, or by a cascade — with this many
358    /// subscriptions.
359    SessionClosed {
360        /// The session.
361        session: SessionId,
362        /// How many subscriptions went with it.
363        subscriptions: usize,
364    },
365    /// A session was evicted to make room for a new one (§4.11.1.1).
366    Evicted {
367        /// The session.
368        session: SessionId,
369    },
370    /// A subscription was created and its priming report is going out.
371    Subscribed {
372        /// Its id.
373        id: u32,
374        /// The maximum interval granted.
375        max_interval_s: u16,
376    },
377    /// A subscription's `SubscribeResponse` went out: it is active.
378    Granted {
379        /// Its id.
380        id: u32,
381    },
382    /// A due report could not be built, framed or queued; the subscription is still due.
383    ReportFailed {
384        /// The subscription.
385        id: u32,
386        /// Why.
387        error: Error,
388    },
389    /// A fabric joined (`AddNOC`).
390    FabricAdded(FabricIndex),
391    /// A fabric's identity was replaced (`UpdateNOC`).
392    FabricUpdated(FabricIndex),
393    /// A fabric left (`RemoveFabric`, or a rollback of `AddNOC`).
394    FabricRemoved(FabricIndex),
395    /// The fail-safe was disarmed or expired and its cleanup ran (§11.10.7.2.2).
396    RolledBack,
397    /// `CommissioningComplete` succeeded on this fabric (§11.10.7.6).
398    Commissioned(FabricIndex),
399    /// A commissioning window opened, and the channel admits PASE again.
400    WindowOpened,
401    /// An established PASE channel was released to an open window.
402    ChannelReleased,
403    /// A groupcast was acted on (and, as §8.7.2.3 requires, not answered).
404    Groupcast(GroupId),
405    /// An access-control change could not be recorded as an event.
406    EventLost(Option<RecordError>),
407    /// The outbox was full and a datagram was dropped; MRP will retransmit a reliable one.
408    OutboxFull,
409    /// MRP gave up on an exchange.
410    Abandoned(ExchangeKey),
411}
412
413/// The interaction-model state the runtime keeps across messages.
414#[derive(Debug)]
415struct Im<C: Config, const I: usize> {
416    dispatcher: Dispatcher<4>,
417    interactions: Interactions<I>,
418    subscriptions: Subscriptions<C>,
419    /// One outstanding report per subscription: the exchange it went out on.
420    reporting: Vec<(u32, ExchangeKey), SUBSCRIPTIONS>,
421    /// Subscriptions whose last report could not be built, and when to try again — so a report
422    /// that cannot be built does not spin the loop.
423    backoff: Vec<(u32, Instant), SUBSCRIPTIONS>,
424}
425
426/// The work space the runtime builds messages in.
427#[derive(Debug)]
428struct Buffers<const B: usize> {
429    /// The protocol payload of a reply, before framing.
430    payload: [u8; MAX_UDP_PAYLOAD],
431    /// One attribute value, before the server decides where it fits.
432    scratch: [u8; B],
433    /// Where §4.8's AEAD joins the header and the payload.
434    frame: [u8; MAX_UDP_MESSAGE],
435    /// The framed datagram.
436    wire: [u8; MAX_UDP_MESSAGE],
437    /// §4.11.1.1's `CloseSession` to an evicted peer; also a group message's decryption space.
438    evict: [u8; MAX_UDP_MESSAGE],
439}
440
441/// The PASE channel's commissioning progress, for §5.5's release rule.
442#[derive(Debug, Clone, Copy, Default)]
443struct PaseProgress {
444    established_at: Option<Instant>,
445    armed_seen: bool,
446}
447
448/// The node runtime.
449///
450/// `S` sessions and `X` exchanges size the messaging stack ([`Messaging`]'s own defaults); `I`
451/// interactions in progress; `R` datagrams kept for retransmission; `Q` datagrams queued for
452/// sending; `B` octets of attribute scratch ([`SCRATCH`]). The defaults fit [`DefaultConfig`]
453/// and satisfy every specification minimum for five fabrics; a device with less RAM lowers
454/// `I`, `R` and `Q` first.
455///
456/// About 60 KiB with the defaults, almost all of it datagram buffers and the subscription
457/// table, so a device puts it in a `static` rather than on a task's stack.
458#[derive(Debug)]
459pub struct Runtime<
460    C: Config,
461    const S: usize = 16,
462    const X: usize = 64,
463    const I: usize = 8,
464    const R: usize = 4,
465    const Q: usize = 4,
466    const B: usize = SCRATCH,
467> {
468    stack: Messaging<C, S, X>,
469    channel: Channel,
470    im: Im<C, I>,
471    outbox: Outbox<Q>,
472    resend: Resend<R>,
473    group_peers: GroupPeers,
474    notices: Deque<Notice, 16>,
475    window_was_open: bool,
476    pase: PaseProgress,
477    buf: Buffers<B>,
478}
479
480impl<
481    C: Config,
482    const S: usize,
483    const X: usize,
484    const I: usize,
485    const R: usize,
486    const Q: usize,
487    const B: usize,
488> Runtime<C, S, X, I, R, Q, B>
489{
490    /// A runtime with no sessions, its ids and counters drawn from `rng`.
491    ///
492    /// # Errors
493    ///
494    /// The `rng` failed.
495    pub fn new(rng: &impl Rng) -> Result<Self> {
496        const {
497            assert!(
498                B >= max_nocs_len(C::FABRICS),
499                "the scratch must hold a non-fabric-filtered NOCs read for every fabric"
500            );
501            assert!(Q > 1, "one input can owe a reply and an eviction report");
502        }
503        Ok(Self {
504            // §4.13.2.4 wants an unpredictable non-zero session id.
505            stack: Messaging::new(rng.next_u16()? | 1, rng.next_u16()?, rng.next_u32()?),
506            channel: Channel::new(),
507            im: Im {
508                // Basic Information's own default; `with_max_paths_per_invoke` matches a product
509                // that advertises more.
510                dispatcher: Dispatcher::new(1),
511                interactions: Interactions::new(),
512                subscriptions: SubscriptionTable::new(),
513                reporting: Vec::new(),
514                backoff: Vec::new(),
515            },
516            outbox: Outbox::new(),
517            resend: Resend::new(),
518            group_peers: PeerTable::new(),
519            notices: Deque::new(),
520            window_was_open: false,
521            pase: PaseProgress::default(),
522            buf: Buffers {
523                payload: [0; MAX_UDP_PAYLOAD],
524                scratch: [0; B],
525                frame: [0; MAX_UDP_MESSAGE],
526                wire: [0; MAX_UDP_MESSAGE],
527                evict: [0; MAX_UDP_MESSAGE],
528            },
529        })
530    }
531
532    /// Sets `MaxPathsPerInvoke` (§8.8.2.3) — what Basic Information advertises.
533    #[must_use]
534    pub fn with_max_paths_per_invoke(mut self, max: u16) -> Self {
535        self.im.dispatcher = Dispatcher::new(max);
536        self
537    }
538
539    /// The messaging stack.
540    #[must_use]
541    pub const fn messaging(&self) -> &Messaging<C, S, X> {
542        &self.stack
543    }
544
545    /// The messaging stack, for installing a session directly or registering protocols.
546    pub const fn messaging_mut(&mut self) -> &mut Messaging<C, S, X> {
547        &mut self.stack
548    }
549
550    /// The subscriptions.
551    #[must_use]
552    pub const fn subscriptions(&self) -> &Subscriptions<C> {
553        &self.im.subscriptions
554    }
555
556    /// The secure channel.
557    #[must_use]
558    pub const fn channel(&self) -> &Channel {
559        &self.channel
560    }
561
562    /// The next datagram to send, and where. Valid until the next call.
563    pub fn transmit(&mut self) -> Option<(Peer, &[u8])> {
564        self.outbox.pop()
565    }
566
567    /// The oldest notice not yet taken.
568    pub fn notice(&mut self) -> Option<Notice> {
569        self.notices.pop_front()
570    }
571
572    fn notify(&mut self, notice: Notice) {
573        #[cfg(feature = "log")]
574        log::debug!("{notice:?}");
575        #[cfg(all(feature = "defmt", not(feature = "log")))]
576        defmt::debug!("{}", defmt::Debug2Format(&notice));
577        if self.notices.is_full() {
578            self.notices.pop_front();
579        }
580        let _ = self.notices.push_back(notice);
581    }
582
583    /// One datagram in.
584    ///
585    /// Whatever it owes — a reply, an acknowledgement, a `CloseSession` to an evicted peer — is
586    /// queued for [`Self::transmit`]. `datagram` is decrypted in place.
587    pub fn receive<K, G, H, Ac, Gk, Ev, V, const F: usize>(
588        &mut self,
589        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
590        datagram: &mut [u8],
591        from: Peer,
592        now: Instant,
593    ) where
594        K: KeyStore,
595        G: Rng,
596        H: ClusterHandler,
597        Ac: AccessList,
598        Gk: GroupKeyStore,
599        Ev: EventLog,
600        V: ChangeLog,
601    {
602        self.watch_window(device, now);
603        let received = match self.stack.receive(datagram, from, now) {
604            Ok(received) => received,
605            Err(e) => {
606                self.notify(Notice::Dropped(e));
607                return;
608            }
609        };
610        match received {
611            Received::Group { .. } => {
612                if let Peer::Udp(addr) = from {
613                    self.groupcast(device, datagram, addr, now);
614                }
615            }
616            // §4.12.2.2: acknowledged, not acted on.
617            Received::Duplicate {
618                exchange,
619                needs_ack,
620            } => {
621                if needs_ack {
622                    self.acknowledge(exchange, now);
623                }
624            }
625            // §4.11.1.4: the peer closed the session and `Messaging` has closed this end. What
626            // is left is everything above that layer which was keyed on it.
627            Received::SessionClosed { session } => self.session_gone(session),
628            Received::Acknowledged { exchange } => {
629                // A report this node sent has been acknowledged: the slot is free for the next.
630                // Unless the acknowledgement was for an older message — a duplicate's, arriving
631                // late — in which case the exchange still owes delivery and stays as it is.
632                if !self.stack.is_awaiting_ack(exchange) {
633                    self.im.reporting.retain(|(_, on)| *on != exchange);
634                }
635                self.close_if_idle(exchange);
636            }
637            Received::Message {
638                exchange,
639                header,
640                payload,
641                ..
642            } => self.message(
643                device,
644                exchange,
645                header.protocol,
646                header.opcode,
647                payload,
648                now,
649            ),
650        }
651        self.drain_changes(device);
652    }
653
654    /// Everything time-driven.
655    ///
656    /// Call it whenever [`Self::next_deadline`] passes, and after every [`Self::receive`] — the
657    /// driver does both on every iteration, whichever event woke it, because a loop that runs
658    /// time-driven work only when the timer wins a race against the sockets starves one or the
659    /// other.
660    pub fn poll<K, G, H, Ac, Gk, Ev, V, const F: usize>(
661        &mut self,
662        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
663        now: Instant,
664    ) where
665        K: KeyStore,
666        G: Rng,
667        H: ClusterHandler,
668        Ac: AccessList,
669        Gk: GroupKeyStore,
670        Ev: EventLog,
671        V: ChangeLog,
672    {
673        self.watch_window(device, now);
674        // "If the PASE session is not established within the expected time window the
675        // Commissionee SHALL terminate the current session establishment".
676        if self.channel.deadline().is_some_and(|d| d <= now) {
677            self.channel.poll(now, device.commissioning.window);
678        }
679        self.expire_fail_safe(device, now);
680        self.drain_changes(device);
681        self.reports(device, now);
682        loop {
683            let randomness = random(device);
684            let Some(due) = self.stack.poll(now, randomness) else {
685                break;
686            };
687            match due {
688                // §4.12.5.2.2: the acknowledgement waited for a message to ride on and none came,
689                // so it goes on its own — and it has to actually go.
690                Due::Acknowledge { exchange } => {
691                    self.acknowledge(exchange, now);
692                    // A standalone acknowledgement means nothing is coming back on this exchange
693                    // — nobody acknowledges an acknowledgement — so a responder exchange with no
694                    // series in progress is finished. Not this node's own report exchanges: those
695                    // are waiting for the acknowledgement that `Received::Acknowledged` closes.
696                    if matches!(exchange.role, Role::Responder) {
697                        self.close_if_idle(exchange);
698                    }
699                }
700                Due::Retransmit { exchange, counter } => {
701                    if let Some((peer, bytes)) = self.resend.find(exchange, counter)
702                        && !self.outbox.push(peer, bytes)
703                    {
704                        self.notify(Notice::OutboxFull);
705                    }
706                }
707                Due::Abandoned { exchange } => {
708                    // The exchange is closed and its report will never be acknowledged; free the
709                    // slot or the subscription never reports again.
710                    self.im.reporting.retain(|(_, on)| *on != exchange);
711                    self.im.interactions.forget(exchange);
712                    self.resend.forget(exchange);
713                    self.notify(Notice::Abandoned(exchange));
714                }
715            }
716        }
717    }
718
719    /// The earliest instant [`Self::poll`] has work, if any.
720    #[must_use]
721    pub fn next_deadline<K, G, H, Ac, Gk, Ev, V, const F: usize>(
722        &self,
723        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
724    ) -> Option<Instant>
725    where
726        K: KeyStore,
727        G: Rng,
728        H: ClusterHandler,
729        Ac: AccessList,
730        Gk: GroupKeyStore,
731        Ev: EventLog,
732        V: ChangeLog,
733    {
734        // A subscription that cannot report yet — its priming report is going out, or a report
735        // is already in flight — is not a deadline: waking for it would spin the loop until the
736        // acknowledgement arrives, which is itself an event.
737        let reports = self
738            .im
739            .subscriptions
740            .iter()
741            .filter(|s| {
742                !self.im.interactions.priming(s.id)
743                    && !self.im.reporting.iter().any(|(id, _)| *id == s.id)
744            })
745            .map(|s| {
746                let at = s.next_deadline();
747                match self.im.backoff.iter().find(|(id, _)| *id == s.id) {
748                    Some((_, retry)) => at.max(*retry),
749                    None => at,
750                }
751            })
752            .min();
753        let pase_release = self
754            .pase
755            .established_at
756            .filter(|_| !self.pase.armed_seen)
757            .map(|at| at.saturating_add(PASE_ABANDON_GRACE));
758        [
759            self.stack.wake_at(),
760            self.channel.deadline(),
761            reports,
762            device.commissioning.fail_safe.borrow().next_deadline(),
763            device.commissioning.window.borrow().deadline(),
764            pase_release,
765        ]
766        .into_iter()
767        .flatten()
768        .min()
769    }
770
771    // --- Routing ---------------------------------------------------------------------------
772
773    fn message<K, G, H, Ac, Gk, Ev, V, const F: usize>(
774        &mut self,
775        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
776        exchange: ExchangeKey,
777        protocol: ProtocolId,
778        opcode: u8,
779        body: &[u8],
780        now: Instant,
781    ) where
782        K: KeyStore,
783        G: Rng,
784        H: ClusterHandler,
785        Ac: AccessList,
786        Gk: GroupKeyStore,
787        Ev: EventLog,
788        V: ChangeLog,
789    {
790        if protocol == ProtocolId::SECURE_CHANNEL {
791            self.secure_channel(device, exchange, opcode, body, now);
792            return;
793        }
794        if protocol != ProtocolId::INTERACTION_MODEL {
795            return;
796        }
797        // §10.7.3.2: a subscriber answers a report with a `StatusResponse`, and a peer may carry
798        // the acknowledgement on it rather than send a bare one — the CHIP SDK does. Either way
799        // the report has been delivered once the exchange is no longer awaiting it, and the
800        // in-flight slot is free; otherwise the subscription never reports again.
801        if !self.stack.is_awaiting_ack(exchange) {
802            self.im.reporting.retain(|(_, on)| *on != exchange);
803        }
804        let reply = self.interaction(device, exchange, opcode, body, now);
805        // §11.10.7.2.2, §11.18.6.8, §11.18.6.12: what the command left for the node, applied
806        // before the reply so the reply reflects it — and the parts that would strand the
807        // reply (closing the session it is about to go out on) deferred until after it.
808        let deferred = self.follow_up(device, exchange.session, now);
809        match reply {
810            Ok(Some((opcode, len))) => self.send(device, exchange, opcode, len, now),
811            // Nothing is owed and nothing is part-way through, so §4.10.5.3's "application
812            // layer" has decided the exchange is over. The close cannot wait for a bare
813            // acknowledgement: a peer may piggyback it on its next message instead, and the CHIP
814            // SDK does — a read would leave an exchange open that nothing ever closes.
815            Ok(None) => self.close_if_idle(exchange),
816            Err(e) => {
817                self.notify(Notice::Refused(e));
818                self.im.interactions.forget(exchange);
819                self.close_if_idle(exchange);
820            }
821        }
822        self.apply(deferred);
823    }
824
825    fn secure_channel<K, G, H, Ac, Gk, Ev, V, const F: usize>(
826        &mut self,
827        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
828        exchange: ExchangeKey,
829        opcode: u8,
830        body: &[u8],
831        now: Instant,
832    ) where
833        K: KeyStore,
834        G: Rng,
835        H: ClusterHandler,
836        Ac: AccessList,
837        Gk: GroupKeyStore,
838        Ev: EventLog,
839        V: ChangeLog,
840    {
841        let answered = {
842            let rng = device.credentials.rng.borrow();
843            let ctx = ChannelContext {
844                fabrics: device.credentials.fabrics,
845                keys: device.credentials.keys,
846                rng: &*rng,
847                window: device.commissioning.window,
848                verifier: device.verifier,
849                parameters: device.parameters,
850                now,
851            };
852            let mut buffers = ChannelBuffers {
853                reply: &mut self.buf.payload,
854                frame: &mut self.buf.frame,
855                evict: &mut self.buf.evict,
856            };
857            self.channel
858                .on_message(&mut self.stack, opcode, body, &ctx, &mut buffers)
859        };
860        let answered = match answered {
861            Ok(answered) => answered,
862            Err(e) => {
863                self.notify(Notice::Refused(e));
864                return;
865            }
866        };
867        if let Some(established) = &answered.established {
868            if established.kind == SessionKind::Pase {
869                self.pase = PaseProgress {
870                    established_at: Some(now),
871                    armed_seen: false,
872                };
873            }
874            self.notify(Notice::Established {
875                session: established.session,
876                kind: established.kind,
877                fabric: established.fabric,
878            });
879        }
880        // A message for a handshake that is not running gets no answer: saying nothing is the
881        // answer, not an error.
882        if let Some((opcode, len)) = answered.reply {
883            self.send(device, exchange, opcode, len, now);
884        }
885        if let Some(evicted) = answered.evicted {
886            self.evicted(evicted);
887        }
888    }
889
890    // --- Sending ---------------------------------------------------------------------------
891
892    /// Frames `payload[..len]` on `exchange`, queues it, and keeps it for retransmission.
893    fn send<K, G, H, Ac, Gk, Ev, V, const F: usize>(
894        &mut self,
895        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
896        exchange: ExchangeKey,
897        opcode: u8,
898        len: usize,
899        now: Instant,
900    ) where
901        K: KeyStore,
902        G: Rng,
903        H: ClusterHandler,
904        Ac: AccessList,
905        Gk: GroupKeyStore,
906        Ev: EventLog,
907        V: ChangeLog,
908    {
909        if let Err(e) = self.frame(exchange, opcode, len, random(device), now) {
910            self.notify(Notice::Refused(e));
911        }
912    }
913
914    fn frame(
915        &mut self,
916        exchange: ExchangeKey,
917        opcode: u8,
918        len: usize,
919        randomness: u32,
920        now: Instant,
921    ) -> Result<()> {
922        let payload = self
923            .buf
924            .payload
925            .get(..len)
926            .ok_or(Error::new(crate::ErrorCode::BufferTooSmall))?;
927        let (n, counter) = self.stack.send(
928            exchange,
929            opcode,
930            true,
931            payload,
932            now,
933            randomness,
934            &mut self.buf.frame,
935            &mut self.buf.wire,
936        )?;
937        let peer = self
938            .stack
939            .peer(exchange)
940            .ok_or(Error::new(crate::ErrorCode::NoSession))?;
941        let bytes = self
942            .buf
943            .wire
944            .get(..n)
945            .ok_or(Error::new(crate::ErrorCode::BufferTooSmall))?;
946        let queued = self.outbox.push(peer, bytes);
947        self.resend.record(exchange, counter, peer, bytes);
948        if !queued {
949            self.notify(Notice::OutboxFull);
950        }
951        Ok(())
952    }
953
954    fn acknowledge(&mut self, exchange: ExchangeKey, now: Instant) {
955        let Ok(len) = self.stack.acknowledge(exchange, now, &mut self.buf.wire) else {
956            return;
957        };
958        if len == 0 {
959            return;
960        }
961        let (Some(peer), Some(bytes)) = (self.stack.peer(exchange), self.buf.wire.get(..len))
962        else {
963            return;
964        };
965        if !self.outbox.push(peer, bytes) {
966            self.notify(Notice::OutboxFull);
967        }
968    }
969
970    // --- Exchange and session lifetime -------------------------------------------------------
971
972    /// Closes `exchange` if nothing is part-way through on it.
973    ///
974    /// §4.10.5.3 leaves reclaiming a finished exchange to "the application layer", and a
975    /// fixed-capacity table makes that not optional: a node that never says so fills its
976    /// exchange table and then drops every datagram — including the acknowledgements that would
977    /// have freed it. A chunked read and a priming report are the two series that keep an
978    /// exchange alive past one message.
979    fn close_if_idle(&mut self, exchange: ExchangeKey) {
980        if !self.im.interactions.idle(exchange) {
981            return;
982        }
983        if self.im.reporting.iter().any(|(_, on)| *on == exchange) {
984            return;
985        }
986        // Our own last message is still in flight: closing would drop its retransmission. The
987        // acknowledgement that frees it closes the exchange; abandonment and §4.10.5.3's idle
988        // reclamation are the backstops.
989        if self.stack.is_awaiting_ack(exchange) {
990            return;
991        }
992        self.im.interactions.forget(exchange);
993        self.resend.forget(exchange);
994        self.stack.close(exchange);
995    }
996
997    /// Everything above the messaging layer that was keyed on a session that has gone.
998    ///
999    /// §8.5: a subscription reports *on a session*, and one whose session has gone has nowhere to
1000    /// report — it would hold its slot until its maximum interval ran out. §5.5: the channel is
1001    /// released by the PASE session on it going away.
1002    fn session_gone(&mut self, session: SessionId) {
1003        let dropped = self.im.subscriptions.remove_for_session(Some(session));
1004        self.im.reporting.retain(|(_, on)| on.session != session);
1005        self.im.interactions.forget_session(session);
1006        self.resend.forget_session(session);
1007        self.channel.closed(session);
1008        if !self.channel.is_established() {
1009            self.pase = PaseProgress::default();
1010        }
1011        self.notify(Notice::SessionClosed {
1012            session,
1013            subscriptions: dropped,
1014        });
1015    }
1016
1017    /// Closes a session this node decided to close, and cascades.
1018    fn close_session(&mut self, session: SessionId) {
1019        if self.stack.close_session(session) {
1020            self.session_gone(session);
1021        }
1022    }
1023
1024    /// §4.11.1.1 step 2a: the evicted peer is owed a `CloseSession`, whether or not this node had
1025    /// anything else to say — without it the peer finds out at its next message, as a timeout.
1026    fn evicted(&mut self, evicted: Evicted) {
1027        if let (Some(peer), Some(bytes)) = (evicted.peer, self.buf.evict.get(..evicted.len))
1028            && evicted.len > 0
1029            && !self.outbox.push(peer, bytes)
1030        {
1031            self.notify(Notice::OutboxFull);
1032        }
1033        self.notify(Notice::Evicted {
1034            session: evicted.session,
1035        });
1036        self.session_gone(evicted.session);
1037    }
1038
1039    // --- §5.5's channel against the commissioning window ------------------------------------
1040
1041    /// §5.5's two ways back into commissioning mode.
1042    ///
1043    /// A window *opening* re-admits PASE: without it a node commissioned once can never be
1044    /// commissioned again — `OpenCommissioningWindow` succeeds, the node advertises, and every
1045    /// `PBKDFParamRequest` comes back `Busy`. Not while an established PASE session holds the
1046    /// channel, though: that is a commissioning in progress.
1047    ///
1048    /// An established channel is *released* to an open window only when the commissioning it
1049    /// was for is over and nothing else is: no fail-safe armed, and either one was armed and has
1050    /// since resolved (a commit or rollback, which also closes the session), or none ever was and
1051    /// the session has sat for [`PASE_ABANDON_GRACE`]. Releasing on "window open and fail-safe
1052    /// disarmed" alone would release the channel the instant PASE completes, before its
1053    /// commissioner has sent `ArmFailSafe` — admitting a second commissioner into the first one's
1054    /// commissioning, which is the takeover §5.5 rule 1 exists to prevent.
1055    fn watch_window<K, G, H, Ac, Gk, Ev, V, const F: usize>(
1056        &mut self,
1057        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
1058        now: Instant,
1059    ) where
1060        K: KeyStore,
1061        G: Rng,
1062        H: ClusterHandler,
1063        Ac: AccessList,
1064        Gk: GroupKeyStore,
1065        Ev: EventLog,
1066        V: ChangeLog,
1067    {
1068        let open = device.commissioning.window.borrow().open(now).is_some();
1069        // Not while a PASE session holds the channel: reopening would reset §5.5 rule 1 under a
1070        // commissioning in progress and admit a second commissioner into it. A held channel is
1071        // released by the rule below instead, once that commissioning is over.
1072        if open && !self.window_was_open && !self.channel.is_established() {
1073            self.channel.reopen();
1074            self.pase = PaseProgress::default();
1075            self.notify(Notice::WindowOpened);
1076        }
1077        self.window_was_open = open;
1078        if !self.channel.is_established() {
1079            return;
1080        }
1081        let armed = device.commissioning.fail_safe.borrow().armed(now).is_some();
1082        if armed {
1083            self.pase.armed_seen = true;
1084            return;
1085        }
1086        let abandoned = self
1087            .pase
1088            .established_at
1089            .is_some_and(|at| now.saturating_duration_since(at) >= PASE_ABANDON_GRACE);
1090        if open && (self.pase.armed_seen || abandoned) {
1091            self.channel.release();
1092            self.pase = PaseProgress::default();
1093            self.notify(Notice::ChannelReleased);
1094        }
1095    }
1096
1097    /// §8.5.3: a change to a path a subscription covers is what makes a report due, and §7.10.3
1098    /// already records every such change — so the version table is where changes are read from.
1099    fn drain_changes<K, G, H, Ac, Gk, Ev, V, const F: usize>(
1100        &mut self,
1101        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
1102    ) where
1103        K: KeyStore,
1104        G: Rng,
1105        H: ClusterHandler,
1106        Ac: AccessList,
1107        Gk: GroupKeyStore,
1108        Ev: EventLog,
1109        V: ChangeLog,
1110    {
1111        let subscriptions = &mut self.im.subscriptions;
1112        device.versions.drain(&mut |endpoint, cluster| {
1113            subscriptions.note_cluster_change(endpoint, cluster);
1114        });
1115    }
1116}
1117
1118/// A fresh 32-bit draw for MRP's jitter; a failed rng costs jitter, never a message.
1119fn random<C, K, G, H, Ac, Gk, Ev, V, const F: usize>(
1120    device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
1121) -> u32
1122where
1123    C: Config,
1124    K: KeyStore,
1125    G: Rng,
1126    H: ClusterHandler,
1127    Ac: AccessList,
1128    Gk: GroupKeyStore,
1129    Ev: EventLog,
1130    V: ChangeLog,
1131{
1132    device.credentials.rng.borrow().next_u32().unwrap_or(0)
1133}