Skip to main content

rs_matter_node_core/
networks.rs

1/*
2 *
3 *    Copyright (c) 2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18//! The networks store of the node: the credentials of the wireless networks
19//! it may connect to, and their persistence.
20
21use core::fmt;
22
23use rs_matter_tlv::TlvError;
24
25use crate::error::{Error, ErrorCode};
26use crate::persist::{KvBlobStoreAccess, Persist};
27use crate::utils::sync::MaybeSendSync;
28
29/// Network type supported by the `NetCtl` implementations
30#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
31#[cfg_attr(feature = "defmt", derive(defmt::Format))]
32pub enum NetworkType {
33    Ethernet,
34    Wifi,
35    Thread,
36}
37
38impl NetworkType {
39    /// Check if the given credentials match the network type
40    pub fn check_creds(&self, creds: &WirelessCreds<'_>) -> Result<(), Error> {
41        match creds {
42            WirelessCreds::Wifi { .. } if matches!(self, NetworkType::Wifi) => Ok(()),
43            WirelessCreds::Thread { .. } if matches!(self, NetworkType::Thread) => Ok(()),
44            _ => Err(ErrorCode::InvalidAction.into()),
45        }
46    }
47}
48
49/// Wireless credentials used for connecting to a network
50#[derive(Debug, Clone, Eq, PartialEq, Hash)]
51pub enum WirelessCreds<'a> {
52    /// WiFi credentials
53    Wifi { ssid: &'a [u8], pass: &'a [u8] },
54    /// Thread credentials
55    Thread { dataset_tlv: &'a [u8] },
56}
57
58impl WirelessCreds<'_> {
59    /// Return the network ID of the credentials
60    /// For Wifi networks, this is the SSID
61    /// For Thread networks, this is the extended PAN ID
62    pub fn id(&self) -> Result<&[u8], Error> {
63        match self {
64            WirelessCreds::Wifi { ssid, .. } => Ok(ssid),
65            WirelessCreds::Thread { dataset_tlv } => ThreadTLV::new(dataset_tlv).ext_pan_id(),
66        }
67    }
68}
69
70impl fmt::Display for WirelessCreds<'_> {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            WirelessCreds::Wifi { ssid, .. } => write!(
74                f,
75                "SSID({})",
76                core::str::from_utf8(ssid).ok().unwrap_or("???")
77            ),
78            WirelessCreds::Thread { dataset_tlv } => write!(
79                f,
80                "ExtEpanId({:?})",
81                ThreadTLV::new(dataset_tlv).ext_pan_id().ok().unwrap_or(&[])
82            ),
83        }
84    }
85}
86
87#[cfg(feature = "defmt")]
88impl defmt::Format for WirelessCreds<'_> {
89    fn format(&self, fmt: defmt::Formatter) {
90        match self {
91            WirelessCreds::Wifi { ssid, .. } => defmt::write!(
92                fmt,
93                "SSID({})",
94                core::str::from_utf8(ssid).ok().unwrap_or("???")
95            ),
96            WirelessCreds::Thread { dataset_tlv } => defmt::write!(
97                fmt,
98                "ExtEpanId({:?})",
99                ThreadTLV::new(dataset_tlv).ext_pan_id().ok().unwrap_or(&[])
100            ),
101        }
102    }
103}
104
105/// Network error type for the `Networks` trait
106#[derive(Debug)]
107#[cfg_attr(feature = "defmt", derive(defmt::Format))]
108pub enum NetworksError {
109    NetworkIdNotFound,
110    DuplicateNetworkId,
111    OutOfRange,
112    BoundsExceeded,
113    Other(Error),
114}
115
116impl From<Error> for NetworksError {
117    fn from(err: Error) -> Self {
118        NetworksError::Other(err)
119    }
120}
121
122// TODO: Remove once network errors are refactored.
123impl From<TlvError> for NetworksError {
124    fn from(err: TlvError) -> Self {
125        NetworksError::Other(err.into())
126    }
127}
128
129/// Trait for managing networks' credentials storage
130pub trait Networks: MaybeSendSync {
131    /// Return the maximum number of networks supported by the implementation
132    ///
133    /// For `NetworkType::Ethernet` this method should always return 1
134    fn max_networks(&self) -> Result<u8, Error>;
135
136    /// Iterate over the networks recorded in the implementation and call the provided function for each network
137    fn networks(&self, f: &mut dyn FnMut(&[u8]) -> Result<(), Error>) -> Result<(), Error>;
138
139    /// Get the credentials for the given network ID by calling the provided function
140    ///
141    /// For `NetworkType::Ethernet` this method should always fail with an error.
142    ///
143    /// The function will be called with the credentials for the network ID, or an error if the network ID is not found.
144    ///
145    /// Return the index of the network ID if found, or an error if not found.
146    fn creds(
147        &self,
148        network_id: &[u8],
149        f: &mut dyn FnMut(&WirelessCreds) -> Result<(), Error>,
150    ) -> Result<u8, NetworksError>;
151
152    /// Return the next credentials after the ones corresponding to the given network ID by calling the provided function
153    ///
154    /// For `NetworkType::Ethernet` this method should always fail with an error.
155    ///
156    /// If the network ID is `None` or credentials with the provided network ID cannot be found,
157    /// the first credentials will be returned.
158    ///
159    /// If the credentials corresponding to the network ID are the last ones recorded in the `Netwrks` trait implementation,
160    /// the method will wrap-over and will return the first credentials or even the same credentials again if there is only one
161    /// recorded network.
162    ///
163    /// Return `true` if the credentials were found, `false` otherwise.
164    fn next_creds(
165        &self,
166        last_network_id: Option<&[u8]>,
167        f: &mut dyn FnMut(&WirelessCreds) -> Result<(), Error>,
168    ) -> Result<bool, Error>;
169
170    /// Return whether the network interface is enabled
171    fn enabled(&self) -> Result<bool, Error>;
172
173    /// Set the network interface enabled or disabled
174    fn set_enabled(&mut self, enabled: bool) -> Result<(), Error>;
175
176    /// Add or update the credentials for the given network ID
177    ///
178    /// For `NetworkType::Ethernet` this method should always fail with an error.
179    ///
180    /// The network ID is derived from the credentials.
181    ///
182    /// Return the index of the network ID if it was added or updated, or an error if the operation failed.
183    fn add_or_update(&mut self, creds: &WirelessCreds<'_>) -> Result<u8, NetworksError>;
184
185    /// Reorder the network with the given index
186    ///
187    /// For `NetworkType::Ethernet` this method should always fail with an error.
188    ///
189    /// The index is the new index of the network ID.
190    ///
191    /// Return the index of the network ID if it was reordered, or an error if the operation failed.
192    fn reorder(&mut self, index: u8, network_id: &[u8]) -> Result<u8, NetworksError>;
193
194    /// Remove the network with the given network ID
195    ///
196    /// For `NetworkType::Ethernet` this method should always fail with an error.
197    ///
198    /// Return the index of the network ID if it was removed, or an error if the operation failed.
199    fn remove(&mut self, network_id: &[u8]) -> Result<u8, NetworksError>;
200
201    /// Return whether the networks store is in "managed" state.
202    ///
203    /// Managed means: the store holds *committed* operational network
204    /// configuration, and the operational connectivity manager
205    /// (`WirelessMgr`) may act on it. The store starts unmanaged (never
206    /// commissioned, empty), and temporarily *becomes* unmanaged again while
207    /// network changes are staged under an armed fail-safe (any successful
208    /// `AddOrUpdate*Network` / `RemoveNetwork` / `ReorderNetwork` /
209    /// `ConnectNetwork` flips it to `false`) - during such a window the
210    /// commissioner drives connectivity explicitly, and the manager must
211    /// stand down.
212    ///
213    /// The state comes back to managed on either exit from the window:
214    /// - commit: `CommissioningComplete` calls `set_managed(true)` and
215    ///   persists the store;
216    /// - revert: the fail-safe expiry reloads the persisted store, which
217    ///   always carries the committed - hence managed - state.
218    ///
219    /// Note that a window which stages no network changes (e.g. opened only
220    /// to commission an additional fabric) leaves the store managed, so
221    /// connectivity maintenance of the operational network continues
222    /// throughout - matching CHIP's behavior.
223    fn managed(&self) -> Result<bool, Error>;
224
225    /// Set the managed state of the networks store (see `managed`).
226    fn set_managed(&mut self, managed: bool) -> Result<(), Error>;
227
228    /// Reset the networks to the initial state, removing all recorded network credentials
229    fn reset(&mut self) -> Result<(), Error>;
230
231    /// Load the networks' credentials from the given data
232    fn load(&mut self, data: &[u8]) -> Result<(), Error>;
233
234    /// Save the networks' credentials into the given buffer and return the number of bytes written
235    /// or `None` if the networks do not need persistence.
236    fn save(&self, buf: &mut [u8]) -> Result<Option<usize>, Error>;
237
238    /// Return the type of the networks the store holds, if it knows it.
239    ///
240    /// The default implementation returns `None`.
241    fn net_type(&self) -> Option<NetworkType> {
242        None
243    }
244}
245
246impl<T> Networks for &mut T
247where
248    T: Networks,
249{
250    fn max_networks(&self) -> Result<u8, Error> {
251        (**self).max_networks()
252    }
253
254    fn networks(&self, f: &mut dyn FnMut(&[u8]) -> Result<(), Error>) -> Result<(), Error> {
255        (**self).networks(f)
256    }
257
258    fn creds(
259        &self,
260        network_id: &[u8],
261        f: &mut dyn FnMut(&WirelessCreds) -> Result<(), Error>,
262    ) -> Result<u8, NetworksError> {
263        (**self).creds(network_id, f)
264    }
265
266    fn next_creds(
267        &self,
268        last_network_id: Option<&[u8]>,
269        f: &mut dyn FnMut(&WirelessCreds) -> Result<(), Error>,
270    ) -> Result<bool, Error> {
271        (**self).next_creds(last_network_id, f)
272    }
273
274    fn enabled(&self) -> Result<bool, Error> {
275        (**self).enabled()
276    }
277
278    fn set_enabled(&mut self, enabled: bool) -> Result<(), Error> {
279        (*self).set_enabled(enabled)
280    }
281
282    fn add_or_update(&mut self, creds: &WirelessCreds<'_>) -> Result<u8, NetworksError> {
283        (*self).add_or_update(creds)
284    }
285
286    fn reorder(&mut self, index: u8, network_id: &[u8]) -> Result<u8, NetworksError> {
287        (*self).reorder(index, network_id)
288    }
289
290    fn remove(&mut self, network_id: &[u8]) -> Result<u8, NetworksError> {
291        (*self).remove(network_id)
292    }
293
294    fn managed(&self) -> Result<bool, Error> {
295        (**self).managed()
296    }
297
298    fn set_managed(&mut self, managed: bool) -> Result<(), Error> {
299        (**self).set_managed(managed)
300    }
301
302    fn reset(&mut self) -> Result<(), Error> {
303        (**self).reset()
304    }
305
306    fn load(&mut self, data: &[u8]) -> Result<(), Error> {
307        (**self).load(data)
308    }
309
310    fn save(&self, buf: &mut [u8]) -> Result<Option<usize>, Error> {
311        (**self).save(buf)
312    }
313
314    fn net_type(&self) -> Option<NetworkType> {
315        (**self).net_type()
316    }
317}
318
319impl Networks for &mut dyn Networks {
320    fn max_networks(&self) -> Result<u8, Error> {
321        (**self).max_networks()
322    }
323
324    fn networks(&self, f: &mut dyn FnMut(&[u8]) -> Result<(), Error>) -> Result<(), Error> {
325        (**self).networks(f)
326    }
327
328    fn creds(
329        &self,
330        network_id: &[u8],
331        f: &mut dyn FnMut(&WirelessCreds) -> Result<(), Error>,
332    ) -> Result<u8, NetworksError> {
333        (**self).creds(network_id, f)
334    }
335
336    fn next_creds(
337        &self,
338        last_network_id: Option<&[u8]>,
339        f: &mut dyn FnMut(&WirelessCreds) -> Result<(), Error>,
340    ) -> Result<bool, Error> {
341        (**self).next_creds(last_network_id, f)
342    }
343
344    fn enabled(&self) -> Result<bool, Error> {
345        (**self).enabled()
346    }
347
348    fn set_enabled(&mut self, enabled: bool) -> Result<(), Error> {
349        (**self).set_enabled(enabled)
350    }
351
352    fn add_or_update(&mut self, creds: &WirelessCreds<'_>) -> Result<u8, NetworksError> {
353        (**self).add_or_update(creds)
354    }
355
356    fn reorder(&mut self, index: u8, network_id: &[u8]) -> Result<u8, NetworksError> {
357        (**self).reorder(index, network_id)
358    }
359
360    fn remove(&mut self, network_id: &[u8]) -> Result<u8, NetworksError> {
361        (**self).remove(network_id)
362    }
363
364    fn managed(&self) -> Result<bool, Error> {
365        (**self).managed()
366    }
367
368    fn set_managed(&mut self, managed: bool) -> Result<(), Error> {
369        (**self).set_managed(managed)
370    }
371
372    fn reset(&mut self) -> Result<(), Error> {
373        (**self).reset()
374    }
375
376    fn load(&mut self, data: &[u8]) -> Result<(), Error> {
377        (**self).load(data)
378    }
379
380    fn save(&self, buf: &mut [u8]) -> Result<Option<usize>, Error> {
381        (**self).save(buf)
382    }
383
384    fn net_type(&self) -> Option<NetworkType> {
385        (**self).net_type()
386    }
387}
388
389/// A `Networks` implementation with no networks, which refuses to record any.
390pub struct DummyNetworks;
391
392impl Networks for DummyNetworks {
393    fn max_networks(&self) -> Result<u8, Error> {
394        Ok(0)
395    }
396
397    fn networks(&self, _f: &mut dyn FnMut(&[u8]) -> Result<(), Error>) -> Result<(), Error> {
398        Ok(())
399    }
400
401    fn creds(
402        &self,
403        _network_id: &[u8],
404        _f: &mut dyn FnMut(&WirelessCreds) -> Result<(), Error>,
405    ) -> Result<u8, NetworksError> {
406        Err(NetworksError::NetworkIdNotFound)
407    }
408
409    fn next_creds(
410        &self,
411        _last_network_id: Option<&[u8]>,
412        _f: &mut dyn FnMut(&WirelessCreds) -> Result<(), Error>,
413    ) -> Result<bool, Error> {
414        Ok(false)
415    }
416
417    fn enabled(&self) -> Result<bool, Error> {
418        Ok(false)
419    }
420
421    fn set_enabled(&mut self, _enabled: bool) -> Result<(), Error> {
422        Ok(())
423    }
424
425    fn add_or_update(&mut self, _creds: &WirelessCreds<'_>) -> Result<u8, NetworksError> {
426        Err(NetworksError::Other(ErrorCode::InvalidAction.into()))
427    }
428
429    fn reorder(&mut self, _index: u8, _network_id: &[u8]) -> Result<u8, NetworksError> {
430        Err(NetworksError::Other(ErrorCode::InvalidAction.into()))
431    }
432
433    fn remove(&mut self, _network_id: &[u8]) -> Result<u8, NetworksError> {
434        Err(NetworksError::Other(ErrorCode::InvalidAction.into()))
435    }
436
437    fn managed(&self) -> Result<bool, Error> {
438        Ok(false)
439    }
440
441    fn set_managed(&mut self, _managed: bool) -> Result<(), Error> {
442        Ok(())
443    }
444
445    fn reset(&mut self) -> Result<(), Error> {
446        Ok(())
447    }
448
449    fn load(&mut self, _data: &[u8]) -> Result<(), Error> {
450        Ok(())
451    }
452
453    fn save(&self, _buf: &mut [u8]) -> Result<Option<usize>, Error> {
454        Ok(None)
455    }
456}
457
458/// Reload the committed networks of `networks` from `kv`, where they are
459/// persisted under `key`; reset the store if nothing is persisted, or if what
460/// is cannot be loaded.
461pub fn load_networks<N, K>(mut networks: N, key: u16, kv: K) -> Result<(), Error>
462where
463    N: Networks,
464    K: KvBlobStoreAccess,
465{
466    let loaded = Persist::new(kv).load(key, |data| networks.load(data))?;
467
468    // A load that failed may have stopped half-way
469    match loaded {
470        Some(()) => Ok(()),
471        None => networks.reset(),
472    }
473}
474
475/// Persist `networks` into `kv`, under `key`.
476pub fn store_networks<N, K>(networks: N, key: u16, kv: K) -> Result<(), Error>
477where
478    N: Networks,
479    K: KvBlobStoreAccess,
480{
481    let mut persist = Persist::new(kv);
482
483    persist.store(key, |buf| networks.save(buf))?;
484
485    persist.run()
486}
487
488/// Reset `networks` and remove what is persisted for it in `kv`, under `key`.
489pub fn remove_networks<N, K>(mut networks: N, key: u16, kv: K) -> Result<(), Error>
490where
491    N: Networks,
492    K: KvBlobStoreAccess,
493{
494    networks.reset()?;
495
496    // Strict, as credentials surviving a factory reset must not go unreported
497    let mut persist = Persist::strict(kv);
498
499    persist.remove(key)?;
500
501    persist.run()
502}
503
504/// A simple Thread TLV reader
505#[derive(Debug, Copy, Clone)]
506#[cfg_attr(feature = "defmt", derive(defmt::Format))]
507pub struct ThreadTLV<'a>(&'a [u8]);
508
509impl<'a> ThreadTLV<'a> {
510    /// Create a new `ThreadTLV` instance with the given TLV data
511    pub const fn new(tlv: &'a [u8]) -> Self {
512        Self(tlv)
513    }
514
515    /// Get the Extended PAN ID from the operational dataset
516    pub fn ext_pan_id(&mut self) -> Result<&'a [u8], Error> {
517        const EXT_PAN_ID: u8 = 2;
518
519        let ext_pan_id =
520            self.find_map(|(tlv_type, tlv_value)| (tlv_type == EXT_PAN_ID).then_some(tlv_value));
521
522        let Some(ext_pan_id) = ext_pan_id else {
523            return Err(ErrorCode::InvalidData.into());
524        };
525
526        Ok(ext_pan_id)
527    }
528
529    /// Get the next TLV from the data
530    ///
531    /// Returns `Some` with the TLV type and value if there is a TLV available,
532    /// otherwise returns `None`.
533    pub fn next_tlv(&mut self) -> Option<(u8, &'a [u8])> {
534        const LONG_VALUE_ID: u8 = 255;
535
536        // Adopted from here:
537        // https://github.com/openthread/openthread/blob/main/tools/tcat_ble_client/tlv/tlv.py
538
539        let mut slice = self.0;
540
541        (slice.len() >= 2).then_some(())?;
542
543        let tlv_type = slice[0];
544        slice = &slice[1..];
545
546        let tlv_len_size = if slice[0] == LONG_VALUE_ID {
547            slice = &slice[1..];
548            3
549        } else {
550            1
551        };
552
553        (slice.len() >= tlv_len_size).then_some(())?;
554
555        let tlv_len = if tlv_len_size == 1 {
556            slice[0] as usize
557        } else {
558            u32::from_be_bytes([0, slice[0], slice[1], slice[2]]) as usize
559        };
560
561        slice = &slice[tlv_len_size..];
562        (slice.len() >= tlv_len).then_some(())?;
563
564        let tlv_value = &slice[..tlv_len];
565
566        slice = &slice[tlv_len..];
567
568        self.0 = slice;
569
570        Some((tlv_type, tlv_value))
571    }
572}
573
574impl<'a> Iterator for ThreadTLV<'a> {
575    type Item = (u8, &'a [u8]);
576
577    fn next(&mut self) -> Option<Self::Item> {
578        self.next_tlv()
579    }
580}