Skip to main content

zwave_host/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5mod controller;
6pub mod device_config;
7pub mod firmware;
8mod inclusion;
9mod interview;
10pub mod node;
11mod nvm;
12pub mod nvm3;
13pub mod store;
14pub mod values;
15
16pub use controller::{
17    Controller, ControllerInfo, Events, HostConfig, Topology, TopologyNode, MAX_PENDING_EVENTS,
18};
19pub use inclusion::{GrantPolicy, InclusionOptions, InclusionResult};
20pub use node::{NodeRecord, NodeStatus};
21pub use values::{ValueId, ValueKind, ValueUpdate};
22pub use zwave_security::SecurityClass;
23pub use zwave_serial::NodeId;
24
25use zwave_security::provisioning::Entry as ProvisioningEntry;
26
27/// Whether a node id is a Long Range node (256 and up).
28pub fn is_long_range(node: NodeId) -> bool {
29    node > 255
30}
31
32/// The network keys and the controller's long-term S2 key pair.
33///
34/// Generate them once per network with [`NetworkKeys::generate`] and keep
35/// them secret: anyone with these keys can read and command the network.
36#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37pub struct NetworkKeys {
38    /// The S0 network key.
39    #[serde(with = "hex_key")]
40    pub s0: [u8; 16],
41    /// S2 Unauthenticated.
42    #[serde(with = "hex_key")]
43    pub s2_unauthenticated: [u8; 16],
44    /// S2 Authenticated.
45    #[serde(with = "hex_key")]
46    pub s2_authenticated: [u8; 16],
47    /// S2 Access Control.
48    #[serde(with = "hex_key")]
49    pub s2_access_control: [u8; 16],
50    /// The controller's Curve25519 private key for S2 key exchange.
51    #[serde(with = "hex_key")]
52    pub ecdh_private: [u8; 32],
53    /// Long Range S2 Authenticated (Long Range nodes use their own keys).
54    #[serde(default, with = "hex_key_opt", skip_serializing_if = "Option::is_none")]
55    pub lr_s2_authenticated: Option<[u8; 16]>,
56    /// Long Range S2 Access Control.
57    #[serde(default, with = "hex_key_opt", skip_serializing_if = "Option::is_none")]
58    pub lr_s2_access_control: Option<[u8; 16]>,
59}
60
61impl std::fmt::Debug for NetworkKeys {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.write_str("NetworkKeys(..)")
64    }
65}
66
67impl NetworkKeys {
68    /// Fresh random keys from the operating system's CSPRNG.
69    pub fn generate() -> Result<Self, zwave_security::Error> {
70        use zwave_security::random_bytes;
71        Ok(NetworkKeys {
72            s0: random_bytes()?,
73            s2_unauthenticated: random_bytes()?,
74            s2_authenticated: random_bytes()?,
75            s2_access_control: random_bytes()?,
76            ecdh_private: random_bytes()?,
77            lr_s2_authenticated: Some(random_bytes()?),
78            lr_s2_access_control: Some(random_bytes()?),
79        })
80    }
81
82    /// Adds the Long Range keys to keys made before they existed; true if any was added.
83    pub fn fill_long_range(&mut self) -> Result<bool, zwave_security::Error> {
84        let mut added = false;
85        if self.lr_s2_authenticated.is_none() {
86            self.lr_s2_authenticated = Some(zwave_security::random_bytes()?);
87            added = true;
88        }
89        if self.lr_s2_access_control.is_none() {
90            self.lr_s2_access_control = Some(zwave_security::random_bytes()?);
91            added = true;
92        }
93        Ok(added)
94    }
95
96    /// The Long Range key for a class (only the two authenticated S2 classes exist on Long Range).
97    pub fn long_range_key(&self, class: SecurityClass) -> Option<&[u8; 16]> {
98        match class {
99            SecurityClass::S2Authenticated => self.lr_s2_authenticated.as_ref(),
100            SecurityClass::S2AccessControl => self.lr_s2_access_control.as_ref(),
101            _ => None,
102        }
103    }
104
105    /// The key for a class.
106    pub fn key(&self, class: SecurityClass) -> &[u8; 16] {
107        match class {
108            SecurityClass::S0Legacy => &self.s0,
109            SecurityClass::S2Unauthenticated => &self.s2_unauthenticated,
110            SecurityClass::S2Authenticated => &self.s2_authenticated,
111            SecurityClass::S2AccessControl => &self.s2_access_control,
112        }
113    }
114
115    /// The controller's DSK (first 16 bytes of its public key), for a controller-side QR label.
116    pub fn controller_dsk(&self) -> zwave_security::dsk::Dsk {
117        let kp = zwave_security::kex::KeyPair::from_private(self.ecdh_private);
118        zwave_security::dsk::Dsk::from_public_key(kp.public())
119    }
120}
121
122mod hex_key_opt {
123    use serde::{Deserialize, Deserializer, Serializer};
124
125    pub fn serialize<S: Serializer>(k: &Option<[u8; 16]>, s: S) -> Result<S::Ok, S::Error> {
126        match k {
127            Some(k) => s.serialize_str(&hex::encode(k)),
128            None => s.serialize_none(),
129        }
130    }
131
132    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<[u8; 16]>, D::Error> {
133        let s: Option<String> = Option::deserialize(d)?;
134        match s {
135            None => Ok(None),
136            Some(s) => {
137                let v = hex::decode(s.trim()).map_err(serde::de::Error::custom)?;
138                v.try_into()
139                    .map(Some)
140                    .map_err(|_| serde::de::Error::custom("expected 16 bytes"))
141            }
142        }
143    }
144}
145
146mod hex_key {
147    use serde::{Deserialize, Deserializer, Serializer};
148
149    pub fn serialize<S: Serializer, const N: usize>(k: &[u8; N], s: S) -> Result<S::Ok, S::Error> {
150        s.serialize_str(&hex::encode(k))
151    }
152
153    pub fn deserialize<'de, D: Deserializer<'de>, const N: usize>(
154        d: D,
155    ) -> Result<[u8; N], D::Error> {
156        let s = String::deserialize(d)?;
157        let v = hex::decode(s.trim()).map_err(serde::de::Error::custom)?;
158        v.try_into()
159            .map_err(|_| serde::de::Error::custom(format!("expected {N} bytes")))
160    }
161}
162
163/// Errors from the host stack.
164#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
165pub enum Error {
166    /// The serial link failed.
167    #[error("serial: {0}")]
168    Serial(#[from] zwave_serial::SerialError),
169    /// The controller answered in a way that makes no sense.
170    #[error("controller: {0}")]
171    Controller(String),
172    /// The node did not acknowledge (asleep, out of range or gone).
173    #[error("node {0} did not acknowledge")]
174    NoAck(NodeId),
175    /// The transmission failed at the radio.
176    #[error("transmission to node {0} failed: {1}")]
177    TransmitFailed(NodeId, String),
178    /// No answer from the node in time.
179    #[error("node {0} did not answer in time")]
180    Timeout(NodeId),
181    /// A security exchange failed.
182    #[error("security: {0}")]
183    Security(String),
184    /// No such node.
185    #[error("no node {0}")]
186    UnknownNode(NodeId),
187    /// Another inclusion or exclusion is running.
188    #[error("the controller is busy with another inclusion or exclusion")]
189    Busy,
190    /// Inclusion or exclusion failed.
191    #[error("{0}")]
192    Inclusion(String),
193    /// The node store could not be read or written.
194    #[error("store: {0}")]
195    Store(String),
196    /// The controller task stopped.
197    #[error("controller stopped")]
198    Stopped,
199}
200
201/// Something that happened on the network.
202#[derive(Debug, Clone, PartialEq)]
203pub enum Event {
204    /// The controller is initialized.
205    Ready(ControllerInfo),
206    /// Inclusion mode is on; press the node's button.
207    InclusionStarted,
208    /// Inclusion mode is off.
209    InclusionStopped,
210    /// Exclusion mode is on.
211    ExclusionStarted,
212    /// Exclusion mode is off.
213    ExclusionStopped,
214    /// A node joined (protocol part done; security and interview follow).
215    NodeAdded {
216        /// The node.
217        node: NodeId,
218    },
219    /// A node left or was removed.
220    NodeRemoved {
221        /// The node.
222        node: NodeId,
223    },
224    /// S2: the node asks for these keys; answer with [`Controller::grant_security_classes`].
225    GrantSecurityClasses {
226        /// The joining node.
227        node: NodeId,
228        /// Requested classes, highest first.
229        requested: Vec<SecurityClass>,
230    },
231    /// S2: confirm the PIN (first five digits of the DSK) with [`Controller::validate_dsk`].
232    ValidateDsk {
233        /// The joining node.
234        node: NodeId,
235        /// The DSK with the PIN masked, `xxxxx-12345-...`.
236        dsk: String,
237    },
238    /// The key exchange finished; these classes are granted.
239    SecurityBootstrapped {
240        /// The node.
241        node: NodeId,
242        /// Granted classes, highest first (empty: included without security).
243        classes: Vec<SecurityClass>,
244    },
245    /// The key exchange failed; the node is included without security.
246    SecurityFailed {
247        /// The node.
248        node: NodeId,
249        /// Why.
250        reason: String,
251    },
252    /// The interview reached a new stage.
253    InterviewStage {
254        /// The node.
255        node: NodeId,
256        /// The stage just reached.
257        stage: node::InterviewStage,
258    },
259    /// The interview finished.
260    InterviewCompleted {
261        /// The node.
262        node: NodeId,
263    },
264    /// The interview failed for now; it is retried.
265    InterviewFailed {
266        /// The node.
267        node: NodeId,
268        /// Why.
269        reason: String,
270    },
271    /// A node's record changed (new metadata); re-read it with [`Controller::node`].
272    NodeUpdated {
273        /// The node.
274        node: NodeId,
275    },
276    /// Awake, asleep, alive or dead.
277    NodeStatus {
278        /// The node.
279        node: NodeId,
280        /// The new status.
281        status: NodeStatus,
282    },
283    /// A value reported by a node.
284    Value(ValueUpdate),
285    /// A transmission reached the node along this route.
286    Route {
287        /// The node.
288        node: NodeId,
289        /// Repeaters from the controller outwards (empty: direct).
290        repeaters: Vec<NodeId>,
291        /// RSSI of the node's ACK at the controller.
292        rssi: Option<i8>,
293    },
294    /// A command a node sent that the stack did not turn into a value.
295    Command {
296        /// The node.
297        node: NodeId,
298        /// The endpoint (0 is the root device).
299        endpoint: u8,
300        /// The command.
301        command: zwave_cc::Command,
302    },
303    /// Fragments sent so far in a firmware update.
304    FirmwareUpdateProgress {
305        /// The node.
306        node: NodeId,
307        /// Fragments sent.
308        sent: u16,
309        /// Fragments in the image.
310        total: u16,
311    },
312    /// A firmware update ended.
313    FirmwareUpdateFinished {
314        /// The node.
315        node: NodeId,
316        /// The node's status byte.
317        status: u8,
318        /// Whether the node accepted the image.
319        success: bool,
320    },
321    /// The provisioning list changed.
322    ProvisioningChanged {
323        /// The entries.
324        entries: Vec<ProvisioningEntry>,
325    },
326}
327
328// The repository README's Rust examples run as doctests, so they cannot rot.
329#[cfg(doctest)]
330#[doc = include_str!("../../../README.md")]
331struct ReadmeDoctests;