Skip to main content

nibkeep_node/
place.rs

1//! Where a replica is: the drive that holds its folder, the folder itself, and on the drive
2//! that the system runs from, the computer, which tell a replica from a copy of it, as
3//! the technical design's section on copies of a replica decides.
4
5use std::fs;
6use std::io;
7use std::path::{Component, Path, PathBuf};
8use std::sync::Mutex;
9
10use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
11use nibkeep_crypto::rand_core::CryptoRng;
12use unicode_normalization::UnicodeNormalization;
13
14use crate::NodeError;
15
16/// The suite of the place file in version 1 of the specification.
17const SUITE: u8 = 1;
18
19/// What the hash of a drive's serial is keyed for, besides the salt.
20const SERIAL: &str = "nibkeep 2026-10 drive serial";
21
22/// What the hash of a folder's ID is keyed for, besides the salt.
23const FOLDER: &str = "nibkeep 2026-10 folder";
24
25/// What the hash of a computer's ID is keyed for, besides the salt.
26const COMPUTER: &str = "nibkeep 2026-10 computer";
27
28/// What the hash of a FAT or exFAT volume's UUID is keyed for, besides the salt.
29const VOLUME: &str = "nibkeep 2026-10 volume";
30
31/// The name of a replica's place file.
32pub(crate) const PLACE: &str = "place.cbor";
33
34/// A drive, as the system reports it.
35#[derive(Clone, Debug, Default, PartialEq, Eq)]
36#[expect(
37	clippy::struct_excessive_bools,
38	reason = "four facts that the system reports apart"
39)]
40pub struct Drive {
41	/// The serial of its file system, if the system reads one.
42	pub serial: Option<Vec<u8>>,
43	/// On FAT and exFAT, the volume's UUID as macOS makes it from the serial, which macOS
44	/// reads in place of the serial, and other systems make alike where they can.
45	pub volume: Option<Vec<u8>>,
46	/// Whether its file system keeps IDs of folders that a move keeps, as all but FAT and
47	/// exFAT do.
48	pub folder_ids: bool,
49	/// Whether the system runs from it.
50	pub system: bool,
51	/// Whether its file system is on another computer, as a network drive's is.
52	pub remote: bool,
53	/// Whether a program may take its files' content away to the cloud, as the folders of
54	/// Windows' cloud files and macOS's File Provider are.
55	pub cloud: bool,
56	/// Whether its file system keeps no journal, as FAT, exFAT and ext2: a removal without
57	/// unmounting can leave it inconsistent until it is checked (technical design: drives without a journal).
58	pub unjournaled: bool,
59	/// The physical drive's own name, as its partition table gives it, if declared: the
60	/// system's is read only when asked, as copies are counted.
61	pub disk: Option<Vec<u8>>,
62}
63
64/// Where a folder is now.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Whereabouts {
67	/// The drive that holds it.
68	pub drive: Drive,
69	/// The folder that the drive is mounted at.
70	pub mount: PathBuf,
71	/// The folder's ID on its file system, if the file system keeps IDs that a move keeps.
72	pub folder: Option<Vec<u8>>,
73	/// The folder's path on the drive, from [`Whereabouts::mount`], or `None` in an app's own
74	/// folder on a phone.
75	pub path: Option<String>,
76	/// The computer's ID, if the system gives one: on a phone, the phone's.
77	pub computer: Option<Vec<u8>>,
78	/// Whether this is an app's own folder on a phone, where the phone's ID has to be there
79	/// and match.
80	pub phone: bool,
81}
82
83/// Folders whose whereabouts are declared rather than read.
84static DECLARED: Mutex<Vec<Declared>> = Mutex::new(Vec::new());
85
86#[derive(Clone, Debug)]
87enum Declared {
88	/// A drive mounted at a folder, on a computer.
89	Drive {
90		mount: PathBuf,
91		drive: Drive,
92		computer: Option<Vec<u8>>,
93	},
94	/// An app's own folder on a phone, the phone's ID, and the name that the apps of one
95	/// developer share for the phone, if the app gave one.
96	Phone {
97		folder: PathBuf,
98		phone: Vec<u8>,
99		disk: Option<Vec<u8>>,
100	},
101}
102
103impl Declared {
104	fn folder(&self) -> &Path {
105		match self {
106			Self::Drive { mount, .. } => mount,
107			Self::Phone { folder, .. } => folder,
108		}
109	}
110}
111
112/// Declares that the folders in `mount` are on `drive`, mounted there, on the computer whose
113/// ID is `computer`, whatever the system reports: for tests, which pretend that folders are
114/// on other drives and computers. The IDs of folders are still read from the file system
115/// that holds them, if `drive` keeps them. A later declaration of the same folder replaces
116/// it.
117#[doc(hidden)]
118pub fn declare_drive(mount: &Path, drive: Drive, computer: Option<Vec<u8>>) {
119	declare(Declared::Drive {
120		mount: canonical(mount),
121		drive,
122		computer,
123	});
124}
125
126/// Declares that `folder` is an app's own folder on a phone, which no other app reaches,
127/// and `phone` the phone's ID, which the app keeps where the system never copies it to
128/// another phone: the replicas in it are told from copies by the phone's ID alone, as the
129/// folder's path may change when the app is updated.
130pub fn declare_phone(folder: &Path, phone: Vec<u8>) {
131	declare(Declared::Phone {
132		folder: canonical(folder),
133		phone,
134		disk: None,
135	});
136}
137
138/// Declares an app's own folder on a phone as [`declare_phone`] does, with `disk`, a name of
139/// the phone that the apps of one developer share, such as Android's ID for them: replicas
140/// of such apps on one phone are on one disk, and count as one copy.
141pub fn declare_phone_with_disk(folder: &Path, phone: Vec<u8>, disk: Vec<u8>) {
142	declare(Declared::Phone {
143		folder: canonical(folder),
144		phone,
145		disk: Some(disk).filter(|disk| !disk.is_empty()),
146	});
147}
148
149fn declare(declared: Declared) {
150	let mut all = DECLARED
151		.lock()
152		.unwrap_or_else(std::sync::PoisonError::into_inner);
153	all.retain(|other| other.folder() != declared.folder());
154	all.push(declared);
155}
156
157/// A folder as the file system resolves it: the deepest folder of it that exists, resolved,
158/// and the rest of its names after it, so that a folder declared before it exists, through a
159/// link such as Android's `/data/user/0`, is the same folder once it does.
160fn canonical(folder: &Path) -> PathBuf {
161	let mut rest = Vec::new();
162	let mut existing = folder;
163	loop {
164		if let Ok(resolved) = fs::canonicalize(existing) {
165			return rest
166				.iter()
167				.rev()
168				.fold(resolved, |path, name| path.join(name));
169		}
170		match (existing.parent(), existing.file_name()) {
171			(Some(parent), Some(name)) => {
172				rest.push(name.to_owned());
173				existing = parent;
174			}
175			_ => return folder.to_owned(),
176		}
177	}
178}
179
180/// The computer's ID, as the place file records it on the system's drive: `None` where
181/// the system gives none.
182#[cfg(not(any(target_os = "android", target_os = "ios")))]
183pub(crate) fn computer_id() -> Option<Vec<u8>> {
184	system::computer()
185}
186
187/// Where a folder is now: as declared, if a folder that holds it was, or as the system
188/// reports.
189pub(crate) fn whereabouts(folder: &Path) -> Whereabouts {
190	let folder = canonical(folder);
191	let declared = DECLARED
192		.lock()
193		.unwrap_or_else(std::sync::PoisonError::into_inner)
194		.iter()
195		.filter(|declared| folder.starts_with(declared.folder()))
196		.max_by_key(|declared| declared.folder().components().count())
197		.cloned();
198	match declared {
199		Some(Declared::Phone { folder, phone, .. }) => Whereabouts {
200			drive: Drive {
201				system: true,
202				..Drive::default()
203			},
204			mount: folder,
205			folder: None,
206			path: None,
207			computer: Some(phone).filter(|phone| !phone.is_empty()),
208			phone: true,
209		},
210		Some(Declared::Drive {
211			mount,
212			drive,
213			computer,
214		}) => Whereabouts {
215			folder: drive.folder_ids.then(|| folder_id(&folder)).flatten(),
216			path: Some(path_on(&folder, &mount)),
217			drive,
218			mount,
219			computer,
220			phone: false,
221		},
222		None => system::whereabouts(&folder),
223	}
224}
225
226/// What names the disk that holds a folder, as copies count disks: the physical drive's own
227/// name, from its partition table, which every system reads alike, so that partitions of one
228/// drive are one disk; else the file system's serial; else, on the drive the system runs
229/// from, the computer's ID, as on a phone; or `None` where nothing names it, and the folder
230/// counts as on a disk of its own ([technical design: where the copies are]). Each kind of
231/// name is told apart by a prefix.
232///
233/// Public for the tests of the apps' cores, which declare phones.
234///
235/// [technical design: where the copies are]: ../../../docs/Technical-design.md#96-where-the-copies-are
236#[doc(hidden)]
237#[must_use]
238pub fn disk_name(folder: &Path) -> Option<Vec<u8>> {
239	let folder = canonical(folder);
240	let declared = DECLARED
241		.lock()
242		.unwrap_or_else(std::sync::PoisonError::into_inner)
243		.iter()
244		.filter(|declared| folder.starts_with(declared.folder()))
245		.max_by_key(|declared| declared.folder().components().count())
246		.cloned();
247	let named = |kind: &[u8], name: &[u8]| [kind, b"\0", name].concat();
248	let now = whereabouts(&folder);
249	let drive = match declared {
250		Some(Declared::Phone { disk, phone, .. }) => {
251			return disk
252				.map(|disk| named(b"phone apps", &disk))
253				.or_else(|| (!phone.is_empty()).then(|| named(b"phone", &phone)));
254		}
255		Some(Declared::Drive { drive, .. }) => drive.disk.clone(),
256		None => system_disk_name(&folder, &now),
257	};
258	drive
259		.map(|name| named(b"drive", &name))
260		.or_else(|| {
261			now.drive
262				.serial
263				.as_ref()
264				.map(|serial| named(b"file system", serial))
265		})
266		.or_else(|| {
267			now.drive
268				.volume
269				.as_ref()
270				.map(|volume| named(b"volume", volume))
271		})
272		.or_else(|| {
273			now.drive
274				.system
275				.then_some(now.computer.as_ref())
276				.flatten()
277				.map(|computer| named(b"computer", computer))
278		})
279}
280
281/// What names the disk of a drive known only by its file system's serial, as Android's
282/// picker gives it, such as `9CB1-1616` for FAT and exFAT: named as a computer names a
283/// drive whose serial alone it reads.
284#[must_use]
285pub fn serial_disk_name(serial: &str) -> Option<Vec<u8>> {
286	parse_serial(serial).map(|serial| [b"file system".as_slice(), b"\0", &serial].concat())
287}
288
289/// A partition table's ID, in one form whatever system read it: a GPT's GUID, as 16 bytes,
290/// or an MBR's signature, as 4 bytes, from its text, the GUID with or without braces, or the
291/// signature in hexadecimal; `None` for one of zeros, which names no drive. Linux's udev
292/// writes them so.
293#[cfg(any(target_os = "linux", target_os = "android", test))]
294fn partition_table(id: &str) -> Option<Vec<u8>> {
295	let digits: String = id
296		.chars()
297		.filter(|character| !matches!(character, '{' | '}' | '-'))
298		.collect();
299	if !digits.len().is_multiple_of(2) {
300		return None;
301	}
302	let bytes: Vec<u8> = (0..digits.len())
303		.step_by(2)
304		.map(|at| u8::from_str_radix(digits.get(at..at + 2)?, 16).ok())
305		.collect::<Option<_>>()?;
306	table_id(&bytes)
307}
308
309/// A partition table's ID from its bytes: a GPT's GUID, as 16 bytes in the order its text
310/// gives them, or an MBR's signature, as 4 bytes, most significant first; `None` for one of
311/// zeros, which names no drive.
312#[cfg(any(target_os = "linux", target_os = "android", windows, test))]
313fn table_id(bytes: &[u8]) -> Option<Vec<u8>> {
314	if bytes.iter().all(|byte| *byte == 0) {
315		return None;
316	}
317	match bytes.len() {
318		16 => Some([b"gpt\0".as_slice(), bytes].concat()),
319		4 => Some([b"mbr\0".as_slice(), bytes].concat()),
320		_ => None,
321	}
322}
323
324/// The physical drive's own name, as the system reads it: on Linux, from the mount table
325/// down to the drives.
326#[cfg(any(target_os = "linux", target_os = "android"))]
327fn system_disk_name(folder: &Path, _now: &Whereabouts) -> Option<Vec<u8>> {
328	system::disk_name(folder)
329}
330
331/// The physical drive's own name, as the system reads it: on Windows, from the volume at
332/// the mount that the folder's whereabouts found, unless it is a network drive.
333#[cfg(windows)]
334fn system_disk_name(_folder: &Path, now: &Whereabouts) -> Option<Vec<u8>> {
335	if now.drive.remote {
336		return None;
337	}
338	system::disk_name(&now.mount)
339}
340
341/// No drive's name: macOS and iOS are not read yet, and the other names count instead.
342#[cfg(not(any(target_os = "linux", target_os = "android", windows)))]
343fn system_disk_name(_folder: &Path, _now: &Whereabouts) -> Option<Vec<u8>> {
344	None
345}
346
347/// The name of a file system's drives, as one disk: each drive's name, sorted, joined by
348/// zero bytes; `None` for no drive.
349#[cfg(any(target_os = "linux", target_os = "android", windows))]
350fn drives_named(names: std::collections::BTreeSet<Vec<u8>>) -> Option<Vec<u8>> {
351	(!names.is_empty()).then(|| names.into_iter().collect::<Vec<_>>().join(&0_u8))
352}
353
354/// Where a new replica's folder, made as `made`, is once it is renamed to `named`, in the
355/// same folder: a rename keeps its ID.
356pub(crate) fn whereabouts_as(made: &Path, named: &Path) -> Whereabouts {
357	let mut now = whereabouts(made);
358	if now.path.is_some()
359		&& let (Some(parent), Some(name)) = (named.parent(), named.file_name())
360	{
361		now.path = Some(path_on(&canonical(parent).join(name), &now.mount));
362	}
363	now
364}
365
366/// A folder's path from the folder that its drive is mounted at: its names, with `/`
367/// between them, in Unicode's composed form, so that a drive gives the same path on every
368/// system.
369fn path_on(folder: &Path, mount: &Path) -> String {
370	folder
371		.strip_prefix(mount)
372		.unwrap_or(folder)
373		.components()
374		.filter_map(|part| match part {
375			Component::Normal(name) => Some(name.to_string_lossy().nfc().collect::<String>()),
376			_ => None,
377		})
378		.collect::<Vec<_>>()
379		.join("/")
380}
381
382/// A folder's inode, on the systems that have them.
383#[cfg(unix)]
384fn folder_id(folder: &Path) -> Option<Vec<u8>> {
385	use std::os::unix::fs::MetadataExt;
386	fs::metadata(folder)
387		.ok()
388		.map(|metadata| numeric(metadata.ino()))
389}
390
391/// A folder's file ID, as Windows gives it.
392#[cfg(windows)]
393fn folder_id(folder: &Path) -> Option<Vec<u8>> {
394	system::folder_id(folder)
395}
396
397#[cfg(not(any(unix, windows)))]
398fn folder_id(_folder: &Path) -> Option<Vec<u8>> {
399	None
400}
401
402/// A file system's serial, as the systems write it: a UUID with dashes, as ext4's, Btrfs's
403/// and APFS's are; 32 bits as `ABCD-1234`, as FAT's and exFAT's are; or 64 bits as 16
404/// hexadecimal digits, as NTFS's are. A UUID is kept as its 16 bytes, and a shorter serial as
405/// a number, as Windows reads every one.
406#[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))]
407fn parse_serial(text: &str) -> Option<Vec<u8>> {
408	let bytes = hex(&text.replace('-', ""))?;
409	match bytes.len() {
410		16 => Some(bytes),
411		1..=8 => {
412			let mut number = [0; 8];
413			number[8 - bytes.len()..].copy_from_slice(&bytes);
414			Some(numeric(u64::from_be_bytes(number)))
415		}
416		_ => None,
417	}
418}
419
420/// The UUID that macOS gives a FAT or exFAT volume, which other systems make alike: a
421/// version 3 UUID, the MD5 of Apple's namespace of file systems' UUIDs, the serial's four
422/// bytes as the volume stores them, least significant first, and on FAT, the count of its
423/// sectors the same way, as Apple's `msdosfs` makes it.
424#[cfg_attr(target_vendor = "apple", allow(dead_code))]
425fn fat_volume_uuid(serial: u32, sectors: Option<u32>) -> Vec<u8> {
426	use md5::{Digest as _, Md5};
427	const NAMESPACE: [u8; 16] = [
428		0xB3, 0xE2, 0x0F, 0x39, 0xF2, 0x92, 0x11, 0xD6, 0x97, 0xA4, 0x00, 0x30, 0x65, 0x43, 0xEC,
429		0xAC,
430	];
431	let mut md5 = Md5::new();
432	md5.update(NAMESPACE);
433	md5.update(serial.to_le_bytes());
434	if let Some(sectors) = sectors {
435		md5.update(sectors.to_le_bytes());
436	}
437	let mut uuid: [u8; 16] = md5.finalize().into();
438	uuid[6] = (uuid[6] & 0x0F) | 0x30;
439	uuid[8] = (uuid[8] & 0x3F) | 0x80;
440	uuid.to_vec()
441}
442
443/// A serial or an ID that is a number: its bytes, most significant first, without leading
444/// zeros.
445fn numeric(number: u64) -> Vec<u8> {
446	let bytes = number.to_be_bytes();
447	let start = bytes.iter().position(|&byte| byte != 0).unwrap_or(7);
448	bytes[start..].to_vec()
449}
450
451/// Bytes written as pairs of hexadecimal digits, either case.
452fn hex(text: &str) -> Option<Vec<u8>> {
453	if text.is_empty() || !text.len().is_multiple_of(2) {
454		return None;
455	}
456	(0..text.len())
457		.step_by(2)
458		.map(|at| u8::from_str_radix(text.get(at..at + 2)?, 16).ok())
459		.collect()
460}
461
462/// Whether a replica is here, or a copy of it is.
463#[derive(Clone, Copy, Debug, PartialEq, Eq)]
464pub(crate) enum Verdict {
465	/// It is where it was made, or where it moved to on its drive, or with it.
466	Here,
467	/// It is a copy: on another drive, as another folder, or on the system's drive of
468	/// another computer.
469	Copy,
470}
471
472/// Where a replica was made: the place file, written once. In CBOR, the array
473/// `[1, salt, serial, folder, path, computer, volume]`, with the hashes of the drive's serial,
474/// of the folder's ID, of the computer's ID and of a FAT or exFAT volume's UUID, and `null`
475/// for what was not read. A place file written before the volume's UUID was read has no
476/// last item.
477#[derive(Clone, Debug, PartialEq, Eq)]
478pub(crate) struct PlaceFile {
479	/// The key of the hashes, drawn at random when the replica is made.
480	salt: [u8; 32],
481	serial: Option<[u8; 32]>,
482	folder: Option<[u8; 32]>,
483	path: Option<String>,
484	/// Recorded only on the drive that the system runs from.
485	computer: Option<[u8; 32]>,
486	volume: Option<[u8; 32]>,
487}
488
489impl PlaceFile {
490	/// The place file of a new replica, where it is now.
491	pub(crate) fn new(now: &Whereabouts, rng: &mut impl CryptoRng) -> Self {
492		let mut salt = [0; 32];
493		rng.fill_bytes(&mut salt);
494		let hashed = |context, value: &Option<Vec<u8>>| {
495			value.as_deref().map(|value| hash(&salt, context, value))
496		};
497		Self {
498			salt,
499			serial: hashed(SERIAL, &now.drive.serial),
500			folder: hashed(FOLDER, &now.folder),
501			path: now.path.clone(),
502			computer: now
503				.drive
504				.system
505				.then(|| hashed(COMPUTER, &now.computer))
506				.flatten(),
507			volume: hashed(VOLUME, &now.drive.volume),
508		}
509	}
510
511	/// Reads a place file, or `None` if there is none.
512	pub(crate) fn read(path: &Path) -> Result<Option<Self>, NodeError> {
513		match fs::read(path) {
514			Ok(bytes) => cbor::from_slice(&bytes)
515				.map(Some)
516				.map_err(|error| NodeError::Damaged(error.to_string())),
517			Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
518			Err(error) => Err(NodeError::file(path)(error)),
519		}
520	}
521
522	/// Writes the place file of a new replica, which fails if one is there.
523	pub(crate) fn create(&self, path: &Path) -> Result<(), NodeError> {
524		use std::io::Write as _;
525		let mut file = fs::OpenOptions::new()
526			.write(true)
527			.create_new(true)
528			.open(path)
529			.map_err(|error| match error.kind() {
530				io::ErrorKind::AlreadyExists => NodeError::Exists,
531				_ => NodeError::file(path)(error),
532			})?;
533		file.write_all(&cbor::to_vec(self))
534			.and_then(|()| file.sync_all())
535			.map_err(NodeError::file(path))
536	}
537
538	/// Whether the replica whose folder is `folder` is here, where it is now `now`. Its drive
539	/// matches by its serial, and on the drive that the system runs from, its computer by its
540	/// ID. Its folder matches by its ID, or where none is kept, by its path, or if nothing is
541	/// at the path it recorded any more. What either side lacks is not compared.
542	pub(crate) fn verdict(&self, now: &Whereabouts, folder: &Path) -> Verdict {
543		let matches =
544			|recorded: &Option<[u8; 32]>, context, value: &Option<Vec<u8>>| match (recorded, value)
545			{
546				(Some(recorded), Some(value)) => *recorded == hash(&self.salt, context, value),
547				_ => true,
548			};
549		// On a phone, the phone's ID has to be there and match: a copy on another phone has
550		// none of the first one's.
551		if now.phone {
552			let id = self.computer.zip(now.computer.as_deref());
553			return match id {
554				Some((recorded, id)) if recorded == hash(&self.salt, COMPUTER, id) => Verdict::Here,
555				_ => Verdict::Copy,
556			};
557		}
558		if !matches(&self.serial, SERIAL, &now.drive.serial)
559			|| !matches(&self.volume, VOLUME, &now.drive.volume)
560			|| (now.drive.system && !matches(&self.computer, COMPUTER, &now.computer))
561		{
562			return Verdict::Copy;
563		}
564		// A replica made off the drive that the system runs from records no computer's ID,
565		// which this computer has: found on that drive, it was copied there, from a stick or
566		// another drive whose serial this system may not read.
567		if now.drive.system && self.computer.is_none() && now.computer.is_some() {
568			return Verdict::Copy;
569		}
570		if self.folder.is_some() && now.folder.is_some() {
571			return if matches(&self.folder, FOLDER, &now.folder) {
572				Verdict::Here
573			} else {
574				Verdict::Copy
575			};
576		}
577		// Without IDs of folders, the path it recorded, looked up on its drive, has to lead
578		// to this very folder, as it does in another case on a drive that ignores case, or to
579		// nothing any more, as when the folder was moved on its drive.
580		let Some(recorded) = &self.path else {
581			return Verdict::Here;
582		};
583		let before = recorded
584			.split('/')
585			.fold(now.mount.clone(), |path, name| path.join(name));
586		match fs::symlink_metadata(&before) {
587			Err(error) if error.kind() == io::ErrorKind::NotFound => Verdict::Here,
588			Ok(_) if same_folder(&before, folder) => Verdict::Here,
589			_ => Verdict::Copy,
590		}
591	}
592}
593
594/// The hash of a serial or an ID, keyed with a replica's salt.
595fn hash(salt: &[u8; 32], context: &str, value: &[u8]) -> [u8; 32] {
596	let mut hasher = blake3::Hasher::new_keyed(salt);
597	hasher.update(context.as_bytes());
598	hasher.update(&[0]);
599	hasher.update(value);
600	*hasher.finalize().as_bytes()
601}
602
603/// Whether two paths lead to one folder, as two spellings of it do on a drive that ignores
604/// case: the same inode on the same device, which lasts while the drive is mounted, on FAT
605/// too.
606#[cfg(unix)]
607pub(crate) fn same_folder(one: &Path, other: &Path) -> bool {
608	use std::os::unix::fs::MetadataExt;
609	matches!(
610		(fs::metadata(one), fs::metadata(other)),
611		(Ok(one), Ok(other)) if one.dev() == other.dev() && one.ino() == other.ino()
612	)
613}
614
615/// Whether two paths lead to one folder, as Windows resolves them, with the case of the
616/// names it keeps.
617#[cfg(not(unix))]
618pub(crate) fn same_folder(one: &Path, other: &Path) -> bool {
619	matches!(
620		(fs::canonicalize(one), fs::canonicalize(other)),
621		(Ok(one), Ok(other)) if one == other
622	)
623}
624
625impl ToCbor for PlaceFile {
626	fn to_cbor(&self) -> Value {
627		let hash =
628			|hash: &Option<[u8; 32]>| hash.map_or(Value::Null, |hash| Value::Bytes(hash.to_vec()));
629		Value::Array(vec![
630			SUITE.to_cbor(),
631			Value::Bytes(self.salt.to_vec()),
632			hash(&self.serial),
633			hash(&self.folder),
634			self.path.as_ref().map_or(Value::Null, ToCbor::to_cbor),
635			hash(&self.computer),
636			hash(&self.volume),
637		])
638	}
639}
640
641impl FromCbor for PlaceFile {
642	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
643		const EXPECTED: &str = "a place file: [1, salt, serial, folder, path, computer, volume]";
644		let Value::Array(items) = value else {
645			return Err(cbor::Error::Expected(EXPECTED));
646		};
647		let (suite, salt, serial, folder, path, computer, volume) = match items.as_slice() {
648			[suite, salt, serial, folder, path, computer, volume] => {
649				(suite, salt, serial, folder, path, computer, volume)
650			}
651			// Written before the volume's UUID was read.
652			[suite, salt, serial, folder, path, computer] => {
653				(suite, salt, serial, folder, path, computer, &Value::Null)
654			}
655			_ => return Err(cbor::Error::Expected(EXPECTED)),
656		};
657		if u8::from_cbor(suite) != Ok(SUITE) {
658			return Err(cbor::Error::Expected(EXPECTED));
659		}
660		let bytes = |value: &Value| match value {
661			Value::Bytes(bytes) => {
662				<[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| cbor::Error::Expected(EXPECTED))
663			}
664			_ => Err(cbor::Error::Expected(EXPECTED)),
665		};
666		let optional = |value: &Value| match value {
667			Value::Null => Ok(None),
668			value => bytes(value).map(Some),
669		};
670		Ok(Self {
671			salt: bytes(salt)?,
672			serial: optional(serial)?,
673			folder: optional(folder)?,
674			path: match path {
675				Value::Null => None,
676				path => Some(String::from_cbor(path)?),
677			},
678			computer: optional(computer)?,
679			volume: optional(volume)?,
680		})
681	}
682}
683
684#[cfg(any(target_os = "linux", target_os = "android"))]
685mod system {
686	//! Linux, and `nib` in a shell on Android, from the mount table.
687
688	use std::fs;
689	use std::path::{Path, PathBuf};
690
691	use super::{Drive, Whereabouts, fat_volume_uuid, folder_id, hex, parse_serial, path_on};
692
693	/// File systems on another computer, or reached through one: SQLite's write-ahead log
694	/// does not work on them. FUSE mounts are named by their subtype.
695	const REMOTE: &[&str] = &[
696		"nfs",
697		"nfs4",
698		"cifs",
699		"smb3",
700		"smbfs",
701		"ncpfs",
702		"afs",
703		"9p",
704		"drvfs",
705		"ceph",
706		"glusterfs",
707		"lustre",
708		"gpfs",
709		"davfs",
710		"fuse.sshfs",
711		"fuse.rclone",
712		"fuse.s3fs",
713		"fuse.gcsfuse",
714		"fuse.davfs2",
715		"fuse.glusterfs",
716	];
717
718	/// File systems whose IDs of folders last, which a move keeps: FAT's and exFAT's are made
719	/// up when they are mounted, and so are those of many file systems in FUSE.
720	const FOLDER_IDS: &[&str] = &[
721		"ext2", "ext3", "ext4", "btrfs", "xfs", "zfs", "f2fs", "bcachefs", "jfs", "nilfs2",
722		"ntfs3", "hfsplus", "tmpfs",
723	];
724
725	/// A mount, as the mount table lists it.
726	#[derive(Debug, PartialEq, Eq)]
727	pub(super) struct Mount {
728		pub(super) point: PathBuf,
729		pub(super) kind: String,
730		pub(super) source: String,
731	}
732
733	pub(super) fn whereabouts(folder: &Path) -> Whereabouts {
734		let mounts =
735			fs::read_to_string("/proc/self/mountinfo").map_or_default(|table| mounts(&table));
736		let Some(mount) = mount_of(&mounts, folder) else {
737			return Whereabouts {
738				drive: Drive::default(),
739				mount: PathBuf::from("/"),
740				folder: None,
741				path: Some(path_on(folder, Path::new("/"))),
742				computer: computer(),
743				phone: false,
744			};
745		};
746		let device = device(mount);
747		let pool = pool(mount);
748		let root = mount_of(&mounts, Path::new("/"));
749		let system = mount.point == Path::new("/")
750			|| device.is_some() && device == root.and_then(self::device)
751			|| pool.is_some() && pool == root.and_then(self::pool);
752		let folder_ids = FOLDER_IDS.contains(&mount.kind.as_str());
753		// A file system in FUSE is named by udev, which the mount table hides.
754		let kind = if mount.kind.starts_with("fuse") {
755			device
756				.as_deref()
757				.and_then(|device| udev_value(device, "ID_FS_TYPE"))
758				.unwrap_or_default()
759		} else {
760			mount.kind.clone()
761		};
762		let named = device.as_deref().and_then(serial_name);
763		Whereabouts {
764			drive: Drive {
765				serial: named.as_deref().and_then(parse_serial),
766				volume: device
767					.as_deref()
768					.zip(named.as_deref())
769					.and_then(|(device, name)| volume(device, &kind, name)),
770				folder_ids,
771				system,
772				remote: REMOTE.contains(&mount.kind.as_str()),
773				cloud: false,
774				unjournaled: UNJOURNALED.contains(&kind.as_str()),
775				disk: None,
776			},
777			folder: folder_ids.then(|| folder_id(folder)).flatten(),
778			path: Some(path_on(folder, &mount.point)),
779			mount: mount.point.clone(),
780			computer: computer(),
781			phone: false,
782		}
783	}
784
785	/// File systems that keep no journal, as the mount table and udev name them.
786	const UNJOURNALED: &[&str] = &["vfat", "msdos", "exfat", "ext2"];
787
788	/// The major and minor numbers of a device.
789	fn numbers(device: &Path) -> Option<(u64, u64)> {
790		use std::os::unix::fs::MetadataExt;
791		let number = fs::metadata(device).ok()?.rdev();
792		let major = ((number >> 8) & 0xfff) | ((number >> 32) & !0xfff);
793		let minor = (number & 0xff) | ((number >> 12) & !0xff);
794		Some((major, minor))
795	}
796
797	/// A property of a device that udev recorded, as the type of its file system.
798	fn udev_value(device: &Path, name: &str) -> Option<String> {
799		let (major, minor) = numbers(device)?;
800		let record = fs::read_to_string(format!("/run/udev/data/b{major}:{minor}")).ok()?;
801		let prefix = format!("E:{name}=");
802		record
803			.lines()
804			.find_map(|line| line.strip_prefix(prefix.as_str()))
805			.map(str::to_owned)
806	}
807
808	/// On FAT and exFAT, the volume's UUID as macOS makes it, from its serial, as
809	/// `/dev/disk/by-uuid` names it, and on FAT, the count of its sectors: the size of its
810	/// file system that udev records, in the device's sectors.
811	fn volume(device: &Path, kind: &str, name: &str) -> Option<Vec<u8>> {
812		let serial = u32::from_str_radix(&name.replace('-', ""), 16).ok()?;
813		match kind {
814			"exfat" => Some(fat_volume_uuid(serial, None)),
815			"vfat" | "msdos" => {
816				let size: u64 = udev_value(device, "ID_FS_SIZE")?.parse().ok()?;
817				let (major, minor) = numbers(device)?;
818				// A partition's queue is its disk's.
819				let sector = ["queue", "../queue"]
820					.iter()
821					.find_map(|queue| {
822						fs::read_to_string(format!(
823							"/sys/dev/block/{major}:{minor}/{queue}/logical_block_size"
824						))
825						.ok()?
826						.trim()
827						.parse::<u64>()
828						.ok()
829					})
830					.unwrap_or(512);
831				let sectors = u32::try_from(size / sector).ok()?;
832				Some(fat_volume_uuid(serial, Some(sectors)))
833			}
834			_ => None,
835		}
836	}
837
838	/// The device that a mount's file system is on, if it is on one.
839	fn device(mount: &Mount) -> Option<PathBuf> {
840		mount
841			.source
842			.starts_with("/dev/")
843			.then(|| fs::canonicalize(&mount.source).ok())
844			.flatten()
845	}
846
847	/// The pool of a ZFS dataset, which the mount table names in place of a device.
848	fn pool(mount: &Mount) -> Option<&str> {
849		(mount.kind == "zfs")
850			.then(|| mount.source.split('/').next())
851			.flatten()
852	}
853
854	/// The mounts that a mount table lists, in its order.
855	pub(super) fn mounts(table: &str) -> Vec<Mount> {
856		table
857			.lines()
858			.filter_map(|line| {
859				let fields: Vec<&str> = line.split(' ').collect();
860				let point = fields.get(4)?;
861				let separator = fields.iter().skip(6).position(|field| *field == "-")? + 6;
862				Some(Mount {
863					point: PathBuf::from(unescaped(point)),
864					kind: (*fields.get(separator + 1)?).to_owned(),
865					source: unescaped(fields.get(separator + 2)?),
866				})
867			})
868			.collect()
869	}
870
871	/// The mount that holds a folder: the one at the longest path that holds it, and of
872	/// several at one path, the last, which hides the others.
873	pub(super) fn mount_of<'a>(mounts: &'a [Mount], folder: &Path) -> Option<&'a Mount> {
874		mounts
875			.iter()
876			.enumerate()
877			.filter(|(_, mount)| folder.starts_with(&mount.point))
878			.max_by_key(|(at, mount)| (mount.point.components().count(), *at))
879			.map(|(_, mount)| mount)
880	}
881
882	/// A field of the mount table, whose spaces, tabs, line feeds and backslashes are written
883	/// as three octal digits after a backslash.
884	fn unescaped(field: &str) -> String {
885		let bytes = field.as_bytes();
886		let mut out = Vec::with_capacity(bytes.len());
887		let mut at = 0;
888		while at < bytes.len() {
889			let octal = bytes
890				.get(at + 1..at + 4)
891				.filter(|_| bytes[at] == b'\\')
892				.and_then(|digits| u8::from_str_radix(std::str::from_utf8(digits).ok()?, 8).ok());
893			if let Some(byte) = octal {
894				out.push(byte);
895				at += 4;
896			} else {
897				out.push(bytes[at]);
898				at += 1;
899			}
900		}
901		String::from_utf8_lossy(&out).into_owned()
902	}
903
904	/// The serial of the file system on a device, as udev lists it under `/dev/disk/by-uuid`.
905	fn serial_name(device: &Path) -> Option<String> {
906		fs::read_dir("/dev/disk/by-uuid")
907			.ok()?
908			.flatten()
909			.find(|entry| fs::canonicalize(entry.path()).is_ok_and(|target| target == device))
910			.map(|entry| entry.file_name().to_string_lossy().into_owned())
911	}
912
913	/// The physical drives that hold a folder's file system, named by their partition
914	/// tables as udev records them, or by their serials: through device mapper, as for an
915	/// encrypted drive, and RAID, down to the partitions, and from each to its drive. A file
916	/// system on several drives is named by all of them, sorted, as one disk.
917	pub(super) fn disk_name(folder: &Path) -> Option<Vec<u8>> {
918		let mounts = fs::read_to_string("/proc/self/mountinfo")
919			.map(|table| mounts(&table))
920			.ok()?;
921		let device = device(mount_of(&mounts, folder)?)?;
922		let mut leaves = std::collections::BTreeSet::new();
923		under(device.file_name()?.to_str()?, &mut leaves, 0);
924		let mut names = std::collections::BTreeSet::new();
925		for leaf in leaves {
926			names.insert(drive_name(&whole_drive(&leaf))?);
927		}
928		super::drives_named(names)
929	}
930
931	/// The block devices that a block device is made of, as device mapper and RAID make
932	/// them, down to those made of none.
933	fn under(name: &str, leaves: &mut std::collections::BTreeSet<String>, depth: usize) {
934		let made_of: Vec<String> = fs::read_dir(format!("/sys/class/block/{name}/slaves"))
935			.map_or_default(|entries| {
936				entries
937					.flatten()
938					.map(|entry| entry.file_name().to_string_lossy().into_owned())
939					.collect()
940			});
941		if made_of.is_empty() || depth > 8 {
942			leaves.insert(name.to_owned());
943			return;
944		}
945		for each in made_of {
946			under(&each, leaves, depth + 1);
947		}
948	}
949
950	/// The drive that a partition is on, or the device itself if it is no partition.
951	fn whole_drive(name: &str) -> String {
952		let block = PathBuf::from(format!("/sys/class/block/{name}"));
953		if !block.join("partition").exists() {
954			return name.to_owned();
955		}
956		fs::canonicalize(&block)
957			.ok()
958			.and_then(|path| Some(path.parent()?.file_name()?.to_string_lossy().into_owned()))
959			.unwrap_or_else(|| name.to_owned())
960	}
961
962	/// A drive's name: its partition table's ID, as every system reads it, else its WWN or
963	/// serial, as udev records them.
964	fn drive_name(drive: &str) -> Option<Vec<u8>> {
965		let numbers = fs::read_to_string(format!("/sys/class/block/{drive}/dev")).ok()?;
966		let record = fs::read_to_string(format!("/run/udev/data/b{}", numbers.trim())).ok()?;
967		let value = |name: &str| {
968			let prefix = format!("E:{name}=");
969			record
970				.lines()
971				.find_map(|line| line.strip_prefix(prefix.as_str()))
972				.filter(|value| !value.is_empty())
973				.map(str::to_owned)
974		};
975		value("ID_PART_TABLE_UUID")
976			.and_then(|id| super::partition_table(&id))
977			.or_else(|| {
978				["ID_WWN", "ID_SERIAL"].iter().find_map(|name| {
979					value(name).map(|value| format!("{name}={}", value.to_lowercase()).into_bytes())
980				})
981			})
982	}
983
984	/// The computer's ID: systemd's machine ID, or D-Bus's where systemd's is missing.
985	pub(super) fn computer() -> Option<Vec<u8>> {
986		["/etc/machine-id", "/var/lib/dbus/machine-id"]
987			.iter()
988			.find_map(|path| hex(fs::read_to_string(path).ok()?.trim()))
989	}
990}
991
992#[cfg(windows)]
993mod system {
994	//! Windows: the volume that holds the folder, among the mounted drives that `sysinfo`
995	//! lists; the serial of its file system and the folder's ID, as `file-id` reads them; the
996	//! drives under the volume and their partition tables, as `nibkeep-drives` reads them;
997	//! and the computer's ID and the cloud files' sync roots, in the registry. Nothing here
998	//! needs `unsafe` code of its own.
999
1000	use std::path::{Path, PathBuf};
1001
1002	use file_id::FileId;
1003	use nibkeep_drives::PartitionTable;
1004	use sysinfo::{Disk, Disks};
1005	use winreg::HKLM;
1006	use winreg::enums::{KEY_READ, KEY_WOW64_64KEY};
1007
1008	use super::{Drive, Whereabouts, fat_volume_uuid, hex, numeric, path_on};
1009
1010	/// A path without the `\\?\` that canonical paths have on Windows, as the mounted drives
1011	/// are named, with a share's in the form `\\server\share`.
1012	fn plain(path: &Path) -> PathBuf {
1013		let text = path.to_string_lossy();
1014		if let Some(share) = text.strip_prefix(r"\\?\UNC\") {
1015			PathBuf::from(format!(r"\\{share}"))
1016		} else if let Some(local) = text.strip_prefix(r"\\?\") {
1017			PathBuf::from(local)
1018		} else {
1019			path.to_owned()
1020		}
1021	}
1022
1023	/// The mounted drive that holds a path: the one at the longest folder that holds it.
1024	/// Drives that are neither fixed nor removable, as network drives, are not listed.
1025	fn drive_of<'a>(disks: &'a Disks, path: &Path) -> Option<&'a Disk> {
1026		disks
1027			.iter()
1028			.filter(|disk| path.starts_with(disk.mount_point()))
1029			.max_by_key(|disk| disk.mount_point().as_os_str().len())
1030	}
1031
1032	/// Whether a drive's file system keeps IDs of folders that a move keeps.
1033	fn keeps_ids(disk: Option<&Disk>) -> bool {
1034		disk.is_some_and(|disk| {
1035			let kind = disk.file_system().to_string_lossy();
1036			kind.eq_ignore_ascii_case("NTFS") || kind.eq_ignore_ascii_case("ReFS")
1037		})
1038	}
1039
1040	pub(super) fn whereabouts(folder: &Path) -> Whereabouts {
1041		let shown = plain(folder);
1042		let disks = Disks::new_with_refreshed_list().ok();
1043		let disk = disks.as_ref().and_then(|disks| drive_of(disks, &shown));
1044		let mount = disk.map_or_else(
1045			|| shown.ancestors().last().unwrap_or(&shown).to_owned(),
1046			|disk| disk.mount_point().to_owned(),
1047		);
1048		let system = std::env::var_os("SystemRoot")
1049			.and_then(|windows| drive_of(disks.as_ref()?, &plain(Path::new(&windows))))
1050			.zip(disk)
1051			.is_some_and(|(windows, disk)| windows.mount_point() == disk.mount_point());
1052		let folder_ids = keeps_ids(disk);
1053		let (serial, id) = identity(folder, disk);
1054		let exfat = disk.is_some_and(|disk| {
1055			disk.file_system()
1056				.to_string_lossy()
1057				.eq_ignore_ascii_case("exFAT")
1058		});
1059		Whereabouts {
1060			drive: Drive {
1061				serial: serial.map(numeric),
1062				// On exFAT, made from the serial alone; on FAT, it takes the count of sectors,
1063				// which no safe crate reads here.
1064				volume: serial
1065					.filter(|_| exfat)
1066					.and_then(|serial| u32::try_from(serial).ok())
1067					.map(|serial| fat_volume_uuid(serial, None)),
1068				folder_ids,
1069				system,
1070				// A share, or a drive that is neither fixed nor removable; not one that is not
1071				// there, as a stick that was taken out.
1072				remote: shown.to_string_lossy().starts_with(r"\\")
1073					|| (disk.is_none() && mount.exists()),
1074				cloud: in_sync_root(&shown),
1075				unjournaled: disk.is_some_and(|disk| {
1076					let kind = disk.file_system().to_string_lossy();
1077					["FAT", "FAT32", "exFAT"]
1078						.iter()
1079						.any(|fat| kind.eq_ignore_ascii_case(fat))
1080				}),
1081				disk: None,
1082			},
1083			folder: id.filter(|_| folder_ids),
1084			path: Some(path_on(&shown, &mount)),
1085			mount,
1086			computer: computer(),
1087			phone: false,
1088		}
1089	}
1090
1091	/// The physical drives under the volume mounted at `mount`, named by their partition
1092	/// tables, as their layouts give them: a GPT's GUID, or an MBR's signature. A volume on
1093	/// several drives is named by all of them, as one disk, as on Linux; one on a drive
1094	/// without a partition table, or with an ID of zeros, by none, as Windows reads no WWN or
1095	/// serial of a drive here.
1096	pub(super) fn disk_name(mount: &Path) -> Option<Vec<u8>> {
1097		let mut names = std::collections::BTreeSet::new();
1098		for table in nibkeep_drives::partition_tables(mount).ok()? {
1099			names.insert(match table? {
1100				PartitionTable::Gpt(guid) => super::table_id(&guid)?,
1101				PartitionTable::Mbr(signature) => super::table_id(&signature.to_be_bytes())?,
1102			});
1103		}
1104		super::drives_named(names)
1105	}
1106
1107	/// The serial of a folder's volume, and the folder's ID: on NTFS, the number of its record
1108	/// in the master file table, the lower 48 bits of the ID that Windows gives, whose upper
1109	/// 16 count the record's reuses, as Linux reads it too.
1110	fn identity(folder: &Path, disk: Option<&Disk>) -> (Option<u64>, Option<Vec<u8>>) {
1111		let ntfs = disk.is_some_and(|disk| {
1112			disk.file_system()
1113				.to_string_lossy()
1114				.eq_ignore_ascii_case("NTFS")
1115		});
1116		match file_id::get_file_id(folder) {
1117			Ok(FileId::HighRes {
1118				volume_serial_number,
1119				file_id,
1120			}) => {
1121				let id = if ntfs {
1122					numeric((file_id & 0xFFFF_FFFF_FFFF) as u64)
1123				} else {
1124					file_id.to_be_bytes().to_vec()
1125				};
1126				(Some(volume_serial_number), Some(id))
1127			}
1128			Ok(FileId::LowRes {
1129				volume_serial_number,
1130				file_index,
1131			}) => {
1132				let id = if ntfs {
1133					file_index & 0xFFFF_FFFF_FFFF
1134				} else {
1135					file_index
1136				};
1137				(Some(u64::from(volume_serial_number)), Some(numeric(id)))
1138			}
1139			_ => (None, None),
1140		}
1141	}
1142
1143	/// A folder's ID, as [`whereabouts`] reads it.
1144	pub(super) fn folder_id(folder: &Path) -> Option<Vec<u8>> {
1145		let disks = Disks::new_with_refreshed_list().ok();
1146		let disk = disks
1147			.as_ref()
1148			.and_then(|disks| drive_of(disks, &plain(folder)));
1149		identity(folder, disk).1
1150	}
1151
1152	/// Whether a folder is in a sync root of Windows' cloud files, as OneDrive's, whose files'
1153	/// content a program may take away to the cloud: the roots that the registry lists.
1154	fn in_sync_root(folder: &Path) -> bool {
1155		let Ok(manager) = HKLM.open_subkey_with_flags(
1156			r"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SyncRootManager",
1157			KEY_READ | KEY_WOW64_64KEY,
1158		) else {
1159			return false;
1160		};
1161		manager.enum_keys().flatten().any(|root| {
1162			manager
1163				.open_subkey_with_flags(format!(r"{root}\UserSyncRoots"), KEY_READ)
1164				.is_ok_and(|users| {
1165					users.enum_values().flatten().any(|(_, value)| {
1166						let path = value.to_string();
1167						!path.is_empty()
1168							&& folder.starts_with(plain(Path::new(path.trim_end_matches('\0'))))
1169					})
1170				})
1171		})
1172	}
1173
1174	/// The computer's ID: the GUID that Windows draws when it is installed.
1175	pub(super) fn computer() -> Option<Vec<u8>> {
1176		let guid: String = HKLM
1177			.open_subkey_with_flags(
1178				r"SOFTWARE\Microsoft\Cryptography",
1179				KEY_READ | KEY_WOW64_64KEY,
1180			)
1181			.and_then(|key| key.get_value("MachineGuid"))
1182			.ok()?;
1183		hex(&guid.replace('-', ""))
1184	}
1185}
1186
1187#[cfg(target_vendor = "apple")]
1188mod system {
1189	//! macOS, and iOS outside an app's own folder: the volume that holds the folder, as the
1190	//! system's `statfs` of the folder reports it, which finds volumes that Finder does not
1191	//! show too, as one attached with `-nobrowse`; and on macOS, the hardware UUID that
1192	//! `ioreg` reports, and the UUID of a FAT or exFAT volume that `diskutil` reports, which
1193	//! the system makes from its serial. No serial is read: only the system reads a drive's
1194	//! raw sectors.
1195
1196	use std::ffi::{OsStr, c_char};
1197	use std::os::unix::ffi::OsStrExt as _;
1198	use std::path::{Path, PathBuf};
1199
1200	use super::{Drive, Whereabouts, folder_id, path_on};
1201
1202	/// File systems whose IDs of folders do not last.
1203	const NO_FOLDER_IDS: &[&str] = &["msdos", "exfat"];
1204
1205	/// File systems on another computer.
1206	const REMOTE: &[&str] = &["smbfs", "nfs", "afpfs", "webdav", "ftp"];
1207
1208	/// The flag of a volume on the computer's own drives, `MNT_LOCAL` in `<sys/mount.h>`.
1209	const LOCAL: u32 = 0x0000_1000;
1210
1211	/// The volume that holds a folder, or the deepest folder above it that exists, as
1212	/// `statfs` reports it: the folder it is mounted at, the name of its file system, and
1213	/// whether it is on the computer's own drives. None if the system lets it not be read,
1214	/// rather than the volume of a folder above it, which may be another.
1215	fn volume(folder: &Path) -> Option<(PathBuf, String, bool)> {
1216		let found = folder
1217			.ancestors()
1218			.find_map(|folder| match rustix::fs::statfs(folder) {
1219				Ok(found) => Some(Some(found)),
1220				// A folder still to be made: the one above it holds it.
1221				Err(rustix::io::Errno::NOENT) => None,
1222				Err(_) => Some(None),
1223			})??;
1224		let mount = PathBuf::from(OsStr::from_bytes(&text(&found.f_mntonname)));
1225		let kind = String::from_utf8_lossy(&text(&found.f_fstypename)).into_owned();
1226		Some((mount, kind, found.f_flags & LOCAL != 0))
1227	}
1228
1229	/// The bytes of a C string in a fixed array, up to its end.
1230	fn text(chars: &[c_char]) -> Vec<u8> {
1231		chars
1232			.iter()
1233			.take_while(|&&char| char != 0)
1234			.map(|&char| char.cast_unsigned())
1235			.collect()
1236	}
1237
1238	pub(super) fn whereabouts(folder: &Path) -> Whereabouts {
1239		let volume = volume(folder);
1240		let mounted = volume.as_ref().map(|(mount, _, _)| mount.as_path());
1241		// The system's volume, and the volume of its data, which holds the home folders.
1242		let system = mounted.is_none_or(|mounted| {
1243			mounted == Path::new("/") || mounted == Path::new("/System/Volumes/Data")
1244		});
1245		// The home folders are on the volume of the system's data, through links from the
1246		// system's volume, such as `/Users`, so a folder there is placed by its path from `/`.
1247		let mount = mounted
1248			.filter(|mounted| folder.starts_with(mounted))
1249			.map_or_else(|| PathBuf::from("/"), Path::to_owned);
1250		let kind = volume.as_ref().map(|(_, kind, _)| kind.as_str());
1251		let folder_ids = !kind.is_some_and(|kind| NO_FOLDER_IDS.contains(&kind));
1252		let remote = volume
1253			.as_ref()
1254			.is_some_and(|(_, kind, local)| !local || REMOTE.contains(&kind.as_str()));
1255		Whereabouts {
1256			drive: Drive {
1257				serial: None,
1258				folder_ids,
1259				system,
1260				remote,
1261				cloud: in_file_provider(folder),
1262				unjournaled: !folder_ids,
1263				volume: if folder_ids {
1264					None
1265				} else {
1266					volume_uuid(&mount)
1267				},
1268				disk: None,
1269			},
1270			folder: folder_ids.then(|| folder_id(folder)).flatten(),
1271			path: Some(path_on(folder, &mount)),
1272			mount,
1273			computer: computer(),
1274			phone: false,
1275		}
1276	}
1277
1278	/// Whether a folder is where File Provider keeps the files of iCloud Drive and of other
1279	/// programs that sync folders, whose content may stay in the cloud until opened: in their
1280	/// folders, or in the Desktop or Documents when iCloud keeps them, as iCloud Drive's links
1281	/// to them show.
1282	fn in_file_provider(folder: &Path) -> bool {
1283		let Some(home) = home() else {
1284			return false;
1285		};
1286		let library = home.join("Library");
1287		let icloud = library.join("Mobile Documents");
1288		folder.starts_with(library.join("CloudStorage"))
1289			|| folder.starts_with(&icloud)
1290			|| ["Desktop", "Documents"].into_iter().any(|name| {
1291				// iCloud Drive is read only for a folder in one of them.
1292				std::fs::canonicalize(home.join(name)).is_ok_and(|own| {
1293					folder.starts_with(&own)
1294						&& std::fs::canonicalize(icloud.join("com~apple~CloudDocs").join(name))
1295							.is_ok_and(|linked| linked == own)
1296				})
1297			})
1298	}
1299
1300	/// The person's home folder. In an app's sandbox, `HOME` names the app's container in
1301	/// it, under `Library/Containers`.
1302	fn home() -> Option<PathBuf> {
1303		let home = PathBuf::from(std::env::var_os("HOME")?);
1304		let outside = home
1305			.ancestors()
1306			.find(|folder| folder.ends_with("Library/Containers"))
1307			.and_then(|containers| containers.parent()?.parent())
1308			.map(Path::to_owned);
1309		Some(outside.unwrap_or(home))
1310	}
1311
1312	/// The computer's ID: the hardware UUID that `ioreg` reports, read once.
1313	#[cfg(target_os = "macos")]
1314	pub(super) fn computer() -> Option<Vec<u8>> {
1315		static READ: std::sync::OnceLock<Option<Vec<u8>>> = std::sync::OnceLock::new();
1316		READ.get_or_init(|| {
1317			let listed = std::process::Command::new("/usr/sbin/ioreg")
1318				.args(["-rd1", "-c", "IOPlatformExpertDevice"])
1319				.output()
1320				.ok()?;
1321			let text = String::from_utf8_lossy(&listed.stdout);
1322			let line = text
1323				.lines()
1324				.find(|line| line.contains("\"IOPlatformUUID\""))?;
1325			let uuid = line.rsplit('"').nth(1)?;
1326			super::hex(&uuid.replace('-', ""))
1327		})
1328		.clone()
1329	}
1330
1331	/// The UUID of the FAT or exFAT volume mounted at `mount`, as `diskutil` reports it: read
1332	/// once for each volume mounted there, as it takes a fifth of a second.
1333	#[cfg(target_os = "macos")]
1334	fn volume_uuid(mount: &Path) -> Option<Vec<u8>> {
1335		use std::os::unix::fs::MetadataExt as _;
1336		use std::sync::{Mutex, PoisonError};
1337		type Known = Vec<(PathBuf, u64, Option<Vec<u8>>)>;
1338		static KNOWN: Mutex<Known> = Mutex::new(Vec::new());
1339		let device = std::fs::metadata(mount).ok()?.dev();
1340		let mut known = KNOWN.lock().unwrap_or_else(PoisonError::into_inner);
1341		if let Some((_, _, uuid)) = known
1342			.iter()
1343			.find(|(at, on, _)| at == mount && *on == device)
1344		{
1345			return uuid.clone();
1346		}
1347		let uuid = std::process::Command::new("/usr/sbin/diskutil")
1348			.args(["info", "-plist"])
1349			.arg(mount)
1350			.output()
1351			.ok()
1352			.and_then(|listed| {
1353				let text = String::from_utf8_lossy(&listed.stdout);
1354				let after = text.split("<key>VolumeUUID</key>").nth(1)?;
1355				let uuid = after.split("<string>").nth(1)?.split("</string>").next()?;
1356				super::hex(&uuid.trim().replace('-', ""))
1357			});
1358		known.push((mount.to_owned(), device, uuid.clone()));
1359		uuid
1360	}
1361
1362	/// iOS lists no volumes of FAT and exFAT that an app could keep a library on.
1363	#[cfg(not(target_os = "macos"))]
1364	fn volume_uuid(_mount: &Path) -> Option<Vec<u8>> {
1365		None
1366	}
1367
1368	/// iOS gives apps no ID of the device but through the app, which declares its folder.
1369	#[cfg(not(target_os = "macos"))]
1370	pub(super) fn computer() -> Option<Vec<u8>> {
1371		None
1372	}
1373}
1374
1375#[cfg(not(any(
1376	target_os = "linux",
1377	target_os = "android",
1378	windows,
1379	target_vendor = "apple"
1380)))]
1381mod system {
1382	//! Other systems: the folder's path alone.
1383
1384	use std::path::{Path, PathBuf};
1385
1386	use super::{Drive, Whereabouts, path_on};
1387
1388	pub(super) fn whereabouts(folder: &Path) -> Whereabouts {
1389		Whereabouts {
1390			drive: Drive::default(),
1391			mount: PathBuf::from("/"),
1392			folder: None,
1393			path: Some(path_on(folder, Path::new("/"))),
1394			computer: None,
1395			phone: false,
1396		}
1397	}
1398
1399	/// No computer's ID: other systems give none that NibKeep reads.
1400	pub(super) fn computer() -> Option<Vec<u8>> {
1401		None
1402	}
1403}
1404
1405#[cfg(test)]
1406mod tests {
1407	use nibkeep_testkit::TestRng;
1408
1409	use super::*;
1410
1411	/// Where a folder is, on a drive that keeps the IDs of folders unless `id` is `None`.
1412	fn at(
1413		path: &str,
1414		serial: Option<&[u8]>,
1415		id: Option<&[u8]>,
1416		system: bool,
1417		computer: Option<&[u8]>,
1418	) -> Whereabouts {
1419		Whereabouts {
1420			drive: Drive {
1421				serial: serial.map(<[u8]>::to_vec),
1422				folder_ids: id.is_some(),
1423				system,
1424				..Drive::default()
1425			},
1426			mount: PathBuf::from("/nowhere"),
1427			folder: id.map(<[u8]>::to_vec),
1428			path: Some(path.to_owned()),
1429			computer: computer.map(<[u8]>::to_vec),
1430			phone: false,
1431		}
1432	}
1433
1434	#[test]
1435	fn a_disk_is_named_by_its_drive_else_its_file_system_else_its_computer() {
1436		let folder = std::env::temp_dir().join("nibkeep place, disk names");
1437		let named = |kind: &str, name: &[u8]| [kind.as_bytes(), b"\0", name].concat();
1438		let declared = |drive: Drive, computer: Option<&[u8]>| {
1439			declare_drive(&folder, drive, computer.map(<[u8]>::to_vec));
1440			disk_name(&folder)
1441		};
1442		let drive = Drive {
1443			serial: Some(b"file system".to_vec()),
1444			system: true,
1445			disk: Some(b"drive".to_vec()),
1446			..Drive::default()
1447		};
1448		assert_eq!(
1449			declared(drive.clone(), Some(b"computer")),
1450			Some(named("drive", b"drive"))
1451		);
1452		let no_drive = Drive {
1453			disk: None,
1454			..drive.clone()
1455		};
1456		assert_eq!(
1457			declared(no_drive.clone(), Some(b"computer")),
1458			Some(named("file system", b"file system"))
1459		);
1460		let no_serial = Drive {
1461			serial: None,
1462			..no_drive
1463		};
1464		assert_eq!(
1465			declared(no_serial.clone(), Some(b"computer")),
1466			Some(named("computer", b"computer"))
1467		);
1468		// Off the system's drive, the computer names no disk: the folder is on one of its own.
1469		let elsewhere = Drive {
1470			system: false,
1471			..no_serial
1472		};
1473		assert_eq!(declared(elsewhere, Some(b"computer")), None);
1474		// On a phone, the name that one developer's apps share, else the phone's ID.
1475		declare_phone(&folder, b"phone".to_vec());
1476		assert_eq!(disk_name(&folder), Some(named("phone", b"phone")));
1477		declare_phone_with_disk(&folder, b"phone".to_vec(), b"apps".to_vec());
1478		assert_eq!(disk_name(&folder), Some(named("phone apps", b"apps")));
1479	}
1480
1481	#[test]
1482	fn a_partition_table_is_named_alike_by_every_system() {
1483		// As Linux's udev writes a GPT's GUID and an MBR's signature, and Windows' Get-Disk
1484		// shows them.
1485		let gpt = partition_table("2fd12b0b-49b1-45e2-a237-f582ae445a87");
1486		assert_eq!(
1487			partition_table("{2FD12B0B-49B1-45E2-A237-F582AE445A87}"),
1488			gpt
1489		);
1490		assert_eq!(gpt.as_ref().map(Vec::len), Some(20));
1491		let signature: u32 = 3_735_928_559;
1492		assert_eq!(
1493			partition_table(&format!("{signature:08x}")),
1494			partition_table("deadbeef")
1495		);
1496		assert_ne!(partition_table("deadbeef"), None);
1497		// As Windows reads them from the drive's layout: the GUID's bytes in the order of its
1498		// text, and the signature as a number.
1499		assert_eq!(
1500			table_id(&[
1501				0x2f, 0xd1, 0x2b, 0x0b, 0x49, 0xb1, 0x45, 0xe2, 0xa2, 0x37, 0xf5, 0x82, 0xae, 0x44,
1502				0x5a, 0x87
1503			]),
1504			gpt
1505		);
1506		assert_eq!(
1507			table_id(&signature.to_be_bytes()),
1508			partition_table("deadbeef")
1509		);
1510		assert_eq!(table_id(&[0; 16]), None);
1511		// Zeros name nothing, nor does what is no ID.
1512		assert_eq!(partition_table("00000000"), None);
1513		assert_eq!(
1514			partition_table("00000000-0000-0000-0000-000000000000"),
1515			None
1516		);
1517		assert_eq!(partition_table("not an ID"), None);
1518		assert_eq!(partition_table("abc"), None);
1519	}
1520
1521	#[test]
1522	#[cfg(any(target_os = "linux", windows))]
1523	fn folders_on_one_file_system_have_one_disk_name() {
1524		let crate_folder = Path::new(env!("CARGO_MANIFEST_DIR"));
1525		assert_eq!(
1526			disk_name(crate_folder),
1527			disk_name(&crate_folder.join("src"))
1528		);
1529	}
1530
1531	#[test]
1532	fn serials_read_alike_wherever_they_are_written() {
1533		assert_eq!(
1534			parse_serial("B86A-4A5C"),
1535			Some(vec![0xB8, 0x6A, 0x4A, 0x5C])
1536		);
1537		assert_eq!(parse_serial("0086-4a5c"), Some(vec![0x86, 0x4A, 0x5C]));
1538		assert_eq!(parse_serial("0086-4a5c"), Some(numeric(0x0086_4A5C)));
1539		assert_eq!(
1540			parse_serial("01D9C2A41B3E5F70"),
1541			Some(numeric(0x01D9_C2A4_1B3E_5F70))
1542		);
1543		assert_eq!(
1544			parse_serial("7edd2919-49c7-46c0-a749-7af51e392e18").map(|uuid| uuid.len()),
1545			Some(16)
1546		);
1547		assert_eq!(parse_serial("not-hex"), None);
1548		assert_eq!(parse_serial(""), None);
1549	}
1550
1551	#[test]
1552	fn a_path_is_the_same_on_every_system() {
1553		let composed = "Чайковский";
1554		let decomposed: String = composed.nfd().collect();
1555		assert_ne!(composed, decomposed);
1556		assert_eq!(
1557			path_on(
1558				&Path::new("/run/media/ada/STICK")
1559					.join(&decomposed)
1560					.join(".nib"),
1561				Path::new("/run/media/ada/STICK")
1562			),
1563			format!("{composed}/.nib")
1564		);
1565		assert_eq!(
1566			path_on(Path::new("/home/ada/.nib"), Path::new("/")),
1567			"home/ada/.nib"
1568		);
1569	}
1570
1571	#[test]
1572	fn a_place_file_reads_as_it_was_written() {
1573		let mut rng = TestRng::new("place 1");
1574		for place in [
1575			PlaceFile::new(
1576				&at(
1577					"ada/.nib/replicas/a",
1578					Some(b"disk"),
1579					Some(b"id"),
1580					true,
1581					Some(b"desk"),
1582				),
1583				&mut rng,
1584			),
1585			PlaceFile::new(
1586				&Whereabouts {
1587					path: None,
1588					..at("", None, None, false, None)
1589				},
1590				&mut rng,
1591			),
1592		] {
1593			assert_eq!(
1594				cbor::from_slice::<PlaceFile>(&cbor::to_vec(&place)),
1595				Ok(place)
1596			);
1597		}
1598	}
1599
1600	#[test]
1601	fn a_replica_is_here_on_its_drive_as_its_folder() {
1602		let mut rng = TestRng::new("place 2");
1603		let folder = Path::new("/nowhere/ada/.nib/replicas/a");
1604		let made = at(
1605			"ada/.nib/replicas/a",
1606			Some(b"disk"),
1607			Some(b"7"),
1608			false,
1609			Some(b"desk"),
1610		);
1611		let place = PlaceFile::new(&made, &mut rng);
1612		assert_eq!(place.verdict(&made, folder), Verdict::Here);
1613		// Another drive, or another folder on it: a copy.
1614		let other_drive = at(
1615			"ada/.nib/replicas/a",
1616			Some(b"other"),
1617			Some(b"7"),
1618			false,
1619			None,
1620		);
1621		assert_eq!(place.verdict(&other_drive, folder), Verdict::Copy);
1622		let beside = at(
1623			"ada/lib/.nib/replicas/a",
1624			Some(b"disk"),
1625			Some(b"8"),
1626			false,
1627			None,
1628		);
1629		assert_eq!(place.verdict(&beside, folder), Verdict::Copy);
1630		// The folder moved on its drive, or the drive into another computer: the same.
1631		let moved = at(
1632			"ada/elsewhere/.nib/replicas/a",
1633			Some(b"disk"),
1634			Some(b"7"),
1635			false,
1636			None,
1637		);
1638		assert_eq!(place.verdict(&moved, folder), Verdict::Here);
1639		let laptop = at(
1640			"ada/.nib/replicas/a",
1641			Some(b"disk"),
1642			Some(b"7"),
1643			false,
1644			Some(b"laptop"),
1645		);
1646		assert_eq!(place.verdict(&laptop, folder), Verdict::Here);
1647		// What one side could not read is not compared.
1648		let unread = at("ada/.nib/replicas/a", None, None, false, None);
1649		assert_eq!(place.verdict(&unread, folder), Verdict::Here);
1650	}
1651
1652	#[test]
1653	fn a_fat_volumes_uuid_is_made_as_macos_makes_it() {
1654		// As a MacBook showed them for disk images of 64 MiB, 131,072 sectors.
1655		assert_eq!(
1656			fat_volume_uuid(0x6AE4_AA42, None),
1657			hex("8EF040E0885D3C1BB9D0D48A6456D147").expect("hex"),
1658			"exFAT"
1659		);
1660		assert_eq!(
1661			fat_volume_uuid(0x7F4E_1709, Some(131_072)),
1662			hex("8BDA5D182C62313A99BF54AEA17574CD").expect("hex"),
1663			"FAT"
1664		);
1665	}
1666
1667	#[test]
1668	fn a_volume_uuid_tells_sticks_apart_where_no_serial_is_read() {
1669		let mut rng = TestRng::new("place 9");
1670		let folder = Path::new("/nowhere/stick/.nib/replicas/a");
1671		let on = |volume: &[u8], serial: Option<&[u8]>| Whereabouts {
1672			drive: Drive {
1673				volume: Some(volume.to_vec()),
1674				..at(".nib/replicas/a", serial, None, false, None).drive
1675			},
1676			..at(".nib/replicas/a", serial, None, false, None)
1677		};
1678		// Made on Linux, which reads both.
1679		let place = PlaceFile::new(&on(b"uuid", Some(b"serial")), &mut rng);
1680		// On a Mac, which reads the UUID alone.
1681		assert_eq!(place.verdict(&on(b"uuid", None), folder), Verdict::Here);
1682		assert_eq!(place.verdict(&on(b"another", None), folder), Verdict::Copy);
1683		// A place file written before the UUID was read, which has no last item.
1684		let Value::Array(mut items) = place.to_cbor() else {
1685			unreachable!("an array");
1686		};
1687		items.pop();
1688		let older = PlaceFile::from_cbor(&Value::Array(items)).expect("reads");
1689		assert_eq!(older.volume, None);
1690		assert_eq!(older.verdict(&on(b"another", None), folder), Verdict::Here);
1691	}
1692
1693	#[test]
1694	fn on_the_systems_drive_the_computer_has_to_match() {
1695		let mut rng = TestRng::new("place 3");
1696		let folder = Path::new("/nowhere/home/ada/.nib/replicas/a");
1697		let path = "home/ada/.nib/replicas/a";
1698		let made = at(path, Some(b"root"), Some(b"7"), true, Some(b"desktop"));
1699		let place = PlaceFile::new(&made, &mut rng);
1700		assert_eq!(place.verdict(&made, folder), Verdict::Here);
1701		// A computer cloned from the same image.
1702		let clone = at(path, Some(b"root"), Some(b"7"), true, Some(b"clone"));
1703		assert_eq!(place.verdict(&clone, folder), Verdict::Copy);
1704		// The same drive, as a data drive of another computer.
1705		let data = at(path, Some(b"root"), Some(b"7"), false, Some(b"other"));
1706		assert_eq!(place.verdict(&data, folder), Verdict::Here);
1707	}
1708
1709	#[test]
1710	fn a_stick_without_ids_of_folders_moves_between_computers() {
1711		let mut rng = TestRng::new("place 4");
1712		let folder = Path::new("/nowhere/stick/.nib/replicas/a");
1713		let made = at(
1714			".nib/replicas/a",
1715			Some(b"stick"),
1716			None,
1717			false,
1718			Some(b"desktop"),
1719		);
1720		let place = PlaceFile::new(&made, &mut rng);
1721		let laptop = at(
1722			".nib/replicas/a",
1723			Some(b"stick"),
1724			None,
1725			false,
1726			Some(b"laptop"),
1727		);
1728		assert_eq!(place.verdict(&laptop, folder), Verdict::Here);
1729		let another_stick = at(".nib/replicas/a", Some(b"another"), None, false, None);
1730		assert_eq!(place.verdict(&another_stick, folder), Verdict::Copy);
1731	}
1732
1733	#[test]
1734	fn a_phone_compares_its_id_alone() {
1735		let mut rng = TestRng::new("place 5");
1736		let folder = Path::new("/nowhere/app/library/replicas/a");
1737		let phone = |id: &[u8], container: &str| Whereabouts {
1738			drive: Drive {
1739				system: true,
1740				..Drive::default()
1741			},
1742			mount: PathBuf::from(container),
1743			folder: None,
1744			path: None,
1745			computer: (!id.is_empty()).then(|| id.to_vec()),
1746			phone: true,
1747		};
1748		let place = PlaceFile::new(&phone(b"phone", "/var/one"), &mut rng);
1749		assert_eq!(
1750			place.verdict(&phone(b"phone", "/var/two"), folder),
1751			Verdict::Here
1752		);
1753		assert_eq!(
1754			place.verdict(&phone(b"other", "/var/one"), folder),
1755			Verdict::Copy
1756		);
1757		// A phone that cannot read its ID has a copy.
1758		assert_eq!(
1759			place.verdict(&phone(b"", "/var/one"), folder),
1760			Verdict::Copy
1761		);
1762	}
1763
1764	#[test]
1765	fn a_place_that_records_nothing_but_a_path_is_here_wherever_the_path_is_but_on_a_computers_own_drive()
1766	 {
1767		let made = Whereabouts {
1768			mount: PathBuf::from("/one"),
1769			..at("replicas/a", None, None, false, None)
1770		};
1771		let place = PlaceFile::new(&made, &mut TestRng::new("place 6"));
1772		let folder = Path::new("/two/replicas/a");
1773		for now in [
1774			at("replicas/a", Some(b"disk"), Some(b"1"), false, None),
1775			at("replicas/a", None, None, false, None),
1776			// On the drive that a system runs from, where it reads no computer's ID, as iOS.
1777			at("replicas/a", None, None, true, None),
1778		] {
1779			assert_eq!(place.verdict(&now, folder), Verdict::Here);
1780		}
1781		let desktop = at(
1782			"replicas/a",
1783			Some(b"disk"),
1784			Some(b"1"),
1785			true,
1786			Some(b"desktop"),
1787		);
1788		assert_eq!(place.verdict(&desktop, folder), Verdict::Copy);
1789	}
1790
1791	#[test]
1792	fn a_sticks_replica_copied_to_a_computers_own_drive_is_a_copy_where_no_serial_is_read() {
1793		let mut rng = TestRng::new("place 8");
1794		let folder = Path::new("/nowhere/Users/ada/copy/.nib/replicas/a");
1795		// Made on a stick whose serial this system does not read, as macOS.
1796		let made = at(".nib/replicas/a", None, None, false, Some(b"mac"));
1797		let place = PlaceFile::new(&made, &mut rng);
1798		// The stick again, on the same computer or another.
1799		assert_eq!(place.verdict(&made, folder), Verdict::Here);
1800		let other = at(".nib/replicas/a", None, None, false, Some(b"desktop"));
1801		assert_eq!(place.verdict(&other, folder), Verdict::Here);
1802		// Copied to the computer's own drive, where the path it recorded leads to nothing.
1803		let copied = at(
1804			"Users/ada/copy/.nib/replicas/a",
1805			None,
1806			Some(b"9"),
1807			true,
1808			Some(b"mac"),
1809		);
1810		assert_eq!(place.verdict(&copied, folder), Verdict::Copy);
1811	}
1812
1813	#[test]
1814	fn without_ids_of_folders_one_moved_is_told_from_one_copied_beside_it() {
1815		let mut rng = TestRng::new("place 7");
1816		let root = std::env::temp_dir().join(format!("nibkeep-place-{}", std::process::id()));
1817		let _ = fs::remove_dir_all(&root);
1818		let first = root.join("first");
1819		let second = root.join("second");
1820		fs::create_dir_all(&first).unwrap();
1821		fs::create_dir_all(&second).unwrap();
1822		let now = |path: &str| Whereabouts {
1823			mount: root.clone(),
1824			..at(path, Some(b"stick"), None, false, None)
1825		};
1826		let place = PlaceFile::new(&now("first"), &mut rng);
1827		// The first folder is still there: the second is a copy of it.
1828		assert_eq!(place.verdict(&now("second"), &second), Verdict::Copy);
1829		// Once the first is gone, the second is the replica, moved.
1830		fs::remove_dir_all(&first).unwrap();
1831		assert_eq!(place.verdict(&now("second"), &second), Verdict::Here);
1832		fs::remove_dir_all(&root).unwrap();
1833	}
1834
1835	#[cfg(any(target_os = "linux", target_os = "android"))]
1836	#[test]
1837	fn the_mount_table_names_the_mount_that_holds_a_folder() {
1838		let table = "\
183933 2 0:30 /@ / rw,relatime shared:1 - btrfs /dev/mapper/root rw,subvol=/@
184066 33 0:30 /@home /home rw,relatime shared:193 - btrfs /dev/mapper/root rw,subvol=/@home
184170 33 8:17 / /run/media/ada/MY\\040STICK rw,nosuid shared:200 - exfat /dev/sdb1 rw
184271 66 0:50 / /home/ada/remote rw master:1 - fuse.sshfs ada@nas: rw
184372 66 0:51 / /home/ada/remote rw master:1 - tmpfs tmpfs rw
1844";
1845		let mounts = system::mounts(table);
1846		let of =
1847			|folder: &str| system::mount_of(&mounts, Path::new(folder)).map(|mount| &mount.point);
1848		assert_eq!(of("/home/ada/.nib"), Some(&PathBuf::from("/home")));
1849		assert_eq!(of("/etc"), Some(&PathBuf::from("/")));
1850		assert_eq!(
1851			of("/run/media/ada/MY STICK/.nib"),
1852			Some(&PathBuf::from("/run/media/ada/MY STICK"))
1853		);
1854		// Of two mounts at one folder, the later hides the earlier.
1855		let hiding = system::mount_of(&mounts, Path::new("/home/ada/remote/x")).unwrap();
1856		assert_eq!(hiding.kind, "tmpfs");
1857		assert_eq!(hiding.source, "tmpfs");
1858	}
1859
1860	#[cfg(windows)]
1861	#[test]
1862	fn windows_reads_its_own_drive_and_the_computers_id() {
1863		let windows = PathBuf::from(std::env::var_os("SystemRoot").expect("Windows' folder"));
1864		let here = whereabouts(&windows);
1865		assert!(here.drive.system, "{here:?}");
1866		assert!(here.drive.serial.is_some(), "{here:?}");
1867		assert!(here.drive.folder_ids && here.folder.is_some(), "{here:?}");
1868		assert!(
1869			!here.drive.remote && !here.drive.cloud && !here.drive.unjournaled,
1870			"{here:?}"
1871		);
1872		// The GUID that Windows draws when it is installed.
1873		assert_eq!(here.computer.as_ref().map(Vec::len), Some(16), "{here:?}");
1874		// Its drive, by the partition table that the drive's layout gives.
1875		let name = disk_name(&windows).expect("names the drive");
1876		assert!(
1877			name.starts_with(b"drive\0gpt\0") || name.starts_with(b"drive\0mbr\0"),
1878			"{name:?}"
1879		);
1880	}
1881
1882	#[cfg(windows)]
1883	#[test]
1884	fn onedrives_folder_is_one_that_a_program_takes_to_the_cloud() {
1885		// OneDrive names its folder in the environment, once it is set up.
1886		let Some(onedrive) = std::env::var_os("OneDrive")
1887			.map(PathBuf::from)
1888			.filter(|folder| folder.is_dir())
1889		else {
1890			return;
1891		};
1892		assert!(whereabouts(&onedrive.join("Passwords")).drive.cloud);
1893		let home = onedrive.parent().expect("the home folder");
1894		assert!(!whereabouts(home).drive.cloud);
1895	}
1896
1897	#[cfg(windows)]
1898	#[test]
1899	fn a_drive_that_is_not_there_is_not_taken_for_a_network_drive() {
1900		let Some(letter) = ('D'..='Z')
1901			.rev()
1902			.find(|letter| !Path::new(&format!(r"{letter}:\")).exists())
1903		else {
1904			return;
1905		};
1906		let here = whereabouts(&PathBuf::from(format!(r"{letter}:\Passwords\.nib")));
1907		assert!(!here.drive.remote, "{here:?}");
1908	}
1909
1910	#[cfg(windows)]
1911	#[test]
1912	fn a_share_is_a_network_drive() {
1913		let here = whereabouts(Path::new(r"\\localhost\C$\Windows"));
1914		assert!(here.drive.remote, "{here:?}");
1915	}
1916
1917	#[cfg(target_os = "macos")]
1918	#[test]
1919	fn the_home_folder_is_on_the_macs_own_drive() {
1920		let home = PathBuf::from(std::env::var_os("HOME").expect("a home folder"));
1921		let here = whereabouts(&home);
1922		assert!(here.drive.system, "{here:?}");
1923		assert_eq!(here.mount, Path::new("/"));
1924		assert!(here.drive.folder_ids && here.folder.is_some(), "{here:?}");
1925		assert!(!here.drive.remote && !here.drive.unjournaled, "{here:?}");
1926		assert_eq!(here.computer.as_ref().map(Vec::len), Some(16), "{here:?}");
1927		// A folder still to be made is on the drive of the folder above it.
1928		let new = whereabouts(&home.join("not made yet").join(".nib"));
1929		assert_eq!(new.mount, Path::new("/"));
1930		assert!(new.drive.system && !new.drive.remote, "{new:?}");
1931	}
1932}