From 6a8dc6c88b03bba64956a6a7f4d009675ad7c7ec Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 19:10:34 -0700 Subject: [PATCH] fix(store): a backup is proven after it is written and repaired when a piece is damaged; a drill passes only on the newest backup A backup that restores old or wrong books while reporting good is the worst defect the product can have. A piece already in the destination was taken as the piece (its name is its hash), the manifest built on the newest backup whose pieces were the right length, no proof ran after a backup, and the drill fell back to older manifests and recorded ok with the older head. - the manifest just written is read back and proven before the backup is recorded good: every journal and access segment re-hashed, the chain replayed to its head, vault and keys present, the index, and the stored files this backup added plus a rotating sixteenth of the others (every stored file is re-read within 16 manifest numbers; the drill re-hashes all) - a piece found damaged is written again under a generation suffix beside the damaged file (never touched), a new manifest names it, and the reader accepts any generation of a piece whose contents hash right - the drill passes only on the newest manifest, and only when it reaches the head of the last backup recorded good; an older whole backup is a failure that says so with its date - no consolidation: a manifest names the one before it and only what is new (a chain of 64, each link proven by the hash its successor holds) - restore and drill read newest first and stop at the first that proves - live books that are the beginning of the destination's longer history are ahead; any other mismatch is diverged or other books - a new set can begin beside the old (.2), never touching it; set folders carry a fixed prefix so no book id is a reserved name on Windows - no hard link is never a reason to replace: only errors that mean the disk makes no links fall back, to a move that refuses to replace - sealed pieces are sharded by two digits; header settings are capped at 4x and bound into the sealed check; find derives one key per distinct setting - vault scratch files are never backed up as records - files a sync service has not downloaded read as not downloaded yet Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/backups.rs | 43 +- crates/ledger-cli/tests/open_while_held.rs | 10 +- crates/ledger-mcp/src/backup.rs | 287 ++++++- crates/ledger-mcp/src/local.rs | 2 + crates/ledger-store/src/backup/cut.rs | 58 +- crates/ledger-store/src/backup/form.rs | 109 ++- crates/ledger-store/src/backup/io.rs | 304 +++++-- crates/ledger-store/src/backup/mod.rs | 75 +- crates/ledger-store/src/backup/read.rs | 886 +++++++++++++++++---- crates/ledger-store/src/backup/seal.rs | 64 +- crates/ledger-store/src/backup/single.rs | 2 +- crates/ledger-store/src/backup/write.rs | 671 +++++++++++++--- crates/ledger-store/tests/backup.rs | 40 +- crates/ledger-store/tests/backup_props.rs | 4 +- 14 files changed, 2116 insertions(+), 439 deletions(-) diff --git a/crates/ledger-cli/tests/backups.rs b/crates/ledger-cli/tests/backups.rs index 8604852d..764db552 100644 --- a/crates/ledger-cli/tests/backups.rs +++ b/crates/ledger-cli/tests/backups.rs @@ -408,7 +408,12 @@ async fn a_book_backs_itself_up_to_its_folder_soon_after_a_write() { let live = live_head(&home, "acme"); assert_eq!(s["head_seq"].as_u64(), Some(live.0)); assert_eq!(proven(&home, &folder, "folder"), live); - assert!(folder.join("acme").join("READ-ME.txt").is_file()); + assert!( + folder + .join("wanderbooks-acme") + .join("READ-ME.txt") + .is_file() + ); // Its journal is the live journal's beginning (a drill's check). let scratch = home.outside("scratch-prefix"); let found = find(&folder, None, &Ctx::new()).unwrap(); @@ -651,21 +656,24 @@ async fn restore_beside_existing_books_and_on_a_clean_install() { assert_eq!(figures(©).await, want); // Its own backups carry on in the same folder, under its own name; the // original's stay as they were. - let orig = proven(&home, &folder.join("acme"), "orig-before"); + let orig = proven(&home, &folder.join("wanderbooks-acme"), "orig-before"); let s = call(©, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); assert_eq!( - proven(&home, &folder.join("acme-copy"), "copy"), + proven(&home, &folder.join("wanderbooks-acme-copy"), "copy"), live_head(&home, "acme-copy") ); - assert_eq!(proven(&home, &folder.join("acme"), "orig-after"), orig); + assert_eq!( + proven(&home, &folder.join("wanderbooks-acme"), "orig-after"), + orig + ); drop(copy); assert!(server.close().success()); // restore_on_clean_install: another computer's root, nothing in it. let other = Home::new("clean"); let server = Server::start(&other, Duration::from_secs(3600)); assert_eq!(books_held(&other), Vec::::new()); - let r = restore(&other, "acme", &folder.join("acme"), false).unwrap(); + let r = restore(&other, "acme", &folder.join("wanderbooks-acme"), false).unwrap(); assert_eq!(r.head, live_head(&home, "acme")); let c = connect(&other, "acme", other.token("acme", &["read"])).await; assert_eq!(figures(&c).await, want); @@ -775,7 +783,7 @@ async fn restore_refuses_a_damaged_backup_and_writes_nothing() { ]; for (tag, spoil) in damage { let copy = home.outside(&format!("bad-{tag}")); - copy_dir(&folder.join("acme"), ©); + copy_dir(&folder.join("wanderbooks-acme"), ©); spoil(©); let why = restore(&home, "acme-bad", ©, false).unwrap_err(); assert!(why.contains("can't be restored"), "{tag}: {why}"); @@ -851,7 +859,7 @@ async fn restore_drill_failure_is_flagged() { let (folder, _) = backed_up_acme(&home).await; assert!(server.close().success()); // The backup is changed behind the books' back. - let j = &files_below(&folder.join("acme"), "journal/")[0]; + let j = &files_below(&folder.join("wanderbooks-acme"), "journal/")[0]; let mut b = std::fs::read(j).unwrap(); let mid = b.len() / 2; b[mid] ^= 1; @@ -1017,7 +1025,7 @@ async fn a_restore_brings_the_vault_and_its_key() { let server = Server::start(&third, Duration::from_secs(3600)); for gone in ["keys/", "vault/"] { let copy = home.outside(&format!("no-{}", gone.trim_end_matches('/'))); - copy_dir(&folder.join("acme"), ©); + copy_dir(&folder.join("wanderbooks-acme"), ©); for f in files_below(©, gone) { std::fs::remove_file(f).unwrap(); } @@ -1036,7 +1044,7 @@ async fn a_replacing_restore_that_fails_leaves_the_books_open() { let (folder, want) = backed_up_acme(&home).await; let before = live_head(&home, "acme"); let bad = home.outside("bad"); - copy_dir(&folder.join("acme"), &bad); + copy_dir(&folder.join("wanderbooks-acme"), &bad); let j = &files_below(&bad, "journal/")[0]; let mut b = std::fs::read(j).unwrap(); let mid = b.len() / 2; @@ -1095,7 +1103,7 @@ async fn restored_books_never_make_their_backup_folder_again() { // there, empty): restored from a copy of the backup. let copy = home.outside("copy-of-disk"); copy_dir(&folder, ©); - std::fs::rename(folder.join("acme"), home.outside("unmounted")).unwrap(); + std::fs::rename(folder.join("wanderbooks-acme"), home.outside("unmounted")).unwrap(); let other = Home::new("restore-mount-new"); let server = Server::start(&other, Duration::from_secs(3600)); restore(&other, "acme", ©, false).unwrap(); @@ -1108,13 +1116,16 @@ async fn restored_books_never_make_their_backup_folder_again() { .contains("holds no backup"), "{s}" ); - assert!(!folder.join("acme").exists(), "made on the wrong disk"); + assert!( + !folder.join("wanderbooks-acme").exists(), + "made on the wrong disk" + ); // The human says it's a new disk: begun there again. let s = call(&c, "books.back_up_now", json!({"new_disk": true})) .await .unwrap(); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); - assert!(folder.join("acme").join("manifests").is_dir()); + assert!(folder.join("wanderbooks-acme").join("manifests").is_dir()); drop(c); assert!(server.close().success()); } @@ -1147,7 +1158,7 @@ async fn a_damaged_backup_record_never_keeps_the_books_shut() { assert!(server.close().success()); // What it knew of whose backups the folder holds was kept: gone, the // folder's backup is a disk not connected, never made again. - std::fs::rename(folder.join("acme"), home.outside("away")).unwrap(); + std::fs::rename(folder.join("wanderbooks-acme"), home.outside("away")).unwrap(); let server = Server::start(&home, Duration::from_secs(3600)); let c = connect(&home, "acme", home.token("acme", &["read", "admin"])).await; let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); @@ -1158,7 +1169,7 @@ async fn a_damaged_backup_record_never_keeps_the_books_shut() { .contains("holds no backup"), "{s}" ); - assert!(!folder.join("acme").exists()); + assert!(!folder.join("wanderbooks-acme").exists()); drop(c); assert!(server.close().success()); } @@ -1232,7 +1243,7 @@ async fn old_settings_and_an_old_backup_history_are_left_alone_and_said() { let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); assert_eq!(std::fs::read(old.join("HEAD")).unwrap(), before); - assert!(folder.join("acme").join("manifests").is_dir()); + assert!(folder.join("wanderbooks-acme").join("manifests").is_dir()); drop(c); assert!(server.close().success()); } @@ -1493,7 +1504,7 @@ async fn a_passphrase_seals_the_backups_and_a_restore_asks_for_it() { let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); assert_eq!(s["targets"][0]["sealed"], false, "{s}"); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); - assert!(folder.join("acme").join("manifests").is_dir()); + assert!(folder.join("wanderbooks-acme").join("manifests").is_dir()); let bytes_after: Vec> = sealed_before .iter() .map(|p| std::fs::read(p).unwrap()) diff --git a/crates/ledger-cli/tests/open_while_held.rs b/crates/ledger-cli/tests/open_while_held.rs index 1190d15f..1403be71 100644 --- a/crates/ledger-cli/tests/open_while_held.rs +++ b/crates/ledger-cli/tests/open_while_held.rs @@ -2697,7 +2697,7 @@ fn a_backup_is_restored_from_the_command_line() { ); assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); let head = s["head_seq"].as_u64().unwrap(); - let backup = disk.join("acme"); + let backup = disk.join("wanderbooks-acme"); let backup = backup.to_str().unwrap(); // Previewed, and not done without a yes. let out = home.books(&["restore", backup, "--id", "copy"]); @@ -2717,7 +2717,7 @@ fn a_backup_is_restored_from_the_command_line() { // A folder named otherwise: restored as the books it holds, by default // (here: over those, refused), said. let renamed = home.dir.path().join("fernhill-backup"); - copy_folder(&disk.join("acme"), &renamed); + copy_folder(&disk.join("wanderbooks-acme"), &renamed); let out = home.books(&["restore", renamed.to_str().unwrap(), "--yes"]); assert!( String::from_utf8_lossy(&out.stderr).contains("already books called \"acme\""), @@ -2925,9 +2925,9 @@ fn books_are_backed_up_now_from_the_command_line() { String::from_utf8_lossy(&out.stdout).contains("Backed up to the backup folder"), "{out:?}" ); - assert!(disk.join("acme").join("manifests").is_dir()); + assert!(disk.join("wanderbooks-acme").join("manifests").is_dir()); // A folder gone since: said, and --new-disk begins it again. - std::fs::rename(disk.join("acme"), home.dir.path().join("away")).unwrap(); + std::fs::rename(disk.join("wanderbooks-acme"), home.dir.path().join("away")).unwrap(); let out = home.books(&["back-up", "acme"]); assert_eq!(out.status.code(), Some(1), "{out:?}"); assert!( @@ -2936,7 +2936,7 @@ fn books_are_backed_up_now_from_the_command_line() { ); let out = home.books(&["back-up", "acme", "--new-disk"]); assert!(out.status.success(), "{out:?}"); - assert!(disk.join("acme").join("manifests").is_dir()); + assert!(disk.join("wanderbooks-acme").join("manifests").is_dir()); a.end(); } diff --git a/crates/ledger-mcp/src/backup.rs b/crates/ledger-mcp/src/backup.rs index bfcf49de..57e83431 100644 --- a/crates/ledger-mcp/src/backup.rs +++ b/crates/ledger-mcp/src/backup.rs @@ -138,6 +138,8 @@ pub const DRILL_EVERY: chrono::Duration = chrono::Duration::days(7); pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(15 * 60); /// The most of an error kept. const ERROR_MAX: usize = 500; +/// The most damaged files a record names. +const REPAIRED_MAX: usize = 20; /// The test knob that holds a stoppable call as it begins ([`Backups::set_hold`]). type CallHold = Arc; @@ -266,6 +268,13 @@ pub struct TargetStatus { pub sealed: bool, /// Its disk isn't connected (its last try found no folder). pub disconnected: bool, + /// What kind of trouble its last backup or drill had (`ahead`, + /// `elsewhere`, `key_missing`, `not_downloaded`, `newest_damaged`, + /// `no_folder`, `other`), for the window to say what to do. + pub error_kind: Option, + /// Files in the backup folder that were found damaged and written again + /// (each is left where it is: nothing in it is deleted). + pub damaged_files: Vec, } /// The books' backup standing. @@ -282,8 +291,9 @@ pub struct Status { /// A destination the settings name. #[derive(Debug, Clone)] struct Named { - /// Where, and sealed or not; Err when its key can't be read. - dest: Result, + /// Where, and sealed or not; Err when its key can't be read, or the + /// backups are sealed and this computer has lost the key (INVARIANT 11). + dest: Result, /// Where, as an agent is told it. at: String, /// The destination itself, as its records name it (INVARIANT 2): a @@ -302,31 +312,81 @@ pub const OLD_REMOTE: &str = "These books' settings still name a private reposit /// What books that still carry an old backup history are told. pub const OLD_ARCHIVE: &str = "An older backup folder from an earlier version is still in the books' folder. It is no longer written or read, and nothing was deleted: you may delete it yourself once the new backup is whole."; +/// What the record says of whether the backups are sealed: the newest +/// record that says (a set-up that chose a passphrase or took it off, a +/// push that was made sealed or plain), with the key's fingerprint, which +/// opens nothing. +fn sealed_before(records: &[Map]) -> Option<(bool, Option)> { + records.iter().rev().find_map(|r| { + if is(r, "setup") { + match r.get("passphrase").and_then(Value::as_str) { + Some("set") => Some((true, text(r, "fp"))), + Some("removed") => Some((false, None)), + _ => None, + } + } else if is(r, "push") { + r.get("sealed") + .and_then(Value::as_bool) + .map(|sealed| (sealed, text(r, "fp"))) + } else { + None + } + }) +} + +/// The records of a book's backup log, if it can be read. +fn read_records(dir: &Path) -> Vec> { + ledger_store::chain::read(&ledger_store::ops::ops_dir(dir).join(LOG_FILE), GENESIS) + .map(|r| r.records) + .unwrap_or_default() +} + /// The destination the book's settings name (D-91). fn targets(store: &ledger_store::Store, book: &str, dir: &Path) -> Vec { use sha2::{Digest, Sha256}; let Some(folder) = store.ledger().settings().backup_folder() else { return Vec::new(); }; - let loaded = BackupKey::load(dir); - let (key, sealed, fp) = match &loaded { - Ok(Some(k)) => (Ok(Some(k.clone())), true, k.fingerprint()), - Ok(None) => (Ok(None), false, String::new()), - Err(e) => (Err(e.to_string()), true, "unreadable".to_string()), + let digest = |fp: &str| -> String { + Sha256::digest(format!("{folder}\0{book}\0{fp}").as_bytes())[..8] + .iter() + .map(|b| format!("{b:02x}")) + .collect() }; - let digest: String = Sha256::digest(format!("{folder}\0{book}\0{fp}").as_bytes())[..8] - .iter() - .map(|b| format!("{b:02x}")) - .collect(); - vec![Named { - dest: key.map(|key| Destination { - folder: PathBuf::from(folder), - key, - }), - at: "the backup folder".to_string(), - key: digest, + let at = "the backup folder".to_string(); + let named = |dest: Result, sealed: bool, fp: &str| Named { + dest, + at: at.clone(), + key: digest(fp), sealed, - }] + }; + let dest = |key: Option| Destination { + folder: PathBuf::from(folder), + key, + }; + let one = match BackupKey::load(dir) { + Ok(Some(k)) => { + let fp = k.fingerprint(); + named(Ok(dest(Some(k))), true, &fp) + } + Err(e) => named(Err(e), true, "unreadable"), + // No key file. Plain, unless the backups were sealed and the file is + // what was lost (INVARIANT 11): the record says what was chosen + // last, and where it has nothing, the folder itself does. + Ok(None) => match sealed_before(&read_records(dir)) { + Some((true, fp)) => named( + Err(BackupError::KeyMissing), + true, + fp.as_deref().unwrap_or(""), + ), + Some((false, _)) => named(Ok(dest(None)), false, ""), + None if ledger_store::backup::holds_only_sealed(Path::new(folder), book) => { + named(Err(BackupError::KeyMissing), true, "") + } + None => named(Ok(dest(None)), false, ""), + }, + }; + vec![one] } /// What an error of a write is, for the record: tells a disk not connected. @@ -334,7 +394,11 @@ fn error_kind(e: &BackupError) -> &'static str { match e { BackupError::NoFolder => "no_folder", BackupError::NoBackupThere => "no_backup_there", - BackupError::Elsewhere | BackupError::Ahead(..) => "elsewhere", + BackupError::Elsewhere => "elsewhere", + BackupError::Ahead(..) => "ahead", + BackupError::KeyMissing | BackupError::NeedsPassphrase => "key_missing", + BackupError::NotDownloaded => "not_downloaded", + BackupError::NewestDamaged { .. } => "newest_damaged", _ => "other", } } @@ -606,6 +670,19 @@ impl Backups { /// books' backups and holds none now is begun again there (the owner /// says it is a new disk). pub async fn run_with(&self, why: &str, new_disk: bool) -> Result { + self.run_with_set(why, new_disk, false).await + } + + /// [`Self::run_with`]; with `new_set`, a destination that holds a + /// longer history of these books than they have now (as after a restore + /// from an older backup) gets a new backup set beside the old one, + /// which is never touched: only at the person's explicit request. + pub async fn run_with_set( + &self, + why: &str, + new_disk: bool, + new_set: bool, + ) -> Result { let _one = self.running.lock().await; // Books let go of (closed, or replaced by a restore) write nothing // more, and leave no record of a run that never began. @@ -664,11 +741,13 @@ impl Backups { Err(e) => { self.record( json!({"kind": "push", "why": why, "target": "folder", "at": n.at, - "key": n.key, "ok": false, "error": e, "error_kind": "other"}), + "key": n.key, "ok": false, "error": e.to_string(), + "error_kind": error_kind(e), "sealed": n.sealed}), ); continue; } }; + let fp = dest.key.as_ref().map(BackupKey::fingerprint); // Its folder is begun only where it never took a backup. let may_create = new_disk || !held_before(&n.key, &records); let step = self.begin()?; @@ -676,7 +755,15 @@ impl Backups { let cut = cut.clone(); let written = tokio::task::spawn_blocking(move || { let _step = step; - backup::write_destination(&dest, &cut, may_create, &ctx) + backup::write_destination_with( + &dest, + &cut, + backup::Options { + may_create, + new_set, + }, + &ctx, + ) }) .await .unwrap_or(Err(BackupError::Damaged("the backup stopped".into()))); @@ -684,6 +771,8 @@ impl Backups { Ok(w) => self.record( json!({"kind": "push", "why": why, "target": "folder", "at": n.at, "key": n.key, "ok": true, "number": w.number, "new": w.new, + "sealed": n.sealed, "fp": fp, "files_proven": w.files_proven, + "repaired": w.repaired.iter().take(REPAIRED_MAX).collect::>(), "head": {"seq": head.0, "hash": head.1}}), ), // Stopped by a close: not a failure of the destination, and @@ -696,7 +785,7 @@ impl Backups { Err(e) => self.record( json!({"kind": "push", "why": why, "target": "folder", "at": n.at, "key": n.key, "ok": false, "error": e.to_string(), - "error_kind": error_kind(&e)}), + "error_kind": error_kind(&e), "sealed": n.sealed, "fp": fp}), ), } } @@ -876,6 +965,8 @@ impl Backups { }; let ctx = self.hurried_ctx(); let (dir, book) = (self.dir.clone(), self.book.clone()); + // The newest backup must reach what was last recorded good. + let expect = last_good_head(&n.key, &records); let drilled = tokio::task::spawn_blocking(move || { let _step = step; let scratch = ledger_store::ops::ops_dir(&dir).join("drill-folder"); @@ -885,6 +976,7 @@ impl Backups { &book, &dir.join(ledger_store::JOURNAL_FILE), &scratch, + expect.as_ref(), &ctx, ) }) @@ -900,7 +992,8 @@ impl Backups { "at": n.at, "key": n.key, "ok": true, "head": {"seq": head.0, "hash": head.1}})) } Err(e) => self.record(json!({"kind": "drill", "target": "folder", - "at": n.at, "key": n.key, "ok": false, "error": e.to_string()})), + "at": n.at, "key": n.key, "ok": false, "error": e.to_string(), + "error_kind": error_kind(&e)})), } } } @@ -933,6 +1026,9 @@ pub struct Standing { pub folder: Option, /// Protected by a passphrase now. pub sealed: bool, + /// What a person is told of the folder when a sync service keeps it + /// (or may): None when no folder is chosen. + pub sync: Option, } impl Backups { @@ -942,10 +1038,16 @@ impl Backups { let (book, dir) = (self.book.clone(), self.dir.clone()); let found = tokio::task::spawn_blocking(move || { store - .with_store(|s| Standing { - status: standing(s, &book, &dir), - folder: s.ledger().settings().backup_folder().map(str::to_string), - sealed: matches!(BackupKey::load(&dir), Ok(Some(_))), + .with_store(|s| { + let folder = s.ledger().settings().backup_folder().map(str::to_string); + Standing { + status: standing(s, &book, &dir), + sync: folder + .as_deref() + .map(|f| sync_words(sync_service(Path::new(f)))), + folder, + sealed: matches!(BackupKey::load(&dir), Ok(Some(_))), + } }) .ok() }) @@ -956,6 +1058,7 @@ impl Backups { status: standing_of(&[], &[], 0, chrono::Utc::now(), None), folder: None, sealed: false, + sync: None, }) } @@ -978,7 +1081,7 @@ impl Backups { } let step = self.begin()?; let (store, dir) = (self.store.clone(), self.dir.clone()); - let done = tokio::task::spawn_blocking(move || -> Result, String> { + let done = tokio::task::spawn_blocking(move || -> Result { let _step = step; let mut lines = Vec::new(); if let Some(folder) = folder.filter(|f| !f.trim().is_empty()) { @@ -1014,29 +1117,44 @@ impl Backups { } else { "The backup folder is chosen: the books back themselves up there a little after each change, when they open and before they close.".to_string() }); + lines.push(sync_words(sync_service(&path))); } if remove_passphrase && passphrase.is_some() { return Err("choose a passphrase or remove it, not both".into()); } + let mut chose: Option<(&str, Option)> = None; if let Some(p) = passphrase { let key = BackupKey::generate(&p).map_err(|e| e.to_string())?; key.store(&dir).map_err(|e| hide(&e.to_string(), &dir))?; + chose = Some(("set", Some(key.fingerprint()))); lines.push("Backups are now protected by the passphrase: from the next backup on, every file in the backup folder is sealed. Backups made before stay as they were, unprotected, and are never deleted: delete their folder yourself if you want them gone. A forgotten passphrase cannot be recovered by anyone.".to_string()); } else if remove_passphrase { BackupKey::forget(&dir).map_err(|e| hide(&e.to_string(), &dir))?; + chose = Some(("removed", None)); lines.push("The passphrase is taken off: from the next backup on, files are written without protection. Backups sealed before stay sealed with the passphrase they were made with.".to_string()); } if lines.is_empty() { lines.push("Nothing was changed.".to_string()); } - Ok(lines) + Ok((lines, chose.map(|(c, fp)| (c.to_string(), fp)))) }) .await .unwrap_or_else(|_| Err("the set-up stopped".into())); - if let Ok(lines) = &done { - self.record(json!({"kind": "setup", "lines": lines.len()})); + match done { + Ok((lines, chose)) => { + // What was chosen about the passphrase is kept in the + // record, so that a key file lost later is told from a + // passphrase taken off (INVARIANT 11). + let mut rec = json!({"kind": "setup", "lines": lines.len()}); + if let Some((choice, fp)) = chose { + rec["passphrase"] = json!(choice); + rec["fp"] = json!(fp); + } + self.record(rec); + Ok(lines) + } + Err(e) => Err(e), } - done } /// Save a backup as one file at `path` ("Save a backup..."): the same @@ -1107,6 +1225,60 @@ impl Backups { } } +/// What a person is told about a backup folder a sync service keeps (set +/// up, and in the window), `service` being its name when the path tells. +pub fn sync_words(service: Option<&str>) -> String { + let whose = match service { + Some(name) => format!("This folder is kept in sync by {name}."), + None => "If this folder is kept in sync by a service (Dropbox, iCloud Drive, OneDrive, Google Drive or another):".to_string(), + }; + format!( + "{whose} Use it from one computer only: two computers backing up into one synced folder can overwrite each other's work, and a second computer needs a folder of its own. Keep it available offline (not online only), so every file is on this computer when a backup is made or checked: a file that is online only reads as \"not downloaded yet\", and the backup waits." + ) +} + +/// The sync service whose folder `path` is inside, by the names of the +/// folders in it: reliable for the folders these services make for +/// themselves on each system (`Dropbox`, `OneDrive`, `iCloud Drive` and +/// `Library/Mobile Documents/com~apple~CloudDocs`, `Google Drive` and +/// `My Drive`, `Nextcloud`, `pCloud Drive`, `Box`), and silent about a +/// service's folder that was renamed or put somewhere else (then the +/// set-up says it in general words instead). +pub fn sync_service(path: &Path) -> Option<&'static str> { + path.components().find_map(|c| { + let name = c.as_os_str().to_str()?.to_lowercase(); + let has = |p: &str| { + name == p || name.starts_with(&format!("{p} ")) || name.starts_with(&format!("{p}-")) + }; + if has("dropbox") { + Some("Dropbox") + } else if has("onedrive") { + Some("OneDrive") + } else if matches!( + name.as_str(), + "icloud drive" | "iclouddrive" | "com~apple~clouddocs" | "mobile documents" + ) { + Some("iCloud Drive") + } else if matches!(name.as_str(), "google drive" | "googledrive" | "my drive") + || name.starts_with("googledrive-") + { + Some("Google Drive") + } else if has("nextcloud") || has("owncloud") { + Some("Nextcloud") + } else if has("pcloud") || name == "pcloud drive" { + Some("pCloud") + } else if name == "box" || name == "box sync" { + Some("Box") + } else { + None + } + }) +} + +/// What a set-up did, in words, and the choice it made about the +/// passphrase ("set" with the key's fingerprint, or "removed"). +type SetUpDone = (Vec, Option<(String, Option)>); + /// The old backup history's folder in a book's folder: left alone. const OLD_ARCHIVE_DIR: &str = "archive.git"; @@ -1164,10 +1336,12 @@ impl Status { /// act on, or one stale, failing, or failing its drill. pub fn needs_attention(&self) -> bool { self.note.is_some() - || self - .targets - .iter() - .any(|t| t.stale || t.last_error.is_some() || t.drill_error.is_some()) + || self.targets.iter().any(|t| { + t.stale + || t.last_error.is_some() + || t.drill_error.is_some() + || !t.damaged_files.is_empty() + }) } } @@ -1245,6 +1419,18 @@ fn text_field(r: &Map, field: &str) -> Option { r.get(field).and_then(Value::as_str).map(str::to_string) } +/// The head of the target `key`'s last backup recorded good. +fn last_good_head(key: &str, records: &[Map]) -> Option<(u64, String)> { + let r = records + .iter() + .rfind(|r| is(r, "push") && of(r, key) && ok(r))?; + let head = r.get("head")?; + Some(( + head.get("seq")?.as_u64()?, + head.get("hash")?.as_str()?.to_string(), + )) +} + /// Whether the target `key` took a backup of these books (INVARIANT 6). fn held_before(key: &str, records: &[Map]) -> bool { records.iter().any(|r| { @@ -1346,6 +1532,29 @@ fn status_of( .is_some_and(|r| { !ok(r) && r.get("error_kind").and_then(Value::as_str) == Some("no_folder") }); + let error_kind = { + let push = records.iter().rfind(|r| is(r, "push") && of(r, key)); + let from_push = push.filter(|r| !ok(r)).and_then(|r| text(r, "error_kind")); + let from_drill = drill.filter(|r| !ok(r)).and_then(|r| text(r, "error_kind")); + from_push.or(from_drill) + }; + let mut damaged_files: Vec = Vec::new(); + for r in records + .iter() + .filter(|r| is(r, "push") && of(r, key) && ok(r)) + { + for name in r + .get("repaired") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if !damaged_files.iter().any(|d| d == name) && damaged_files.len() < REPAIRED_MAX { + damaged_files.push(name.to_string()); + } + } + } TargetStatus { target: kind.to_string(), at: at.to_string(), @@ -1357,6 +1566,8 @@ fn status_of( drill_error: drill.filter(|r| !ok(r)).and_then(|r| text(r, "error")), sealed, disconnected, + error_kind, + damaged_files, } } @@ -1662,6 +1873,8 @@ mod tests { drill_error: None, sealed: false, disconnected: false, + error_kind: None, + damaged_files: Vec::new(), }; let status = |t: TargetStatus| Status { head_seq: 3, diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index ccbddf74..61e81b73 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -4567,6 +4567,8 @@ mod tests { drill_error: None, sealed: false, disconnected: false, + error_kind: None, + damaged_files: Vec::new(), }; let status = |targets| crate::backup::Status { head_seq: 5, diff --git a/crates/ledger-store/src/backup/cut.rs b/crates/ledger-store/src/backup/cut.rs index 4a1837e5..fa56fd17 100644 --- a/crates/ledger-store/src/backup/cut.rs +++ b/crates/ledger-store/src/backup/cut.rs @@ -75,14 +75,40 @@ fn whole_lines(path: &Path, len: u64) -> std::io::Result { Ok(0) } +/// What the exactly-once writes of the vault (ledger-vault `stage`, +/// `settle`) leave in its folder while a call is between its first step +/// and its last: a new record staged under `NAME.staged-TAG`, an old one +/// set aside under `NAME.purging-TAG`. +enum Scratch<'a> { + /// A record staged for a call that has not committed: not the books' + /// yet, and nothing the journal at the cut names. + Staged, + /// A record set aside for a purge that has not committed: still the + /// books' record as the journal at the cut stands, under the name it + /// has when it is not set aside (`own`). + Purging { own: &'a str }, +} + +fn scratch_of(name: &str) -> Option> { + if name.contains(".staged-") { + return Some(Scratch::Staged); + } + name.split_once(".purging-") + .map(|(stem, _)| Scratch::Purging { own: stem }) +} + /// The plain files of a flat folder of a book, by name, with their bytes. -fn flat_files(dir: &Path) -> Result)>, BackupError> { +/// With `vault`, the vault's scratch files are met as they are meant (see +/// [`Scratch`]): never backed up as records of their own, so a backup cut +/// while a write of the vault is under way holds the vault as the journal +/// at the cut says it is. +fn flat_files(dir: &Path, vault: bool) -> Result)>, BackupError> { let entries = match std::fs::read_dir(dir) { Ok(e) => e, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e.into()), }; - let mut out = Vec::new(); + let mut named: Vec<(String, PathBuf)> = Vec::new(); for entry in entries { let entry = entry?; let name = entry.file_name().to_string_lossy().into_owned(); @@ -92,7 +118,24 @@ fn flat_files(dir: &Path) -> Result)>, BackupError> { "a folder of the books holds something no book keeps ({name:?})" ))); } - out.push((name, std::fs::read(entry.path())?)); + named.push((name, entry.path())); + } + let held: std::collections::BTreeSet = named.iter().map(|(n, _)| n.clone()).collect(); + let mut out = Vec::new(); + for (name, path) in named { + let name = match vault.then(|| scratch_of(&name)).flatten() { + None => name, + Some(Scratch::Staged) => continue, + Some(Scratch::Purging { own }) => { + let own = format!("{own}.bin"); + if held.contains(&own) { + // The record was written anew: that one is the books'. + continue; + } + own + } + }; + out.push((name, std::fs::read(path)?)); } out.sort(); Ok(out) @@ -135,11 +178,16 @@ impl Cut { head, journal_len, access_len, - vault: flat_files(&dir.join(crate::root::VAULT_DIR))?, - keys: flat_files(&dir.join(crate::root::KEYS_DIR))?, + vault: flat_files(&dir.join(crate::root::VAULT_DIR), true)?, + keys: flat_files(&dir.join(crate::root::KEYS_DIR), false)?, }) } + /// The book's folder the cut was taken from. + pub(crate) fn dir(&self) -> &Path { + &self.dir + } + /// The books' id. pub fn book(&self) -> &str { &self.book diff --git a/crates/ledger-store/src/backup/form.rs b/crates/ledger-store/src/backup/form.rs index 7a4f2ce8..e36c19a9 100644 --- a/crates/ledger-store/src/backup/form.rs +++ b/crates/ledger-store/src/backup/form.rs @@ -15,6 +15,8 @@ use sha2::{Digest, Sha256}; pub(crate) const FORMAT: &str = "wanderbooks-backup"; /// The form's version. A reader refuses one it does not know. pub(crate) const VERSION: u32 = 1; +/// The folder name of a plain set begins with this. +pub(crate) const SET_PREFIX: &str = "wanderbooks-"; /// The folder of manifests in a set. pub(crate) const MANIFESTS: &str = "manifests"; /// The words a person can open. @@ -23,9 +25,11 @@ pub(crate) const READ_ME: &str = "READ-ME.txt"; pub(crate) const HEADER: &str = "header.json"; /// Where a sealed set keeps every piece, under names that say nothing. pub(crate) const PIECES: &str = "pieces"; -/// A series with this many segments is next written whole as one: a -/// manifest stays small however long the books have been backed up. -pub(crate) const CONSOLIDATE_AT: usize = 200; +/// A manifest names the one before it and only what is new, until a chain +/// of this many is made; then one names everything again. A reader walks +/// at most this many manifests (each proven by the hash its successor +/// holds) to know one manifest's whole. +pub(crate) const DELTA_CHAIN: u32 = 64; /// The kinds of piece. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -78,8 +82,31 @@ pub(crate) struct Series { pub bytes: u64, /// SHA-256 of all of them, one after another, hex. pub sha256: String, - /// The segments, in order. + /// The segments, in order. In a manifest that names the one before it + /// ([`Manifest::base`]), only those after the first `keep`. pub segments: Vec, + /// How many of its base's first segments this series begins with (a + /// manifest that names its base only). Always 0 once read whole. + #[serde(default, skip_serializing_if = "is_zero_usize")] + pub keep: usize, +} + +fn is_zero_usize(n: &usize) -> bool { + *n == 0 +} + +fn is_zero_u32(n: &u32) -> bool { + *n == 0 +} + +/// The manifest a delta manifest is built on: its number and what its +/// body hashes to, so a changed or swapped base is known. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct BaseRef { + /// Its number. + pub number: u64, + /// SHA-256 of its body (the text before its check line), hex. + pub sha256: String, } /// A file named by its place in a flat folder of a book (the vault, the @@ -131,6 +158,18 @@ pub(crate) struct Manifest { pub vault: Vec, /// The keys. pub keys: Vec, + /// The manifest this one is built on, when it names only what is new + /// in its series (the vault and keys are always named whole). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base: Option, + /// How many manifests are chained below this one (0 for one that names + /// everything). + #[serde(default, skip_serializing_if = "is_zero_u32")] + pub depth: u32, + /// What its body hashes to: set when it is read or written, never + /// part of it. + #[serde(skip)] + pub sha: String, } /// A line of the index of stored files. @@ -189,10 +228,15 @@ pub(crate) fn manifest_number(name: &str, sealed: bool) -> Option { /// Where a piece of `kind` whose contents hash to `sha` is kept, as the /// `ordinal`th of its series. Sealed sets keep every piece under a name -/// made from the key and the hash: it says nothing of what the piece is. +/// made from the key and the hash (it says nothing of what the piece is), +/// in a folder of its first two digits, so no folder grows past what a +/// small disk's file system allows. pub(crate) fn piece_path(keys: Option<&Keys>, kind: Kind, ordinal: usize, sha: &str) -> String { match keys { - Some(k) => format!("{PIECES}/{}", k.piece_name(kind.dir(), sha)), + Some(k) => { + let name = k.piece_name(kind.dir(), sha); + format!("{PIECES}/{}/{name}", &name[..2]) + } None => match kind { Kind::Journal | Kind::Access | Kind::Index => { format!("{}/{:06}-{}", kind.dir(), ordinal + 1, &sha[..16]) @@ -203,6 +247,53 @@ pub(crate) fn piece_path(keys: Option<&Keys>, kind: Kind, ordinal: usize, sha: & } } +/// The path of generation `g` of the piece kept at `base`: generation 0 +/// is `base` itself. A piece found damaged is written again under the next +/// generation, beside the damaged file, which is never touched. +pub(crate) fn generation_path(base: &str, g: u32) -> String { + if g == 0 { + base.to_string() + } else { + format!("{base}.g{g}") + } +} + +/// The path without its generation suffix, and the generation. +pub(crate) fn split_generation(path: &str) -> (&str, u32) { + if let Some((stem, g)) = path.rsplit_once(".g") + && !g.is_empty() + && g.bytes().all(|b| b.is_ascii_digit()) + && let Ok(n) = g.parse::() + && n > 0 + { + return (stem, n); + } + (path, 0) +} + +/// The folder a set of `book` is kept in, in a destination, when it is not +/// sealed: a fixed prefix and the id, so the name is legal on every +/// system whatever the id is (`con` and `nul` are not names on Windows, +/// `wanderbooks-con` is). A later set of the same books, begun beside the +/// first, ends `.2`, `.3`: no id holds a dot, so none is another book's. +pub(crate) fn plain_set_name(book: &str, number: u32) -> String { + if number <= 1 { + format!("{SET_PREFIX}{book}") + } else { + format!("{SET_PREFIX}{book}.{number}") + } +} + +/// The book and set number a plain set's folder name says, if it is one. +pub(crate) fn parse_plain_set_name(name: &str) -> Option<(&str, u32)> { + let rest = name.strip_prefix(SET_PREFIX)?; + let (book, number) = match rest.rsplit_once('.') { + Some((book, n)) => (book, n.parse::().ok().filter(|n| *n >= 2)?), + None => (rest, 1), + }; + (!book.is_empty()).then_some((book, number)) +} + /// A manifest as written: its JSON, a newline, and a line that is the /// SHA-256 of that JSON, so a short or changed one is known for what it is. pub(crate) fn encode_manifest(m: &Manifest) -> Vec { @@ -223,7 +314,8 @@ pub(crate) fn decode_manifest(bytes: &[u8]) -> Result { if check != sha_hex(body.as_bytes()) { return Err(bad()); } - let m: Manifest = serde_json::from_str(body).map_err(|_| bad())?; + let mut m: Manifest = serde_json::from_str(body).map_err(|_| bad())?; + m.sha = check.to_string(); if m.format != FORMAT { return Err(BackupError::Damaged( "that isn't a wanderbooks backup".into(), @@ -246,6 +338,9 @@ impl Manifest { for m in [&mut a, &mut b] { m.number = 0; m.written.clear(); + m.base = None; + m.depth = 0; + m.sha.clear(); } a == b } diff --git a/crates/ledger-store/src/backup/io.rs b/crates/ledger-store/src/backup/io.rs index a8213369..cab8a5b8 100644 --- a/crates/ledger-store/src/backup/io.rs +++ b/crates/ledger-store/src/backup/io.rs @@ -15,15 +15,25 @@ //! exFAT disks, some sync folders). A rename is not used for a manifest //! because on Windows a rename replaces what is at the new name, and on //! some network shares it does so without telling. -//! * Where hard links are refused, a *piece* (a file named by what is in -//! it) is moved into place by a rename when its name is free: two writers -//! racing for one piece write the same bytes, so whichever lands, the -//! piece is right. A *manifest* is created exclusively under its own name -//! (`create_new`) and written in place: a crash in the middle leaves a -//! short manifest, which no reader accepts (it carries its own check), -//! and its number is simply spent. +//! * Only an error that means "this disk makes no links" ([`link_unsupported`], +//! named per platform) sends a put down the no-link path. Any other +//! error is an error: it is never taken to mean that a rename, which +//! replaces what is at the new name on POSIX and on Windows, will do. +//! * Where links are refused, the finished scratch file is moved into +//! place by a move that *refuses to replace*: `renameat2` with +//! `RENAME_NOREPLACE` on Linux, `renamex_np` with `RENAME_EXCL` on macOS, +//! `MoveFileExW` without `MOVEFILE_REPLACE_EXISTING` on Windows +//! ([`rename_new`]). Where even that is not offered (a file system that +//! cannot say no), the last resort is exclusive create (`create_new`) +//! under the real name and a copy of the bytes in: nothing is replaced, +//! but a crash in the middle leaves a short file under the real name, +//! which the next proof finds (it re-hashes) and repairs by writing the +//! piece again under a new generation (write.rs); a short manifest is +//! accepted by no reader (it carries its own check), and its number is +//! spent. //! * A file that is there already is never touched: a piece is taken as -//! the piece (the next proof re-hashes it); a manifest number taken is +//! the piece (the proof after the backup re-hashes it, and a piece found +//! damaged is written again beside it); a manifest number taken is //! reported to the writer, which looks again and tries the next. //! //! The scratch names are the one thing this code removes from a @@ -122,6 +132,69 @@ impl DirSet { } p } + + /// Whether the sync service's stand-in for the file at `rel` is there + /// (`.name.icloud` beside where the file should be). + fn stand_in_for(&self, rel: &str) -> bool { + let path = self.path(rel); + match (path.parent(), path.file_name().and_then(|n| n.to_str())) { + (Some(dir), Some(name)) => dir.join(format!(".{name}.icloud")).exists(), + _ => false, + } + } + + /// The finished file at `tmp` given its real name `path` on a disk + /// that makes no links: by a move that refuses to replace, else by + /// exclusive create and copy. The scratch file is gone after. + fn place_without_links(&self, tmp: &Path, path: &Path) -> std::io::Result { + let moved = if self.ctx.refuses_noreplace() { + Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) + } else { + rename_new(tmp, path) + }; + match moved { + Ok(()) => Ok(Put::Created), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let _ = std::fs::remove_file(tmp); + Ok(Put::Existed) + } + Err(e) if e.kind() == std::io::ErrorKind::Unsupported => { + // The last resort: made exclusively under the real name, + // and the finished scratch file copied into it. + let mut file = match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + { + Ok(f) => f, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let _ = std::fs::remove_file(tmp); + return Ok(Put::Existed); + } + Err(e) => { + let _ = std::fs::remove_file(tmp); + return Err(e); + } + }; + let copied = (|| -> std::io::Result<()> { + let mut from = std::fs::File::open(tmp)?; + { + let mut w = std::io::BufWriter::with_capacity(1 << 16, &mut file); + std::io::copy(&mut from, &mut w)?; + w.flush()?; + } + file.sync_all() + })(); + let _ = std::fs::remove_file(tmp); + copied?; + Ok(Put::Created) + } + Err(e) => { + let _ = std::fs::remove_file(tmp); + Err(e) + } + } + } } /// A name for a scratch file: unique to this process and moment. @@ -135,6 +208,51 @@ fn scratch_name() -> String { ) } +/// Whether Windows file attributes say the file is a placeholder of an +/// online-only service (OneDrive, Dropbox Smart Sync, iCloud for Windows): +/// `FILE_ATTRIBUTE_OFFLINE` (0x1000), `FILE_ATTRIBUTE_RECALL_ON_OPEN` +/// (0x40000) or `FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS` (0x400000). Reading +/// one makes Windows fetch it, which may take long or fail with no +/// network, so it is reported as not downloaded, not read. +#[allow(dead_code)] // used where Windows attributes are read; tested everywhere +pub(crate) fn placeholder_attributes(attrs: u32) -> bool { + attrs & (0x1000 | 0x40000 | 0x400000) != 0 +} + +/// Whether macOS file flags say the file is dataless (an iCloud or file +/// provider stand-in whose contents are not on this disk): `SF_DATALESS`. +#[allow(dead_code)] // used where macOS flags are read; tested everywhere +pub(crate) fn dataless_flags(flags: u32) -> bool { + flags & 0x4000_0000 != 0 +} + +/// Whether the name is the stand-in a sync service leaves for a file it +/// has not downloaded (iCloud before macOS 14: `.name.icloud`). +pub(crate) fn is_stand_in_name(name: &str) -> bool { + name.len() > ".x.icloud".len() - 1 && name.starts_with('.') && name.ends_with(".icloud") +} + +/// Whether the file's metadata says it is online only. Where nothing can +/// tell (Linux, whatever the sync client), false: such a file reads as +/// what it is, and a short or missing one is found by the proof. +fn online_only(meta: &std::fs::Metadata) -> bool { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + placeholder_attributes(meta.file_attributes()) + } + #[cfg(target_os = "macos")] + { + use std::os::macos::fs::MetadataExt; + dataless_flags(meta.st_flags()) + } + #[cfg(not(any(windows, target_os = "macos")))] + { + let _ = meta; + false + } +} + /// Make a folder's entries durable (Unix; NTFS journals its own). pub(crate) fn sync_dir(path: &Path) { #[cfg(unix)] @@ -145,10 +263,99 @@ pub(crate) fn sync_dir(path: &Path) { let _ = path; } -/// Whether a link could not be made because the disk does not make them -/// (rather than because the name is taken). -fn link_unsupported(e: &std::io::Error) -> bool { - e.kind() != std::io::ErrorKind::AlreadyExists +/// Whether a failed hard link means the disk does not make links (FAT, +/// exFAT, some network shares and sync folders), as against the name +/// being taken or the disk refusing for another reason. The errors that +/// mean it, by platform: +/// +/// * Unix: `EPERM` (what Linux's vfat and exFAT answer), `ENOSYS`, +/// `EOPNOTSUPP` and `ENOTSUP` (network and FUSE file systems), and the +/// portable kind `Unsupported`. +/// * Windows: `ERROR_INVALID_FUNCTION` (1, FAT and exFAT), `ERROR_NOT_SUPPORTED` +/// (50), `ERROR_INVALID_PARAMETER` (87) and `ERROR_CALL_NOT_IMPLEMENTED` +/// (120). +pub(crate) fn link_unsupported(e: &std::io::Error) -> bool { + if e.kind() == std::io::ErrorKind::Unsupported { + return true; + } + let Some(n) = e.raw_os_error() else { + return false; + }; + #[cfg(unix)] + { + n == libc::EPERM || n == libc::ENOSYS || n == libc::EOPNOTSUPP || n == libc::ENOTSUP + } + #[cfg(windows)] + { + matches!(n, 1 | 50 | 87 | 120) + } + #[cfg(not(any(unix, windows)))] + { + let _ = n; + false + } +} + +/// Move `from` to `to`, which must not be there: never over something +/// already at `to` (that is `AlreadyExists`). `Unsupported` when the file +/// system cannot refuse to replace, which the caller meets by exclusive +/// create and copy. +fn rename_new(from: &Path, to: &Path) -> std::io::Result<()> { + #[cfg(target_os = "linux")] + { + use std::os::unix::ffi::OsStrExt; + let f = std::ffi::CString::new(from.as_os_str().as_bytes())?; + let t = std::ffi::CString::new(to.as_os_str().as_bytes())?; + // SAFETY: two NUL-terminated paths that live past the call. + let rc = unsafe { + libc::renameat2( + libc::AT_FDCWD, + f.as_ptr(), + libc::AT_FDCWD, + t.as_ptr(), + libc::RENAME_NOREPLACE, + ) + }; + if rc == 0 { + return Ok(()); + } + let e = std::io::Error::last_os_error(); + match e.raw_os_error() { + Some(n) if n == libc::EINVAL || n == libc::ENOSYS || n == libc::ENOTSUP => { + Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) + } + _ => Err(e), + } + } + #[cfg(target_os = "macos")] + { + use std::os::unix::ffi::OsStrExt; + let f = std::ffi::CString::new(from.as_os_str().as_bytes())?; + let t = std::ffi::CString::new(to.as_os_str().as_bytes())?; + // SAFETY: two NUL-terminated paths that live past the call. + let rc = unsafe { libc::renamex_np(f.as_ptr(), t.as_ptr(), libc::RENAME_EXCL) }; + if rc == 0 { + return Ok(()); + } + let e = std::io::Error::last_os_error(); + match e.raw_os_error() { + Some(n) if n == libc::ENOTSUP || n == libc::EINVAL || n == libc::ENOSYS => { + Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) + } + _ => Err(e), + } + } + #[cfg(windows)] + { + // MoveFileExW without MOVEFILE_REPLACE_EXISTING refuses an + // existing target itself. + crate::winsec::rename_new(from, to) + } + #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] + { + let _ = (from, to); + Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) + } } impl SetIo for DirSet { @@ -158,6 +365,11 @@ impl SetIo for DirSet { let mut out = Vec::new(); for e in entries { if let Some(n) = e?.file_name().to_str() { + // A stand-in of a file not downloaded: it is + // there, though not as the file itself. + if is_stand_in_name(n) { + return Err(carry(BackupError::NotDownloaded)); + } out.push(n.to_string()); } } @@ -172,9 +384,16 @@ impl SetIo for DirSet { fn len(&self, rel: &str) -> std::io::Result> { match std::fs::symlink_metadata(self.path(rel)) { // A link is not a file of a backup: it could lead anywhere. + Ok(m) if m.is_file() && online_only(&m) => Err(carry(BackupError::NotDownloaded)), Ok(m) if m.is_file() => Ok(Some(m.len())), Ok(_) => Ok(None), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if self.stand_in_for(rel) { + Err(carry(BackupError::NotDownloaded)) + } else { + Ok(None) + } + } Err(e) => Err(e), } } @@ -185,7 +404,16 @@ impl SetIo for DirSet { f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>, ) -> std::io::Result<()> { let path = self.path(rel); - let meta = std::fs::symlink_metadata(&path)?; + let meta = match std::fs::symlink_metadata(&path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound && self.stand_in_for(rel) => { + return Err(carry(BackupError::NotDownloaded)); + } + Err(e) => return Err(e), + }; + if online_only(&meta) { + return Err(carry(BackupError::NotDownloaded)); + } if !meta.is_file() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, @@ -224,48 +452,26 @@ impl SetIo for DirSet { return Err(e); } self.ctx.point("written", rel).map_err(carry)?; - let put = match std::fs::hard_link(&tmp, &path) { + let linked = if self.ctx.refuses_links() { + // A test's disk that makes no links. + Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) + } else { + std::fs::hard_link(&tmp, &path) + }; + let put = match linked { Ok(()) => { let _ = std::fs::remove_file(&tmp); Put::Created } - Err(e) if !link_unsupported(&e) => { + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { let _ = std::fs::remove_file(&tmp); Put::Existed } - Err(_) => { - // A disk that makes no links. - match kind { - PutKind::Manifest => { - let _ = std::fs::remove_file(&tmp); - match std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) - { - Ok(mut file) => { - { - let mut w = std::io::BufWriter::new(&mut file); - fill(&mut w)?; - w.flush()?; - } - file.sync_all()?; - Put::Created - } - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Put::Existed, - Err(e) => return Err(e), - } - } - PutKind::Piece | PutKind::Once => { - if std::fs::symlink_metadata(&path).is_ok() { - let _ = std::fs::remove_file(&tmp); - Put::Existed - } else { - std::fs::rename(&tmp, &path)?; - Put::Created - } - } - } + Err(e) if link_unsupported(&e) => self.place_without_links(&tmp, &path)?, + // Any other error is an error: never a reason to replace. + Err(e) => { + let _ = std::fs::remove_file(&tmp); + return Err(e); } }; sync_dir(&parent); diff --git a/crates/ledger-store/src/backup/mod.rs b/crates/ledger-store/src/backup/mod.rs index 83e849fe..96f769ea 100644 --- a/crates/ledger-store/src/backup/mod.rs +++ b/crates/ledger-store/src/backup/mod.rs @@ -74,7 +74,10 @@ pub use read::list; pub use read::{Candidate, Found, Verified, drill, find, prove_local, verify_found}; pub use seal::BackupKey; pub use single::{FILE_EXTENSION, save_file}; -pub use write::{Destination, Written, set_name_for, write_destination, write_local}; +pub use write::{ + Destination, Options, Written, holds_only_sealed, set_name_for, write_destination, + write_destination_with, write_local, +}; /// What a backup holds, of a book's folder. pub const BACKED_UP: [&str; 5] = [ @@ -104,12 +107,12 @@ pub enum BackupError { NoBackupThere, /// The destination holds other books, or another history of these. #[error( - "the backup folder holds a backup of other books, or of a different history of these: nothing was written there" + "the backup folder holds a backup of other books, or of a different history of these books (they have diverged): nothing was written there" )] Elsewhere, - /// The destination is ahead of these books. + /// The destination holds a longer history of these same books. #[error( - "the backup folder holds a newer backup of these books (through event {0}) than this computer has (event {1}): nothing was written there" + "the backup folder holds a longer history of these books (through event {0}) than this computer has (event {1}), as after restoring from an older backup: nothing was written there. If these books are the ones to carry on with, start a new backup set beside the old one: the old one is never touched" )] Ahead(u64, u64), /// Another program kept taking the next place in the destination. @@ -121,6 +124,28 @@ pub enum BackupError { /// The backup is protected by a passphrase and none was given. #[error("that backup is protected by a passphrase: it needs the passphrase it was made with")] NeedsPassphrase, + /// The backups were sealed with a passphrase and this computer has + /// lost its key. + #[error( + "these backups are protected by a passphrase, but this computer no longer has its key: nothing was written. Enter the passphrase in the backup settings to carry on, or choose remove the passphrase there to back up without one" + )] + KeyMissing, + /// A file of the backup folder is online only: its sync service has + /// not put it on this computer. + #[error( + "some files in the backup folder are online only and not downloaded to this computer yet: open the folder in your sync app, keep it available offline, wait until it has finished, and try again" + )] + NotDownloaded, + /// The newest backup does not prove whole; an older one does. + #[error("{}", newest_damaged_words(*.number, .older_from.as_deref(), .newest_from.as_deref()))] + NewestDamaged { + /// The newest manifest's number. + number: u64, + /// When the newest was made, if it can be read. + newest_from: Option, + /// When the newest one that proves whole was made (None: none does). + older_from: Option, + }, /// The passphrase given opens nothing. #[error("that isn't the passphrase this backup was made with")] WrongPassphrase, @@ -166,6 +191,19 @@ impl From for BackupError { } } +fn newest_damaged_words(number: u64, older: Option<&str>, newest: Option<&str>) -> String { + let which = match newest { + Some(d) => format!("the newest backup (number {number}, from {d})"), + None => format!("the newest backup (number {number})"), + }; + match older { + Some(d) => format!( + "{which} is damaged; an older one from {d} is whole, and a restore would give that one, not the newest" + ), + None => format!("{which} is damaged, and no older one proves whole either"), + } +} + /// Told the name of each phase of a long step as it begins (the server's /// test knob waits in them). pub type PhaseWatch = Arc; @@ -181,6 +219,10 @@ pub struct Ctx { stop: Option>, faults: Option, phase: Option, + /// Tests: a disk that makes no hard links, and one whose move cannot + /// refuse to replace. + no_links: bool, + no_noreplace: bool, } impl std::fmt::Debug for Ctx { @@ -208,6 +250,31 @@ impl Ctx { self } + /// A disk that makes no hard links (tests: the commonest other disk, + /// FAT or exFAT on a stick). + #[doc(hidden)] + pub fn with_no_hard_links(mut self) -> Self { + self.no_links = true; + self + } + + /// A disk that makes no links and whose move cannot refuse to replace + /// (tests: the last resort of `io.rs`). + #[doc(hidden)] + pub fn with_no_exclusive_move(mut self) -> Self { + self.no_links = true; + self.no_noreplace = true; + self + } + + pub(crate) fn refuses_links(&self) -> bool { + self.no_links + } + + pub(crate) fn refuses_noreplace(&self) -> bool { + self.no_noreplace + } + /// Told each phase of a long step as it begins. pub fn with_phase_watch(mut self, watch: PhaseWatch) -> Self { self.phase = Some(watch); diff --git a/crates/ledger-store/src/backup/read.rs b/crates/ledger-store/src/backup/read.rs index dfaa9b56..5957bc35 100644 --- a/crates/ledger-store/src/backup/read.rs +++ b/crates/ledger-store/src/backup/read.rs @@ -52,6 +52,129 @@ impl Read for Hashed<'_, R> { } } +/// Where the contents of a piece go as they are read and proven. A piece +/// that proves damaged after some of it was handed over is read again from +/// another generation, so a sink can be taken back to where the piece +/// began. +pub(crate) trait Sink { + /// The next chunk of contents. + fn put(&mut self, chunk: &[u8]) -> std::io::Result<()>; + /// A piece begins here: [`Sink::rewind`] comes back to this. + fn mark(&mut self); + /// Forget what was handed over since the last [`Sink::mark`]. + fn rewind(&mut self) -> std::io::Result<()>; +} + +/// Contents thrown away (the piece is only proven). +pub(crate) struct Discard; + +impl Sink for Discard { + fn put(&mut self, _: &[u8]) -> std::io::Result<()> { + Ok(()) + } + fn mark(&mut self) {} + fn rewind(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// Contents gathered in memory. +#[derive(Default)] +pub(crate) struct VecSink { + pub(crate) bytes: Vec, + at: usize, +} + +impl Sink for VecSink { + fn put(&mut self, chunk: &[u8]) -> std::io::Result<()> { + self.bytes.extend_from_slice(chunk); + Ok(()) + } + fn mark(&mut self) { + self.at = self.bytes.len(); + } + fn rewind(&mut self) -> std::io::Result<()> { + self.bytes.truncate(self.at); + Ok(()) + } +} + +/// Contents written to a file of this program's own making. +pub(crate) struct FileSink { + file: std::fs::File, + at: u64, + len: u64, +} + +impl FileSink { + pub(crate) fn new(file: std::fs::File) -> Self { + Self { + file, + at: 0, + len: 0, + } + } + + pub(crate) fn finish(self) -> std::io::Result<()> { + self.file.sync_all() + } +} + +impl Sink for FileSink { + fn put(&mut self, chunk: &[u8]) -> std::io::Result<()> { + self.len += chunk.len() as u64; + self.file.write_all(chunk) + } + fn mark(&mut self) { + self.at = self.len; + } + fn rewind(&mut self) -> std::io::Result<()> { + use std::io::{Seek, SeekFrom}; + self.file.set_len(self.at)?; + self.file.seek(SeekFrom::Start(self.at))?; + self.len = self.at; + Ok(()) + } +} + +/// What a series of segments hashes to as its segments are read through +/// it, in front of another sink. +struct SeriesSink<'a> { + inner: &'a mut dyn Sink, + total: Sha256, + bytes: u64, + at: (Sha256, u64), +} + +impl Sink for SeriesSink<'_> { + fn put(&mut self, chunk: &[u8]) -> std::io::Result<()> { + self.total.update(chunk); + self.bytes += chunk.len() as u64; + self.inner.put(chunk) + } + fn mark(&mut self) { + self.at = (self.total.clone(), self.bytes); + self.inner.mark(); + } + fn rewind(&mut self) -> std::io::Result<()> { + self.total = self.at.0.clone(); + self.bytes = self.at.1; + self.inner.rewind() + } +} + +/// A piece that proved damaged: where the manifest names it, and what it +/// should hold. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Damage { + pub kind: Kind, + /// The path the manifest names it at (a stored file's, its first + /// generation's). + pub file: String, + pub bytes: u64, + pub sha256: String, +} + impl Set { pub(crate) fn dir(path: PathBuf, keys: Option, ctx: &Ctx) -> Set { Set { @@ -94,8 +217,10 @@ impl Set { Ok(out) } - /// The manifest numbered `n`: read, opened, checked. - pub(crate) fn manifest(&self, n: u64) -> Result { + /// The manifest numbered `n` as it is kept: read, opened, checked by + /// its own line (a delta manifest names only what is new in its + /// series: [`Set::manifest`] gives it whole). + fn manifest_stored(&self, n: u64) -> Result { let raw = self.read_small(&manifest_path(n, self.sealed()))?; let bytes = match &self.keys { Some(k) => k.open_bytes(&raw, &manifest_aad(n))?, @@ -107,14 +232,96 @@ impl Set { "a manifest of the backup is under another number".into(), )); } + Ok(m) + } + + /// `stored` whole: a manifest that names its base is joined to it. The + /// base is read and must hash to what `stored` says (so a changed, + /// swapped or missing base makes this manifest unreadable, never a + /// manifest that names something else), and must be one link shorter + /// in the chain, so a chain can't loop or run past [`DELTA_CHAIN`]. + fn resolve(&self, mut stored: Manifest) -> Result { + let bad = |why: &str| BackupError::Damaged(format!("a manifest of the backup {why}")); + let Some(base) = stored.base.clone() else { + if stored.depth != 0 + || [&stored.journal, &stored.access, &stored.files] + .iter() + .any(|s| s.keep != 0) + { + return Err(bad("names a base it doesn't have")); + } + return Ok(stored); + }; + if stored.depth == 0 || stored.depth > DELTA_CHAIN || base.number >= stored.number { + return Err(bad("is chained wrongly")); + } + let below = self.manifest_stored(base.number)?; + if below.depth + 1 != stored.depth || below.sha != base.sha256 { + return Err(bad("is built on a manifest that is not the one it names")); + } + let below = self.resolve(below)?; + for (mine, theirs) in [ + (&mut stored.journal, &below.journal), + (&mut stored.access, &below.access), + (&mut stored.files, &below.files), + ] { + if mine.keep > theirs.segments.len() { + return Err(bad("keeps more of its base than there is")); + } + let mut segments = theirs.segments[..mine.keep].to_vec(); + segments.append(&mut mine.segments); + mine.segments = segments; + mine.keep = 0; + } + Ok(stored) + } + + /// The manifest numbered `n`: read, opened, whole, checked. + pub(crate) fn manifest(&self, n: u64) -> Result { + let m = self.resolve(self.manifest_stored(n)?)?; m.check_names(self.sealed())?; Ok(m) } + /// The paths a piece is kept at, as found: `rel` and its other + /// generations (`.g1`, `.g2`, ...), in the order of their generation. + pub(crate) fn generations(&self, rel: &str) -> Result, BackupError> { + let (stem, _) = split_generation(rel); + let (dir, name) = stem.rsplit_once('/').unwrap_or(("", stem)); + let mut found: Vec<(u32, String)> = Vec::new(); + for entry in self.io.list(dir)? { + let (entry_stem, g) = split_generation(&entry); + if entry_stem == name { + let path = if dir.is_empty() { + entry.clone() + } else { + format!("{dir}/{entry}") + }; + found.push((g, path)); + } + } + found.sort(); + Ok(found.into_iter().map(|(_, p)| p).collect()) + } + + /// Whether the piece `p` is there at the length it names, at the path + /// the manifest names or, when that is not so, at another generation. + fn piece_present(&self, p: &Piece) -> Result { + if self.io.len(&p.file)? == Some(p.stored) { + return Ok(true); + } + for other in self.generations(&p.file)? { + if other != p.file && self.io.len(&other)? == Some(p.stored) { + return Ok(true); + } + } + Ok(false) + } + /// Whether every piece `m` names, apart from the stored files, is /// there at the length it names: the cheap look that decides which - /// manifest is the newest whole one. The proof re-hashes. - fn looks_whole(&self, m: &Manifest) -> Result { + /// manifest is worth proving. The proof re-hashes. + pub(crate) fn looks_whole(&self, m: &Manifest) -> Result { let pieces = m .journal .segments @@ -124,7 +331,7 @@ impl Set { .chain(m.vault.iter().map(|n| &n.piece)) .chain(m.keys.iter().map(|n| &n.piece)); for p in pieces { - if self.io.len(&p.file)? != Some(p.stored) { + if !self.piece_present(p)? { return Ok(false); } } @@ -132,58 +339,76 @@ impl Set { } /// The newest manifest that is whole to the eye (INVARIANT 3), and - /// how many newer ones were passed over. + /// how many newer ones were passed over. Newest first, and only as + /// far as the first. pub(crate) fn newest_whole(&self) -> Result, BackupError> { let numbers = self.numbers()?; for (skipped, n) in numbers.iter().rev().enumerate() { self.ctx.check("reading the backup")?; - if let Ok(m) = self.manifest(*n) - && self.looks_whole(&m)? - { - return Ok(Some((m, skipped))); + match self.manifest(*n) { + Ok(m) if self.looks_whole(&m)? => return Ok(Some((m, skipped))), + Ok(_) => {} + // A manifest that is not whole is passed over; a stop, a + // file that is not downloaded, a disk's own refusal is not. + Err(BackupError::Damaged(_)) => {} + Err(e) => return Err(e), } } Ok(None) } - /// Every manifest that is whole to the eye, newest first. - pub(crate) fn whole_ones(&self) -> Result, BackupError> { - let mut out = Vec::new(); - for n in self.numbers()?.iter().rev() { - self.ctx.check("reading the backup")?; - if let Ok(m) = self.manifest(*n) - && self.looks_whole(&m)? - { - out.push(m); - } - } - Ok(out) - } - - /// The contents of the piece at `rel` (of `kind`, `bytes` long, hashing - /// to `sha`) handed to `sink`, proven as they go: a piece that is not - /// what its manifest says is an error. A sealed piece is opened first. - pub(crate) fn read_piece( + /// Read the piece named by `p` (of `kind`) into `sink`, proven as it + /// goes. Ok(true): it is what the manifest says. Ok(false): it is not + /// there, or is not what it should be, at the path named nor at any + /// other generation; `sink` is as it was. Err: a stop, a file not + /// downloaded, a disk's refusal: nothing is said of the piece. + pub(crate) fn read_piece_into( &self, rel: &str, kind: Kind, bytes: u64, sha: &str, - sink: &mut dyn FnMut(&[u8]) -> std::io::Result<()>, - ) -> Result<(), BackupError> { - let damaged = - || BackupError::Damaged(format!("a piece of the backup ({}) is damaged", short(sha))); + sink: &mut dyn Sink, + ) -> Result { + sink.mark(); + if self.attempt(rel, kind, bytes, sha, sink)? { + return Ok(true); + } + sink.rewind()?; + // The piece was written again beside a damaged one: any + // generation of it that hashes right is the piece. + for other in self.generations(rel)? { + if other == rel { + continue; + } + sink.mark(); + if self.attempt(&other, kind, bytes, sha, sink)? { + return Ok(true); + } + sink.rewind()?; + } + Ok(false) + } + + /// One reading of the piece at `rel`. + fn attempt( + &self, + rel: &str, + kind: Kind, + bytes: u64, + sha: &str, + sink: &mut dyn Sink, + ) -> Result { let mut hasher = Sha256::new(); let mut count = 0u64; + let ctx = self.ctx.clone(); let mut feed = |chunk: &[u8]| -> std::io::Result<()> { hasher.update(chunk); count += chunk.len() as u64; - sink(chunk) + sink.put(chunk) }; - let ctx = self.ctx.clone(); let opened: Result<(), BackupError> = match &self.keys { None => { - let mut res: Result<(), BackupError> = Ok(()); let io_res = self.io.read_with(rel, &mut |r| { let mut r = r.take(bytes.saturating_add(1)); let mut buf = vec![0u8; 1 << 16]; @@ -196,10 +421,7 @@ impl Set { feed(&buf[..n])?; } }); - if let Err(e) = io_res { - res = Err(uncarry(e)); - } - res + io_res.map_err(uncarry) } Some(keys) => { let mut res: Result<(), BackupError> = Ok(()); @@ -220,18 +442,55 @@ impl Set { }; match opened { Ok(()) => {} - Err(BackupError::Io(std::io::ErrorKind::NotFound)) => { - return Err(BackupError::Damaged(format!( - "a piece of the backup ({}) is missing", - short(sha) - ))); - } + // Not there, or not a file of the form: damage to the piece. + Err(BackupError::Io( + std::io::ErrorKind::NotFound | std::io::ErrorKind::InvalidData, + )) + | Err(BackupError::Damaged(_)) => return Ok(false), Err(e) => return Err(e), } - if count != bytes || hex::encode(hasher.finalize()) != sha { - return Err(damaged()); + Ok(count == bytes && hex::encode(hasher.finalize()) == sha) + } + + /// A series read whole through `sink`: its segments, each proven, and + /// the whole proven against the manifest. A segment that is damaged + /// is listed and the reading goes on with the next, so that all the + /// damage is found at once; the whole is then not proven (there is a + /// gap), and it is the caller's to say. + pub(crate) fn read_series_lenient( + &self, + series: &Series, + kind: Kind, + sink: &mut dyn Sink, + ) -> Result, BackupError> { + let mut series_sink = SeriesSink { + inner: sink, + total: Sha256::new(), + bytes: 0, + at: (Sha256::new(), 0), + }; + let mut damaged = Vec::new(); + for seg in &series.segments { + self.ctx.check("reading the backup")?; + if !self.read_piece_into(&seg.file, kind, seg.bytes, &seg.sha256, &mut series_sink)? { + damaged.push(Damage { + kind, + file: seg.file.clone(), + bytes: seg.bytes, + sha256: seg.sha256.clone(), + }); + } } - Ok(()) + if damaged.is_empty() + && (series_sink.bytes != series.bytes + || (series_sink.bytes > 0 + && hex::encode(series_sink.total.finalize()) != series.sha256)) + { + return Err(BackupError::Damaged( + "the backup's pieces don't add up to what its manifest says".into(), + )); + } + Ok(damaged) } /// A series read whole through `sink`, its segments and the whole @@ -240,36 +499,25 @@ impl Set { &self, series: &Series, kind: Kind, - sink: &mut dyn FnMut(&[u8]) -> std::io::Result<()>, + sink: &mut dyn Sink, ) -> Result<(), BackupError> { - let mut total = Sha256::new(); - let mut bytes = 0u64; - for seg in &series.segments { - self.ctx.check("reading the backup")?; - self.read_piece(&seg.file, kind, seg.bytes, &seg.sha256, &mut |c| { - total.update(c); - bytes += c.len() as u64; - sink(c) - })?; + let damaged = self.read_series_lenient(series, kind, sink)?; + match damaged.first() { + None => Ok(()), + Some(d) => Err(BackupError::Damaged(format!( + "a piece of the backup ({}) is damaged or missing", + short(&d.sha256) + ))), } - if bytes != series.bytes || (bytes > 0 && hex::encode(total.finalize()) != series.sha256) { - return Err(BackupError::Damaged( - "the backup's pieces don't add up to what its manifest says".into(), - )); - } - Ok(()) } /// The index of stored files a manifest names. pub(crate) fn index(&self, m: &Manifest) -> Result, BackupError> { - let mut text = Vec::new(); - self.read_series(&m.files, Kind::Index, &mut |c| { - text.extend_from_slice(c); - Ok(()) - })?; + let mut text = VecSink::default(); + self.read_series(&m.files, Kind::Index, &mut text)?; let mut out = Vec::new(); let mut seen = BTreeSet::new(); - for line in text.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { + for line in text.bytes.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { let l: IndexLine = serde_json::from_slice(line).map_err(|_| { BackupError::Damaged("the backup's index of stored files is damaged".into()) })?; @@ -310,6 +558,10 @@ pub struct Candidate { pub book: Option, /// Sealed. pub sealed: bool, + /// The journal event its newest backup reaches, if it could be read. + pub through_seq: Option, + /// When its newest backup was made, if it could be read. + pub written: Option, } fn open_header(set: &Set) -> Result, BackupError> { @@ -324,6 +576,7 @@ fn open_set( io: Box, passphrase: Option<&str>, ctx: &Ctx, + cache: &mut KeyCache, ) -> Result<(Set, Option), BackupError> { let probe = Set { io, @@ -334,7 +587,7 @@ fn open_set( return Ok((probe, None)); }; let pass = passphrase.ok_or(BackupError::NeedsPassphrase)?; - let key = BackupKey::from_header(pass, &header)?; + let key = BackupKey::from_header_cached(pass, &header, cache)?; let set = Set { io: probe.io, keys: Some(key.keys()), @@ -343,6 +596,9 @@ fn open_set( Ok((set, Some(key))) } +/// Keys derived while a folder is looked through, one per distinct setting. +type KeyCache = Vec<(super::seal::Kdf, Result)>; + fn found_from(set: Set, key: Option) -> Result { let book = set.newest_whole()?.map(|(m, _)| m.book); Ok(Found { @@ -378,7 +634,12 @@ pub fn find(source: &Path, passphrase: Option<&str>, ctx: &Ctx) -> Result BackupError::from(e), })?; if meta.is_file() { - let (set, key) = open_set(super::single::open(source, ctx)?, passphrase, ctx)?; + let (set, key) = open_set( + super::single::open(source, ctx)?, + passphrase, + ctx, + &mut Vec::new(), + )?; return found_from(set, key); } if !meta.is_dir() { @@ -389,6 +650,7 @@ pub fn find(source: &Path, passphrase: Option<&str>, ctx: &Ctx) -> Result, ctx: &Ctx) -> Result = Vec::new(); let mut wrong = false; let mut needs = false; + // One key derived for each distinct setting, however many sealed sets + // the folder holds (what a header asks is not paid for per set). + let mut cache: KeyCache = Vec::new(); for name in &folders { match open_set( Box::new(DirSet::new(source.join(name), ctx.clone())), passphrase, ctx, + &mut cache, ) { Ok((set, key)) => found.push((name.clone(), found_from(set, key)?)), Err(BackupError::WrongPassphrase) => wrong = true, @@ -433,13 +699,15 @@ pub fn list(source: &Path) -> Vec { let ctx = Ctx::new(); let set = Set::dir(source.join(name), None, &ctx); let sealed = set.io.len(HEADER).ok().flatten().is_some(); - let book = (!sealed) - .then(|| set.newest_whole().ok().flatten().map(|(m, _)| m.book)) + let newest = (!sealed) + .then(|| set.newest_whole().ok().flatten().map(|(m, _)| m)) .flatten(); Candidate { folder: name.to_string(), - book, + book: newest.as_ref().map(|m| m.book.clone()), sealed, + through_seq: newest.as_ref().map(|m| m.head.seq), + written: newest.map(|m| m.written), } }; set_folders(source).iter().map(|n| probe(n)).collect() @@ -458,8 +726,13 @@ pub struct Verified { pub book: Option, /// Its manifest's number. pub number: u64, - /// Newer manifests that were not whole and were passed over. + /// When it was made (UTC), as its manifest says. + pub written: String, + /// How many newer backups there are that were passed over: not whole, + /// or damaged. Not zero means this is not the newest backup there is. pub passed_over: usize, + /// When the newest backup there is was made, if it can be read. + pub newest_written: Option, /// The key, if it was sealed: for the restored books to carry on /// backing up sealed. pub key: Option, @@ -477,90 +750,215 @@ fn put_scratch(dir: &Path, name: &str, bytes: &[u8]) -> std::io::Result<()> { f.sync_all() } +/// Which stored files a pass over a manifest reads. +pub(crate) enum Files<'a> { + /// Every one, built into the scratch folder (a restore, a drill). + All, + /// Only these (the proof after a backup): read and proven, not kept. + Only(&'a BTreeSet), +} + +/// What reading a manifest's pieces found. +pub(crate) struct Audit { + /// Pieces that are damaged or missing, every one of them. + pub damaged: Vec, + /// Stored files the manifest names, by hash. + pub index: BTreeSet, + /// How many stored files were read and proven. + pub files_read: u64, +} + /// Build the books of `m` in `scratch` (a new folder): the journal, the -/// access log, the vault, the keys and every stored file; every piece -/// proven as it is read. (The store reads some stored files itself when -/// it verifies the books, so a drill keeps them too, as a restore does.) -/// Returns the hashes of the stored files proven. -fn materialize(set: &Set, m: &Manifest, scratch: &Path) -> Result, BackupError> { +/// access log, the vault, the keys and (with [`Files::All`]) every stored +/// file; every piece proven as it is read, and every piece that is not +/// whole listed, not only the first. (The store reads some stored files +/// itself when it verifies the books, so a drill keeps them too, as a +/// restore does.) +fn materialize( + set: &Set, + m: &Manifest, + scratch: &Path, + files: &Files<'_>, +) -> Result { let ctx = &set.ctx; std::fs::create_dir_all(scratch)?; + let mut damaged = Vec::new(); for (series, kind, name) in [ (&m.journal, Kind::Journal, crate::JOURNAL_FILE), (&m.access, Kind::Access, crate::access::ACCESS_FILE), ] { - let mut f = std::fs::OpenOptions::new() + let f = std::fs::OpenOptions::new() .write(true) .create_new(true) .open(scratch.join(name))?; - set.read_series(series, kind, &mut |c| f.write_all(c))?; - f.sync_all()?; + let mut sink = FileSink::new(f); + damaged.extend(set.read_series_lenient(series, kind, &mut sink)?); + sink.finish()?; } for (list, kind, dir) in [ (&m.vault, Kind::Vault, crate::root::VAULT_DIR), (&m.keys, Kind::Key, crate::root::KEYS_DIR), ] { for n in list { - let mut bytes = Vec::new(); - set.read_piece( + let mut bytes = VecSink::default(); + if set.read_piece_into( &n.piece.file, kind, n.piece.bytes, &n.piece.sha256, - &mut |c| { - bytes.extend_from_slice(c); - Ok(()) - }, - )?; - put_scratch(&scratch.join(dir), &n.name, &bytes)?; + &mut bytes, + )? { + put_scratch(&scratch.join(dir), &n.name, &bytes.bytes)?; + } else { + damaged.push(Damage { + kind, + file: n.piece.file.clone(), + bytes: n.piece.bytes, + sha256: n.piece.sha256.clone(), + }); + } } } - let mut proven = BTreeSet::new(); - for line in set.index(m)? { - ctx.check("reading the backup")?; - let rel = piece_path(set.keys.as_ref(), Kind::File, 0, &line.sha256); - let blob = scratch - .join(crate::store::BLOBS_DIR) - .join(&line.sha256[0..2]) - .join(&line.sha256[2..4]); - std::fs::create_dir_all(&blob)?; - let mut f = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(blob.join(&line.sha256))?; - set.read_piece(&rel, Kind::File, line.bytes, &line.sha256, &mut |c| { - f.write_all(c) - })?; - f.sync_all()?; - proven.insert(line.sha256); + // The index (itself pieces), then the files it names. + let mut text = VecSink::default(); + let index_damage = set.read_series_lenient(&m.files, Kind::Index, &mut text)?; + let mut index = BTreeSet::new(); + let mut lines = Vec::new(); + if index_damage.is_empty() { + for line in text.bytes.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { + let l: IndexLine = serde_json::from_slice(line).map_err(|_| { + BackupError::Damaged("the backup's index of stored files is damaged".into()) + })?; + if !is_sha(&l.sha256) { + return Err(BackupError::Damaged( + "the backup's index of stored files names a file by no hash".into(), + )); + } + if index.insert(l.sha256.clone()) { + lines.push(l); + } + } } - Ok(proven) + damaged.extend(index_damage); + let mut files_read = 0u64; + for line in lines { + ctx.check("reading the backup")?; + let wanted = match files { + Files::All => true, + Files::Only(only) => only.contains(&line.sha256), + }; + if !wanted { + continue; + } + let rel = piece_path(set.keys.as_ref(), Kind::File, 0, &line.sha256); + let ok = match files { + Files::All => { + let blob = scratch + .join(crate::store::BLOBS_DIR) + .join(&line.sha256[0..2]) + .join(&line.sha256[2..4]); + std::fs::create_dir_all(&blob)?; + let f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(blob.join(&line.sha256))?; + let mut sink = FileSink::new(f); + let ok = + set.read_piece_into(&rel, Kind::File, line.bytes, &line.sha256, &mut sink)?; + sink.finish()?; + ok + } + Files::Only(_) => { + set.read_piece_into(&rel, Kind::File, line.bytes, &line.sha256, &mut Discard)? + } + }; + if ok { + files_read += 1; + } else { + damaged.push(Damage { + kind: Kind::File, + file: rel, + bytes: line.bytes, + sha256: line.sha256.clone(), + }); + } + } + Ok(Audit { + damaged, + index, + files_read, + }) +} + +/// The words for damage found: the first piece, and how many there are. +fn damaged_words(damaged: &[Damage]) -> String { + match damaged { + [] => "nothing is damaged".to_string(), + [one] => format!( + "a piece of the backup ({}) is damaged or missing", + short(&one.sha256) + ), + [first, rest @ ..] => format!( + "{} pieces of the backup are damaged or missing (the first is {})", + rest.len() + 1, + short(&first.sha256) + ), + } +} + +/// How thoroughly the books built from a manifest are proven. +pub(crate) enum Depth { + /// Everything: the chain replays, the store verifies and re-hashes + /// every stored file it names. + Whole, + /// What a backup proves of itself when it is made: the chain + /// replays, the books open, the vault and its key are there, the head + /// is the one recorded, and every stored file the books name is in + /// the manifest's index. Stored files are proven by what was read. + Chain, } /// Prove the books built in `scratch` from `m` (INVARIANT 3): the chain -/// replays, every stored file the books name is among those proven, every -/// vault record the books name and the key that opens them are there, the -/// head is the one the manifest records. +/// replays, every stored file the books name is in the index (and, for +/// [`Depth::Whole`], among those proven), every vault record the books name +/// and the key that opens them are there, the head is the one the +/// manifest records. fn prove_books( m: &Manifest, scratch: &Path, - proven_files: &BTreeSet, + audit: &Audit, + depth: &Depth, ctx: &Ctx, ) -> Result<(u64, (u64, String)), BackupError> { ctx.phase("replay"); let _stoppable = ctx.stop_flag().map(crate::cancel::scope); + if matches!(depth, Depth::Chain) { + // The hash chain, up to the head, before the books are opened. + let lines = crate::journal::read_and_verify_journal(&scratch.join(crate::JOURNAL_FILE))?; + let last = lines.last().map(|l| l.seq).unwrap_or(0); + if last != m.head.seq { + return Err(BackupError::Damaged(format!( + "its journal ends at event {last}, but the backup records another head" + ))); + } + } let mut store = crate::Store::open(scratch)?; - ctx.phase("verify"); - store.verify_and_heal()?; + if matches!(depth, Depth::Whole) { + ctx.phase("verify"); + store.verify_and_heal()?; + } ctx.phase("blobs"); let named: BTreeSet = store.stored_blob_shas()?.into_iter().collect(); - if let Some(missing) = named.iter().find(|s| !proven_files.contains(*s)) { + if let Some(missing) = named.iter().find(|s| !audit.index.contains(*s)) { return Err(BackupError::Damaged(format!( "a stored file the books name isn't in it ({})", short(missing) ))); } - let blobs = store.verify_blobs()?; + let blobs = match depth { + Depth::Whole => store.verify_blobs()?, + Depth::Chain => audit.files_read, + }; let head = store.head(); let tins: Vec = store .ledger() @@ -603,44 +1001,161 @@ fn prove_books( Ok((blobs, head)) } +/// The books built from manifest `m` into `scratch` and proven, whole. +fn prove_manifest( + set: &Set, + m: &Manifest, + scratch: &Path, +) -> Result<(u64, (u64, String)), BackupError> { + let audit = materialize(set, m, scratch, &Files::All)?; + if !audit.damaged.is_empty() { + return Err(BackupError::Damaged(damaged_words(&audit.damaged))); + } + prove_books(m, scratch, &audit, &Depth::Whole, &set.ctx) +} + +/// What the proof after a backup found. +pub(crate) struct Proof { + /// Pieces damaged or missing: none when the backup is whole as far as + /// the proof goes. + pub damaged: Vec, + /// Stored files re-hashed by it. + pub files_read: u64, +} + +/// How many backups it takes for every stored file to be re-read: the +/// proof after a backup reads the stored files that backup added and the +/// share of the others whose hash begins with a digit group equal to its +/// number modulo this. +pub(crate) const ROTATION: u64 = 16; + +/// Which share of the stored files manifest number `number` re-reads: a +/// file belongs to the share `bucket(sha)`, and a backup reads the files +/// of the share equal to its number modulo [`ROTATION`]. Any `ROTATION` +/// manifest numbers in a row between them read every file once. +pub(crate) fn in_rotation(sha: &str, number: u64) -> bool { + u64::from_str_radix(&sha[..4], 16).unwrap_or(0) % ROTATION == number % ROTATION +} + +/// The proof after a backup, of the manifest numbered `number`, read back +/// from the set as a reader would read it: every journal and access +/// segment re-hashed and the chain replayed to its head, the vault and the +/// keys and their presence, the index, and of the stored files those in +/// `added` (this backup's) and the share [`in_rotation`] of the rest. +/// Builds the books in `scratch` (a new folder, removed after). +pub(crate) fn prove_written( + set: &Set, + number: u64, + added: &BTreeSet, + scratch: &Path, +) -> Result { + let m = set.manifest(number)?; + // The share depends on the index, which is read inside the audit: + // those files of it that are in the share or added are read. + let mut index = VecSink::default(); + let _ = set.read_series_lenient(&m.files, Kind::Index, &mut index)?; + let mut want: BTreeSet = added.clone(); + for line in index.bytes.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { + if let Ok(l) = serde_json::from_slice::(line) + && is_sha(&l.sha256) + && in_rotation(&l.sha256, number) + { + want.insert(l.sha256); + } + } + let result = (|| { + let audit = materialize(set, &m, scratch, &Files::Only(&want))?; + if !audit.damaged.is_empty() { + return Ok(Proof { + damaged: audit.damaged, + files_read: audit.files_read, + }); + } + prove_books(&m, scratch, &audit, &Depth::Chain, &set.ctx)?; + Ok(Proof { + damaged: Vec::new(), + files_read: audit.files_read, + }) + })(); + let _ = std::fs::remove_dir_all(scratch); + result +} + +/// The manifest numbered `n` proven whole, its books built in `scratch`: +/// the pieces of the attempt are removed when it does not prove. +fn verify_one( + found: &Found, + n: u64, + scratch: &Path, + passed: usize, + newest: u64, +) -> Result, BackupError> { + let set = &found.set; + let ctx = &set.ctx; + let m = match set.manifest(n) { + Ok(m) => m, + Err(e @ BackupError::Damaged(_)) => return Ok(Err(e)), + Err(e) => return Err(e), + }; + if !set.looks_whole(&m)? { + return Ok(Err(BackupError::Damaged(format!( + "backup number {n} is missing some of its pieces" + )))); + } + ctx.phase("fetch"); + ctx.check("verifying")?; + match prove_manifest(set, &m, scratch) { + Ok((blobs, head)) => Ok(Ok(Verified { + head, + blobs, + tree: scratch.to_path_buf(), + book: Some(m.book.clone()), + number: m.number, + written: m.written.clone(), + passed_over: passed, + newest_written: if n == newest { + Some(m.written.clone()) + } else { + set.manifest(newest).ok().map(|x| x.written) + }, + key: found.key.clone(), + })), + Err(e @ (BackupError::Cancelled(_) | BackupError::Died)) => { + let _ = std::fs::remove_dir_all(scratch); + Err(e) + } + Err(e @ BackupError::Damaged(_)) => { + let _ = std::fs::remove_dir_all(scratch); + Ok(Err(e)) + } + Err(e) => { + let _ = std::fs::remove_dir_all(scratch); + Err(e) + } + } +} + /// Prove the backup found, building its books in `scratch` (a new folder): -/// the newest manifest that proves whole; a newer one that does not is -/// passed over and said. Every stored file is re-hashed and kept in the -/// scratch folder (a restore moves them from it; a drill removes it). +/// the newest manifest that proves whole, tried newest first and no +/// further than the first that proves; a newer one that does not is +/// passed over, and counted. Every stored file is re-hashed and kept in +/// the scratch folder (a restore moves them from it; a drill removes it). pub fn verify_found(found: &Found, scratch: &Path, ctx: &Ctx) -> Result { if scratch.exists() { return Err(BackupError::Damaged("its scratch folder is in use".into())); } let set = &found.set; - let mut passed = 0usize; + let numbers = set.numbers()?; + let Some(newest) = numbers.last().copied() else { + return Err(BackupError::NotABackup); + }; let mut last: Option = None; - for m in set.whole_ones()? { - ctx.phase("fetch"); + for (passed, n) in numbers.iter().rev().enumerate() { ctx.check("verifying")?; - let attempt = - materialize(set, &m, scratch).and_then(|files| prove_books(&m, scratch, &files, ctx)); - match attempt { - Ok((blobs, head)) => { - return Ok(Verified { - head, - blobs, - tree: scratch.to_path_buf(), - book: Some(m.book.clone()), - number: m.number, - passed_over: passed, - key: found.key.clone(), - }); - } - Err(e @ (BackupError::Cancelled(_) | BackupError::Died)) => { - let _ = std::fs::remove_dir_all(scratch); - return Err(e); - } - Err(e) => { - // Not this one: another, older, may be whole. - let _ = std::fs::remove_dir_all(scratch); - passed += 1; - last = Some(e); - } + match verify_one(found, *n, scratch, passed, newest)? { + Ok(v) => return Ok(v), + // Not this one: another, older, may be whole. + Err(e) => last = Some(e), } } Err(last.unwrap_or(BackupError::NotABackup)) @@ -672,15 +1187,28 @@ pub fn is_prefix(live: &Path, backup: &Path, ctx: &Ctx) -> Result, ctx: &Ctx, ) -> Result<(u64, String), BackupError> { if !dest.folder.is_dir() { @@ -693,19 +1221,57 @@ pub fn drill( key: dest.key.clone(), set, }; - let checked = verify_found(&found, scratch, ctx).and_then(|v| { - ctx.phase("prefix"); - if v.book.as_deref() != Some(book) { - return Err(BackupError::Elsewhere); + let _ = std::fs::remove_dir_all(scratch); + let numbers = found.set.numbers()?; + let newest = numbers.last().copied().ok_or(BackupError::NoBackupThere)?; + let checked = match verify_one(&found, newest, scratch, 0, newest) { + Err(e) => Err(e), + Ok(Ok(v)) => { + ctx.phase("prefix"); + if v.book.as_deref() != Some(book) { + Err(BackupError::Elsewhere) + } else if let Some(e) = expect + && (v.head.0 < e.0 || (v.head.0 == e.0 && v.head.1 != e.1)) + { + Err(BackupError::Damaged(format!( + "the newest backup in the folder reaches event {}, but the last backup recorded as good reached event {}: a backup that was made is not there", + v.head.0, e.0 + ))) + } else { + match is_prefix(live, &v.tree.join(crate::JOURNAL_FILE), ctx) { + Ok(true) => Ok(v.head), + Ok(false) => Err(BackupError::Damaged( + "its journal isn't this book's history".into(), + )), + Err(e) => Err(e), + } + } } - match is_prefix(live, &v.tree.join(crate::JOURNAL_FILE), ctx) { - Ok(true) => Ok(v.head), - Ok(false) => Err(BackupError::Damaged( - "its journal isn't this book's history".into(), - )), - Err(e) => Err(e), + Ok(Err(_)) => { + // The newest is damaged: say whether an older one is whole. + let newest_from = found.set.manifest(newest).ok().map(|m| m.written); + let mut older_from = None; + for n in numbers.iter().rev().skip(1).take(OLDER_TRIES) { + let _ = std::fs::remove_dir_all(scratch); + match verify_one(&found, *n, scratch, 1, newest) { + Ok(Ok(v)) => { + older_from = Some(v.written); + break; + } + Ok(Err(_)) => {} + Err(e) => { + let _ = std::fs::remove_dir_all(scratch); + return Err(e); + } + } + } + Err(BackupError::NewestDamaged { + number: newest, + newest_from, + older_from, + }) } - }); + }; let _ = std::fs::remove_dir_all(scratch); checked } diff --git a/crates/ledger-store/src/backup/seal.rs b/crates/ledger-store/src/backup/seal.rs index 0bfbf03c..853752a2 100644 --- a/crates/ledger-store/src/backup/seal.rs +++ b/crates/ledger-store/src/backup/seal.rs @@ -70,16 +70,38 @@ impl std::fmt::Debug for BackupKey { } } +/// How many times this program's own setting a header may ask for, of +/// memory, passes and lanes: a header is read from a folder anyone may +/// have written, and what it asks for is spent before the passphrase is +/// known right. +const KDF_CAP_FACTOR: u32 = 4; + /// Whether `kdf` asks nothing weaker than this program's own cost, and -/// nothing a computer could not afford (a header changed by hand). +/// nothing more than [`KDF_CAP_FACTOR`] times it (a header changed by +/// hand, or written to make a computer spend its memory). fn kdf_in_bounds(kdf: &Kdf) -> bool { + use crate::passphrase::{M_COST, P_COST, T_COST}; kdf.alg == "argon2id" - && (crate::passphrase::M_COST..=1024 * 1024).contains(&kdf.m) - && (crate::passphrase::T_COST..=16).contains(&kdf.t) - && (crate::passphrase::P_COST..=8).contains(&kdf.p) + && (M_COST..=M_COST.saturating_mul(KDF_CAP_FACTOR)).contains(&kdf.m) + && (T_COST..=T_COST.saturating_mul(KDF_CAP_FACTOR)).contains(&kdf.t) + && (P_COST..=P_COST.saturating_mul(KDF_CAP_FACTOR)).contains(&kdf.p) && hex::decode(&kdf.salt).is_ok_and(|s| (SALT_LEN..=64).contains(&s.len())) } +/// What the header's sealed check is bound to: the settings the key was +/// made with, so that the check opens only under the settings it was +/// sealed with. (A change a disk or a person makes by accident breaks the +/// header's own check line and reads as damage; one made on purpose, with +/// that line made right again, can only make the key come out different, +/// which opens nothing: no passphrase is guessed faster by it.) +fn header_aad(kdf: &Kdf) -> Vec { + format!( + "wb1|header|{}|{}|{}|{}|{}", + kdf.alg, kdf.m, kdf.t, kdf.p, kdf.salt + ) + .into_bytes() +} + fn stretch(passphrase: &str, kdf: &Kdf) -> Result, BackupError> { if !kdf_in_bounds(kdf) { return Err(BackupError::Damaged( @@ -207,16 +229,32 @@ impl BackupKey { Err(e) => Err(e.into()), } } +} - /// Derive the key `passphrase` makes from what a sealed set's header - /// says: [`BackupError::WrongPassphrase`] when it opens nothing, - /// [`BackupError::Damaged`] when the header itself is not whole. - pub(crate) fn from_header(passphrase: &str, header: &Header) -> Result { - let master = stretch(passphrase, &header.kdf)?; - let key = Self { +impl BackupKey { + /// The key `passphrase` makes under `header`'s settings, derived once + /// for each distinct setting in `cache`: a folder of many sealed sets + /// made with one passphrase costs one derivation, not one per set. + pub(crate) fn from_header_cached( + passphrase: &str, + header: &Header, + cache: &mut Vec<(Kdf, Result)>, + ) -> Result { + if let Some((_, got)) = cache.iter().find(|(k, _)| *k == header.kdf) { + return match got { + Ok(key) => { + key.keys().check(header)?; + Ok(key.clone()) + } + Err(e) => Err(e.clone()), + }; + } + let derived = stretch(passphrase, &header.kdf).map(|master| Self { kdf: header.kdf.clone(), master, - }; + }); + cache.push((header.kdf.clone(), derived.clone())); + let key = derived?; key.keys().check(header)?; Ok(key) } @@ -281,7 +319,7 @@ impl Keys { /// The header for a set sealed with these keys. pub(crate) fn header(&self) -> Header { let mut sealed = Vec::new(); - self.seal_stream(&mut &CHECK_TEXT[..], &mut sealed, b"wb1|header") + self.seal_stream(&mut &CHECK_TEXT[..], &mut sealed, &header_aad(&self.kdf)) .expect("sealing into memory"); Header { format: HEADER_FORMAT.into(), @@ -300,7 +338,7 @@ impl Keys { .filter(|s| sha_hex(s) == header.check_sha256) .ok_or_else(|| BackupError::Damaged("the sealed backup's header was changed".into()))?; let mut plain = Vec::new(); - match self.open_stream(&mut &sealed[..], b"wb1|header", &mut |b| { + match self.open_stream(&mut &sealed[..], &header_aad(&header.kdf), &mut |b| { plain.extend_from_slice(b); Ok(()) }) { diff --git a/crates/ledger-store/src/backup/single.rs b/crates/ledger-store/src/backup/single.rs index 46e04a56..9d97054b 100644 --- a/crates/ledger-store/src/backup/single.rs +++ b/crates/ledger-store/src/backup/single.rs @@ -164,7 +164,7 @@ pub fn save_file( keys: key.map(|k| k.keys()), ctx: ctx.clone(), }; - let result = write_into_set(&set, cut, ctx).and_then(|written| { + let result = write_into_set(&set, cut, ctx, false).and_then(|written| { // The zip's directory, then the file's. let writer = lock(&shared) .take() diff --git a/crates/ledger-store/src/backup/write.rs b/crates/ledger-store/src/backup/write.rs index 576c1afe..a46b55db 100644 --- a/crates/ledger-store/src/backup/write.rs +++ b/crates/ledger-store/src/backup/write.rs @@ -5,11 +5,11 @@ use super::cut::Cut; use super::form::*; use super::io::{Fill, Put, PutKind, carry, uncarry}; -use super::read::{Hashed, Set}; +use super::read::{Hashed, Set, Sink}; use super::seal::{BackupKey, Keys, piece_aad}; use super::{BackupError, Ctx, READ_ME_TEXT}; use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; @@ -40,40 +40,110 @@ pub struct Written { /// False when the destination already held exactly these books: no /// manifest was written. pub new: bool, + /// Pieces the proof after the backup found damaged or missing, which + /// were written again under a new generation (named as they are in the + /// set, never as a path of the data root). The damaged files stay + /// where they are. + pub repaired: Vec, + /// Stored files the proof after the backup re-read. + pub files_proven: u64, } -/// The folder a set of books has in a destination when it is not sealed: -/// named for the books. +/// What a write is asked to do about the destination's sets. +#[derive(Debug, Clone, Copy, Default)] +pub struct Options { + /// The destination may be begun (it never took these books' backup). + pub may_create: bool, + /// Begin a new set beside the one there (the person's own request, + /// when the destination holds a longer history of these books than + /// the books now have): the old set is never touched. + pub new_set: bool, +} + +/// The folder the first set of `book` has in a destination when it is not +/// sealed: a fixed prefix and the id, a legal name on every system. pub fn set_name_for(book: &str) -> String { - book.to_string() + plain_set_name(book, 1) } -/// The set of `book` in the destination: for a plain one, the folder named -/// for the books; for a sealed one, the folder whose header this key opens -/// and whose backups are these books' (or none yet). None when it is not -/// there. -pub(crate) fn locate( - dest: &Destination, - book: &str, - ctx: &Ctx, -) -> Result, BackupError> { +/// The number a set folder name ends in (`.2`, `.3`), 1 for none, and the +/// name without it. +fn split_set_suffix(name: &str) -> (&str, u32) { + match name.rsplit_once('.') { + Some((base, n)) => match n.parse::() { + Ok(n) if n >= 2 => (base, n), + _ => (name, 1), + }, + None => (name, 1), + } +} + +/// Whether the folder holds sets that are sealed and none of the plain +/// kind for `book`: backups were made protected by a passphrase there. +/// (A destination looked at when this computer has no key for it.) +pub fn holds_only_sealed(folder: &Path, book: &str) -> bool { + let Ok(entries) = std::fs::read_dir(folder) else { + return false; + }; + let (mut sealed, mut plain) = (false, false); + for e in entries.flatten() { + let Some(name) = e.file_name().to_str().map(str::to_string) else { + continue; + }; + if name.starts_with(SEALED_PREFIX) && e.path().join(HEADER).is_file() { + sealed = true; + } + if parse_plain_set_name(&name).is_some_and(|(b, _)| b == book) { + plain = true; + } + } + sealed && !plain +} + +/// The sets of `book` in the destination, oldest first, each with the +/// folder name it has: for a plain one, the folders named for the books +/// (`wanderbooks-`, `wanderbooks-.2`); for a sealed one, the +/// folders whose header this key opens and whose backups are these books' +/// (or none yet). +fn sets_of(dest: &Destination, book: &str, ctx: &Ctx) -> Result, BackupError> { + let mut found: Vec<(String, Set)> = Vec::new(); + let Ok(entries) = std::fs::read_dir(&dest.folder) else { + return Ok(found); + }; + let mut names: Vec = entries + .flatten() + .filter_map(|e| e.file_name().to_str().map(str::to_string)) + .collect(); + names.sort(); match &dest.key { None => { - let dir = dest.folder.join(set_name_for(book)); - Ok(dir.is_dir().then(|| Set::dir(dir, None, ctx))) + let mut plain: Vec<(u32, String)> = names + .into_iter() + .filter_map(|n| match parse_plain_set_name(&n) { + Some((b, number)) if b == book => Some((number, n.clone())), + _ => None, + }) + .collect(); + plain.sort(); + for (_, name) in plain { + let dir = dest.folder.join(&name); + if dir.is_dir() { + found.push((name, Set::dir(dir, None, ctx))); + } + } } Some(key) => { let keys = key.keys(); - let Ok(entries) = std::fs::read_dir(&dest.folder) else { - return Ok(None); - }; - let mut names: Vec = entries - .flatten() - .filter_map(|e| e.file_name().to_str().map(str::to_string)) + let mut sealed: Vec<(String, u32, String)> = names + .into_iter() .filter(|n| n.starts_with(SEALED_PREFIX)) + .map(|n| { + let (base, number) = split_set_suffix(&n); + (base.to_string(), number, n.clone()) + }) .collect(); - names.sort(); - for name in names { + sealed.sort(); + for (_, _, name) in sealed { let dir = dest.folder.join(&name); let Ok(raw) = std::fs::read(dir.join(HEADER)) else { continue; @@ -87,12 +157,32 @@ pub(crate) fn locate( let set = Set::dir(dir, Some(key.keys()), ctx); match set.newest_whole()? { Some((m, _)) if m.book != book => continue, - _ => return Ok(Some(set)), + _ => found.push((name, set)), } } - Ok(None) } } + Ok(found) +} + +/// The set of `book` in the destination that its backups go to: the +/// newest of its sets. None when it is not there. +pub(crate) fn locate( + dest: &Destination, + book: &str, + ctx: &Ctx, +) -> Result, BackupError> { + Ok(current_of(sets_of(dest, book, ctx)?).map(|(_, set)| set)) +} + +/// The set backups go to among `sets` (oldest first): of those that share +/// the first one's name, the newest. +fn current_of(sets: Vec<(String, Set)>) -> Option<(String, Set)> { + let base = sets + .first() + .map(|(n, _)| split_set_suffix(n).0.to_string())?; + sets.into_iter() + .rfind(|(n, _)| split_set_suffix(n).0 == base) } /// One thing to put before the manifest. @@ -122,6 +212,22 @@ fn stored_len(keys: Option<&Keys>, plain: u64) -> u64 { } } +/// Where a piece to be written goes: `path` itself, unless that file is +/// one a proof found damaged, in which case the next generation of it (so +/// the damaged file stays where it is and the piece is written beside it). +/// A generation that is there already and not known damaged is taken: it +/// is a repair that a run before made. +fn fresh_path(path: &str, distrust: &BTreeSet) -> String { + if !distrust.contains(path) { + return path.to_string(); + } + let (stem, _) = split_generation(path); + (1u32..) + .map(|g| generation_path(stem, g)) + .find(|c| !distrust.contains(c)) + .expect("an unbounded count has one") +} + /// Hash `path` from 0 to `len`: the whole, the part before `mid`, and the /// part from `mid`. fn hash_range( @@ -156,11 +262,60 @@ fn hash_range( Ok((h(all), h(before), h(after))) } +/// A hash of the first `limit` bytes handed to it. +struct PrefixHash { + hasher: Sha256, + taken: u64, + limit: u64, + at: (Sha256, u64), +} + +impl Sink for PrefixHash { + fn put(&mut self, chunk: &[u8]) -> std::io::Result<()> { + let room = self + .limit + .saturating_sub(self.taken) + .min(chunk.len() as u64) as usize; + self.hasher.update(&chunk[..room]); + self.taken += chunk.len() as u64; + Ok(()) + } + fn mark(&mut self) { + self.at = (self.hasher.clone(), self.taken); + } + fn rewind(&mut self) -> std::io::Result<()> { + self.hasher = self.at.0.clone(); + self.taken = self.at.1; + Ok(()) + } +} + +/// Whether the live journal's first `len` bytes (hashing to `live`) are +/// the first `len` bytes of the destination's longer journal `series`. +fn live_is_prefix_of( + set: &Set, + series: &Series, + len: u64, + live: &str, +) -> Result { + let mut sink = PrefixHash { + hasher: Sha256::new(), + taken: 0, + limit: len, + at: (Sha256::new(), 0), + }; + set.read_series(series, Kind::Journal, &mut sink)?; + Ok(hex::encode(sink.hasher.finalize()) == live) +} + /// Grow the series of the live file `path` (`len` bytes of whole lines) -/// from `base`, the destination's: a new segment of the bytes it lacks. -/// The journal's must continue the destination's exactly (`strict`: -/// otherwise the books are not the same); an access log that does not is -/// begun again whole. +/// from `base`, the destination's: a new segment of the bytes it lacks; +/// and a segment of the base that is in `distrust` (a proof found it +/// damaged) written again from the live file under a new generation. The +/// journal's must continue the destination's exactly (`strict`: otherwise +/// the books are not the same); an access log that does not is begun +/// again whole. +#[allow(clippy::too_many_arguments)] fn grow( path: &Path, len: u64, @@ -168,8 +323,9 @@ fn grow( kind: Kind, strict: bool, keys: Option<&Keys>, + distrust: &BTreeSet, ctx: &Ctx, -) -> Result<(Series, Option), BackupError> { +) -> Result<(Series, Vec), BackupError> { let empty = Series::default(); let mut base = base.unwrap_or(&empty); if base.bytes > len { @@ -186,44 +342,60 @@ fn grow( } base = ∅ } + let mut plans = Vec::new(); + let mut series = base.clone(); + series.keep = 0; + // Segments of the base that were found damaged: written again from the + // live file (their bytes are the live file's, at the offsets the + // segments before them add up to). + let mut offset = 0u64; + for seg in &mut series.segments { + if distrust.contains(&seg.file) { + let file = fresh_path(&seg.file, distrust); + let piece = Piece { + file: file.clone(), + ..seg.clone() + }; + plans.push(Plan::Range { + path: path.to_path_buf(), + from: offset, + to: offset + seg.bytes, + kind, + piece, + }); + seg.file = file; + } + offset += seg.bytes; + } if base.bytes == len { - return Ok((base.clone(), None)); + return Ok((series, plans)); } - let consolidate = base.segments.len() >= CONSOLIDATE_AT; // `after` was hashed from the base's end: with a different base, from // the whole. - let (from, seg_sha, ordinal, mut segments) = if consolidate || base.bytes == 0 { - (0, all.clone(), 0, Vec::new()) + let (from, seg_sha) = if base.bytes == 0 { + (0, all.clone()) } else { - ( - base.bytes, - after, - base.segments.len(), - base.segments.clone(), - ) + (base.bytes, after) }; let bytes = len - from; + let ordinal = series.segments.len(); let piece = Piece { - file: piece_path(keys, kind, ordinal, &seg_sha), + file: fresh_path(&piece_path(keys, kind, ordinal, &seg_sha), distrust), stored: stored_len(keys, bytes), bytes, sha256: seg_sha, }; - segments.push(piece.clone()); - Ok(( - Series { - bytes: len, - sha256: all, - segments, - }, - Some(Plan::Range { - path: path.to_path_buf(), - from, - to: len, - kind, - piece, - }), - )) + series.segments.push(piece.clone()); + series.bytes = len; + series.sha256 = all; + plans.push(Plan::Range { + path: path.to_path_buf(), + from, + to: len, + kind, + piece, + }); + Ok((series, plans)) } /// `&mut dyn Write` as a `Write` that `io::copy` takes. @@ -246,7 +418,7 @@ fn put_piece( piece: &Piece, plain: &mut dyn Read, ctx: &Ctx, -) -> Result<(), BackupError> { +) -> Result { ctx.check("backing up")?; let mut hashed = Hashed::new(plain, ctx); let keys = set.keys.as_ref(); @@ -271,11 +443,10 @@ fn put_piece( let fill_ref: Fill<'_> = &mut fill; set.io .put(&piece.file, PutKind::Piece, fill_ref) - .map_err(uncarry)?; - Ok(()) + .map_err(uncarry) } -fn execute(set: &Set, plan: &Plan, ctx: &Ctx) -> Result<(), BackupError> { +fn execute(set: &Set, plan: &Plan, ctx: &Ctx) -> Result { match plan { Plan::Range { path, @@ -310,6 +481,7 @@ fn named_pieces( files: &[(String, Vec)], kind: Kind, keys: Option<&Keys>, + distrust: &BTreeSet, plans: &mut Vec, ) -> Vec { files @@ -317,7 +489,7 @@ fn named_pieces( .map(|(name, bytes)| { let sha = sha_hex(bytes); let piece = Piece { - file: piece_path(keys, kind, 0, &sha), + file: fresh_path(&piece_path(keys, kind, 0, &sha), distrust), stored: stored_len(keys, bytes.len() as u64), bytes: bytes.len() as u64, sha256: sha, @@ -336,11 +508,16 @@ fn named_pieces( } /// What to put, and the manifest that says it is whole once it is there -/// (its number and time are the writer's, last). +/// (its number and time are the writer's, last), and the stored files the +/// plan puts (for the proof after the backup to read). +/// +/// `distrust` holds the files a proof found damaged: each is written +/// again under a new generation and named so. fn plan( set: &Set, prev: Option<&Manifest>, cut: &Cut, + distrust: &BTreeSet, ctx: &Ctx, ) -> Result<(Manifest, Vec), BackupError> { let keys = set.keys.as_ref(); @@ -350,7 +527,16 @@ fn plan( return Err(BackupError::Elsewhere); } if p.journal.bytes > cut.journal_len { - return Err(BackupError::Ahead(p.head.seq, cut.head().0)); + // A longer history: of these books (the live journal is the + // beginning of it), or of others. + let (live, _, _) = hash_range(&cut.journal_path(), cut.journal_len, 0, ctx)?; + return Err( + if live_is_prefix_of(set, &p.journal, cut.journal_len, &live)? { + BackupError::Ahead(p.head.seq, cut.head().0) + } else { + BackupError::Elsewhere + }, + ); } } let (journal, put) = grow( @@ -360,6 +546,7 @@ fn plan( Kind::Journal, true, keys, + distrust, ctx, )?; plans.extend(put); @@ -370,59 +557,92 @@ fn plan( Kind::Access, false, keys, + distrust, ctx, )?; plans.extend(put); - // The index of stored files: the new ones, as a segment. + // The index of stored files: the new ones, as a segment. An index that + // can't be read whole (a segment of it is damaged) is begun again from + // the stored files the books have now. ctx.phase("files"); let live = cut.stored_files(ctx)?; + let mut restart = false; let known: Vec = match prev { - Some(p) => set.index(p)?, + Some(p) => { + if p.files.segments.iter().any(|s| distrust.contains(&s.file)) { + restart = true; + Vec::new() + } else { + match set.index(p) { + Ok(k) => k, + Err(BackupError::Damaged(_)) => { + restart = true; + Vec::new() + } + Err(e) => return Err(e), + } + } + } None => Vec::new(), }; let known_set: BTreeMap<&str, u64> = known.iter().map(|l| (l.sha256.as_str(), l.bytes)).collect(); let new: Vec = live - .into_iter() + .iter() .filter(|l| !known_set.contains_key(l.sha256.as_str())) + .cloned() .collect(); - let (files, file_count, file_bytes) = match (prev, new.is_empty()) { + // Stored files found damaged: written again, named by their hash and + // generation (the index doesn't say where; the reader looks). + for l in &live { + let path = piece_path(keys, Kind::File, 0, &l.sha256); + if distrust.contains(&path) && known_set.contains_key(l.sha256.as_str()) { + plans.push(Plan::File { + path: cut.blob_path(&l.sha256), + piece: Piece { + file: fresh_path(&path, distrust), + stored: stored_len(keys, l.bytes), + bytes: l.bytes, + sha256: l.sha256.clone(), + }, + }); + } + } + let (files, file_count, file_bytes) = match (prev, new.is_empty() && !restart) { (_, true) => prev .map(|p| (p.files.clone(), p.file_count, p.file_bytes)) .unwrap_or_default(), _ => { - let base = prev.map(|p| &p.files).cloned().unwrap_or_default(); - let consolidate = base.segments.len() >= CONSOLIDATE_AT; + let mut base = if restart { + Series::default() + } else { + prev.map(|p| p.files.clone()).unwrap_or_default() + }; + base.keep = 0; let mut union: Vec = known.clone(); union.extend(new.iter().cloned()); let count = union.len() as u64; let total = union.iter().fold(0u64, |a, l| a.saturating_add(l.bytes)); - let seg_lines = if consolidate { &union } else { &new }; - let text = index_text(seg_lines); + let text = index_text(&new); let seg_sha = sha_hex(&text); - let ordinal = if consolidate { 0 } else { base.segments.len() }; let piece = Piece { - file: piece_path(keys, Kind::Index, ordinal, &seg_sha), + file: fresh_path( + &piece_path(keys, Kind::Index, base.segments.len(), &seg_sha), + distrust, + ), stored: stored_len(keys, text.len() as u64), bytes: text.len() as u64, sha256: seg_sha, }; - let mut segments = if consolidate { - Vec::new() - } else { - base.segments.clone() - }; + let mut segments = base.segments.clone(); segments.push(piece.clone()); // The whole index's hash: the segments one after another. - let mut all_text = Vec::new(); - if !consolidate { - set.read_series(&base, Kind::Index, &mut |c| { - all_text.extend_from_slice(c); - Ok(()) - })?; + let mut all_text = VecSinkText::default(); + if !base.segments.is_empty() { + set.read_series(&base, Kind::Index, &mut all_text)?; } - all_text.extend_from_slice(&text); + all_text.0.extend_from_slice(&text); plans.push(Plan::Bytes { kind: Kind::Index, piece, @@ -432,7 +652,7 @@ fn plan( plans.push(Plan::File { path: cut.blob_path(&l.sha256), piece: Piece { - file: piece_path(keys, Kind::File, 0, &l.sha256), + file: fresh_path(&piece_path(keys, Kind::File, 0, &l.sha256), distrust), stored: stored_len(keys, l.bytes), bytes: l.bytes, sha256: l.sha256.clone(), @@ -441,17 +661,18 @@ fn plan( } ( Series { - bytes: all_text.len() as u64, - sha256: sha_hex(&all_text), + bytes: all_text.0.len() as u64, + sha256: sha_hex(&all_text.0), segments, + keep: 0, }, count, total, ) } }; - let vault = named_pieces(&cut.vault, Kind::Vault, keys, &mut plans); - let keyed = named_pieces(&cut.keys, Kind::Key, keys, &mut plans); + let vault = named_pieces(&cut.vault, Kind::Vault, keys, distrust, &mut plans); + let keyed = named_pieces(&cut.keys, Kind::Key, keys, distrust, &mut plans); let manifest = Manifest { format: FORMAT.into(), version: VERSION, @@ -469,10 +690,58 @@ fn plan( file_bytes, vault, keys: keyed, + base: None, + depth: 0, + sha: String::new(), }; Ok((manifest, plans)) } +/// Text gathered as a series is read. +#[derive(Default)] +struct VecSinkText(Vec); + +impl Sink for VecSinkText { + fn put(&mut self, chunk: &[u8]) -> std::io::Result<()> { + self.0.extend_from_slice(chunk); + Ok(()) + } + fn mark(&mut self) {} + fn rewind(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// The manifest as it is kept: when `prev` (whole, as read) is a link in a +/// chain that is not yet [`DELTA_CHAIN`] long, built on it, naming only +/// what each series adds to its segments. Otherwise it names everything. +fn kept_form(full: &Manifest, prev: Option<&Manifest>) -> Manifest { + let mut m = full.clone(); + let Some(p) = prev.filter(|p| p.depth + 1 < DELTA_CHAIN && !p.sha.is_empty()) else { + return m; + }; + m.base = Some(BaseRef { + number: p.number, + sha256: p.sha.clone(), + }); + m.depth = p.depth + 1; + for (mine, theirs) in [ + (&mut m.journal, &p.journal), + (&mut m.access, &p.access), + (&mut m.files, &p.files), + ] { + let keep = mine + .segments + .iter() + .zip(&theirs.segments) + .take_while(|(a, b)| a == b) + .count(); + mine.segments = mine.segments.split_off(keep); + mine.keep = keep; + } + m +} + /// The read-me, and for a sealed set its header: put once. fn ensure_markers(set: &Set) -> Result<(), BackupError> { set.io.put(READ_ME, PutKind::Once, &mut |w| { @@ -503,8 +772,125 @@ fn now() -> String { chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) } -/// Write the cut into the set (INVARIANTS 2, 4, 5). -pub(crate) fn write_into_set(set: &Set, cut: &Cut, ctx: &Ctx) -> Result { +/// Put the manifest `full` (its number and time are filled in here) as the +/// next number in the set, built on `prev`. The number it took, or None +/// when another program took the number first. +fn put_manifest( + set: &Set, + full: &mut Manifest, + prev: Option<&Manifest>, + next: u64, + ctx: &Ctx, +) -> Result, BackupError> { + full.number = next; + full.written = now(); + let kept = kept_form(full, prev); + let mut bytes = encode_manifest(&kept); + if let Some(k) = &set.keys { + bytes = k.seal_bytes(&bytes, &super::seal::manifest_aad(next)); + } + ctx.phase("manifest"); + ctx.check("backing up")?; + let put = set + .io + .put( + &manifest_path(next, set.sealed()), + PutKind::Manifest, + &mut |w| w.write_all(&bytes), + ) + .map_err(uncarry)?; + Ok((put == Put::Created).then_some(next)) +} + +/// A folder for the proof's scratch books: private, in the book's own +/// `ops/`, named for this call. +fn proof_scratch(cut: &Cut) -> Result { + let ops = crate::root::private_book_folder(cut.dir(), crate::ops::OPS_DIR) + .map_err(|e| BackupError::Damaged(e.to_string()))?; + let mut r = [0u8; 6]; + let _ = getrandom::getrandom(&mut r); + Ok(ops.join(format!("proof-{}", hex::encode(r)))) +} + +/// The most times a backup is written again to repair what its own proof +/// found damaged. +const REPAIR_ROUNDS: usize = 2; + +/// Prove the manifest `number` just put, and repair what the proof finds +/// damaged (a piece already there under the name, taken as the piece, that +/// is not): written again under a new generation, a new manifest naming +/// it, proven again. What the proof found is in `repaired`. +fn prove_and_repair( + set: &Set, + cut: &Cut, + mut number: u64, + mut added: BTreeSet, + ctx: &Ctx, +) -> Result { + let mut distrust: BTreeSet = BTreeSet::new(); + let mut repaired: Vec = Vec::new(); + for round in 0..=REPAIR_ROUNDS { + ctx.phase("proof"); + ctx.check("proving the backup")?; + let proof = super::read::prove_written(set, number, &added, &proof_scratch(cut)?)?; + if proof.damaged.is_empty() { + return Ok(Written { + number, + head: cut.head().clone(), + new: true, + repaired, + files_proven: proof.files_read, + }); + } + for d in &proof.damaged { + if !repaired.contains(&d.file) { + repaired.push(d.file.clone()); + } + distrust.insert(d.file.clone()); + } + if round == REPAIR_ROUNDS { + break; + } + // Written again beside the damaged ones, and a manifest naming + // them (the stored files are found by their hash and generation). + ctx.phase("repair"); + let prev = set.manifest(number)?; + let (mut manifest, plans) = plan(set, Some(&prev), cut, &distrust, ctx)?; + added = BTreeSet::new(); + for p in &plans { + ctx.check("backing up")?; + if execute(set, p, ctx)? == Put::Created + && let Plan::File { piece, .. } = p + { + added.insert(piece.sha256.clone()); + } + } + if !manifest.same_content(&prev) { + let mut taken = None; + for _ in 0..ATTEMPTS { + let next = set.numbers()?.last().map_or(1, |n| n + 1); + taken = put_manifest(set, &mut manifest, Some(&prev), next, ctx)?; + if taken.is_some() { + break; + } + } + number = taken.ok_or(BackupError::Busy)?; + } + } + Err(BackupError::Damaged( + "a piece of the backup was found damaged and could not be made whole again from the books" + .into(), + )) +} + +/// Write the cut into the set (INVARIANTS 2, 4, 5); with `prove`, then +/// read the manifest back and prove it, repairing what is damaged. +pub(crate) fn write_into_set( + set: &Set, + cut: &Cut, + ctx: &Ctx, + prove: bool, +) -> Result { ensure_markers(set)?; for _ in 0..ATTEMPTS { ctx.check("backing up")?; @@ -512,7 +898,7 @@ pub(crate) fn write_into_set(set: &Set, cut: &Cut, ctx: &Ctx) -> Result Result { + match put_manifest(set, &mut manifest, prev.as_ref(), next, ctx)? { + Some(number) if prove => return prove_and_repair(set, cut, number, added, ctx), + Some(number) => { return Ok(Written { - number: next, + number, head: cut.head().clone(), new: true, + repaired: Vec::new(), + files_proven: 0, }); } // Another program took the number: look again. - Put::Existed => continue, + None => continue, } } Err(BackupError::Busy) @@ -567,25 +947,58 @@ pub fn write_destination( cut: &Cut, may_create: bool, ctx: &Ctx, +) -> Result { + write_destination_with( + dest, + cut, + Options { + may_create, + new_set: false, + }, + ctx, + ) +} + +/// [`write_destination`], with what is asked of the destination's sets +/// ([`Options`]). +pub fn write_destination_with( + dest: &Destination, + cut: &Cut, + opts: Options, + ctx: &Ctx, ) -> Result { if !dest.folder.is_dir() { return Err(BackupError::NoFolder); } - let set = match locate(dest, cut.book(), ctx)? { - Some(set) => set, - None if !may_create => return Err(BackupError::NoBackupThere), - None => match &dest.key { - None => Set::dir(dest.folder.join(set_name_for(cut.book())), None, ctx), - Some(key) => { - let mut id = [0u8; 8]; - getrandom::getrandom(&mut id) - .map_err(|e| BackupError::Io(std::io::Error::from(e).kind()))?; - let name = format!("{SEALED_PREFIX}{}", hex::encode(id)); - Set::dir(dest.folder.join(name), Some(key.keys()), ctx) - } - }, + let sets = sets_of(dest, cut.book(), ctx)?; + let set = if opts.new_set && !sets.is_empty() { + // A new set beside the old one, which is never touched: the old + // folder's name and the next number. + let (name, _) = current_of(sets).expect("there is one"); + let (base, number) = split_set_suffix(&name); + let next = format!("{base}.{}", number + 1); + Set::dir( + dest.folder.join(next), + dest.key.as_ref().map(|k| k.keys()), + ctx, + ) + } else { + match current_of(sets) { + Some((_, set)) => set, + None if !opts.may_create => return Err(BackupError::NoBackupThere), + None => match &dest.key { + None => Set::dir(dest.folder.join(set_name_for(cut.book())), None, ctx), + Some(key) => { + let mut id = [0u8; 8]; + getrandom::getrandom(&mut id) + .map_err(|e| BackupError::Io(std::io::Error::from(e).kind()))?; + let name = format!("{SEALED_PREFIX}{}", hex::encode(id)); + Set::dir(dest.folder.join(name), Some(key.keys()), ctx) + } + }, + } }; - write_into_set(&set, cut, ctx) + write_into_set(&set, cut, ctx, true) } /// Write the cut to the book's own local backup (`local-backup/` in its diff --git a/crates/ledger-store/tests/backup.rs b/crates/ledger-store/tests/backup.rs index 606fa058..4b0d4130 100644 --- a/crates/ledger-store/tests/backup.rs +++ b/crates/ledger-store/tests/backup.rs @@ -126,10 +126,25 @@ fn a_backup_is_the_book_and_proves_whole() { // the journal as a segment, the stored file under its hash. let t = tree(&disk); let names: Vec<&String> = t.keys().collect(); - assert!(names.iter().any(|n| *n == "acme/READ-ME.txt"), "{names:?}"); - assert!(names.iter().any(|n| *n == "acme/manifests/000001.json")); - assert!(names.iter().any(|n| n.starts_with("acme/journal/000001-"))); - assert!(names.iter().any(|n| n.starts_with("acme/files/"))); + assert!( + names.iter().any(|n| *n == "wanderbooks-acme/READ-ME.txt"), + "{names:?}" + ); + assert!( + names + .iter() + .any(|n| *n == "wanderbooks-acme/manifests/000001.json") + ); + assert!( + names + .iter() + .any(|n| n.starts_with("wanderbooks-acme/journal/000001-")) + ); + assert!( + names + .iter() + .any(|n| n.starts_with("wanderbooks-acme/files/")) + ); assert!(!names.iter().any(|n| n.contains(".git"))); // Nothing new: no manifest. @@ -522,13 +537,13 @@ fn a_damaged_newest_backup_falls_back_to_the_one_before_and_says_so() { more(&mut s, 1); write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); // Flip a byte in the second journal segment. - let seg = tree(&disk.join("acme")) + let seg = tree(&disk.join("wanderbooks-acme")) .keys() .filter(|n| n.starts_with("journal/")) .max() .cloned() .unwrap(); - let path = disk.join("acme").join(&seg); + let path = disk.join("wanderbooks-acme").join(&seg); let mut bytes = std::fs::read(&path).unwrap(); bytes[3] ^= 1; std::fs::write(&path, bytes).unwrap(); @@ -643,7 +658,7 @@ fn two_programs_writing_one_destination_do_not_corrupt_it() { // manifest there stands alone. let v = prove(&disk, None, dir.path(), &format!("v{round}")).unwrap(); assert_eq!(v.head, s.head()); - let set = disk.join("acme"); + let set = disk.join("wanderbooks-acme"); for n in std::fs::read_dir(set.join("manifests")).unwrap().flatten() { assert!(n.file_name().to_string_lossy().ends_with(".json")); } @@ -680,7 +695,7 @@ fn a_loser_of_a_manifest_number_goes_on_from_the_winner() { assert_eq!(w.head, s.head()); assert!(!w.new, "the winner's manifest already says it"); assert_eq!( - std::fs::read_dir(disk.join("acme/manifests")) + std::fs::read_dir(disk.join("wanderbooks-acme/manifests")) .unwrap() .count(), 1 @@ -756,7 +771,7 @@ fn a_purged_vault_leaves_the_next_backup_and_not_the_earlier_ones() { ); let then = dir.path().join("then"); copy_tree(&disk, &then); - std::fs::remove_file(then.join("acme/manifests/000002.json")).unwrap(); + std::fs::remove_file(then.join("wanderbooks-acme/manifests/000002.json")).unwrap(); let old = prove(&then, None, dir.path(), "old").unwrap(); assert_eq!( std::fs::read(old.tree.join("vault").join("tin-1.bin")).unwrap(), @@ -774,7 +789,7 @@ fn a_scratch_file_left_by_a_dead_program_never_stops_the_next_backup() { write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); // What a program that died leaves: a scratch file, a short manifest at // the next number (its number is spent), a piece cut short. - let set = disk.join("acme"); + let set = disk.join("wanderbooks-acme"); std::fs::write(set.join("manifests").join(".wb-tmp-9-abcdef"), b"half").unwrap(); std::fs::write( set.join("manifests").join("000002.json"), @@ -825,6 +840,7 @@ fn a_drill_proves_this_books_history_only() { "acme", &b1.join("journal.jsonl"), &dir.path().join("d1"), + None, &Ctx::new(), ) .unwrap(); @@ -836,6 +852,7 @@ fn a_drill_proves_this_books_history_only() { "acme", &b2.join("journal.jsonl"), &dir.path().join("d2"), + None, &Ctx::new(), ) .unwrap_err(); @@ -891,7 +908,7 @@ fn a_link_in_a_backup_is_never_followed() { write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); // The journal's piece replaced by a link to a file elsewhere with the // same bytes: it is no piece of the backup. - let set = disk.join("acme"); + let set = disk.join("wanderbooks-acme"); let piece = std::fs::read_dir(set.join("journal")) .unwrap() .next() @@ -937,6 +954,7 @@ fn a_drill_stops_inside_the_phase_it_is_told_to_stop_in() { "acme", &b.join("journal.jsonl"), &scratch, + None, &ctx, ); assert!( diff --git a/crates/ledger-store/tests/backup_props.rs b/crates/ledger-store/tests/backup_props.rs index 7c8bbc58..24560aaa 100644 --- a/crates/ledger-store/tests/backup_props.rs +++ b/crates/ledger-store/tests/backup_props.rs @@ -198,7 +198,7 @@ proptest! { copy_tree(&disk, &then); for (name, _) in tree(&then) { if let Some(n) = name - .strip_prefix("acme/manifests/") + .strip_prefix("wanderbooks-acme/manifests/") .and_then(|r| r.strip_suffix(".json")) .and_then(|r| r.parse::().ok()) && n > *number @@ -276,7 +276,7 @@ proptest! { books.apply(op); } write_destination(&plain(&disk), &books.cut(), true, &Ctx::new()).unwrap(); - let set = disk.join("acme"); + let set = disk.join("wanderbooks-acme"); let pieces: Vec = tree(&set) .into_keys() .filter(|n| !n.starts_with("manifests/") && n != "READ-ME.txt")