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

+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")