Skip to main content

fritz_core/
cache.rs

1//! A cache of the service descriptions (SCPDs) of devices, so that a run
2//! only fetches the device description.
3//!
4//! The cache keeps one directory per device and firmware, named after its
5//! UDN (or its serial number if it has no UDN) and a hash of its model and
6//! firmware version. The file `device.json` in it names the device, its
7//! model and its firmware version, as the device description states them;
8//! the other files are the SCPDs as the device sent them. Since every
9//! firmware has its own directory, a process that still runs with the old
10//! firmware never writes into the directory of the new one, and a firmware
11//! update never uses old action lists. The directories of other firmware
12//! versions of the device are removed when a new one is created. Devices
13//! whose description has no firmware version, like some FRITZ!Repeaters, are
14//! not cached.
15//!
16//! A file that cannot be read or parsed counts as missing, and the SCPD is
17//! fetched again. The descriptions need no login and hold no secrets;
18//! nothing else goes into the cache.
19//!
20//! Besides the files, the cache keeps the parsed SCPDs in memory, for
21//! processes that run long, like the MCP server.
22
23use std::collections::HashMap;
24use std::fs;
25use std::io;
26use std::path::{Path, PathBuf};
27use std::sync::Mutex;
28use std::sync::atomic::{AtomicU64, Ordering};
29
30use roxmltree::{Document, Node};
31use serde::{Deserialize, Serialize};
32use sha2::{Digest as _, Sha256};
33use tr064::{DescriptionCache, Scpd};
34
35/// The environment variable for another cache directory.
36pub const ENV_CACHE_DIR: &str = "FRITZ_CACHE_DIR";
37
38/// The file in the directory of a device that names it.
39const DEVICE_FILE: &str = "device.json";
40
41/// The cache directory: the one of [`ENV_CACHE_DIR`], else the one of the
42/// platform (see [`crate::dirs::cache`]). `None` if neither is known.
43pub fn default_dir() -> Option<PathBuf> {
44    std::env::var_os(ENV_CACHE_DIR)
45        .filter(|dir| !dir.is_empty())
46        .map(PathBuf::from)
47        .or_else(crate::dirs::cache)
48}
49
50/// A device as its description names it, the key of its cache.
51#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
52pub struct Device {
53    /// The UDN, or the serial number if there is no UDN.
54    pub id: String,
55    /// The model.
56    pub model: Option<String>,
57    /// The firmware version, like `285.08.25`.
58    pub firmware: String,
59}
60
61impl Device {
62    /// The device that a device description describes. `None` if the
63    /// description cannot be parsed, or names neither a UDN nor a serial
64    /// number, or no firmware version.
65    pub fn of(description: &str) -> Option<Self> {
66        let doc = Document::parse(description).ok()?;
67        let root = doc.root_element();
68        let device = child(root, "device")?;
69        let firmware = child(root, "systemVersion").and_then(|v| text(v, "Display"))?;
70        let id = text(device, "UDN").or_else(|| text(device, "serialNumber"))?;
71        Some(Self {
72            id,
73            model: text(device, "modelName"),
74            firmware,
75        })
76    }
77
78    /// The name of its directory: the id with only letters, digits and
79    /// dashes, and a hash of the model and the firmware version, so that
80    /// every firmware has its own directory.
81    fn dir_name(&self) -> String {
82        let id: String = self
83            .id
84            .chars()
85            .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
86            .collect();
87        let mut hash = Sha256::new();
88        hash.update(self.model.as_deref().unwrap_or_default());
89        hash.update([0]);
90        hash.update(&self.firmware);
91        format!("{id}-{}", crate::session::to_hex(&hash.finalize()[..4]))
92    }
93}
94
95fn child<'a, 'input>(node: Node<'a, 'input>, name: &str) -> Option<Node<'a, 'input>> {
96    node.children()
97        .find(|n| n.is_element() && n.tag_name().name() == name)
98}
99
100/// The text of a child element, if it is not empty.
101fn text(node: Node<'_, '_>, name: &str) -> Option<String> {
102    let text = child(node, name)?.text()?.trim();
103    (!text.is_empty()).then(|| text.to_owned())
104}
105
106/// The cached descriptions of one device.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
108pub struct Entry {
109    /// The device, `None` if its file cannot be read.
110    pub device: Option<Device>,
111    /// The directory.
112    pub path: PathBuf,
113    /// The number of SCPDs.
114    pub scpds: usize,
115    /// The size of all files, in bytes.
116    pub bytes: u64,
117}
118
119/// The cache of the service descriptions in a directory.
120#[derive(Debug)]
121pub struct Cache {
122    dir: PathBuf,
123    memory: Mutex<HashMap<(Device, String), Scpd>>,
124}
125
126impl Cache {
127    /// A cache in `dir`, which is created when the first SCPD is stored.
128    pub fn new(dir: impl Into<PathBuf>) -> Self {
129        Self {
130            dir: dir.into(),
131            memory: Mutex::new(HashMap::new()),
132        }
133    }
134
135    /// The directory.
136    pub fn dir(&self) -> &Path {
137        &self.dir
138    }
139
140    /// The cached devices, sorted by their directory.
141    ///
142    /// # Errors
143    ///
144    /// The errors of reading the directory, except that it does not exist.
145    pub fn list(&self) -> io::Result<Vec<Entry>> {
146        let mut entries = Vec::new();
147        for path in self.device_dirs()? {
148            let mut scpds = 0;
149            let mut bytes = 0;
150            for file in fs::read_dir(&path)? {
151                let file = file?;
152                bytes += file.metadata()?.len();
153                if file.file_name() != DEVICE_FILE {
154                    scpds += 1;
155                }
156            }
157            entries.push(Entry {
158                device: read_device(&path),
159                path,
160                scpds,
161                bytes,
162            });
163        }
164        Ok(entries)
165    }
166
167    /// Removes the cached devices, and the directory if nothing else is in
168    /// it. Other files are left alone, in case the directory was set to
169    /// one that holds more. Returns the number of devices removed.
170    ///
171    /// # Errors
172    ///
173    /// The errors of removing the files.
174    pub fn clear(&self) -> io::Result<usize> {
175        self.lock().clear();
176        let dirs = self.device_dirs()?;
177        for dir in &dirs {
178            fs::remove_dir_all(dir)?;
179        }
180        // Fails if other files remain, which stay.
181        let _ = fs::remove_dir(&self.dir);
182        Ok(dirs.len())
183    }
184
185    /// The directories of devices: those with a [`DEVICE_FILE`].
186    fn device_dirs(&self) -> io::Result<Vec<PathBuf>> {
187        let entries = match fs::read_dir(&self.dir) {
188            Ok(entries) => entries,
189            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
190            Err(error) => return Err(error),
191        };
192        let mut dirs = Vec::new();
193        for entry in entries {
194            let path = entry?.path();
195            if path.join(DEVICE_FILE).is_file() {
196                dirs.push(path);
197            }
198        }
199        dirs.sort();
200        Ok(dirs)
201    }
202
203    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<(Device, String), Scpd>> {
204        self.memory
205            .lock()
206            .unwrap_or_else(std::sync::PoisonError::into_inner)
207    }
208
209    /// Reads an SCPD from the directory of the device, if it is there and
210    /// was stored for the same device.
211    fn read(&self, device: &Device, url: &str) -> Option<Scpd> {
212        let dir = self.dir.join(device.dir_name());
213        if read_device(&dir).as_ref() != Some(device) {
214            return None;
215        }
216        Scpd::parse(&fs::read_to_string(dir.join(file_name(url))).ok()?).ok()
217    }
218
219    /// Writes an SCPD to the directory of the device and firmware. A new
220    /// directory replaces the ones of other firmware versions of the device,
221    /// and one that names another device is replaced.
222    fn write(&self, device: &Device, url: &str, xml: &str) -> io::Result<()> {
223        let dir = self.dir.join(device.dir_name());
224        if read_device(&dir).as_ref() != Some(device) {
225            for old in self.device_dirs()? {
226                if old != dir && read_device(&old).is_some_and(|old| old.id == device.id) {
227                    // A process with the old firmware may still write there;
228                    // then its next run removes it.
229                    let _ = fs::remove_dir_all(&old);
230                }
231            }
232            match fs::remove_dir_all(&dir) {
233                Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
234                _ => {}
235            }
236            fs::create_dir_all(&dir)?;
237            write_atomic(&dir.join(DEVICE_FILE), &serde_json::to_vec(device)?)?;
238        }
239        write_atomic(&dir.join(file_name(url)), xml.as_bytes())
240    }
241}
242
243impl DescriptionCache for Cache {
244    fn scpd(&self, description: &str, url: &str) -> Option<Scpd> {
245        let key = (Device::of(description)?, url.to_owned());
246        if let Some(scpd) = self.lock().get(&key) {
247            return Some(scpd.clone());
248        }
249        let scpd = self.read(&key.0, url)?;
250        self.lock().insert(key, scpd.clone());
251        Some(scpd)
252    }
253
254    fn store(&self, description: &str, url: &str, xml: &str, scpd: &Scpd) {
255        let Some(device) = Device::of(description) else {
256            return;
257        };
258        // The cache only saves time; without it, the SCPD is fetched again.
259        let _ = self.write(&device, url, xml);
260        self.lock().insert((device, url.to_owned()), scpd.clone());
261    }
262}
263
264/// The device named in the directory, if its file can be read.
265fn read_device(dir: &Path) -> Option<Device> {
266    serde_json::from_slice(&fs::read(dir.join(DEVICE_FILE)).ok()?).ok()
267}
268
269/// The file of the SCPD at `url`: a hash, so that any URL gives a valid and
270/// distinct name.
271fn file_name(url: &str) -> String {
272    let hash = Sha256::digest(url.as_bytes());
273    format!("{}.xml", crate::session::to_hex(&hash[..16]))
274}
275
276/// Writes a file through a temporary file and a rename, so that readers
277/// never see a part of it.
278fn write_atomic(path: &Path, contents: &[u8]) -> io::Result<()> {
279    static COUNTER: AtomicU64 = AtomicU64::new(0);
280    let count = COUNTER.fetch_add(1, Ordering::Relaxed);
281    let temporary = path.with_extension(format!("{}.{count}.tmp", std::process::id()));
282    let result = fs::write(&temporary, contents).and_then(|()| fs::rename(&temporary, path));
283    if result.is_err() {
284        let _ = fs::remove_file(&temporary);
285    }
286    result
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    const DESCRIPTION: &str = r"<root>
294<systemVersion><Display>285.08.25</Display></systemVersion>
295<device><UDN>uuid:1</UDN><modelName>FRITZ!Box 7690</modelName></device>
296</root>";
297
298    const SCPD: &str =
299        r"<scpd><actionList><action><name>GetInfo</name></action></actionList></scpd>";
300
301    fn device() -> Device {
302        Device {
303            id: "uuid:1".to_owned(),
304            model: Some("FRITZ!Box 7690".to_owned()),
305            firmware: "285.08.25".to_owned(),
306        }
307    }
308
309    #[test]
310    fn names_devices() {
311        assert_eq!(Device::of(DESCRIPTION), Some(device()));
312        let serial = "<root><systemVersion><Display>7.32</Display></systemVersion>\
313            <device><serialNumber>AA:BB</serialNumber></device></root>";
314        let device = Device::of(serial).unwrap();
315        assert_eq!(
316            (device.id.as_str(), device.model.as_deref()),
317            ("AA:BB", None)
318        );
319        assert_eq!(device.dir_name(), "AA-BB-1009c30b");
320        for unknown in [
321            "not xml",
322            "<root/>",
323            "<root><device><UDN>uuid:1</UDN></device></root>",
324            "<root><systemVersion><Display> </Display></systemVersion><device><UDN>u</UDN></device></root>",
325            "<root><systemVersion><Display>1</Display></systemVersion><device/></root>",
326        ] {
327            assert_eq!(Device::of(unknown), None, "{unknown}");
328        }
329    }
330
331    #[test]
332    fn keeps_scpds_per_device_and_firmware() {
333        let dir = tempfile::tempdir().unwrap();
334        let cache = Cache::new(dir.path().join("cache"));
335        assert_eq!(cache.dir(), dir.path().join("cache"));
336        assert_eq!(cache.list().unwrap(), []);
337        assert_eq!(cache.scpd(DESCRIPTION, "/a.xml"), None);
338
339        let scpd = Scpd::parse(SCPD).unwrap();
340        cache.store(DESCRIPTION, "/a.xml", SCPD, &scpd);
341        assert_eq!(cache.scpd(DESCRIPTION, "/a.xml"), Some(scpd.clone()));
342        assert_eq!(cache.scpd(DESCRIPTION, "/b.xml"), None);
343
344        // Another process reads the files.
345        let other = Cache::new(cache.dir());
346        assert_eq!(other.scpd(DESCRIPTION, "/a.xml"), Some(scpd.clone()));
347        let entries = other.list().unwrap();
348        assert_eq!(entries.len(), 1);
349        assert_eq!(entries[0].device, Some(device()));
350        assert_eq!(entries[0].path, cache.dir().join(device().dir_name()));
351        assert!(device().dir_name().starts_with("uuid-1-"));
352        assert_eq!(entries[0].scpds, 1);
353        assert!(entries[0].bytes > SCPD.len() as u64);
354
355        // A new firmware replaces the files of the device.
356        let updated = DESCRIPTION.replace("285.08.25", "285.08.30");
357        assert_eq!(Cache::new(cache.dir()).scpd(&updated, "/a.xml"), None);
358        other.store(&updated, "/b.xml", SCPD, &scpd);
359        assert_eq!(Cache::new(cache.dir()).scpd(DESCRIPTION, "/a.xml"), None);
360        assert_eq!(Cache::new(cache.dir()).scpd(&updated, "/a.xml"), None);
361        assert_eq!(Cache::new(cache.dir()).scpd(&updated, "/b.xml"), Some(scpd));
362        assert_eq!(other.list().unwrap()[0].scpds, 1);
363    }
364
365    #[test]
366    fn keeps_every_firmware_in_its_own_directory() {
367        let dir = tempfile::tempdir().unwrap();
368        let scpd = Scpd::parse(SCPD).unwrap();
369        let updated = DESCRIPTION.replace("285.08.25", "285.08.30");
370        let old = Device::of(DESCRIPTION).unwrap();
371        let new = Device::of(&updated).unwrap();
372        assert_ne!(old.dir_name(), new.dir_name());
373        let mut other_model = old.clone();
374        other_model.model = None;
375        assert_ne!(old.dir_name(), other_model.dir_name());
376
377        // A process with the old firmware checked its directory, then
378        // another one stored the new firmware. The SCPD the first one writes
379        // afterwards never ends up in the directory of the new firmware.
380        let before = Cache::new(dir.path());
381        before.store(DESCRIPTION, "/a.xml", SCPD, &scpd);
382        let after = Cache::new(dir.path());
383        after.store(&updated, "/b.xml", SCPD, &scpd);
384        assert!(!dir.path().join(old.dir_name()).exists());
385        let late = dir.path().join(old.dir_name()).join(file_name("/c.xml"));
386        write_atomic(&late, SCPD.as_bytes()).unwrap_err();
387        let entries = after.list().unwrap();
388        assert_eq!(entries.len(), 1);
389        assert_eq!(entries[0].device, Some(new.clone()));
390        assert_eq!(entries[0].scpds, 1);
391        assert_eq!(Cache::new(dir.path()).scpd(&updated, "/c.xml"), None);
392
393        // Each firmware replaces the directory of the other one.
394        before.store(DESCRIPTION, "/c.xml", SCPD, &scpd);
395        assert_eq!(after.list().unwrap()[0].device, Some(old));
396        after.store(&updated, "/b.xml", SCPD, &scpd);
397        let entries = after.list().unwrap();
398        assert_eq!(entries.len(), 1);
399        assert_eq!(entries[0].device, Some(new));
400        assert_eq!(Cache::new(dir.path()).scpd(DESCRIPTION, "/c.xml"), None);
401
402        // Other devices keep their directories.
403        let second = DESCRIPTION.replace("uuid:1", "uuid:2");
404        after.store(&second, "/a.xml", SCPD, &scpd);
405        assert_eq!(after.list().unwrap().len(), 2);
406        assert_eq!(Cache::new(dir.path()).scpd(&updated, "/b.xml"), Some(scpd));
407    }
408
409    #[test]
410    fn ignores_what_it_cannot_parse() {
411        let dir = tempfile::tempdir().unwrap();
412        let cache = Cache::new(dir.path());
413        let scpd = Scpd::parse(SCPD).unwrap();
414        cache.store(DESCRIPTION, "/a.xml", SCPD, &scpd);
415        let file = dir
416            .path()
417            .join(device().dir_name())
418            .join(file_name("/a.xml"));
419        fs::write(&file, "<scpd><actionList>").unwrap();
420        assert_eq!(Cache::new(dir.path()).scpd(DESCRIPTION, "/a.xml"), None);
421
422        fs::write(dir.path().join(device().dir_name()).join(DEVICE_FILE), "{").unwrap();
423        let entries = cache.list().unwrap();
424        assert_eq!(entries[0].device, None);
425        assert_eq!(Cache::new(dir.path()).scpd(DESCRIPTION, "/a.xml"), None);
426
427        // A description without a firmware version is not cached.
428        let unversioned = "<root><device><UDN>uuid:2</UDN></device></root>";
429        cache.store(unversioned, "/a.xml", SCPD, &scpd);
430        assert_eq!(cache.scpd(unversioned, "/a.xml"), None);
431        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
432    }
433
434    #[test]
435    fn clears_only_its_own_files() {
436        let dir = tempfile::tempdir().unwrap();
437        let cache = Cache::new(dir.path());
438        assert_eq!(Cache::new(dir.path().join("missing")).clear().unwrap(), 0);
439        let scpd = Scpd::parse(SCPD).unwrap();
440        cache.store(DESCRIPTION, "/a.xml", SCPD, &scpd);
441        fs::create_dir(dir.path().join("other")).unwrap();
442        fs::write(dir.path().join("notes.txt"), "kept").unwrap();
443
444        assert_eq!(cache.clear().unwrap(), 1);
445        assert!(!dir.path().join(device().dir_name()).exists());
446        assert!(dir.path().join("other").exists());
447        assert!(dir.path().join("notes.txt").exists());
448        assert_eq!(cache.scpd(DESCRIPTION, "/a.xml"), None);
449
450        // An empty directory is removed.
451        let cache = Cache::new(dir.path().join("cache"));
452        cache.store(DESCRIPTION, "/a.xml", SCPD, &scpd);
453        assert_eq!(cache.clear().unwrap(), 1);
454        assert!(!cache.dir().exists());
455    }
456
457    #[test]
458    fn survives_an_unwritable_directory() {
459        let dir = tempfile::tempdir().unwrap();
460        let file = dir.path().join("file");
461        fs::write(&file, "").unwrap();
462        // The cache directory is a file, so nothing can be written.
463        let cache = Cache::new(&file);
464        let scpd = Scpd::parse(SCPD).unwrap();
465        cache.store(DESCRIPTION, "/a.xml", SCPD, &scpd);
466        // The memory still has it.
467        assert_eq!(cache.scpd(DESCRIPTION, "/a.xml"), Some(scpd));
468        assert!(Cache::new(&file).list().is_err());
469        assert!(write_atomic(&file.join("x"), b"").is_err());
470    }
471}