1use std::collections::{BTreeMap, BTreeSet};
2use std::fs;
3use std::io::ErrorKind;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use anyhow::{Context, Result};
8
9use super::storage::run_bounded;
10use super::store_key::{remove_if_present, replace_private_file};
11
12pub const HARDWARE_BINDING_FILE: &str = "device.hardware";
13
14const DISK: &str = "disk";
17const DEVICETREE: &str = "devicetree";
18const PLATFORM: &str = "platform";
19
20const HARDWARE_BY_ID_PREFIXES: &[&str] = &["nvme-", "ata-", "wwn-"];
24const MAX_STACK_DEPTH: usize = 8;
25const IOREG: &str = "/usr/sbin/ioreg";
26const IOREG_TIMEOUT: Duration = Duration::from_secs(10);
27
28#[derive(Debug, Clone, Default, PartialEq, Eq)]
31pub struct HardwareId(BTreeMap<String, BTreeSet<String>>);
32
33impl HardwareId {
34 pub fn parse(text: &str) -> Self {
36 let mut id = Self::default();
37 for line in text.lines() {
38 if let Some((kind, value)) = line.split_once(':') {
39 id.insert(kind, value);
40 }
41 }
42 id
43 }
44
45 pub fn insert(&mut self, kind: &str, value: &str) {
46 let kind = kind.trim();
47 let value = value.trim_matches(|c: char| c.is_whitespace() || c == '\0');
48 if kind.is_empty() || value.is_empty() || kind.contains(':') {
49 return;
50 }
51 if kind.chars().chain(value.chars()).any(char::is_control) {
52 return;
53 }
54 self.0
55 .entry(kind.to_string())
56 .or_default()
57 .insert(value.to_string());
58 }
59
60 pub fn is_empty(&self) -> bool {
61 self.0.is_empty()
62 }
63
64 pub fn to_text(&self) -> String {
65 let mut text = String::new();
66 for (kind, values) in &self.0 {
67 for value in values {
68 text.push_str(kind);
69 text.push(':');
70 text.push_str(value);
71 text.push('\n');
72 }
73 }
74 text
75 }
76
77 pub fn matches(&self, current: &HardwareId) -> Option<bool> {
81 let mut compared = false;
82 for (kind, recorded) in &self.0 {
83 let Some(now) = current.0.get(kind) else {
84 continue;
85 };
86 if recorded.is_disjoint(now) {
87 return Some(false);
88 }
89 compared = true;
90 }
91 compared.then_some(true)
92 }
93
94 pub fn refreshed(&self, current: &HardwareId) -> HardwareId {
97 let mut refreshed = self.clone();
98 for (kind, values) in ¤t.0 {
99 refreshed.0.insert(kind.clone(), values.clone());
100 }
101 refreshed
102 }
103}
104
105pub trait HardwareSource: Send + Sync {
106 fn read(&self, data_dir: &Path) -> HardwareId;
108}
109
110#[derive(Debug, Clone, Copy, Default)]
115pub struct SystemHardware;
116
117impl HardwareSource for SystemHardware {
118 fn read(&self, data_dir: &Path) -> HardwareId {
119 if cfg!(target_os = "macos") {
120 mac_platform_id()
121 } else if cfg!(target_os = "linux") {
122 LinuxHardware::system().read(data_dir)
123 } else {
124 HardwareId::default()
125 }
126 }
127}
128
129fn mac_platform_id() -> HardwareId {
130 let mut id = HardwareId::default();
131 let args = ["-rd1", "-c", "IOPlatformExpertDevice"];
132 match run_bounded(Path::new(IOREG), &args, &[], IOREG_TIMEOUT) {
133 Ok(out) => {
134 if let Some(uuid) = parse_ioreg(&String::from_utf8_lossy(&out)) {
135 id.insert(PLATFORM, &uuid);
136 }
137 }
138 Err(e) => tracing::warn!("cannot read this Mac's platform UUID: {e:#}"),
139 }
140 id
141}
142
143fn parse_ioreg(text: &str) -> Option<String> {
144 text.lines().find_map(|line| {
145 let (key, value) = line.split_once('=')?;
146 if key.trim() != "\"IOPlatformUUID\"" {
147 return None;
148 }
149 let value = value.trim().trim_matches('"').trim();
150 (!value.is_empty()).then(|| value.to_string())
151 })
152}
153
154pub(crate) struct LinuxHardware {
155 sys: PathBuf,
156 by_id: PathBuf,
157 devicetree_serial: PathBuf,
158 mountinfo: PathBuf,
159}
160
161impl LinuxHardware {
162 fn system() -> Self {
163 Self {
164 sys: PathBuf::from("/sys"),
165 by_id: PathBuf::from("/dev/disk/by-id"),
166 devicetree_serial: PathBuf::from("/sys/firmware/devicetree/base/serial-number"),
167 mountinfo: PathBuf::from("/proc/self/mountinfo"),
168 }
169 }
170
171 fn read(&self, data_dir: &Path) -> HardwareId {
172 let mut id = self
173 .block_dir(data_dir)
174 .map(|block| self.block_ids(&block))
175 .unwrap_or_default();
176 if let Some(serial) = read_text(&self.devicetree_serial) {
177 id.insert(DEVICETREE, &serial);
178 }
179 id
180 }
181
182 fn block_dir(&self, data_dir: &Path) -> Option<PathBuf> {
186 if let Some((major, minor)) = device_number(data_dir) {
187 let dir = self.sys.join("dev/block").join(format!("{major}:{minor}"));
188 if dir.exists() {
189 return Some(dir);
190 }
191 }
192 let table = fs::read_to_string(&self.mountinfo).ok()?;
193 let source = mount_source(&table, &fs::canonicalize(data_dir).ok()?)?;
194 if !source.is_absolute() {
195 return None;
196 }
197 let name = fs::canonicalize(source).ok()?.file_name()?.to_owned();
198 let dir = self.sys.join("class/block").join(name);
199 dir.exists().then_some(dir)
200 }
201
202 fn block_ids(&self, block: &Path) -> HardwareId {
203 let mut disks = BTreeSet::new();
204 self.collect_disks(block, 0, &mut disks);
205 let mut id = HardwareId::default();
206 for disk in &disks {
207 self.disk_ids(disk, &mut id);
208 }
209 id
210 }
211
212 fn collect_disks(&self, block: &Path, depth: usize, disks: &mut BTreeSet<PathBuf>) {
213 if depth > MAX_STACK_DEPTH {
214 return;
215 }
216 let Ok(block) = fs::canonicalize(block) else {
217 return;
218 };
219 if block.join("partition").is_file() {
220 if let Some(disk) = block.parent() {
221 self.collect_disks(disk, depth + 1, disks);
222 }
223 return;
224 }
225 let slaves = entry_names(&block.join("slaves"));
226 if slaves.is_empty() {
227 disks.insert(block);
228 return;
229 }
230 for slave in slaves {
231 let slave = self.sys.join("class/block").join(slave);
232 self.collect_disks(&slave, depth + 1, disks);
233 }
234 }
235
236 fn disk_ids(&self, disk: &Path, id: &mut HardwareId) {
237 if let Some(serial) = read_text(&disk.join("device/serial")) {
238 id.insert(DISK, &serial);
239 }
240 let Some(name) = disk.file_name() else {
241 return;
242 };
243 for link in entry_names(&self.by_id) {
244 let Some(link_name) = link.to_str() else {
245 continue;
246 };
247 if !HARDWARE_BY_ID_PREFIXES
248 .iter()
249 .any(|prefix| link_name.starts_with(prefix))
250 {
251 continue;
252 }
253 if fs::read_link(self.by_id.join(&link))
254 .is_ok_and(|target| target.file_name() == Some(name))
255 {
256 id.insert(DISK, link_name);
257 }
258 }
259 }
260}
261
262#[cfg(unix)]
263fn device_number(path: &Path) -> Option<(u64, u64)> {
264 use std::os::unix::fs::MetadataExt;
265
266 let dev = fs::metadata(path).ok()?.dev();
267 let major = ((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0x0fff);
268 let minor = ((dev >> 12) & 0xffff_ff00) | (dev & 0xff);
269 Some((major, minor))
270}
271
272#[cfg(not(unix))]
273fn device_number(_path: &Path) -> Option<(u64, u64)> {
274 None
275}
276
277fn mount_source(mountinfo: &str, path: &Path) -> Option<PathBuf> {
280 let mut best: Option<(usize, PathBuf)> = None;
281 for line in mountinfo.lines() {
282 let fields: Vec<&str> = line.split(' ').collect();
283 let Some(separator) = fields.iter().position(|f| *f == "-") else {
284 continue;
285 };
286 let (Some(mount_point), Some(source)) = (fields.get(4), fields.get(separator + 2)) else {
287 continue;
288 };
289 if separator < 6 {
290 continue;
291 }
292 let mount_point = PathBuf::from(unescape_mount_field(mount_point));
293 if !path.starts_with(&mount_point) {
294 continue;
295 }
296 let depth = mount_point.components().count();
297 if best.as_ref().is_none_or(|(deepest, _)| depth >= *deepest) {
298 best = Some((depth, PathBuf::from(unescape_mount_field(source))));
299 }
300 }
301 best.map(|(_, source)| source)
302}
303
304fn unescape_mount_field(field: &str) -> String {
307 let bytes = field.as_bytes();
308 let mut out = Vec::with_capacity(bytes.len());
309 let mut i = 0;
310 while i < bytes.len() {
311 let octal = bytes
312 .get(i + 1..i + 4)
313 .filter(|d| bytes[i] == b'\\' && d.iter().all(|b| (b'0'..=b'7').contains(b)));
314 match octal.and_then(|d| u8::from_str_radix(std::str::from_utf8(d).ok()?, 8).ok()) {
315 Some(byte) => {
316 out.push(byte);
317 i += 4;
318 }
319 None => {
320 out.push(bytes[i]);
321 i += 1;
322 }
323 }
324 }
325 String::from_utf8_lossy(&out).into_owned()
326}
327
328fn read_text(path: &Path) -> Option<String> {
329 let bytes = fs::read(path).ok()?;
330 let text = String::from_utf8_lossy(&bytes);
331 let text = text.trim_matches(|c: char| c.is_whitespace() || c == '\0');
332 (!text.is_empty()).then(|| text.to_string())
333}
334
335fn entry_names(dir: &Path) -> Vec<std::ffi::OsString> {
336 let Ok(entries) = fs::read_dir(dir) else {
337 return Vec::new();
338 };
339 let mut names: Vec<_> = entries.flatten().map(|e| e.file_name()).collect();
340 names.sort();
341 names
342}
343
344pub fn read_binding(data_dir: &Path) -> Result<Option<HardwareId>> {
346 let path = data_dir.join(HARDWARE_BINDING_FILE);
347 match fs::read_to_string(&path) {
348 Ok(text) => Ok(Some(HardwareId::parse(&text))),
349 Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
350 Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
351 }
352}
353
354pub fn write_binding(data_dir: &Path, id: &HardwareId) -> Result<()> {
356 if id.is_empty() {
357 return remove_if_present(&data_dir.join(HARDWARE_BINDING_FILE));
358 }
359 replace_private_file(data_dir, HARDWARE_BINDING_FILE, id.to_text().as_bytes())
360}
361
362#[cfg(test)]
363mod tests {
364 use std::os::unix::fs::symlink;
365
366 use super::*;
367
368 fn id(lines: &[&str]) -> HardwareId {
369 HardwareId::parse(&lines.join("\n"))
370 }
371
372 struct Tree {
373 root: tempfile::TempDir,
374 }
375
376 impl Tree {
377 fn new() -> Self {
378 let tree = Self {
379 root: tempfile::tempdir().unwrap(),
380 };
381 for dir in ["sys/class/block", "sys/dev/block", "by-id", "dt", "dev"] {
382 fs::create_dir_all(tree.path(dir)).unwrap();
383 }
384 tree
385 }
386
387 fn path(&self, rel: &str) -> PathBuf {
388 self.root.path().join(rel)
389 }
390
391 fn hardware(&self) -> LinuxHardware {
392 LinuxHardware {
393 sys: self.path("sys"),
394 by_id: self.path("by-id"),
395 devicetree_serial: self.path("dt/serial-number"),
396 mountinfo: self.path("mountinfo"),
397 }
398 }
399
400 fn class_link(&self, name: &str, target: &Path) {
401 symlink(target, self.path("sys/class/block").join(name)).unwrap();
402 }
403
404 fn disk(&self, name: &str, serial: Option<&str>) -> PathBuf {
405 let dir = self.path("sys/devices/pci0000:00/block").join(name);
406 fs::create_dir_all(dir.join("device")).unwrap();
407 if let Some(serial) = serial {
408 fs::write(dir.join("device/serial"), format!("{serial}\n")).unwrap();
409 }
410 self.class_link(name, &dir);
411 dir
412 }
413
414 fn partition(&self, disk: &Path, name: &str) -> PathBuf {
415 let dir = disk.join(name);
416 fs::create_dir_all(&dir).unwrap();
417 fs::write(dir.join("partition"), "1\n").unwrap();
418 self.class_link(name, &dir);
419 dir
420 }
421
422 fn stacked(&self, name: &str, slaves: &[&str]) -> PathBuf {
423 let dir = self.path("sys/devices/virtual/block").join(name);
424 fs::create_dir_all(dir.join("slaves")).unwrap();
425 for slave in slaves {
426 symlink(
427 self.path("sys/class/block").join(slave),
428 dir.join("slaves").join(slave),
429 )
430 .unwrap();
431 }
432 self.class_link(name, &dir);
433 dir
434 }
435
436 fn by_id(&self, name: &str, target: &str) {
437 symlink(format!("../../{target}"), self.path("by-id").join(name)).unwrap();
438 }
439
440 fn block(&self, name: &str) -> PathBuf {
441 self.path("sys/class/block").join(name)
442 }
443 }
444
445 #[test]
446 fn a_partition_resolves_to_its_disks_serial_and_hardware_names() {
447 let tree = Tree::new();
448 let disk = tree.disk("nvme0n1", Some("S4EWNX0R123456"));
449 tree.partition(&disk, "nvme0n1p2");
450 tree.by_id("nvme-Example_SSD_S4EWNX0R123456", "nvme0n1");
451 tree.by_id("nvme-Example_SSD_S4EWNX0R123456-part2", "nvme0n1p2");
452 tree.by_id("nvme-eui.0025385b91b0f1aa", "nvme0n1");
453 tree.by_id("wwn-0x5002538e40a1b2c3", "nvme0n1");
454
455 assert_eq!(
456 tree.hardware().block_ids(&tree.block("nvme0n1p2")),
457 id(&[
458 "disk:S4EWNX0R123456",
459 "disk:nvme-Example_SSD_S4EWNX0R123456",
460 "disk:nvme-eui.0025385b91b0f1aa",
461 "disk:wwn-0x5002538e40a1b2c3",
462 ])
463 );
464 }
465
466 #[test]
467 fn a_dm_device_resolves_through_its_slaves_to_the_physical_disk() {
468 let tree = Tree::new();
469 let disk = tree.disk("sda", None);
470 tree.partition(&disk, "sda3");
471 tree.stacked("dm-0", &["sda3"]);
472 tree.stacked("dm-1", &["dm-0"]);
473 tree.by_id("ata-Example_HDD_WD-WCC4E1234567", "sda");
474 tree.by_id("dm-uuid-CRYPT-LUKS2-0123abcd-luks", "dm-0");
475 tree.by_id("dm-uuid-LVM-abcdef0123456789", "dm-1");
476 tree.by_id("lvm-pv-uuid-Ab12Cd-34Ef", "dm-0");
477 tree.by_id("dm-name-vg-root", "dm-1");
478
479 assert_eq!(
480 tree.hardware().block_ids(&tree.block("dm-1")),
481 id(&["disk:ata-Example_HDD_WD-WCC4E1234567"])
482 );
483 }
484
485 #[test]
486 fn an_md_array_binds_the_set_of_member_serials() {
487 let tree = Tree::new();
488 let a = tree.disk("nvme0n1", Some("SERIAL-A"));
489 let b = tree.disk("nvme1n1", Some("SERIAL-B"));
490 tree.partition(&a, "nvme0n1p1");
491 tree.partition(&b, "nvme1n1p1");
492 tree.stacked("md0", &["nvme0n1p1", "nvme1n1p1"]);
493
494 assert_eq!(
495 tree.hardware().block_ids(&tree.block("md0")),
496 id(&["disk:SERIAL-A", "disk:SERIAL-B"])
497 );
498 }
499
500 #[test]
501 fn image_copied_names_alone_give_no_id() {
502 let tree = Tree::new();
503 tree.stacked("dm-0", &[]);
504 tree.disk("loop0", None);
505 tree.by_id("dm-uuid-CRYPT-LUKS2-0123abcd-luks", "dm-0");
506 tree.by_id("lvm-pv-uuid-Ab12Cd-34Ef", "dm-0");
507 tree.by_id("dm-name-luks", "dm-0");
508
509 let hardware = tree.hardware();
510 assert!(hardware.block_ids(&tree.block("dm-0")).is_empty());
511 assert!(hardware.block_ids(&tree.block("loop0")).is_empty());
512 }
513
514 #[test]
515 fn a_stacking_loop_ends_without_an_id() {
516 let tree = Tree::new();
517 tree.stacked("dm-0", &["dm-1"]);
518 tree.stacked("dm-1", &["dm-0"]);
519 assert!(tree.hardware().block_ids(&tree.block("dm-0")).is_empty());
520 }
521
522 #[cfg(target_os = "linux")]
523 #[test]
524 fn the_data_dir_is_found_by_its_device_number() {
525 let tree = Tree::new();
526 let disk = tree.disk("mmcblk0", Some("0x1234abcd"));
527 let part = tree.partition(&disk, "mmcblk0p2");
528 let (major, minor) = device_number(tree.root.path()).unwrap();
529 symlink(&part, tree.path(&format!("sys/dev/block/{major}:{minor}"))).unwrap();
530 fs::write(tree.path("dt/serial-number"), "10000000abcdef01\0").unwrap();
531
532 assert_eq!(
533 tree.hardware().read(tree.root.path()),
534 id(&["disk:0x1234abcd", "devicetree:10000000abcdef01"])
535 );
536 }
537
538 #[test]
539 fn a_device_number_sysfs_lacks_falls_back_to_the_mount_source() {
540 let tree = Tree::new();
541 let disk = tree.disk("nvme0n1", Some("S4EW"));
542 tree.partition(&disk, "nvme0n1p2");
543 fs::write(tree.path("dev/nvme0n1p2"), "").unwrap();
544 let data_dir = tree.path("home/user/.second-brain");
545 fs::create_dir_all(&data_dir).unwrap();
546 let mount = fs::canonicalize(tree.path("home")).unwrap();
547 let source = tree.path("dev/nvme0n1p2");
548 fs::write(
549 tree.path("mountinfo"),
550 format!(
551 "22 1 0:21 / / rw shared:1 - tmpfs tmpfs rw\n\
552 36 22 0:31 /@home {} rw,relatime shared:2 - btrfs {} rw,subvol=/@home\n",
553 mount.display(),
554 source.display()
555 ),
556 )
557 .unwrap();
558
559 assert_eq!(tree.hardware().read(&data_dir), id(&["disk:S4EW"]));
560 }
561
562 #[test]
563 fn the_mount_source_is_the_longest_mount_point_over_the_path_and_the_last_mounted() {
564 let table = "22 1 0:21 / / rw - ext4 /dev/sda1 rw\n\
565 30 22 0:30 / /home rw - ext4 /dev/sdb1 rw\n\
566 31 22 0:31 / /home/us rw - ext4 /dev/sdc1 rw\n\
567 32 30 0:32 / /home/user\\040name rw shared:3 - ext4 /dev/sdd1 rw\n\
568 33 30 0:33 / /home/user\\040name rw - ext4 /dev/sde1 rw\n";
569 let source = |path: &str| mount_source(table, Path::new(path));
570 assert_eq!(
571 source("/home/user name/.second-brain"),
572 Some(PathBuf::from("/dev/sde1"))
573 );
574 assert_eq!(source("/home/user/x"), Some(PathBuf::from("/dev/sdb1")));
575 assert_eq!(source("/var/lib"), Some(PathBuf::from("/dev/sda1")));
576 assert_eq!(mount_source("garbage line\n", Path::new("/x")), None);
577 }
578
579 #[test]
580 fn hardware_ids_compare_per_kind() {
581 let disk_a = id(&["disk:A"]);
582 let cases = [
583 ("same disk", disk_a.clone(), id(&["disk:A"]), Some(true)),
584 ("other disk", disk_a.clone(), id(&["disk:B"]), Some(false)),
585 (
586 "one array member left",
587 id(&["disk:A", "disk:B"]),
588 id(&["disk:B", "disk:C"]),
589 Some(true),
590 ),
591 (
592 "every array member replaced",
593 id(&["disk:A", "disk:B"]),
594 id(&["disk:C", "disk:D"]),
595 Some(false),
596 ),
597 ("nothing read now", disk_a.clone(), id(&[]), None),
598 (
599 "no kind in common",
600 disk_a.clone(),
601 id(&["devicetree:P"]),
602 None,
603 ),
604 (
605 "the disk moved to another board",
606 id(&["disk:A", "devicetree:P"]),
607 id(&["disk:A", "devicetree:Q"]),
608 Some(false),
609 ),
610 (
611 "by-id links renamed under the same serial",
612 id(&["disk:S4EW", "disk:nvme-Old_Name_S4EW"]),
613 id(&["disk:S4EW", "disk:nvme-New_Name_S4EW"]),
614 Some(true),
615 ),
616 (
617 "a kind read only now",
618 disk_a.clone(),
619 id(&["disk:A", "devicetree:Q"]),
620 Some(true),
621 ),
622 ];
623 for (name, recorded, current, expected) in cases {
624 assert_eq!(recorded.matches(¤t), expected, "{name}");
625 }
626 }
627
628 #[test]
629 fn a_refreshed_binding_takes_the_kinds_read_now_and_keeps_the_rest() {
630 let recorded = id(&["disk:A", "disk:B", "devicetree:P"]);
631 assert_eq!(
632 recorded.refreshed(&id(&["disk:B", "disk:C"])),
633 id(&["disk:B", "disk:C", "devicetree:P"])
634 );
635 }
636
637 #[test]
638 fn ids_parse_strictly_and_round_trip_through_text() {
639 let parsed =
640 HardwareId::parse("disk: A1 \nnot an id\n:empty-kind\nby-id:\nserial:B\u{7}\n");
641 assert_eq!(parsed.to_text(), "disk:A1\n");
642 assert_eq!(HardwareId::parse(&parsed.to_text()), parsed);
643 }
644
645 #[test]
646 fn the_binding_file_round_trips_and_an_empty_id_removes_it() {
647 let dir = tempfile::tempdir().unwrap();
648 assert_eq!(read_binding(dir.path()).unwrap(), None);
649 let bound = id(&["disk:A", "disk:ata-X"]);
650 write_binding(dir.path(), &bound).unwrap();
651 assert_eq!(read_binding(dir.path()).unwrap(), Some(bound));
652 write_binding(dir.path(), &HardwareId::default()).unwrap();
653 assert!(!dir.path().join(HARDWARE_BINDING_FILE).exists());
654 write_binding(dir.path(), &HardwareId::default()).unwrap();
655 }
656
657 #[test]
658 fn ioreg_output_yields_the_platform_uuid() {
659 let text = "+-o J314sAP <class IOPlatformExpertDevice, id 0x100000110>\n\
660 {\n\
661 \x20 \"IOPlatformSerialNumber\" = \"C02ABCDEF\"\n\
662 \x20 \"IOPlatformUUID\" = \"1A2B3C4D-0000-1111-2222-333344445555\"\n\
663 }\n";
664 assert_eq!(
665 parse_ioreg(text).as_deref(),
666 Some("1A2B3C4D-0000-1111-2222-333344445555")
667 );
668 assert_eq!(parse_ioreg("no uuid here"), None);
669 assert_eq!(parse_ioreg(" \"IOPlatformUUID\" = \"\"\n"), None);
670 }
671}