Skip to main content

nibkeep_node/
backup.rs

1//! A backup's folder: what it holds, and how each file in it is written whole, without keys
2//! and without a database ([Storage](../../../docs/spec/storage.md#6-backups)). The engine
3//! reaches it through an interface of files, [`BackupFolder`]: on computers, the file system
4//! stands behind it; on Android, the folder that the system's picker gives.
5
6use std::collections::BTreeMap;
7use std::fs::{self, File};
8use std::io::{self, Read, Write};
9use std::path::{Path, PathBuf};
10use std::sync::Mutex;
11use std::time::{Duration, Instant};
12
13use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
14use nibkeep_base::{ChangeId, EntityId, Hash, SpaceId};
15
16use crate::recovery_file::{RECOVERY_FILE, RecoveryFile};
17use crate::{NodeError, place};
18
19/// The file that names a backup.
20pub(crate) const BACKUP_FILE: &str = "backup.cbor";
21
22/// The backup's record of its updates and checks.
23const RECORD: &str = "record.cbor";
24
25/// What the folder is, in plain words.
26const README: &str = "README.txt";
27
28/// The folders of packs, of blobs, of what checks found damaged, and of files being
29/// written.
30const SPACES: &str = "spaces";
31const BLOBS: &str = "blobs";
32const DAMAGED: &str = "damaged";
33const TMP: &str = "tmp";
34
35/// The file that an update locks, and the mark of an update under way.
36const LOCK: &str = "lock";
37const IN_USE: &str = "in-use";
38
39/// The files written anew in place of the old: where a folder cannot replace a file in one
40/// step, the old one is deleted before the new one moves in from `tmp/`, so an update that
41/// finds one of them in `tmp/` and none in its place moves it there first.
42const REPLACED: [&str; 2] = [RECORD, RECOVERY_FILE];
43
44/// The extension of packs.
45const PACK: &str = "pack";
46
47/// The version of the formats of `backup.cbor` and `record.cbor`.
48const VERSION: u64 = 1;
49
50/// What `README.txt` says.
51const README_TEXT: &str = "\
52This folder is a backup that NibKeep keeps up to date whenever one of its owner's
53devices finds it, such as when this drive is plugged in.
54
55Everything in it is encrypted, and it holds no keys: whoever finds it reads nothing.
56To restore from it, plug it into a computer of the owner's whose library holds the keys.
57
58Do not change, rename or add files here. To stop using it, remove it in NibKeep first
59(nib backup remove), then delete this folder.
60";
61
62/// A backup's folder, as the engine reads and writes it: files and folders under it, named by
63/// their paths from it, with `/` between names, such as `spaces/<space>/<digest>.pack`. On
64/// computers, the file system stands behind it; on Android, the folder that the system's
65/// picker gives, which gives files but no paths, never replaces a file in one step, and
66/// moves a file only under its own name ([technical design: backups]).
67///
68/// [technical design: backups]: ../../../docs/Technical-design.md#910-backups
69pub trait BackupFolder: Send + Sync {
70	/// A path in the folder, as messages show it.
71	fn shown(&self, path: &str) -> PathBuf;
72
73	/// The entries of a folder in it, `""` for the folder itself: each one's name, with a
74	/// file's size, or `None` for a folder.
75	///
76	/// # Errors
77	///
78	/// Returns an error of the kind [`io::ErrorKind::NotFound`] if there is no such folder.
79	fn list(&self, folder: &str) -> io::Result<Vec<(String, Option<u64>)>>;
80
81	/// Opens a file to read.
82	///
83	/// # Errors
84	///
85	/// Returns an error of the kind [`io::ErrorKind::NotFound`] if there is no such file.
86	fn open(&self, file: &str) -> io::Result<File>;
87
88	/// Makes a new file to write, and the folders it is in.
89	///
90	/// # Errors
91	///
92	/// Returns an error if it cannot be made, or one is there already.
93	fn create(&self, file: &str) -> io::Result<File>;
94
95	/// Opens a file to read and write, made if there is none: the one that an update locks.
96	///
97	/// # Errors
98	///
99	/// Returns an error if it cannot be opened or made.
100	fn open_lock(&self, file: &str) -> io::Result<File>;
101
102	/// Moves a file into another folder, made if there is none, under the same name, in place
103	/// of a file of that name there: in one step where the system can, and otherwise by
104	/// deleting that one first.
105	///
106	/// # Errors
107	///
108	/// Returns an error if it cannot be moved.
109	fn put(&self, file: &str, folder: &str) -> io::Result<()>;
110
111	/// Deletes a file, if it is there.
112	///
113	/// # Errors
114	///
115	/// Returns an error if it is there and cannot be deleted.
116	fn remove(&self, file: &str) -> io::Result<()>;
117
118	/// Whether a file is there.
119	fn exists(&self, file: &str) -> bool {
120		self.open(file).is_ok()
121	}
122
123	/// Saves a folder's entries to the disk, where the system allows it.
124	fn sync_folder(&self, _folder: &str) {}
125
126	/// How many bytes its drive has free.
127	///
128	/// # Errors
129	///
130	/// Returns an error if the system does not say.
131	fn free(&self) -> io::Result<u64>;
132
133	/// What its drive is, as copies count it.
134	fn drive(&self) -> BackupDrive;
135
136	/// Whether its file system keeps no journal, as [`BackupDrive::unjournaled`] says, which
137	/// an update asks before it needs the rest.
138	fn unjournaled(&self) -> bool {
139		self.drive().unjournaled
140	}
141}
142
143/// What the drive or share that holds a backup's folder is, as copies count it.
144#[derive(Clone, Debug, Default, PartialEq, Eq)]
145pub struct BackupDrive {
146	/// The folder's path from the root of its drive or share, with `/` between names, if the
147	/// system says: where computers look for it under each mount.
148	pub path: Option<String>,
149	/// What names its disk, as a replica's would be, so that a backup and a replica on one
150	/// drive count once; `None` where nothing names it, as on a network share, where the
151	/// backup itself names its disk.
152	pub disk: Option<Vec<u8>>,
153	/// Whether it is on another computer, as a network share is.
154	pub remote: bool,
155	/// Whether its file system keeps no journal, as FAT, exFAT and ext2, so that a drive
156	/// pulled out while written may damage other files.
157	pub unjournaled: bool,
158}
159
160/// A backup's folder in the file system, on a computer.
161pub(crate) struct InFileSystem {
162	folder: PathBuf,
163}
164
165impl InFileSystem {
166	pub(crate) fn new(folder: &Path) -> Self {
167		Self {
168			folder: folder.to_owned(),
169		}
170	}
171
172	/// The path in the file system of a path in the folder.
173	fn at(&self, path: &str) -> PathBuf {
174		path.split('/')
175			.filter(|name| !name.is_empty())
176			.fold(self.folder.clone(), |at, name| at.join(name))
177	}
178}
179
180impl BackupFolder for InFileSystem {
181	fn shown(&self, path: &str) -> PathBuf {
182		self.at(path)
183	}
184
185	fn list(&self, folder: &str) -> io::Result<Vec<(String, Option<u64>)>> {
186		let mut entries = Vec::new();
187		for entry in fs::read_dir(self.at(folder))?.flatten() {
188			let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
189				continue;
190			};
191			let Ok(metadata) = entry.metadata() else {
192				continue;
193			};
194			entries.push((name, metadata.is_file().then_some(metadata.len())));
195		}
196		Ok(entries)
197	}
198
199	fn open(&self, file: &str) -> io::Result<File> {
200		File::open(self.at(file))
201	}
202
203	fn create(&self, file: &str) -> io::Result<File> {
204		let at = self.at(file);
205		if let Some(parent) = at.parent() {
206			fs::create_dir_all(parent)?;
207		}
208		File::options()
209			.read(true)
210			.write(true)
211			.create_new(true)
212			.open(at)
213	}
214
215	fn open_lock(&self, file: &str) -> io::Result<File> {
216		File::options()
217			.read(true)
218			.write(true)
219			.create(true)
220			.truncate(false)
221			.open(self.at(file))
222	}
223
224	fn put(&self, file: &str, folder: &str) -> io::Result<()> {
225		let from = self.at(file);
226		let name = from.file_name().ok_or(io::ErrorKind::InvalidInput)?;
227		let into = self.at(folder);
228		fs::create_dir_all(&into)?;
229		// A rename replaces in one step.
230		fs::rename(&from, into.join(name))
231	}
232
233	fn remove(&self, file: &str) -> io::Result<()> {
234		match fs::remove_file(self.at(file)) {
235			Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
236			done => done,
237		}
238	}
239
240	fn exists(&self, file: &str) -> bool {
241		self.at(file).exists()
242	}
243
244	fn sync_folder(&self, folder: &str) {
245		sync_folder(&self.at(folder));
246	}
247
248	fn free(&self) -> io::Result<u64> {
249		fs4::available_space(&self.folder)
250	}
251
252	fn unjournaled(&self) -> bool {
253		place::whereabouts(&self.folder).drive.unjournaled
254	}
255
256	fn drive(&self) -> BackupDrive {
257		let whereabouts = place::whereabouts(&self.folder);
258		let remote = whereabouts.drive.remote;
259		BackupDrive {
260			disk: (!remote).then(|| place::disk_name(&self.folder)).flatten(),
261			path: whereabouts.path,
262			remote,
263			unjournaled: whereabouts.drive.unjournaled,
264		}
265	}
266}
267
268/// A folder that keeps the rules of Android's picker over a folder of the file system, for
269/// tests: making a file that exists fails, a move keeps the file's name, nothing replaces a
270/// file in one step, and no folder is synchronized. Its drive is as `drive` says, and it
271/// shows paths as the picker does, after the drive's title and the folder's path on it.
272#[doc(hidden)]
273pub struct PickerRules {
274	root: PathBuf,
275	drive: BackupDrive,
276	/// The moves asked for, each a file and the folder it went to.
277	moves: Mutex<Vec<(String, String)>>,
278}
279
280impl PickerRules {
281	/// The folder `root`, made if there is none, on `drive`.
282	///
283	/// # Panics
284	///
285	/// Panics if the folder cannot be made.
286	#[must_use]
287	pub fn new(root: &Path, drive: BackupDrive) -> Self {
288		fs::create_dir_all(root).expect("makes the picked folder");
289		Self {
290			root: root.to_owned(),
291			drive,
292			moves: Mutex::new(Vec::new()),
293		}
294	}
295
296	/// The moves asked for until now, each a file and the folder it went to.
297	#[must_use]
298	pub fn moves(&self) -> Vec<(String, String)> {
299		self.moves
300			.lock()
301			.unwrap_or_else(std::sync::PoisonError::into_inner)
302			.clone()
303	}
304
305	fn at(&self, path: &str) -> PathBuf {
306		InFileSystem::new(&self.root).at(path)
307	}
308}
309
310impl BackupFolder for PickerRules {
311	/// With `/` between names, as on Android, whatever system the test runs on.
312	fn shown(&self, path: &str) -> PathBuf {
313		let names = self
314			.drive
315			.path
316			.iter()
317			.flat_map(|on| on.split('/'))
318			.chain(path.split('/'))
319			.filter(|name| !name.is_empty());
320		PathBuf::from(
321			std::iter::once("USB drive")
322				.chain(names)
323				.collect::<Vec<_>>()
324				.join("/"),
325		)
326	}
327
328	fn list(&self, folder: &str) -> io::Result<Vec<(String, Option<u64>)>> {
329		InFileSystem::new(&self.root).list(folder)
330	}
331
332	fn open(&self, file: &str) -> io::Result<File> {
333		File::open(self.at(file))
334	}
335
336	fn create(&self, file: &str) -> io::Result<File> {
337		InFileSystem::new(&self.root).create(file)
338	}
339
340	fn open_lock(&self, file: &str) -> io::Result<File> {
341		InFileSystem::new(&self.root).open_lock(file)
342	}
343
344	fn put(&self, file: &str, folder: &str) -> io::Result<()> {
345		let from = self.at(file);
346		let name = from.file_name().ok_or(io::ErrorKind::InvalidInput)?;
347		let to = self.at(folder).join(name);
348		// What is there goes first, in a step of its own.
349		match fs::remove_file(&to) {
350			Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
351			_ => {}
352		}
353		fs::create_dir_all(self.at(folder))?;
354		self.moves
355			.lock()
356			.unwrap_or_else(std::sync::PoisonError::into_inner)
357			.push((file.to_owned(), folder.to_owned()));
358		fs::rename(from, to)
359	}
360
361	fn remove(&self, file: &str) -> io::Result<()> {
362		InFileSystem::new(&self.root).remove(file)
363	}
364
365	fn free(&self) -> io::Result<u64> {
366		Ok(64 << 30)
367	}
368
369	fn drive(&self) -> BackupDrive {
370		self.drive.clone()
371	}
372}
373
374/// A path in a backup's folder, from a folder's path in it and a name.
375fn joined(folder: &str, name: &str) -> String {
376	if folder.is_empty() {
377		name.to_owned()
378	} else {
379		format!("{folder}/{name}")
380	}
381}
382
383/// The folder that holds a path in a backup's folder, `""` for the folder itself.
384fn parent_of(path: &str) -> &str {
385	path.rsplit_once('/').map_or("", |(parent, _)| parent)
386}
387
388/// A backup's record of its updates and checks.
389#[derive(Clone, Debug, Default, PartialEq, Eq)]
390pub(crate) struct Record {
391	/// The number of its last update.
392	pub(crate) update: u64,
393	/// When each sealed blob that it holds was last read in full and found intact, in
394	/// milliseconds since 1970, or 0.
395	pub(crate) checks: BTreeMap<Hash, u64>,
396	/// When checks found each damaged copy, in the 4 weeks before the update.
397	pub(crate) damaged: BTreeMap<Hash, u64>,
398	/// How long the backup waits before purging, from each time on, in milliseconds, as its
399	/// updates saw its owner's mark ([technical design: copies that wait]).
400	///
401	/// [technical design: copies that wait]: ../../../docs/Technical-design.md#911-copies-that-wait
402	pub(crate) waits: Vec<(u64, u64)>,
403	/// The purges whose destruction the backup keeps apart, each with when the update that
404	/// first brought it ran, and how many items and files it keeps of it.
405	pub(crate) purges: BTreeMap<ChangeId, (u64, u64)>,
406}
407
408impl Record {
409	fn to_bytes(&self) -> Vec<u8> {
410		let pairs = |map: &BTreeMap<Hash, u64>| {
411			Value::Array(
412				map.iter()
413					.map(|(sealed, at)| Value::Array(vec![sealed.to_cbor(), at.to_cbor()]))
414					.collect(),
415			)
416		};
417		let waits = Value::Array(
418			self.waits
419				.iter()
420				.map(|(since, wait)| Value::Array(vec![since.to_cbor(), wait.to_cbor()]))
421				.collect(),
422		);
423		let purges = Value::Array(
424			self.purges
425				.iter()
426				.map(|(purge, (seen, items))| {
427					Value::Array(vec![purge.to_cbor(), seen.to_cbor(), items.to_cbor()])
428				})
429				.collect(),
430		);
431		cbor::encode(&Value::Array(vec![
432			VERSION.to_cbor(),
433			self.update.to_cbor(),
434			pairs(&self.checks),
435			pairs(&self.damaged),
436			waits,
437			purges,
438		]))
439	}
440
441	fn from_bytes(bytes: &[u8]) -> Option<Self> {
442		let Value::Array(items) = cbor::decode(bytes).ok()? else {
443			return None;
444		};
445		let [version, update, checks, damaged, waits, purges] = items.as_slice() else {
446			return None;
447		};
448		if u64::from_cbor(version).ok()? != VERSION {
449			return None;
450		}
451		let pairs = |value: &Value| -> Option<BTreeMap<Hash, u64>> {
452			let Value::Array(pairs) = value else {
453				return None;
454			};
455			let mut map = BTreeMap::new();
456			for pair in pairs {
457				let Value::Array(pair) = pair else {
458					return None;
459				};
460				let [sealed, at] = pair.as_slice() else {
461					return None;
462				};
463				map.insert(Hash::from_cbor(sealed).ok()?, u64::from_cbor(at).ok()?);
464			}
465			Some(map)
466		};
467		let Value::Array(waits) = waits else {
468			return None;
469		};
470		let mut read = Vec::new();
471		for pair in waits {
472			let Value::Array(pair) = pair else {
473				return None;
474			};
475			let [since, wait] = pair.as_slice() else {
476				return None;
477			};
478			read.push((u64::from_cbor(since).ok()?, u64::from_cbor(wait).ok()?));
479		}
480		let Value::Array(purges) = purges else {
481			return None;
482		};
483		let mut seen = BTreeMap::new();
484		for pair in purges {
485			let Value::Array(pair) = pair else {
486				return None;
487			};
488			let [purge, at, items] = pair.as_slice() else {
489				return None;
490			};
491			seen.insert(
492				ChangeId::from_cbor(purge).ok()?,
493				(u64::from_cbor(at).ok()?, u64::from_cbor(items).ok()?),
494			);
495		}
496		Some(Self {
497			update: u64::from_cbor(update).ok()?,
498			checks: pairs(checks)?,
499			damaged: pairs(damaged)?,
500			waits: read,
501			purges: seen,
502		})
503	}
504}
505
506/// A file's bytes in a backup's folder.
507fn read_all(files: &dyn BackupFolder, file: &str) -> io::Result<Vec<u8>> {
508	let mut bytes = Vec::new();
509	files.open(file)?.read_to_end(&mut bytes)?;
510	Ok(bytes)
511}
512
513/// The backup that a folder names, if it names one, by its record's ID.
514#[must_use]
515pub fn named_at(folder: &Path) -> Option<EntityId> {
516	named_in(&InFileSystem::new(folder))
517}
518
519/// The backup that a folder reached through the interface of files names, if it names one,
520/// by its record's ID.
521#[must_use]
522pub fn named_in(files: &dyn BackupFolder) -> Option<EntityId> {
523	let bytes = read_all(files, BACKUP_FILE).ok()?;
524	let Value::Array(items) = cbor::decode(&bytes).ok()? else {
525		return None;
526	};
527	let [version, id] = items.as_slice() else {
528		return None;
529	};
530	if u64::from_cbor(version).ok()? != VERSION {
531		return None;
532	}
533	let Value::Bytes(id) = id else {
534		return None;
535	};
536	Some(EntityId::from_bytes(
537		<[u8; 16]>::try_from(id.as_slice()).ok()?,
538	))
539}
540
541/// Makes a backup's folder, which must be new or empty: the file that names the backup, and
542/// what the folder is.
543pub(crate) fn make(files: &dyn BackupFolder, backup: EntityId) -> Result<(), NodeError> {
544	match files.list("") {
545		Ok(entries) => {
546			if !entries.is_empty() {
547				return Err(NodeError::BackupFolder(format!(
548					"{} is not empty, and a backup is made only in an empty folder or a new one",
549					files.shown("").display()
550				)));
551			}
552		}
553		Err(error) if error.kind() == io::ErrorKind::NotFound => {}
554		Err(error) => return Err(NodeError::file(&files.shown(""))(error)),
555	}
556	let named = cbor::encode(&Value::Array(vec![
557		VERSION.to_cbor(),
558		Value::Bytes(backup.as_bytes().to_vec()),
559	]));
560	for (name, bytes) in [
561		(README, README_TEXT.as_bytes()),
562		(BACKUP_FILE, named.as_slice()),
563	] {
564		(|| {
565			let mut file = files.create(name)?;
566			file.write_all(bytes)?;
567			file.sync_all()
568		})()
569		.map_err(NodeError::file(&files.shown(name)))?;
570	}
571	files.sync_folder("");
572	Ok(())
573}
574
575/// Takes away what [`make`] wrote, after the backup could not be recorded.
576pub(crate) fn unmake(files: &dyn BackupFolder) {
577	for name in [README, BACKUP_FILE] {
578		let _ = files.remove(name);
579	}
580}
581
582/// A backup's record, read from its folder, or an empty one where it has none that reads.
583pub(crate) fn read_record(files: &dyn BackupFolder) -> Record {
584	read_all(files, RECORD)
585		.ok()
586		.and_then(|bytes| Record::from_bytes(&bytes))
587		.unwrap_or_default()
588}
589
590/// The sealed blobs that the backup in `files` holds in files of their own, with their
591/// sizes.
592///
593/// # Errors
594///
595/// Returns an error if the folder of blobs cannot be read.
596pub(crate) fn blob_files_in(files: &dyn BackupFolder) -> Result<BTreeMap<Hash, u64>, NodeError> {
597	let mut blobs = BTreeMap::new();
598	let algorithms = match files.list(BLOBS) {
599		Ok(entries) => entries,
600		Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(blobs),
601		Err(error) => return Err(NodeError::file(&files.shown(BLOBS))(error)),
602	};
603	for (algorithm, size) in algorithms {
604		if size.is_some() {
605			continue;
606		}
607		let of_algorithm = joined(BLOBS, &algorithm);
608		let Ok(prefixes) = files.list(&of_algorithm) else {
609			continue;
610		};
611		for (prefix, size) in prefixes {
612			if size.is_some() {
613				continue;
614			}
615			let of_prefix = joined(&of_algorithm, &prefix);
616			let Ok(entries) = files.list(&of_prefix) else {
617				continue;
618			};
619			for (digest, size) in entries {
620				if let Some(size) = size
621					&& let Ok(sealed) = format!("{algorithm}:{digest}").parse::<Hash>()
622					&& blob_path(&sealed) == joined(&of_prefix, &digest)
623				{
624					blobs.insert(sealed, size);
625				}
626			}
627		}
628	}
629	Ok(blobs)
630}
631
632/// Whether the backup in `files` holds the mark of an update: one under way, or one that a
633/// drive pulled out or a lost power cut short, after which its copies count again only once
634/// read back.
635pub(crate) fn marked_in_use(files: &dyn BackupFolder) -> bool {
636	files.exists(IN_USE)
637}
638
639/// Where a backup keeps a sealed blob in a file of its own, as a replica does.
640pub(crate) fn blob_path(sealed: &Hash) -> String {
641	nibkeep_store::place_in(Path::new(BLOBS), sealed)
642		.components()
643		.map(|name| name.as_os_str().to_string_lossy())
644		.collect::<Vec<_>>()
645		.join("/")
646}
647
648/// What names the disk of a backup in `files`, as copies count disks: its drive's name, as
649/// a replica's would be, so that a backup and a replica on one drive count once; on a
650/// network share, whose drive no system names, or where nothing names it, the backup
651/// itself ([technical design](../../../docs/Technical-design.md#910-backups)).
652pub(crate) fn disk_name(files: &dyn BackupFolder, backup: EntityId) -> Vec<u8> {
653	files
654		.drive()
655		.disk
656		.unwrap_or_else(|| [b"backup\0".as_slice(), backup.as_bytes()].concat())
657}
658
659/// The folders that drives and shares are mounted at, as the system lists them: on Linux,
660/// each mount point of the mount table; on macOS, the system's drive and each volume in
661/// `/Volumes`; on Windows, each drive's letter.
662pub(crate) fn mounts() -> Vec<PathBuf> {
663	let mut mounts = system_mounts();
664	mounts.sort();
665	mounts.dedup();
666	mounts
667}
668
669#[cfg(any(target_os = "linux", target_os = "android"))]
670fn system_mounts() -> Vec<PathBuf> {
671	let Ok(table) = fs::read_to_string("/proc/self/mountinfo") else {
672		return Vec::new();
673	};
674	table.lines().filter_map(mount_of_line).collect()
675}
676
677/// The mount point of a line of the mount table, unless its file system holds no files of
678/// a person's, as the kernel's own do, or is mounted on access, as autofs is, which a look
679/// would set off.
680#[cfg(any(target_os = "linux", target_os = "android", test))]
681fn mount_of_line(line: &str) -> Option<PathBuf> {
682	const NOT_FOR_FILES: [&str; 22] = [
683		"autofs",
684		"binfmt_misc",
685		"bpf",
686		"cgroup",
687		"cgroup2",
688		"configfs",
689		"debugfs",
690		"devpts",
691		"devtmpfs",
692		"efivarfs",
693		"fusectl",
694		"hugetlbfs",
695		"mqueue",
696		"nsfs",
697		"proc",
698		"pstore",
699		"ramfs",
700		"rpc_pipefs",
701		"securityfs",
702		"squashfs",
703		"sysfs",
704		"tracefs",
705	];
706	let mount = line.split(' ').nth(4)?;
707	let kind = line.split(" - ").nth(1)?.split(' ').next()?;
708	(!NOT_FOR_FILES.contains(&kind)).then(|| PathBuf::from(unescape_mount(mount)))
709}
710
711/// A mount point as the mount table writes it, with a space, a tab, a line feed and a
712/// backslash as octal escapes.
713#[cfg(any(target_os = "linux", target_os = "android", test))]
714fn unescape_mount(written: &str) -> String {
715	let mut text = String::with_capacity(written.len());
716	let mut rest = written;
717	while let Some(at) = rest.find('\\') {
718		text.push_str(rest.get(..at).unwrap_or_default());
719		let code = rest
720			.get(at + 1..at + 4)
721			.and_then(|digits| u8::from_str_radix(digits, 8).ok());
722		if let Some(byte) = code {
723			text.push(char::from(byte));
724			rest = rest.get(at + 4..).unwrap_or_default();
725		} else {
726			text.push('\\');
727			rest = rest.get(at + 1..).unwrap_or_default();
728		}
729	}
730	text.push_str(rest);
731	text
732}
733
734#[cfg(target_os = "macos")]
735fn system_mounts() -> Vec<PathBuf> {
736	let mut mounts = vec![PathBuf::from("/")];
737	if let Ok(volumes) = fs::read_dir("/Volumes") {
738		mounts.extend(volumes.flatten().map(|volume| volume.path()));
739	}
740	mounts
741}
742
743#[cfg(windows)]
744fn system_mounts() -> Vec<PathBuf> {
745	(b'A'..=b'Z')
746		.map(|letter| PathBuf::from(format!("{}:\\", char::from(letter))))
747		.filter(|root| fs::metadata(root).is_ok())
748		.collect()
749}
750
751#[cfg(not(any(
752	target_os = "linux",
753	target_os = "android",
754	target_os = "macos",
755	windows
756)))]
757fn system_mounts() -> Vec<PathBuf> {
758	Vec::new()
759}
760
761/// The folders of mounts where a look did not end in time, as a network share whose server
762/// went away: left out of looks for ten minutes, so that looks do not pile up behind them.
763static SLOW: Mutex<BTreeMap<PathBuf, Instant>> = Mutex::new(BTreeMap::new());
764
765/// How long a mount where a look did not end in time is left out of looks.
766const SLOW_FOR: Duration = Duration::from_mins(10);
767
768/// Of `candidates`, each a mount's folder (or the folder itself), a folder there and the
769/// backup it may hold, those whose folder names that backup, in their order; looked at on a
770/// thread of their own, for at most `within`, so that a network share that does not answer
771/// never holds up the caller: one found slow is left out of looks for a while.
772pub(crate) fn find_named(
773	candidates: Vec<(PathBuf, PathBuf, EntityId)>,
774	within: Duration,
775) -> Vec<(EntityId, PathBuf)> {
776	let now = Instant::now();
777	let candidates: Vec<(PathBuf, PathBuf, EntityId)> = {
778		let mut slow = SLOW
779			.lock()
780			.unwrap_or_else(std::sync::PoisonError::into_inner);
781		slow.retain(|_, since| now.duration_since(*since) < SLOW_FOR);
782		candidates
783			.into_iter()
784			.filter(|(root, _, _)| !slow.contains_key(root))
785			.collect()
786	};
787	let (sender, results) = std::sync::mpsc::channel();
788	let looked = candidates.clone();
789	std::thread::spawn(move || {
790		for (at, (_, folder, backup)) in looked.into_iter().enumerate() {
791			let named = named_at(&folder) == Some(backup);
792			if sender.send((at, named)).is_err() {
793				return;
794			}
795		}
796	});
797	let deadline = now + within;
798	let mut found = Vec::new();
799	let mut answered = 0;
800	while answered < candidates.len() {
801		let Some(left) = deadline.checked_duration_since(Instant::now()) else {
802			break;
803		};
804		match results.recv_timeout(left) {
805			Ok((at, named)) => {
806				answered = at + 1;
807				if named && let Some((_, folder, backup)) = candidates.get(at) {
808					found.push((*backup, folder.clone()));
809				}
810			}
811			Err(_) => break,
812		}
813	}
814	if let Some((root, _, _)) = candidates.get(answered) {
815		SLOW.lock()
816			.unwrap_or_else(std::sync::PoisonError::into_inner)
817			.insert(root.clone(), Instant::now());
818	}
819	found
820}
821
822/// A backup's folder, held by an update: locked, and marked as being updated, until it
823/// goes.
824pub(crate) struct Updating<'a> {
825	files: &'a dyn BackupFolder,
826	_lock: File,
827	/// Whether the folder held the mark of an update while nobody held the lock: a drive
828	/// pulled out or that lost its power during an update.
829	pub(crate) unclean: bool,
830	/// Whether its file system keeps no journal, as FAT, exFAT and ext2.
831	pub(crate) unjournaled: bool,
832}
833
834impl<'a> Updating<'a> {
835	/// Holds the backup in `files` for an update: `None` while another program holds it.
836	///
837	/// # Errors
838	///
839	/// Returns [`NodeError::NotTheBackup`] if the folder names another backup or none, and an
840	/// error if its files cannot be written.
841	pub(crate) fn hold(
842		files: &'a dyn BackupFolder,
843		backup: EntityId,
844		name: &str,
845	) -> Result<Option<Self>, NodeError> {
846		if named_in(files) != Some(backup) {
847			return Err(NodeError::NotTheBackup {
848				path: files.shown(""),
849				name: name.to_owned(),
850			});
851		}
852		let lock = files
853			.open_lock(LOCK)
854			.map_err(NodeError::file(&files.shown(LOCK)))?;
855		match lock.try_lock() {
856			Ok(()) => {}
857			Err(fs::TryLockError::WouldBlock) => return Ok(None),
858			Err(fs::TryLockError::Error(error)) => {
859				return Err(NodeError::file(&files.shown(LOCK))(error));
860			}
861		}
862		let unclean = files.exists(IN_USE);
863		if !unclean {
864			(|| {
865				let mark = files.create(IN_USE)?;
866				mark.sync_all()
867			})()
868			.map_err(NodeError::file(&files.shown(IN_USE)))?;
869			files.sync_folder("");
870		}
871		// A file written anew whose old one was deleted, before it moved into place: told from
872		// the folders' listings, never from a look that failed.
873		if let (Ok(here), Ok(staged)) = (files.list(""), files.list(TMP)) {
874			let holds = |entries: &[(String, Option<u64>)], name: &str| {
875				entries
876					.iter()
877					.any(|(entry, size)| entry == name && size.is_some())
878			};
879			for name in REPLACED {
880				if !holds(&here, name) && holds(&staged, name) {
881					files
882						.put(&joined(TMP, name), "")
883						.map_err(NodeError::file(&files.shown(name)))?;
884				}
885			}
886		}
887		// What a pulled drive left half written.
888		if let Ok(entries) = files.list(TMP) {
889			for (name, _) in entries {
890				let _ = files.remove(&joined(TMP, &name));
891			}
892		}
893		Ok(Some(Self {
894			files,
895			_lock: lock,
896			unclean,
897			unjournaled: files.unjournaled(),
898		}))
899	}
900
901	/// A path in the folder, as messages show it.
902	pub(crate) fn shown(&self, path: &str) -> PathBuf {
903		self.files.shown(path)
904	}
905
906	/// The backup's record, or an empty one where it has none that reads.
907	pub(crate) fn record(&self) -> Record {
908		read_record(self.files)
909	}
910
911	/// The backup's recovery file: `None` where there is none, or one that does not read, as
912	/// on a damaged drive.
913	pub(crate) fn recovery(&self) -> Option<RecoveryFile> {
914		RecoveryFile::from_bytes(&read_all(self.files, RECOVERY_FILE).ok()?)
915	}
916
917	/// Writes the backup's recovery file anew, whole, from its bytes.
918	///
919	/// # Errors
920	///
921	/// Returns an error if it cannot be written whole, or does not read back.
922	pub(crate) fn save_recovery(&self, bytes: &[u8]) -> Result<(), NodeError> {
923		self.write_whole(RECOVERY_FILE, &mut &*bytes, None)
924			.map(|_| ())
925	}
926
927	/// Deletes the backup's recovery file.
928	///
929	/// # Errors
930	///
931	/// Returns an error if it is there and cannot be deleted.
932	pub(crate) fn delete_recovery(&self) -> Result<(), NodeError> {
933		self.delete(RECOVERY_FILE)
934	}
935
936	/// Writes the backup's record anew.
937	///
938	/// # Errors
939	///
940	/// Returns an error if it cannot be written whole.
941	pub(crate) fn save_record(&self, record: &Record) -> Result<(), NodeError> {
942		let bytes = record.to_bytes();
943		self.write_whole(RECORD, &mut bytes.as_slice(), None)
944			.map(|_| ())
945	}
946
947	/// The packs of each space, by their paths, with their sizes.
948	///
949	/// # Errors
950	///
951	/// Returns an error if the folders cannot be read.
952	pub(crate) fn packs(&self) -> Result<Vec<(SpaceId, String, u64)>, NodeError> {
953		let mut packs = Vec::new();
954		let spaces = match self.files.list(SPACES) {
955			Ok(entries) => entries,
956			Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(packs),
957			Err(error) => return Err(NodeError::file(&self.shown(SPACES))(error)),
958		};
959		for (name, size) in spaces {
960			let Some(space) = size
961				.is_none()
962				.then(|| name.parse::<SpaceId>().ok())
963				.flatten()
964			else {
965				continue;
966			};
967			let folder = joined(SPACES, &name);
968			let Ok(files) = self.files.list(&folder) else {
969				continue;
970			};
971			for (file, size) in files {
972				if let Some(size) = size
973					&& Path::new(&file)
974						.extension()
975						.and_then(|extension| extension.to_str())
976						== Some(PACK)
977				{
978					packs.push((space, joined(&folder, &file), size));
979				}
980			}
981		}
982		packs.sort();
983		Ok(packs)
984	}
985
986	/// The sealed blobs that the backup holds in files of their own, with their sizes.
987	///
988	/// # Errors
989	///
990	/// Returns an error if the folder of blobs cannot be read.
991	pub(crate) fn blob_files(&self) -> Result<BTreeMap<Hash, u64>, NodeError> {
992		blob_files_in(self.files)
993	}
994
995	/// Where the backup keeps a pack of `space` whose BLAKE3 hash is `hash`.
996	pub(crate) fn pack_path(space: SpaceId, hash: &Hash) -> String {
997		format!("{SPACES}/{space}/{}.{PACK}", hex(hash.digest()))
998	}
999
1000	/// A file's bytes.
1001	pub(crate) fn read(&self, file: &str) -> io::Result<Vec<u8>> {
1002		read_all(self.files, file)
1003	}
1004
1005	/// Opens a file to read.
1006	pub(crate) fn open(&self, file: &str) -> io::Result<File> {
1007		self.files.open(file)
1008	}
1009
1010	/// The BLAKE3 hash of a file's bytes.
1011	pub(crate) fn hash(&self, file: &str) -> io::Result<Hash> {
1012		hash_of(&mut self.files.open(file)?)
1013	}
1014
1015	/// Writes a pack of `space` from its bytes, whole, and returns its path.
1016	///
1017	/// # Errors
1018	///
1019	/// Returns an error if it cannot be written whole, or does not read back.
1020	pub(crate) fn write_pack(&self, space: SpaceId, bytes: &[u8]) -> Result<String, NodeError> {
1021		let hash = Hash::of(bytes);
1022		let path = Self::pack_path(space, &hash);
1023		if !self.files.exists(&path) {
1024			self.write_whole(&path, &mut &*bytes, Some(&hash))?;
1025		}
1026		Ok(path)
1027	}
1028
1029	/// Writes a sealed blob in a file of its own, whole, from `bytes`, and returns whether it
1030	/// did: not if `bytes` do not have its sealed hash, as a damaged copy's.
1031	///
1032	/// # Errors
1033	///
1034	/// Returns an error if it cannot be written whole, or does not read back as written.
1035	pub(crate) fn write_blob(
1036		&self,
1037		sealed: &Hash,
1038		bytes: &mut dyn Read,
1039	) -> Result<bool, NodeError> {
1040		self.write_whole(&blob_path(sealed), bytes, Some(sealed))
1041	}
1042
1043	/// Moves a pack or a blob's file aside, to `damaged/`, as a check found it damaged.
1044	pub(crate) fn set_aside(&self, path: &str) {
1045		if self.files.put(path, DAMAGED).is_err() {
1046			let _ = self.files.remove(path);
1047		}
1048		self.files.sync_folder(DAMAGED);
1049	}
1050
1051	/// Deletes a pack or a blob's file.
1052	pub(crate) fn delete(&self, path: &str) -> Result<(), NodeError> {
1053		self.files
1054			.remove(path)
1055			.map_err(NodeError::file(&self.shown(path)))?;
1056		self.files.sync_folder(parent_of(path));
1057		Ok(())
1058	}
1059
1060	/// How many bytes its drive has free.
1061	pub(crate) fn free(&self) -> Result<u64, NodeError> {
1062		self.files.free().map_err(NodeError::file(&self.shown("")))
1063	}
1064
1065	/// Writes a file whole: into `tmp/` under its own name, synchronized, moved into place, and
1066	/// read back as written. Returns whether it wrote it: not if `hash` is given and the bytes
1067	/// do not have it, which leaves `path` as it was. One that does not read back is deleted.
1068	fn write_whole(
1069		&self,
1070		path: &str,
1071		bytes: &mut dyn Read,
1072		hash: Option<&Hash>,
1073	) -> Result<bool, NodeError> {
1074		let name = path.rsplit('/').next().unwrap_or(path);
1075		let staged = joined(TMP, name);
1076		let failed = |error| NodeError::file(&self.shown(&staged))(error);
1077		// One left by a write that failed.
1078		self.files.remove(&staged).map_err(failed)?;
1079		let written = (|| -> io::Result<Hash> {
1080			let mut file = self.files.create(&staged)?;
1081			let mut hasher = nibkeep_base::Hasher::new();
1082			let mut buffer = vec![0; 1 << 20];
1083			loop {
1084				let read = bytes.read(&mut buffer)?;
1085				if read == 0 {
1086					break;
1087				}
1088				let chunk = buffer.get(..read).unwrap_or_default();
1089				hasher.update(chunk);
1090				file.write_all(chunk)?;
1091			}
1092			file.sync_all()?;
1093			Ok(hasher.finalize())
1094		})();
1095		let written = match written {
1096			Ok(written) => written,
1097			Err(error) => {
1098				let _ = self.files.remove(&staged);
1099				return Err(failed(error));
1100			}
1101		};
1102		if hash.is_some_and(|hash| *hash != written) {
1103			let _ = self.files.remove(&staged);
1104			return Ok(false);
1105		}
1106		let parent = parent_of(path);
1107		if let Err(error) = self.files.put(&staged, parent) {
1108			// One that replaces a file stays, so that the next update moves it in.
1109			if !REPLACED.contains(&path) {
1110				let _ = self.files.remove(&staged);
1111			}
1112			return Err(NodeError::file(&self.shown(path))(error));
1113		}
1114		self.files.sync_folder(parent);
1115		// Read back, as the drive keeps it, and synchronized where it is now: where a folder
1116		// cannot be synchronized, as through Android's picker, FAT and exFAT write a file's
1117		// entry in its folder as they synchronize the file.
1118		// A system that synchronizes no file opened to read, as Windows, has done so already.
1119		let read_back = self.files.open(path).and_then(|mut file| {
1120			let hash = hash_of(&mut file)?;
1121			let _ = file.sync_all();
1122			Ok(hash)
1123		});
1124		if read_back.ok() != Some(written) {
1125			let _ = self.files.remove(path);
1126			return Err(NodeError::BackupWrite(self.shown(path)));
1127		}
1128		Ok(true)
1129	}
1130}
1131
1132impl Drop for Updating<'_> {
1133	/// Takes the mark away, as the update ends, before the lock goes.
1134	fn drop(&mut self) {
1135		if self.files.remove(IN_USE).is_ok() {
1136			self.files.sync_folder("");
1137		}
1138	}
1139}
1140
1141/// The BLAKE3 hash of what a file holds, read from where it is to its end.
1142fn hash_of(file: &mut File) -> io::Result<Hash> {
1143	let mut hasher = nibkeep_base::Hasher::new();
1144	let mut buffer = vec![0; 1 << 20];
1145	loop {
1146		let read = file.read(&mut buffer)?;
1147		if read == 0 {
1148			return Ok(hasher.finalize());
1149		}
1150		hasher.update(buffer.get(..read).unwrap_or_default());
1151	}
1152}
1153
1154/// Saves a folder's entries to the disk, where the system allows it.
1155fn sync_folder(folder: &Path) {
1156	#[cfg(unix)]
1157	let _ = File::open(folder).and_then(|folder| folder.sync_all());
1158	#[cfg(not(unix))]
1159	let _ = folder;
1160}
1161
1162/// Bytes in lowercase hexadecimal.
1163fn hex(bytes: &[u8]) -> String {
1164	use std::fmt::Write as _;
1165	bytes.iter().fold(String::new(), |mut text, byte| {
1166		let _ = write!(text, "{byte:02x}");
1167		text
1168	})
1169}
1170
1171#[cfg(test)]
1172mod tests {
1173	use super::*;
1174
1175	#[test]
1176	fn the_mount_table_gives_the_mounts_that_hold_files() {
1177		assert_eq!(
1178			mount_of_line("36 25 8:2 / /run/media/ada/STICK rw,nosuid - exfat /dev/sdb1 rw"),
1179			Some(PathBuf::from("/run/media/ada/STICK"))
1180		);
1181		assert_eq!(
1182			mount_of_line("22 1 0:21 / /proc rw,nosuid shared:5 - proc proc rw"),
1183			None
1184		);
1185		assert_eq!(
1186			mount_of_line("40 1 0:40 / /mnt/nas rw - autofs systemd-1 rw"),
1187			None
1188		);
1189	}
1190
1191	#[test]
1192	fn a_mount_point_reads_with_its_escapes() {
1193		assert_eq!(
1194			unescape_mount("/run/media/ada/My\\040Stick"),
1195			"/run/media/ada/My Stick"
1196		);
1197		assert_eq!(unescape_mount("/plain"), "/plain");
1198	}
1199
1200	#[test]
1201	fn a_record_reads_back_and_a_damaged_one_reads_as_none() {
1202		let mut record = Record {
1203			update: 4,
1204			checks: [(Hash::of(b"a"), 7), (Hash::of(b"b"), 0)].into(),
1205			damaged: [(Hash::of(b"c"), 9)].into(),
1206			waits: Vec::new(),
1207			purges: BTreeMap::new(),
1208		};
1209		// One without waits, as backups' records were before they waited, reads as none.
1210		let older = cbor::encode(&Value::Array(vec![
1211			VERSION.to_cbor(),
1212			4_u64.to_cbor(),
1213			Value::Array(vec![
1214				Value::Array(vec![Hash::of(b"a").to_cbor(), 7_u64.to_cbor()]),
1215				Value::Array(vec![Hash::of(b"b").to_cbor(), 0_u64.to_cbor()]),
1216			]),
1217			Value::Array(vec![Value::Array(vec![
1218				Hash::of(b"c").to_cbor(),
1219				9_u64.to_cbor(),
1220			])]),
1221		]));
1222		assert_eq!(Record::from_bytes(&older), None);
1223		assert_eq!(Record::from_bytes(&record.to_bytes()), Some(record.clone()));
1224		record.waits = vec![(5, 30 * 86_400_000)];
1225		record.purges = [(ChangeId::from_hash(Hash::of(b"a purge")), (6, 3))].into();
1226		assert_eq!(Record::from_bytes(&record.to_bytes()), Some(record));
1227		assert_eq!(Record::from_bytes(b"\x80"), None);
1228	}
1229}