1use 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
35pub const ENV_CACHE_DIR: &str = "FRITZ_CACHE_DIR";
37
38const DEVICE_FILE: &str = "device.json";
40
41pub 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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
52pub struct Device {
53 pub id: String,
55 pub model: Option<String>,
57 pub firmware: String,
59}
60
61impl Device {
62 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 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
100fn 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
108pub struct Entry {
109 pub device: Option<Device>,
111 pub path: PathBuf,
113 pub scpds: usize,
115 pub bytes: u64,
117}
118
119#[derive(Debug)]
121pub struct Cache {
122 dir: PathBuf,
123 memory: Mutex<HashMap<(Device, String), Scpd>>,
124}
125
126impl Cache {
127 pub fn new(dir: impl Into<PathBuf>) -> Self {
129 Self {
130 dir: dir.into(),
131 memory: Mutex::new(HashMap::new()),
132 }
133 }
134
135 pub fn dir(&self) -> &Path {
137 &self.dir
138 }
139
140 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 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 let _ = fs::remove_dir(&self.dir);
182 Ok(dirs.len())
183 }
184
185 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 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 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 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 let _ = self.write(&device, url, xml);
260 self.lock().insert((device, url.to_owned()), scpd.clone());
261 }
262}
263
264fn read_device(dir: &Path) -> Option<Device> {
266 serde_json::from_slice(&fs::read(dir.join(DEVICE_FILE)).ok()?).ok()
267}
268
269fn file_name(url: &str) -> String {
272 let hash = Sha256::digest(url.as_bytes());
273 format!("{}.xml", crate::session::to_hex(&hash[..16]))
274}
275
276fn 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 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 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 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 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 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 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 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 let cache = Cache::new(&file);
464 let scpd = Scpd::parse(SCPD).unwrap();
465 cache.store(DESCRIPTION, "/a.xml", SCPD, &scpd);
466 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}