matter_kit/clusters/network_commissioning.rs
1//! Network Commissioning cluster `0x0031` (Core §11.9) — putting a device on a network.
2//!
3//! > The main goal of Network Commissioning Cluster is to associate a Node with or manage a
4//! > Node's one or more network interfaces.
5//!
6//! One instance per interface: "An instance of the Network Commissioning Cluster only applies
7//! to a single network interface instance present." A device with Wi-Fi and Ethernet has two,
8//! on different endpoints, each with its own `Networks` list and its own feature bit.
9//!
10//! # Three clusters wearing one id
11//!
12//! §11.9.4's `WI`, `TH` and `ET` have conformance `O.a` — exactly one. What that bit selects
13//! is not a detail: an Ethernet instance has **no commands at all** and its `Networks` list is
14//! "automatically populated by the cluster server", while a Wi-Fi instance has seven commands
15//! and a radio behind them. [`ethernet`] and [`wifi`]/[`thread`] therefore build different
16//! descriptors, and [`NetworkCommissioning::new`] refuses a driver whose kind disagrees with
17//! the descriptor it was given.
18//!
19//! # What the credentials never touch
20//!
21//! §11.9.7.3: "The Credentials associated with the network are not readable after execution of
22//! this command, as they do not appear in the Networks attribute, for security reasons." So
23//! `AddOrUpdateWiFiNetwork` hands them straight to the [`NetworkDriver`] and this module never
24//! stores them. A `Networks` entry is an id and a boolean, and that is all it can ever be.
25//!
26//! # The list is ordered, and the order is the point
27//!
28//! §11.9.6.2: "The order of configurations in the list reflects precedence … the list SHALL be
29//! stable over time." `ReorderNetwork` is the only command that permutes it, and §11.9.7.10
30//! publishes two worked examples of what it must produce — both are tests.
31//!
32//! # Everything here is inside the fail-safe
33//!
34//! Every command requires an armed fail-safe, and §11.10.7.2.2 step 5 is "Reset the
35//! configuration of all Network Commissioning Networks attribute to their state prior to the
36//! Fail-Safe being armed". [`NetworkStore::snapshot`] and [`NetworkStore::restore`] are that
37//! step — without them a commissioner that half-configured a network and walked away would
38//! leave the device pointed at an access point it cannot reach.
39//!
40//! # Revision 2
41//!
42//! | Revision | Change |
43//! |---|---|
44//! | 1 | Initial revision |
45//! | 2 | Wi-Fi and Thread capability attributes; directed Wi-Fi scanning |
46
47use core::cell::{Cell, RefCell};
48
49use heapless::Vec;
50
51use crate::dm::access::{Access, Privilege};
52use crate::dm::meta::{
53 AttributeDescriptor, AttributeQualities, ClusterDescriptor, CommandDescriptor,
54};
55use crate::dm::{Resolved, ResolvedCommand};
56use crate::im::{
57 AttributeId, ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb,
58 WriteOp,
59};
60use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, set_once};
61
62use super::Cluster;
63
64/// `0x0031` (§11.9.3).
65pub const ID: ClusterId = 0x0031;
66
67/// The highest revision in §11.9.1's table.
68pub const REVISION: u16 = 2;
69
70/// `WI` (§11.9.4, bit 0) — Wi-Fi related features.
71pub const FEATURE_WIFI: u32 = 1 << 0;
72/// `TH` (§11.9.4, bit 1) — Thread related features.
73pub const FEATURE_THREAD: u32 = 1 << 1;
74/// `ET` (§11.9.4, bit 2) — Ethernet related features.
75pub const FEATURE_ETHERNET: u32 = 1 << 2;
76
77/// `MaxNetworks` (§11.9.6.1) — `uint8` min 1, `F`, `RA`, mandatory.
78pub const MAX_NETWORKS: AttributeId = 0x0000;
79/// `Networks` (§11.9.6.2) — `list[NetworkInfoStruct]`, `RA`, mandatory.
80pub const NETWORKS: AttributeId = 0x0001;
81/// `ScanMaxTimeSeconds` (§11.9.6.3) — `uint8`, `F`, `RV`, `WI | TH`.
82pub const SCAN_MAX_TIME_SECONDS: AttributeId = 0x0002;
83/// `ConnectMaxTimeSeconds` (§11.9.6.4) — `uint8`, `F`, `RV`, `WI | TH`.
84pub const CONNECT_MAX_TIME_SECONDS: AttributeId = 0x0003;
85/// `InterfaceEnabled` (§11.9.6.5) — `bool`, `N`, fallback true, `RW VA`, mandatory.
86pub const INTERFACE_ENABLED: AttributeId = 0x0004;
87/// `LastNetworkingStatus` (§11.9.6.6) — nullable, `RA`, mandatory.
88pub const LAST_NETWORKING_STATUS: AttributeId = 0x0005;
89/// `LastNetworkID` (§11.9.6.7) — `octstr` 1 to 32, nullable, `RA`, mandatory.
90pub const LAST_NETWORK_ID: AttributeId = 0x0006;
91/// `LastConnectErrorValue` (§11.9.6.8) — `int32`, nullable, `RA`, mandatory.
92pub const LAST_CONNECT_ERROR_VALUE: AttributeId = 0x0007;
93/// `SupportedWiFiBands` (§11.9.6.9) — `list[WiFiBandEnum]` min 1, `F`, `RV`, `WI`.
94pub const SUPPORTED_WIFI_BANDS: AttributeId = 0x0008;
95/// `SupportedThreadFeatures` (§11.9.6.10) — `ThreadCapabilitiesBitmap`, `F`, `RV`, `TH`.
96pub const SUPPORTED_THREAD_FEATURES: AttributeId = 0x0009;
97/// `ThreadVersion` (§11.9.6.11) — `uint16`, `F`, `RV`, `TH`.
98pub const THREAD_VERSION: AttributeId = 0x000A;
99
100/// `ScanNetworks` (§11.9.7.1) — access `A`, `WI | TH`.
101pub const SCAN_NETWORKS: CommandId = 0x00;
102/// `ScanNetworksResponse` (§11.9.7.2).
103pub const SCAN_NETWORKS_RESPONSE: CommandId = 0x01;
104/// `AddOrUpdateWiFiNetwork` (§11.9.7.3) — access `A`, `WI`.
105pub const ADD_OR_UPDATE_WIFI_NETWORK: CommandId = 0x02;
106/// `AddOrUpdateThreadNetwork` (§11.9.7.4) — access `A`, `TH`.
107pub const ADD_OR_UPDATE_THREAD_NETWORK: CommandId = 0x03;
108/// `RemoveNetwork` (§11.9.7.6) — access `A`, `WI | TH`.
109pub const REMOVE_NETWORK: CommandId = 0x04;
110/// `NetworkConfigResponse` (§11.9.7.7).
111pub const NETWORK_CONFIG_RESPONSE: CommandId = 0x05;
112/// `ConnectNetwork` (§11.9.7.8) — access `A`, `WI | TH`.
113pub const CONNECT_NETWORK: CommandId = 0x06;
114/// `ConnectNetworkResponse` (§11.9.7.9).
115pub const CONNECT_NETWORK_RESPONSE: CommandId = 0x07;
116/// `ReorderNetwork` (§11.9.7.10) — access `A`, `WI | TH`.
117pub const REORDER_NETWORK: CommandId = 0x08;
118
119/// The longest `NetworkID` — §11.9.5.5's `1 to 32`.
120///
121/// "Every network is uniquely identified (for purposes of commissioning) by a NetworkID
122/// mapping to … SSID for Wi-Fi, Extended PAN ID for Thread, Network interface instance name
123/// at operating system … for Ethernet." So it is an *octet string*, not a name: §11.9.5.5
124/// warns that an SSID's "text encoding … is not specified" and that implementations "must be
125/// careful to support reporting byte strings without requiring a particular encoding".
126pub const NETWORK_ID_MAX: usize = 32;
127
128/// The longest Wi-Fi `Credentials` — §11.9.7.3's `max 64`, a WPA raw hex PSK.
129pub const CREDENTIALS_MAX: usize = 64;
130
131/// The longest Thread `OperationalDataset` — §11.9.7.4's `max 254`.
132pub const OPERATIONAL_DATASET_MAX: usize = 254;
133
134/// `NetworkCommissioningStatusEnum` (§11.9.5.4).
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136#[repr(u8)]
137#[non_exhaustive]
138pub enum NetworkStatus {
139 /// `0` — OK, no error.
140 Success = 0,
141 /// `1` — value outside range.
142 OutOfRange = 1,
143 /// `2` — "A collection would exceed its size limit".
144 BoundsExceeded = 2,
145 /// `3` — "The NetworkID is not among the collection of added networks".
146 NetworkIdNotFound = 3,
147 /// `4` — "The NetworkID is already among the collection of added networks".
148 DuplicateNetworkId = 4,
149 /// `5` — "Cannot find AP: SSID Not found".
150 NetworkNotFound = 5,
151 /// `6` — "Cannot find AP: Mismatch on band/channels/regulatory domain / 2.4GHz vs 5GHz".
152 RegulatoryError = 6,
153 /// `7` — "Cannot associate due to authentication failure".
154 AuthFailure = 7,
155 /// `8` — "Cannot associate due to unsupported security mode".
156 UnsupportedSecurity = 8,
157 /// `9` — "Other association failure".
158 OtherConnectionFailure = 9,
159 /// `10` — "Failure to generate an IPv6 address".
160 Ipv6Failed = 10,
161 /// `11` — "Failure to bind Wi-Fi <-> IP interfaces".
162 IpBindFailed = 11,
163 /// `12` — unknown error.
164 UnknownError = 12,
165}
166
167impl NetworkStatus {
168 /// The value the enum encodes as.
169 #[must_use]
170 pub const fn value(self) -> u8 {
171 self as u8
172 }
173
174 /// Whether this is [`NetworkStatus::Success`].
175 #[must_use]
176 pub const fn is_success(self) -> bool {
177 matches!(self, Self::Success)
178 }
179}
180
181/// Which technology one cluster instance manages.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
183pub enum NetworkKind {
184 /// `WI` — IEEE 802.11.
185 WiFi,
186 /// `TH` — IEEE 802.15.4 / Thread.
187 Thread,
188 /// `ET` — IEEE 802.3. No commands at all.
189 Ethernet,
190}
191
192impl NetworkKind {
193 /// The feature bit this kind sets in the `FeatureMap`.
194 #[must_use]
195 pub const fn feature(self) -> u32 {
196 match self {
197 Self::WiFi => FEATURE_WIFI,
198 Self::Thread => FEATURE_THREAD,
199 Self::Ethernet => FEATURE_ETHERNET,
200 }
201 }
202}
203
204/// `WiFiBandEnum` (§11.9.5.3).
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206#[repr(u8)]
207#[non_exhaustive]
208pub enum WiFiBand {
209 /// `0` — 2.4GHz, 802.11b/g/n/ax.
210 Band2G4 = 0,
211 /// `1` — 3.65GHz, 802.11y.
212 Band3G65 = 1,
213 /// `2` — 5GHz, 802.11a/n/ac/ax.
214 Band5G = 2,
215 /// `3` — 6GHz, 802.11ax / Wi-Fi 6E.
216 Band6G = 3,
217 /// `4` — 60GHz, 802.11ad/ay.
218 Band60G = 4,
219 /// `5` — sub-1GHz, 802.11ah.
220 Band1G = 5,
221}
222
223impl WiFiBand {
224 /// The value the enum encodes as.
225 #[must_use]
226 pub const fn value(self) -> u8 {
227 self as u8
228 }
229}
230
231bitflags::bitflags! {
232 /// `WiFiSecurityBitmap` (§11.9.5.1) — "the supported Wi-Fi security types present in the
233 /// Security field of the WiFiInterfaceScanResultStruct".
234 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
235 pub struct WiFiSecurity: u8 {
236 /// Bit 0 — unencrypted.
237 const UNENCRYPTED = 1 << 0;
238 /// Bit 1 — WEP.
239 const WEP = 1 << 1;
240 /// Bit 2 — WPA-Personal.
241 const WPA_PERSONAL = 1 << 2;
242 /// Bit 3 — WPA2-Personal.
243 const WPA2_PERSONAL = 1 << 3;
244 /// Bit 4 — WPA3-Personal.
245 const WPA3_PERSONAL = 1 << 4;
246 }
247
248 /// `ThreadCapabilitiesBitmap` (§11.9.5.2).
249 ///
250 /// "The valid combinations of capabilities are restricted and dependent on Thread
251 /// version", so nothing here validates a combination — the Thread stack is the authority.
252 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
253 pub struct ThreadCapabilities: u16 {
254 /// Bit 0 — Thread Border Router functionality is present.
255 const IS_BORDER_ROUTER_CAPABLE = 1 << 0;
256 /// Bit 1 — router or REED mode is supported.
257 const IS_ROUTER_CAPABLE = 1 << 1;
258 /// Bit 2 — sleepy end-device mode is supported.
259 const IS_SLEEPY_END_DEVICE_CAPABLE = 1 << 2;
260 /// Bit 3 — a full Thread device, as opposed to a Minimal Thread Device.
261 const IS_FULL_THREAD_DEVICE = 1 << 3;
262 /// Bit 4 — synchronized sleepy end-device mode is supported.
263 const IS_SYNCHRONIZED_SLEEPY_END_DEVICE_CAPABLE = 1 << 4;
264 }
265}
266
267// --- The network store -------------------------------------------------------------------------
268
269/// One entry of the `Networks` attribute (§11.9.5.5's `NetworkInfoStruct`).
270///
271/// Two fields, and deliberately no third: §11.9.7.3 keeps credentials out of this list "for
272/// security reasons", so there is nowhere for them to leak to.
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct NetworkInfo {
275 /// `NetworkID [0]` — 1 to 32 octets. An SSID, an Extended PAN ID, or an interface name.
276 pub id: Vec<u8, NETWORK_ID_MAX>,
277 /// `Connected [1]` — "currently linked to the network technology (e.g. Associated for a
278 /// Wi-Fi network, media connected for an Ethernet network)".
279 pub connected: bool,
280}
281
282impl NetworkInfo {
283 /// An entry for `id`, not connected.
284 ///
285 /// Returns [`NetworkStatus::OutOfRange`] for an id outside §11.9.5.5's `1 to 32` — which
286 /// is what §11.9.7.7 calls "Network identifier was invalid (e.g. empty, too long, etc)".
287 pub fn new(id: &[u8]) -> Result<Self, NetworkStatus> {
288 Ok(Self {
289 id: copy_id(id)?,
290 connected: false,
291 })
292 }
293}
294
295fn copy_id(id: &[u8]) -> Result<Vec<u8, NETWORK_ID_MAX>, NetworkStatus> {
296 if id.is_empty() || id.len() > NETWORK_ID_MAX {
297 return Err(NetworkStatus::OutOfRange);
298 }
299 Vec::from_slice(id).map_err(|_| NetworkStatus::OutOfRange)
300}
301
302/// The `Networks` attribute: an ordered, fixed-capacity list where **position is precedence**.
303///
304/// §11.9.6.2: "The order of configurations in the list reflects precedence. That is, any time
305/// the Node attempts to connect to the network it SHALL attempt to do so using the
306/// configurations in Networks Attribute in the order as they appear in the list. The order of
307/// list items SHALL only be modified by the AddOrUpdateThreadNetwork, AddOrUpdateWiFiNetwork
308/// and ReorderNetwork commands."
309///
310/// So this is a `Vec`, not a map: every operation states exactly what it does to the order,
311/// and an implementation that sorted or re-hashed would silently change which access point a
312/// device prefers.
313///
314/// `N` is `MaxNetworks` (§11.9.6.1), "the maximum number of network configuration entries that
315/// can be added, based on available device resources".
316#[derive(Debug, Clone)]
317pub struct NetworkStore<const N: usize> {
318 networks: Vec<NetworkInfo, N>,
319 /// The list as it was when the fail-safe was armed — §11.10.7.2.2 step 5's "state prior to
320 /// the Fail-Safe being armed".
321 saved: Option<Vec<NetworkInfo, N>>,
322}
323
324impl<const N: usize> Default for NetworkStore<N> {
325 fn default() -> Self {
326 Self::new()
327 }
328}
329
330impl<const N: usize> NetworkStore<N> {
331 /// An empty store — what a factory-fresh Wi-Fi or Thread interface has.
332 #[must_use]
333 pub const fn new() -> Self {
334 Self {
335 networks: Vec::new(),
336 saved: None,
337 }
338 }
339
340 /// `MaxNetworks` (§11.9.6.1).
341 #[must_use]
342 pub const fn capacity(&self) -> usize {
343 N
344 }
345
346 /// The entries, in precedence order.
347 #[must_use]
348 pub fn entries(&self) -> &[NetworkInfo] {
349 &self.networks
350 }
351
352 /// The position of `id`, if it is configured.
353 #[must_use]
354 pub fn position(&self, id: &[u8]) -> Option<usize> {
355 self.networks.iter().position(|n| n.id.as_slice() == id)
356 }
357
358 /// `AddOrUpdateWiFiNetwork` / `AddOrUpdateThreadNetwork`, as §11.9.7.5 defines them.
359 ///
360 /// > If validation of all parameters has succeeded, this command SHALL append the
361 /// > configuration at the end of the existing list in the Networks attribute, making this
362 /// > new network the one with least priority.
363 ///
364 /// and, for an update:
365 ///
366 /// > this command SHALL update the existing entry indexed by NetworkID in the Networks
367 /// > attribute, **keeping existing position within the list**.
368 ///
369 /// Returns the 0-based index for the `NetworkConfigResponse`.
370 pub fn add_or_update(&mut self, id: &[u8]) -> Result<u8, NetworkStatus> {
371 let id = copy_id(id)?;
372 if let Some(index) = self.position(&id) {
373 // An update keeps its place: re-sorting here would silently change which network
374 // the device prefers, which is the one thing §11.9.6.2 asks not to happen.
375 return index_of(index);
376 }
377 // "If the Networks attribute is already full, the command SHALL immediately respond
378 // with NetworkConfigResponse having NetworkingStatus status field set to
379 // BoundsExceeded."
380 if self.networks.len() >= N {
381 return Err(NetworkStatus::BoundsExceeded);
382 }
383 self.networks
384 .push(NetworkInfo {
385 id,
386 connected: false,
387 })
388 .map_err(|_| NetworkStatus::BoundsExceeded)?;
389 index_of(self.networks.len().saturating_sub(1))
390 }
391
392 /// `RemoveNetwork` (§11.9.7.6).
393 ///
394 /// > The relative order of the entries in the Networks attribute SHALL remain unchanged,
395 /// > except for the removal of the requested network configuration.
396 ///
397 /// Returns the index the entry *had*, which is what the response reports.
398 pub fn remove(&mut self, id: &[u8]) -> Result<u8, NetworkStatus> {
399 let index = self.position(id).ok_or(NetworkStatus::NetworkIdNotFound)?;
400 // `remove` shifts the tail down, preserving relative order — `swap_remove` would not.
401 self.networks.remove(index);
402 index_of(index)
403 }
404
405 /// `ReorderNetwork` (§11.9.7.10).
406 ///
407 /// > The entry selected SHALL be inserted at the new position in the list. All other
408 /// > entries, if any exist, SHALL be moved to allow the insertion, in a way that they all
409 /// > retain their existing relative order between each other, with the exception of the
410 /// > newly re-ordered entry.
411 ///
412 /// A remove-then-insert, which is exactly that sentence: everything between the old and
413 /// new position shifts by one and nothing else changes. Re-ordering to the position an
414 /// entry already holds "SHALL be considered as a success and yield no visible changes".
415 pub fn reorder(&mut self, id: &[u8], to: u8) -> Result<u8, NetworkStatus> {
416 let from = self.position(id).ok_or(NetworkStatus::NetworkIdNotFound)?;
417 let to_index = usize::from(to);
418 // "If the NetworkIndex field has a value larger or equal to the current number of
419 // entries in the Networks attribute … OutOfRange."
420 if to_index >= self.networks.len() {
421 return Err(NetworkStatus::OutOfRange);
422 }
423 if from == to_index {
424 return Ok(to);
425 }
426 let entry = self.networks.remove(from);
427 self.networks
428 .insert(to_index, entry)
429 .map_err(|_| NetworkStatus::UnknownError)?;
430 Ok(to)
431 }
432
433 /// Marks `id` connected and every other entry disconnected (§11.9.7.8).
434 ///
435 /// > On successful connection, the entry associated with the given Network configuration
436 /// > in the Networks attribute SHALL indicate its Connected field set to true, and **all
437 /// > other entries, if any exist, SHALL indicate their Connected field set to false**.
438 pub fn set_connected(&mut self, id: &[u8]) -> Result<(), NetworkStatus> {
439 if self.position(id).is_none() {
440 return Err(NetworkStatus::NetworkIdNotFound);
441 }
442 for entry in &mut self.networks {
443 entry.connected = entry.id.as_slice() == id;
444 }
445 Ok(())
446 }
447
448 /// Marks every entry disconnected — what a failed `ConnectNetwork` leaves behind.
449 pub fn set_all_disconnected(&mut self) {
450 for entry in &mut self.networks {
451 entry.connected = false;
452 }
453 }
454
455 /// Records the list as it stands, for §11.10.7.2.2 step 5.
456 ///
457 /// Called when the fail-safe is armed. Idempotent within one period: a second `ArmFailSafe`
458 /// re-arms the *same* context, so the state to revert to is still the one from before the
459 /// first.
460 pub fn snapshot(&mut self) {
461 if self.saved.is_none() {
462 self.saved = Some(self.networks.clone());
463 }
464 }
465
466 /// Reverts to the snapshot — §11.10.7.2.2 step 5, "Reset the configuration of all Network
467 /// Commissioning Networks attribute to their state prior to the Fail-Safe being armed".
468 ///
469 /// Without this, a commissioner that half-configured a network and walked away leaves the
470 /// device pointed at an access point it cannot reach, with no way back.
471 pub fn restore(&mut self) {
472 if let Some(saved) = self.saved.take() {
473 self.networks = saved;
474 }
475 }
476
477 /// Drops the snapshot, keeping the current list — what `CommissioningComplete` does.
478 pub fn commit(&mut self) {
479 self.saved = None;
480 }
481
482 /// Seeds the list with an entry that cannot be added or removed.
483 ///
484 /// §11.9.6.2: "Ethernet networks SHALL be automatically populated by the cluster server.
485 /// Ethernet Network Commissioning Cluster instances SHALL always have exactly one
486 /// NetworkInfoStruct instance in their Networks attribute. There SHALL be no way to add,
487 /// update or remove Ethernet network configurations to those Cluster instances." The
488 /// id is "Network interface instance name at operating system (or equivalent unique
489 /// name)".
490 pub fn seed(&mut self, id: &[u8], connected: bool) -> Result<(), NetworkStatus> {
491 let id = copy_id(id)?;
492 self.networks.clear();
493 self.networks
494 .push(NetworkInfo { id, connected })
495 .map_err(|_| NetworkStatus::BoundsExceeded)
496 }
497}
498
499fn index_of(index: usize) -> Result<u8, NetworkStatus> {
500 u8::try_from(index).map_err(|_| NetworkStatus::OutOfRange)
501}
502
503/// The Extended PAN ID from a Thread Active Operational Dataset.
504///
505/// §11.9.7.4: "The XPAN ID in the OperationalDataset serves as the NetworkID for the network
506/// configuration to be added or updated", and §11.9.5.5: "XPAN ID is a big-endian 64-bit
507/// unsigned number, represented on the first 8 octets of the octet string."
508///
509/// The dataset is Thread's own TLV encoding — type, length, value, with a length of `0xFF`
510/// introducing a 16-bit extended length. Type 2 is the Extended PAN ID and is always 8 octets.
511/// Everything else is skipped without interpretation: the client "SHALL pass the
512/// OperationalDataset as an opaque octet string", and this reads exactly the one field Matter
513/// needs from it.
514///
515/// Returns `None` for a dataset that is malformed, truncated, or carries no Extended PAN ID —
516/// all of which §11.9.7.5 makes "a value different than Success and consistent with the
517/// error".
518#[must_use]
519pub fn thread_extended_pan_id(dataset: &[u8]) -> Option<[u8; 8]> {
520 /// Thread's `Extended PAN ID` TLV type.
521 const EXTENDED_PAN_ID: u8 = 2;
522 /// A length of `0xFF` means the real length follows as a big-endian `u16`.
523 const EXTENDED_LENGTH: u8 = 0xFF;
524
525 let mut at = 0usize;
526 loop {
527 let kind = *dataset.get(at)?;
528 let short = *dataset.get(at.checked_add(1)?)?;
529 let (header, len) = if short == EXTENDED_LENGTH {
530 let hi = u16::from(*dataset.get(at.checked_add(2)?)?);
531 let lo = u16::from(*dataset.get(at.checked_add(3)?)?);
532 (4usize, usize::from((hi << 8) | lo))
533 } else {
534 (2usize, usize::from(short))
535 };
536 let start = at.checked_add(header)?;
537 let end = start.checked_add(len)?;
538 let value = dataset.get(start..end)?;
539 if kind == EXTENDED_PAN_ID {
540 let bytes: [u8; 8] = value.try_into().ok()?;
541 return Some(bytes);
542 }
543 at = end;
544 if at >= dataset.len() {
545 return None;
546 }
547 }
548}
549
550// --- The driver --------------------------------------------------------------------------------
551
552/// One Wi-Fi scan result (§11.9.5.6's `WiFiInterfaceScanResultStruct`).
553#[derive(Debug, Clone, Copy, PartialEq, Eq)]
554pub struct WiFiScanResult<'a> {
555 /// `Security [0]`.
556 pub security: WiFiSecurity,
557 /// `SSID [1]` — max 32 octets, of unspecified encoding.
558 pub ssid: &'a [u8],
559 /// `BSSID [2]` — exactly 6 octets.
560 pub bssid: [u8; 6],
561 /// `Channel [3]`.
562 pub channel: u16,
563 /// `WiFiBand [4]`, optional — "MAY be used to differentiate overlapping channel number
564 /// values across different Wi-Fi frequency bands".
565 pub band: Option<WiFiBand>,
566 /// `RSSI [5]`, optional — "the signal strength in dBm of the associated scan result".
567 pub rssi: Option<i8>,
568}
569
570/// One Thread scan result (§11.9.5.7's `ThreadInterfaceScanResultStruct`).
571#[derive(Debug, Clone, Copy, PartialEq, Eq)]
572pub struct ThreadScanResult<'a> {
573 /// `PanId [0]` — max 65534.
574 pub pan_id: u16,
575 /// `ExtendedPanId [1]`.
576 pub extended_pan_id: u64,
577 /// `NetworkName [2]` — 1 to 16 characters.
578 pub network_name: &'a str,
579 /// `Channel [3]`.
580 pub channel: u16,
581 /// `Version [4]`.
582 pub version: u8,
583 /// `ExtendedAddress [5]` — an IEEE 802.15.4 Extended Address.
584 pub extended_address: [u8; 8],
585 /// `RSSI [6]`.
586 pub rssi: i8,
587 /// `LQI [7]`.
588 pub lqi: u8,
589}
590
591/// Where a [`NetworkDriver`] puts what it found.
592///
593/// A typed sink rather than a raw [`TlvWriter`], so the encoding stays in this module and a
594/// driver cannot emit a structure the specification does not define. §11.9.7.2 asks for a
595/// particular order — "Results SHOULD be reported in decreasing RSSI order … to maximize the
596/// likelihood that most likely to be reachable elements are included within the size limits of
597/// the response" — which is the driver's to honour, since only it knows the signal strengths.
598pub struct ScanResults<'w, 'b> {
599 w: &'w mut TlvWriter<'b>,
600 count: usize,
601 full: bool,
602}
603
604/// Enough for one scan result of either kind: a Wi-Fi struct is about 60 octets with a
605/// 32-octet SSID, a Thread one about the same with a 16-character network name.
606const ONE_RESULT_BYTES: usize = 128;
607
608impl ScanResults<'_, '_> {
609 /// Appends a Wi-Fi result.
610 ///
611 /// Returns [`NetworkStatus::BoundsExceeded`] once the response buffer is full, which is
612 /// not a failure: §11.9.7.2 says the list "MAY contain a subset of possibilities, to avoid
613 /// memory exhaustion on the cluster server and avoid crossing the maximum command response
614 /// size supported".
615 pub fn wifi(&mut self, result: &WiFiScanResult<'_>) -> Result<(), NetworkStatus> {
616 self.append(|w| {
617 w.start_structure(Tag::Anonymous)?;
618 w.unsigned(Tag::Context(0), u64::from(result.security.bits()))?;
619 w.octets(Tag::Context(1), result.ssid)?;
620 w.octets(Tag::Context(2), &result.bssid)?;
621 w.unsigned(Tag::Context(3), u64::from(result.channel))?;
622 if let Some(band) = result.band {
623 w.unsigned(Tag::Context(4), u64::from(band.value()))?;
624 }
625 if let Some(rssi) = result.rssi {
626 w.signed(Tag::Context(5), i64::from(rssi))?;
627 }
628 w.end_container()
629 })
630 }
631
632 /// Appends a Thread result.
633 pub fn thread(&mut self, result: &ThreadScanResult<'_>) -> Result<(), NetworkStatus> {
634 self.append(|w| {
635 w.start_structure(Tag::Anonymous)?;
636 w.unsigned(Tag::Context(0), u64::from(result.pan_id))?;
637 w.unsigned(Tag::Context(1), result.extended_pan_id)?;
638 w.utf8(Tag::Context(2), result.network_name)?;
639 w.unsigned(Tag::Context(3), u64::from(result.channel))?;
640 w.unsigned(Tag::Context(4), u64::from(result.version))?;
641 w.octets(Tag::Context(5), &result.extended_address)?;
642 w.signed(Tag::Context(6), i64::from(result.rssi))?;
643 w.unsigned(Tag::Context(7), u64::from(result.lqi))?;
644 w.end_container()
645 })
646 }
647
648 /// Builds one result into its own buffer and splices it whole, or not at all.
649 ///
650 /// Writing straight into the response would leave a half-written structure behind the
651 /// first field that did not fit — and a driver is free to ignore the error and keep
652 /// going, which is exactly when that happens. Once the list is full it *stays* full, so a
653 /// later, smaller result cannot slip in behind a larger one that was dropped and leave the
654 /// array in an order the driver did not choose.
655 fn append(
656 &mut self,
657 build: impl FnOnce(&mut TlvWriter<'_>) -> crate::error::Result<()>,
658 ) -> Result<(), NetworkStatus> {
659 if self.full {
660 return Err(NetworkStatus::BoundsExceeded);
661 }
662 let mut scratch = [0u8; ONE_RESULT_BYTES];
663 let encoded = {
664 let mut one = TlvWriter::new_in(&mut scratch, ContainerKind::Array);
665 build(&mut one).and_then(|()| one.finish())
666 };
667 let Ok(encoded) = encoded else {
668 // One result that does not fit its own buffer is a driver bug, not a full
669 // response — but dropping it is still the safe answer, and the list is allowed to
670 // be a subset.
671 self.full = true;
672 return Err(NetworkStatus::BoundsExceeded);
673 };
674 if self.w.raw_element(encoded).is_err() {
675 self.full = true;
676 return Err(NetworkStatus::BoundsExceeded);
677 }
678 self.count = self.count.saturating_add(1);
679 Ok(())
680 }
681
682 /// How many results have been written.
683 #[must_use]
684 pub const fn len(&self) -> usize {
685 self.count
686 }
687
688 /// Whether nothing was found — which is a legitimate `Success`.
689 #[must_use]
690 pub const fn is_empty(&self) -> bool {
691 self.count == 0
692 }
693
694 /// Whether the response filled up and later results are being dropped.
695 ///
696 /// A driver reporting in decreasing signal order, as §11.9.7.2 asks, can stop here.
697 #[must_use]
698 pub const fn is_full(&self) -> bool {
699 self.full
700 }
701}
702
703/// What a `ConnectNetwork` attempt produced (§11.9.7.9).
704#[derive(Debug, Clone, Copy, PartialEq, Eq)]
705pub struct ConnectOutcome {
706 /// `NetworkingStatus [0]`.
707 pub status: NetworkStatus,
708 /// `ErrorValue [2]` — nullable, and null on success.
709 ///
710 /// For Wi-Fi, §11.9.7.9 is specific: "the ErrorValue field SHALL be set to the Status Code
711 /// value that was present in the last frame related to association where Status Code was
712 /// not equal to zero" — an IEEE 802.11-2020 Table 9-50 code, which a diagnostic tool can
713 /// name. Otherwise it is "an implementation-dependent value".
714 pub error_value: Option<i32>,
715}
716
717impl ConnectOutcome {
718 /// A successful connection: `Success`, and a null `ErrorValue`.
719 ///
720 /// §11.9.7.9: "Set the LastConnectErrorValue attribute value to the ErrorValue matching
721 /// the response, **including setting it to null if the ErrorValue is not applicable**."
722 #[must_use]
723 pub const fn success() -> Self {
724 Self {
725 status: NetworkStatus::Success,
726 error_value: None,
727 }
728 }
729
730 /// A failure with no further detail.
731 #[must_use]
732 pub const fn failed(status: NetworkStatus) -> Self {
733 Self {
734 status,
735 error_value: None,
736 }
737 }
738
739 /// A failure carrying an implementation or 802.11 status code.
740 #[must_use]
741 pub const fn failed_with(status: NetworkStatus, error_value: i32) -> Self {
742 Self {
743 status,
744 error_value: Some(error_value),
745 }
746 }
747}
748
749/// The radio behind a Network Commissioning instance.
750///
751/// Everything this cluster cannot do itself: scanning, associating, and remembering
752/// credentials it is forbidden to store. `&self` throughout, because
753/// [`ClusterHandler`] is — a driver with mutable state uses a [`Cell`] or a
754/// [`RefCell`], the same as the clusters do.
755///
756/// An Ethernet instance needs none of it, which is why [`EthernetDriver`] exists and why its
757/// methods are unreachable: §11.9.7's whole command table is `WI | TH`.
758pub trait NetworkDriver {
759 /// Which technology this interface is.
760 fn kind(&self) -> NetworkKind;
761
762 /// `ScanNetworks` (§11.9.7.1).
763 ///
764 /// `ssid` is a directed scan: "if a network identifier (e.g. Wi-Fi SSID) is provided …
765 /// Directed scanning SHALL restrict the result set to the specified network only." Absent
766 /// or null means "scanning of all BSSID in range", and it "SHALL be ignored for
767 /// ScanNetworks invocations on non-Wi-Fi server instances".
768 fn scan(&self, _ssid: Option<&[u8]>, _results: &mut ScanResults<'_, '_>) -> NetworkStatus {
769 NetworkStatus::UnknownError
770 }
771
772 /// Remembers the credentials for a Wi-Fi network (§11.9.7.3).
773 ///
774 /// The credentials reach the driver and stop there — they are never put in the `Networks`
775 /// attribute, and this crate keeps no copy. §11.9.7.3's valid lengths (0, 5, 8..=63, 64,
776 /// and the hex forms) are "contextually interpreted based on the security type of the
777 /// BSSID where connection will occur", so only the driver can judge them.
778 fn add_or_update_wifi(&self, _ssid: &[u8], _credentials: &[u8]) -> NetworkStatus {
779 NetworkStatus::UnknownError
780 }
781
782 /// Remembers a Thread Operational Dataset (§11.9.7.4).
783 fn add_or_update_thread(&self, _dataset: &[u8]) -> NetworkStatus {
784 NetworkStatus::UnknownError
785 }
786
787 /// Forgets whatever `add_or_update_*` remembered for `id`.
788 fn forget(&self, _id: &[u8]) {}
789
790 /// `ConnectNetwork` (§11.9.7.8) — associate with the network `id` names.
791 fn connect(&self, _id: &[u8]) -> ConnectOutcome {
792 ConnectOutcome::failed(NetworkStatus::UnknownError)
793 }
794
795 /// `InterfaceEnabled` (§11.9.6.5).
796 ///
797 /// "It MAY be possible to disable Ethernet interfaces but it is implementation-defined. If
798 /// not supported, a write to this attribute with a value of false SHALL fail with a status
799 /// of INVALID_ACTION."
800 fn set_interface_enabled(&self, _enabled: bool) -> Result<(), Status> {
801 Err(Status::InvalidAction)
802 }
803}
804
805/// The driver for an Ethernet instance, which needs no radio.
806///
807/// §11.9.6.2 gives an Ethernet instance exactly one `Networks` entry, automatically populated
808/// and not modifiable, and §11.9.7's command table is entirely `WI | TH` — so an Ethernet
809/// instance accepts no commands at all and this driver implements none of them.
810#[derive(Debug, Clone, Copy, Default)]
811pub struct EthernetDriver;
812
813impl NetworkDriver for EthernetDriver {
814 fn kind(&self) -> NetworkKind {
815 NetworkKind::Ethernet
816 }
817
818 fn set_interface_enabled(&self, enabled: bool) -> Result<(), Status> {
819 // "On Ethernet-only Nodes, there SHALL always be at least one of the Network
820 // Commissioning server cluster instances with InterfaceEnabled set to true." Refusing
821 // to disable is the conservative reading, and §11.9.6.5 names the status for it.
822 if enabled {
823 Ok(())
824 } else {
825 Err(Status::InvalidAction)
826 }
827 }
828}
829
830// --- Descriptors -------------------------------------------------------------------------------
831
832const fn fixed(id: AttributeId) -> AttributeDescriptor {
833 AttributeDescriptor::read_only(id).with_qualities(AttributeQualities::FIXED)
834}
835
836/// `RA` — Administer to read. The network list is not something a View subject may enumerate:
837/// it names the access points a home uses.
838const fn administered(id: AttributeId) -> AttributeDescriptor {
839 AttributeDescriptor::read_only(id).with_access(Access::read_only(Privilege::Administer))
840}
841
842/// The attributes every instance has, whatever its feature bit.
843const COMMON: [AttributeDescriptor; 6] = [
844 administered(MAX_NETWORKS).with_qualities(AttributeQualities::FIXED),
845 administered(NETWORKS),
846 // `RW VA`, `N` — an administrator may turn the interface off, and the choice survives a
847 // reboot.
848 AttributeDescriptor::read_write(INTERFACE_ENABLED)
849 .with_access(Access::read_write_with(
850 Privilege::View,
851 Privilege::Administer,
852 ))
853 .with_qualities(AttributeQualities::NON_VOLATILE),
854 administered(LAST_NETWORKING_STATUS).with_qualities(AttributeQualities::NULLABLE),
855 administered(LAST_NETWORK_ID).with_qualities(AttributeQualities::NULLABLE),
856 administered(LAST_CONNECT_ERROR_VALUE).with_qualities(AttributeQualities::NULLABLE),
857];
858
859/// Ethernet: the common six, in id order.
860const ETHERNET_ATTRIBUTES: &[AttributeDescriptor] = &[
861 COMMON[0], COMMON[1], COMMON[2], COMMON[3], COMMON[4], COMMON[5],
862];
863
864/// Wi-Fi: plus the two timing attributes (`WI | TH`) and `SupportedWiFiBands` (`WI`).
865const WIFI_ATTRIBUTES: &[AttributeDescriptor] = &[
866 COMMON[0],
867 COMMON[1],
868 fixed(SCAN_MAX_TIME_SECONDS),
869 fixed(CONNECT_MAX_TIME_SECONDS),
870 COMMON[2],
871 COMMON[3],
872 COMMON[4],
873 COMMON[5],
874 fixed(SUPPORTED_WIFI_BANDS),
875];
876
877/// Thread: plus the two timing attributes and the two capability attributes (`TH`).
878const THREAD_ATTRIBUTES: &[AttributeDescriptor] = &[
879 COMMON[0],
880 COMMON[1],
881 fixed(SCAN_MAX_TIME_SECONDS),
882 fixed(CONNECT_MAX_TIME_SECONDS),
883 COMMON[2],
884 COMMON[3],
885 COMMON[4],
886 COMMON[5],
887 fixed(SUPPORTED_THREAD_FEATURES),
888 fixed(THREAD_VERSION),
889];
890
891const fn invoke_admin(id: CommandId) -> CommandDescriptor {
892 CommandDescriptor::new(id).with_access(Access::invoke(Privilege::Administer))
893}
894
895/// The commands `WI | TH` share.
896const SHARED_COMMANDS: [CommandDescriptor; 4] = [
897 invoke_admin(SCAN_NETWORKS).with_response(SCAN_NETWORKS_RESPONSE),
898 invoke_admin(REMOVE_NETWORK).with_response(NETWORK_CONFIG_RESPONSE),
899 invoke_admin(CONNECT_NETWORK).with_response(CONNECT_NETWORK_RESPONSE),
900 invoke_admin(REORDER_NETWORK).with_response(NETWORK_CONFIG_RESPONSE),
901];
902
903const WIFI_COMMANDS: &[CommandDescriptor] = &[
904 SHARED_COMMANDS[0],
905 invoke_admin(ADD_OR_UPDATE_WIFI_NETWORK).with_response(NETWORK_CONFIG_RESPONSE),
906 SHARED_COMMANDS[1],
907 SHARED_COMMANDS[2],
908 SHARED_COMMANDS[3],
909];
910
911const THREAD_COMMANDS: &[CommandDescriptor] = &[
912 SHARED_COMMANDS[0],
913 invoke_admin(ADD_OR_UPDATE_THREAD_NETWORK).with_response(NETWORK_CONFIG_RESPONSE),
914 SHARED_COMMANDS[1],
915 SHARED_COMMANDS[2],
916 SHARED_COMMANDS[3],
917];
918
919/// The descriptor for an Ethernet instance.
920///
921/// No commands: §11.9.7's whole table is `WI | TH`. An Ethernet interface is configured by
922/// being plugged in, and the cluster exists so a commissioner can *see* that.
923#[must_use]
924pub const fn ethernet() -> ClusterDescriptor<'static> {
925 ClusterDescriptor {
926 id: ID,
927 revision: REVISION,
928 feature_map: FEATURE_ETHERNET,
929 attributes: ETHERNET_ATTRIBUTES,
930 accepted_commands: &[],
931 generated_commands: &[],
932 events: &[],
933 }
934}
935
936/// The descriptor for a Wi-Fi instance.
937#[must_use]
938pub const fn wifi() -> ClusterDescriptor<'static> {
939 ClusterDescriptor {
940 id: ID,
941 revision: REVISION,
942 feature_map: FEATURE_WIFI,
943 attributes: WIFI_ATTRIBUTES,
944 accepted_commands: WIFI_COMMANDS,
945 generated_commands: &[],
946 events: &[],
947 }
948}
949
950/// The descriptor for a Thread instance.
951#[must_use]
952pub const fn thread() -> ClusterDescriptor<'static> {
953 ClusterDescriptor {
954 id: ID,
955 revision: REVISION,
956 feature_map: FEATURE_THREAD,
957 attributes: THREAD_ATTRIBUTES,
958 accepted_commands: THREAD_COMMANDS,
959 generated_commands: &[],
960 events: &[],
961 }
962}
963
964/// The fixed capabilities an instance reports, beyond its network list.
965///
966/// §11.9.6.3 and §11.9.6.4's timings are `WI | TH` and have no fallback, so a device has to
967/// state them: `ScanMaxTimeSeconds` is "the maximum duration taken, in seconds, by the network
968/// interface … to provide scan results", and `ConnectMaxTimeSeconds` the same for a
969/// connection, accounting for "obtaining IP addresses, or the execution of necessary internal
970/// retries". A commissioner sizes its fail-safe from them.
971#[derive(Debug, Clone, Copy)]
972pub struct Capabilities<'a> {
973 /// `ScanMaxTimeSeconds` (§11.9.6.3).
974 pub scan_max_time_seconds: u8,
975 /// `ConnectMaxTimeSeconds` (§11.9.6.4).
976 pub connect_max_time_seconds: u8,
977 /// `SupportedWiFiBands` (§11.9.6.9) — min 1 entry on a Wi-Fi instance.
978 pub wifi_bands: &'a [WiFiBand],
979 /// `SupportedThreadFeatures` (§11.9.6.10).
980 pub thread_features: ThreadCapabilities,
981 /// `ThreadVersion` (§11.9.6.11) — "the value mapping found in the 'Version TLV' section of
982 /// Thread specification. For example, Thread 1.3.0 would have ThreadVersion set to 4."
983 pub thread_version: u16,
984}
985
986impl Default for Capabilities<'_> {
987 fn default() -> Self {
988 Self {
989 // Conservative and common: a scan takes a few seconds, a connection rather longer
990 // once DHCP and retries are counted.
991 scan_max_time_seconds: 10,
992 connect_max_time_seconds: 30,
993 wifi_bands: &[WiFiBand::Band2G4],
994 thread_features: ThreadCapabilities::empty(),
995 thread_version: 4,
996 }
997 }
998}
999
1000// --- The cluster -------------------------------------------------------------------------------
1001
1002/// One Network Commissioning instance: one interface, one `Networks` list, one driver.
1003///
1004/// The fail-safe is shared with General Commissioning and Operational Credentials, because it
1005/// is node state and because §11.10.7.2.2 step 5 reverts *this* list when it expires.
1006pub struct NetworkCommissioning<'a, D: NetworkDriver, const N: usize> {
1007 /// The interface's radio, or [`EthernetDriver`] for a wire.
1008 pub driver: &'a D,
1009 /// The node's fail-safe. Every command here requires it armed.
1010 pub fail_safe: &'a RefCell<crate::commissioning::failsafe::FailSafe>,
1011 /// The fixed capability values this instance reports.
1012 pub capabilities: Capabilities<'a>,
1013 store: RefCell<NetworkStore<N>>,
1014 enabled: Cell<bool>,
1015 last_status: Cell<Option<NetworkStatus>>,
1016 last_network_id: RefCell<Option<Vec<u8, NETWORK_ID_MAX>>>,
1017 last_connect_error: Cell<Option<i32>>,
1018}
1019
1020impl<'a, D: NetworkDriver, const N: usize> NetworkCommissioning<'a, D, N> {
1021 /// An instance over a driver.
1022 ///
1023 /// The three `Last*` attributes start null: §11.9.6.6 says so — "If no such attempt was
1024 /// made, or no network configurations exist in the Networks attribute, then this attribute
1025 /// SHALL be set to null."
1026 #[must_use]
1027 pub fn new(
1028 driver: &'a D,
1029 fail_safe: &'a RefCell<crate::commissioning::failsafe::FailSafe>,
1030 capabilities: Capabilities<'a>,
1031 ) -> Self {
1032 Self {
1033 driver,
1034 fail_safe,
1035 capabilities,
1036 store: RefCell::new(NetworkStore::new()),
1037 // §11.9.6.5: "By default all network interfaces SHOULD be enabled during initial
1038 // commissioning (InterfaceEnabled set to true)."
1039 enabled: Cell::new(true),
1040 last_status: Cell::new(None),
1041 last_network_id: RefCell::new(None),
1042 last_connect_error: Cell::new(None),
1043 }
1044 }
1045
1046 /// The descriptor matching this instance's driver.
1047 #[must_use]
1048 pub fn descriptor(&self) -> ClusterDescriptor<'static> {
1049 match self.driver.kind() {
1050 NetworkKind::WiFi => wifi(),
1051 NetworkKind::Thread => thread(),
1052 NetworkKind::Ethernet => ethernet(),
1053 }
1054 }
1055
1056 /// The `Networks` list.
1057 #[must_use]
1058 pub fn store(&self) -> core::cell::Ref<'_, NetworkStore<N>> {
1059 self.store.borrow()
1060 }
1061
1062 /// The `Networks` list, mutably — for an Ethernet instance's
1063 /// [`seed`](NetworkStore::seed), and for a driver reporting a link change.
1064 #[must_use]
1065 pub fn store_mut(&self) -> core::cell::RefMut<'_, NetworkStore<N>> {
1066 self.store.borrow_mut()
1067 }
1068
1069 /// `InterfaceEnabled` (§11.9.6.5).
1070 #[must_use]
1071 pub fn is_enabled(&self) -> bool {
1072 self.enabled.get()
1073 }
1074
1075 /// Reverts the list — §11.10.7.2.2 step 5. Call this when the fail-safe expires.
1076 pub fn on_fail_safe_expired(&self) {
1077 self.store.borrow_mut().restore();
1078 }
1079
1080 /// Keeps the list — call this on `CommissioningComplete`.
1081 pub fn on_commissioning_complete(&self) {
1082 self.store.borrow_mut().commit();
1083 }
1084
1085 /// §11.9.7.2, §11.9.7.7 and §11.9.7.9 each open with the same instruction: "Before
1086 /// generating a …Response, the server SHALL set the LastNetworkingStatus attribute value
1087 /// to the NetworkingStatus matching the response."
1088 ///
1089 /// So the three `Last*` attributes are written on the way *out*, together, and this is the
1090 /// one place that does it — a command that set only some of them would leave a
1091 /// commissioner reading a status from one attempt beside an id from another, which is
1092 /// precisely what §11.9.6.6 says they exist to prevent.
1093 fn record_outcome(&self, status: NetworkStatus, id: Option<&[u8]>, error: Option<i32>) {
1094 self.last_status.set(Some(status));
1095 if let Some(id) = id {
1096 *self.last_network_id.borrow_mut() = Vec::from_slice(id).ok();
1097 }
1098 self.last_connect_error.set(error);
1099 }
1100
1101 /// The fail-safe must be armed, or every command here is `FAILSAFE_REQUIRED`.
1102 fn require_fail_safe(&self, ctx: &InteractionContext<'_>) -> Result<(), Status> {
1103 if self.fail_safe.borrow().is_armed(ctx.now) {
1104 Ok(())
1105 } else {
1106 Err(Status::FailsafeRequired)
1107 }
1108 }
1109
1110 /// Takes §11.10.7.2.2 step 5's snapshot, and tells the fail-safe there is one to revert.
1111 ///
1112 /// Called before any mutation, and the snapshot is taken *lazily* — on the first change
1113 /// inside a fail-safe period rather than when the period opened. That is the same state,
1114 /// and it means this cluster needs no notification when `ArmFailSafe` runs: the fail-safe's
1115 /// own `changed_networks` flag, which is reset whenever a new context is created, says
1116 /// whether the current period has touched the list yet.
1117 ///
1118 /// Setting `changed_networks` is what makes
1119 /// [`Cleanup::restore_networks`](crate::commissioning::failsafe::Cleanup::restore_networks)
1120 /// fire on expiry. Without it the device would be told nothing needs reverting and would
1121 /// keep a half-configured network list.
1122 fn record_change(&self, ctx: &InteractionContext<'_>) {
1123 let already = self
1124 .fail_safe
1125 .borrow()
1126 .armed(ctx.now)
1127 .is_some_and(|armed| armed.progress.changed_networks);
1128 if !already {
1129 self.store.borrow_mut().snapshot();
1130 }
1131 let _ = self
1132 .fail_safe
1133 .borrow_mut()
1134 .record(ctx.now, |p| p.changed_networks = true);
1135 }
1136
1137 /// Writes the `Breadcrumb` the command carried, if it carried one.
1138 ///
1139 /// §11.9.7.1.2: "The Breadcrumb field, if present, SHALL be used to atomically set the
1140 /// Breadcrumb attribute in the General Commissioning cluster **on success** of the
1141 /// associated command. If the command fails, the Breadcrumb attribute … SHALL be left
1142 /// unchanged."
1143 fn set_breadcrumb(&self, breadcrumb: Option<u64>, status: NetworkStatus) {
1144 if status.is_success()
1145 && let Some(breadcrumb) = breadcrumb
1146 {
1147 self.fail_safe.borrow_mut().set_breadcrumb(breadcrumb);
1148 }
1149 }
1150}
1151
1152// --- The commands ------------------------------------------------------------------------------
1153
1154impl<D: NetworkDriver, const N: usize> NetworkCommissioning<'_, D, N> {
1155 /// `ScanNetworks` (§11.9.7.1) → `ScanNetworksResponse` (§11.9.7.2).
1156 ///
1157 /// The results are built into `scratch` before anything is written to `w`, because the
1158 /// response's `NetworkingStatus` is field 0 and the results are fields 2 and 3 — and the
1159 /// status is not known until the driver has finished. Emitting the fields out of order
1160 /// would be a non-canonical structure (§A.2.4), and guessing the status and rewriting it
1161 /// would mean a half-written response on the failure path.
1162 pub fn scan(
1163 &self,
1164 ssid: Option<&[u8]>,
1165 breadcrumb: Option<u64>,
1166 ctx: &InteractionContext<'_>,
1167 scratch: &mut [u8],
1168 w: &mut TlvWriter<'_>,
1169 tag: Tag,
1170 ) -> Result<(), Status> {
1171 self.require_fail_safe(ctx)?;
1172 // "This field SHALL be ignored for ScanNetworks invocations on non-Wi-Fi server
1173 // instances." Dropping it here rather than in each driver keeps a Thread driver from
1174 // having to know the rule.
1175 let ssid = ssid.filter(|_| self.driver.kind() == NetworkKind::WiFi);
1176 // "OutOfRange: Network identifier was invalid (e.g. empty, too long, etc)."
1177 if let Some(ssid) = ssid
1178 && (ssid.is_empty() || ssid.len() > NETWORK_ID_MAX)
1179 {
1180 self.record_outcome(NetworkStatus::OutOfRange, Some(ssid), None);
1181 return write_scan_response(NetworkStatus::OutOfRange, None, w, tag);
1182 }
1183
1184 // Field 2 for Wi-Fi, field 3 for Thread — an instance has one or the other, never
1185 // both, because §11.9.4's features are `O.a`.
1186 let results_tag = match self.driver.kind() {
1187 NetworkKind::Thread => Tag::Context(3),
1188 _ => Tag::Context(2),
1189 };
1190 let mut results = TlvWriter::new_in(scratch, ContainerKind::Structure);
1191 results
1192 .start_array(results_tag)
1193 .map_err(|_| Status::ResourceExhausted)?;
1194 let status = {
1195 let mut sink = ScanResults {
1196 w: &mut results,
1197 count: 0,
1198 full: false,
1199 };
1200 self.driver.scan(ssid, &mut sink)
1201 };
1202 results
1203 .end_container()
1204 .map_err(|_| Status::ResourceExhausted)?;
1205 let encoded = results.finish().map_err(|_| Status::ResourceExhausted)?;
1206
1207 // §11.9.7.2: "Before generating a ScanNetworksResponse, the server SHALL set the
1208 // LastNetworkingStatus attribute value to the NetworkingStatus matching the response."
1209 self.record_outcome(status, ssid, None);
1210 self.set_breadcrumb(breadcrumb, status);
1211
1212 // "Results are valid only if NetworkingStatus is Success" — so a failed scan reports
1213 // the status and nothing else, rather than an empty list a client might read as "no
1214 // networks in range".
1215 write_scan_response(status, status.is_success().then_some(encoded), w, tag)
1216 }
1217
1218 /// `AddOrUpdateWiFiNetwork` (§11.9.7.3) → `NetworkConfigResponse`.
1219 ///
1220 /// The credentials go to the driver and stop there. §11.9.7.3: "The Credentials associated
1221 /// with the network are not readable after execution of this command, as they do not
1222 /// appear in the Networks attribute, for security reasons."
1223 pub fn add_or_update_wifi(
1224 &self,
1225 ssid: &[u8],
1226 credentials: &[u8],
1227 breadcrumb: Option<u64>,
1228 ctx: &InteractionContext<'_>,
1229 w: &mut TlvWriter<'_>,
1230 tag: Tag,
1231 ) -> Result<(), Status> {
1232 self.require_fail_safe(ctx)?;
1233 if self.driver.kind() != NetworkKind::WiFi {
1234 return Err(Status::UnsupportedCommand);
1235 }
1236 self.record_change(ctx);
1237 let outcome = match self.driver.add_or_update_wifi(ssid, credentials) {
1238 NetworkStatus::Success => self.store.borrow_mut().add_or_update(ssid),
1239 other => Err(other),
1240 };
1241 self.finish_config(outcome, ssid, breadcrumb, w, tag)
1242 }
1243
1244 /// `AddOrUpdateThreadNetwork` (§11.9.7.4) → `NetworkConfigResponse`.
1245 ///
1246 /// "The XPAN ID in the OperationalDataset serves as the NetworkID", so the dataset is
1247 /// parsed for exactly that one field and otherwise passed through opaque.
1248 pub fn add_or_update_thread(
1249 &self,
1250 dataset: &[u8],
1251 breadcrumb: Option<u64>,
1252 ctx: &InteractionContext<'_>,
1253 w: &mut TlvWriter<'_>,
1254 tag: Tag,
1255 ) -> Result<(), Status> {
1256 self.require_fail_safe(ctx)?;
1257 if self.driver.kind() != NetworkKind::Thread {
1258 return Err(Status::UnsupportedCommand);
1259 }
1260 // "If any of the parameters in the OperationalDataset are invalid, the command SHALL
1261 // immediately respond with NetworkConfigResponse having NetworkingStatus status field
1262 // set to a value different than Success and consistent with the error." A dataset with
1263 // no Extended PAN ID has no NetworkID, so there is nothing to key the entry by.
1264 self.record_change(ctx);
1265 let Some(xpan) = thread_extended_pan_id(dataset) else {
1266 self.record_outcome(NetworkStatus::OutOfRange, None, None);
1267 return write_config_response(NetworkStatus::OutOfRange, None, w, tag);
1268 };
1269 let outcome = match self.driver.add_or_update_thread(dataset) {
1270 NetworkStatus::Success => self.store.borrow_mut().add_or_update(&xpan),
1271 other => Err(other),
1272 };
1273 self.finish_config(outcome, &xpan, breadcrumb, w, tag)
1274 }
1275
1276 /// `RemoveNetwork` (§11.9.7.6) → `NetworkConfigResponse`.
1277 pub fn remove_network(
1278 &self,
1279 id: &[u8],
1280 breadcrumb: Option<u64>,
1281 ctx: &InteractionContext<'_>,
1282 w: &mut TlvWriter<'_>,
1283 tag: Tag,
1284 ) -> Result<(), Status> {
1285 self.require_fail_safe(ctx)?;
1286 self.record_change(ctx);
1287 let outcome = self.store.borrow_mut().remove(id);
1288 if outcome.is_ok() {
1289 // The driver is told after the list, so a driver that refuses cannot leave an
1290 // entry the list no longer has.
1291 self.driver.forget(id);
1292 }
1293 self.finish_config(outcome, id, breadcrumb, w, tag)
1294 }
1295
1296 /// `ReorderNetwork` (§11.9.7.10) → `NetworkConfigResponse`.
1297 pub fn reorder_network(
1298 &self,
1299 id: &[u8],
1300 index: u8,
1301 breadcrumb: Option<u64>,
1302 ctx: &InteractionContext<'_>,
1303 w: &mut TlvWriter<'_>,
1304 tag: Tag,
1305 ) -> Result<(), Status> {
1306 self.require_fail_safe(ctx)?;
1307 self.record_change(ctx);
1308 let outcome = self.store.borrow_mut().reorder(id, index);
1309 self.finish_config(outcome, id, breadcrumb, w, tag)
1310 }
1311
1312 /// `ConnectNetwork` (§11.9.7.8) → `ConnectNetworkResponse` (§11.9.7.9).
1313 pub fn connect_network(
1314 &self,
1315 id: &[u8],
1316 breadcrumb: Option<u64>,
1317 ctx: &InteractionContext<'_>,
1318 w: &mut TlvWriter<'_>,
1319 tag: Tag,
1320 ) -> Result<(), Status> {
1321 self.require_fail_safe(ctx)?;
1322 // A connection changes the `Connected` flags, which are part of what step 5 reverts:
1323 // "Even after successfully connecting to a network, the configuration SHALL revert to
1324 // the prior state of configuration if the CommissioningComplete command is not
1325 // successfully invoked before expiry of the Fail-Safe timer" (§11.9.7.8).
1326 self.record_change(ctx);
1327 // "NetworkIdNotFound: The network identifier was not found among the added network
1328 // configurations in Networks attribute."
1329 if self.store.borrow().position(id).is_none() {
1330 self.record_outcome(NetworkStatus::NetworkIdNotFound, Some(id), None);
1331 return write_connect_response(
1332 ConnectOutcome::failed(NetworkStatus::NetworkIdNotFound),
1333 w,
1334 tag,
1335 );
1336 }
1337
1338 let outcome = self.driver.connect(id);
1339 {
1340 let mut store = self.store.borrow_mut();
1341 if outcome.status.is_success() {
1342 let _ = store.set_connected(id);
1343 } else {
1344 // "On failure to connect, the entry associated with the given Network
1345 // configuration in the Networks attribute SHALL indicate its Connected field
1346 // set to false."
1347 store.set_all_disconnected();
1348 }
1349 }
1350 // §11.9.7.9 sets all three `Last*` attributes, including "setting it to null if the
1351 // ErrorValue is not applicable".
1352 self.record_outcome(outcome.status, Some(id), outcome.error_value);
1353 self.set_breadcrumb(breadcrumb, outcome.status);
1354 write_connect_response(outcome, w, tag)
1355 }
1356
1357 fn finish_config(
1358 &self,
1359 outcome: Result<u8, NetworkStatus>,
1360 id: &[u8],
1361 breadcrumb: Option<u64>,
1362 w: &mut TlvWriter<'_>,
1363 tag: Tag,
1364 ) -> Result<(), Status> {
1365 let (status, index) = match outcome {
1366 Ok(index) => (NetworkStatus::Success, Some(index)),
1367 Err(status) => (status, None),
1368 };
1369 // §11.9.7.7: "Before generating a NetworkConfigResponse, the server SHALL set the
1370 // LastNetworkingStatus attribute … and the LastNetworkID attribute value to the
1371 // NetworkID that was used in the command".
1372 self.record_outcome(status, Some(id), None);
1373 self.set_breadcrumb(breadcrumb, status);
1374 write_config_response(status, index, w, tag)
1375 }
1376}
1377
1378/// `ScanNetworksResponse` (§11.9.7.2): `NetworkingStatus [0]`, `DebugText [1]`, and the
1379/// results array already encoded with its own context tag.
1380fn write_scan_response(
1381 status: NetworkStatus,
1382 results: Option<&[u8]>,
1383 w: &mut TlvWriter<'_>,
1384 tag: Tag,
1385) -> Result<(), Status> {
1386 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1387 full(w.start_structure(tag))?;
1388 full(w.unsigned(Tag::Context(0), u64::from(status.value())))?;
1389 // `DebugText` is optional and omitted: a device that filled it would be describing its
1390 // internals to anyone who can invoke the command.
1391 if let Some(results) = results {
1392 full(w.raw_element(results))?;
1393 }
1394 full(w.end_container())
1395}
1396
1397/// `NetworkConfigResponse` (§11.9.7.7): `NetworkingStatus [0]`, `DebugText [1]`,
1398/// `NetworkIndex [2]`.
1399///
1400/// `NetworkIndex`'s conformance is `NetworkingStatus == Success`, so it is present exactly on
1401/// success and absent otherwise — not zero, which would name the first entry.
1402fn write_config_response(
1403 status: NetworkStatus,
1404 index: Option<u8>,
1405 w: &mut TlvWriter<'_>,
1406 tag: Tag,
1407) -> Result<(), Status> {
1408 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1409 full(w.start_structure(tag))?;
1410 full(w.unsigned(Tag::Context(0), u64::from(status.value())))?;
1411 if let Some(index) = index {
1412 full(w.unsigned(Tag::Context(2), u64::from(index)))?;
1413 }
1414 full(w.end_container())
1415}
1416
1417/// `ConnectNetworkResponse` (§11.9.7.9): `NetworkingStatus [0]`, `DebugText [1]`,
1418/// `ErrorValue [2]`.
1419///
1420/// `ErrorValue` is mandatory **and** nullable, so it is always present and null on success.
1421fn write_connect_response(
1422 outcome: ConnectOutcome,
1423 w: &mut TlvWriter<'_>,
1424 tag: Tag,
1425) -> Result<(), Status> {
1426 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1427 full(w.start_structure(tag))?;
1428 full(w.unsigned(Tag::Context(0), u64::from(outcome.status.value())))?;
1429 match outcome.error_value {
1430 Some(value) => full(w.signed(Tag::Context(2), i64::from(value)))?,
1431 None => full(w.null(Tag::Context(2)))?,
1432 }
1433 full(w.end_container())
1434}
1435
1436// --- The attributes ----------------------------------------------------------------------------
1437
1438/// The scratch an invoke uses to build a `ScanNetworksResponse`'s result list.
1439///
1440/// Sized against §4.4.4's message limits rather than generously: a `ScanNetworksResponse` has
1441/// to fit in one message, and §11.9.7.2 explicitly permits reporting "a subset of
1442/// possibilities, to avoid memory exhaustion on the cluster server and avoid crossing the
1443/// maximum command response size supported". The driver sees the sink fill up and stops.
1444pub const SCAN_SCRATCH_BYTES: usize = 1024;
1445
1446impl<D: NetworkDriver, const N: usize> ClusterHandler for NetworkCommissioning<'_, D, N> {
1447 /// The network list is the one thing the fail-safe stages that is not a fabric: §11.10.7.2.2
1448 /// step 5 reverts it on expiry, and §11.10.7.6 makes it permanent on
1449 /// `CommissioningComplete`. A node that never commits reverts to its *first* snapshot at
1450 /// the next expiry, whenever that is.
1451 fn on_lifecycle(&self, event: crate::im::Lifecycle) {
1452 match event {
1453 crate::im::Lifecycle::FailSafeExpired { .. } => self.on_fail_safe_expired(),
1454 crate::im::Lifecycle::CommissioningComplete(_) => self.on_commissioning_complete(),
1455 crate::im::Lifecycle::FabricRemoved(_) => {}
1456 }
1457 }
1458 fn read(
1459 &self,
1460 resolved: &Resolved<'_>,
1461 _ctx: &InteractionContext<'_>,
1462 w: &mut TlvWriter<'_>,
1463 tag: Tag,
1464 ) -> Result<(), Status> {
1465 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
1466 match resolved.attribute {
1467 MAX_NETWORKS => {
1468 let capacity = u8::try_from(N).unwrap_or(u8::MAX);
1469 full(w.unsigned(tag, u64::from(capacity)))
1470 }
1471 NETWORKS => {
1472 let store = self.store.borrow();
1473 full(w.start_array(tag))?;
1474 for entry in store.entries() {
1475 full(w.start_structure(Tag::Anonymous))?;
1476 full(w.octets(Tag::Context(0), &entry.id))?;
1477 full(w.bool(Tag::Context(1), entry.connected))?;
1478 full(w.end_container())?;
1479 }
1480 full(w.end_container())
1481 }
1482 SCAN_MAX_TIME_SECONDS => {
1483 full(w.unsigned(tag, u64::from(self.capabilities.scan_max_time_seconds)))
1484 }
1485 CONNECT_MAX_TIME_SECONDS => {
1486 full(w.unsigned(tag, u64::from(self.capabilities.connect_max_time_seconds)))
1487 }
1488 INTERFACE_ENABLED => full(w.bool(tag, self.enabled.get())),
1489 // The three `Last*` attributes are nullable and null until something has been
1490 // attempted — §11.9.6.6: "If no such attempt was made … this attribute SHALL be
1491 // set to null." A zero would name `Success`, which is a different claim.
1492 LAST_NETWORKING_STATUS => match self.last_status.get() {
1493 Some(status) => full(w.unsigned(tag, u64::from(status.value()))),
1494 None => full(w.null(tag)),
1495 },
1496 LAST_NETWORK_ID => match self.last_network_id.borrow().as_deref() {
1497 Some(id) => full(w.octets(tag, id)),
1498 None => full(w.null(tag)),
1499 },
1500 LAST_CONNECT_ERROR_VALUE => match self.last_connect_error.get() {
1501 Some(value) => full(w.signed(tag, i64::from(value))),
1502 None => full(w.null(tag)),
1503 },
1504 SUPPORTED_WIFI_BANDS => {
1505 full(w.start_array(tag))?;
1506 for band in self.capabilities.wifi_bands {
1507 full(w.unsigned(Tag::Anonymous, u64::from(band.value())))?;
1508 }
1509 full(w.end_container())
1510 }
1511 SUPPORTED_THREAD_FEATURES => {
1512 full(w.unsigned(tag, u64::from(self.capabilities.thread_features.bits())))
1513 }
1514 THREAD_VERSION => full(w.unsigned(tag, u64::from(self.capabilities.thread_version))),
1515 _ => Err(Status::UnsupportedAttribute),
1516 }
1517 }
1518
1519 fn write(
1520 &self,
1521 resolved: &Resolved<'_>,
1522 data: &[u8],
1523 _op: WriteOp,
1524 _ctx: &InteractionContext<'_>,
1525 ) -> Result<(), Status> {
1526 match resolved.attribute {
1527 INTERFACE_ENABLED => {
1528 let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
1529 let value = reader
1530 .next_element()
1531 .ok()
1532 .flatten()
1533 .and_then(|element| element.bool().ok())
1534 .ok_or(Status::InvalidDataType)?;
1535 // §11.9.6.5: a driver that cannot disable its interface answers
1536 // INVALID_ACTION, and the attribute is left alone.
1537 self.driver.set_interface_enabled(value)?;
1538 self.enabled.set(value);
1539 Ok(())
1540 }
1541 _ => Err(Status::UnsupportedWrite),
1542 }
1543 }
1544
1545 fn invoke(
1546 &self,
1547 resolved: &ResolvedCommand<'_>,
1548 fields: Option<&[u8]>,
1549 ctx: &InteractionContext<'_>,
1550 w: &mut TlvWriter<'_>,
1551 tag: Tag,
1552 ) -> Result<Option<CommandId>, StatusIb> {
1553 match resolved.command.id {
1554 SCAN_NETWORKS => {
1555 let request = ScanRequest::decode(fields)?;
1556 let mut scratch = [0u8; SCAN_SCRATCH_BYTES];
1557 self.scan(request.ssid, request.breadcrumb, ctx, &mut scratch, w, tag)?;
1558 Ok(Some(SCAN_NETWORKS_RESPONSE))
1559 }
1560 ADD_OR_UPDATE_WIFI_NETWORK => {
1561 let request = WiFiRequest::decode(fields)?;
1562 self.add_or_update_wifi(
1563 request.ssid,
1564 request.credentials,
1565 request.breadcrumb,
1566 ctx,
1567 w,
1568 tag,
1569 )?;
1570 Ok(Some(NETWORK_CONFIG_RESPONSE))
1571 }
1572 ADD_OR_UPDATE_THREAD_NETWORK => {
1573 let request = ThreadRequest::decode(fields)?;
1574 self.add_or_update_thread(request.dataset, request.breadcrumb, ctx, w, tag)?;
1575 Ok(Some(NETWORK_CONFIG_RESPONSE))
1576 }
1577 REMOVE_NETWORK => {
1578 let request = NetworkIdRequest::decode(fields)?;
1579 self.remove_network(request.id, request.breadcrumb, ctx, w, tag)?;
1580 Ok(Some(NETWORK_CONFIG_RESPONSE))
1581 }
1582 CONNECT_NETWORK => {
1583 let request = NetworkIdRequest::decode(fields)?;
1584 self.connect_network(request.id, request.breadcrumb, ctx, w, tag)?;
1585 Ok(Some(CONNECT_NETWORK_RESPONSE))
1586 }
1587 REORDER_NETWORK => {
1588 let request = ReorderRequest::decode(fields)?;
1589 self.reorder_network(request.id, request.index, request.breadcrumb, ctx, w, tag)?;
1590 Ok(Some(NETWORK_CONFIG_RESPONSE))
1591 }
1592 _ => Err(Status::UnsupportedCommand.into()),
1593 }
1594 }
1595}
1596
1597impl<D: NetworkDriver, const N: usize> Cluster for NetworkCommissioning<'_, D, N> {
1598 const ID: ClusterId = ID;
1599}
1600
1601// --- Command decoding --------------------------------------------------------------------------
1602
1603/// Walks a `CommandFields` structure, refusing a truncated or malformed one.
1604///
1605/// The same contract as every other cluster's decoder: only the structure's own
1606/// end-of-container ends the walk, so a short buffer cannot be read as "these fields were
1607/// absent" and silently take a command's fallbacks.
1608fn walk_fields<'a>(
1609 fields: Option<&'a [u8]>,
1610 mut on_field: impl FnMut(u8, &crate::tlv::Element<'a>) -> Result<bool, Status>,
1611) -> Result<(), Status> {
1612 let fields = fields.ok_or(Status::InvalidCommand)?;
1613 let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
1614 let element = reader
1615 .next_element()
1616 .map_err(|_| Status::InvalidCommand)?
1617 .ok_or(Status::InvalidCommand)?;
1618 if element.value.container() != Some(ContainerKind::Structure) {
1619 return Err(Status::InvalidCommand);
1620 }
1621 let start_depth = reader.depth();
1622 loop {
1623 let Some(field) = reader.next_element().map_err(|_| Status::InvalidCommand)? else {
1624 return Err(Status::InvalidCommand);
1625 };
1626 if reader.depth() < start_depth {
1627 break;
1628 }
1629 let Tag::Context(number) = field.tag else {
1630 reader
1631 .skip_value(&field)
1632 .map_err(|_| Status::InvalidCommand)?;
1633 continue;
1634 };
1635 if !on_field(number, &field)? {
1636 reader
1637 .skip_value(&field)
1638 .map_err(|_| Status::InvalidCommand)?;
1639 }
1640 }
1641 Ok(())
1642}
1643
1644struct ScanRequest<'a> {
1645 ssid: Option<&'a [u8]>,
1646 breadcrumb: Option<u64>,
1647}
1648
1649impl<'a> ScanRequest<'a> {
1650 fn decode(fields: Option<&'a [u8]>) -> Result<Self, Status> {
1651 let mut ssid = None;
1652 let mut breadcrumb = None;
1653 walk_fields(fields, |number, element| {
1654 match number {
1655 // `SSID [0]` is optional *and* nullable, and both mean the same thing here:
1656 // "if the field is absent, or if it is null, this SHALL indicate scanning of
1657 // all BSSID in range".
1658 0 => {
1659 if !element.value.is_null() {
1660 set_once(
1661 &mut ssid,
1662 element.octets().map_err(|_| Status::InvalidCommand)?,
1663 )
1664 .map_err(|_| Status::InvalidCommand)?;
1665 }
1666 }
1667 1 => set_once(
1668 &mut breadcrumb,
1669 element.unsigned().map_err(|_| Status::InvalidCommand)?,
1670 )
1671 .map_err(|_| Status::InvalidCommand)?,
1672 _ => return Ok(false),
1673 }
1674 Ok(true)
1675 })?;
1676 Ok(Self { ssid, breadcrumb })
1677 }
1678}
1679
1680struct WiFiRequest<'a> {
1681 ssid: &'a [u8],
1682 credentials: &'a [u8],
1683 breadcrumb: Option<u64>,
1684}
1685
1686impl<'a> WiFiRequest<'a> {
1687 fn decode(fields: Option<&'a [u8]>) -> Result<Self, Status> {
1688 let mut ssid = None;
1689 let mut credentials = None;
1690 let mut breadcrumb = None;
1691 walk_fields(fields, |number, element| {
1692 match number {
1693 0 => set_once(
1694 &mut ssid,
1695 element.octets().map_err(|_| Status::InvalidCommand)?,
1696 ),
1697 1 => set_once(
1698 &mut credentials,
1699 element.octets().map_err(|_| Status::InvalidCommand)?,
1700 ),
1701 2 => set_once(
1702 &mut breadcrumb,
1703 element.unsigned().map_err(|_| Status::InvalidCommand)?,
1704 ),
1705 _ => return Ok(false),
1706 }
1707 .map_err(|_| Status::InvalidCommand)?;
1708 Ok(true)
1709 })?;
1710 let ssid = ssid.ok_or(Status::InvalidCommand)?;
1711 let credentials = credentials.ok_or(Status::InvalidCommand)?;
1712 // §11.9.7.3's `max 32` and `max 64`. A longer value is a constraint error rather than
1713 // something to truncate: truncating a PSK produces a device that cannot associate and
1714 // cannot say why.
1715 if ssid.len() > NETWORK_ID_MAX || credentials.len() > CREDENTIALS_MAX {
1716 return Err(Status::ConstraintError);
1717 }
1718 Ok(Self {
1719 ssid,
1720 credentials,
1721 breadcrumb,
1722 })
1723 }
1724}
1725
1726struct ThreadRequest<'a> {
1727 dataset: &'a [u8],
1728 breadcrumb: Option<u64>,
1729}
1730
1731impl<'a> ThreadRequest<'a> {
1732 fn decode(fields: Option<&'a [u8]>) -> Result<Self, Status> {
1733 let mut dataset = None;
1734 let mut breadcrumb = None;
1735 walk_fields(fields, |number, element| {
1736 match number {
1737 0 => set_once(
1738 &mut dataset,
1739 element.octets().map_err(|_| Status::InvalidCommand)?,
1740 ),
1741 1 => set_once(
1742 &mut breadcrumb,
1743 element.unsigned().map_err(|_| Status::InvalidCommand)?,
1744 ),
1745 _ => return Ok(false),
1746 }
1747 .map_err(|_| Status::InvalidCommand)?;
1748 Ok(true)
1749 })?;
1750 let dataset = dataset.ok_or(Status::InvalidCommand)?;
1751 if dataset.len() > OPERATIONAL_DATASET_MAX {
1752 return Err(Status::ConstraintError);
1753 }
1754 Ok(Self {
1755 dataset,
1756 breadcrumb,
1757 })
1758 }
1759}
1760
1761struct NetworkIdRequest<'a> {
1762 id: &'a [u8],
1763 breadcrumb: Option<u64>,
1764}
1765
1766impl<'a> NetworkIdRequest<'a> {
1767 fn decode(fields: Option<&'a [u8]>) -> Result<Self, Status> {
1768 let mut id = None;
1769 let mut breadcrumb = None;
1770 walk_fields(fields, |number, element| {
1771 match number {
1772 0 => set_once(
1773 &mut id,
1774 element.octets().map_err(|_| Status::InvalidCommand)?,
1775 ),
1776 1 => set_once(
1777 &mut breadcrumb,
1778 element.unsigned().map_err(|_| Status::InvalidCommand)?,
1779 ),
1780 _ => return Ok(false),
1781 }
1782 .map_err(|_| Status::InvalidCommand)?;
1783 Ok(true)
1784 })?;
1785 Ok(Self {
1786 id: id.ok_or(Status::InvalidCommand)?,
1787 breadcrumb,
1788 })
1789 }
1790}
1791
1792struct ReorderRequest<'a> {
1793 id: &'a [u8],
1794 index: u8,
1795 breadcrumb: Option<u64>,
1796}
1797
1798impl<'a> ReorderRequest<'a> {
1799 fn decode(fields: Option<&'a [u8]>) -> Result<Self, Status> {
1800 let mut id = None;
1801 let mut index = None;
1802 let mut breadcrumb = None;
1803 walk_fields(fields, |number, element| {
1804 match number {
1805 0 => set_once(
1806 &mut id,
1807 element.octets().map_err(|_| Status::InvalidCommand)?,
1808 ),
1809 1 => {
1810 let value = element.unsigned().map_err(|_| Status::InvalidCommand)?;
1811 set_once(
1812 &mut index,
1813 u8::try_from(value).map_err(|_| Status::ConstraintError)?,
1814 )
1815 }
1816 2 => set_once(
1817 &mut breadcrumb,
1818 element.unsigned().map_err(|_| Status::InvalidCommand)?,
1819 ),
1820 _ => return Ok(false),
1821 }
1822 .map_err(|_| Status::InvalidCommand)?;
1823 Ok(true)
1824 })?;
1825 Ok(Self {
1826 id: id.ok_or(Status::InvalidCommand)?,
1827 index: index.ok_or(Status::InvalidCommand)?,
1828 breadcrumb,
1829 })
1830 }
1831}