1use std::cell::RefCell;
6use std::collections::HashMap;
7use std::net::{SocketAddr, UdpSocket};
8use std::num::NonZeroU8;
9use std::rc::Rc;
10use std::time::{Duration, Instant, SystemTime};
11
12use matter_model::{encode_to_vec, Shape};
13use rs_matter::acl::{AclEntry, AuthMode, Target};
14use rs_matter::attest::DeviceAttestation;
15use rs_matter::basic_info::BasicInfoConfig;
16use rs_matter::bdx::{Bdx, PROTO_ID_BDX};
17use rs_matter::cert::gen::VALID_FOREVER;
18use rs_matter::cert::{MAX_CERT_TLV_AND_ASN1_LEN, MAX_CERT_TLV_LEN};
19use rs_matter::crypto::{
20 default_crypto, CanonAeadKeyRef, CanonPkcPublicKeyRef, CanonPkcSecretKeyRef, Crypto,
21};
22use rs_matter::dm::clusters::desc::{self, ClusterHandler as _};
23use rs_matter::dm::clusters::ota_prov::{OtaBdxHandler, OtaProviderHandler};
24use rs_matter::dm::devices::DEV_TYPE_OTA_PROVIDER;
25use rs_matter::dm::{
26 Async, Cluster, Dataver, EmptyHandler, Endpoint as DmEndpoint, Node as DmNode, Privilege,
27};
28use rs_matter::im::PROTO_ID_INTERACTION_MODEL;
29use rs_matter::im::{
30 AttrDataTag, AttrPath, CmdDataTag, CmdResp, EventFilter, EventPath, GenericPath, IMStatusCode,
31 ImClient, InteractionModel, InteractionModelState, ReportContext, ReportDataHandler,
32 ReportDataResp, SubscribeOutcome,
33};
34use rs_matter::onboard::noc::NocGenerator;
35use rs_matter::onboard::{CommissionHooks, CommissionOptions, Commissioner};
36use rs_matter::pairing::qr::{no_optional_data, CommFlowType, QrPayload};
37use rs_matter::pairing::{BasicCommData, DevCommData, DiscoveryCapabilities};
38use rs_matter::persist::DummyKvBlobStore;
39use rs_matter::respond::ChainedExchangeHandler;
40use rs_matter::respond::Responder;
41use rs_matter::sc::pase::{Spake2pVerifierPassword, Spake2pVerifierPasswordRef};
42use rs_matter::sc::ExchangeInitiator as _;
43use rs_matter::sc::SecureChannel;
44use rs_matter::tlv::{TLVElement, TLVTag, ToTLV as _};
45use rs_matter::transport::exchange::{Exchange, MatterBuffers};
46use rs_matter::transport::network::mdns::{MdnsBrowseMatch, MdnsBrowseQuery};
47use rs_matter::transport::network::{Address, NoNetwork};
48use rs_matter::utils::init::InitMaybeUninit as _;
49use rs_matter::Matter;
50use serde_json::{json, Value};
51use tokio::sync::{mpsc, oneshot};
52
53use crate::ca::{AnyCa, CertificateAuthority, FileCa, IntermediateCa};
54use crate::icd::{Icds, Registration};
55use crate::identity::Identity;
56use crate::onboarding::Onboarding;
57use crate::ota::{OtaDir, OtaImage};
58
59#[cfg(feature = "ble")]
60use crate::ble::Link;
61#[cfg(not(feature = "ble"))]
63enum Link {}
64#[cfg(not(feature = "ble"))]
65impl Link {
66 async fn close(self) {}
67}
68use crate::reports::{items, Collected};
69use crate::store::{BasicInfo, DeviceType, Endpoint, Node, NodeStore};
70use crate::{
71 AttributePath, AttributeValue, CommissionRequest, CommissionStep, Commissionable,
72 CommissioningWindow, Config, ControllerInfo, Error, Event,
73};
74
75const ROOT_ENDPOINT: u16 = 0;
76const DESCRIPTOR: u32 = 0x001D;
77const BASIC_INFORMATION: u32 = 0x0028;
78const OPERATIONAL_CREDENTIALS: u32 = 0x003E;
79const ADMINISTRATOR_COMMISSIONING: u32 = 0x003C;
80const GROUPS: u32 = 0x0004;
81const GROUP_KEY_MANAGEMENT: u32 = 0x003F;
82const GROUPCAST: u32 = 0x0065;
83const ACCESS_CONTROL: u32 = 0x001F;
84const NETWORK_COMMISSIONING: u32 = 0x0031;
85const OTA_REQUESTOR: u32 = 0x002A;
86const ICD_MANAGEMENT: u32 = 0x0046;
87const REGISTER_CLIENT: u32 = 0x0000;
89const ANNOUNCE_OTA_PROVIDER: u32 = 0x0000;
91
92const OTA_PROVIDER: Cluster<'static> = <OtaProviderHandler<&OtaDir> as rs_matter::dm::clusters::ota_prov::ClusterAsyncHandler>::CLUSTER;
94
95const CONTROLLER_NODE: DmNode<'static> = DmNode {
97 endpoints: &[DmEndpoint::new(
98 ROOT_ENDPOINT,
99 &[DEV_TYPE_OTA_PROVIDER],
100 &[desc::DescHandler::CLUSTER, OTA_PROVIDER],
101 )],
102};
103const ADD_WIFI_NETWORK: u32 = 0x02;
104const ADD_THREAD_NETWORK: u32 = 0x03;
105const CONNECT_NETWORK: u32 = 0x06;
106const TIMED_MS: u16 = 10_000;
108const MAX_PAYLOAD: usize = 1024;
110
111#[derive(Clone)]
114pub struct Controller {
115 jobs: mpsc::UnboundedSender<Job>,
116 events: EventBus,
117 info: ControllerInfo,
118 ota_dir: std::path::PathBuf,
119}
120
121type Reply<T> = oneshot::Sender<Result<T, Error>>;
122
123#[derive(Clone, Default)]
126pub(crate) struct EventBus(std::sync::Arc<std::sync::Mutex<Vec<mpsc::UnboundedSender<Event>>>>);
127
128impl EventBus {
129 fn subscribe(&self) -> mpsc::UnboundedReceiver<Event> {
130 let (tx, rx) = mpsc::unbounded_channel();
131 self.0.lock().unwrap().push(tx);
132 rx
133 }
134
135 pub(crate) fn send(&self, event: Event) {
136 let mut subscribers = self.0.lock().unwrap();
137 subscribers.retain(|s| !s.is_closed());
138 if let Some((last, rest)) = subscribers.split_last() {
139 for s in rest {
140 let _ = s.send(event.clone());
141 }
142 let _ = last.send(event);
143 }
144 }
145}
146
147enum Job {
148 Commission(CommissionRequest, Reply<Node>),
149 Read(u64, AttributePath, Reply<Vec<AttributeValue>>),
150 Write(u64, u16, u32, u32, Value, Option<u16>, Reply<()>),
151 Invoke(u64, u16, u32, u32, Value, Option<u16>, Reply<Value>),
152 OpenWindow(u64, u16, Reply<CommissioningWindow>),
153 Remove(u64, bool, Reply<()>),
154 Rename(u64, String, Reply<Node>),
155 Interview(u64, Reply<Node>),
156 Discover(u16, Reply<Vec<Commissionable>>),
157 Nodes(Reply<Vec<Node>>),
158 Abort(Reply<bool>),
159 AddToGroup(u64, u16, u16, String, Reply<()>),
160 RemoveFromGroup(u64, u16, u16, Reply<()>),
161 GroupInvoke(u16, u32, u32, Value, Reply<()>),
162 AnnounceOta(u64, Reply<Option<OtaImage>>),
163}
164
165impl Controller {
166 pub fn start(config: Config) -> Result<Self, Error> {
169 let (jobs_tx, jobs_rx) = mpsc::unbounded_channel();
170 let events = EventBus::default();
171 let (ready_tx, ready_rx) = std::sync::mpsc::channel();
172
173 let thread_events = events.clone();
174 let ota_dir = config.ota_dir.clone();
175 std::thread::Builder::new()
176 .name("matter".into())
177 .spawn(move || {
178 let rt = match tokio::runtime::Builder::new_current_thread()
179 .enable_all()
180 .build()
181 {
182 Ok(rt) => rt,
183 Err(e) => {
184 let _ = ready_tx.send(Err(Error::Io(e)));
185 return;
186 }
187 };
188 let local = tokio::task::LocalSet::new();
189 local.block_on(&rt, async move {
190 if let Err(e) = run(config, jobs_rx, thread_events, &ready_tx).await {
191 log::error!("controller stopped: {e}");
192 let _ = ready_tx.send(Err(e));
193 }
194 });
195 })?;
196
197 let info = ready_rx.recv().map_err(|_| Error::Stopped)??;
198 Ok(Self {
199 jobs: jobs_tx,
200 events,
201 info,
202 ota_dir,
203 })
204 }
205
206 pub fn info(&self) -> &ControllerInfo {
208 &self.info
209 }
210
211 pub fn events(&self) -> mpsc::UnboundedReceiver<Event> {
216 self.events.subscribe()
217 }
218
219 async fn call<T>(&self, job: impl FnOnce(Reply<T>) -> Job) -> Result<T, Error> {
220 let (tx, rx) = oneshot::channel();
221 self.jobs.send(job(tx)).map_err(|_| Error::Stopped)?;
222 rx.await.map_err(|_| Error::Stopped)?
223 }
224
225 pub async fn commission(&self, req: CommissionRequest) -> Result<Node, Error> {
228 self.call(|r| Job::Commission(req, r)).await
229 }
230
231 pub async fn read(&self, node: u64, path: AttributePath) -> Result<Vec<AttributeValue>, Error> {
233 self.call(|r| Job::Read(node, path, r)).await
234 }
235
236 pub async fn write(
238 &self,
239 node: u64,
240 endpoint: u16,
241 cluster: u32,
242 attribute: u32,
243 value: Value,
244 timed_ms: Option<u16>,
245 ) -> Result<(), Error> {
246 self.call(|r| Job::Write(node, endpoint, cluster, attribute, value, timed_ms, r))
247 .await
248 }
249
250 pub async fn invoke(
253 &self,
254 node: u64,
255 endpoint: u16,
256 cluster: u32,
257 command: u32,
258 fields: Value,
259 timed_ms: Option<u16>,
260 ) -> Result<Value, Error> {
261 self.call(|r| Job::Invoke(node, endpoint, cluster, command, fields, timed_ms, r))
262 .await
263 }
264
265 pub async fn open_commissioning_window(
268 &self,
269 node: u64,
270 timeout: u16,
271 ) -> Result<CommissioningWindow, Error> {
272 self.call(|r| Job::OpenWindow(node, timeout, r)).await
273 }
274
275 pub async fn remove(&self, node: u64, force: bool) -> Result<(), Error> {
278 self.call(|r| Job::Remove(node, force, r)).await
279 }
280
281 pub async fn rename(&self, node: u64, name: String) -> Result<Node, Error> {
283 self.call(|r| Job::Rename(node, name, r)).await
284 }
285
286 pub async fn interview(&self, node: u64) -> Result<Node, Error> {
288 self.call(|r| Job::Interview(node, r)).await
289 }
290
291 pub async fn discover(&self, seconds: u16) -> Result<Vec<Commissionable>, Error> {
293 self.call(|r| Job::Discover(seconds, r)).await
294 }
295
296 pub async fn add_to_group(
300 &self,
301 node: u64,
302 endpoint: u16,
303 group: u16,
304 name: String,
305 ) -> Result<(), Error> {
306 self.call(|r| Job::AddToGroup(node, endpoint, group, name, r))
307 .await
308 }
309
310 pub async fn remove_from_group(
312 &self,
313 node: u64,
314 endpoint: u16,
315 group: u16,
316 ) -> Result<(), Error> {
317 self.call(|r| Job::RemoveFromGroup(node, endpoint, group, r))
318 .await
319 }
320
321 pub async fn group_invoke(
324 &self,
325 group: u16,
326 cluster: u32,
327 command: u32,
328 fields: Value,
329 ) -> Result<(), Error> {
330 self.call(|r| Job::GroupInvoke(group, cluster, command, fields, r))
331 .await
332 }
333
334 pub fn ota_images(&self) -> Result<Vec<OtaImage>, Error> {
336 crate::ota::list(&self.ota_dir)
337 }
338
339 pub async fn announce_ota(&self, node: u64) -> Result<Option<OtaImage>, Error> {
345 self.call(|r| Job::AnnounceOta(node, r)).await
346 }
347
348 pub async fn abort_commissioning(&self) -> Result<bool, Error> {
351 self.call(Job::Abort).await
352 }
353
354 pub async fn nodes(&self) -> Result<Vec<Node>, Error> {
356 self.call(Job::Nodes).await
357 }
358}
359
360static CONTROLLER_INFO: BasicInfoConfig<'static> = BasicInfoConfig {
363 vid: 0xFFF1,
364 pid: 0x8000,
365 hw_ver: 1,
366 hw_ver_str: "1",
367 sw_ver: 1,
368 sw_ver_str: env!("CARGO_PKG_VERSION"),
369 serial_no: "",
370 vendor_name: "matter-bridge",
371 product_name: "matter-bridge controller",
372 device_name: "matter-bridge",
373 ..BasicInfoConfig::new()
374};
375
376struct NoAttestation;
378
379static ZERO_PUBLIC_KEY: [u8; 65] = [0; 65];
380static ZERO_SECRET_KEY: [u8; 32] = [0; 32];
381
382impl DeviceAttestation for NoAttestation {
383 fn cert_declaration(&self) -> &[u8] {
384 &[]
385 }
386 fn pai(&self) -> &[u8] {
387 &[]
388 }
389 fn dac(&self) -> &[u8] {
390 &[]
391 }
392 fn dac_pub_key(&self) -> CanonPkcPublicKeyRef<'_> {
393 CanonPkcPublicKeyRef::new(&ZERO_PUBLIC_KEY)
394 }
395 fn dac_priv_key(&self) -> CanonPkcSecretKeyRef<'_> {
396 CanonPkcSecretKeyRef::new(&ZERO_SECRET_KEY)
397 }
398}
399
400static NO_ATTESTATION: NoAttestation = NoAttestation;
401
402struct Ctx<C: 'static> {
404 matter: &'static Matter<'static>,
405 crypto: C,
406 fab_idx: NonZeroU8,
407 ca: AnyCa,
408 store: RefCell<NodeStore>,
409 events: EventBus,
410 config: Config,
411 subs: Rc<Subscriptions>,
412 tasks: RefCell<HashMap<u64, tokio::task::JoinHandle<()>>>,
413 commissioning: tokio::sync::Mutex<()>,
414 abort: tokio::sync::Notify,
415 kv: &'static rs_matter::persist::MatterKvBlobStoreAccess<'static, DummyKvBlobStore>,
416 groups: RefCell<crate::groups::GroupKey>,
417 icds: &'static Icds<C>,
418 #[cfg(feature = "ble")]
419 ble: Option<crate::ble::Ble>,
420}
421
422#[derive(Default)]
425struct Subscriptions {
426 by_node: RefCell<HashMap<u64, SubState>>,
427 partial: RefCell<HashMap<u64, Collected>>,
429}
430
431struct SubState {
432 id: Option<u32>,
433 max_interval: u16,
434 last_report: Instant,
435 last_event: Option<u64>,
436}
437
438async fn run(
439 config: Config,
440 mut jobs: mpsc::UnboundedReceiver<Job>,
441 events: EventBus,
442 ready: &std::sync::mpsc::Sender<Result<ControllerInfo, Error>>,
443) -> Result<(), Error> {
444 std::fs::create_dir_all(&config.state_dir)?;
445
446 let singleton: &'static [u8; 32] = Box::leak(Box::new(rand::random()));
449 let crypto: &'static _ = Box::leak(Box::new(default_crypto(
450 rand::rng(),
451 CanonPkcSecretKeyRef::new(singleton),
452 )));
453
454 let ca = match config.ca {
455 crate::CaChoice::File => AnyCa::File(FileCa::open_or_create(
456 &config.state_dir.join("ca.json"),
457 config.fabric_id,
458 crypto,
459 )?),
460 crate::CaChoice::Intermediate => AnyCa::Intermediate(IntermediateCa::open(
461 &config.state_dir.join("intermediate.json"),
462 )?),
463 };
464 let identity =
465 Identity::load_or_create(&config.state_dir.join("controller.json"), &ca, crypto).await?;
466 let store = NodeStore::open(&config.state_dir.join("nodes.json"))?;
467
468 let passcode: u32 = 1 + rand::random::<u32>() % 99_999_997;
471 let dev_comm = DevCommData::Passcode(BasicCommData {
472 password: Spake2pVerifierPassword::new_from_ref(Spake2pVerifierPasswordRef::new(
473 &passcode.to_le_bytes(),
474 )),
475 discriminator: rand::random::<u16>() & 0x0FFF,
476 });
477
478 let matter: &'static Matter<'static> = Box::leak(Box::<Matter>::new_uninit()).init_with(
480 Matter::init(&CONTROLLER_INFO, dev_comm, &NO_ATTESTATION, config.port),
481 );
482
483 let fab_idx = matter.with_state(|state| {
484 state
485 .fabrics
486 .add(
487 crypto,
488 CanonPkcSecretKeyRef::new(&identity.key),
489 ca.root_cert(),
490 &identity.noc,
491 ca.intermediate_cert().unwrap_or(&[]),
492 Some(CanonAeadKeyRef::new(ca.ipk())),
493 config.vendor_id,
494 identity.node_id,
495 )
496 .map(|f| f.fab_idx())
497 })?;
498
499 let compressed_fabric_id = matter.with_state(|state| {
500 state
501 .fabrics
502 .fabric(fab_idx)
503 .map(|f| f.compressed_fabric_id())
504 })?;
505
506 let info = ControllerInfo {
507 fabric_id: ca.fabric_id(),
508 compressed_fabric_id,
509 node_id: identity.node_id,
510 vendor_id: config.vendor_id,
511 };
512
513 let socket = async_io::Async::<UdpSocket>::bind(SocketAddr::from((
515 std::net::Ipv6Addr::UNSPECIFIED,
516 config.port,
517 )))?;
518
519 #[cfg(feature = "ble")]
522 let btp: &'static rs_matter::transport::network::btp::Btp =
523 Box::leak(Box::<rs_matter::transport::network::btp::Btp>::new_uninit())
524 .init_with(rs_matter::transport::network::btp::Btp::init());
525 #[cfg(feature = "ble")]
526 let ble = match &config.bluetooth {
527 Some(spec) => {
528 Some(crate::ble::Ble::open(spec, config.bluetooth_random_address, btp).await?)
529 }
530 None => None,
531 };
532 #[cfg(not(feature = "ble"))]
533 if config.bluetooth.is_some() {
534 return Err(Error::Unsupported(
535 "Bluetooth: this build has no `ble` feature".into(),
536 ));
537 }
538
539 let subs = Rc::new(Subscriptions::default());
540
541 std::fs::create_dir_all(&config.ota_dir)?;
544 let ota: &'static OtaDir = Box::leak(Box::new(OtaDir::new(
545 config.ota_dir.clone(),
546 events.clone(),
547 )));
548 matter.with_state(|state| {
550 let mut entry = AclEntry::new(None, Privilege::OPERATE, AuthMode::Case);
551 entry.add_target(Target::new(
552 Some(ROOT_ENDPOINT),
553 Some(OTA_PROVIDER.id),
554 None,
555 ))?;
556 state
557 .fabrics
558 .fabric_mut(fab_idx)?
559 .acl_add(entry)
560 .map(|_| ())
561 })?;
562 let buffers: &'static MatterBuffers = Box::leak(Box::new(MatterBuffers::new()));
563 let im_state: &'static InteractionModelState<1, 1024> =
564 Box::leak(Box::new(InteractionModelState::new()));
565 let kv: &'static _ = Box::leak(Box::new(matter.kv(DummyKvBlobStore)));
566
567 let groups = crate::groups::GroupKey::load_or_create(&config.state_dir.join("groups.json"))?;
569 groups.install(matter, fab_idx)?;
570 let sink = ReportSink {
571 subs: subs.clone(),
572 events: events.clone(),
573 };
574 let im: &'static _ = Box::leak(Box::new(InteractionModel::new_with_reports(
575 matter,
576 crypto,
577 buffers,
578 (
579 CONTROLLER_NODE,
580 EmptyHandler
581 .chain(
582 |e, c| e == ROOT_ENDPOINT && c == desc::DescHandler::CLUSTER.id,
583 Async(desc::DescHandler::new(Dataver::new(rand::random())).adapt()),
584 )
585 .chain(
586 |e, c| e == ROOT_ENDPOINT && c == OTA_PROVIDER.id,
587 OtaProviderHandler::new(Dataver::new(rand::random()), matter, ota).adapt(),
588 ),
589 ),
590 kv,
591 sink,
592 im_state,
593 )));
594 let icds: &'static Icds<_> = Box::leak(Box::new(Icds::load(
597 &config.state_dir.join("icd.json"),
598 crypto,
599 events.clone(),
600 )?));
601
602 let bdx_buffers: &'static MatterBuffers<2> =
604 Box::leak(Box::<MatterBuffers<2>>::new_uninit()).init_with(MatterBuffers::init());
605 let responder = Responder::new(
606 "Responder",
607 ChainedExchangeHandler::new(
608 PROTO_ID_INTERACTION_MODEL,
609 im,
610 SecureChannel::new_with_handler(matter, crypto, im, icds),
611 )
612 .chain(PROTO_ID_BDX, Bdx::new(OtaBdxHandler::new(bdx_buffers, ota))),
613 matter,
614 0,
615 );
616
617 let ctx = Rc::new(Ctx {
618 matter,
619 crypto,
620 fab_idx,
621 ca,
622 store: RefCell::new(store),
623 events,
624 config: config.clone(),
625 subs,
626 tasks: RefCell::new(HashMap::new()),
627 commissioning: tokio::sync::Mutex::new(()),
628 abort: tokio::sync::Notify::new(),
629 kv,
630 groups: RefCell::new(groups),
631 icds,
632 #[cfg(feature = "ble")]
633 ble,
634 });
635
636 let _ = ready.send(Ok(info));
637
638 let node_ids: Vec<u64> = ctx.store.borrow().nodes().map(|n| n.node_id).collect();
639 for node_id in node_ids {
640 ctx.start_subscription(node_id, false);
641 }
642
643 let serve = async {
644 while let Some(job) = jobs.recv().await {
645 let ctx = ctx.clone();
646 tokio::task::spawn_local(async move { ctx.handle(job).await });
647 }
648 };
649
650 let mdns = crate::mdns::run(matter, crypto, config.interface.as_deref());
651
652 tokio::select! {
653 r = run_transport(
654 matter,
655 crypto,
656 &socket,
657 #[cfg(feature = "ble")]
658 btp,
659 ) => r,
660 r = mdns => r,
661 r = responder.run::<4>() => r.map_err(Error::from),
662 () = serve => Ok(()),
663 }
664}
665
666async fn run_transport<C: Crypto>(
668 matter: &Matter<'_>,
669 crypto: C,
670 socket: &async_io::Async<UdpSocket>,
671 #[cfg(feature = "ble")] btp: &rs_matter::transport::network::btp::Btp,
672) -> Result<(), Error> {
673 #[cfg(feature = "ble")]
674 {
675 use rs_matter::transport::network::ChainedNetwork;
676 let mut send = ChainedNetwork::new(|a: &Address| a.is_btp(), btp, socket);
677 let mut recv = ChainedNetwork::new(|a: &Address| a.is_btp(), btp, socket);
678 matter
679 .run(crypto, &mut send, &mut recv, NoNetwork)
680 .await
681 .map_err(Error::from)
682 }
683 #[cfg(not(feature = "ble"))]
684 {
685 matter
686 .run(crypto, socket, socket, NoNetwork)
687 .await
688 .map_err(Error::from)
689 }
690}
691
692struct ReportSink {
695 subs: Rc<Subscriptions>,
696 events: EventBus,
697}
698
699impl ReportDataHandler for ReportSink {
700 async fn handle_report(
701 &self,
702 ctx: impl ReportContext,
703 report: &ReportDataResp<'_>,
704 ) -> Result<(), IMStatusCode> {
705 let sub = ctx.subscription();
706 let node = sub.peer_node_id;
707
708 {
709 let mut by_node = self.subs.by_node.borrow_mut();
710 match by_node.get_mut(&node) {
711 Some(state) if state.id.is_none() || state.id == sub.subscription_id => {
712 state.last_report = Instant::now();
713 }
714 _ => return Err(IMStatusCode::InvalidSubscription),
717 }
718 }
719
720 let mut partial = self.subs.partial.borrow_mut();
721 let collected = partial.entry(node).or_default();
722 collected.add_chunk(node, report);
723 if report.more_chunks.unwrap_or(false) {
724 return Ok(());
725 }
726 let collected = partial.remove(&node).unwrap_or_default();
727 drop(partial);
728
729 if let Some(last) = collected.events.iter().map(|e| e.number).max() {
730 if let Some(state) = self.subs.by_node.borrow_mut().get_mut(&node) {
731 state.last_event = Some(last);
732 }
733 }
734 publish(&self.events, collected);
735 Ok(())
736 }
737}
738
739fn publish(events: &EventBus, collected: Collected) {
740 for a in collected.attributes {
741 events.send(Event::Attribute(a));
742 }
743 for e in collected.events {
744 events.send(Event::Event(e));
745 }
746}
747
748fn now_secs() -> u64 {
749 SystemTime::now()
750 .duration_since(SystemTime::UNIX_EPOCH)
751 .map_or(0, |d| d.as_secs())
752}
753
754struct Hooks<'a> {
756 node: u64,
757 events: &'a EventBus,
758 abort: &'a tokio::sync::Notify,
759}
760
761impl Hooks<'_> {
762 fn emit(&self, step: CommissionStep) {
763 self.events.send(Event::Commissioning {
764 node: self.node,
765 step,
766 });
767 }
768}
769
770impl CommissionHooks for Hooks<'_> {
771 fn step(&self, step: rs_matter::onboard::CommissionStep) {
772 use rs_matter::onboard::CommissionStep as S;
773 let step = match step {
774 S::Pase => CommissionStep::Pase,
775 S::ArmFailSafe => CommissionStep::ArmFailSafe,
776 S::DeviceAttestation => CommissionStep::DeviceAttestation,
777 S::CsrRequest => CommissionStep::CsrRequest,
778 S::AddTrustedRootCertificate => CommissionStep::AddTrustedRootCertificate,
779 S::AddNoc => CommissionStep::AddNoc,
780 S::FindOperational => CommissionStep::FindOperational,
781 S::CommissioningComplete => CommissionStep::CommissioningComplete,
782 S::Cleanup => CommissionStep::Cleanup,
783 };
784 self.events.send(Event::Commissioning {
785 node: self.node,
786 step,
787 });
788 }
789
790 async fn cancelled(&self) {
791 self.abort.notified().await
792 }
793}
794
795impl<C: Crypto + Copy + 'static> Ctx<C> {
796 async fn handle(self: Rc<Self>, job: Job) {
797 match job {
798 Job::Commission(req, r) => {
799 let _ = r.send(self.commission(req).await);
800 }
801 Job::Read(node, path, r) => {
802 let _ = r.send(self.read(node, path).await);
803 }
804 Job::Write(node, ep, cl, at, value, timed, r) => {
805 let _ = r.send(self.write(node, ep, cl, at, &value, timed).await);
806 }
807 Job::Invoke(node, ep, cl, cmd, fields, timed, r) => {
808 let _ = r.send(self.invoke(node, ep, cl, cmd, &fields, timed).await);
809 }
810 Job::OpenWindow(node, timeout, r) => {
811 let _ = r.send(self.open_window(node, timeout).await);
812 }
813 Job::Remove(node, force, r) => {
814 let _ = r.send(self.remove(node, force).await);
815 }
816 Job::Rename(node, name, r) => {
817 let _ = r.send(self.rename(node, name));
818 }
819 Job::Interview(node, r) => {
820 let _ = r.send(self.interview(node).await);
821 }
822 Job::Discover(seconds, r) => {
823 let _ = r.send(self.discover(seconds).await);
824 }
825 Job::Nodes(r) => {
826 let _ = r.send(Ok(self.store.borrow().nodes().cloned().collect()));
827 }
828 Job::AddToGroup(node, ep, group, name, r) => {
829 let _ = r.send(self.add_to_group(node, ep, group, &name).await);
830 }
831 Job::RemoveFromGroup(node, ep, group, r) => {
832 let _ = r.send(self.remove_from_group(node, ep, group).await);
833 }
834 Job::GroupInvoke(group, cl, cmd, fields, r) => {
835 let _ = r.send(self.group_invoke(group, cl, cmd, &fields).await);
836 }
837 Job::AnnounceOta(node, r) => {
838 let _ = r.send(self.announce_ota(node).await);
839 }
840 Job::Abort(r) => {
841 let running = self.commissioning.try_lock().is_err();
844 if running {
845 self.abort.notify_waiters();
846 }
847 let _ = r.send(Ok(running));
848 }
849 }
850 }
851
852 fn known(&self, node: u64) -> Result<Node, Error> {
853 self.store
854 .borrow()
855 .get(node)
856 .cloned()
857 .ok_or_else(|| Error::Invalid(format!("no node {node}")))
858 }
859
860 async fn exchange(&self, node: u64) -> Result<Exchange<'static>, Error> {
863 if let Some(icd) = self.icds.get(node) {
864 let subscribed = self.subs.by_node.borrow().get(&node).is_some_and(|s| {
865 s.id.is_some()
866 && s.last_report.elapsed()
867 < Duration::from_secs(u64::from(s.max_interval)) + Duration::from_secs(30)
868 });
869 if !subscribed && !self.icds.wait_check_in(node, icd.check_in_wait()).await {
870 return Err(Error::Timeout(format!(
871 "node {node:016X} is asleep and did not check in"
872 )));
873 }
874 }
875 Ok(Exchange::initiate(self.matter, self.crypto, self.fab_idx, node).await?)
876 }
877
878 async fn commission(self: &Rc<Self>, req: CommissionRequest) -> Result<Node, Error> {
879 let _one_at_a_time = self.commissioning.lock().await;
880 let onboarding = Onboarding::parse(&req.code)?;
881 if onboarding.custom_flow {
882 log::warn!("the device needs a custom commissioning flow; it may have to be put in pairing mode first");
883 }
884
885 let node_id = self.ca.allocate_node_id().await?;
886 let hooks = Hooks {
887 node: node_id,
888 events: &self.events,
889 abort: &self.abort,
890 };
891 self.events.send(Event::Commissioning {
892 node: node_id,
893 step: CommissionStep::Discovery,
894 });
895
896 let (address, link) = match req.address {
897 Some(addr) => (Address::Udp(addr), None),
898 None => self.locate(&onboarding, req.discovery_timeout).await?,
899 };
900 log::info!("commissioning {address:?} as node {node_id:016X}");
901
902 let signing_key = self.ca.signing_key().ok_or_else(|| {
903 Error::Unsupported(
904 "commissioning with a CA whose key is elsewhere needs rs-matter's commissioner to take an async NOC issuer".into(),
905 )
906 })?;
907 let mut noc_buf = vec![0u8; MAX_CERT_TLV_AND_ASN1_LEN];
908 let mut noc_gen = NocGenerator::create(
909 CanonPkcSecretKeyRef::new(signing_key),
910 self.ca.root_cert(),
911 self.ca.intermediate_cert().unwrap_or(&[]),
912 &mut noc_buf,
913 )?;
914 let mut buf = vec![0u8; MAX_CERT_TLV_LEN];
915 let mut commissioner = Commissioner::new(
916 self.matter,
917 self.crypto,
918 self.fab_idx,
919 &mut noc_gen,
920 &mut buf,
921 );
922
923 if self.config.allow_unverified_attestation {
924 log::warn!("device attestation is not verified (not implemented in rs-matter yet)");
925 }
926 let opts = CommissionOptions {
927 allow_test_attestation: self.config.allow_unverified_attestation,
928 fail_safe_secs: if address.is_btp() { 180 } else { 60 },
931 };
932
933 let commissioned = async {
934 let phase1 = commissioner
935 .commission(
936 address,
937 onboarding.passcode,
938 &opts,
939 node_id,
940 VALID_FOREVER,
941 &hooks,
942 )
943 .await?;
944 if address.is_btp() {
947 let pase = phase1.pase_session_id;
948 if let Err(e) = self.network_commission(pase, &req.networks, &hooks).await {
949 let _ = commissioner.disarm_fail_safe(pase).await;
950 commissioner.end_pase(pase);
951 return Err(e);
952 }
953 }
954 commissioner.complete_via_case(&phase1, &hooks).await?;
955 Ok::<_, Error>(())
956 }
957 .await;
958 if let Some(link) = link {
959 link.close().await;
960 }
961 commissioned?;
962
963 let name = {
964 let store = self.store.borrow();
965 match req.name {
966 Some(name) => name,
967 None => store.unique_name(&Node::default_name(node_id)),
968 }
969 };
970 let node = Node {
971 node_id,
972 name,
973 basic: BasicInfo::default(),
974 endpoints: Default::default(),
975 interviewed: false,
976 commissioned_at: now_secs(),
977 };
978 self.store.borrow_mut().put(node.clone())?;
979 self.events.send(Event::NodeUpdated(node.clone()));
980
981 self.events.send(Event::Commissioning {
982 node: node_id,
983 step: CommissionStep::Interview,
984 });
985 let node = match self.interview(node_id).await {
986 Ok(node) => node,
987 Err(e) => {
988 log::warn!("node {node_id:016X}: interview failed, will retry: {e}");
989 node
990 }
991 };
992 if let Err(e) = self.register_icd(node_id).await {
993 log::warn!("node {node_id:016X}: ICD registration: {e}");
994 }
995 self.start_subscription(node_id, true);
996 Ok(node)
997 }
998
999 #[cfg_attr(not(feature = "ble"), allow(dead_code))]
1004 async fn network_commission(
1005 &self,
1006 pase_session: u32,
1007 networks: &crate::Networks,
1008 hooks: &Hooks<'_>,
1009 ) -> Result<(), Error> {
1010 const WIFI: u64 = 1 << 0;
1011 const THREAD: u64 = 1 << 1;
1012 const ETHERNET: u64 = 1 << 2;
1013
1014 let pase_exchange =
1015 || Exchange::initiate_for_session(self.matter.transport(), self.crypto, pase_session);
1016
1017 hooks.emit(CommissionStep::NetworkSetup);
1018 let features = self
1019 .read_on(
1020 pase_exchange()?,
1021 AttributePath {
1022 endpoint: Some(ROOT_ENDPOINT),
1023 cluster: Some(NETWORK_COMMISSIONING),
1024 attribute: Some(0xFFFC), },
1026 )
1027 .await?
1028 .first()
1029 .and_then(|a| a.value.as_u64())
1030 .ok_or_else(|| {
1031 Error::Invalid("the device has no Network Commissioning cluster".into())
1032 })?;
1033
1034 let (add, add_fields, network_id) = if features & THREAD != 0 {
1035 let dataset = networks.thread_dataset.as_ref().ok_or_else(|| {
1036 Error::Invalid("the device joins a Thread network: give a Thread dataset".into())
1037 })?;
1038 let ext_pan_id = crate::network::thread_extended_pan_id(dataset)?;
1039 log::info!(
1040 "giving the device Thread network {}",
1041 hex::encode(ext_pan_id)
1042 );
1043 (
1044 ADD_THREAD_NETWORK,
1045 json!({ "0": hex::encode(dataset), "1": 1 }),
1046 ext_pan_id.to_vec(),
1047 )
1048 } else if features & WIFI != 0 {
1049 let wifi = networks.wifi.as_ref().ok_or_else(|| {
1050 Error::Invalid(
1051 "the device joins a Wi-Fi network: give its SSID and passphrase".into(),
1052 )
1053 })?;
1054 log::info!(
1055 "giving the device Wi-Fi network {}",
1056 String::from_utf8_lossy(&wifi.ssid)
1057 );
1058 (
1059 ADD_WIFI_NETWORK,
1060 json!({ "0": hex::encode(&wifi.ssid), "1": hex::encode(&wifi.credentials), "2": 1 }),
1061 wifi.ssid.clone(),
1062 )
1063 } else if features & ETHERNET != 0 {
1064 return Ok(());
1065 } else {
1066 return Err(Error::Invalid(format!(
1067 "the device's network interface is not one this controller knows (features {features:#x})"
1068 )));
1069 };
1070
1071 let response = self
1072 .invoke_on(
1073 pase_exchange()?,
1074 ROOT_ENDPOINT,
1075 NETWORK_COMMISSIONING,
1076 add,
1077 &add_fields,
1078 None,
1079 )
1080 .await?;
1081 networking_status("adding the network", &response)?;
1082
1083 hooks.emit(CommissionStep::NetworkConnect);
1084 let response = self
1085 .invoke_on(
1086 pase_exchange()?,
1087 ROOT_ENDPOINT,
1088 NETWORK_COMMISSIONING,
1089 CONNECT_NETWORK,
1090 &json!({ "0": hex::encode(network_id), "1": 2 }),
1091 None,
1092 )
1093 .await?;
1094 networking_status("connecting to the network", &response)
1095 }
1096
1097 async fn locate(
1102 &self,
1103 onboarding: &Onboarding,
1104 timeout: u16,
1105 ) -> Result<(Address, Option<Link>), Error> {
1106 let caps = onboarding.capabilities;
1107 let try_ip = caps.is_none_or(|c| c.on_network);
1108 #[cfg(feature = "ble")]
1109 if let Some(ble) = &self.ble {
1110 let try_ble = caps.is_none_or(|c| c.ble);
1111 if try_ble {
1112 let total = Duration::from_secs(timeout.max(2).into());
1113 if try_ip {
1114 let ip_secs = (timeout / 2).clamp(1, 10);
1115 if let Ok(address) = self.find(onboarding, ip_secs).await {
1116 return Ok((address, None));
1117 }
1118 }
1119 let peer = ble.find(&onboarding.filter(), total).await?;
1120 let (addr, link) = ble.connect(peer).await?;
1121 log::info!("reached the device over Bluetooth ({addr})");
1122 return Ok((Address::Btp(addr), Some(link)));
1123 }
1124 }
1125 if !try_ip {
1126 return Err(Error::Unsupported(
1127 "the device can only be found over Bluetooth, which this controller has not got"
1128 .into(),
1129 ));
1130 }
1131 Ok((self.find(onboarding, timeout).await?, None))
1132 }
1133
1134 async fn find(&self, onboarding: &Onboarding, timeout: u16) -> Result<Address, Error> {
1136 let transport = self.matter.transport();
1137 let query = MdnsBrowseQuery::Commissionable(onboarding.filter());
1138 let deadline = Instant::now() + Duration::from_secs(timeout.max(1).into());
1139
1140 while Instant::now() < deadline {
1141 let mut ids = Vec::new();
1142 transport
1143 .browse(&query, 1000, |m| {
1144 if let MdnsBrowseMatch::Commissionable { id } = m {
1145 ids.push(id);
1146 }
1147 })
1148 .await?;
1149 for id in ids {
1150 match transport.resolve_commissionable_addrs(id).await {
1151 Ok(addrs) if !addrs.is_empty() => return Ok(addrs[0]),
1152 Ok(_) => {}
1153 Err(e) => log::debug!("resolving {id:016X}: {e:?}"),
1154 }
1155 }
1156 }
1157 Err(Error::Timeout(format!(
1158 "no commissionable device with discriminator {:?} answered in {timeout} s",
1159 onboarding.discriminator
1160 )))
1161 }
1162
1163 async fn discover(&self, seconds: u16) -> Result<Vec<Commissionable>, Error> {
1164 let transport = self.matter.transport();
1165 let query = MdnsBrowseQuery::Commissionable(Default::default());
1166 let mut ids = Vec::new();
1167 let deadline = Instant::now() + Duration::from_secs(seconds.max(1).into());
1168 while Instant::now() < deadline {
1169 transport
1170 .browse(&query, 1000, |m| {
1171 if let MdnsBrowseMatch::Commissionable { id } = m {
1172 if !ids.contains(&id) {
1173 ids.push(id);
1174 }
1175 }
1176 })
1177 .await?;
1178 }
1179 let mut out = Vec::new();
1180 for id in ids {
1181 let addresses = match transport.resolve_commissionable_addrs(id).await {
1182 Ok(addrs) => addrs
1183 .iter()
1184 .filter_map(|a| match a {
1185 Address::Udp(sa) => Some(*sa),
1186 _ => None,
1187 })
1188 .collect(),
1189 Err(_) => Vec::new(),
1190 };
1191 out.push(Commissionable {
1192 instance: format!("{id:016X}"),
1193 addresses,
1194 });
1195 }
1196 Ok(out)
1197 }
1198
1199 async fn read(&self, node: u64, path: AttributePath) -> Result<Vec<AttributeValue>, Error> {
1200 self.known(node)?;
1201 let exchange = self.exchange(node).await?;
1202 let mut values = self.read_on(exchange, path).await?;
1203 for v in &mut values {
1204 v.node = node;
1205 }
1206 Ok(values)
1207 }
1208
1209 async fn read_on(
1212 &self,
1213 exchange: Exchange<'static>,
1214 path: AttributePath,
1215 ) -> Result<Vec<AttributeValue>, Error> {
1216 let paths = [AttrPath::from_gp(&GenericPath::new(
1217 path.endpoint,
1218 path.cluster,
1219 path.attribute,
1220 ))];
1221 let mut chunk = exchange
1222 .read_with(|b| b.attr_requests_from(&paths)?.fabric_filtered(true)?.end())
1223 .await?;
1224 let mut collected = Collected::default();
1225 loop {
1226 collected.add_chunk(0, &chunk.response()?);
1227 match chunk.complete().await? {
1228 Some(next) => chunk = next,
1229 None => break,
1230 }
1231 }
1232 Ok(collected.attributes)
1233 }
1234
1235 async fn write(
1236 &self,
1237 node: u64,
1238 endpoint: u16,
1239 cluster: u32,
1240 attribute: u32,
1241 value: &Value,
1242 timed: Option<u16>,
1243 ) -> Result<(), Error> {
1244 self.known(node)?;
1245 let attr = matter_model::cluster(cluster).and_then(|c| c.attribute(attribute));
1246 if let Some(attr) = attr {
1247 if !attr.writable {
1248 return Err(Error::Invalid(format!("{} is read-only", attr.name)));
1249 }
1250 }
1251 let shape = attr.map_or(Shape::ANY, |a| a.shape());
1252 let data = encode_to_vec(shape, value, MAX_PAYLOAD)?;
1253 let timed = timed.or(attr.filter(|a| a.timed_write).map(|_| TIMED_MS));
1254
1255 let exchange = self.exchange(node).await?;
1256 let handle = exchange
1257 .write_with(timed, |b| {
1258 b.timed_request(timed.is_some())?
1259 .write_requests()?
1260 .push()?
1261 .path(endpoint, cluster, attribute)?
1262 .data(|w| {
1263 TLVElement::new(&data).to_tlv(&TLVTag::Context(AttrDataTag::Data as u8), w)
1264 })?
1265 .end()?
1266 .end()?
1267 .end()
1268 })
1269 .await?;
1270 for status in items(&handle.response()?.write_responses)? {
1271 let status = status?;
1272 if status.status.status != IMStatusCode::Success {
1273 return Err(Error::Status(format!(
1274 "write {endpoint}/{cluster:#06x}/{attribute:#06x}: {:?}",
1275 status.status.status
1276 )));
1277 }
1278 }
1279 Ok(())
1280 }
1281
1282 async fn invoke(
1283 &self,
1284 node: u64,
1285 endpoint: u16,
1286 cluster: u32,
1287 command: u32,
1288 fields: &Value,
1289 timed: Option<u16>,
1290 ) -> Result<Value, Error> {
1291 self.known(node)?;
1292 let exchange = self.exchange(node).await?;
1293 self.invoke_on(exchange, endpoint, cluster, command, fields, timed)
1294 .await
1295 }
1296
1297 async fn invoke_on(
1300 &self,
1301 exchange: Exchange<'static>,
1302 endpoint: u16,
1303 cluster: u32,
1304 command: u32,
1305 fields: &Value,
1306 timed: Option<u16>,
1307 ) -> Result<Value, Error> {
1308 let model = matter_model::cluster(cluster);
1309 let cmd = model.and_then(|c| c.command(command));
1310 let shape = match cmd {
1311 Some(c) => c.request.map_or(Shape::ANY, |s| s.shape()),
1312 None => Shape::ANY,
1313 };
1314 let fields = if fields.is_null() {
1315 json!({})
1316 } else {
1317 fields.clone()
1318 };
1319 let data = encode_to_vec(shape, &fields, MAX_PAYLOAD)?;
1320 let timed = timed.or(cmd.filter(|c| c.timed).map(|_| TIMED_MS));
1321
1322 let mut chunk = exchange
1323 .invoke_with(timed, |b| {
1327 b.timed_request(timed.is_some())?
1328 .invoke_requests()?
1329 .push()?
1330 .path(endpoint, cluster, command)?
1331 .data(|w| {
1332 TLVElement::new(&data).to_tlv(&TLVTag::Context(CmdDataTag::Data as u8), w)
1333 })?
1334 .end()?
1335 .end()?
1336 .end()
1337 })
1338 .await?;
1339
1340 let mut result = Value::Null;
1341 loop {
1342 if let Some(resp) = chunk.response()? {
1343 if let Some(responses) = &resp.invoke_responses {
1344 for r in items(responses)? {
1345 match r? {
1346 CmdResp::Cmd(data) => {
1347 let shape = data
1348 .path
1349 .cmd
1350 .and_then(|id| model.and_then(|c| c.response(id)))
1351 .map_or(Shape::ANY, |s| s.shape());
1352 result = matter_model::to_json(&data.data, shape)?;
1353 }
1354 CmdResp::Status(s) if s.status.status != IMStatusCode::Success => {
1355 return Err(Error::Status(format!(
1356 "invoke {endpoint}/{cluster:#06x}/{command:#06x}: {:?}{}",
1357 s.status.status,
1358 s.status
1359 .cluster_status
1360 .map(|c| format!(" (cluster status {c})"))
1361 .unwrap_or_default()
1362 )));
1363 }
1364 CmdResp::Status(_) => {}
1365 }
1366 }
1367 }
1368 }
1369 match chunk.complete().await? {
1370 Some(next) => chunk = next,
1371 None => break,
1372 }
1373 }
1374 Ok(result)
1375 }
1376
1377 async fn interview(&self, node_id: u64) -> Result<Node, Error> {
1378 let mut node = self.known(node_id)?;
1379
1380 let basic = self
1381 .read(
1382 node_id,
1383 AttributePath {
1384 endpoint: Some(ROOT_ENDPOINT),
1385 cluster: Some(BASIC_INFORMATION),
1386 attribute: None,
1387 },
1388 )
1389 .await?;
1390 let get = |id: u32| basic.iter().find(|a| a.attribute == id).map(|a| &a.value);
1391 let string = |id: u32| get(id).and_then(Value::as_str).map(str::to_string);
1392 let number = |id: u32| {
1393 get(id)
1394 .and_then(Value::as_u64)
1395 .and_then(|v| u16::try_from(v).ok())
1396 };
1397 node.basic = BasicInfo {
1398 vendor_name: string(1),
1399 vendor_id: number(2),
1400 product_name: string(3),
1401 product_id: number(4),
1402 node_label: string(5).filter(|s| !s.is_empty()),
1403 hardware_version: string(8),
1404 software_version: string(0x0A),
1405 serial_number: string(0x0F),
1406 unique_id: string(0x12),
1407 };
1408
1409 let descriptor = self
1410 .read(
1411 node_id,
1412 AttributePath {
1413 endpoint: None,
1414 cluster: Some(DESCRIPTOR),
1415 attribute: None,
1416 },
1417 )
1418 .await?;
1419 node.endpoints.clear();
1420 for a in descriptor.iter().filter(|a| a.status.is_none()) {
1421 let ep = node
1422 .endpoints
1423 .entry(a.endpoint)
1424 .or_insert_with(Endpoint::default);
1425 let items = a.value.as_array().map(Vec::as_slice).unwrap_or_default();
1426 match a.attribute {
1427 0 => {
1428 ep.device_types = items
1429 .iter()
1430 .filter_map(|d| {
1431 Some(DeviceType {
1432 id: d.get("deviceType")?.as_u64()?.try_into().ok()?,
1433 revision: d.get("revision")?.as_u64()?.try_into().ok()?,
1434 })
1435 })
1436 .collect()
1437 }
1438 1 => ep.server_clusters = numbers(items),
1439 2 => ep.client_clusters = numbers(items),
1440 3 => ep.parts = numbers(items),
1441 _ => {}
1442 }
1443 }
1444 node.interviewed = true;
1445
1446 self.store.borrow_mut().put(node.clone())?;
1447 self.events.send(Event::NodeUpdated(node.clone()));
1448 Ok(node)
1449 }
1450
1451 async fn open_window(&self, node_id: u64, timeout: u16) -> Result<CommissioningWindow, Error> {
1452 let node = self.known(node_id)?;
1453 if !(180..=900).contains(&timeout) {
1454 return Err(Error::Invalid(
1455 "a commissioning window lasts 180 to 900 seconds".into(),
1456 ));
1457 }
1458
1459 let passcode = random_passcode();
1460 let discriminator = rand::random::<u16>() & 0x0FFF;
1461 let salt: [u8; 32] = rand::random();
1462 const ITERATIONS: u32 = 1000;
1463
1464 let password = Spake2pVerifierPassword::new_from_ref(Spake2pVerifierPasswordRef::new(
1465 &passcode.to_le_bytes(),
1466 ));
1467 let mut verifier = rs_matter::pairing::Spake2pVerifierStr::new();
1468 rs_matter::sc::pase::spake2p::Spake2P::compute_verifier(
1469 self.crypto,
1470 password.reference(),
1471 ITERATIONS,
1472 &salt,
1473 &mut verifier,
1474 )?;
1475
1476 self.invoke(
1477 node_id,
1478 ROOT_ENDPOINT,
1479 ADMINISTRATOR_COMMISSIONING,
1480 0x00, &json!({
1482 "0": timeout,
1483 "1": hex::encode(verifier.access()),
1484 "2": discriminator,
1485 "3": ITERATIONS,
1486 "4": hex::encode(salt),
1487 }),
1488 Some(TIMED_MS),
1489 )
1490 .await?;
1491
1492 let comm = BasicCommData {
1493 password,
1494 discriminator,
1495 };
1496 let manual_code = comm.compute_pretty_pairing_code().to_string();
1497 let qr = QrPayload::new(
1498 DiscoveryCapabilities::IP,
1499 CommFlowType::Standard,
1500 comm,
1501 node.basic.vendor_id.unwrap_or(0),
1502 node.basic.product_id.unwrap_or(0),
1503 "",
1504 no_optional_data,
1505 );
1506 let mut qr_buf = [0u8; 128];
1507 let (qr_code, _) = qr.as_str(&mut qr_buf)?;
1508
1509 Ok(CommissioningWindow {
1510 node: node_id,
1511 manual_code,
1512 qr_code: qr_code.to_string(),
1513 discriminator,
1514 timeout,
1515 })
1516 }
1517
1518 async fn remove(&self, node_id: u64, force: bool) -> Result<(), Error> {
1519 self.known(node_id)?;
1520 let left = async {
1521 let index = self
1522 .read(
1523 node_id,
1524 AttributePath {
1525 endpoint: Some(ROOT_ENDPOINT),
1526 cluster: Some(OPERATIONAL_CREDENTIALS),
1527 attribute: Some(5), },
1529 )
1530 .await?
1531 .first()
1532 .and_then(|a| a.value.as_u64())
1533 .ok_or_else(|| Error::Invalid("the node did not say its fabric index".into()))?;
1534 self.invoke(
1535 node_id,
1536 ROOT_ENDPOINT,
1537 OPERATIONAL_CREDENTIALS,
1538 0x0A, &json!({ "0": index }),
1540 None,
1541 )
1542 .await
1543 .map(|_| ())
1544 }
1545 .await;
1546
1547 match left {
1548 Ok(()) => {}
1549 Err(Error::Matter(e)) if force || e.contains("Timeout") => {
1552 log::warn!("node {node_id:016X}: RemoveFabric: {e}");
1553 }
1554 Err(e) if force => log::warn!("node {node_id:016X}: RemoveFabric: {e}"),
1555 Err(e) => return Err(e),
1556 }
1557
1558 if let Some(task) = self.tasks.borrow_mut().remove(&node_id) {
1559 task.abort();
1560 }
1561 self.subs.by_node.borrow_mut().remove(&node_id);
1562 self.icds.forget(node_id)?;
1563 self.matter.with_state(|state| {
1564 state.sessions.remove_case_for_peer(self.fab_idx, node_id);
1565 });
1566 self.store.borrow_mut().remove(node_id)?;
1567 self.events.send(Event::NodeRemoved { node: node_id });
1568 Ok(())
1569 }
1570
1571 fn uses_groupcast(&self, node: u64) -> Result<bool, Error> {
1574 Ok(self
1575 .known(node)?
1576 .endpoints
1577 .get(&ROOT_ENDPOINT)
1578 .is_some_and(|ep| ep.server_clusters.contains(&GROUPCAST)))
1579 }
1580
1581 async fn add_to_group(
1582 &self,
1583 node: u64,
1584 endpoint: u16,
1585 group: u16,
1586 name: &str,
1587 ) -> Result<(), Error> {
1588 if group == 0 {
1589 return Err(Error::Invalid("group 0 is not a group".into()));
1590 }
1591 let (key_set, epoch_key, start) = {
1592 let g = self.groups.borrow();
1593 (g.key_set_id, g.epoch_key, g.epoch_start_time)
1594 };
1595
1596 if self.uses_groupcast(node)? {
1597 self.invoke(
1600 node,
1601 ROOT_ENDPOINT,
1602 GROUPCAST,
1603 0x00, &json!({
1605 "groupID": group,
1606 "endpoints": [endpoint],
1607 "keySetID": key_set,
1608 "key": hex::encode(epoch_key),
1609 "useAuxiliaryACL": true,
1612 "mcastAddrPolicy": 1, }),
1614 None,
1615 )
1616 .await?;
1617 } else {
1618 self.join_group_legacy(node, endpoint, group, name, key_set, epoch_key, start)
1619 .await?;
1620 }
1621
1622 self.groups
1623 .borrow_mut()
1624 .add(group, &self.config.state_dir.join("groups.json"))?;
1625 self.matter.with_state(|state| {
1626 let fabric = state.fabrics.fabric_mut(self.fab_idx)?;
1627 fabric.groups_mut().key_map_set_group(group, key_set)
1628 })?;
1629 Ok(())
1630 }
1631
1632 #[allow(clippy::too_many_arguments)]
1635 async fn join_group_legacy(
1636 &self,
1637 node: u64,
1638 endpoint: u16,
1639 group: u16,
1640 name: &str,
1641 key_set: u16,
1642 epoch_key: [u8; 16],
1643 start: u64,
1644 ) -> Result<(), Error> {
1645 self.invoke(
1647 node,
1648 ROOT_ENDPOINT,
1649 GROUP_KEY_MANAGEMENT,
1650 0x00, &json!({ "groupKeySet": {
1652 "groupKeySetID": key_set,
1653 "groupKeySecurityPolicy": 0, "epochKey0": hex::encode(epoch_key),
1655 "epochStartTime0": start,
1656 "groupKeyMulticastPolicy": 0, } }),
1658 None,
1659 )
1660 .await?;
1661
1662 let current = self
1665 .read(
1666 node,
1667 AttributePath {
1668 endpoint: Some(ROOT_ENDPOINT),
1669 cluster: Some(GROUP_KEY_MANAGEMENT),
1670 attribute: Some(0), },
1672 )
1673 .await?;
1674 let mut map: Vec<Value> = current
1675 .first()
1676 .and_then(|a| a.value.as_array().cloned())
1677 .unwrap_or_default()
1678 .into_iter()
1679 .filter(|m| m.get("groupId").and_then(Value::as_u64) != Some(u64::from(group)))
1680 .map(|m| json!({ "1": m["groupId"], "2": m["groupKeySetID"], "254": 0 }))
1681 .collect();
1682 map.push(json!({ "1": group, "2": key_set, "254": 0 }));
1683 self.write(
1684 node,
1685 ROOT_ENDPOINT,
1686 GROUP_KEY_MANAGEMENT,
1687 0,
1688 &Value::Array(map),
1689 None,
1690 )
1691 .await?;
1692
1693 let acl = self
1697 .read(
1698 node,
1699 AttributePath {
1700 endpoint: Some(ROOT_ENDPOINT),
1701 cluster: Some(ACCESS_CONTROL),
1702 attribute: Some(0), },
1704 )
1705 .await?;
1706 let mut entries: Vec<Value> = acl
1709 .first()
1710 .and_then(|a| a.value.as_array().cloned())
1711 .unwrap_or_default()
1712 .into_iter()
1713 .filter(|e| e.get("auxiliaryType").is_none_or(Value::is_null))
1714 .map(|e| {
1715 json!({
1716 "privilege": e["privilege"],
1717 "authMode": e["authMode"],
1718 "subjects": e["subjects"],
1719 "targets": e["targets"],
1720 "fabricIndex": 0,
1721 })
1722 })
1723 .collect();
1724 let entry = json!({
1725 "privilege": 3, "authMode": 3, "subjects": [group],
1728 "targets": [{ "cluster": null, "endpoint": endpoint, "deviceType": null }],
1729 "fabricIndex": 0,
1730 });
1731 let has = |e: &Value| {
1732 e["authMode"] == entry["authMode"]
1733 && e["subjects"] == entry["subjects"]
1734 && e["targets"] == entry["targets"]
1735 };
1736 if !entries.iter().any(has) {
1737 entries.push(entry);
1738 self.write(
1739 node,
1740 ROOT_ENDPOINT,
1741 ACCESS_CONTROL,
1742 0,
1743 &Value::Array(entries),
1744 None,
1745 )
1746 .await?;
1747 }
1748
1749 let response = self
1751 .invoke(
1752 node,
1753 endpoint,
1754 GROUPS,
1755 0x00,
1756 &json!({ "0": group, "1": name }),
1757 None,
1758 )
1759 .await?;
1760 match response.get("status").and_then(Value::as_u64) {
1761 Some(0) | None => Ok(()),
1762 Some(status) => Err(Error::Status(format!("AddGroup: status {status:#04x}"))),
1763 }
1764 }
1765
1766 async fn remove_from_group(&self, node: u64, endpoint: u16, group: u16) -> Result<(), Error> {
1767 if self.uses_groupcast(node)? {
1768 self.invoke(
1769 node,
1770 ROOT_ENDPOINT,
1771 GROUPCAST,
1772 0x01, &json!({ "groupID": group, "endpoints": [endpoint] }),
1774 None,
1775 )
1776 .await?;
1777 return Ok(());
1778 }
1779 let response = self
1780 .invoke(node, endpoint, GROUPS, 0x03, &json!({ "0": group }), None)
1781 .await?;
1782 match response.get("status").and_then(Value::as_u64) {
1783 Some(0) | None => Ok(()),
1784 Some(status) => Err(Error::Status(format!("RemoveGroup: status {status:#04x}"))),
1785 }
1786 }
1787
1788 async fn register_icd(&self, node: u64) -> Result<(), Error> {
1791 let serves = self
1792 .known(node)?
1793 .endpoints
1794 .get(&ROOT_ENDPOINT)
1795 .is_some_and(|e| e.server_clusters.contains(&ICD_MANAGEMENT));
1796 if !serves {
1797 return Ok(());
1798 }
1799 const CHECK_IN_PROTOCOL: u64 = 0x1;
1800 if self.read_number(node, ICD_MANAGEMENT, 0xFFFC).await? & CHECK_IN_PROTOCOL == 0 {
1801 return Ok(());
1802 }
1803 let idle_mode_duration = self.read_number(node, ICD_MANAGEMENT, 0x0000).await? as u32;
1804 let active_mode_duration = self.read_number(node, ICD_MANAGEMENT, 0x0001).await? as u32;
1805 let key: [u8; 16] = rand::random();
1806 let me = self
1807 .matter
1808 .with_state(|state| state.fabrics.fabric(self.fab_idx).map(|f| f.node_id()))?;
1809 let response = self
1810 .invoke(
1811 node,
1812 ROOT_ENDPOINT,
1813 ICD_MANAGEMENT,
1814 REGISTER_CLIENT,
1815 &json!({
1816 "checkInNodeID": me,
1817 "monitoredSubject": me,
1818 "key": hex::encode(key),
1819 "clientType": 0,
1821 }),
1822 None,
1823 )
1824 .await?;
1825 let start_counter = response
1826 .get("ICDCounter")
1827 .and_then(Value::as_u64)
1828 .ok_or_else(|| Error::Status("RegisterClient: no ICDCounter".into()))?
1829 as u32;
1830 log::info!(
1831 "node {node:016X}: registered for Check-Ins (sleeps up to {idle_mode_duration} s)"
1832 );
1833 self.icds.register(
1834 node,
1835 Registration {
1836 key,
1837 start_counter,
1838 last_counter: None,
1839 idle_mode_duration,
1840 active_mode_duration,
1841 },
1842 )
1843 }
1844
1845 async fn read_number(&self, node: u64, cluster: u32, attribute: u32) -> Result<u64, Error> {
1847 let values = self
1848 .read(
1849 node,
1850 AttributePath {
1851 endpoint: Some(ROOT_ENDPOINT),
1852 cluster: Some(cluster),
1853 attribute: Some(attribute),
1854 },
1855 )
1856 .await?;
1857 values
1858 .first()
1859 .and_then(|v| v.value.as_u64())
1860 .ok_or_else(|| Error::Status(format!("{cluster:#06x}/{attribute:#06x}: no value")))
1861 }
1862
1863 async fn announce_ota(&self, node: u64) -> Result<Option<OtaImage>, Error> {
1864 let known = self.known(node)?;
1865 let requestor = known
1866 .endpoints
1867 .iter()
1868 .find(|(_, e)| e.server_clusters.contains(&OTA_REQUESTOR))
1869 .map(|(id, _)| *id)
1870 .ok_or_else(|| Error::Unsupported(format!("node {node} has no OTA Requestor")))?;
1871 let vendor_id = self.read_number(node, BASIC_INFORMATION, 0x0002).await? as u16;
1872 let product_id = self.read_number(node, BASIC_INFORMATION, 0x0004).await? as u16;
1873 let version = self.read_number(node, BASIC_INFORMATION, 0x0009).await? as u32;
1874
1875 let images = crate::ota::list(&self.config.ota_dir)?;
1876 let Some(image) = crate::ota::best(&images, vendor_id, product_id, version).cloned() else {
1877 return Ok(None);
1878 };
1879 let info = self.matter.with_state(|state| {
1880 state
1881 .fabrics
1882 .fabric(self.fab_idx)
1883 .map(|f| (f.node_id(), f.vendor_id()))
1884 })?;
1885 self.invoke(
1886 node,
1887 requestor,
1888 OTA_REQUESTOR,
1889 ANNOUNCE_OTA_PROVIDER,
1890 &json!({
1891 "providerNodeID": info.0,
1892 "vendorID": info.1,
1893 "announcementReason": 2,
1896 "endpoint": ROOT_ENDPOINT,
1897 }),
1898 None,
1899 )
1900 .await?;
1901 Ok(Some(image))
1902 }
1903
1904 async fn group_invoke(
1905 &self,
1906 group: u16,
1907 cluster: u32,
1908 command: u32,
1909 fields: &Value,
1910 ) -> Result<(), Error> {
1911 use rs_matter::im::CmdPath;
1912
1913 if !self.groups.borrow().groups.contains(&group) {
1914 return Err(Error::Invalid(format!(
1915 "no device has been put in group {group}"
1916 )));
1917 }
1918 let shape = matter_model::cluster(cluster)
1919 .and_then(|c| c.command(command))
1920 .and_then(|c| c.request)
1921 .map_or(Shape::ANY, |s| s.shape());
1922 let fields = if fields.is_null() {
1923 json!({})
1924 } else {
1925 fields.clone()
1926 };
1927 let data = encode_to_vec(shape, &fields, MAX_PAYLOAD)?;
1928 let exchange =
1929 Exchange::initiate_group(self.matter, self.crypto, self.kv, self.fab_idx, group)?;
1930 exchange
1931 .group_invoke_with(|b| {
1932 b.push()?
1933 .path_from(&CmdPath::new(None, Some(cluster), Some(command)))?
1934 .data(|w| {
1935 TLVElement::new(&data).to_tlv(&TLVTag::Context(CmdDataTag::Data as u8), w)
1936 })?
1937 .end()
1938 })
1939 .await?;
1940 Ok(())
1941 }
1942
1943 fn rename(&self, node_id: u64, name: String) -> Result<Node, Error> {
1944 if name.is_empty() || name.contains(['/', '#', '+']) {
1945 return Err(Error::Invalid(
1946 "a name must not be empty or contain /, # or +".into(),
1947 ));
1948 }
1949 let mut node = self.known(node_id)?;
1950 node.name = name;
1951 self.store.borrow_mut().put(node.clone())?;
1952 self.events.send(Event::NodeUpdated(node.clone()));
1953 Ok(node)
1954 }
1955
1956 fn start_subscription(self: &Rc<Self>, node_id: u64, awake: bool) {
1961 let ctx = self.clone();
1962 let task = tokio::task::spawn_local(async move { ctx.subscription(node_id, awake).await });
1963 if let Some(old) = self.tasks.borrow_mut().insert(node_id, task) {
1964 old.abort();
1965 }
1966 }
1967
1968 async fn subscription(self: Rc<Self>, node: u64, awake: bool) {
1969 let mut backoff = Duration::from_secs(1);
1970 let mut online = false;
1971 let mut wait_check_in = !awake;
1973 loop {
1974 if wait_check_in {
1975 if let Some(icd) = self.icds.get(node) {
1976 if !self.icds.wait_check_in(node, icd.check_in_wait()).await {
1977 log::info!("node {node:016X}: no Check-In; trying anyway");
1978 }
1979 }
1980 }
1981 match self.subscribe(node).await {
1982 Ok(max_interval) => {
1983 backoff = Duration::from_secs(1);
1984 if !online {
1985 online = true;
1986 self.events.send(Event::Availability { node, online });
1987 }
1988 if !self.node_interviewed(node) {
1989 if let Err(e) = self.interview(node).await {
1990 log::warn!("node {node:016X}: interview: {e}");
1991 }
1992 }
1993 let grace =
1996 Duration::from_secs(u64::from(max_interval)) + Duration::from_secs(30);
1997 loop {
1998 tokio::time::sleep(Duration::from_secs(5)).await;
1999 let last = self.subs.by_node.borrow().get(&node).map(|s| s.last_report);
2000 match last {
2001 Some(last) if last.elapsed() <= grace => {}
2002 _ => break,
2003 }
2004 }
2005 log::info!("node {node:016X}: subscription lapsed, renewing");
2006 wait_check_in = true;
2007 }
2008 Err(e) => {
2009 log::info!("node {node:016X}: subscribe: {e}; retrying in {backoff:?}");
2010 if online {
2011 online = false;
2012 self.events.send(Event::Availability { node, online });
2013 }
2014 if self.icds.get(node).is_some() {
2015 wait_check_in = true;
2016 continue;
2017 }
2018 tokio::time::sleep(backoff).await;
2019 backoff = (backoff * 2).min(Duration::from_secs(300));
2020 }
2021 }
2022 }
2023 }
2024
2025 fn node_interviewed(&self, node: u64) -> bool {
2026 self.store.borrow().get(node).is_some_and(|n| n.interviewed)
2027 }
2028
2029 async fn subscribe(&self, node: u64) -> Result<u16, Error> {
2032 let last_event = {
2033 let mut by_node = self.subs.by_node.borrow_mut();
2034 let state = by_node.entry(node).or_insert(SubState {
2035 id: None,
2036 last_report: Instant::now(),
2037 last_event: None,
2038 max_interval: 0,
2039 });
2040 state.id = None;
2042 state.last_event
2043 };
2044
2045 let attrs = [AttrPath::from_gp(&GenericPath::new(None, None, None))];
2046 let events = [EventPath::from_gp(&GenericPath::new(None, None, None))];
2047 let filters = last_event.map(|n| {
2048 [EventFilter {
2049 node: None,
2050 event_min: Some(n + 1),
2051 }]
2052 });
2053 let max_ceil = match self.icds.get(node) {
2055 Some(icd) => self
2056 .config
2057 .max_report_interval
2058 .max(u16::try_from(icd.idle_mode_duration).unwrap_or(u16::MAX)),
2059 None => self.config.max_report_interval,
2060 };
2061
2062 let exchange = Exchange::initiate(self.matter, self.crypto, self.fab_idx, node).await?;
2063 let mut chunk = exchange
2064 .subscribe_with(|b| {
2065 let b = b
2066 .keep_subs(true)?
2067 .min_int_floor(0)?
2068 .max_int_ceil(max_ceil)?
2069 .attr_requests_from(&attrs)?
2070 .event_requests_from(&events)?;
2071 match &filters {
2072 Some(f) => b.event_filters_from(f)?.fabric_filtered(true)?.end(),
2073 None => b.fabric_filtered(true)?.end(),
2074 }
2075 })
2076 .await?;
2077
2078 let mut collected = Collected::default();
2079 let established = loop {
2080 collected.add_chunk(node, &chunk.response()?);
2081 match chunk.complete().await? {
2082 SubscribeOutcome::NextChunk(next) => chunk = next,
2083 SubscribeOutcome::Established(est) => break est,
2084 }
2085 };
2086
2087 if let Some(state) = self.subs.by_node.borrow_mut().get_mut(&node) {
2088 state.id = Some(established.subscription_id);
2089 state.max_interval = established.max_int;
2090 state.last_report = Instant::now();
2091 if let Some(last) = collected.events.iter().map(|e| e.number).max() {
2092 state.last_event = Some(last);
2093 }
2094 }
2095 publish(&self.events, collected);
2096 Ok(established.max_int)
2097 }
2098}
2099
2100fn networking_status(doing: &str, response: &Value) -> Result<(), Error> {
2103 let status = response
2104 .get("networkingStatus")
2105 .or_else(|| response.get("0"))
2106 .and_then(Value::as_u64);
2107 match status {
2108 Some(0) => Ok(()),
2109 Some(code) => {
2110 let name = matter_model::cluster(NETWORK_COMMISSIONING)
2111 .and_then(|c| c.response(0x05))
2112 .and_then(|s| s.field(0))
2113 .and_then(|f| match f.ty {
2114 matter_model::Type::Enum(e) => e.name_of(code),
2115 _ => None,
2116 })
2117 .unwrap_or("unknown");
2118 let debug = response
2119 .get("debugText")
2120 .and_then(Value::as_str)
2121 .unwrap_or_default();
2122 Err(Error::Status(format!("{doing}: {name} ({code}) {debug}")))
2123 }
2124 None => Err(Error::Status(format!(
2125 "{doing}: no networking status in {response}"
2126 ))),
2127 }
2128}
2129
2130fn numbers<T: TryFrom<u64>>(items: &[Value]) -> Vec<T> {
2131 items
2132 .iter()
2133 .filter_map(|v| v.as_u64().and_then(|v| T::try_from(v).ok()))
2134 .collect()
2135}
2136
2137fn random_passcode() -> u32 {
2140 const INVALID: [u32; 12] = [
2141 0, 11111111, 22222222, 33333333, 44444444, 55555555, 66666666, 77777777, 88888888,
2142 99999999, 12345678, 87654321,
2143 ];
2144 loop {
2145 let p = 1 + rand::random::<u32>() % 99_999_998;
2146 if !INVALID.contains(&p) {
2147 return p;
2148 }
2149 }
2150}
2151
2152#[cfg(test)]
2153mod tests {
2154 use super::*;
2155
2156 #[test]
2158 fn group_requests_encode() {
2159 let gkm = matter_model::cluster(GROUP_KEY_MANAGEMENT).unwrap();
2160 let req = gkm.command(0x00).unwrap().request.unwrap();
2161 encode_to_vec(
2162 req.shape(),
2163 &json!({ "groupKeySet": {
2164 "groupKeySetID": 0x4D42,
2165 "groupKeySecurityPolicy": 0,
2166 "epochKey0": "00112233445566778899aabbccddeeff",
2167 "epochStartTime0": 1,
2168 "groupKeyMulticastPolicy": 0,
2169 } }),
2170 MAX_PAYLOAD,
2171 )
2172 .unwrap();
2173 let map = gkm.attribute(0).unwrap();
2174 encode_to_vec(
2175 map.shape(),
2176 &json!([{ "1": 257, "2": 0x4D42, "254": 0 }]),
2177 MAX_PAYLOAD,
2178 )
2179 .unwrap();
2180 let add = matter_model::cluster(GROUPS)
2181 .unwrap()
2182 .command(0x00)
2183 .unwrap()
2184 .request
2185 .unwrap();
2186 encode_to_vec(add.shape(), &json!({ "0": 257, "1": "e2e" }), MAX_PAYLOAD).unwrap();
2187 }
2188
2189 #[test]
2190 fn passcodes_are_valid() {
2191 for _ in 0..1000 {
2192 let p = random_passcode();
2193 assert!((1..=99_999_998).contains(&p));
2194 }
2195 }
2196}