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 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 19:10:34 -07:00
1 parent 49459c9f6a
commit 6a8dc6c88b
14 files changed
+2116 -439

No files matched your search

+27 -16
View File
@@ -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(&copy).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(&copy, "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::<String>::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);
copy_dir(&folder.join("wanderbooks-acme"), &copy);
spoil(&copy);
let why = restore(&home, "acme-bad", &copy, 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);
copy_dir(&folder.join("wanderbooks-acme"), &copy);
for f in files_below(&copy, 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, &copy);
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", &copy, 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<Vec<u8>> = sealed_before
.iter()
.map(|p| std::fs::read(p).unwrap())
+5 -5
View File
@@ -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();
}
+250 -37
View File
@@ -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<dyn Fn(&str) + Send + Sync>;
@@ -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<String>,
/// 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<String>,
}
/// 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<Destination, String>,
/// 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<Destination, BackupError>,
/// 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<String, Value>]) -> Option<(bool, Option<String>)> {
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<Map<String, Value>> {
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<Named> {
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<Destination, BackupError>, sealed: bool, fp: &str| Named {
dest,
at: at.clone(),
key: digest(fp),
sealed,
}]
};
let dest = |key: Option<BackupKey>| 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<Status, String> {
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<Status, String> {
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::<Vec<_>>(),
"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<String>,
/// 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<String>,
}
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<Vec<String>, String> {
let done = tokio::task::spawn_blocking(move || -> Result<SetUpDone, String> {
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<String>)> = 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<String>, Option<(String, Option<String>)>);
/// 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<String, Value>, field: &str) -> Option<String> {
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<String, Value>]) -> 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<String, Value>]) -> 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<String> = 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,
+2
View File
@@ -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,
+53 -5
View File
@@ -75,14 +75,40 @@ fn whole_lines(path: &Path, len: u64) -> std::io::Result<u64> {
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<Scratch<'_>> {
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<Vec<(String, Vec<u8>)>, 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<Vec<(String, Vec<u8>)>, 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<Vec<(String, Vec<u8>)>, 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<String> = 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
+102 -7
View File
@@ -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<Piece>,
/// 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<Named>,
/// The keys.
pub keys: Vec<Named>,
/// 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<BaseRef>,
/// 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<u64> {
/// 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::<u32>()
&& 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::<u32>().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<u8> {
@@ -223,7 +314,8 @@ pub(crate) fn decode_manifest(bytes: &[u8]) -> Result<Manifest, BackupError> {
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
}
+255 -49
View File
@@ -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<Put> {
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<Option<u64>> {
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);
+71 -4
View File
@@ -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<String>,
/// When the newest one that proves whole was made (None: none does).
older_from: Option<String>,
},
/// The passphrase given opens nothing.
#[error("that isn't the passphrase this backup was made with")]
WrongPassphrase,
@@ -166,6 +191,19 @@ impl From<crate::StoreError> 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<dyn Fn(&str) + Send + Sync>;
@@ -181,6 +219,10 @@ pub struct Ctx {
stop: Option<Arc<AtomicBool>>,
faults: Option<Faults>,
phase: Option<PhaseWatch>,
/// 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);
File diff suppressed because it is too large. Load diff
+51 -13
View File
@@ -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<u8> {
format!(
"wb1|header|{}|{}|{}|{}|{}",
kdf.alg, kdf.m, kdf.t, kdf.p, kdf.salt
)
.into_bytes()
}
fn stretch(passphrase: &str, kdf: &Kdf) -> Result<Zeroizing<[u8; 32]>, 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<Self, BackupError> {
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<BackupKey, BackupError>)>,
) -> Result<Self, BackupError> {
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(())
}) {
+1 -1
View File
@@ -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()
+542 -129
View File
@@ -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<String>,
/// 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<Option<Set>, 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::<u32>() {
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-<id>`, `wanderbooks-<id>.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<Vec<(String, Set)>, 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<String> = 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<String> = 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<Option<Set>, 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>) -> 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<bool, BackupError> {
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<String>,
ctx: &Ctx,
) -> Result<(Series, Option<Plan>), BackupError> {
) -> Result<(Series, Vec<Plan>), BackupError> {
let empty = Series::default();
let mut base = base.unwrap_or(&empty);
if base.bytes > len {
@@ -186,44 +342,60 @@ fn grow(
}
base = &empty;
}
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<Put, BackupError> {
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<Put, BackupError> {
match plan {
Plan::Range {
path,
@@ -310,6 +481,7 @@ fn named_pieces(
files: &[(String, Vec<u8>)],
kind: Kind,
keys: Option<&Keys>,
distrust: &BTreeSet<String>,
plans: &mut Vec<Plan>,
) -> Vec<Named> {
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<String>,
ctx: &Ctx,
) -> Result<(Manifest, Vec<Plan>), 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<IndexLine> = 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<IndexLine> = 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<IndexLine> = 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<u8>);
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<Written, BackupError> {
/// 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<Option<u64>, 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<PathBuf, BackupError> {
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<String>,
ctx: &Ctx,
) -> Result<Written, BackupError> {
let mut distrust: BTreeSet<String> = BTreeSet::new();
let mut repaired: Vec<String> = 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<Written, BackupError> {
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<Written,
let prev = set.newest_whole()?.map(|(m, _)| m);
let next = numbers.last().map_or(1, |n| n + 1);
ctx.phase("plan");
let (mut manifest, plans) = plan(set, prev.as_ref(), cut, ctx)?;
let (mut manifest, plans) = plan(set, prev.as_ref(), cut, &BTreeSet::new(), ctx)?;
if let Some(p) = &prev
&& manifest.same_content(p)
{
@@ -520,39 +906,33 @@ pub(crate) fn write_into_set(set: &Set, cut: &Cut, ctx: &Ctx) -> Result<Written,
number: p.number,
head: cut.head().clone(),
new: false,
repaired: Vec::new(),
files_proven: 0,
});
}
ctx.phase("pieces");
let mut added = BTreeSet::new();
for p in &plans {
ctx.check("backing up")?;
execute(set, p, ctx)?;
if execute(set, p, ctx)? == Put::Created
&& let Plan::File { piece, .. } = p
{
added.insert(piece.sha256.clone());
}
}
manifest.number = next;
manifest.written = now();
let mut bytes = encode_manifest(&manifest);
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)?;
match put {
Put::Created => {
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<Written, BackupError> {
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<Written, BackupError> {
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
+29 -11
View File
@@ -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!(
+2 -2
View File
@@ -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::<u64>().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<String> = tree(&set)
.into_keys()
.filter(|n| !n.starts_with("manifests/") && n != "READ-ME.txt")