Skip to main content

zigbee_bridge/
network.rs

1//! The network file: the keys and PAN ids the bridge runs, in the data
2//! directory, readable by its owner only. The bridge writes it with random
3//! values on first start; a platform that manages keys writes it before.
4
5use std::path::Path;
6
7use serde::{Deserialize, Serialize};
8use zigbee_host::{Backup, NetworkSettings};
9use zigbee_primitives::{ExtPanId, Key};
10
11/// The file's name in the data directory.
12pub const FILE: &str = "network.json";
13
14#[derive(Serialize, Deserialize)]
15#[serde(deny_unknown_fields)]
16struct NetworkFile {
17    channel: u8,
18    pan_id: String,
19    extended_pan_id: ExtPanId,
20    network_key: Key,
21}
22
23/// Read the network file, or create it with `channel` and random ids and
24/// key when there is none.
25pub fn load_or_create(
26    dir: &Path,
27    channel: u8,
28    tx_power: Option<i8>,
29) -> Result<(NetworkSettings, bool), String> {
30    let path = dir.join(FILE);
31    match std::fs::read_to_string(&path) {
32        Ok(text) => {
33            let f: NetworkFile =
34                serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
35            let pan_id = u16::from_str_radix(f.pan_id.trim_start_matches("0x"), 16)
36                .map_err(|e| format!("{}: pan_id: {e}", path.display()))?;
37            Ok((
38                NetworkSettings {
39                    channel: f.channel,
40                    pan_id,
41                    extended_pan_id: f.extended_pan_id,
42                    network_key: f.network_key,
43                    tx_power,
44                },
45                false,
46            ))
47        }
48        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
49            let mut settings = zigbee_host::random_network(channel).map_err(|e| e.to_string())?;
50            settings.tx_power = tx_power;
51            save(dir, &settings)?;
52            Ok((settings, true))
53        }
54        Err(e) => Err(format!("{}: {e}", path.display())),
55    }
56}
57
58/// Write the network file (mode 0600 on Unix).
59pub fn save(dir: &Path, settings: &NetworkSettings) -> Result<(), String> {
60    let f = NetworkFile {
61        channel: settings.channel,
62        pan_id: format!("{:04x}", settings.pan_id),
63        extended_pan_id: settings.extended_pan_id,
64        network_key: settings.network_key,
65    };
66    let text = serde_json::to_string_pretty(&f).map_err(|e| e.to_string())?;
67    let path = dir.join(FILE);
68    zigbee_host::store::write_atomic(&path, text.as_bytes())
69        .map_err(|e| format!("{}: {e}", path.display()))?;
70    restrict(&path);
71    Ok(())
72}
73
74/// The network a backup describes.
75pub fn from_backup(backup: &Backup) -> NetworkSettings {
76    NetworkSettings {
77        channel: backup.channel,
78        pan_id: backup.pan_id,
79        extended_pan_id: backup.extended_pan_id,
80        network_key: backup.network_key.key,
81        tx_power: None,
82    }
83}
84
85/// Make a file readable by its owner only.
86pub fn restrict(path: &Path) {
87    #[cfg(unix)]
88    {
89        use std::os::unix::fs::PermissionsExt;
90        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
91    }
92    #[cfg(not(unix))]
93    let _ = path;
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn creates_once_then_reads_the_same_network() {
102        let dir = tempfile::tempdir().unwrap();
103        let (first, created) = load_or_create(dir.path(), 20, None).unwrap();
104        assert!(created);
105        let (again, created) = load_or_create(dir.path(), 11, Some(3)).unwrap();
106        assert!(!created);
107        assert_eq!(again.network_key, first.network_key);
108        assert_eq!(again.channel, 20);
109        assert_eq!(again.tx_power, Some(3));
110        #[cfg(unix)]
111        {
112            use std::os::unix::fs::PermissionsExt;
113            let mode = std::fs::metadata(dir.path().join(FILE))
114                .unwrap()
115                .permissions()
116                .mode();
117            assert_eq!(mode & 0o077, 0);
118        }
119    }
120}