Skip to main content

zwave_host/
inclusion.rs

1//! Inclusion and exclusion, the S2 and S0 key exchanges, and SmartStart.
2
3use crate::controller::{Controller, RxSecurity, TxSecurity};
4use crate::node::{InterviewStage, NodeRecord};
5use crate::{Error, Event, NodeId, SecurityClass};
6use std::time::Duration;
7use tokio::sync::{mpsc, oneshot};
8use tracing::{debug, info, warn};
9use zwave_cc::{security, security_2, Command};
10use zwave_security::dsk::{apply_pin, Dsk};
11use zwave_security::kex::{bootstrap_keys, KexFail, ECDH_CURVE25519, KEX_SCHEME_1};
12use zwave_security::provisioning::{Entry, EntryStatus};
13use zwave_security::s2::KeyId;
14use zwave_serial::message::{add_mode, AddNodeStatus, NodeInfo, RemoveNodeStatus};
15use zwave_serial::{DataFrame, FunctionId as F, Request};
16
17/// Which keys to grant a joining S2 node.
18#[derive(Debug, Clone, PartialEq, Eq, Default)]
19pub enum GrantPolicy {
20    /// Ask with [`Event::GrantSecurityClasses`] and wait for
21    /// [`Controller::grant_security_classes`].
22    #[default]
23    Ask,
24    /// Grant whatever the node requests.
25    Requested,
26    /// Grant these (those the node also requests).
27    Only(Vec<SecurityClass>),
28}
29
30/// How to include a node.
31#[derive(Debug, Clone, Default)]
32pub struct InclusionOptions {
33    /// Keys to grant.
34    pub grant: GrantPolicy,
35    /// The DSK PIN, if known up front; otherwise [`Event::ValidateDsk`] asks.
36    pub pin: Option<u16>,
37    /// Include without any security.
38    pub insecure: bool,
39    /// How long to wait for a node (the configured default if `None`).
40    pub timeout: Option<Duration>,
41}
42
43/// The outcome of an inclusion.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct InclusionResult {
46    /// The new node.
47    pub node: NodeId,
48    /// Granted security classes, highest first.
49    pub security: Vec<SecurityClass>,
50    /// Why security failed, if it did (the node is then included insecurely).
51    pub security_error: Option<String>,
52}
53
54#[derive(Default)]
55pub(crate) struct InclusionState {
56    busy: bool,
57    add_tx: Option<mpsc::Sender<AddNodeStatus>>,
58    remove_tx: Option<mpsc::Sender<RemoveNodeStatus>>,
59    replace_tx: Option<mpsc::Sender<u8>>,
60    cancel: Option<oneshot::Sender<()>>,
61    grant: Option<oneshot::Sender<Vec<SecurityClass>>>,
62    pin: Option<oneshot::Sender<Option<u16>>>,
63    listening: bool,
64}
65
66struct Busy<'a>(&'a Controller);
67
68impl Drop for Busy<'_> {
69    fn drop(&mut self) {
70        let mut st = self.0.inner.inclusion.lock().expect("lock");
71        st.busy = false;
72        st.add_tx = None;
73        st.remove_tx = None;
74        st.replace_tx = None;
75        st.cancel = None;
76        st.grant = None;
77        st.pin = None;
78    }
79}
80
81const KEX_TIMEOUT: Duration = Duration::from_secs(10);
82
83fn s2_cmd(c: impl Into<Command>) -> Vec<u8> {
84    c.into().encode()
85}
86
87impl Controller {
88    pub(crate) fn on_add_node_status(&self, payload: &[u8]) {
89        match AddNodeStatus::parse(payload, self.inner.nid) {
90            Ok(s) => {
91                let tx = self.inner.inclusion.lock().expect("lock").add_tx.clone();
92                match tx {
93                    Some(tx) => {
94                        let _ = tx.try_send(s);
95                    }
96                    None => debug!("add node status {s:?} with no inclusion running"),
97                }
98            }
99            Err(e) => debug!("{e}"),
100        }
101    }
102
103    pub(crate) fn on_remove_node_status(&self, payload: &[u8]) {
104        match RemoveNodeStatus::parse(payload, self.inner.nid) {
105            Ok(s) => {
106                let tx = self.inner.inclusion.lock().expect("lock").remove_tx.clone();
107                if let Some(tx) = tx {
108                    let _ = tx.try_send(s);
109                }
110            }
111            Err(e) => debug!("{e}"),
112        }
113    }
114
115    pub(crate) fn on_replace_status(&self, payload: &[u8]) {
116        let Some(&status) = payload.get(1) else {
117            return;
118        };
119        let tx = self
120            .inner
121            .inclusion
122            .lock()
123            .expect("lock")
124            .replace_tx
125            .clone();
126        if let Some(tx) = tx {
127            let _ = tx.try_send(status);
128        }
129    }
130
131    /// Replaces a failed node: the controller gives its node id to the next
132    /// node that joins (press its button), which then gets security and an
133    /// interview as a new node would. The node must be one the controller
134    /// considers failed.
135    pub async fn replace_failed_node(
136        &self,
137        node: NodeId,
138        opts: InclusionOptions,
139    ) -> Result<InclusionResult, Error> {
140        let busy = self.take_busy()?;
141        let (tx, mut rx) = mpsc::channel(8);
142        let (ctx, mut crx) = oneshot::channel();
143        {
144            let mut st = self.inner.inclusion.lock().expect("lock");
145            st.replace_tx = Some(tx);
146            st.cancel = Some(ctx);
147        }
148        let cb = self.inner.api.next_callback_id();
149        let mut p = self.node_payload(node);
150        p.push(cb);
151        let r = self
152            .inner
153            .api
154            .request(
155                DataFrame::request(F::REPLACE_FAILED_NODE, p),
156                Duration::from_secs(2),
157            )
158            .await?;
159        if r.payload.first() != Some(&0) {
160            return Err(Error::Inclusion(format!(
161                "the controller refused to replace node {node} ({:#04x})",
162                r.payload.first().copied().unwrap_or(0)
163            )));
164        }
165        let deadline =
166            tokio::time::Instant::now() + opts.timeout.unwrap_or(self.inner.cfg.inclusion_timeout);
167        let outcome = loop {
168            tokio::select! {
169                s = rx.recv() => match s {
170                    Some(0x03) => self.emit(Event::InclusionStarted),
171                    Some(0x04) => break Ok(()),
172                    Some(0x05) => break Err(Error::Inclusion(format!("replacing node {node} failed"))),
173                    Some(0x00) => break Err(Error::Inclusion(format!("node {node} answers; it is not failed"))),
174                    Some(other) => debug!("replace status {other:#x}"),
175                    None => break Err(Error::Stopped),
176                },
177                _ = tokio::time::sleep_until(deadline) => break Err(Error::Inclusion("no node joined".into())),
178                _ = &mut crx => break Err(Error::Inclusion("replacement stopped".into())),
179            }
180        };
181        self.emit(Event::InclusionStopped);
182        drop(busy);
183        outcome?;
184        // A new node in the old id: forget everything about the old one.
185        self.s2(node).lock().expect("lock").forget_peer(node);
186        self.inner.runtime.lock().expect("lock").remove(&node);
187        self.inner
188            .store
189            .lock()
190            .expect("store lock")
191            .nodes
192            .insert(node, NodeRecord::new(node));
193        self.mark_dirty();
194        self.assume_awake(node);
195        let (_g, nif) = self.wait_for(node, false, |i| {
196            matches!(
197                i,
198                crate::controller::Inbound::NodeInfo(_)
199                    | crate::controller::Inbound::NodeInfoFailed
200            )
201        });
202        self.inner
203            .api
204            .request(
205                DataFrame::request(F::REQUEST_NODE_INFO, self.node_payload(node)),
206                Duration::from_secs(2),
207            )
208            .await?;
209        let info = match tokio::time::timeout(self.inner.cfg.request_timeout * 2, nif).await {
210            Ok(Ok(crate::controller::Inbound::NodeInfo(i))) => i,
211            _ => NodeInfo::default(),
212        };
213        let res = self.on_node_added(node, info, &opts, None).await;
214        self.update_smartstart().await;
215        Ok(res)
216    }
217
218    fn take_busy(&self) -> Result<Busy<'_>, Error> {
219        let mut st = self.inner.inclusion.lock().expect("lock");
220        if st.busy {
221            return Err(Error::Busy);
222        }
223        st.busy = true;
224        st.listening = false;
225        Ok(Busy(self))
226    }
227
228    async fn add_node(&self, payload: Vec<u8>) -> Result<(), Error> {
229        self.inner
230            .api
231            .execute(Request::ack_only(DataFrame::request(
232                F::ADD_NODE_TO_NETWORK,
233                payload,
234            )))
235            .await?;
236        Ok(())
237    }
238
239    async fn stop_add(&self) {
240        if let Err(e) = self.add_node(vec![add_mode::STOP, 0]).await {
241            warn!("stopping inclusion: {e}");
242        }
243    }
244
245    /// Answers [`Event::GrantSecurityClasses`].
246    pub fn grant_security_classes(&self, classes: Vec<SecurityClass>) -> bool {
247        match self.inner.inclusion.lock().expect("lock").grant.take() {
248            Some(tx) => tx.send(classes).is_ok(),
249            None => false,
250        }
251    }
252
253    /// Answers [`Event::ValidateDsk`] with the PIN, or `None` to abort.
254    pub fn validate_dsk(&self, pin: Option<u16>) -> bool {
255        match self.inner.inclusion.lock().expect("lock").pin.take() {
256            Some(tx) => tx.send(pin).is_ok(),
257            None => false,
258        }
259    }
260
261    /// Stops a running inclusion or exclusion.
262    pub fn stop_inclusion(&self) -> bool {
263        match self.inner.inclusion.lock().expect("lock").cancel.take() {
264            Some(tx) => tx.send(()).is_ok(),
265            None => false,
266        }
267    }
268
269    /// Includes a node: turns on inclusion mode, waits for a node, runs the
270    /// key exchange, and starts its interview.
271    pub async fn include(&self, opts: InclusionOptions) -> Result<InclusionResult, Error> {
272        let busy = self.take_busy()?;
273        let (tx, rx) = mpsc::channel(16);
274        let (ctx, crx) = oneshot::channel();
275        {
276            let mut st = self.inner.inclusion.lock().expect("lock");
277            st.add_tx = Some(tx);
278            st.cancel = Some(ctx);
279        }
280        let cb = self.inner.api.next_callback_id();
281        self.add_node(vec![
282            add_mode::ANY | add_mode::HIGH_POWER | add_mode::NETWORK_WIDE,
283            cb,
284        ])
285        .await?;
286        self.emit(Event::InclusionStarted);
287        let r = self
288            .run_add(
289                rx,
290                crx,
291                opts.timeout.unwrap_or(self.inner.cfg.inclusion_timeout),
292            )
293            .await;
294        self.emit(Event::InclusionStopped);
295        let r = match r {
296            Ok((node, info)) => Ok(self.on_node_added(node, info, &opts, None).await),
297            Err(e) => Err(e),
298        };
299        drop(busy);
300        self.update_smartstart().await;
301        r
302    }
303
304    /// Follows the controller's inclusion callbacks to the end.
305    async fn run_add(
306        &self,
307        mut rx: mpsc::Receiver<AddNodeStatus>,
308        mut cancel: oneshot::Receiver<()>,
309        timeout: Duration,
310    ) -> Result<(NodeId, NodeInfo), Error> {
311        let mut deadline = tokio::time::Instant::now() + timeout;
312        let mut found: Option<(NodeId, NodeInfo)> = None;
313        loop {
314            tokio::select! {
315                s = rx.recv() => {
316                    let Some(s) = s else { return Err(Error::Stopped) };
317                    debug!("inclusion: {s:?}");
318                    match s {
319                        AddNodeStatus::Ready => {}
320                        AddNodeStatus::NodeFound => deadline = tokio::time::Instant::now() + Duration::from_secs(60),
321                        AddNodeStatus::AddingEndNode { node, info } | AddNodeStatus::AddingController { node, info } => found = Some((node, info)),
322                        AddNodeStatus::ProtocolDone => {
323                            let cb = self.inner.api.next_callback_id();
324                            self.add_node(vec![add_mode::STOP, cb]).await?;
325                        }
326                        AddNodeStatus::Done { node } => {
327                            self.stop_add().await;
328                            return match found {
329                                Some((n, info)) => Ok((n, info)),
330                                None if node != 0 => Ok((node, NodeInfo::default())),
331                                None => Err(Error::Inclusion("inclusion ended without a node".into())),
332                            };
333                        }
334                        AddNodeStatus::Failed => {
335                            self.stop_add().await;
336                            return Err(Error::Inclusion("inclusion failed".into()));
337                        }
338                        AddNodeStatus::Other(o) => debug!("inclusion status {o:#x}"),
339                    }
340                }
341                _ = tokio::time::sleep_until(deadline) => {
342                    self.stop_add().await;
343                    return Err(Error::Inclusion("no node joined".into()));
344                }
345                _ = &mut cancel => {
346                    self.stop_add().await;
347                    return Err(Error::Inclusion("inclusion stopped".into()));
348                }
349            }
350        }
351    }
352
353    async fn on_node_added(
354        &self,
355        node: NodeId,
356        info: NodeInfo,
357        opts: &InclusionOptions,
358        entry: Option<Entry>,
359    ) -> InclusionResult {
360        {
361            let mut s = self.inner.store.lock().expect("store lock");
362            let mut r = NodeRecord::new(node);
363            for cc in &info.supported {
364                r.root_mut().ccs.entry(*cc).or_default();
365            }
366            if !info.supported.is_empty() {
367                r.stage = InterviewStage::New;
368            }
369            s.nodes.insert(node, r);
370        }
371        {
372            let mut info = self.inner.info.lock().expect("lock");
373            if !info.nodes.contains(&node) {
374                info.nodes.push(node);
375            }
376        }
377        self.mark_dirty();
378        self.emit(Event::NodeAdded { node });
379        if let Err(e) = self.fetch_protocol_info(node).await {
380            warn!(node, "protocol info: {e}");
381        }
382        self.assume_awake(node);
383        let _a = self.activity(node);
384        let supports = |cc: u16| info.supported.contains(&cc);
385        let result = if opts.insecure && entry.is_none() {
386            Ok(vec![])
387        } else if supports(0x9f) {
388            self.bootstrap_s2(node, opts, entry.as_ref()).await
389        } else if supports(0x98) && !crate::is_long_range(node) {
390            self.bootstrap_s0(node).await
391        } else {
392            Ok(vec![])
393        };
394        let (security, security_error) = match result {
395            Ok(c) => (c, None),
396            Err(e) => {
397                warn!(node, "security bootstrap failed: {e}");
398                self.emit(Event::SecurityFailed {
399                    node,
400                    reason: e.to_string(),
401                });
402                (vec![], Some(e.to_string()))
403            }
404        };
405        self.s2(node)
406            .lock()
407            .expect("lock")
408            .set_peer_classes(node, &security);
409        let dsk = entry.map(|e| e.dsk.to_string());
410        let _ = self.update_node(node, |r| {
411            r.security = security.clone();
412            if !info.supported.is_empty() && r.stage < InterviewStage::NodeInfo {
413                r.stage = InterviewStage::NodeInfo;
414            }
415            if dsk.is_some() {
416                r.dsk = dsk;
417            }
418        });
419        if security_error.is_none() {
420            self.emit(Event::SecurityBootstrapped {
421                node,
422                classes: security.clone(),
423            });
424        }
425        info!(node, ?security, "node included");
426        self.spawn_interview(node);
427        InclusionResult {
428            node,
429            security,
430            security_error,
431        }
432    }
433
434    /// The network key a node gets for a class: Long Range nodes have their own.
435    fn network_key(&self, node: NodeId, class: SecurityClass) -> [u8; 16] {
436        let keys = &self.inner.cfg.keys;
437        match (crate::is_long_range(node), keys.long_range_key(class)) {
438            (true, Some(k)) => *k,
439            _ => *keys.key(class),
440        }
441    }
442
443    async fn kex_fail(&self, node: NodeId, why: KexFail, sec: TxSecurity) {
444        let _ = self
445            .send_bytes(
446                node,
447                s2_cmd(security_2::KexFail {
448                    fail_type: why as u8,
449                }),
450                sec,
451            )
452            .await;
453        self.s2(node).lock().expect("lock").end_bootstrap(node);
454    }
455
456    async fn ask<T>(&self, rx: oneshot::Receiver<T>) -> Option<T> {
457        tokio::time::timeout(self.inner.cfg.user_timeout, rx)
458            .await
459            .ok()
460            .and_then(Result::ok)
461    }
462
463    /// The controller side of the S2 key exchange.
464    async fn bootstrap_s2(
465        &self,
466        node: NodeId,
467        opts: &InclusionOptions,
468        entry: Option<&Entry>,
469    ) -> Result<Vec<SecurityClass>, Error> {
470        let plain = TxSecurity::Plain;
471        let temp = TxSecurity::S2(KeyId::Temporary);
472        let (report, _) = self
473            .request_secured(node, s2_cmd(security_2::KexGet {}), plain, KEX_TIMEOUT, |c, _| {
474                matches!(c, Command::Security2(security_2::Command::KexReport(r)) if !r.echo)
475            })
476            .await?;
477        let Command::Security2(security_2::Command::KexReport(report)) = report else {
478            unreachable!()
479        };
480        if report.schemes & KEX_SCHEME_1 == 0 {
481            self.kex_fail(node, KexFail::Scheme, plain).await;
482            return Err(Error::Security("no supported KEX scheme".into()));
483        }
484        if report.curves & ECDH_CURVE25519 == 0 {
485            self.kex_fail(node, KexFail::Curves, plain).await;
486            return Err(Error::Security("no supported ECDH curve".into()));
487        }
488        let requested = SecurityClass::from_key_bits(report.keys);
489        // Long Range has only the two authenticated S2 classes.
490        let requested: Vec<SecurityClass> = if crate::is_long_range(node) {
491            requested
492                .into_iter()
493                .filter(|c| {
494                    matches!(
495                        c,
496                        SecurityClass::S2AccessControl | SecurityClass::S2Authenticated
497                    )
498                })
499                .collect()
500        } else {
501            requested
502        };
503        let intersect = |allowed: &[SecurityClass]| -> Vec<SecurityClass> {
504            requested
505                .iter()
506                .copied()
507                .filter(|c| allowed.contains(c))
508                .collect()
509        };
510        let granted = match (entry, &opts.grant) {
511            (Some(e), _) => intersect(&e.granted),
512            (None, GrantPolicy::Requested) => requested.clone(),
513            (None, GrantPolicy::Only(v)) => intersect(v),
514            (None, GrantPolicy::Ask) => {
515                let (tx, rx) = oneshot::channel();
516                self.inner.inclusion.lock().expect("lock").grant = Some(tx);
517                self.emit(Event::GrantSecurityClasses {
518                    node,
519                    requested: requested.clone(),
520                });
521                match self.ask(rx).await {
522                    Some(v) => intersect(&v),
523                    None => {
524                        self.kex_fail(node, KexFail::Cancel, plain).await;
525                        return Err(Error::Security("no answer to the key grant".into()));
526                    }
527                }
528            }
529        };
530        if granted.is_empty() {
531            self.kex_fail(node, KexFail::Key, plain).await;
532            return Err(Error::Security("no key granted".into()));
533        }
534        let set = security_2::KexSet {
535            request_csa: false,
536            echo: false,
537            scheme: KEX_SCHEME_1,
538            curve: ECDH_CURVE25519,
539            keys: SecurityClass::to_key_bits(&granted),
540        };
541        let (pk, _) = self
542            .request_secured(node, s2_cmd(set.clone()), plain, KEX_TIMEOUT, |c, _| {
543                matches!(c, Command::Security2(security_2::Command::PublicKeyReport(r)) if !r.including_node)
544            })
545            .await?;
546        let Command::Security2(security_2::Command::PublicKeyReport(pk)) = pk else {
547            unreachable!()
548        };
549        let Ok(mut node_pub) = <[u8; 32]>::try_from(pk.public_key.as_slice()) else {
550            self.kex_fail(node, KexFail::Cancel, plain).await;
551            return Err(Error::Security("public key is not 32 bytes".into()));
552        };
553        // The node's full DSK, once its key is known to be authentic: with the
554        // PIN put back, or matching its provisioning entry.
555        let mut dsk = None;
556        if granted.iter().any(|c| c.needs_pin()) {
557            let pin = match (entry, opts.pin) {
558                (Some(e), _) => {
559                    if e.dsk.0[2..] != node_pub[2..16] {
560                        self.kex_fail(node, KexFail::Auth, plain).await;
561                        return Err(Error::Security(
562                            "the node's key does not match its provisioned DSK".into(),
563                        ));
564                    }
565                    e.dsk.pin()
566                }
567                (None, Some(p)) => p,
568                (None, None) => {
569                    let (tx, rx) = oneshot::channel();
570                    self.inner.inclusion.lock().expect("lock").pin = Some(tx);
571                    self.emit(Event::ValidateDsk {
572                        node,
573                        dsk: Dsk::from_public_key(&node_pub).masked(),
574                    });
575                    match self.ask(rx).await.flatten() {
576                        Some(p) => p,
577                        None => {
578                            self.kex_fail(node, KexFail::Cancel, plain).await;
579                            return Err(Error::Security("DSK not confirmed".into()));
580                        }
581                    }
582                }
583            };
584            apply_pin(&mut node_pub, pin);
585            dsk = Some(Dsk::from_public_key(&node_pub));
586        } else if let Some(e) = entry {
587            if e.dsk.0[..] != node_pub[..16] {
588                self.kex_fail(node, KexFail::Auth, plain).await;
589                return Err(Error::Security(
590                    "the node's key does not match its provisioned DSK".into(),
591                ));
592            }
593            dsk = Some(e.dsk);
594        }
595        let shared = match self.inner.keypair.shared_secret(&node_pub) {
596            Ok(s) => s,
597            Err(_) => {
598                self.kex_fail(node, KexFail::Cancel, plain).await;
599                return Err(Error::Security("invalid public key".into()));
600            }
601        };
602        let tk = bootstrap_keys(&shared, self.inner.keypair.public(), &node_pub);
603        self.s2(node)
604            .lock()
605            .expect("lock")
606            .begin_bootstrap(node, tk);
607        let result = self.exchange_keys(node, &set, &report, &granted).await;
608        match result {
609            Ok(()) => {
610                {
611                    let mut s2 = self.s2(node).lock().expect("lock");
612                    s2.end_bootstrap(node);
613                    s2.set_peer_classes(node, &granted);
614                }
615                if let Some(d) = dsk {
616                    let _ = self.update_node(node, |r| r.dsk = Some(d.to_string()));
617                }
618                Ok(granted)
619            }
620            Err((why, e)) => {
621                self.kex_fail(node, why, temp).await;
622                Err(e)
623            }
624        }
625    }
626
627    async fn exchange_keys(
628        &self,
629        node: NodeId,
630        set: &security_2::KexSet,
631        report: &security_2::KexReport,
632        granted: &[SecurityClass],
633    ) -> Result<(), (KexFail, Error)> {
634        let temp = TxSecurity::S2(KeyId::Temporary);
635        let is_temp = |s: Option<RxSecurity>| s == Some(RxSecurity::S2(KeyId::Temporary));
636        let own_pub = *self.inner.keypair.public();
637        let (echo, _) = self
638            .request_secured(
639                node,
640                s2_cmd(security_2::PublicKeyReport {
641                    including_node: true,
642                    public_key: own_pub.to_vec(),
643                }),
644                TxSecurity::Plain,
645                KEX_TIMEOUT,
646                move |c, s| {
647                    is_temp(s)
648                        && matches!(c, Command::Security2(security_2::Command::KexSet(k)) if k.echo)
649                },
650            )
651            .await
652            .map_err(|e| (KexFail::Decrypt, e))?;
653        let Command::Security2(security_2::Command::KexSet(echo)) = echo else {
654            unreachable!()
655        };
656        if echo.scheme != set.scheme || echo.curve != set.curve || echo.keys != set.keys {
657            return Err((
658                KexFail::Auth,
659                Error::Security("the echoed KEX Set differs".into()),
660            ));
661        }
662        let mut next = self.wait_for(node, false, move |i| {
663            matches!(i, crate::controller::Inbound::Command { command: Command::Security2(security_2::Command::NetworkKeyGet(_)), security, .. } if is_temp(*security))
664        });
665        self.send_bytes(
666            node,
667            s2_cmd(security_2::KexReport {
668                request_csa: report.request_csa,
669                echo: true,
670                schemes: report.schemes,
671                curves: report.curves,
672                keys: report.keys,
673            }),
674            temp,
675        )
676        .await
677        .map_err(|e| (KexFail::Cancel, e))?;
678        let mut sent: Vec<SecurityClass> = Vec::new();
679        loop {
680            let got = tokio::time::timeout(KEX_TIMEOUT, next.1).await;
681            drop(next.0);
682            let Ok(Ok(crate::controller::Inbound::Command { command, .. })) = got else {
683                return Err((KexFail::Cancel, Error::Timeout(node)));
684            };
685            match command {
686                Command::Security2(security_2::Command::NetworkKeyGet(g)) => {
687                    let Some(class) = SecurityClass::from_key_bit(g.requested_key)
688                        .filter(|c| granted.contains(c) && !sent.contains(c))
689                    else {
690                        return Err((
691                            KexFail::KeyGet,
692                            Error::Security(format!(
693                                "the node asked for key {:#04x}",
694                                g.requested_key
695                            )),
696                        ));
697                    };
698                    let mut classes = sent.clone();
699                    classes.push(class);
700                    self.s2(node)
701                        .lock()
702                        .expect("lock")
703                        .set_peer_classes(node, &classes);
704                    let (verify, _) = self
705                        .request_secured(
706                            node,
707                            s2_cmd(security_2::NetworkKeyReport {
708                                granted_key: class.key_bit(),
709                                network_key: self.network_key(node, class).to_vec(),
710                            }),
711                            temp,
712                            KEX_TIMEOUT,
713                            move |c, s| {
714                                s == Some(RxSecurity::S2(KeyId::Class(class)))
715                                    && matches!(
716                                        c,
717                                        Command::Security2(security_2::Command::NetworkKeyVerify(
718                                            _
719                                        ))
720                                    )
721                            },
722                        )
723                        .await
724                        .map_err(|e| (KexFail::KeyVerify, e))?;
725                    debug!(node, %class, "key verified: {}", verify.name());
726                    sent.push(class);
727                    next = self.wait_for(node, false, move |i| {
728                        matches!(i, crate::controller::Inbound::Command { command: Command::Security2(security_2::Command::NetworkKeyGet(_) | security_2::Command::TransferEnd(_)), security, .. } if is_temp(*security))
729                    });
730                    self.send_bytes(
731                        node,
732                        s2_cmd(security_2::TransferEnd {
733                            key_verified: true,
734                            key_request_complete: false,
735                        }),
736                        temp,
737                    )
738                    .await
739                    .map_err(|e| (KexFail::Cancel, e))?;
740                }
741                Command::Security2(security_2::Command::TransferEnd(t))
742                    if t.key_request_complete =>
743                {
744                    if sent.len() != granted.len() {
745                        return Err((
746                            KexFail::Key,
747                            Error::Security("the node did not take every granted key".into()),
748                        ));
749                    }
750                    return Ok(());
751                }
752                other => {
753                    return Err((
754                        KexFail::Cancel,
755                        Error::Security(format!("unexpected {}", other.name())),
756                    ))
757                }
758            }
759        }
760    }
761
762    /// The controller side of the S0 key exchange.
763    async fn bootstrap_s0(&self, node: NodeId) -> Result<Vec<SecurityClass>, Error> {
764        self.request_secured(
765            node,
766            Command::from(security::SchemeGet { schemes: 0 }).encode(),
767            TxSecurity::Plain,
768            KEX_TIMEOUT,
769            |c, _| matches!(c, Command::Security(security::Command::SchemeReport(_))),
770        )
771        .await?;
772        let set = Command::from(security::NetworkKeySet {
773            network_key: self.inner.cfg.keys.s0.to_vec(),
774        })
775        .encode();
776        self.request_secured(
777            node,
778            set,
779            TxSecurity::S0 { temp: true },
780            KEX_TIMEOUT,
781            |c, s| {
782                s == Some(RxSecurity::S0)
783                    && matches!(c, Command::Security(security::Command::NetworkKeyVerify(_)))
784            },
785        )
786        .await?;
787        Ok(vec![SecurityClass::S0Legacy])
788    }
789
790    /// Excludes a node: turns on exclusion mode and waits for one.
791    /// Returns the node id it had in this network, if any.
792    pub async fn exclude(&self, timeout: Option<Duration>) -> Result<Option<NodeId>, Error> {
793        let busy = self.take_busy()?;
794        let (tx, mut rx) = mpsc::channel(16);
795        let (ctx, mut crx) = oneshot::channel();
796        {
797            let mut st = self.inner.inclusion.lock().expect("lock");
798            st.remove_tx = Some(tx);
799            st.cancel = Some(ctx);
800        }
801        let api = &self.inner.api;
802        let remove = |p: Vec<u8>| {
803            api.execute(Request::ack_only(DataFrame::request(
804                F::REMOVE_NODE_FROM_NETWORK,
805                p,
806            )))
807        };
808        let cb = api.next_callback_id();
809        remove(vec![
810            add_mode::ANY | add_mode::HIGH_POWER | add_mode::NETWORK_WIDE,
811            cb,
812        ])
813        .await?;
814        self.emit(Event::ExclusionStarted);
815        let deadline =
816            tokio::time::Instant::now() + timeout.unwrap_or(self.inner.cfg.inclusion_timeout);
817        let mut removed = None;
818        let result = loop {
819            tokio::select! {
820                s = rx.recv() => match s {
821                    Some(RemoveNodeStatus::RemovingEndNode { node } | RemoveNodeStatus::RemovingController { node }) => removed = Some(node),
822                    Some(RemoveNodeStatus::Done { node }) => break Ok(removed.or(Some(node)).filter(|&n| n != 0)),
823                    Some(RemoveNodeStatus::Failed) => break Err(Error::Inclusion("exclusion failed".into())),
824                    Some(_) => {}
825                    None => break Err(Error::Stopped),
826                },
827                _ = tokio::time::sleep_until(deadline) => break Err(Error::Inclusion("no node left".into())),
828                _ = &mut crx => break Err(Error::Inclusion("exclusion stopped".into())),
829            }
830        };
831        let _ = remove(vec![add_mode::STOP, 0]).await;
832        self.emit(Event::ExclusionStopped);
833        if let Ok(Some(n)) = result {
834            self.forget_node(n);
835        }
836        drop(busy);
837        self.update_smartstart().await;
838        result
839    }
840
841    /// Removes a node the controller considers failed (it stopped answering).
842    pub async fn remove_failed_node(&self, node: NodeId) -> Result<(), Error> {
843        let cb = self.inner.api.next_callback_id();
844        let req = Request::with_callback(
845            DataFrame::request(F::REMOVE_FAILED_NODE, {
846                let mut v = self.node_payload(node);
847                v.push(cb);
848                v
849            }),
850            Duration::from_secs(2),
851            cb,
852            Duration::from_secs(30),
853        );
854        let mut req = req;
855        req.callback_follows = |r| r.payload.first() == Some(&0);
856        let ex = self.inner.api.execute(req).await?;
857        match ex.callback.as_ref().and_then(|c| c.payload.get(1)) {
858            Some(0x01) => {
859                self.forget_node(node);
860                Ok(())
861            }
862            _ => Err(Error::Controller(format!(
863                "node {node} was not removed (it may still be answering)"
864            ))),
865        }
866    }
867
868    // ------------------------------------------------------------- SmartStart
869
870    /// Adds or replaces a provisioning list entry (from a scanned QR code).
871    pub async fn provision(&self, entry: Entry) -> Result<(), Error> {
872        {
873            let mut s = self.inner.store.lock().expect("store lock");
874            if !s.provisioning.upsert(entry) {
875                return Err(Error::Store("the provisioning list is full".into()));
876            }
877        }
878        self.provisioning_changed().await;
879        Ok(())
880    }
881
882    /// Removes a provisioning list entry.
883    pub async fn unprovision(&self, dsk: &Dsk) -> Option<Entry> {
884        let e = self
885            .inner
886            .store
887            .lock()
888            .expect("store lock")
889            .provisioning
890            .remove(dsk);
891        self.provisioning_changed().await;
892        e
893    }
894
895    /// The provisioning list.
896    pub fn provisioning_list(&self) -> Vec<Entry> {
897        self.inner
898            .store
899            .lock()
900            .expect("store lock")
901            .provisioning
902            .entries()
903            .to_vec()
904    }
905
906    async fn provisioning_changed(&self) {
907        self.mark_dirty();
908        self.emit(Event::ProvisioningChanged {
909            entries: self.provisioning_list(),
910        });
911        self.update_smartstart().await;
912    }
913
914    /// Listens for SmartStart requests while the provisioning list has active entries.
915    pub(crate) async fn update_smartstart(&self) {
916        let want = self
917            .inner
918            .store
919            .lock()
920            .expect("store lock")
921            .provisioning
922            .has_active();
923        let change = {
924            let st = self.inner.inclusion.lock().expect("lock");
925            !st.busy && st.listening != want
926        };
927        if !change {
928            return;
929        }
930        let payload = if want {
931            vec![
932                add_mode::SMART_START_LISTEN | add_mode::HIGH_POWER | add_mode::NETWORK_WIDE,
933                0,
934            ]
935        } else {
936            vec![add_mode::STOP, 0]
937        };
938        match self.add_node(payload).await {
939            Ok(()) => self.inner.inclusion.lock().expect("lock").listening = want,
940            Err(e) => warn!("SmartStart listen mode: {e}"),
941        }
942    }
943
944    pub(crate) fn on_smartstart_request(&self, nwi: [u8; 4], long_range: bool) {
945        let entry = self
946            .inner
947            .store
948            .lock()
949            .expect("store lock")
950            .provisioning
951            .match_nwi_home_id(&nwi)
952            .cloned();
953        let Some(entry) = entry else {
954            debug!("SmartStart request from a node not on the provisioning list");
955            return;
956        };
957        if entry.status != EntryStatus::Active || entry.node_id.is_some() {
958            return;
959        }
960        let c = self.clone();
961        tokio::spawn(async move {
962            match c.include_smartstart(entry, long_range).await {
963                Ok(r) => info!(node = r.node, "SmartStart inclusion done"),
964                Err(e) => warn!("SmartStart inclusion: {e}"),
965            }
966        });
967    }
968
969    async fn include_smartstart(
970        &self,
971        entry: Entry,
972        long_range: bool,
973    ) -> Result<InclusionResult, Error> {
974        let busy = self.take_busy()?;
975        let (tx, rx) = mpsc::channel(16);
976        let (ctx, crx) = oneshot::channel();
977        {
978            let mut st = self.inner.inclusion.lock().expect("lock");
979            st.add_tx = Some(tx);
980            st.cancel = Some(ctx);
981        }
982        let cb = self.inner.api.next_callback_id();
983        let mode = if long_range {
984            add_mode::SMART_START_DSK | add_mode::HIGH_POWER | add_mode::PROTOCOL_LONG_RANGE
985        } else {
986            add_mode::SMART_START_DSK | add_mode::HIGH_POWER | add_mode::NETWORK_WIDE
987        };
988        let mut p = vec![mode, cb];
989        p.extend_from_slice(&entry.dsk.nwi_home_id());
990        p.extend_from_slice(&entry.dsk.auth_home_id());
991        self.add_node(p).await?;
992        self.emit(Event::InclusionStarted);
993        let r = self
994            .run_add(rx, crx, self.inner.cfg.inclusion_timeout)
995            .await;
996        self.emit(Event::InclusionStopped);
997        let r = match r {
998            Ok((node, info)) => {
999                let res = self
1000                    .on_node_added(
1001                        node,
1002                        info,
1003                        &InclusionOptions::default(),
1004                        Some(entry.clone()),
1005                    )
1006                    .await;
1007                if let Some(e) = self
1008                    .inner
1009                    .store
1010                    .lock()
1011                    .expect("store lock")
1012                    .provisioning
1013                    .get_mut(&entry.dsk)
1014                {
1015                    e.node_id = Some(node);
1016                }
1017                self.mark_dirty();
1018                Ok(res)
1019            }
1020            Err(e) => Err(e),
1021        };
1022        drop(busy);
1023        self.update_smartstart().await;
1024        r
1025    }
1026}