1use 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
19pub(crate) const BACKUP_FILE: &str = "backup.cbor";
21
22const RECORD: &str = "record.cbor";
24
25const README: &str = "README.txt";
27
28const SPACES: &str = "spaces";
31const BLOBS: &str = "blobs";
32const DAMAGED: &str = "damaged";
33const TMP: &str = "tmp";
34
35const LOCK: &str = "lock";
37const IN_USE: &str = "in-use";
38
39const REPLACED: [&str; 2] = [RECORD, RECOVERY_FILE];
43
44const PACK: &str = "pack";
46
47const VERSION: u64 = 1;
49
50const 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
62pub trait BackupFolder: Send + Sync {
70 fn shown(&self, path: &str) -> PathBuf;
72
73 fn list(&self, folder: &str) -> io::Result<Vec<(String, Option<u64>)>>;
80
81 fn open(&self, file: &str) -> io::Result<File>;
87
88 fn create(&self, file: &str) -> io::Result<File>;
94
95 fn open_lock(&self, file: &str) -> io::Result<File>;
101
102 fn put(&self, file: &str, folder: &str) -> io::Result<()>;
110
111 fn remove(&self, file: &str) -> io::Result<()>;
117
118 fn exists(&self, file: &str) -> bool {
120 self.open(file).is_ok()
121 }
122
123 fn sync_folder(&self, _folder: &str) {}
125
126 fn free(&self) -> io::Result<u64>;
132
133 fn drive(&self) -> BackupDrive;
135
136 fn unjournaled(&self) -> bool {
139 self.drive().unjournaled
140 }
141}
142
143#[derive(Clone, Debug, Default, PartialEq, Eq)]
145pub struct BackupDrive {
146 pub path: Option<String>,
149 pub disk: Option<Vec<u8>>,
153 pub remote: bool,
155 pub unjournaled: bool,
158}
159
160pub(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 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 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#[doc(hidden)]
273pub struct PickerRules {
274 root: PathBuf,
275 drive: BackupDrive,
276 moves: Mutex<Vec<(String, String)>>,
278}
279
280impl PickerRules {
281 #[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 #[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 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 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
374fn joined(folder: &str, name: &str) -> String {
376 if folder.is_empty() {
377 name.to_owned()
378 } else {
379 format!("{folder}/{name}")
380 }
381}
382
383fn parent_of(path: &str) -> &str {
385 path.rsplit_once('/').map_or("", |(parent, _)| parent)
386}
387
388#[derive(Clone, Debug, Default, PartialEq, Eq)]
390pub(crate) struct Record {
391 pub(crate) update: u64,
393 pub(crate) checks: BTreeMap<Hash, u64>,
396 pub(crate) damaged: BTreeMap<Hash, u64>,
398 pub(crate) waits: Vec<(u64, u64)>,
403 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
506fn 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#[must_use]
515pub fn named_at(folder: &Path) -> Option<EntityId> {
516 named_in(&InFileSystem::new(folder))
517}
518
519#[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
541pub(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
575pub(crate) fn unmake(files: &dyn BackupFolder) {
577 for name in [README, BACKUP_FILE] {
578 let _ = files.remove(name);
579 }
580}
581
582pub(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
590pub(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
632pub(crate) fn marked_in_use(files: &dyn BackupFolder) -> bool {
636 files.exists(IN_USE)
637}
638
639pub(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
648pub(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
659pub(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#[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#[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
761static SLOW: Mutex<BTreeMap<PathBuf, Instant>> = Mutex::new(BTreeMap::new());
764
765const SLOW_FOR: Duration = Duration::from_mins(10);
767
768pub(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
822pub(crate) struct Updating<'a> {
825 files: &'a dyn BackupFolder,
826 _lock: File,
827 pub(crate) unclean: bool,
830 pub(crate) unjournaled: bool,
832}
833
834impl<'a> Updating<'a> {
835 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 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 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 pub(crate) fn shown(&self, path: &str) -> PathBuf {
903 self.files.shown(path)
904 }
905
906 pub(crate) fn record(&self) -> Record {
908 read_record(self.files)
909 }
910
911 pub(crate) fn recovery(&self) -> Option<RecoveryFile> {
914 RecoveryFile::from_bytes(&read_all(self.files, RECOVERY_FILE).ok()?)
915 }
916
917 pub(crate) fn save_recovery(&self, bytes: &[u8]) -> Result<(), NodeError> {
923 self.write_whole(RECOVERY_FILE, &mut &*bytes, None)
924 .map(|_| ())
925 }
926
927 pub(crate) fn delete_recovery(&self) -> Result<(), NodeError> {
933 self.delete(RECOVERY_FILE)
934 }
935
936 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 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 pub(crate) fn blob_files(&self) -> Result<BTreeMap<Hash, u64>, NodeError> {
992 blob_files_in(self.files)
993 }
994
995 pub(crate) fn pack_path(space: SpaceId, hash: &Hash) -> String {
997 format!("{SPACES}/{space}/{}.{PACK}", hex(hash.digest()))
998 }
999
1000 pub(crate) fn read(&self, file: &str) -> io::Result<Vec<u8>> {
1002 read_all(self.files, file)
1003 }
1004
1005 pub(crate) fn open(&self, file: &str) -> io::Result<File> {
1007 self.files.open(file)
1008 }
1009
1010 pub(crate) fn hash(&self, file: &str) -> io::Result<Hash> {
1012 hash_of(&mut self.files.open(file)?)
1013 }
1014
1015 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 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 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 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 pub(crate) fn free(&self) -> Result<u64, NodeError> {
1062 self.files.free().map_err(NodeError::file(&self.shown("")))
1063 }
1064
1065 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 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 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 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 fn drop(&mut self) {
1135 if self.files.remove(IN_USE).is_ok() {
1136 self.files.sync_folder("");
1137 }
1138 }
1139}
1140
1141fn 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
1154fn 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
1162fn 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 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}