Merge branch 't3/plain-folder-backups': a backup is a plain folder; git leaves the program (D-91, D-92)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
e6d722372e
84 files changed
+14087
-7326
No files matched your search
@@ -25,6 +25,14 @@ hex = "0.4"
|
||||
getrandom = { version = "0.2", features = ["std"] }
|
||||
subtle = "2"
|
||||
argon2 = "0.6"
|
||||
# A backup protected by a passphrase is sealed as the TIN vault is
|
||||
# (XChaCha20-Poly1305, already in the tree); its key is kept off the
|
||||
# page when this program is done with it (D-92).
|
||||
chacha20poly1305 = "0.11"
|
||||
zeroize = "1"
|
||||
# "Save a backup..." is one file: a zip of the backup's folder form (the
|
||||
# crate the viewer and the packages already use, deflate only).
|
||||
zip = { version = "9.0.1", default-features = false, features = ["deflate"] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,260 @@
|
||||
//! A cut of the books: what a backup is made from, taken in one look
|
||||
//! under the store's lock, and read from the book's folder after it.
|
||||
//!
|
||||
//! The journal is append-only and a stored file never changes once it is
|
||||
//! there, so what the lock has to fix is small: how long the journal is
|
||||
//! (and that its last line is the head), how much of the access log is
|
||||
//! whole lines, and the vault and the keys, which can change. Everything
|
||||
//! else is read afterwards, outside the lock, and cannot move: the bytes
|
||||
//! of the journal before the cut's length are the same bytes a moment
|
||||
//! later.
|
||||
|
||||
use super::form::{IndexLine, is_plain_name, is_sha};
|
||||
use super::{BackupError, Ctx};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// A cut of one book. Take it with the store's lock held ([`Cut::take`]).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cut {
|
||||
book: String,
|
||||
dir: PathBuf,
|
||||
head: (u64, String),
|
||||
pub(crate) journal_len: u64,
|
||||
pub(crate) access_len: u64,
|
||||
pub(crate) vault: Vec<(String, Vec<u8>)>,
|
||||
pub(crate) keys: Vec<(String, Vec<u8>)>,
|
||||
}
|
||||
|
||||
/// The bytes of the last line of `path`, which is `len` long and ends in a
|
||||
/// newline, read from the end.
|
||||
fn last_line(path: &Path, len: u64) -> std::io::Result<Vec<u8>> {
|
||||
let mut f = std::fs::File::open(path)?;
|
||||
let mut tail: Vec<u8> = Vec::new();
|
||||
let mut at = len;
|
||||
// Without the final newline; looking back for the one before it.
|
||||
loop {
|
||||
let step = at.min(64 * 1024);
|
||||
at -= step;
|
||||
f.seek(SeekFrom::Start(at))?;
|
||||
let mut chunk = vec![0u8; step as usize];
|
||||
f.read_exact(&mut chunk)?;
|
||||
chunk.extend_from_slice(&tail);
|
||||
tail = chunk;
|
||||
if tail.last() != Some(&b'\n') {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"the journal does not end in a whole line",
|
||||
));
|
||||
}
|
||||
let body = &tail[..tail.len() - 1];
|
||||
if let Some(i) = body.iter().rposition(|b| *b == b'\n') {
|
||||
return Ok(body[i + 1..].to_vec());
|
||||
}
|
||||
if at == 0 {
|
||||
return Ok(body.to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of `path`, `len` long, is whole lines.
|
||||
fn whole_lines(path: &Path, len: u64) -> std::io::Result<u64> {
|
||||
let mut f = std::fs::File::open(path)?;
|
||||
let mut at = len;
|
||||
while at > 0 {
|
||||
let step = at.min(64 * 1024);
|
||||
at -= step;
|
||||
f.seek(SeekFrom::Start(at))?;
|
||||
let mut chunk = vec![0u8; step as usize];
|
||||
f.read_exact(&mut chunk)?;
|
||||
if let Some(i) = chunk.iter().rposition(|b| *b == b'\n') {
|
||||
return Ok(at + i as u64 + 1);
|
||||
}
|
||||
}
|
||||
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.
|
||||
/// 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 named: Vec<(String, PathBuf)> = Vec::new();
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let meta = std::fs::symlink_metadata(entry.path())?;
|
||||
if !meta.is_file() || !is_plain_name(&name) {
|
||||
return Err(BackupError::Damaged(format!(
|
||||
"a folder of the books holds something no book keeps ({name:?})"
|
||||
)));
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
impl Cut {
|
||||
/// Take a cut of the book `book` kept in `dir`, whose journal's head
|
||||
/// is `head`. The caller holds the store's lock, so the journal is
|
||||
/// whole lines and the vault matches it.
|
||||
pub fn take(book: &str, dir: &Path, head: (u64, String)) -> Result<Cut, BackupError> {
|
||||
let journal = dir.join(crate::JOURNAL_FILE);
|
||||
let journal_len = match std::fs::metadata(&journal) {
|
||||
Ok(m) => m.len(),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if head.0 == 0 {
|
||||
if journal_len != 0 {
|
||||
return Err(BackupError::Damaged(
|
||||
"the journal has lines the books don't count".into(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
let line = last_line(&journal, journal_len)?;
|
||||
if hex::encode(Sha256::digest(&line)) != head.1 {
|
||||
return Err(BackupError::Damaged(
|
||||
"the journal's last line isn't the books' head".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let access = dir.join(crate::access::ACCESS_FILE);
|
||||
let access_len = match std::fs::metadata(&access) {
|
||||
Ok(m) => whole_lines(&access, m.len())?,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
Ok(Cut {
|
||||
book: book.to_string(),
|
||||
dir: dir.to_path_buf(),
|
||||
head,
|
||||
journal_len,
|
||||
access_len,
|
||||
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
|
||||
}
|
||||
|
||||
/// The journal's head at the cut: seq and hash.
|
||||
pub fn head(&self) -> &(u64, String) {
|
||||
&self.head
|
||||
}
|
||||
|
||||
pub(crate) fn journal_path(&self) -> PathBuf {
|
||||
self.dir.join(crate::JOURNAL_FILE)
|
||||
}
|
||||
|
||||
pub(crate) fn access_path(&self) -> PathBuf {
|
||||
self.dir.join(crate::access::ACCESS_FILE)
|
||||
}
|
||||
|
||||
/// The stored files, by hash, with their lengths: those named as this
|
||||
/// program names them (`blobs/ab/cd/<sha256>`), nothing else.
|
||||
pub(crate) fn stored_files(&self, ctx: &Ctx) -> Result<Vec<IndexLine>, BackupError> {
|
||||
let root = self.dir.join(crate::store::BLOBS_DIR);
|
||||
let mut out = Vec::new();
|
||||
let level = |p: &Path| -> std::io::Result<Vec<std::fs::DirEntry>> {
|
||||
match std::fs::read_dir(p) {
|
||||
Ok(e) => e.collect(),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
};
|
||||
for a in level(&root)? {
|
||||
ctx.check("listing the stored files")?;
|
||||
let an = a.file_name().to_string_lossy().into_owned();
|
||||
if an.len() != 2 || !a.path().is_dir() {
|
||||
continue;
|
||||
}
|
||||
for b in level(&a.path())? {
|
||||
let bn = b.file_name().to_string_lossy().into_owned();
|
||||
if bn.len() != 2 || !b.path().is_dir() {
|
||||
continue;
|
||||
}
|
||||
for f in level(&b.path())? {
|
||||
let name = f.file_name().to_string_lossy().into_owned();
|
||||
let meta = std::fs::symlink_metadata(f.path())?;
|
||||
if meta.is_file()
|
||||
&& is_sha(&name)
|
||||
&& name.starts_with(&an)
|
||||
&& name[2..].starts_with(&bn)
|
||||
{
|
||||
out.push(IndexLine {
|
||||
sha256: name,
|
||||
bytes: meta.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|x, y| x.sha256.cmp(&y.sha256));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where a stored file is in the book.
|
||||
pub(crate) fn blob_path(&self, sha: &str) -> PathBuf {
|
||||
self.dir
|
||||
.join(crate::store::BLOBS_DIR)
|
||||
.join(&sha[0..2])
|
||||
.join(&sha[2..4])
|
||||
.join(sha)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
//! The records of a backup: pieces, series of pieces, and the manifest
|
||||
//! that names them, and the names a piece is kept under.
|
||||
//!
|
||||
//! A *series* is what grows: the journal, the access log and the index of
|
||||
//! stored files are each a run of immutable segments whose bytes, read one
|
||||
//! after another, are the whole. A backup that has new lines adds a
|
||||
//! segment; nothing already written is touched.
|
||||
|
||||
use super::BackupError;
|
||||
use super::seal::Keys;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// What a manifest says it is.
|
||||
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 folder of proof marks in a set: one tiny file per manifest whose
|
||||
/// proof (write.rs) came out whole, so a manifest whose proof was cut short
|
||||
/// is proven by the next backup, even one with nothing new to write.
|
||||
pub(crate) const PROOFS: &str = "proofs";
|
||||
/// The words a person can open.
|
||||
pub(crate) const READ_ME: &str = "READ-ME.txt";
|
||||
/// The sealed form's header: how to derive the key.
|
||||
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 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)]
|
||||
pub(crate) enum Kind {
|
||||
/// A segment of the journal.
|
||||
Journal,
|
||||
/// A segment of the access log.
|
||||
Access,
|
||||
/// A segment of the index of stored files.
|
||||
Index,
|
||||
/// A stored file.
|
||||
File,
|
||||
/// A vault record.
|
||||
Vault,
|
||||
/// A key file.
|
||||
Key,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub(crate) fn dir(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Journal => "journal",
|
||||
Kind::Access => "access",
|
||||
Kind::Index => "files-index",
|
||||
Kind::File => "files",
|
||||
Kind::Vault => "vault",
|
||||
Kind::Key => "keys",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One piece: a file of the set, by where it is, how long it is as it is
|
||||
/// kept, and what is in it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Piece {
|
||||
/// Its path in the set.
|
||||
pub file: String,
|
||||
/// Its length as kept (sealed pieces are longer than their contents).
|
||||
pub stored: u64,
|
||||
/// Its contents' length.
|
||||
pub bytes: u64,
|
||||
/// Its contents' SHA-256, hex.
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
/// A run of segments, and what they make together.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Series {
|
||||
/// Bytes in all the segments.
|
||||
pub bytes: u64,
|
||||
/// SHA-256 of all of them, one after another, hex.
|
||||
pub sha256: String,
|
||||
/// 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
|
||||
/// keys).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Named {
|
||||
/// Its name in the book's folder.
|
||||
pub name: String,
|
||||
/// Where it is kept.
|
||||
#[serde(flatten)]
|
||||
pub piece: Piece,
|
||||
}
|
||||
|
||||
/// The journal's head.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Head {
|
||||
/// Its last line's seq.
|
||||
pub seq: u64,
|
||||
/// Its last line's hash.
|
||||
pub hash: String,
|
||||
}
|
||||
|
||||
/// What makes a backup whole: written last, and never again.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Manifest {
|
||||
/// [`FORMAT`].
|
||||
pub format: String,
|
||||
/// [`VERSION`].
|
||||
pub version: u32,
|
||||
/// The books' id, as they were backed up.
|
||||
pub book: String,
|
||||
/// Its number in the set: also its name.
|
||||
pub number: u64,
|
||||
/// When it was written (UTC).
|
||||
pub written: String,
|
||||
/// The journal's head it reaches.
|
||||
pub head: Head,
|
||||
/// The journal.
|
||||
pub journal: Series,
|
||||
/// The access log.
|
||||
pub access: Series,
|
||||
/// The index of stored files: one `{"sha256","bytes"}` per line.
|
||||
pub files: Series,
|
||||
/// How many stored files the index names, and their bytes.
|
||||
pub file_count: u64,
|
||||
/// Bytes of the stored files.
|
||||
pub file_bytes: u64,
|
||||
/// The vault's records.
|
||||
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.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct IndexLine {
|
||||
/// The file's SHA-256, hex.
|
||||
pub sha256: String,
|
||||
/// Its length.
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
/// SHA-256, hex.
|
||||
pub(crate) fn sha_hex(bytes: &[u8]) -> String {
|
||||
hex::encode(Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
/// Whether `s` is a SHA-256 in hex as this program writes it.
|
||||
pub(crate) fn is_sha(s: &str) -> bool {
|
||||
s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
|
||||
}
|
||||
|
||||
/// A name in a book's flat folders: nothing that could leave the folder.
|
||||
pub(crate) fn is_plain_name(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& s.len() <= 200
|
||||
&& s != "."
|
||||
&& s != ".."
|
||||
&& s.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
|
||||
}
|
||||
|
||||
/// The manifest's file name in a set, as its number.
|
||||
pub(crate) fn manifest_path(number: u64, sealed: bool) -> String {
|
||||
if sealed {
|
||||
format!("{MANIFESTS}/{number:06}")
|
||||
} else {
|
||||
format!("{MANIFESTS}/{number:06}.json")
|
||||
}
|
||||
}
|
||||
|
||||
/// The mark that manifest `number` was proven whole.
|
||||
pub(crate) fn proof_path(number: u64) -> String {
|
||||
format!("{PROOFS}/{number:06}")
|
||||
}
|
||||
|
||||
/// The number a manifest file name carries, if it is one.
|
||||
pub(crate) fn manifest_number(name: &str, sealed: bool) -> Option<u64> {
|
||||
let digits = if sealed {
|
||||
name
|
||||
} else {
|
||||
name.strip_suffix(".json")?
|
||||
};
|
||||
if digits.len() < 6 || !digits.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let n: u64 = digits.parse().ok()?;
|
||||
// Exactly the name this program writes (no conflict copy of one, no
|
||||
// other spelling of the same number).
|
||||
(manifest_path(n, sealed) == format!("{MANIFESTS}/{name}")).then_some(n)
|
||||
}
|
||||
|
||||
/// 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),
|
||||
/// 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) => {
|
||||
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])
|
||||
}
|
||||
Kind::File => format!("{}/{}/{sha}", kind.dir(), &sha[..2]),
|
||||
Kind::Vault | Kind::Key => format!("{}/{sha}", kind.dir()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let body = serde_json::to_string(m).expect("a manifest serializes");
|
||||
let check = sha_hex(body.as_bytes());
|
||||
format!("{body}\nwanderbooks-manifest-sha256 {check}\n").into_bytes()
|
||||
}
|
||||
|
||||
/// A manifest read back, or why it is not one.
|
||||
pub(crate) fn decode_manifest(bytes: &[u8]) -> Result<Manifest, BackupError> {
|
||||
let bad = || BackupError::Damaged("a manifest of the backup is cut short or changed".into());
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| bad())?;
|
||||
let text = text.strip_suffix('\n').ok_or_else(bad)?;
|
||||
let (body, check) = text.rsplit_once('\n').ok_or_else(bad)?;
|
||||
let check = check
|
||||
.strip_prefix("wanderbooks-manifest-sha256 ")
|
||||
.ok_or_else(bad)?;
|
||||
if check != sha_hex(body.as_bytes()) {
|
||||
return 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(),
|
||||
));
|
||||
}
|
||||
if m.version != VERSION {
|
||||
return Err(BackupError::Damaged(
|
||||
"that backup was made by a newer wanderbooks: update to read it".into(),
|
||||
));
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
/// What this manifest holds, apart from its number and time: two with
|
||||
/// the same content need not both be written.
|
||||
pub(crate) fn same_content(&self, other: &Manifest) -> bool {
|
||||
let mut a = self.clone();
|
||||
let mut b = other.clone();
|
||||
for m in [&mut a, &mut b] {
|
||||
m.number = 0;
|
||||
m.written.clear();
|
||||
m.base = None;
|
||||
m.depth = 0;
|
||||
m.sha.clear();
|
||||
}
|
||||
a == b
|
||||
}
|
||||
|
||||
/// Every name in it is one this program would have written: nothing
|
||||
/// that could lead out of the set or into another's.
|
||||
pub(crate) fn check_names(&self, sealed: bool) -> Result<(), BackupError> {
|
||||
let bad = |why: &str| BackupError::Damaged(format!("a manifest of the backup {why}"));
|
||||
if !is_sha(&self.head.hash) && self.head.seq > 0 {
|
||||
return Err(bad("has a head that is not a hash"));
|
||||
}
|
||||
for series in [&self.journal, &self.access, &self.files] {
|
||||
if !is_sha(&series.sha256) && series.bytes > 0 {
|
||||
return Err(bad("has a series that is not a hash"));
|
||||
}
|
||||
let total = series
|
||||
.segments
|
||||
.iter()
|
||||
.fold(0u64, |a, s| a.saturating_add(s.bytes));
|
||||
if total != series.bytes {
|
||||
return Err(bad("has segments that don't add up"));
|
||||
}
|
||||
for p in &series.segments {
|
||||
self.check_piece(p, sealed)?;
|
||||
}
|
||||
}
|
||||
for n in self.vault.iter().chain(&self.keys) {
|
||||
if !is_plain_name(&n.name) {
|
||||
return Err(bad("names a file no book keeps"));
|
||||
}
|
||||
self.check_piece(&n.piece, sealed)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_piece(&self, p: &Piece, sealed: bool) -> Result<(), BackupError> {
|
||||
let bad = |why: &str| BackupError::Damaged(format!("a manifest of the backup {why}"));
|
||||
if !is_sha(&p.sha256) {
|
||||
return Err(bad("has a piece that is not a hash"));
|
||||
}
|
||||
let ok_path = p.file.split('/').all(|part| {
|
||||
!part.is_empty()
|
||||
&& part != "."
|
||||
&& part != ".."
|
||||
&& part
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
|
||||
});
|
||||
let starts = [
|
||||
"journal/",
|
||||
"access/",
|
||||
"files-index/",
|
||||
"files/",
|
||||
"vault/",
|
||||
"keys/",
|
||||
];
|
||||
let right_place = if sealed {
|
||||
p.file.starts_with(&format!("{PIECES}/"))
|
||||
} else {
|
||||
starts.iter().any(|s| p.file.starts_with(s))
|
||||
};
|
||||
if !ok_path || !right_place {
|
||||
return Err(bad("names a piece outside the backup"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
//! Where a backup's files live, behind one seam: a folder on a disk
|
||||
//! ([`DirSet`]), or the one-file form ([`crate::backup::single`]).
|
||||
//!
|
||||
//! The only operations a backup needs of a place are four: list a folder,
|
||||
//! ask how long a file is, read a file, and put a file there that was not
|
||||
//! there. Nothing deletes, nothing replaces (INVARIANT 1 of the module).
|
||||
//!
|
||||
//! How a file is put (the whole of the argument for two writers):
|
||||
//!
|
||||
//! * It is written under a name no reader looks at (`.wb-tmp-…`, in the
|
||||
//! folder it is for), synced, and then given its real name by a
|
||||
//! *hard link*, which every disk and every network share this program
|
||||
//! meets either does atomically and exclusively (the name is made, or
|
||||
//! it exists already: Unix, NTFS, SMB, NFS) or refuses outright (FAT and
|
||||
//! 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.
|
||||
//! * 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 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
|
||||
//! destination, and only the file it made itself a moment before; one left
|
||||
//! by a process that died stays (a person may delete `.wb-tmp-*` by hand).
|
||||
|
||||
use super::{BackupError, Ctx};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// What kind of file is being put: how an existing file at the name is met.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum PutKind {
|
||||
/// Named by what is in it: if it is there, it is the one.
|
||||
Piece,
|
||||
/// One for the whole set, written once (the read-me, the header): if
|
||||
/// it is there, it stays.
|
||||
Once,
|
||||
/// A manifest: the name is a number, taken exclusively. The decision
|
||||
/// point of a backup.
|
||||
Manifest,
|
||||
}
|
||||
|
||||
/// How a put came out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Put {
|
||||
/// This call made the file.
|
||||
Created,
|
||||
/// It was there already: untouched.
|
||||
Existed,
|
||||
}
|
||||
|
||||
/// Fill a file: the callback writes its bytes.
|
||||
pub(crate) type Fill<'a> = &'a mut dyn FnMut(&mut dyn Write) -> std::io::Result<()>;
|
||||
|
||||
/// Where a set's files live.
|
||||
pub(crate) trait SetIo: Send + Sync {
|
||||
/// The names directly in `dir` (a path in the set, `/` between parts),
|
||||
/// none if it is not there.
|
||||
fn list(&self, dir: &str) -> std::io::Result<Vec<String>>;
|
||||
/// How long the file at `rel` is, None if it is not there.
|
||||
fn len(&self, rel: &str) -> std::io::Result<Option<u64>>;
|
||||
/// Read the file at `rel` through `f`.
|
||||
fn read_with(
|
||||
&self,
|
||||
rel: &str,
|
||||
f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>,
|
||||
) -> std::io::Result<()>;
|
||||
/// Put a file at `rel` that is not there ([`PutKind`]).
|
||||
fn put(&self, rel: &str, kind: PutKind, fill: Fill<'_>) -> std::io::Result<Put>;
|
||||
}
|
||||
|
||||
/// A backup error carried through an `io::Error` (a callback that has to
|
||||
/// stop the file it is writing).
|
||||
#[derive(Debug)]
|
||||
struct Carried(BackupError);
|
||||
|
||||
impl std::fmt::Display for Carried {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Carried {}
|
||||
|
||||
/// `e` as an `io::Error` a callback can return.
|
||||
pub(crate) fn carry(e: BackupError) -> std::io::Error {
|
||||
std::io::Error::other(Carried(e))
|
||||
}
|
||||
|
||||
/// A backup error back out of an `io::Error` (one that was carried, or the
|
||||
/// disk's own).
|
||||
pub(crate) fn uncarry(e: std::io::Error) -> BackupError {
|
||||
match e.get_ref().and_then(|i| i.downcast_ref::<Carried>()) {
|
||||
Some(c) => c.0.clone(),
|
||||
None => BackupError::Io(e.kind()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A set that is a folder on a disk.
|
||||
pub(crate) struct DirSet {
|
||||
root: PathBuf,
|
||||
ctx: Ctx,
|
||||
}
|
||||
|
||||
impl DirSet {
|
||||
/// The set in the folder `root` (which need not exist yet).
|
||||
pub(crate) fn new(root: PathBuf, ctx: Ctx) -> Self {
|
||||
Self { root, ctx }
|
||||
}
|
||||
|
||||
fn path(&self, rel: &str) -> PathBuf {
|
||||
let mut p = self.root.clone();
|
||||
for part in rel.split('/').filter(|s| !s.is_empty()) {
|
||||
p.push(part);
|
||||
}
|
||||
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.
|
||||
fn scratch_name() -> String {
|
||||
let mut r = [0u8; 6];
|
||||
let _ = getrandom::getrandom(&mut r);
|
||||
format!(
|
||||
".wb-tmp-{}-{}",
|
||||
std::process::id(),
|
||||
r.iter().map(|b| format!("{b:02x}")).collect::<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)]
|
||||
if let Ok(dir) = std::fs::File::open(path) {
|
||||
let _ = dir.sync_all();
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
fn list(&self, dir: &str) -> std::io::Result<Vec<String>> {
|
||||
match std::fs::read_dir(self.path(dir)) {
|
||||
Ok(entries) => {
|
||||
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());
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn len(&self, rel: &str) -> std::io::Result<Option<u64>> {
|
||||
self.ctx.traced("len", rel);
|
||||
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 => {
|
||||
if self.stand_in_for(rel) {
|
||||
Err(carry(BackupError::NotDownloaded))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_with(
|
||||
&self,
|
||||
rel: &str,
|
||||
f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>,
|
||||
) -> std::io::Result<()> {
|
||||
self.ctx.traced("read", rel);
|
||||
let path = self.path(rel);
|
||||
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,
|
||||
"not a plain file",
|
||||
));
|
||||
}
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
f(&mut file)
|
||||
}
|
||||
|
||||
fn put(&self, rel: &str, kind: PutKind, fill: Fill<'_>) -> std::io::Result<Put> {
|
||||
let path = self.path(rel);
|
||||
let parent = path.parent().unwrap_or(&self.root).to_path_buf();
|
||||
std::fs::create_dir_all(&parent)?;
|
||||
if kind != PutKind::Manifest && std::fs::symlink_metadata(&path).is_ok() {
|
||||
return Ok(Put::Existed);
|
||||
}
|
||||
let tmp = parent.join(scratch_name());
|
||||
self.ctx.point("create", rel).map_err(carry)?;
|
||||
let written = (|| -> std::io::Result<()> {
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp)?;
|
||||
{
|
||||
let mut w = std::io::BufWriter::with_capacity(1 << 16, &mut file);
|
||||
fill(&mut w)?;
|
||||
w.flush()?;
|
||||
}
|
||||
if self.ctx.syncs() {
|
||||
file.sync_all()
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
})();
|
||||
if let Err(e) = written {
|
||||
// Something of ours that failed on its own: its scratch file
|
||||
// goes (a death, which `point` reports, leaves it).
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
self.ctx.point("written", rel).map_err(carry)?;
|
||||
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 e.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
Put::Existed
|
||||
}
|
||||
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);
|
||||
}
|
||||
};
|
||||
if self.ctx.syncs() {
|
||||
sync_dir(&parent);
|
||||
}
|
||||
self.ctx.point("published", rel).map_err(carry)?;
|
||||
Ok(put)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
//! Backups in plain folders (plan/p15-app-and-relay.md section 9, D-91,
|
||||
//! D-92): a backup is a folder the person picks, holding one folder per
|
||||
//! set of books, made only of files that are written once.
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: a book's every write survives the loss of this computer, a
|
||||
//! backup is proven whole before it is trusted or restored, and the
|
||||
//! person needs nothing installed and nothing explained to have one.
|
||||
//! SOURCE: plan/p15-app-and-relay.md section 9 (the form, D-91: git leaves
|
||||
//! backups entirely; D-92: a passphrase, off by default), plan 3.7
|
||||
//! (what a backup holds, when it runs, the proof after it, the
|
||||
//! weekly drill), 3.9 and D-39 (a proven local backup with the
|
||||
//! keys before a format upgrade), WB-backup-1.
|
||||
//! INVARIANTS:
|
||||
//! 1. Nothing in a destination is ever deleted or rewritten. Every file
|
||||
//! is put once (io.rs): a piece under a name made from what is in it,
|
||||
//! a manifest under its number, taken exclusively. The one thing this
|
||||
//! code removes from a destination is the scratch file it made itself
|
||||
//! a moment before. So a destination only grows, a syncing service
|
||||
//! never sees a file change under it, and an earlier state of the
|
||||
//! books is always still there.
|
||||
//! 2. A backup is whole when its manifest is in place, and not before.
|
||||
//! The manifest is written last, after every piece it names is there;
|
||||
//! a run that dies leaves pieces no manifest names, which are
|
||||
//! harmless, and at most a short manifest, which no reader accepts
|
||||
//! (it carries its own check) and whose number is spent.
|
||||
//! 3. A manifest names every piece it needs, by where it is, how long it
|
||||
//! is and what is in it (SHA-256), either itself or by naming the
|
||||
//! manifest before it (by number and by what its body hashes to) and
|
||||
//! only what is new, a chain of at most `DELTA_CHAIN` links; a reader
|
||||
//! proves the chain link by link. A reader tries the manifests newest
|
||||
//! first and takes the first whose pieces are all there at the length
|
||||
//! it names and that proves (`verify_found`), reading no more: the
|
||||
//! journal's chain replays to the head the manifest records, the books
|
||||
//! open, every stored file re-hashes, every vault record the books name
|
||||
//! and the key that opens them are there. A piece is accepted under
|
||||
//! any generation of it whose contents hash right.
|
||||
//! 4. A backup is written only onto a destination whose newest whole
|
||||
//! manifest is a point on the live journal (same line, same hash,
|
||||
//! same place in the file). Otherwise it is said, and nothing is
|
||||
//! written: the live journal is the beginning of a longer one
|
||||
//! (`Ahead`: the books are behind the folder, and a new set may be
|
||||
//! begun beside the old at the person's request), or the books are
|
||||
//! others or have diverged (`Elsewhere`).
|
||||
//! 5. Two programs, or two computers, writing one destination cannot
|
||||
//! corrupt it: pieces are named by what is in them, so two writers of
|
||||
//! one piece write the same bytes; the only decision is which of them
|
||||
//! takes the next manifest number, and the disk decides it
|
||||
//! (exclusive create). The loser looks again and goes on from what the
|
||||
//! winner wrote, or finds there is nothing left to write.
|
||||
//! 6. A manifest that is lost, or replaced by a sync service's conflict
|
||||
//! copy, makes unreadable only the manifests chained on it (at most
|
||||
//! the rest of its chain of 64); every earlier one, and every later
|
||||
//! one that names everything, stands.
|
||||
//! 7. With a passphrase every piece, every manifest, is sealed
|
||||
//! (seal.rs); names say no more than counts and sizes; the key is
|
||||
//! derived by a memory-hard function; this computer keeps it in the
|
||||
//! book's `local/` folder, owner-only, never in a backup. A wrong
|
||||
//! passphrase opens nothing, and is told from damage.
|
||||
//! 8. A step that has to end when the books are let go looks for the
|
||||
//! stop between pieces, and once per chunk of a file read; a stopped
|
||||
//! backup leaves a destination that proves whole at its previous
|
||||
//! manifest.
|
||||
//! 9. Nothing here names a path of the data root: errors speak of "the
|
||||
//! backup folder".
|
||||
//! 10. A backup is proven before it is recorded good (write.rs
|
||||
//! `prove_and_repair`, read.rs `prove_written`): the manifest just put
|
||||
//! is read back, every journal and access segment re-hashed, the chain
|
||||
//! replayed to its head, the vault and keys present, and the stored
|
||||
//! files this backup added and one sixteenth of the rest re-hashed (a
|
||||
//! share that comes round within 16 backups); what is found damaged is
|
||||
//! written again under a new generation beside it and proven again.
|
||||
//! A manifest whose proof was cut short is marked unproven (no mark in
|
||||
//! `proofs/`) and proven by the next backup.
|
||||
//! 11. A drill passes only on the newest manifest, and only if it reaches
|
||||
//! the last head recorded good (`drill`).
|
||||
//! ```
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
mod cut;
|
||||
mod form;
|
||||
mod io;
|
||||
mod read;
|
||||
mod seal;
|
||||
mod single;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod write;
|
||||
|
||||
pub use cut::Cut;
|
||||
pub use read::list;
|
||||
pub use read::{Candidate, Found, Verified, drill, find, prove_local, verify_found};
|
||||
pub use seal::{BackupKey, key_derivations};
|
||||
pub use single::{FILE_EXTENSION, save_file};
|
||||
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] = [
|
||||
crate::JOURNAL_FILE,
|
||||
"blobs",
|
||||
crate::root::VAULT_DIR,
|
||||
crate::root::KEYS_DIR,
|
||||
crate::access::ACCESS_FILE,
|
||||
];
|
||||
|
||||
/// A book's own local backup, in its folder: the same form as a
|
||||
/// destination, written under the store's lock before a format upgrade.
|
||||
pub const LOCAL_DIR: &str = "local-backup";
|
||||
|
||||
/// Why a backup couldn't be made, proven or restored. Never names a path
|
||||
/// of the data root (INVARIANT 9).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum BackupError {
|
||||
/// A folder that isn't there (an external disk not connected).
|
||||
#[error("the backup folder isn't there (is its disk connected?)")]
|
||||
NoFolder,
|
||||
/// A folder that took these books' backups but holds none now (a disk
|
||||
/// not mounted on its mount point, or a new disk).
|
||||
#[error(
|
||||
"the backup folder holds no backup of these books: connect the disk that does; if it is a new disk, back up now saying so (new_disk)"
|
||||
)]
|
||||
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 books (they have diverged): nothing was written there"
|
||||
)]
|
||||
Elsewhere,
|
||||
/// The destination holds a longer history of these same books.
|
||||
#[error(
|
||||
"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.
|
||||
#[error("another program kept writing to the backup folder: try again in a moment")]
|
||||
Busy,
|
||||
/// A backup that isn't whole.
|
||||
#[error("that backup can't be trusted: {0}")]
|
||||
Damaged(String),
|
||||
/// 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,
|
||||
/// A passphrase of a length not taken.
|
||||
#[error(
|
||||
"a backup passphrase is {} to {} characters long",
|
||||
crate::passphrase::MIN_CHARS,
|
||||
crate::passphrase::MAX_CHARS
|
||||
)]
|
||||
PassphraseLength,
|
||||
/// More than one set of books is there, and which was not said.
|
||||
#[error(
|
||||
"that folder holds backups of more than one set of books ({0}): choose the folder of one"
|
||||
)]
|
||||
Several(String),
|
||||
/// Nothing there is a backup.
|
||||
#[error("there is no backup there")]
|
||||
NotABackup,
|
||||
/// Stopped because the books are closing.
|
||||
#[error("{0} was stopped: the books are closing")]
|
||||
Cancelled(String),
|
||||
/// A test's death at a write point; never made otherwise.
|
||||
#[doc(hidden)]
|
||||
#[error("the program died here")]
|
||||
Died,
|
||||
/// The disk refused.
|
||||
#[error("the backup couldn't be made: {0}")]
|
||||
Io(std::io::ErrorKind),
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for BackupError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
io::uncarry(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::StoreError> for BackupError {
|
||||
fn from(e: crate::StoreError) -> Self {
|
||||
match e {
|
||||
crate::StoreError::Cancelled => BackupError::Cancelled("verifying".into()),
|
||||
e => BackupError::Damaged(e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>;
|
||||
|
||||
/// A test's way to die at a write point: told the kind of point and the
|
||||
/// file it is for, answers true to die there.
|
||||
pub type Faults = Arc<dyn Fn(&str, &str) -> bool + Send + Sync>;
|
||||
|
||||
/// What a step is run under: the stop it looks for (INVARIANT 8) and, in
|
||||
/// tests, where it dies.
|
||||
#[derive(Clone, Default)]
|
||||
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,
|
||||
/// Tests: nothing is synced to disk (a destination of thousands of
|
||||
/// backups is made quickly; a real one never is).
|
||||
no_sync: bool,
|
||||
/// Tests: the proof after a backup is left out (for the tests that make
|
||||
/// many backups only to see what is written, which prove what they
|
||||
/// made themselves).
|
||||
no_proof: bool,
|
||||
/// Tests: told each read and length look at a file of the set.
|
||||
trace: Option<Trace>,
|
||||
}
|
||||
|
||||
/// A test's look at which files of a set are read or measured.
|
||||
pub type Trace = Arc<dyn Fn(&str, &str) + Send + Sync>;
|
||||
|
||||
impl std::fmt::Debug for Ctx {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Ctx")
|
||||
}
|
||||
}
|
||||
|
||||
impl Ctx {
|
||||
/// No stop, no faults.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Stopped when `flag` is set.
|
||||
pub fn with_stop(mut self, flag: Arc<AtomicBool>) -> Self {
|
||||
self.stop = Some(flag);
|
||||
self
|
||||
}
|
||||
|
||||
/// Dies where `faults` says (tests).
|
||||
#[doc(hidden)]
|
||||
pub fn with_faults(mut self, faults: Faults) -> Self {
|
||||
self.faults = Some(faults);
|
||||
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
|
||||
}
|
||||
|
||||
/// Told, in tests, each `read` and `len` of a file of a set.
|
||||
#[doc(hidden)]
|
||||
pub fn with_trace(mut self, trace: Trace) -> Self {
|
||||
self.trace = Some(trace);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn traced(&self, kind: &str, rel: &str) {
|
||||
if let Some(t) = &self.trace {
|
||||
t(kind, rel);
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing is synced to disk (tests that make thousands of backups).
|
||||
#[doc(hidden)]
|
||||
pub fn with_no_sync(mut self) -> Self {
|
||||
self.no_sync = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The proof after a backup is left out (tests that make many backups
|
||||
/// only to see what is written; the proof has tests of its own).
|
||||
#[doc(hidden)]
|
||||
pub fn with_proof_skipped(mut self) -> Self {
|
||||
self.no_proof = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn skips_proof(&self) -> bool {
|
||||
self.no_proof
|
||||
}
|
||||
|
||||
pub(crate) fn syncs(&self) -> bool {
|
||||
!self.no_sync
|
||||
}
|
||||
|
||||
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);
|
||||
self
|
||||
}
|
||||
|
||||
/// A phase of a step begins.
|
||||
pub(crate) fn phase(&self, name: &str) {
|
||||
if let Some(w) = &self.phase {
|
||||
w(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The stop flag, if there is one.
|
||||
pub fn stop_flag(&self) -> Option<Arc<AtomicBool>> {
|
||||
self.stop.clone()
|
||||
}
|
||||
|
||||
/// Ok, or [`BackupError::Cancelled`] when a stop was asked for.
|
||||
pub fn check(&self, what: &str) -> Result<(), BackupError> {
|
||||
if self.stop.as_ref().is_some_and(|f| f.load(Ordering::SeqCst)) {
|
||||
Err(BackupError::Cancelled(what.to_string()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A write point: where a test's fault may die.
|
||||
pub(crate) fn point(&self, kind: &str, rel: &str) -> Result<(), BackupError> {
|
||||
match &self.faults {
|
||||
Some(f) if f(kind, rel) => Err(BackupError::Died),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a person sees of a backup's standing in one line of the record:
|
||||
/// serialisable pieces for the server.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Reached {
|
||||
/// The journal seq the backup reaches.
|
||||
pub seq: u64,
|
||||
/// Its hash.
|
||||
pub hash: String,
|
||||
/// The number of the manifest that made it whole.
|
||||
pub number: u64,
|
||||
}
|
||||
|
||||
/// The words in a set's READ-ME, for a person who opens the folder.
|
||||
pub(crate) const READ_ME_TEXT: &str = "\
|
||||
This folder is a backup of a set of books kept with Wanderbooks.
|
||||
|
||||
Nothing in it needs to be opened or changed by hand, and nothing in it is
|
||||
ever deleted or rewritten by Wanderbooks: a backup only adds files. If your
|
||||
disk is short of room you may delete the whole folder, but not parts of it.
|
||||
|
||||
To get the books back, open Wanderbooks and choose Restore, then point it at
|
||||
this folder (or at the folder above it). It checks everything before it
|
||||
puts anything in place.
|
||||
|
||||
If these backups are protected by a passphrase, the files here are sealed:
|
||||
only Wanderbooks with that passphrase can read them, and nobody can recover
|
||||
a forgotten passphrase.
|
||||
";
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,504 @@
|
||||
//! A backup protected by a passphrase (D-92): the key, the header that
|
||||
//! lets another computer derive it, the sealed form of a piece, and the
|
||||
//! key kept privately on this computer.
|
||||
//!
|
||||
//! The passphrase is run through Argon2id (the same function and the same
|
||||
//! cost as the owner passphrase, `passphrase.rs`: 64 MiB, 3 passes, 1 lane,
|
||||
//! RFC 9106) with a random salt of its own. The 32 bytes it gives (the
|
||||
//! *master*) are what this computer keeps, never the passphrase. Two keys
|
||||
//! come from the master, each by SHA-256 of a label and the master: the
|
||||
//! one pieces are sealed with, and the one their names are made with.
|
||||
//!
|
||||
//! A piece is sealed in chunks of 1 MiB with XChaCha20-Poly1305 (as the TIN
|
||||
//! vault is): a random 16-byte prefix per piece and an 8-byte chunk
|
||||
//! counter make each chunk's 24-byte nonce; each chunk's associated data
|
||||
//! is the piece's identity (what is in it) and whether it is the last, so
|
||||
//! a piece cut short, reordered, or put under another's name is not
|
||||
//! opened.
|
||||
|
||||
use super::BackupError;
|
||||
use super::form::sha_hex;
|
||||
use argon2::{Algorithm, Argon2, Params, Version};
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// The sealed piece's first bytes.
|
||||
const MAGIC: &[u8; 4] = b"WBS1";
|
||||
/// Plaintext bytes in a chunk.
|
||||
const CHUNK: usize = 1 << 20;
|
||||
/// What a chunk's seal adds.
|
||||
const TAG: usize = 16;
|
||||
/// The salt's length.
|
||||
const SALT_LEN: usize = 16;
|
||||
/// The words the header's check seals: opening them tells a right
|
||||
/// passphrase from a wrong one.
|
||||
const CHECK_TEXT: &[u8] = b"wanderbooks backup key check";
|
||||
/// The local key file's folder in a book's folder, and its name.
|
||||
pub(crate) const LOCAL_DIR: &str = "local";
|
||||
/// The key file's name.
|
||||
pub(crate) const KEY_FILE: &str = "backup-key.json";
|
||||
|
||||
/// How the passphrase is stretched. Recorded in the header so another
|
||||
/// computer derives the same key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Kdf {
|
||||
pub alg: String,
|
||||
pub m: u32,
|
||||
pub t: u32,
|
||||
pub p: u32,
|
||||
/// Hex.
|
||||
pub salt: String,
|
||||
}
|
||||
|
||||
/// The key a passphrase makes, with how it was made. Kept on this
|
||||
/// computer in the book's `local/` folder; never in a backup, never in the
|
||||
/// journal, never in a log (its `Debug` says nothing of the key).
|
||||
#[derive(Clone)]
|
||||
pub struct BackupKey {
|
||||
kdf: Kdf,
|
||||
master: Zeroizing<[u8; 32]>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BackupKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("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 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"
|
||||
&& (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()
|
||||
}
|
||||
|
||||
/// How many keys this program has derived from a passphrase (tests: a
|
||||
/// folder of sealed sets costs one derivation per distinct setting).
|
||||
static DERIVATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
/// How many keys have been derived by this process.
|
||||
#[doc(hidden)]
|
||||
pub fn key_derivations() -> usize {
|
||||
DERIVATIONS.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn stretch(passphrase: &str, kdf: &Kdf) -> Result<Zeroizing<[u8; 32]>, BackupError> {
|
||||
if !kdf_in_bounds(kdf) {
|
||||
return Err(BackupError::Damaged(
|
||||
"its header asks for a key this program won't derive".into(),
|
||||
));
|
||||
}
|
||||
DERIVATIONS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let salt = hex::decode(&kdf.salt).expect("checked");
|
||||
let params = Params::new(kdf.m, kdf.t, kdf.p, Some(32))
|
||||
.map_err(|_| BackupError::Damaged("its header's key settings are not valid".into()))?;
|
||||
let mut out = Zeroizing::new([0u8; 32]);
|
||||
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
|
||||
.hash_password_into(passphrase.as_bytes(), &salt, &mut *out)
|
||||
.map_err(|_| BackupError::Damaged("the key could not be derived".into()))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl BackupKey {
|
||||
/// A new key from `passphrase` with a salt of its own.
|
||||
pub fn generate(passphrase: &str) -> Result<Self, BackupError> {
|
||||
crate::passphrase::check_length(passphrase).map_err(|_| BackupError::PassphraseLength)?;
|
||||
let mut salt = [0u8; SALT_LEN];
|
||||
getrandom::getrandom(&mut salt)
|
||||
.map_err(|e| BackupError::Io(std::io::Error::from(e).kind()))?;
|
||||
let kdf = Kdf {
|
||||
alg: "argon2id".into(),
|
||||
m: crate::passphrase::M_COST,
|
||||
t: crate::passphrase::T_COST,
|
||||
p: crate::passphrase::P_COST,
|
||||
salt: hex::encode(salt),
|
||||
};
|
||||
let master = stretch(passphrase, &kdf)?;
|
||||
Ok(Self { kdf, master })
|
||||
}
|
||||
|
||||
fn label(&self, label: &str) -> Zeroizing<[u8; 32]> {
|
||||
let mut h = Sha256::new();
|
||||
h.update(b"wanderbooks backup v1 ");
|
||||
h.update(label.as_bytes());
|
||||
h.update(*self.master);
|
||||
Zeroizing::new(h.finalize().into())
|
||||
}
|
||||
|
||||
/// The sealing and naming keys.
|
||||
pub(crate) fn keys(&self) -> Keys {
|
||||
Keys {
|
||||
enc: self.label("encryption"),
|
||||
names: self.label("names"),
|
||||
kdf: self.kdf.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same key as another: the same passphrase and salt.
|
||||
pub fn same_as(&self, other: &BackupKey) -> bool {
|
||||
use subtle::ConstantTimeEq;
|
||||
self.kdf.salt == other.kdf.salt && bool::from(self.master.ct_eq(&*other.master))
|
||||
}
|
||||
|
||||
/// A short, public name for this key: what the salt it was derived
|
||||
/// with hashes to. Said in a record to tell one passphrase's backups
|
||||
/// from another's; it opens nothing.
|
||||
pub fn fingerprint(&self) -> String {
|
||||
sha_hex(self.kdf.salt.as_bytes())[..12].to_string()
|
||||
}
|
||||
|
||||
/// Keep it, privately, in the book's folder (INVARIANT: owner-only).
|
||||
pub fn store(&self, book_dir: &Path) -> Result<(), BackupError> {
|
||||
let dir = crate::root::private_book_folder(book_dir, LOCAL_DIR)
|
||||
.map_err(|e| BackupError::Damaged(e.to_string()))?;
|
||||
#[derive(Serialize)]
|
||||
struct OnDisk<'a> {
|
||||
version: u32,
|
||||
kdf: &'a Kdf,
|
||||
master: String,
|
||||
}
|
||||
let text = Zeroizing::new(
|
||||
serde_json::to_string_pretty(&OnDisk {
|
||||
version: 1,
|
||||
kdf: &self.kdf,
|
||||
master: hex::encode(*self.master),
|
||||
})
|
||||
.expect("a key serializes"),
|
||||
);
|
||||
let tmp = dir.join(format!(".{KEY_FILE}.new"));
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
crate::root::write_new_private_file(&tmp, text.as_bytes())?;
|
||||
std::fs::rename(&tmp, dir.join(KEY_FILE))?;
|
||||
super::io::sync_dir(&dir);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The key kept for the book in `book_dir`, if one is.
|
||||
pub fn load(book_dir: &Path) -> Result<Option<Self>, BackupError> {
|
||||
let path = book_dir.join(LOCAL_DIR).join(KEY_FILE);
|
||||
let text = match std::fs::read_to_string(&path) {
|
||||
Ok(t) => Zeroizing::new(t),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
#[derive(Deserialize)]
|
||||
struct OnDisk {
|
||||
version: u32,
|
||||
kdf: Kdf,
|
||||
master: String,
|
||||
}
|
||||
let bad = || BackupError::Damaged("the backup passphrase's key can't be read".into());
|
||||
let on: OnDisk = serde_json::from_str(&text).map_err(|_| bad())?;
|
||||
if on.version != 1 || !kdf_in_bounds(&on.kdf) {
|
||||
return Err(bad());
|
||||
}
|
||||
let master_hex = Zeroizing::new(on.master);
|
||||
let raw = Zeroizing::new(hex::decode(master_hex.as_str()).map_err(|_| bad())?);
|
||||
let master: [u8; 32] = raw.as_slice().try_into().map_err(|_| bad())?;
|
||||
Ok(Some(Self {
|
||||
kdf: on.kdf,
|
||||
master: Zeroizing::new(master),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Forget it (the passphrase is taken off): the next backup is plain.
|
||||
/// The file is removed from this computer only.
|
||||
pub fn forget(book_dir: &Path) -> Result<(), BackupError> {
|
||||
match std::fs::remove_file(book_dir.join(LOCAL_DIR).join(KEY_FILE)) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// The two keys a set uses.
|
||||
pub(crate) struct Keys {
|
||||
enc: Zeroizing<[u8; 32]>,
|
||||
names: Zeroizing<[u8; 32]>,
|
||||
kdf: Kdf,
|
||||
}
|
||||
|
||||
/// A sealed set's header: what another computer needs to derive the key,
|
||||
/// and a sealed check that tells a wrong passphrase from damage.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Header {
|
||||
pub format: String,
|
||||
pub version: u32,
|
||||
pub cipher: String,
|
||||
pub kdf: Kdf,
|
||||
/// Hex of the check text, sealed.
|
||||
pub check: String,
|
||||
/// SHA-256 of the sealed check, hex: it differs from the check only if
|
||||
/// the header was damaged.
|
||||
pub check_sha256: String,
|
||||
}
|
||||
|
||||
const HEADER_FORMAT: &str = "wanderbooks-backup-header";
|
||||
|
||||
impl Header {
|
||||
/// The header's file: JSON, a newline, and its own check line.
|
||||
pub(crate) fn encode(&self) -> Vec<u8> {
|
||||
let body = serde_json::to_string(self).expect("a header serializes");
|
||||
format!(
|
||||
"{body}\nwanderbooks-header-sha256 {}\n",
|
||||
sha_hex(body.as_bytes())
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// A header read back, or why it is not one.
|
||||
pub(crate) fn decode(bytes: &[u8]) -> Result<Self, BackupError> {
|
||||
let bad =
|
||||
|| BackupError::Damaged("the sealed backup's header is cut short or changed".into());
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| bad())?;
|
||||
let text = text.strip_suffix('\n').ok_or_else(bad)?;
|
||||
let (body, check) = text.rsplit_once('\n').ok_or_else(bad)?;
|
||||
if check.strip_prefix("wanderbooks-header-sha256 ") != Some(&sha_hex(body.as_bytes())) {
|
||||
return Err(bad());
|
||||
}
|
||||
let h: Header = serde_json::from_str(body).map_err(|_| bad())?;
|
||||
if h.format != HEADER_FORMAT || h.version != 1 || h.cipher != "xchacha20poly1305-stream" {
|
||||
return Err(BackupError::Damaged(
|
||||
"the sealed backup's header is of a kind this program doesn't know".into(),
|
||||
));
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
}
|
||||
|
||||
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, &header_aad(&self.kdf))
|
||||
.expect("sealing into memory");
|
||||
Header {
|
||||
format: HEADER_FORMAT.into(),
|
||||
version: 1,
|
||||
cipher: "xchacha20poly1305-stream".into(),
|
||||
kdf: self.kdf.clone(),
|
||||
check_sha256: sha_hex(&sealed),
|
||||
check: hex::encode(sealed),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether these keys open `header`'s check.
|
||||
pub(crate) fn check(&self, header: &Header) -> Result<(), BackupError> {
|
||||
let sealed = hex::decode(&header.check)
|
||||
.ok()
|
||||
.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[..], &header_aad(&header.kdf), &mut |b| {
|
||||
plain.extend_from_slice(b);
|
||||
Ok(())
|
||||
}) {
|
||||
Ok(()) if plain == CHECK_TEXT => Ok(()),
|
||||
_ => Err(BackupError::WrongPassphrase),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name a piece is kept under: made from the key, the piece's
|
||||
/// kind and its hash.
|
||||
pub(crate) fn piece_name(&self, kind: &str, sha: &str) -> String {
|
||||
let mut h = Sha256::new();
|
||||
h.update(*self.names);
|
||||
h.update(kind.as_bytes());
|
||||
h.update([0]);
|
||||
h.update(sha.as_bytes());
|
||||
hex::encode(h.finalize())
|
||||
}
|
||||
|
||||
fn cipher(&self) -> XChaCha20Poly1305 {
|
||||
XChaCha20Poly1305::new_from_slice(&self.enc[..]).expect("a 32-byte key")
|
||||
}
|
||||
|
||||
/// The length a piece of `plain` bytes is kept at.
|
||||
pub(crate) fn sealed_len(plain: u64) -> u64 {
|
||||
let chunks = plain.div_ceil(CHUNK as u64).max(1);
|
||||
(MAGIC.len() + 16) as u64 + plain + chunks * TAG as u64
|
||||
}
|
||||
|
||||
/// Seal all of `plain` into `out`, bound to `aad` (the piece's
|
||||
/// identity).
|
||||
pub(crate) fn seal_stream(
|
||||
&self,
|
||||
plain: &mut dyn Read,
|
||||
out: &mut dyn Write,
|
||||
aad: &[u8],
|
||||
) -> std::io::Result<()> {
|
||||
let cipher = self.cipher();
|
||||
let mut prefix = [0u8; 16];
|
||||
getrandom::getrandom(&mut prefix).map_err(std::io::Error::from)?;
|
||||
out.write_all(MAGIC)?;
|
||||
out.write_all(&prefix)?;
|
||||
let mut cur = read_full(plain, CHUNK)?;
|
||||
let mut counter = 0u64;
|
||||
loop {
|
||||
let next = read_full(plain, CHUNK)?;
|
||||
let last = next.is_empty();
|
||||
let mut nonce = [0u8; 24];
|
||||
nonce[..16].copy_from_slice(&prefix);
|
||||
nonce[16..].copy_from_slice(&counter.to_be_bytes());
|
||||
let mut a = aad.to_vec();
|
||||
a.push(u8::from(last));
|
||||
let ct = cipher
|
||||
.encrypt(&XNonce::from(nonce), Payload { msg: &cur, aad: &a })
|
||||
.map_err(|_| std::io::Error::other("sealing failed"))?;
|
||||
out.write_all(&ct)?;
|
||||
if last {
|
||||
return Ok(());
|
||||
}
|
||||
cur = next;
|
||||
counter += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a sealed piece, handing its contents to `sink` chunk by chunk.
|
||||
/// A wrong key, a changed byte, a piece cut short, or one bound to
|
||||
/// another identity is an error before the contents are complete; the
|
||||
/// caller discards what the sink had.
|
||||
pub(crate) fn open_stream(
|
||||
&self,
|
||||
stored: &mut dyn Read,
|
||||
aad: &[u8],
|
||||
sink: &mut dyn FnMut(&[u8]) -> std::io::Result<()>,
|
||||
) -> Result<(), BackupError> {
|
||||
let bad =
|
||||
|| BackupError::Damaged("a piece of the sealed backup is damaged or cut short".into());
|
||||
let cipher = self.cipher();
|
||||
let mut head = [0u8; 4 + 16];
|
||||
stored.read_exact(&mut head).map_err(|_| bad())?;
|
||||
if &head[..4] != MAGIC {
|
||||
return Err(bad());
|
||||
}
|
||||
let prefix: [u8; 16] = head[4..].try_into().expect("16 bytes");
|
||||
let mut cur = read_full(stored, CHUNK + TAG).map_err(super::io::uncarry)?;
|
||||
if cur.is_empty() {
|
||||
return Err(bad());
|
||||
}
|
||||
let mut counter = 0u64;
|
||||
loop {
|
||||
let next = read_full(stored, CHUNK + TAG).map_err(super::io::uncarry)?;
|
||||
let last = next.is_empty();
|
||||
let mut nonce = [0u8; 24];
|
||||
nonce[..16].copy_from_slice(&prefix);
|
||||
nonce[16..].copy_from_slice(&counter.to_be_bytes());
|
||||
let mut a = aad.to_vec();
|
||||
a.push(u8::from(last));
|
||||
let plain = cipher
|
||||
.decrypt(&XNonce::from(nonce), Payload { msg: &cur, aad: &a })
|
||||
.map_err(|_| bad())?;
|
||||
sink(&plain).map_err(super::io::uncarry)?;
|
||||
if last {
|
||||
return Ok(());
|
||||
}
|
||||
cur = next;
|
||||
counter += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// A small file sealed whole.
|
||||
pub(crate) fn seal_bytes(&self, plain: &[u8], aad: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
self.seal_stream(&mut &plain[..], &mut out, aad)
|
||||
.expect("sealing into memory");
|
||||
out
|
||||
}
|
||||
|
||||
/// A small file opened whole.
|
||||
pub(crate) fn open_bytes(&self, stored: &[u8], aad: &[u8]) -> Result<Vec<u8>, BackupError> {
|
||||
let mut out = Vec::new();
|
||||
self.open_stream(&mut &stored[..], aad, &mut |b| {
|
||||
out.extend_from_slice(b);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to `n` bytes from `r`: fewer only at its end.
|
||||
fn read_full(r: &mut dyn Read, n: usize) -> std::io::Result<Vec<u8>> {
|
||||
let mut buf = vec![0u8; n];
|
||||
let mut got = 0;
|
||||
while got < n {
|
||||
match r.read(&mut buf[got..]) {
|
||||
Ok(0) => break,
|
||||
Ok(k) => got += k,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
buf.truncate(got);
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// A piece's identity: what it is bound to when sealed.
|
||||
pub(crate) fn piece_aad(kind: &str, sha: &str) -> Vec<u8> {
|
||||
format!("wb1|{kind}|{sha}").into_bytes()
|
||||
}
|
||||
|
||||
/// A manifest's identity.
|
||||
pub(crate) fn manifest_aad(number: u64) -> Vec<u8> {
|
||||
format!("wb1|manifest|{number}").into_bytes()
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! The backup as one file ("Save a backup..."): a zip of the folder form
|
||||
//! of one set, holding one manifest and only the pieces it names. A zip is
|
||||
//! a file any computer can carry and a person can open to see what is
|
||||
//! inside. Sealed when the backups are: the pieces in it are the sealed
|
||||
//! pieces, so the file says no more than a sealed folder does.
|
||||
//!
|
||||
//! The extension is `.wbbackup`.
|
||||
|
||||
use super::cut::Cut;
|
||||
use super::io::{Fill, Put, PutKind, SetIo};
|
||||
use super::read::{Found, Set, verify_found};
|
||||
use super::write::{Written, proof_scratch, write_into_set};
|
||||
use super::{BackupError, Ctx};
|
||||
use std::collections::BTreeSet;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// The file's extension, without the dot.
|
||||
pub const FILE_EXTENSION: &str = "wbbackup";
|
||||
|
||||
/// A set read from a zip.
|
||||
struct ZipRead {
|
||||
archive: Mutex<zip::ZipArchive<std::fs::File>>,
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
impl SetIo for ZipRead {
|
||||
fn list(&self, dir: &str) -> std::io::Result<Vec<String>> {
|
||||
let prefix = format!("{}/", dir.trim_end_matches('/'));
|
||||
let archive = lock(&self.archive);
|
||||
let mut out: Vec<String> = archive
|
||||
.file_names()
|
||||
.filter_map(|n| n.ok())
|
||||
.filter_map(|n| n.strip_prefix(prefix.as_str()).map(str::to_string))
|
||||
.filter(|rest| !rest.is_empty() && !rest.contains('/'))
|
||||
.collect();
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn len(&self, rel: &str) -> std::io::Result<Option<u64>> {
|
||||
let mut archive = lock(&self.archive);
|
||||
match archive.by_name(rel) {
|
||||
Ok(f) if f.is_file() => Ok(Some(f.size())),
|
||||
Ok(_) | Err(zip::result::ZipError::FileNotFound) => Ok(None),
|
||||
Err(e) => Err(std::io::Error::other(e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_with(
|
||||
&self,
|
||||
rel: &str,
|
||||
f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>,
|
||||
) -> std::io::Result<()> {
|
||||
let mut archive = lock(&self.archive);
|
||||
let mut file = archive
|
||||
.by_name(rel)
|
||||
.map_err(|_| std::io::Error::from(std::io::ErrorKind::NotFound))?;
|
||||
f(&mut file)
|
||||
}
|
||||
|
||||
fn put(&self, _rel: &str, _kind: PutKind, _fill: Fill<'_>) -> std::io::Result<Put> {
|
||||
Err(std::io::Error::other("a backup file is read only"))
|
||||
}
|
||||
}
|
||||
|
||||
/// A zip being written. The writer is shared with [`save_file`], which
|
||||
/// finishes it.
|
||||
struct ZipWrite {
|
||||
writer: Arc<Mutex<Option<zip::ZipWriter<std::fs::File>>>>,
|
||||
names: Mutex<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
impl SetIo for ZipWrite {
|
||||
fn list(&self, _dir: &str) -> std::io::Result<Vec<String>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn len(&self, _rel: &str) -> std::io::Result<Option<u64>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn read_with(
|
||||
&self,
|
||||
_rel: &str,
|
||||
_f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>,
|
||||
) -> std::io::Result<()> {
|
||||
Err(std::io::Error::from(std::io::ErrorKind::NotFound))
|
||||
}
|
||||
|
||||
fn put(&self, rel: &str, _kind: PutKind, fill: Fill<'_>) -> std::io::Result<Put> {
|
||||
if !lock(&self.names).insert(rel.to_string()) {
|
||||
return Ok(Put::Existed);
|
||||
}
|
||||
// Text compresses; stored files and sealed pieces do not.
|
||||
let text = ["journal/", "access/", "files-index/", "manifests/"]
|
||||
.iter()
|
||||
.any(|p| rel.starts_with(p))
|
||||
|| rel == super::form::READ_ME;
|
||||
let method = if text {
|
||||
zip::CompressionMethod::Deflated
|
||||
} else {
|
||||
zip::CompressionMethod::Stored
|
||||
};
|
||||
let options = zip::write::SimpleFileOptions::default()
|
||||
.compression_method(method)
|
||||
.large_file(true);
|
||||
let mut guard = lock(&self.writer);
|
||||
let writer = guard
|
||||
.as_mut()
|
||||
.ok_or_else(|| std::io::Error::other("the backup file is finished"))?;
|
||||
writer
|
||||
.start_file(rel, options)
|
||||
.map_err(std::io::Error::other)?;
|
||||
fill(writer)?;
|
||||
Ok(Put::Created)
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a backup file for reading.
|
||||
pub(crate) fn open(path: &Path, _ctx: &Ctx) -> Result<Box<dyn SetIo>, BackupError> {
|
||||
let file = std::fs::File::open(path)?;
|
||||
let archive = zip::ZipArchive::new(file).map_err(|_| BackupError::NotABackup)?;
|
||||
Ok(Box::new(ZipRead {
|
||||
archive: Mutex::new(archive),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Write the cut as one file at `path` (which must not be there): the same
|
||||
/// contents as a backup folder, sealed when `key` is given. Written aside
|
||||
/// and moved into place only when whole, so a file by that name is a
|
||||
/// whole backup.
|
||||
pub fn save_file(
|
||||
path: &Path,
|
||||
cut: &Cut,
|
||||
key: Option<&super::BackupKey>,
|
||||
ctx: &Ctx,
|
||||
) -> Result<Written, BackupError> {
|
||||
if std::fs::symlink_metadata(path).is_ok() {
|
||||
return Err(BackupError::Damaged(
|
||||
"a file by that name is there already: choose another name".into(),
|
||||
));
|
||||
}
|
||||
let name = path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.ok_or(BackupError::NotABackup)?;
|
||||
let aside = path.with_file_name(format!(".{name}.partial"));
|
||||
let _ = std::fs::remove_file(&aside);
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&aside)?;
|
||||
let shared = Arc::new(Mutex::new(Some(zip::ZipWriter::new(file))));
|
||||
let set = Set {
|
||||
io: Box::new(ZipWrite {
|
||||
writer: shared.clone(),
|
||||
names: Mutex::new(BTreeSet::new()),
|
||||
}),
|
||||
keys: key.map(|k| k.keys()),
|
||||
ctx: ctx.clone(),
|
||||
};
|
||||
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()
|
||||
.ok_or_else(|| BackupError::Damaged("the backup file was finished twice".into()))?;
|
||||
let file = writer
|
||||
.finish()
|
||||
.map_err(|e| BackupError::Io(std::io::Error::other(e).kind()))?;
|
||||
file.sync_all()?;
|
||||
// Read back as a restore would read it, and proven whole (every
|
||||
// piece re-hashed, the chain replayed, the books opened), before it
|
||||
// is given its name: a file by that name is a backup that proved.
|
||||
let reader = Set {
|
||||
io: open(&aside, ctx)?,
|
||||
keys: key.map(|k| k.keys()),
|
||||
ctx: ctx.clone(),
|
||||
};
|
||||
let found = Found::of(reader, key.cloned(), cut.book());
|
||||
let scratch = proof_scratch(cut)?;
|
||||
let proven = verify_found(&found, &scratch, ctx);
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
proven?;
|
||||
Ok(written)
|
||||
});
|
||||
match result {
|
||||
Ok(written) => {
|
||||
// Moved into place only if the name is still free.
|
||||
let placed = std::fs::hard_link(&aside, path).or_else(|e| {
|
||||
if e.kind() == std::io::ErrorKind::AlreadyExists
|
||||
|| std::fs::symlink_metadata(path).is_ok()
|
||||
{
|
||||
Err(std::io::Error::from(std::io::ErrorKind::AlreadyExists))
|
||||
} else {
|
||||
std::fs::rename(&aside, path)
|
||||
}
|
||||
});
|
||||
let _ = std::fs::remove_file(&aside);
|
||||
placed?;
|
||||
Ok(written)
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&aside);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
//! Tests of the parts of a backup that need what the crate keeps to itself:
|
||||
//! how a failed link is told from a disk that makes none, what a sync
|
||||
//! service's stand-ins look like, the share of stored files each backup
|
||||
//! re-reads, and a destination with thousands of backups.
|
||||
|
||||
use super::Ctx;
|
||||
use super::cut::Cut;
|
||||
use super::form::*;
|
||||
use super::io::{dataless_flags, is_stand_in_name, link_unsupported, placeholder_attributes};
|
||||
use super::read::{Set, in_rotation};
|
||||
use super::write::{kept_form, write_into_set};
|
||||
use std::io::Write;
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn only_an_error_that_means_no_links_is_taken_to_mean_it() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
assert!(link_unsupported(&Error::from(ErrorKind::Unsupported)));
|
||||
// The name being taken, a missing folder, a refused permission and a
|
||||
// full disk are what they say: never a reason to try a rename, which
|
||||
// replaces.
|
||||
for kind in [
|
||||
ErrorKind::AlreadyExists,
|
||||
ErrorKind::NotFound,
|
||||
ErrorKind::PermissionDenied,
|
||||
ErrorKind::StorageFull,
|
||||
ErrorKind::Other,
|
||||
] {
|
||||
assert!(!link_unsupported(&Error::from(kind)), "{kind:?}");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
for n in [libc::EPERM, libc::ENOSYS, libc::EOPNOTSUPP, libc::ENOTSUP] {
|
||||
assert!(link_unsupported(&Error::from_raw_os_error(n)), "errno {n}");
|
||||
}
|
||||
for n in [
|
||||
libc::EACCES,
|
||||
libc::ENOENT,
|
||||
libc::EEXIST,
|
||||
libc::ENOSPC,
|
||||
libc::EIO,
|
||||
] {
|
||||
assert!(!link_unsupported(&Error::from_raw_os_error(n)), "errno {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_a_sync_service_leaves_for_a_file_it_has_not_downloaded_is_known() {
|
||||
// iCloud, before macOS 14: `.name.icloud` in the folder.
|
||||
assert!(is_stand_in_name(".000002.json.icloud"));
|
||||
assert!(is_stand_in_name(".a.icloud"));
|
||||
assert!(!is_stand_in_name("000002.json"));
|
||||
assert!(!is_stand_in_name(".wb-tmp-1-abc"));
|
||||
assert!(!is_stand_in_name(".icloud"));
|
||||
// Windows: offline (0x1000), recall on open (0x40000), recall on data
|
||||
// access (0x400000); a plain file (archive, 0x20) and a read-only one
|
||||
// (0x1) are not.
|
||||
for attrs in [0x1000, 0x40000, 0x400000, 0x20 | 0x400000] {
|
||||
assert!(placeholder_attributes(attrs), "{attrs:#x}");
|
||||
}
|
||||
for attrs in [0x20, 0x1, 0x80, 0x100] {
|
||||
assert!(!placeholder_attributes(attrs), "{attrs:#x}");
|
||||
}
|
||||
// macOS: SF_DATALESS.
|
||||
assert!(dataless_flags(0x4000_0000));
|
||||
assert!(!dataless_flags(0x0004_0000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_belongs_to_one_share_and_every_share_is_read_within_sixteen_backups() {
|
||||
use super::read::ROTATION;
|
||||
let mut x = 0x2545_f491_4f6c_dd1du64;
|
||||
for _ in 0..2000 {
|
||||
// A pseudo-random hash.
|
||||
let mut sha = String::new();
|
||||
while sha.len() < 64 {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
sha.push_str(&format!("{x:016x}"));
|
||||
}
|
||||
sha.truncate(64);
|
||||
for start in [1u64, 2, 17, 255, 3000] {
|
||||
let reads = (start..start + ROTATION)
|
||||
.filter(|n| in_rotation(&sha, *n))
|
||||
.count();
|
||||
assert_eq!(reads, 1, "{sha} from backup {start}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generations_and_set_names_round_trip() {
|
||||
assert_eq!(generation_path("files/ab/xyz", 0), "files/ab/xyz");
|
||||
assert_eq!(generation_path("files/ab/xyz", 2), "files/ab/xyz.g2");
|
||||
assert_eq!(split_generation("files/ab/xyz.g2"), ("files/ab/xyz", 2));
|
||||
assert_eq!(split_generation("files/ab/xyz"), ("files/ab/xyz", 0));
|
||||
assert_eq!(
|
||||
split_generation("journal/000001-abcd.g"),
|
||||
("journal/000001-abcd.g", 0)
|
||||
);
|
||||
assert_eq!(plain_set_name("con", 1), "wanderbooks-con");
|
||||
assert_eq!(plain_set_name("acme", 3), "wanderbooks-acme.3");
|
||||
assert_eq!(parse_plain_set_name("wanderbooks-acme"), Some(("acme", 1)));
|
||||
assert_eq!(
|
||||
parse_plain_set_name("wanderbooks-acme.3"),
|
||||
Some(("acme", 3))
|
||||
);
|
||||
// No book id holds a dot, so a later set is never another book's.
|
||||
assert_eq!(parse_plain_set_name("wanderbooks-acme.1"), None);
|
||||
assert_eq!(parse_plain_set_name("acme"), None);
|
||||
}
|
||||
|
||||
/// A `Set` over a fresh folder, nothing synced.
|
||||
fn fresh_set(root: &std::path::Path) -> (Set, std::path::PathBuf) {
|
||||
let at = root.join("disk/wanderbooks-acme");
|
||||
(Set::dir(at.clone(), None, &Ctx::new().with_no_sync()), at)
|
||||
}
|
||||
|
||||
/// What a person's backups look like after a while, made by the real
|
||||
/// writer: every manifest names every segment once read, but is kept as
|
||||
/// the one before it and what is new, and a chain is cut at 64.
|
||||
#[test]
|
||||
fn the_writers_manifests_chain_to_a_bounded_depth_and_are_proven_link_by_link() {
|
||||
const N: u64 = 150;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let book = dir.path().join("book");
|
||||
std::fs::create_dir(&book).unwrap();
|
||||
let ctx = Ctx::new().with_no_sync();
|
||||
let (set, at) = fresh_set(dir.path());
|
||||
// A journal of made-up lines: the writer never reads one, it hashes the
|
||||
// bytes and takes the head from the caller. Each backup adds a line.
|
||||
let mut journal = std::fs::File::create(book.join(crate::JOURNAL_FILE)).unwrap();
|
||||
for i in 1..=N {
|
||||
let line = format!("{{\"seq\":{i},\"pad\":\"{}\"}}", "x".repeat(60));
|
||||
writeln!(journal, "{line}").unwrap();
|
||||
journal.flush().unwrap();
|
||||
let cut = Cut::take("acme", &book, (i, sha_hex(line.as_bytes()))).unwrap();
|
||||
let w = write_into_set(&set, &cut, &ctx, false).unwrap();
|
||||
assert!(w.new && w.number == i);
|
||||
}
|
||||
let mut depths = Vec::new();
|
||||
for n in 1..=N {
|
||||
let m = set.manifest(n).unwrap();
|
||||
depths.push(m.depth);
|
||||
assert_eq!(m.journal.segments.len() as u64, n, "manifest {n}");
|
||||
let raw = std::fs::read_to_string(at.join(manifest_path(n, false))).unwrap();
|
||||
let stored: Manifest = serde_json::from_str(raw.lines().next().unwrap()).unwrap();
|
||||
assert_eq!(stored.depth == 0, stored.base.is_none());
|
||||
// A stored manifest that chains names only what is new.
|
||||
if stored.base.is_some() {
|
||||
assert_eq!(stored.journal.segments.len(), 1, "manifest {n}");
|
||||
assert_eq!(stored.journal.keep as u64, n - 1);
|
||||
}
|
||||
}
|
||||
// Chains of 64: a manifest that names everything at 1, 65, 129.
|
||||
assert_eq!(depths[0], 0);
|
||||
assert_eq!(depths[63], 63);
|
||||
assert_eq!(depths[64], 0);
|
||||
assert_eq!(depths[128], 0);
|
||||
assert!(depths.iter().all(|d| *d < DELTA_CHAIN));
|
||||
|
||||
// Each link is proven by the hash its successor holds: a manifest in
|
||||
// the chain that was changed makes the ones built on it unreadable, and
|
||||
// the reader takes the newest that still reads, saying how many it
|
||||
// passed.
|
||||
let k = N - 5;
|
||||
let bad = at.join(manifest_path(k, false));
|
||||
let mut bytes = std::fs::read(&bad).unwrap();
|
||||
let i = bytes.len() / 3;
|
||||
bytes[i] = if bytes[i] == b'0' { b'1' } else { b'0' };
|
||||
std::fs::write(&bad, bytes).unwrap();
|
||||
assert!(matches!(
|
||||
set.manifest(N),
|
||||
Err(super::BackupError::Damaged(_))
|
||||
));
|
||||
let (m, passed) = set.newest_whole().unwrap().unwrap();
|
||||
assert_eq!((m.number, passed as u64), (k - 1, N - k + 1));
|
||||
assert_eq!(m.journal.segments.len() as u64, k - 1);
|
||||
}
|
||||
|
||||
/// A destination of thousands of backups, made cheaply: the real forms
|
||||
/// (`kept_form`, `encode_manifest`) written straight into a folder with a
|
||||
/// one-byte file for each segment, no books and no syncing, then read as
|
||||
/// a restore reads it. The time and size are printed (the numbers the
|
||||
/// docs quote) and bounded.
|
||||
#[test]
|
||||
fn a_destination_of_thousands_of_backups_stays_small_and_quick_to_read() {
|
||||
const N: u64 = 3000;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (set, at) = fresh_set(dir.path());
|
||||
std::fs::create_dir_all(at.join("journal")).unwrap();
|
||||
std::fs::create_dir_all(at.join(MANIFESTS)).unwrap();
|
||||
let made = Instant::now();
|
||||
let mut full = Manifest {
|
||||
format: FORMAT.into(),
|
||||
version: VERSION,
|
||||
book: "acme".into(),
|
||||
number: 0,
|
||||
written: "2026-11-21T00:00:00Z".into(),
|
||||
head: Head {
|
||||
seq: 0,
|
||||
hash: String::new(),
|
||||
},
|
||||
journal: Series::default(),
|
||||
access: Series::default(),
|
||||
files: Series::default(),
|
||||
file_count: 0,
|
||||
file_bytes: 0,
|
||||
vault: Vec::new(),
|
||||
keys: Vec::new(),
|
||||
base: None,
|
||||
depth: 0,
|
||||
sha: String::new(),
|
||||
};
|
||||
let mut prev: Option<Manifest> = None;
|
||||
for i in 1..=N {
|
||||
let name = format!("journal/{i:06}-{i:016x}");
|
||||
std::fs::write(at.join(&name), b"x").unwrap();
|
||||
full.journal.segments.push(Piece {
|
||||
file: name,
|
||||
stored: 1,
|
||||
bytes: 1,
|
||||
sha256: format!("{i:064x}"),
|
||||
});
|
||||
full.journal.bytes = i;
|
||||
full.journal.sha256 = format!("{i:064x}");
|
||||
full.number = i;
|
||||
full.head = Head {
|
||||
seq: i,
|
||||
hash: format!("{i:064x}"),
|
||||
};
|
||||
let kept = kept_form(&full, prev.as_ref());
|
||||
let bytes = encode_manifest(&kept);
|
||||
std::fs::write(at.join(manifest_path(i, false)), &bytes).unwrap();
|
||||
let mut view = full.clone();
|
||||
view.depth = kept.depth;
|
||||
view.sha = decode_manifest(&bytes).unwrap().sha;
|
||||
prev = Some(view);
|
||||
}
|
||||
let made = made.elapsed();
|
||||
|
||||
let sizes: Vec<u64> = (1..=N)
|
||||
.map(|n| {
|
||||
std::fs::metadata(at.join(manifest_path(n, false)))
|
||||
.unwrap()
|
||||
.len()
|
||||
})
|
||||
.collect();
|
||||
let total: u64 = sizes.iter().sum();
|
||||
let largest = *sizes.iter().max().unwrap();
|
||||
let newest = *sizes.last().unwrap();
|
||||
// What it would have been if every manifest named everything: a
|
||||
// journal segment is ~170 bytes of a manifest.
|
||||
let everything: u64 = (1..=N).map(|n| 170 * n).sum();
|
||||
|
||||
// Read as a restore reads it: the newest found, and whole.
|
||||
let began = Instant::now();
|
||||
let (m, passed) = set.newest_whole().unwrap().unwrap();
|
||||
let found_in = began.elapsed();
|
||||
assert_eq!((m.number, passed), (N, 0));
|
||||
assert_eq!(m.journal.segments.len() as u64, N);
|
||||
let began = Instant::now();
|
||||
let numbers = set.numbers().unwrap().len();
|
||||
let listed_in = began.elapsed();
|
||||
assert_eq!(numbers as u64, N);
|
||||
println!(
|
||||
"{N} backups: manifests {total} bytes in all (named in full each time: ~{everything}), largest {largest}, newest {newest}; made in {made:?}; newest found and whole in {found_in:?}; listed in {listed_in:?}"
|
||||
);
|
||||
assert!(newest < 6 * 1024, "the newest manifest is {newest} bytes");
|
||||
assert!(total < everything / 20, "{total} of ~{everything}");
|
||||
assert!(found_in.as_secs() < 10, "{found_in:?}");
|
||||
// Any manifest in it reads whole (a sample: each read walks a chain).
|
||||
for n in (1..=N).step_by(131).chain([N - 1]) {
|
||||
let m = set.manifest(n).unwrap();
|
||||
assert_eq!(m.journal.segments.len() as u64, n);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,370 +0,0 @@
|
||||
//! Reading what a child process says, without waiting on a pipe it doesn't
|
||||
//! hold (P11c, found on Windows in the open/close hammer).
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: the output of a child that has ended is in hand once everything
|
||||
//! it wrote has been read, however long some other process keeps the
|
||||
//! other end of its pipe open.
|
||||
//! SOURCE: the standard library's `Command` (Windows: `CreateProcessW` with
|
||||
//! `bInheritHandles`, the child's end of each pipe inheritable from
|
||||
//! the moment it is made until the parent closes it, so a process
|
||||
//! started by another thread in that moment holds a copy and the
|
||||
//! pipe has no end-of-file until that process ends too); found by
|
||||
//! the open/close hammer on Windows (plan/p15-app-and-relay.md
|
||||
//! 3.1, D-77).
|
||||
//! INVARIANTS:
|
||||
//! 1. Nothing a child wrote is lost: bytes already in the pipe when the
|
||||
//! child ended are read before the reader is let go (the pipe is asked
|
||||
//! what it holds; the reader is let go only when it is blocked in its
|
||||
//! read with nothing in the pipe, for QUIET together).
|
||||
//! 2. The reader is let go when the pipe reaches its end (every writer
|
||||
//! gone), or when it is idle as in 1, or after `limit`, whichever is
|
||||
//! first; which one is reported ([`Closed`]).
|
||||
//! 3. A reader let go while still blocked ends by itself when the last
|
||||
//! holder of the pipe's other end lets go; it holds nothing else.
|
||||
//! ```
|
||||
|
||||
use std::io::Read;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a reader must be seen blocked in its read, with nothing in the
|
||||
/// pipe, before it is let go (INVARIANT 1): longer than any thread waits to
|
||||
/// run after it has been handed a byte.
|
||||
pub(crate) const QUIET: Duration = Duration::from_millis(100);
|
||||
|
||||
/// How long a reader in its read, with no read returning, is waited for when
|
||||
/// the pipe can't say whether it holds anything.
|
||||
const BLIND: Duration = Duration::from_millis(1500);
|
||||
|
||||
/// How the wait for a pipe ended.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Closed {
|
||||
/// The pipe reached its end: every writer was gone.
|
||||
Eof,
|
||||
/// Something else still held the pipe's other end, and nothing was left
|
||||
/// in it to read.
|
||||
Idle,
|
||||
/// The limit passed first; what had been read is what is returned.
|
||||
Limit,
|
||||
}
|
||||
|
||||
impl Closed {
|
||||
pub(crate) fn word(self) -> &'static str {
|
||||
match self {
|
||||
Closed::Eof => "eof",
|
||||
Closed::Idle => "held-open",
|
||||
Closed::Limit => "limit",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pipe being read on its own thread.
|
||||
pub(crate) struct Drain {
|
||||
bytes: Arc<Mutex<Vec<u8>>>,
|
||||
/// True while the pipe is open (its reader hasn't ended): guards the
|
||||
/// raw descriptor or handle asked about below.
|
||||
open: Arc<Mutex<bool>>,
|
||||
/// True from just before the reader calls `read` until it returns.
|
||||
reading: Arc<AtomicBool>,
|
||||
/// How many reads have returned.
|
||||
reads: Arc<AtomicU64>,
|
||||
raw: usize,
|
||||
cap: usize,
|
||||
}
|
||||
|
||||
/// The raw descriptor (Unix) or handle (Windows) of a pipe, as a number.
|
||||
pub(crate) trait Raw {
|
||||
fn raw(&self) -> usize;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl<T: std::os::unix::io::AsRawFd> Raw for T {
|
||||
fn raw(&self) -> usize {
|
||||
self.as_raw_fd() as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl<T: std::os::windows::io::AsRawHandle> Raw for T {
|
||||
fn raw(&self) -> usize {
|
||||
self.as_raw_handle() as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// How many bytes `pipe` holds now, if that can be asked: `None` when it
|
||||
/// can't (the pipe is at its end, or the question failed), which is never
|
||||
/// taken as "nothing".
|
||||
fn pending(raw: usize) -> Option<usize> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut fd = libc::pollfd {
|
||||
fd: raw as libc::c_int,
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
// SAFETY: one valid pollfd, and no wait.
|
||||
let ready = unsafe { libc::poll(&mut fd, 1, 0) };
|
||||
// Anything else is readable, or hung up (end of file), or failed:
|
||||
// never "nothing".
|
||||
if ready == 0 { Some(0) } else { None }
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
|
||||
let mut available: u32 = 0;
|
||||
// SAFETY: `raw` is a pipe handle that stays open while `open` is
|
||||
// held (the reader closes it only under that lock); no buffer is
|
||||
// asked for, only the count.
|
||||
let ok = unsafe {
|
||||
PeekNamedPipe(
|
||||
raw as *mut core::ffi::c_void,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
&mut available,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if ok == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(available as usize)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drain {
|
||||
/// Start reading `pipe` (if any) on a thread of its own, keeping the
|
||||
/// last `cap` bytes; `heard` is set to the milliseconds since `started`
|
||||
/// whenever a byte arrives.
|
||||
pub(crate) fn start<P>(
|
||||
pipe: Option<P>,
|
||||
cap: usize,
|
||||
started: Instant,
|
||||
heard: Arc<AtomicU64>,
|
||||
) -> Drain
|
||||
where
|
||||
P: Read + Raw + Send + 'static,
|
||||
{
|
||||
let bytes = Arc::new(Mutex::new(Vec::new()));
|
||||
let open = Arc::new(Mutex::new(pipe.is_some()));
|
||||
let reading = Arc::new(AtomicBool::new(false));
|
||||
let reads = Arc::new(AtomicU64::new(0));
|
||||
let raw = pipe.as_ref().map_or(0, Raw::raw);
|
||||
let (b, o, r, n_reads) = (bytes.clone(), open.clone(), reading.clone(), reads.clone());
|
||||
if let Some(mut p) = pipe {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
r.store(true, Ordering::SeqCst);
|
||||
let got = p.read(&mut buf);
|
||||
r.store(false, Ordering::SeqCst);
|
||||
n_reads.fetch_add(1, Ordering::SeqCst);
|
||||
match got {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
heard.store(started.elapsed().as_millis() as u64, Ordering::Relaxed);
|
||||
// Bounded: a git that says this much is kept
|
||||
// only in part, its last part (where its
|
||||
// errors are).
|
||||
let mut bytes = b.lock().unwrap_or_else(|e| e.into_inner());
|
||||
bytes.extend_from_slice(&buf[..n]);
|
||||
if bytes.len() > cap.saturating_mul(2) {
|
||||
let cut = bytes.len() - cap;
|
||||
bytes.drain(..cut);
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
// Closed under the lock the question above is asked under,
|
||||
// so a descriptor that is gone is never asked about.
|
||||
let mut open = o.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*open = false;
|
||||
drop(p);
|
||||
});
|
||||
}
|
||||
Drain {
|
||||
bytes,
|
||||
open,
|
||||
reading,
|
||||
reads,
|
||||
raw,
|
||||
cap,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pipe has reached its end.
|
||||
fn ended(&self) -> bool {
|
||||
!*self.open.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Whether the reader is blocked in its read with nothing in the pipe;
|
||||
/// when the pipe can't say what it holds, whether the reader is in its
|
||||
/// read (`None` is returned for the caller to weigh against time).
|
||||
fn idle(&self) -> Option<bool> {
|
||||
let open = self.open.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !*open || !self.reading.load(Ordering::SeqCst) {
|
||||
return Some(false);
|
||||
}
|
||||
pending(self.raw).map(|n| n == 0)
|
||||
}
|
||||
|
||||
/// What has been read, in whole (the last `cap` bytes of it).
|
||||
fn taken(&self) -> Vec<u8> {
|
||||
let mut bytes = self.bytes.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if bytes.len() > self.cap {
|
||||
let cut = bytes.len() - self.cap;
|
||||
bytes.drain(..cut);
|
||||
}
|
||||
std::mem::take(&mut *bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait, until `limit` after `since`, for every one of `drains` to reach
|
||||
/// its end or to be idle (INVARIANT 1 and 2), then take what each read: the
|
||||
/// bytes, and how its wait ended.
|
||||
pub(crate) fn finish<const N: usize>(
|
||||
drains: [&Drain; N],
|
||||
since: Instant,
|
||||
limit: Duration,
|
||||
) -> [(Vec<u8>, Closed); N] {
|
||||
// When each reader was first seen blocked in its read (with nothing in
|
||||
// the pipe, or the pipe unable to say), and the reads it had made then.
|
||||
let mut idle_since: [Option<Instant>; N] = [None; N];
|
||||
let mut blind_since: [Option<(Instant, u64)>; N] = [None; N];
|
||||
let mut how: [Option<Closed>; N] = [None; N];
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
for (i, d) in drains.iter().enumerate() {
|
||||
if how[i].is_some() {
|
||||
continue;
|
||||
}
|
||||
if d.ended() {
|
||||
how[i] = Some(Closed::Eof);
|
||||
} else {
|
||||
match d.idle() {
|
||||
Some(true) => {
|
||||
let since = *idle_since[i].get_or_insert(now);
|
||||
if now.duration_since(since) >= QUIET {
|
||||
how[i] = Some(Closed::Idle);
|
||||
}
|
||||
}
|
||||
Some(false) => {
|
||||
idle_since[i] = None;
|
||||
blind_since[i] = None;
|
||||
}
|
||||
// The pipe can't say what it holds: the reader in its
|
||||
// read, with no read returning for BLIND, is idle (a
|
||||
// reader is never kept from a byte for that long).
|
||||
None => {
|
||||
let reads = d.reads.load(Ordering::SeqCst);
|
||||
let (since, was) = *blind_since[i].get_or_insert((now, reads));
|
||||
if was != reads {
|
||||
blind_since[i] = Some((now, reads));
|
||||
} else if now.duration_since(since) >= BLIND {
|
||||
how[i] = Some(Closed::Idle);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if how.iter().all(Option::is_some) {
|
||||
break;
|
||||
}
|
||||
if now.duration_since(since) >= limit {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
// An end reached in the instant before this is read: its last bytes
|
||||
// are in, the reader having stored them before it ended.
|
||||
std::array::from_fn(|i| (drains[i].taken(), how[i].unwrap_or(Closed::Limit)))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
fn drained(child: &mut std::process::Child) -> (Drain, Drain) {
|
||||
let heard = Arc::new(AtomicU64::new(0));
|
||||
let now = Instant::now();
|
||||
(
|
||||
Drain::start(child.stdout.take(), usize::MAX, now, heard.clone()),
|
||||
Drain::start(child.stderr.take(), 1 << 20, now, heard),
|
||||
)
|
||||
}
|
||||
|
||||
/// INVARIANT 1 and 2. A child that ends, leaving a grandchild that
|
||||
/// still holds its pipes (the Windows leak, made by hand), has its
|
||||
/// whole output read, and the wait ends in far less than the limit.
|
||||
#[test]
|
||||
fn a_pipe_another_process_still_holds_is_read_in_whole_without_waiting_for_it() {
|
||||
let mut child = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("echo out-one; echo err-one >&2; (sleep 5 </dev/null) & echo out-two")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let status = child.wait().unwrap();
|
||||
assert!(status.success());
|
||||
let (out, err) = drained(&mut child);
|
||||
let began = Instant::now();
|
||||
let got = finish([&out, &err], began, Duration::from_secs(4));
|
||||
let took = began.elapsed();
|
||||
assert_eq!(String::from_utf8_lossy(&got[0].0), "out-one\nout-two\n");
|
||||
assert_eq!(String::from_utf8_lossy(&got[1].0), "err-one\n");
|
||||
assert_eq!(got[0].1, Closed::Idle, "held open, nothing left to read");
|
||||
assert_eq!(got[1].1, Closed::Idle);
|
||||
assert!(took < Duration::from_secs(2), "took {took:?}");
|
||||
}
|
||||
|
||||
/// INVARIANT 2. With nobody else holding the pipe, the end is the
|
||||
/// pipe's own, at once.
|
||||
#[test]
|
||||
fn a_pipe_nobody_holds_ends_at_its_end() {
|
||||
let mut child = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("echo said")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
child.wait().unwrap();
|
||||
let (out, err) = drained(&mut child);
|
||||
let began = Instant::now();
|
||||
let got = finish([&out, &err], began, Duration::from_secs(4));
|
||||
assert_eq!(String::from_utf8_lossy(&got[0].0), "said\n");
|
||||
assert_eq!((got[0].1, got[1].1), (Closed::Eof, Closed::Eof));
|
||||
assert!(began.elapsed() < QUIET * 5, "took {:?}", began.elapsed());
|
||||
}
|
||||
|
||||
/// INVARIANT 1. A lot of output, written and the writer gone before the
|
||||
/// reader is looked at, is read in whole.
|
||||
#[test]
|
||||
fn a_lot_of_output_is_read_in_whole() {
|
||||
let mut child = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("i=0; while [ $i -lt 20000 ]; do echo line-$i; i=$((i+1)); done; (sleep 3 </dev/null) &")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let heard = Arc::new(AtomicU64::new(0));
|
||||
let out = Drain::start(child.stdout.take(), usize::MAX, Instant::now(), heard);
|
||||
child.wait().unwrap();
|
||||
let got = finish([&out], Instant::now(), Duration::from_secs(4));
|
||||
let text = String::from_utf8_lossy(&got[0].0).to_string();
|
||||
assert_eq!(text.lines().count(), 20000);
|
||||
assert_eq!(text.lines().last(), Some("line-19999"));
|
||||
assert_eq!(got[0].1, Closed::Idle);
|
||||
}
|
||||
}
|
||||
@@ -1,554 +0,0 @@
|
||||
//! The lock files a git leaves in a repository, found and (only where it
|
||||
//! is ours to) removed through a directory handle (ledger-store `backup`
|
||||
//! INVARIANT 5).
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: a lock file a stopped git left can be seen, and removed from the
|
||||
//! one repository this program owns, without ever touching anything
|
||||
//! a swapped folder or link points to.
|
||||
//! SOURCE: the books server's close (ledger-mcp local.rs INVARIANT 10, 13:
|
||||
//! a close is answered with no git of ours still working, and
|
||||
//! leaves nothing a person must clean up); git's own lock files
|
||||
//! (git-config, gitrepository-layout: `HEAD.lock`, `index.lock`,
|
||||
//! `<ref>.lock`, `packed-refs.lock`, `shallow.lock`,
|
||||
//! `config.lock`).
|
||||
//! INVARIANTS:
|
||||
//! 1. A repository is opened once (`RepoDir::open`, `open_in`): a
|
||||
//! directory that is not a link, the folder it was found in kept as
|
||||
//! the book's own. Every look and every removal after that goes
|
||||
//! through that handle: the folders below it (`refs/`, and those
|
||||
//! under it) are each opened from the one above with links refused,
|
||||
//! so a folder swapped for a link, or the repository's own path swapped
|
||||
//! for one, after the handle was opened, sends nothing anywhere: the
|
||||
//! handle still names the folder that was opened.
|
||||
//! 2. Only a regular file is ever removed (never a link, never a folder,
|
||||
//! never a file whose type changed), and only one named as git names
|
||||
//! its locks, in the places git puts them (`is_lock`). A name that
|
||||
//! isn't one is refused.
|
||||
//! 3. Where there is no directory handle to be had (not Unix) each step
|
||||
//! looks at the path itself and refuses a link: the same rules,
|
||||
//! without the guarantee against a swap in between. Nothing else
|
||||
//! about the platform's behaviour is designed here.
|
||||
//! ```
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// Locks git makes in a repository's own folder.
|
||||
const TOP: [&str; 5] = [
|
||||
"HEAD.lock",
|
||||
"index.lock",
|
||||
"config.lock",
|
||||
"packed-refs.lock",
|
||||
"shallow.lock",
|
||||
];
|
||||
/// Locks git makes below it, outside `refs/`.
|
||||
const BELOW: [&str; 2] = [
|
||||
"objects/info/commit-graph.lock",
|
||||
"objects/pack/multi-pack-index.lock",
|
||||
];
|
||||
/// How deep under `refs/` a lock is looked for.
|
||||
const REFS_DEPTH: usize = 12;
|
||||
|
||||
/// Whether `rel` (a path in a repository, with `/` between its parts) is
|
||||
/// named as git names a lock, in a place git puts one (INVARIANT 2).
|
||||
pub fn is_lock(rel: &str) -> bool {
|
||||
if TOP.contains(&rel) || BELOW.contains(&rel) {
|
||||
return true;
|
||||
}
|
||||
let Some(under) = rel.strip_prefix("refs/") else {
|
||||
return false;
|
||||
};
|
||||
let parts: Vec<&str> = under.split('/').collect();
|
||||
parts.len() <= REFS_DEPTH
|
||||
&& parts
|
||||
.iter()
|
||||
.all(|p| !p.is_empty() && *p != "." && *p != "..")
|
||||
&& parts
|
||||
.last()
|
||||
.is_some_and(|name| name.len() > ".lock".len() && name.ends_with(".lock"))
|
||||
}
|
||||
|
||||
/// A lock found: its path in the repository, and when it was last written.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Found {
|
||||
/// `index.lock`, `refs/heads/main.lock`.
|
||||
pub lock: String,
|
||||
/// Its modification time, when the system said.
|
||||
pub modified: Option<SystemTime>,
|
||||
}
|
||||
|
||||
/// A repository's folder, opened once (INVARIANT 1).
|
||||
#[derive(Debug)]
|
||||
pub struct RepoDir {
|
||||
path: PathBuf,
|
||||
inner: imp::Dir,
|
||||
}
|
||||
|
||||
impl RepoDir {
|
||||
/// The folder at `path`, which must not itself be a link.
|
||||
pub fn open(path: &Path) -> io::Result<RepoDir> {
|
||||
Ok(RepoDir {
|
||||
path: path.to_path_buf(),
|
||||
inner: imp::open(path)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The folder `name` inside the folder `parent` (the book's own folder
|
||||
/// holding its archive): `name` must not be a link.
|
||||
pub fn open_in(parent: &Path, name: &str) -> io::Result<RepoDir> {
|
||||
Ok(RepoDir {
|
||||
path: parent.join(name),
|
||||
inner: imp::open_in(parent, name)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The path it was opened by (for words, never for an operation).
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// The locks in it, sorted: regular files named as git names its locks.
|
||||
pub fn locks(&self) -> Vec<Found> {
|
||||
let mut out = Vec::new();
|
||||
for rel in TOP.iter().chain(BELOW.iter()) {
|
||||
if let Some(modified) = self.inner.regular(rel) {
|
||||
out.push(Found {
|
||||
lock: (*rel).to_string(),
|
||||
modified,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.inner.refs(&mut out, REFS_DEPTH);
|
||||
out.sort_by(|a, b| a.lock.cmp(&b.lock));
|
||||
out
|
||||
}
|
||||
|
||||
/// Remove the lock `rel` (INVARIANTS 1, 2): Ok(true) if a regular file
|
||||
/// of that name was removed, Ok(false) if there was none (or it was
|
||||
/// not a regular file: nothing was done), Err if the name isn't a
|
||||
/// lock's or the system refused.
|
||||
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
||||
if !is_lock(rel) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"not a name git gives a lock",
|
||||
));
|
||||
}
|
||||
self.inner.remove(rel)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod imp {
|
||||
use super::{Found, SystemTime};
|
||||
use std::ffi::{CStr, CString, OsStr};
|
||||
use std::io;
|
||||
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Dir(OwnedFd);
|
||||
|
||||
const FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC;
|
||||
|
||||
fn c(text: &OsStr) -> io::Result<CString> {
|
||||
CString::new(text.as_bytes())
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a name with a NUL"))
|
||||
}
|
||||
|
||||
fn owned(fd: libc::c_int) -> io::Result<OwnedFd> {
|
||||
if fd < 0 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
// SAFETY: a file descriptor just returned by the system, owned
|
||||
// by no one else.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open(path: &Path) -> io::Result<Dir> {
|
||||
let path = c(path.as_os_str())?;
|
||||
// SAFETY: a NUL-ended path; the flags refuse a link at its end.
|
||||
owned(unsafe { libc::open(path.as_ptr(), FLAGS | libc::O_NOFOLLOW) }).map(Dir)
|
||||
}
|
||||
|
||||
pub fn open_in(parent: &Path, name: &str) -> io::Result<Dir> {
|
||||
let parent = c(parent.as_os_str())?;
|
||||
// SAFETY: as in `open`; the parent may be reached through links (it
|
||||
// is the book's own folder), only `name` may not be one.
|
||||
let parent = owned(unsafe { libc::open(parent.as_ptr(), FLAGS) })?;
|
||||
sub(parent.as_raw_fd(), name).map(Dir)
|
||||
}
|
||||
|
||||
/// The folder `name` of `dir`, a link refused.
|
||||
fn sub(dir: RawFd, name: &str) -> io::Result<OwnedFd> {
|
||||
let name = c(OsStr::new(name))?;
|
||||
// SAFETY: `dir` is open for the call; the name is NUL-ended.
|
||||
owned(unsafe { libc::openat(dir, name.as_ptr(), FLAGS | libc::O_NOFOLLOW) })
|
||||
}
|
||||
|
||||
/// `name` in `dir` as it is (a link is not followed): its stat.
|
||||
fn stat(dir: RawFd, name: &str) -> io::Result<libc::stat> {
|
||||
let name = c(OsStr::new(name))?;
|
||||
// SAFETY: zeroed stat is a valid out-parameter; `dir` is open.
|
||||
let mut st: libc::stat = unsafe { std::mem::zeroed() };
|
||||
let found =
|
||||
unsafe { libc::fstatat(dir, name.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) };
|
||||
if found == 0 {
|
||||
Ok(st)
|
||||
} else {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_regular(st: &libc::stat) -> bool {
|
||||
(st.st_mode & libc::S_IFMT) == libc::S_IFREG
|
||||
}
|
||||
|
||||
fn is_dir(st: &libc::stat) -> bool {
|
||||
(st.st_mode & libc::S_IFMT) == libc::S_IFDIR
|
||||
}
|
||||
|
||||
fn modified(st: &libc::stat) -> Option<SystemTime> {
|
||||
let secs = u64::try_from(st.st_mtime).ok()?;
|
||||
let nanos = u32::try_from(st.st_mtime_nsec).ok()?;
|
||||
Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs, nanos))
|
||||
}
|
||||
|
||||
/// The names in the folder `dir` (a fresh look each time).
|
||||
fn names(dir: RawFd) -> Vec<String> {
|
||||
// SAFETY: a duplicate of an open descriptor, handed to fdopendir,
|
||||
// which owns it from then on (closedir closes it).
|
||||
let copy = unsafe { libc::dup(dir) };
|
||||
if copy < 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let stream = unsafe { libc::fdopendir(copy) };
|
||||
if stream.is_null() {
|
||||
// SAFETY: fdopendir didn't take it.
|
||||
unsafe { libc::close(copy) };
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
// SAFETY: `stream` is a live directory stream until closedir; each
|
||||
// entry's name is a NUL-ended string valid until the next readdir.
|
||||
unsafe {
|
||||
libc::rewinddir(stream);
|
||||
loop {
|
||||
let entry = libc::readdir(stream);
|
||||
if entry.is_null() {
|
||||
break;
|
||||
}
|
||||
let name = CStr::from_ptr((*entry).d_name.as_ptr());
|
||||
if let Ok(name) = name.to_str()
|
||||
&& name != "."
|
||||
&& name != ".."
|
||||
{
|
||||
out.push(name.to_string());
|
||||
}
|
||||
}
|
||||
libc::closedir(stream);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Dir {
|
||||
/// The folder holding `rel`, opened step by step from this one
|
||||
/// with a link refused at each, and `rel`'s last part.
|
||||
fn parent_of<'a>(&self, rel: &'a str) -> io::Result<(OwnedFd, &'a str)> {
|
||||
let mut parts: Vec<&str> = rel.split('/').collect();
|
||||
let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?;
|
||||
// SAFETY: a duplicate of the open descriptor, owned here.
|
||||
let mut here = owned(unsafe { libc::dup(self.0.as_raw_fd()) })?;
|
||||
for part in parts {
|
||||
here = sub(here.as_raw_fd(), part)?;
|
||||
}
|
||||
Ok((here, last))
|
||||
}
|
||||
|
||||
/// A regular file at `rel`: its modification time (when known).
|
||||
pub fn regular(&self, rel: &str) -> Option<Option<SystemTime>> {
|
||||
let (parent, name) = self.parent_of(rel).ok()?;
|
||||
let st = stat(parent.as_raw_fd(), name).ok()?;
|
||||
is_regular(&st).then(|| modified(&st))
|
||||
}
|
||||
|
||||
/// The locks under `refs/`, in `out`.
|
||||
pub fn refs(&self, out: &mut Vec<Found>, depth: usize) {
|
||||
let Ok(refs) = sub(self.0.as_raw_fd(), "refs") else {
|
||||
return;
|
||||
};
|
||||
fn walk(dir: RawFd, prefix: &str, depth: usize, out: &mut Vec<Found>) {
|
||||
for name in names(dir) {
|
||||
let Ok(st) = stat(dir, &name) else { continue };
|
||||
let rel = format!("{prefix}{name}");
|
||||
if is_regular(&st) {
|
||||
if super::is_lock(&rel) {
|
||||
out.push(Found {
|
||||
lock: rel,
|
||||
modified: modified(&st),
|
||||
});
|
||||
}
|
||||
} else if is_dir(&st)
|
||||
&& depth > 0
|
||||
&& let Ok(inner) = sub(dir, &name)
|
||||
{
|
||||
walk(inner.as_raw_fd(), &format!("{rel}/"), depth - 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(refs.as_raw_fd(), "refs/", depth, out);
|
||||
}
|
||||
|
||||
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
||||
let (parent, name) = match self.parent_of(rel) {
|
||||
Ok(found) => found,
|
||||
// A folder that isn't there (or is a link): nothing to remove.
|
||||
Err(_) => return Ok(false),
|
||||
};
|
||||
match stat(parent.as_raw_fd(), name) {
|
||||
Ok(st) if is_regular(&st) => {}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
let name = c(OsStr::new(name))?;
|
||||
// SAFETY: the parent is open; the name is NUL-ended and relative
|
||||
// to it, and names a regular file just looked at.
|
||||
let removed = unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), 0) };
|
||||
if removed == 0 {
|
||||
Ok(true)
|
||||
} else {
|
||||
let e = io::Error::last_os_error();
|
||||
if e.kind() == io::ErrorKind::NotFound {
|
||||
Ok(false)
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
mod imp {
|
||||
use super::{Found, SystemTime};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Dir(PathBuf);
|
||||
|
||||
fn plain(path: &Path) -> io::Result<()> {
|
||||
let meta = std::fs::symlink_metadata(path)?;
|
||||
if meta.file_type().is_symlink() || !meta.is_dir() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"not a plain folder",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn open(path: &Path) -> io::Result<Dir> {
|
||||
plain(path)?;
|
||||
Ok(Dir(path.to_path_buf()))
|
||||
}
|
||||
|
||||
pub fn open_in(parent: &Path, name: &str) -> io::Result<Dir> {
|
||||
open(&parent.join(name))
|
||||
}
|
||||
|
||||
impl Dir {
|
||||
fn at(&self, rel: &str) -> io::Result<PathBuf> {
|
||||
let mut path = self.0.clone();
|
||||
let mut parts: Vec<&str> = rel.split('/').collect();
|
||||
let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?;
|
||||
for part in parts {
|
||||
path.push(part);
|
||||
plain(&path)?;
|
||||
}
|
||||
path.push(last);
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub fn regular(&self, rel: &str) -> Option<Option<SystemTime>> {
|
||||
let path = self.at(rel).ok()?;
|
||||
let meta = std::fs::symlink_metadata(path).ok()?;
|
||||
meta.file_type().is_file().then(|| meta.modified().ok())
|
||||
}
|
||||
|
||||
pub fn refs(&self, out: &mut Vec<Found>, depth: usize) {
|
||||
fn walk(dir: &Path, prefix: &str, depth: usize, out: &mut Vec<Found>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let Ok(meta) = std::fs::symlink_metadata(e.path()) else {
|
||||
continue;
|
||||
};
|
||||
let rel = format!("{prefix}{}", e.file_name().to_string_lossy());
|
||||
if meta.file_type().is_file() {
|
||||
if super::is_lock(&rel) {
|
||||
out.push(Found {
|
||||
lock: rel,
|
||||
modified: meta.modified().ok(),
|
||||
});
|
||||
}
|
||||
} else if meta.is_dir() && !meta.file_type().is_symlink() && depth > 0 {
|
||||
walk(&e.path(), &format!("{rel}/"), depth - 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let refs = self.0.join("refs");
|
||||
if plain(&refs).is_ok() {
|
||||
walk(&refs, "refs/", depth, out);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
||||
let Ok(path) = self.at(rel) else {
|
||||
return Ok(false);
|
||||
};
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(meta) if meta.file_type().is_file() => std::fs::remove_file(path).map(|()| true),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn repo(dir: &Path) -> PathBuf {
|
||||
let repo = dir.join("repo.git");
|
||||
std::fs::create_dir_all(repo.join("refs/heads")).unwrap();
|
||||
std::fs::create_dir_all(repo.join("objects/pack")).unwrap();
|
||||
std::fs::create_dir_all(repo.join("objects/info")).unwrap();
|
||||
repo
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_names_git_gives_its_locks_are_locks() {
|
||||
for yes in [
|
||||
"HEAD.lock",
|
||||
"index.lock",
|
||||
"config.lock",
|
||||
"packed-refs.lock",
|
||||
"shallow.lock",
|
||||
"refs/heads/main.lock",
|
||||
"refs/heads/feature/x.lock",
|
||||
"refs/tags/v1.lock",
|
||||
"objects/info/commit-graph.lock",
|
||||
"objects/pack/multi-pack-index.lock",
|
||||
] {
|
||||
assert!(is_lock(yes), "{yes}");
|
||||
}
|
||||
for no in [
|
||||
"",
|
||||
".lock",
|
||||
"refs/.lock",
|
||||
"refs/heads/",
|
||||
"refs/heads/main",
|
||||
"refs/heads/../../x.lock",
|
||||
"refs//x.lock",
|
||||
"refs/heads/./x.lock",
|
||||
"other.lock",
|
||||
"objects/pack/pack-1.pack",
|
||||
"objects/other.lock",
|
||||
"../index.lock",
|
||||
"/etc/x.lock",
|
||||
"hooks/pre-commit.lock",
|
||||
"refs",
|
||||
] {
|
||||
assert!(!is_lock(no), "{no:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locks_are_found_and_only_regular_files_are_removed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repo = repo(dir.path());
|
||||
std::fs::write(repo.join("index.lock"), b"").unwrap();
|
||||
std::fs::write(repo.join("refs/heads/main.lock"), b"").unwrap();
|
||||
// Named like locks, but not files: neither is listed nor removed.
|
||||
std::fs::create_dir(repo.join("HEAD.lock")).unwrap();
|
||||
std::fs::write(dir.path().join("elsewhere"), b"").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(dir.path().join("elsewhere"), repo.join("config.lock")).unwrap();
|
||||
// Not a lock's name.
|
||||
std::fs::write(repo.join("refs/heads/main"), b"").unwrap();
|
||||
let handle = RepoDir::open(&repo).unwrap();
|
||||
let found: Vec<String> = handle.locks().into_iter().map(|f| f.lock).collect();
|
||||
assert_eq!(found, ["index.lock", "refs/heads/main.lock"]);
|
||||
assert!(handle.locks().iter().all(|f| f.modified.is_some()));
|
||||
assert!(handle.remove("index.lock").unwrap());
|
||||
assert!(!handle.remove("index.lock").unwrap(), "already gone");
|
||||
assert!(!handle.remove("HEAD.lock").unwrap(), "a folder stays");
|
||||
assert!(repo.join("HEAD.lock").is_dir());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
assert!(!handle.remove("config.lock").unwrap(), "a link stays");
|
||||
assert!(repo.join("config.lock").is_symlink());
|
||||
assert!(dir.path().join("elsewhere").exists());
|
||||
}
|
||||
assert!(handle.remove("refs/heads/main").is_err(), "not a lock");
|
||||
assert!(repo.join("refs/heads/main").exists());
|
||||
assert!(handle.remove("../elsewhere.lock").is_err());
|
||||
}
|
||||
|
||||
/// INVARIANT 1: a folder (or the repository's own path) swapped for a
|
||||
/// link after the handle was opened sends nothing anywhere.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_folder_swapped_for_a_link_after_the_handle_was_opened_touches_nothing_outside() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let outside = dir.path().join("outside");
|
||||
std::fs::create_dir_all(outside.join("refs/heads")).unwrap();
|
||||
for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] {
|
||||
std::fs::write(outside.join(lock), b"theirs").unwrap();
|
||||
}
|
||||
// `refs` swapped for a link to a folder holding a lock of that name.
|
||||
let repo_path = repo(dir.path());
|
||||
std::fs::write(repo_path.join("refs/heads/main.lock"), b"ours").unwrap();
|
||||
let handle = RepoDir::open(&repo_path).unwrap();
|
||||
std::fs::rename(repo_path.join("refs"), dir.path().join("refs-moved")).unwrap();
|
||||
std::os::unix::fs::symlink(outside.join("refs"), repo_path.join("refs")).unwrap();
|
||||
assert!(!handle.remove("refs/heads/main.lock").unwrap());
|
||||
assert!(handle.locks().is_empty(), "a link is not looked through");
|
||||
assert_eq!(
|
||||
std::fs::read(outside.join("refs/heads/main.lock")).unwrap(),
|
||||
b"theirs"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(dir.path().join("refs-moved/heads/main.lock")).unwrap(),
|
||||
b"ours",
|
||||
"nor was the folder it moved to touched through the link"
|
||||
);
|
||||
// The repository's own path swapped for a link: the handle still
|
||||
// names the folder it opened (moved aside), and the link's target
|
||||
// is never touched.
|
||||
let second = dir.path().join("second.git");
|
||||
std::fs::create_dir_all(second.join("refs")).unwrap();
|
||||
std::fs::write(second.join("index.lock"), b"ours").unwrap();
|
||||
let handle = RepoDir::open(&second).unwrap();
|
||||
std::fs::rename(&second, dir.path().join("second-moved.git")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, &second).unwrap();
|
||||
assert!(handle.remove("index.lock").unwrap());
|
||||
assert!(!dir.path().join("second-moved.git/index.lock").exists());
|
||||
assert_eq!(
|
||||
std::fs::read(outside.join("index.lock")).unwrap(),
|
||||
b"theirs",
|
||||
"the link's target was touched"
|
||||
);
|
||||
assert_eq!(std::fs::read(outside.join("HEAD.lock")).unwrap(), b"theirs");
|
||||
// And a repository that is a link when the handle is opened is
|
||||
// refused, with the archive's own `open_in` too.
|
||||
assert!(RepoDir::open(&second).is_err());
|
||||
assert!(RepoDir::open_in(dir.path(), "second.git").is_err());
|
||||
assert!(RepoDir::open_in(dir.path(), "second-moved.git").is_ok());
|
||||
}
|
||||
}
|
||||
@@ -25,12 +25,10 @@ pub mod blob;
|
||||
pub mod cancel;
|
||||
pub mod chain;
|
||||
pub mod describe;
|
||||
mod drain;
|
||||
pub mod error;
|
||||
pub mod exports;
|
||||
pub mod form1099;
|
||||
pub mod format;
|
||||
pub mod git_locks;
|
||||
pub mod journal;
|
||||
pub mod lock;
|
||||
pub mod meta;
|
||||
|
||||
@@ -16,8 +16,9 @@
|
||||
//! every process that could still hold it: a child forked by another
|
||||
//! thread of this process holds a copy of every open descriptor (this
|
||||
//! lock's too) from its fork until its exec, and a `flock` lasts as
|
||||
//! long as any copy does. Every child this crate starts is started by
|
||||
//! [`spawn`], and dropping a [`WriterLock`] returns only once every
|
||||
//! long as any copy does. Every child a process that holds a store starts
|
||||
//! is started by [`spawn`] (the store itself starts none since backups
|
||||
//! became plain files, D-91; the seam stays for any that does), and dropping a [`WriterLock`] returns only once every
|
||||
//! [`spawn`] begun before it has ended (its child has exec'd and the
|
||||
//! copies are closed), and then the lock is taken afresh and let go
|
||||
//! (it is free, or another writer has it, or 500 ms passed: the system
|
||||
|
||||
@@ -196,7 +196,7 @@ impl JobStop {
|
||||
self
|
||||
}
|
||||
|
||||
/// The flag: what git and the store's loops are handed to look at.
|
||||
/// The flag: what a backup's copy and the store's loops are handed to look at.
|
||||
pub fn flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
|
||||
self.flag.clone()
|
||||
}
|
||||
@@ -229,7 +229,7 @@ impl JobStop {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stop that reached the store's own loops or git, said as a job's.
|
||||
/// A stop that reached the store's own loops or a backup's copy, said as a job's.
|
||||
fn said(&self, e: RootError, undone: &str) -> RootError {
|
||||
match e {
|
||||
RootError::Store(_, StoreError::Cancelled) => RootError::Stopped(format!(
|
||||
@@ -1146,6 +1146,15 @@ pub struct RestorePreview {
|
||||
pub exists: bool,
|
||||
/// The id of the books it holds, as they were backed up.
|
||||
pub origin: Option<String>,
|
||||
/// Whether it is protected by a passphrase.
|
||||
pub sealed: bool,
|
||||
/// Newer backups in it that were not whole or were damaged and were
|
||||
/// passed over: not zero means this is not the newest backup there is.
|
||||
pub passed_over: u64,
|
||||
/// When this backup was made (UTC).
|
||||
pub written: Option<String>,
|
||||
/// When the newest backup there is was made (UTC), if it can be read.
|
||||
pub newest_written: Option<String>,
|
||||
}
|
||||
|
||||
/// What [`Root::restore`] did.
|
||||
@@ -1166,21 +1175,21 @@ pub struct RestoreReport {
|
||||
}
|
||||
|
||||
impl Root {
|
||||
/// Clone the backup at `source` (a git repository's address, or its
|
||||
/// folder: `<book>.git` in a backup folder) into a scratch folder in `books/` and prove it
|
||||
/// whole (backup.rs INVARIANT 3); the caller holds the books lock and
|
||||
/// removes the folder.
|
||||
/// Find the backup at `source` (a destination folder, one set's own
|
||||
/// folder, or a backup file), prove it whole (backup INVARIANT 3), and
|
||||
/// build its books in a scratch folder in `books/`, with every stored
|
||||
/// file when `with_files`; the caller holds the books lock and removes
|
||||
/// the folder.
|
||||
fn fetch_backup(
|
||||
&self,
|
||||
git: &crate::backup::Git,
|
||||
source: &str,
|
||||
source: &Path,
|
||||
passphrase: Option<&str>,
|
||||
books: &Path,
|
||||
id: &BookId,
|
||||
stop: &JobStop,
|
||||
) -> Result<(PathBuf, crate::backup::Verified), RootError> {
|
||||
stop.at("fetch", "restored")?;
|
||||
// git, and the verification's own phases and loops, look at the stop.
|
||||
let git = git.clone().with_cancel(stop.flag());
|
||||
let ctx = crate::backup::Ctx::new().with_stop(stop.flag());
|
||||
// Anything left from one that never finished goes first: none is
|
||||
// in progress (each holds the books lock).
|
||||
for entry in std::fs::read_dir(books)? {
|
||||
@@ -1194,7 +1203,9 @@ impl Root {
|
||||
}
|
||||
}
|
||||
let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id()));
|
||||
match crate::backup::verify(&git, source, &scratch) {
|
||||
let proven = crate::backup::find(source, passphrase, &ctx)
|
||||
.and_then(|found| crate::backup::verify_found(&found, &scratch, &ctx));
|
||||
match proven {
|
||||
Ok(v) => Ok((scratch, v)),
|
||||
Err(e) => {
|
||||
// What the verification wrote goes with it (a stop leaves the
|
||||
@@ -1214,19 +1225,19 @@ impl Root {
|
||||
/// proven as [`Self::restore`] proves it, adding nothing to the root.
|
||||
pub fn restore_preview(
|
||||
&self,
|
||||
git: &crate::backup::Git,
|
||||
source: &str,
|
||||
source: &Path,
|
||||
passphrase: Option<&str>,
|
||||
id: &BookId,
|
||||
) -> Result<RestorePreview, RootError> {
|
||||
self.restore_preview_stoppable(git, source, id, &JobStop::never())
|
||||
self.restore_preview_stoppable(source, passphrase, id, &JobStop::never())
|
||||
}
|
||||
|
||||
/// [`Self::restore_preview`], stopped if `stop` asks: the clone is
|
||||
/// removed and nothing is left.
|
||||
pub fn restore_preview_stoppable(
|
||||
&self,
|
||||
git: &crate::backup::Git,
|
||||
source: &str,
|
||||
source: &Path,
|
||||
passphrase: Option<&str>,
|
||||
id: &BookId,
|
||||
stop: &JobStop,
|
||||
) -> Result<RestorePreview, RootError> {
|
||||
@@ -1234,7 +1245,7 @@ impl Root {
|
||||
(|| {
|
||||
let _lock = self.books_lock(stop, "restored")?;
|
||||
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
||||
let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?;
|
||||
let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop)?;
|
||||
let vault = scratch.join(VAULT_DIR);
|
||||
let vault_files = if vault.is_dir() {
|
||||
std::fs::read_dir(&vault)
|
||||
@@ -1250,6 +1261,10 @@ impl Root {
|
||||
vault_files,
|
||||
exists: std::fs::symlink_metadata(books.join(id.as_str())).is_ok(),
|
||||
origin: v.book,
|
||||
sealed: v.key.is_some(),
|
||||
passed_over: v.passed_over as u64,
|
||||
written: Some(v.written.clone()),
|
||||
newest_written: v.newest_written.clone(),
|
||||
})
|
||||
})()
|
||||
.map_err(|e| self.hide(e))
|
||||
@@ -1264,13 +1279,20 @@ impl Root {
|
||||
/// first, kept whole; refused while anything holds them open.
|
||||
pub fn restore(
|
||||
&self,
|
||||
git: &crate::backup::Git,
|
||||
source: &str,
|
||||
source: &Path,
|
||||
passphrase: Option<&str>,
|
||||
id: &BookId,
|
||||
expect_head: &(u64, String),
|
||||
replace: bool,
|
||||
) -> Result<RestoreReport, RootError> {
|
||||
self.restore_stoppable(git, source, id, expect_head, replace, &JobStop::never())
|
||||
self.restore_stoppable(
|
||||
source,
|
||||
passphrase,
|
||||
id,
|
||||
expect_head,
|
||||
replace,
|
||||
&JobStop::never(),
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Self::restore`], stopped if `stop` asks at any phase before the
|
||||
@@ -1280,14 +1302,14 @@ impl Root {
|
||||
/// finishes: two renames and two directory syncs.
|
||||
pub fn restore_stoppable(
|
||||
&self,
|
||||
git: &crate::backup::Git,
|
||||
source: &str,
|
||||
source: &Path,
|
||||
passphrase: Option<&str>,
|
||||
id: &BookId,
|
||||
expect_head: &(u64, String),
|
||||
replace: bool,
|
||||
stop: &JobStop,
|
||||
) -> Result<RestoreReport, RootError> {
|
||||
self.restore_inner(git, source, id, expect_head, replace, stop)
|
||||
self.restore_inner(source, passphrase, id, expect_head, replace, stop)
|
||||
.map_err(|e| match e {
|
||||
// The copy's checks are the adoption's: said as a restore.
|
||||
RootError::Adopt(text) => {
|
||||
@@ -1300,8 +1322,8 @@ impl Root {
|
||||
|
||||
fn restore_inner(
|
||||
&self,
|
||||
git: &crate::backup::Git,
|
||||
source: &str,
|
||||
source: &Path,
|
||||
passphrase: Option<&str>,
|
||||
id: &BookId,
|
||||
expect_head: &(u64, String),
|
||||
replace: bool,
|
||||
@@ -1337,7 +1359,7 @@ impl Root {
|
||||
};
|
||||
stop.at("start", "restored")?;
|
||||
let _scope = crate::cancel::scope(stop.flag());
|
||||
let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?;
|
||||
let (scratch, v) = self.fetch_backup(source, passphrase, &books, id, stop)?;
|
||||
let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id()));
|
||||
let built = (|| -> Result<RestoreReport, RootError> {
|
||||
stop.at("copy", "restored")?;
|
||||
@@ -1377,11 +1399,12 @@ impl Root {
|
||||
&std::fs::read(&access)?,
|
||||
)?;
|
||||
}
|
||||
// Its backup history: the next backup carries on from it.
|
||||
std::fs::rename(
|
||||
scratch.join(".git"),
|
||||
staging.join(crate::backup::ARCHIVE_DIR),
|
||||
)?;
|
||||
// A sealed backup keeps its key: the restored books carry on
|
||||
// backing up sealed, to the same place, with no question asked.
|
||||
if let Some(key) = &v.key {
|
||||
key.store(&staging)
|
||||
.map_err(|e| RootError::Adopt(format!("that backup can't be restored: {e}")))?;
|
||||
}
|
||||
// Whose books they were, placed with them.
|
||||
crate::ops::prepare(&staging)?;
|
||||
write_private_file(
|
||||
|
||||
@@ -0,0 +1,980 @@
|
||||
//! Backups in plain folders (WB-backup-1 to WB-backup-9): what a backup
|
||||
//! is, that it only grows, that a restore of any whole manifest is a
|
||||
//! prefix of the books, that two writers do not corrupt one destination,
|
||||
//! that a program that dies at any write leaves a destination that proves
|
||||
//! whole at its previous manifest, that a flipped or cut piece is never
|
||||
//! restored, and that a wrong passphrase never yields books.
|
||||
|
||||
use ledger_core::{AccountType, Currency, Money, Side};
|
||||
use ledger_store::Store;
|
||||
use ledger_store::backup::{
|
||||
BackupError, BackupKey, Ctx, Cut, Destination, find, save_file, verify_found, write_destination,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn usd(s: &str) -> Money {
|
||||
Money::new(s.parse().unwrap(), Currency::USD)
|
||||
}
|
||||
|
||||
/// A book with a few entries and a stored file.
|
||||
fn book(dir: &Path) -> Store {
|
||||
let mut s = Store::create(dir, Currency::USD).unwrap();
|
||||
let cash = s
|
||||
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let cap = s
|
||||
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||
.unwrap();
|
||||
let e = s
|
||||
.create_entry(
|
||||
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
|
||||
"Start",
|
||||
)
|
||||
.unwrap();
|
||||
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
|
||||
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// One more write to the books: an account and a stored file.
|
||||
fn more(s: &mut Store, n: usize) {
|
||||
s.add_account(
|
||||
&format!("{}", 6000 + n),
|
||||
&format!("Expense {n}"),
|
||||
AccountType::Expense,
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
s.attach_receipt(
|
||||
None,
|
||||
&format!("f{n}.txt"),
|
||||
"text/plain",
|
||||
format!("receipt number {n}").as_bytes(),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn cut(dir: &Path, s: &Store) -> Cut {
|
||||
Cut::take("acme", dir, s.head()).unwrap()
|
||||
}
|
||||
|
||||
fn plain(folder: &Path) -> Destination {
|
||||
Destination {
|
||||
folder: folder.to_path_buf(),
|
||||
key: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file under `root`, by relative path, with its bytes.
|
||||
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let p = e.unwrap().path();
|
||||
if p.is_dir() {
|
||||
walk(base, &p, out);
|
||||
} else {
|
||||
let rel = p
|
||||
.strip_prefix(base)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
out.insert(rel, std::fs::read(&p).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
if root.is_dir() {
|
||||
walk(root, root, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Prove the backup at `source` and give the books it holds, built in a
|
||||
/// scratch folder next to `root`.
|
||||
fn prove(
|
||||
source: &Path,
|
||||
pass: Option<&str>,
|
||||
root: &Path,
|
||||
name: &str,
|
||||
) -> Result<ledger_store::backup::Verified, BackupError> {
|
||||
let found = find(source, pass, &Ctx::new())?;
|
||||
verify_found(&found, &root.join(name), &Ctx::new())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backup_is_the_book_and_proves_whole() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(w.new);
|
||||
assert_eq!(w.number, 1);
|
||||
assert_eq!(w.head, s.head());
|
||||
|
||||
// The form on disk: a folder for the books, a read-me, one manifest,
|
||||
// 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 == "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.
|
||||
let again = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(!again.new);
|
||||
assert_eq!(again.number, 1);
|
||||
assert_eq!(tree(&disk), t);
|
||||
|
||||
// Proven, and the books it holds are the book.
|
||||
let v = prove(&disk, None, dir.path(), "v1").unwrap();
|
||||
assert_eq!(v.head, s.head());
|
||||
assert_eq!(v.blobs, 1);
|
||||
assert_eq!(v.book.as_deref(), Some("acme"));
|
||||
assert_eq!(
|
||||
std::fs::read(v.tree.join("journal.jsonl")).unwrap(),
|
||||
std::fs::read(b.join("journal.jsonl")).unwrap()
|
||||
);
|
||||
|
||||
// More writes: a new manifest and new pieces; the old ones untouched.
|
||||
more(&mut s, 1);
|
||||
let w2 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert_eq!(w2.number, 2);
|
||||
let t2 = tree(&disk);
|
||||
for (name, bytes) in &t {
|
||||
assert_eq!(t2.get(name), Some(bytes), "{name} must not change");
|
||||
}
|
||||
assert!(t2.len() > t.len());
|
||||
let v2 = prove(&disk, None, dir.path(), "v2").unwrap();
|
||||
assert_eq!(v2.head, s.head());
|
||||
assert_eq!(v2.blobs, 2);
|
||||
// No scratch file of ours is left behind.
|
||||
assert!(!t2.keys().any(|n| n.contains(".wb-tmp-")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destination_of_other_books_or_another_history_is_never_written() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (b1, b2) = (dir.path().join("one"), dir.path().join("two"));
|
||||
let (mut s1, s2) = (book(&b1), book(&b2));
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
|
||||
let before = tree(&disk);
|
||||
// The same id, another history (a different journal from the start).
|
||||
assert_eq!(
|
||||
write_destination(&plain(&disk), &cut(&b2, &s2), true, &Ctx::new()).unwrap_err(),
|
||||
BackupError::Elsewhere
|
||||
);
|
||||
assert_eq!(tree(&disk), before);
|
||||
// Books behind the destination: said, nothing written.
|
||||
more(&mut s1, 1);
|
||||
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
|
||||
let ahead = tree(&disk);
|
||||
let b1_old = dir.path().join("one-old");
|
||||
let _old = book(&b1_old);
|
||||
let err =
|
||||
write_destination(&plain(&disk), &cut(&b1_old, &_old), true, &Ctx::new()).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BackupError::Ahead(..) | BackupError::Elsewhere),
|
||||
"{err:?}"
|
||||
);
|
||||
assert_eq!(tree(&disk), ahead);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disk_that_is_gone_is_never_made_again_where_it_should_be() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let missing = dir.path().join("nodisk");
|
||||
assert_eq!(
|
||||
write_destination(&plain(&missing), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
|
||||
BackupError::NoFolder
|
||||
);
|
||||
// A mount point with nothing on it: the folder is there, the books'
|
||||
// backup is not, and the caller says it never made one here.
|
||||
let mount = dir.path().join("mount");
|
||||
std::fs::create_dir(&mount).unwrap();
|
||||
assert_eq!(
|
||||
write_destination(&plain(&mount), &cut(&b, &s), false, &Ctx::new()).unwrap_err(),
|
||||
BackupError::NoBackupThere
|
||||
);
|
||||
assert!(tree(&mount).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_backup_leaves_what_proved_whole_before() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
more(&mut s, 1);
|
||||
let stop = Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||
let err = write_destination(
|
||||
&plain(&disk),
|
||||
&cut(&b, &s),
|
||||
true,
|
||||
&Ctx::new().with_stop(stop),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}");
|
||||
let v = prove(&disk, None, dir.path(), "v").unwrap();
|
||||
assert_eq!(v.number, 1);
|
||||
}
|
||||
|
||||
// --- the passphrase --------------------------------------------------
|
||||
|
||||
const PASS: &str = "correct horse battery staple";
|
||||
|
||||
#[test]
|
||||
fn a_sealed_backup_gives_away_counts_and_sizes_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let key = BackupKey::generate(PASS).unwrap();
|
||||
let dest = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(key),
|
||||
};
|
||||
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
for (name, bytes) in tree(&disk) {
|
||||
for word in [
|
||||
"acme", "journal", "access", "vault", "keys", "blobs", "files", "receipt", "Cash",
|
||||
] {
|
||||
// The read-me is plain words and says nothing of the books;
|
||||
// nothing else carries a word of them, in its name or in it.
|
||||
if !name.ends_with("READ-ME.txt") {
|
||||
assert!(!name.contains(word), "{name} names {word}");
|
||||
assert!(
|
||||
!String::from_utf8_lossy(&bytes).contains(word)
|
||||
|| name.ends_with("header.json"),
|
||||
"{name} holds {word}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(!bytes.windows(8).any(|w| w == b"PDF-1.4 "), "{name}");
|
||||
}
|
||||
// Opened with the passphrase: the same books.
|
||||
let v = prove(&disk, Some(PASS), dir.path(), "v").unwrap();
|
||||
assert_eq!(v.head, s.head());
|
||||
assert!(v.key.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_passphrase_never_yields_books_and_is_told_from_damage() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let dest = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||
};
|
||||
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(matches!(
|
||||
find(&disk, None, &Ctx::new()),
|
||||
Err(BackupError::NeedsPassphrase)
|
||||
));
|
||||
assert!(matches!(
|
||||
find(&disk, Some("not the right words at all"), &Ctx::new()),
|
||||
Err(BackupError::WrongPassphrase)
|
||||
));
|
||||
// A damaged header is damage, not a wrong passphrase.
|
||||
let set = std::fs::read_dir(&disk)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
|
||||
.unwrap()
|
||||
.path();
|
||||
let header = set.join("header.json");
|
||||
let mut bytes = std::fs::read(&header).unwrap();
|
||||
bytes[40] ^= 1;
|
||||
std::fs::write(&header, &bytes).unwrap();
|
||||
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
|
||||
assert!(
|
||||
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
|
||||
"{err:?}"
|
||||
);
|
||||
assert!(!dir.path().join("v").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_passphrase_is_a_new_set_beside_the_old_which_is_untouched() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let first = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||
};
|
||||
write_destination(&first, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let before = tree(&disk);
|
||||
more(&mut s, 1);
|
||||
// Another passphrase: found no set of its own, so (the caller says it
|
||||
// may) a new one is made; the first is not touched.
|
||||
let second = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate("an entirely different phrase").unwrap()),
|
||||
};
|
||||
write_destination(&second, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let after = tree(&disk);
|
||||
for (name, bytes) in &before {
|
||||
assert_eq!(after.get(name), Some(bytes), "{name}");
|
||||
}
|
||||
let sets: Vec<_> = std::fs::read_dir(&disk).unwrap().flatten().collect();
|
||||
assert_eq!(sets.len(), 2);
|
||||
// The old passphrase still opens the old set only when it is alone;
|
||||
// with two sets, a passphrase opens the one that is its own.
|
||||
let v = prove(&disk, Some("an entirely different phrase"), dir.path(), "v").unwrap();
|
||||
assert_eq!(v.head, s.head());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_is_kept_privately_and_only_there() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let key = BackupKey::generate(PASS).unwrap();
|
||||
key.store(&b).unwrap();
|
||||
let loaded = BackupKey::load(&b).unwrap().expect("kept");
|
||||
assert!(key.same_as(&loaded));
|
||||
let file = b.join("local").join("backup-key.json");
|
||||
let text = std::fs::read_to_string(&file).unwrap();
|
||||
assert!(!text.contains(PASS));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
let dir_mode = std::fs::metadata(file.parent().unwrap())
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode()
|
||||
& 0o777;
|
||||
assert_eq!(dir_mode, 0o700);
|
||||
}
|
||||
// Never in a backup: not the journal, not the folder of the backup.
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let raw = text
|
||||
.lines()
|
||||
.find(|l| l.contains("master"))
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let master = raw.split('"').nth(3).unwrap().to_string();
|
||||
for (name, bytes) in tree(&disk) {
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains(&master), "{name}");
|
||||
}
|
||||
BackupKey::forget(&b).unwrap();
|
||||
assert!(BackupKey::load(&b).unwrap().is_none());
|
||||
}
|
||||
|
||||
// --- the single file -------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_single_file_holds_the_same_backup_plain_or_sealed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
for (pass, name) in [(None, "plain.wbbackup"), (Some(PASS), "sealed.wbbackup")] {
|
||||
let key = pass.map(|p| BackupKey::generate(p).unwrap());
|
||||
let file = dir.path().join(name);
|
||||
let w = save_file(&file, &cut(&b, &s), key.as_ref(), &Ctx::new()).unwrap();
|
||||
assert_eq!(w.head, s.head());
|
||||
let v = prove(&file, pass, dir.path(), &format!("v-{name}")).unwrap();
|
||||
assert_eq!(v.head, s.head());
|
||||
assert_eq!(v.blobs, 1);
|
||||
// A file by that name is not written over.
|
||||
assert!(save_file(&file, &cut(&b, &s), key.as_ref(), &Ctx::new()).is_err());
|
||||
}
|
||||
assert!(matches!(
|
||||
find(&dir.path().join("sealed.wbbackup"), None, &Ctx::new()),
|
||||
Err(BackupError::NeedsPassphrase)
|
||||
));
|
||||
assert!(matches!(
|
||||
find(
|
||||
&dir.path().join("sealed.wbbackup"),
|
||||
Some("a wrong passphrase here"),
|
||||
&Ctx::new()
|
||||
),
|
||||
Err(BackupError::WrongPassphrase)
|
||||
));
|
||||
// Not a backup at all.
|
||||
let junk = dir.path().join("junk.wbbackup");
|
||||
std::fs::write(&junk, b"not a zip").unwrap();
|
||||
assert!(matches!(
|
||||
find(&junk, None, &Ctx::new()),
|
||||
Err(BackupError::NotABackup)
|
||||
));
|
||||
}
|
||||
|
||||
// --- damage ------------------------------------------------------------
|
||||
|
||||
/// Every piece a manifest names, as paths under the set.
|
||||
fn pieces(set: &Path) -> Vec<PathBuf> {
|
||||
tree(set)
|
||||
.keys()
|
||||
.filter(|n| {
|
||||
!n.starts_with("manifests/")
|
||||
&& !n.starts_with("proofs/")
|
||||
&& !n.ends_with("READ-ME.txt")
|
||||
&& !n.ends_with("header.json")
|
||||
})
|
||||
.map(|n| set.join(n))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flipped_or_cut_piece_is_found_and_never_restored() {
|
||||
for sealed in [false, true] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let key = sealed.then(|| BackupKey::generate(PASS).unwrap());
|
||||
let dest = Destination {
|
||||
folder: disk.clone(),
|
||||
key,
|
||||
};
|
||||
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let pass = sealed.then_some(PASS);
|
||||
// Found once (a sealed backup's key takes a moment to derive).
|
||||
let found = find(&disk, pass, &Ctx::new()).unwrap();
|
||||
let prove = |_: &Path, _: Option<&str>, root: &Path, name: &str| {
|
||||
verify_found(&found, &root.join(name), &Ctx::new())
|
||||
};
|
||||
let set = std::fs::read_dir(&disk)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.next()
|
||||
.unwrap()
|
||||
.path();
|
||||
for piece in pieces(&set) {
|
||||
let original = std::fs::read(&piece).unwrap();
|
||||
for damage in 0..3 {
|
||||
let mut bytes = original.clone();
|
||||
match damage {
|
||||
0 => {
|
||||
let at = bytes.len() / 2;
|
||||
bytes[at] ^= 0x01;
|
||||
}
|
||||
1 => bytes.truncate(bytes.len().saturating_sub(1)),
|
||||
_ => bytes.clear(),
|
||||
}
|
||||
std::fs::write(&piece, &bytes).unwrap();
|
||||
let scratch = format!("v-{damage}");
|
||||
let got = prove(&disk, pass, dir.path(), &scratch);
|
||||
assert!(
|
||||
got.is_err(),
|
||||
"{} damage {damage} of {piece:?} was restored",
|
||||
if sealed { "sealed" } else { "plain" }
|
||||
);
|
||||
assert!(!dir.path().join(&scratch).exists(), "scratch left");
|
||||
}
|
||||
std::fs::write(&piece, &original).unwrap();
|
||||
}
|
||||
// Whole again once put back.
|
||||
prove(&disk, pass, dir.path(), "ok").unwrap();
|
||||
// A manifest cut short or changed is no manifest.
|
||||
let manifest = tree(&set)
|
||||
.keys()
|
||||
.find(|n| n.starts_with("manifests/"))
|
||||
.cloned()
|
||||
.unwrap();
|
||||
let mpath = set.join(&manifest);
|
||||
let original = std::fs::read(&mpath).unwrap();
|
||||
std::fs::write(&mpath, &original[..original.len() / 2]).unwrap();
|
||||
assert!(prove(&disk, pass, dir.path(), "cut").is_err());
|
||||
std::fs::write(&mpath, &original).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_newest_backup_falls_back_to_the_one_before_and_says_so() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let first_head = s.head();
|
||||
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("wanderbooks-acme"))
|
||||
.keys()
|
||||
.filter(|n| n.starts_with("journal/"))
|
||||
.max()
|
||||
.cloned()
|
||||
.unwrap();
|
||||
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();
|
||||
let v = prove(&disk, None, dir.path(), "v").unwrap();
|
||||
assert_eq!(v.number, 1);
|
||||
assert_eq!(v.passed_over, 1);
|
||||
assert_eq!(v.head, first_head);
|
||||
}
|
||||
|
||||
// --- death at every write point --------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let base_disk = dir.path().join("base");
|
||||
std::fs::create_dir(&base_disk).unwrap();
|
||||
write_destination(
|
||||
&plain(&base_disk),
|
||||
&cut(&b, &s),
|
||||
true,
|
||||
&Ctx::new().with_proof_skipped(),
|
||||
)
|
||||
.unwrap();
|
||||
let first_head = s.head();
|
||||
more(&mut s, 1);
|
||||
let c = cut(&b, &s);
|
||||
|
||||
// How many write points a whole second backup has.
|
||||
let counted = Arc::new(AtomicUsize::new(0));
|
||||
let probe = {
|
||||
let disk = dir.path().join("probe");
|
||||
copy_tree(&base_disk, &disk);
|
||||
let n = counted.clone();
|
||||
let ctx = Ctx::new()
|
||||
.with_proof_skipped()
|
||||
.with_faults(Arc::new(move |_, _| {
|
||||
n.fetch_add(1, Ordering::SeqCst);
|
||||
false
|
||||
}));
|
||||
write_destination(&plain(&disk), &c, true, &ctx).unwrap();
|
||||
counted.load(Ordering::SeqCst)
|
||||
};
|
||||
assert!(probe >= 6, "a second backup has several writes: {probe}");
|
||||
|
||||
for die_at in 0..probe {
|
||||
let disk = dir.path().join(format!("died-{die_at}"));
|
||||
copy_tree(&base_disk, &disk);
|
||||
let n = Arc::new(AtomicUsize::new(0));
|
||||
let ctx = {
|
||||
let n = n.clone();
|
||||
Ctx::new()
|
||||
.with_proof_skipped()
|
||||
.with_faults(Arc::new(move |_, _| {
|
||||
n.fetch_add(1, Ordering::SeqCst) == die_at
|
||||
}))
|
||||
};
|
||||
let err = write_destination(&plain(&disk), &c, true, &ctx).unwrap_err();
|
||||
assert_eq!(err, BackupError::Died, "point {die_at}");
|
||||
// What is left proves whole at the previous manifest, never a
|
||||
// half-written one (before the manifest was in place), or at the
|
||||
// new one (after).
|
||||
let v = prove(&disk, None, dir.path(), &format!("r-{die_at}")).unwrap();
|
||||
assert!(
|
||||
v.head == first_head || v.head == s.head(),
|
||||
"point {die_at}: head {:?}",
|
||||
v.head
|
||||
);
|
||||
// A restore from what is left is a prefix of the books.
|
||||
let restored = std::fs::read(v.tree.join("journal.jsonl")).unwrap();
|
||||
let live = std::fs::read(b.join("journal.jsonl")).unwrap();
|
||||
assert!(live.starts_with(&restored), "point {die_at}");
|
||||
// And the next run goes on from it (proven again at some points:
|
||||
// each proof replays the books).
|
||||
let w =
|
||||
write_destination(&plain(&disk), &c, true, &Ctx::new().with_proof_skipped()).unwrap();
|
||||
assert_eq!(w.head, s.head());
|
||||
if die_at % 6 == 0 {
|
||||
let again = prove(&disk, None, dir.path(), &format!("again-{die_at}")).unwrap();
|
||||
assert_eq!(again.head, s.head());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) {
|
||||
for (rel, bytes) in tree(from) {
|
||||
let p = to.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, bytes).unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(to).unwrap();
|
||||
}
|
||||
|
||||
// --- two writers -------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn two_programs_writing_one_destination_do_not_corrupt_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
for round in 0..3 {
|
||||
more(&mut s, round);
|
||||
let c = cut(&b, &s);
|
||||
let results: Vec<_> = std::thread::scope(|scope| {
|
||||
let handles: Vec<_> = (0..3)
|
||||
.map(|_| {
|
||||
let (c, disk) = (c.clone(), disk.clone());
|
||||
scope.spawn(move || write_destination(&plain(&disk), &c, true, &Ctx::new()))
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
for r in &results {
|
||||
let w = r
|
||||
.as_ref()
|
||||
.unwrap_or_else(|e| panic!("round {round}: {e:?}"));
|
||||
assert_eq!(w.head, s.head());
|
||||
}
|
||||
// However they interleaved: whole, at these books, and every
|
||||
// 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("wanderbooks-acme");
|
||||
for n in std::fs::read_dir(set.join("manifests")).unwrap().flatten() {
|
||||
assert!(n.file_name().to_string_lossy().ends_with(".json"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loser_of_a_manifest_number_goes_on_from_the_winner() {
|
||||
// Another program takes the next number between this one's look and its
|
||||
// write: this one looks again and finds nothing left to write.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let c = cut(&b, &s);
|
||||
let rival_disk = disk.clone();
|
||||
let rival_cut = c.clone();
|
||||
let done = Arc::new(AtomicUsize::new(0));
|
||||
let ctx = {
|
||||
let done = done.clone();
|
||||
Ctx::new().with_faults(Arc::new(move |kind, rel| {
|
||||
// Just before this writer's manifest, the rival writes its own.
|
||||
if kind == "create"
|
||||
&& rel.starts_with("manifests/")
|
||||
&& done.fetch_add(1, Ordering::SeqCst) == 0
|
||||
{
|
||||
write_destination(&plain(&rival_disk), &rival_cut, true, &Ctx::new()).unwrap();
|
||||
}
|
||||
false
|
||||
}))
|
||||
};
|
||||
let w = write_destination(&plain(&disk), &c, true, &ctx).unwrap();
|
||||
assert_eq!(w.head, s.head());
|
||||
assert!(!w.new, "the winner's manifest already says it");
|
||||
assert_eq!(
|
||||
std::fs::read_dir(disk.join("wanderbooks-acme/manifests"))
|
||||
.unwrap()
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
prove(&disk, None, dir.path(), "v").unwrap();
|
||||
}
|
||||
|
||||
// --- what the store reads of a backup -----------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_text_read_from_a_stored_file_is_a_stored_file_too() {
|
||||
// The store's own verification reads the text an extraction recorded as
|
||||
// a stored file; a backup that left it out would not prove whole, so it
|
||||
// is carried and proven with the rest.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let (attachment, _, _) = s
|
||||
.attach_receipt(
|
||||
None,
|
||||
"words.txt",
|
||||
"text/plain",
|
||||
b"a receipt with words",
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
s.extract_attachment(attachment).unwrap();
|
||||
let text_sha = s
|
||||
.extraction(attachment)
|
||||
.unwrap()
|
||||
.and_then(|x| x.text_sha256)
|
||||
.expect("the text is a stored file");
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let v = prove(&disk, None, dir.path(), "v").unwrap();
|
||||
assert!(
|
||||
v.tree
|
||||
.join("blobs")
|
||||
.join(&text_sha[0..2])
|
||||
.join(&text_sha[2..4])
|
||||
.join(&text_sha)
|
||||
.is_file()
|
||||
);
|
||||
assert_eq!(v.head, s.head());
|
||||
}
|
||||
|
||||
// --- what the removed tests of the old form protected ------------------------
|
||||
|
||||
#[test]
|
||||
fn a_purged_vault_leaves_the_next_backup_and_not_the_earlier_ones() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
std::fs::create_dir_all(b.join("vault")).unwrap();
|
||||
std::fs::write(b.join("vault").join("tin-1.bin"), b"sealed record").unwrap();
|
||||
std::fs::create_dir_all(b.join("keys")).unwrap();
|
||||
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
// The vault is purged to nothing: the next backup holds none, the
|
||||
// earlier one still does (nothing in a destination is deleted).
|
||||
std::fs::remove_file(b.join("vault").join("tin-1.bin")).unwrap();
|
||||
std::fs::remove_dir(b.join("vault")).unwrap();
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(w.new && w.number == 2, "{w:?}");
|
||||
let now = prove(&disk, None, dir.path(), "now").unwrap();
|
||||
assert!(!now.tree.join("vault").exists());
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(now.tree.join("keys").join("legacy.key")).unwrap(),
|
||||
"ab".repeat(32)
|
||||
);
|
||||
let then = dir.path().join("then");
|
||||
copy_tree(&disk, &then);
|
||||
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(),
|
||||
b"sealed record"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scratch_file_left_by_a_dead_program_never_stops_the_next_backup() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
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("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"),
|
||||
b"{\"format\":\"wan",
|
||||
)
|
||||
.unwrap();
|
||||
more(&mut s, 1);
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(w.new && w.number == 3, "{w:?}");
|
||||
let v = prove(&disk, None, dir.path(), "v").unwrap();
|
||||
assert_eq!(v.head, s.head());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_file_that_does_not_match_its_name_is_refused_and_nothing_is_written() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let sha = ledger_store::journal::sha256_hex(b"%PDF-1.4 r");
|
||||
let blob = b.join("blobs").join(&sha[0..2]).join(&sha[2..4]).join(&sha);
|
||||
std::fs::write(&blob, b"changed under its name").unwrap();
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err();
|
||||
assert!(matches!(err, BackupError::Damaged(_)), "{err:?}");
|
||||
// No manifest: nothing there is a backup.
|
||||
assert!(
|
||||
!tree(&disk)
|
||||
.keys()
|
||||
.any(|n| n.contains("manifests/") && n.ends_with(".json"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drill_proves_this_books_history_only() {
|
||||
use ledger_store::backup::drill;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (b1, b2) = (dir.path().join("one"), dir.path().join("two"));
|
||||
let (mut s1, s2) = (book(&b1), book(&b2));
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b1, &s1), true, &Ctx::new()).unwrap();
|
||||
let head = s1.head();
|
||||
// The books move on: the backup is the beginning of their journal.
|
||||
more(&mut s1, 1);
|
||||
let got = drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b1.join("journal.jsonl"),
|
||||
&dir.path().join("d1"),
|
||||
None,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(got, head);
|
||||
assert!(!dir.path().join("d1").exists(), "the scratch is removed");
|
||||
// Another book's history under the same name: not this book's.
|
||||
let err = drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b2.join("journal.jsonl"),
|
||||
&dir.path().join("d2"),
|
||||
None,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BackupError::Damaged(_)),
|
||||
"{err:?} {:?}",
|
||||
s2.head()
|
||||
);
|
||||
assert!(!dir.path().join("d2").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_local_backup_proves_to_hold_the_book_as_it_is_keys_and_all() {
|
||||
use ledger_store::backup::{prove_local, write_local};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
std::fs::create_dir_all(b.join("keys")).unwrap();
|
||||
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||
let scratch = dir.path().join("check");
|
||||
let c = cut(&b, &s);
|
||||
write_local(&b, &c, &Ctx::new()).unwrap();
|
||||
assert_eq!(
|
||||
prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).unwrap(),
|
||||
1
|
||||
);
|
||||
assert!(!scratch.exists(), "the scratch folder is removed");
|
||||
// A changed key, a changed vault record, an extra one, books that moved
|
||||
// on, each refused.
|
||||
std::fs::write(b.join("keys").join("legacy.key"), "cd".repeat(32)).unwrap();
|
||||
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
|
||||
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||
std::fs::create_dir_all(b.join("vault")).unwrap();
|
||||
std::fs::write(b.join("vault").join("tin-2.bin"), b"extra").unwrap();
|
||||
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
|
||||
std::fs::remove_file(b.join("vault").join("tin-2.bin")).unwrap();
|
||||
more(&mut s, 1);
|
||||
assert!(prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).is_err());
|
||||
// Written again, it proves the books as they are now.
|
||||
write_local(&b, &cut(&b, &s), &Ctx::new()).unwrap();
|
||||
prove_local(&b, "acme", &s.head(), &scratch, &Ctx::new()).unwrap();
|
||||
assert!(!scratch.exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_in_a_backup_is_never_followed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
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("wanderbooks-acme");
|
||||
let piece = std::fs::read_dir(set.join("journal"))
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.path();
|
||||
let elsewhere = dir.path().join("elsewhere");
|
||||
std::fs::copy(&piece, &elsewhere).unwrap();
|
||||
std::fs::remove_file(&piece).unwrap();
|
||||
std::os::unix::fs::symlink(&elsewhere, &piece).unwrap();
|
||||
assert!(prove(&disk, None, dir.path(), "v").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drill_stops_inside_the_phase_it_is_told_to_stop_in() {
|
||||
use ledger_store::backup::drill;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
// The phases a drill goes through; a stop asked as each begins ends the
|
||||
// drill there (the observer sees no later phase), scratch removed.
|
||||
let phases = ["fetch", "replay", "verify", "blobs", "vault", "prefix"];
|
||||
for stop_at in phases {
|
||||
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||
let ctx = {
|
||||
let (stop, seen) = (stop.clone(), seen.clone());
|
||||
Ctx::new()
|
||||
.with_stop(stop.clone())
|
||||
.with_phase_watch(Arc::new(move |p: &str| {
|
||||
seen.lock().unwrap().push(p.to_string());
|
||||
if p == stop_at {
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}))
|
||||
};
|
||||
let scratch = dir.path().join(format!("d-{stop_at}"));
|
||||
let got = drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b.join("journal.jsonl"),
|
||||
&scratch,
|
||||
None,
|
||||
&ctx,
|
||||
);
|
||||
assert!(
|
||||
matches!(got, Err(BackupError::Cancelled(_))),
|
||||
"{stop_at}: {got:?}"
|
||||
);
|
||||
let seen = seen.lock().unwrap().clone();
|
||||
assert_eq!(seen.last().map(String::as_str), Some(stop_at), "{seen:?}");
|
||||
assert!(!scratch.exists(), "{stop_at}: scratch left");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
//! Backups onto the disks people really have (WB-backup-18 to WB-backup-22):
|
||||
//! a disk that makes no hard links (FAT or exFAT on a stick), sealed pieces
|
||||
//! in folders a small disk can hold, a header that asks for more than it
|
||||
//! should, and a folder a sync service has not finished putting on this
|
||||
//! computer.
|
||||
|
||||
use ledger_core::{AccountType, Currency, Money, Side};
|
||||
use ledger_store::Store;
|
||||
use ledger_store::backup::{
|
||||
BackupError, BackupKey, Ctx, Cut, Destination, Options, find, key_derivations, verify_found,
|
||||
write_destination, write_destination_with,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn usd(s: &str) -> Money {
|
||||
Money::new(s.parse().unwrap(), Currency::USD)
|
||||
}
|
||||
|
||||
fn book(dir: &Path) -> Store {
|
||||
let mut s = Store::create(dir, Currency::USD).unwrap();
|
||||
let cash = s
|
||||
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let cap = s
|
||||
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||
.unwrap();
|
||||
let e = s
|
||||
.create_entry(
|
||||
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
|
||||
"Start",
|
||||
)
|
||||
.unwrap();
|
||||
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
|
||||
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn more(s: &mut Store, n: usize) {
|
||||
s.add_account(
|
||||
&format!("{}", 6000 + n),
|
||||
&format!("Expense {n}"),
|
||||
AccountType::Expense,
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
s.attach_receipt(
|
||||
None,
|
||||
&format!("f{n}.txt"),
|
||||
"text/plain",
|
||||
format!("receipt number {n}").as_bytes(),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn cut(dir: &Path, s: &Store) -> Cut {
|
||||
Cut::take("acme", dir, s.head()).unwrap()
|
||||
}
|
||||
|
||||
fn plain(folder: &Path) -> Destination {
|
||||
Destination {
|
||||
folder: folder.to_path_buf(),
|
||||
key: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let p = e.unwrap().path();
|
||||
if p.is_dir() {
|
||||
walk(base, &p, out);
|
||||
} else {
|
||||
let rel = p
|
||||
.strip_prefix(base)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
out.insert(rel, std::fs::read(&p).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
if root.is_dir() {
|
||||
walk(root, root, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn prove(
|
||||
source: &Path,
|
||||
pass: Option<&str>,
|
||||
root: &Path,
|
||||
name: &str,
|
||||
) -> ledger_store::backup::Verified {
|
||||
let found = find(source, pass, &Ctx::new()).unwrap();
|
||||
verify_found(&found, &root.join(name), &Ctx::new()).unwrap()
|
||||
}
|
||||
|
||||
// --- a disk that makes no hard links ---------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_disk_that_makes_no_links_takes_whole_backups_and_only_grows() {
|
||||
for ctx in [
|
||||
Ctx::new().with_no_hard_links(),
|
||||
// And one whose move cannot refuse to replace either: exclusive
|
||||
// create and copy.
|
||||
Ctx::new().with_no_exclusive_move(),
|
||||
] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let mut before = BTreeMap::new();
|
||||
for n in 0..3 {
|
||||
more(&mut s, n);
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
|
||||
assert!(w.new && w.repaired.is_empty(), "{w:?}");
|
||||
let now = tree(&disk);
|
||||
for (name, bytes) in &before {
|
||||
assert_eq!(now.get(name), Some(bytes), "{name} must not change");
|
||||
}
|
||||
assert!(!now.keys().any(|n| n.contains(".wb-tmp-")), "scratch left");
|
||||
before = now;
|
||||
}
|
||||
let v = prove(&disk, None, dir.path(), "v");
|
||||
assert_eq!(v.head, s.head());
|
||||
assert_eq!(v.passed_over, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_writers_racing_on_a_disk_that_makes_no_links_do_not_corrupt_it() {
|
||||
for exclusive_move_missing in [false, true] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
for round in 0..3 {
|
||||
more(&mut s, round);
|
||||
let c = cut(&b, &s);
|
||||
let results: Vec<_> = std::thread::scope(|scope| {
|
||||
let handles: Vec<_> = (0..3)
|
||||
.map(|_| {
|
||||
let (c, disk) = (c.clone(), disk.clone());
|
||||
scope.spawn(move || {
|
||||
let ctx = if exclusive_move_missing {
|
||||
Ctx::new().with_no_exclusive_move()
|
||||
} else {
|
||||
Ctx::new().with_no_hard_links()
|
||||
};
|
||||
write_destination(&plain(&disk), &c, true, &ctx)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
for r in &results {
|
||||
let w = r
|
||||
.as_ref()
|
||||
.unwrap_or_else(|e| panic!("round {round}: {e:?}"));
|
||||
assert_eq!(w.head, s.head());
|
||||
}
|
||||
let v = prove(&disk, None, dir.path(), &format!("v{round}"));
|
||||
assert_eq!(v.head, s.head());
|
||||
assert_eq!(v.passed_over, 0, "round {round}");
|
||||
assert!(
|
||||
!tree(&disk).keys().any(|n| n.contains(".wb-tmp-")),
|
||||
"scratch left"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_taken_number_or_name_is_never_replaced_on_a_disk_that_makes_no_links() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let ctx = Ctx::new().with_no_hard_links();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
|
||||
let set = disk.join("wanderbooks-acme");
|
||||
// A rival's manifest 2 is already in place when this one comes to put
|
||||
// its own as number 2.
|
||||
more(&mut s, 1);
|
||||
let rival = disk.join("rival");
|
||||
std::fs::create_dir(&rival).unwrap();
|
||||
let c = cut(&b, &s);
|
||||
let taken = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let hook = {
|
||||
let (set, taken) = (set.clone(), taken.clone());
|
||||
Ctx::new()
|
||||
.with_no_hard_links()
|
||||
.with_faults(std::sync::Arc::new(move |kind, rel| {
|
||||
if kind == "create"
|
||||
&& rel.starts_with("manifests/")
|
||||
&& taken.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0
|
||||
{
|
||||
std::fs::write(set.join("manifests/000002.json"), b"a rival's, whole").unwrap();
|
||||
}
|
||||
false
|
||||
}))
|
||||
};
|
||||
let _ = write_destination(&plain(&disk), &c, true, &hook);
|
||||
assert_eq!(
|
||||
std::fs::read(set.join("manifests/000002.json")).unwrap(),
|
||||
b"a rival's, whole",
|
||||
"the manifest that was there is never replaced"
|
||||
);
|
||||
}
|
||||
|
||||
// --- sealed pieces in folders a small disk can hold --------------------------
|
||||
|
||||
const PASS: &str = "correct horse battery staple";
|
||||
|
||||
/// The count of derived keys is the process's: the tests that read it, and
|
||||
/// every test that derives one, take turns.
|
||||
static KEYS: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> {
|
||||
KEYS.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sealed_pieces_are_spread_over_folders_as_the_plain_form_does() {
|
||||
let _turn = one_at_a_time();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
for n in 0..30 {
|
||||
more(&mut s, n);
|
||||
}
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let dest = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||
};
|
||||
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let set = std::fs::read_dir(&disk)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
|
||||
.unwrap()
|
||||
.path();
|
||||
let mut in_folders = 0usize;
|
||||
for entry in std::fs::read_dir(set.join("pieces")).unwrap().flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
assert!(
|
||||
entry.path().is_dir(),
|
||||
"{name}: a piece sits in a flat folder"
|
||||
);
|
||||
assert_eq!(name.len(), 2, "{name}");
|
||||
for piece in std::fs::read_dir(entry.path()).unwrap().flatten() {
|
||||
assert!(
|
||||
piece.file_name().to_string_lossy().starts_with(&name),
|
||||
"a piece is in the folder of its name's first two digits"
|
||||
);
|
||||
in_folders += 1;
|
||||
}
|
||||
}
|
||||
assert!(in_folders > 30, "{in_folders}");
|
||||
let v = prove(&disk, Some(PASS), dir.path(), "v");
|
||||
assert_eq!(v.head, s.head());
|
||||
}
|
||||
|
||||
// --- a header that is read from a folder anyone may have written -------------
|
||||
|
||||
/// The sealed set's folder in `disk`.
|
||||
fn sealed_set(disk: &Path) -> PathBuf {
|
||||
std::fs::read_dir(disk)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.find(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
|
||||
.unwrap()
|
||||
.path()
|
||||
}
|
||||
|
||||
/// Rewrite the header's key settings and make its own check line right
|
||||
/// again (what a person who meant to would do).
|
||||
fn set_header(header: &Path, edit: impl Fn(&mut serde_json::Value)) {
|
||||
let text = std::fs::read_to_string(header).unwrap();
|
||||
let body = text.lines().next().unwrap();
|
||||
let mut v: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
edit(&mut v);
|
||||
let body = serde_json::to_string(&v).unwrap();
|
||||
let check = hex::encode(Sha256::digest(body.as_bytes()));
|
||||
std::fs::write(
|
||||
header,
|
||||
format!("{body}\nwanderbooks-header-sha256 {check}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_cannot_ask_for_more_than_a_few_times_what_this_program_spends() {
|
||||
let _turn = one_at_a_time();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let dest = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||
};
|
||||
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let header = sealed_set(&disk).join("header.json");
|
||||
let original = std::fs::read(&header).unwrap();
|
||||
for (what, value) in [
|
||||
("m", serde_json::json!(4_000_000u32)),
|
||||
("m", serde_json::json!(64 * 1024 * 5)),
|
||||
("t", serde_json::json!(13)),
|
||||
("p", serde_json::json!(5)),
|
||||
] {
|
||||
set_header(&header, |v| v["kdf"][what] = value.clone());
|
||||
let derived = key_derivations();
|
||||
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
|
||||
// Refused as damage before any key is derived: no memory spent.
|
||||
assert!(
|
||||
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
|
||||
"{what}: {err:?}"
|
||||
);
|
||||
assert_eq!(key_derivations(), derived, "{what}: a key was derived");
|
||||
}
|
||||
std::fs::write(&header, &original).unwrap();
|
||||
let v = prove(&disk, Some(PASS), dir.path(), "v");
|
||||
assert_eq!(v.head, s.head());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_that_was_changed_reads_as_damage_and_not_as_a_wrong_passphrase() {
|
||||
let _turn = one_at_a_time();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let dest = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||
};
|
||||
write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let header = sealed_set(&disk).join("header.json");
|
||||
// A setting changed in the file as a bad sector or a bad sync would:
|
||||
// the header's own check line no longer matches.
|
||||
let text = std::fs::read_to_string(&header).unwrap();
|
||||
let changed = text.replacen("\"t\":3", "\"t\":4", 1);
|
||||
assert_ne!(text, changed, "the header names its passes");
|
||||
std::fs::write(&header, changed).unwrap();
|
||||
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
|
||||
assert!(
|
||||
matches!(err, BackupError::Damaged(_) | BackupError::NotABackup),
|
||||
"{err:?}"
|
||||
);
|
||||
// Changed on purpose and made consistent again: the key comes out
|
||||
// different and opens nothing (the safe way to fail), and no
|
||||
// passphrase is guessed any faster.
|
||||
std::fs::write(&header, &text).unwrap();
|
||||
set_header(&header, |v| v["kdf"]["t"] = serde_json::json!(4));
|
||||
assert!(matches!(
|
||||
find(&disk, Some(PASS), &Ctx::new()),
|
||||
Err(BackupError::WrongPassphrase)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_of_sealed_sets_costs_one_key_derivation_per_setting_not_one_per_set() {
|
||||
let _turn = one_at_a_time();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let dest = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate(PASS).unwrap()),
|
||||
};
|
||||
let c = cut(&b, &s);
|
||||
write_destination(&dest, &c, true, &Ctx::new()).unwrap();
|
||||
for _ in 0..2 {
|
||||
write_destination_with(
|
||||
&dest,
|
||||
&c,
|
||||
Options {
|
||||
may_create: true,
|
||||
new_set: true,
|
||||
},
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let sets = std::fs::read_dir(&disk)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.filter(|e| e.file_name().to_string_lossy().starts_with("sealed-"))
|
||||
.count();
|
||||
assert_eq!(sets, 3);
|
||||
let derived = key_derivations();
|
||||
// Three sets of one book: it asks which, after one derivation.
|
||||
let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap();
|
||||
assert!(matches!(err, BackupError::Several(_)), "{err:?}");
|
||||
assert_eq!(key_derivations() - derived, 1);
|
||||
}
|
||||
|
||||
// --- files a sync service has not downloaded ---------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_downloaded_yet_reads_as_such_and_never_as_damage_or_absence() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let set = disk.join("wanderbooks-acme");
|
||||
let before = tree(&disk);
|
||||
|
||||
// A piece of the newest backup that iCloud has left as a stand-in
|
||||
// (`.name.icloud`) in its place.
|
||||
let manifest = std::fs::read_to_string(set.join("manifests/000001.json")).unwrap();
|
||||
let m: serde_json::Value = serde_json::from_str(manifest.lines().next().unwrap()).unwrap();
|
||||
let seg = set.join(m["journal"]["segments"][0]["file"].as_str().unwrap());
|
||||
let stand_in = seg.with_file_name(format!(
|
||||
".{}.icloud",
|
||||
seg.file_name().unwrap().to_string_lossy()
|
||||
));
|
||||
let held = std::fs::read(&seg).unwrap();
|
||||
std::fs::rename(&seg, &stand_in).unwrap();
|
||||
let found = find(&disk, None, &Ctx::new());
|
||||
// Nothing says "damaged", nothing says "not a backup": it is waiting.
|
||||
assert_eq!(found.err(), Some(BackupError::NotDownloaded));
|
||||
more(&mut s, 1);
|
||||
assert_eq!(
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
|
||||
BackupError::NotDownloaded
|
||||
);
|
||||
assert!(
|
||||
BackupError::NotDownloaded
|
||||
.to_string()
|
||||
.contains("not downloaded to this computer yet")
|
||||
);
|
||||
// Downloaded: all as it was.
|
||||
std::fs::rename(&stand_in, &seg).unwrap();
|
||||
assert_eq!(std::fs::read(&seg).unwrap(), held);
|
||||
assert_eq!(tree(&disk), before);
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
|
||||
// The newest manifest as a stand-in: the folder is listed with it, and
|
||||
// the writer will not make a manifest under its number.
|
||||
let newest = set.join("manifests/000002.json");
|
||||
let stand = set.join("manifests/.000002.json.icloud");
|
||||
std::fs::rename(&newest, &stand).unwrap();
|
||||
more(&mut s, 2);
|
||||
assert_eq!(
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err(),
|
||||
BackupError::NotDownloaded
|
||||
);
|
||||
assert_eq!(
|
||||
find(&disk, None, &Ctx::new()).err(),
|
||||
Some(BackupError::NotDownloaded)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! Backups as properties (WB-backup-1 to WB-backup-7): random books and
|
||||
//! random sequences of backups, interleavings of two writers, damage to any
|
||||
//! piece, and passphrases that are not the right one. Each case builds a
|
||||
//! book, which is the cost; the cases are few and the oracles are the laws.
|
||||
|
||||
use ledger_core::{AccountType, Currency};
|
||||
use ledger_store::Store;
|
||||
use ledger_store::backup::{
|
||||
BackupError, BackupKey, Ctx, Cut, Destination, find, verify_found, write_destination,
|
||||
};
|
||||
use proptest::prelude::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// One thing that happens to the books between backups.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Op {
|
||||
/// A new account.
|
||||
Account,
|
||||
/// A stored file of these bytes (the same bytes twice are one file).
|
||||
File(Vec<u8>),
|
||||
/// A backup.
|
||||
Backup,
|
||||
}
|
||||
|
||||
fn ops() -> impl Strategy<Value = Vec<Op>> {
|
||||
prop::collection::vec(
|
||||
prop_oneof![
|
||||
2 => Just(Op::Account),
|
||||
2 => prop::collection::vec(any::<u8>(), 1..40).prop_map(Op::File),
|
||||
3 => Just(Op::Backup),
|
||||
],
|
||||
2..9,
|
||||
)
|
||||
}
|
||||
|
||||
/// A context for tests of logic, not of durability: nothing is synced.
|
||||
fn fast() -> Ctx {
|
||||
// The proof after a backup has tests of its own (backup_repair.rs); the
|
||||
// properties here prove what they make by restoring it.
|
||||
Ctx::new().with_no_sync().with_proof_skipped()
|
||||
}
|
||||
|
||||
fn plain(folder: &Path) -> Destination {
|
||||
Destination {
|
||||
folder: folder.to_path_buf(),
|
||||
key: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let p = e.unwrap().path();
|
||||
if p.is_dir() {
|
||||
walk(base, &p, out);
|
||||
} else {
|
||||
let rel = p
|
||||
.strip_prefix(base)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
out.insert(rel, std::fs::read(&p).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
if root.is_dir() {
|
||||
walk(root, root, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) {
|
||||
std::fs::create_dir_all(to).unwrap();
|
||||
for (rel, bytes) in tree(from) {
|
||||
let p = to.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, bytes).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A book with one account, and a way to apply [`Op`]s to it.
|
||||
struct Books {
|
||||
store: Store,
|
||||
dir: std::path::PathBuf,
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl Books {
|
||||
fn new(dir: &Path) -> Self {
|
||||
let mut store = Store::create(dir, Currency::USD).unwrap();
|
||||
store
|
||||
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
Self {
|
||||
store,
|
||||
dir: dir.to_path_buf(),
|
||||
n: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, op: &Op) {
|
||||
match op {
|
||||
Op::Account => {
|
||||
self.n += 1;
|
||||
self.store
|
||||
.add_account(
|
||||
&format!("{}", 6000 + self.n),
|
||||
&format!("Expense {}", self.n),
|
||||
AccountType::Expense,
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
Op::File(bytes) => {
|
||||
self.store
|
||||
.attach_receipt(None, "f.bin", "application/octet-stream", bytes, None)
|
||||
.unwrap();
|
||||
}
|
||||
Op::Backup => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn cut(&self) -> Cut {
|
||||
Cut::take("acme", &self.dir, self.store.head()).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn prove(
|
||||
folder: &Path,
|
||||
pass: Option<&str>,
|
||||
scratch: &Path,
|
||||
) -> Result<ledger_store::backup::Verified, BackupError> {
|
||||
let found = find(folder, pass, &Ctx::new())?;
|
||||
verify_found(&found, scratch, &Ctx::new())
|
||||
}
|
||||
|
||||
fn config() -> ProptestConfig {
|
||||
ProptestConfig {
|
||||
cases: 5,
|
||||
max_shrink_iters: 4,
|
||||
failure_persistence: None,
|
||||
..ProptestConfig::default()
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// WB-backup-1: whatever the books do and whenever they are backed up,
|
||||
/// every file the destination held is still there, byte for byte.
|
||||
#[test]
|
||||
fn a_destination_only_grows(ops in ops()) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut books = Books::new(&dir.path().join("book"));
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let mut before = tree(&disk);
|
||||
for op in &ops {
|
||||
books.apply(op);
|
||||
if matches!(op, Op::Backup) {
|
||||
write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
|
||||
let after = tree(&disk);
|
||||
for (name, bytes) in &before {
|
||||
prop_assert_eq!(after.get(name), Some(bytes), "{} changed or went", name);
|
||||
}
|
||||
prop_assert!(!after.keys().any(|n| n.contains(".wb-tmp-")));
|
||||
before = after;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// WB-backup-3: the destination as of any of its manifests restores to
|
||||
/// books whose journal is byte-identical to the beginning of the
|
||||
/// books' journal now, and whose head is the one that manifest names.
|
||||
#[test]
|
||||
fn any_whole_manifest_restores_a_prefix_of_the_books(ops in ops()) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut books = Books::new(&dir.path().join("book"));
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let mut heads = Vec::new();
|
||||
for op in &ops {
|
||||
books.apply(op);
|
||||
if matches!(op, Op::Backup) {
|
||||
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
|
||||
if w.new {
|
||||
heads.push((w.number, w.head));
|
||||
}
|
||||
}
|
||||
}
|
||||
// (A last backup, so there is at least one.)
|
||||
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
|
||||
if w.new {
|
||||
heads.push((w.number, w.head));
|
||||
}
|
||||
let live = std::fs::read(dir.path().join("book").join("journal.jsonl")).unwrap();
|
||||
for (number, head) in &heads {
|
||||
// The destination as it was when that manifest was the newest.
|
||||
let then = dir.path().join(format!("then-{number}"));
|
||||
copy_tree(&disk, &then);
|
||||
for (name, _) in tree(&then) {
|
||||
if let Some(n) = name
|
||||
.strip_prefix("wanderbooks-acme/manifests/")
|
||||
.and_then(|r| r.strip_suffix(".json"))
|
||||
.and_then(|r| r.parse::<u64>().ok())
|
||||
&& n > *number
|
||||
{
|
||||
std::fs::remove_file(then.join(&name)).unwrap();
|
||||
}
|
||||
}
|
||||
let v = prove(&then, None, &dir.path().join(format!("v-{number}"))).unwrap();
|
||||
prop_assert_eq!(&v.head, head);
|
||||
let restored = std::fs::read(v.tree.join("journal.jsonl")).unwrap();
|
||||
prop_assert!(live.starts_with(&restored));
|
||||
}
|
||||
}
|
||||
|
||||
/// WB-backup-5: a writer that finds another writer's backup appear at
|
||||
/// any of its write points (the other with books a little behind or a
|
||||
/// little ahead) leaves a destination that proves whole, at the head
|
||||
/// of one of them, restoring to a prefix of the longer books.
|
||||
#[test]
|
||||
fn random_interleavings_of_two_writers_leave_a_whole_backup(
|
||||
files in prop::collection::vec(prop::collection::vec(any::<u8>(), 1..20), 1..3),
|
||||
rival_after in 0usize..3,
|
||||
at in 0usize..14,
|
||||
) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut books = Books::new(&dir.path().join("book"));
|
||||
for f in &files {
|
||||
books.apply(&Op::File(f.clone()));
|
||||
}
|
||||
let first = books.cut();
|
||||
for _ in 0..rival_after {
|
||||
books.apply(&Op::Account);
|
||||
}
|
||||
let second = books.cut();
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
// The writer of `first` is met, at its `at`th write point, by a
|
||||
// complete write of `second`.
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
let rival = {
|
||||
let (disk, second, count) = (disk.clone(), second.clone(), count.clone());
|
||||
fast().with_faults(Arc::new(move |_, _| {
|
||||
if count.fetch_add(1, Ordering::SeqCst) == at {
|
||||
write_destination(
|
||||
&plain(&disk),
|
||||
&second,
|
||||
true,
|
||||
&fast(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
false
|
||||
}))
|
||||
};
|
||||
let mine = write_destination(&plain(&disk), &first, true, &rival);
|
||||
match mine {
|
||||
Ok(_) | Err(BackupError::Ahead(..)) | Err(BackupError::Elsewhere) => {}
|
||||
Err(e) => prop_assert!(false, "{e:?}"),
|
||||
}
|
||||
let v = prove(&disk, None, &dir.path().join("v")).unwrap();
|
||||
prop_assert!(v.head == *first.head() || v.head == *second.head());
|
||||
let live = std::fs::read(dir.path().join("book").join("journal.jsonl")).unwrap();
|
||||
prop_assert!(live.starts_with(&std::fs::read(v.tree.join("journal.jsonl")).unwrap()));
|
||||
}
|
||||
|
||||
/// WB-backup-6: a piece with one byte flipped, or cut anywhere, is
|
||||
/// found: the backup that names it is not restored.
|
||||
#[test]
|
||||
fn any_flipped_or_cut_piece_is_found_never_restored(
|
||||
ops in ops(),
|
||||
pick in any::<prop::sample::Index>(),
|
||||
at in any::<prop::sample::Index>(),
|
||||
cut in any::<bool>(),
|
||||
) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut books = Books::new(&dir.path().join("book"));
|
||||
books.apply(&Op::File(vec![1, 2, 3, 4]));
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
for op in &ops {
|
||||
books.apply(op);
|
||||
}
|
||||
write_destination(
|
||||
&plain(&disk),
|
||||
&books.cut(),
|
||||
true,
|
||||
&fast(),
|
||||
)
|
||||
.unwrap();
|
||||
let set = disk.join("wanderbooks-acme");
|
||||
let pieces: Vec<String> = tree(&set)
|
||||
.into_keys()
|
||||
.filter(|n| {
|
||||
!n.starts_with("manifests/") && !n.starts_with("proofs/") && n != "READ-ME.txt"
|
||||
})
|
||||
.collect();
|
||||
let name = &pieces[pick.index(pieces.len())];
|
||||
let path = set.join(name);
|
||||
let mut bytes = std::fs::read(&path).unwrap();
|
||||
prop_assume!(!bytes.is_empty());
|
||||
let i = at.index(bytes.len());
|
||||
if cut {
|
||||
bytes.truncate(i);
|
||||
} else {
|
||||
bytes[i] ^= 0x01;
|
||||
}
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
let scratch = dir.path().join("v");
|
||||
prop_assert!(prove(&disk, None, &scratch).is_err(), "{name} damaged was restored");
|
||||
prop_assert!(!scratch.exists());
|
||||
}
|
||||
|
||||
/// WB-backup-7: no passphrase but the right one gives books.
|
||||
#[test]
|
||||
fn a_wrong_passphrase_never_yields_books(wrong in "[a-zA-Z0-9 ]{1,30}") {
|
||||
prop_assume!(wrong != "the right words, exactly");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let books = Books::new(&dir.path().join("book"));
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let dest = Destination {
|
||||
folder: disk.clone(),
|
||||
key: Some(BackupKey::generate("the right words, exactly").unwrap()),
|
||||
};
|
||||
write_destination(&dest, &books.cut(), true, &fast()).unwrap();
|
||||
let scratch = dir.path().join("v");
|
||||
let got = prove(&disk, Some(&wrong), &scratch);
|
||||
prop_assert!(matches!(got, Err(BackupError::WrongPassphrase)), "{got:?}");
|
||||
prop_assert!(!scratch.exists());
|
||||
let none = prove(&disk, None, &scratch);
|
||||
prop_assert!(matches!(none, Err(BackupError::NeedsPassphrase)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,790 @@
|
||||
//! A backup that restores old or wrong books while reporting good is the
|
||||
//! worst defect this product can have (WB-backup-12 to WB-backup-17): a
|
||||
//! damaged piece must not be reused by later backups, the drill must not
|
||||
//! prove an older backup and say ok, a damaged piece must be found by the
|
||||
//! proof after the backup and written again beside the damaged file, books
|
||||
//! that are behind a destination must be told from books that have
|
||||
//! diverged, and a restore must say when it is not of the newest backup.
|
||||
|
||||
use ledger_core::{AccountType, Currency, Money, Role, Side, TinFacts, TinType};
|
||||
use ledger_store::Store;
|
||||
use ledger_store::backup::{
|
||||
BackupError, Ctx, Cut, Destination, Options, drill, find, verify_found, write_destination,
|
||||
write_destination_with,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn usd(s: &str) -> Money {
|
||||
Money::new(s.parse().unwrap(), Currency::USD)
|
||||
}
|
||||
|
||||
fn book(dir: &Path) -> Store {
|
||||
let mut s = Store::create(dir, Currency::USD).unwrap();
|
||||
let cash = s
|
||||
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let cap = s
|
||||
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||
.unwrap();
|
||||
let e = s
|
||||
.create_entry(
|
||||
chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(),
|
||||
"Start",
|
||||
)
|
||||
.unwrap();
|
||||
s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap();
|
||||
s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None)
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn more(s: &mut Store, n: usize) {
|
||||
s.add_account(
|
||||
&format!("{}", 6000 + n),
|
||||
&format!("Expense {n}"),
|
||||
AccountType::Expense,
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
s.attach_receipt(
|
||||
None,
|
||||
&format!("f{n}.txt"),
|
||||
"text/plain",
|
||||
format!("receipt number {n}").as_bytes(),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn cut(dir: &Path, s: &Store) -> Cut {
|
||||
Cut::take("acme", dir, s.head()).unwrap()
|
||||
}
|
||||
|
||||
fn plain(folder: &Path) -> Destination {
|
||||
Destination {
|
||||
folder: folder.to_path_buf(),
|
||||
key: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn set_of(disk: &Path) -> PathBuf {
|
||||
disk.join("wanderbooks-acme")
|
||||
}
|
||||
|
||||
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let p = e.unwrap().path();
|
||||
if p.is_dir() {
|
||||
walk(base, &p, out);
|
||||
} else {
|
||||
let rel = p
|
||||
.strip_prefix(base)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
out.insert(rel, std::fs::read(&p).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
if root.is_dir() {
|
||||
walk(root, root, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) {
|
||||
std::fs::create_dir_all(to).unwrap();
|
||||
for e in std::fs::read_dir(from).unwrap() {
|
||||
let e = e.unwrap();
|
||||
let (src, dst) = (e.path(), to.join(e.file_name()));
|
||||
if src.is_dir() {
|
||||
copy_tree(&src, &dst);
|
||||
} else {
|
||||
std::fs::copy(&src, &dst).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Flip one byte in the middle of a file, as a bad sector or a bad sync
|
||||
/// would; the file keeps its length.
|
||||
fn flip(path: &Path) {
|
||||
let mut bytes = std::fs::read(path).unwrap();
|
||||
let at = bytes.len() / 2;
|
||||
bytes[at] ^= 0x55;
|
||||
std::fs::write(path, bytes).unwrap();
|
||||
}
|
||||
|
||||
/// The manifest `n` of the set, as JSON.
|
||||
fn manifest(set: &Path, n: u64) -> serde_json::Value {
|
||||
let text = std::fs::read_to_string(set.join(format!("manifests/{n:06}.json"))).unwrap();
|
||||
serde_json::from_str(text.lines().next().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The newest journal segment a manifest names (the one its backup added).
|
||||
fn newest_journal_segment(set: &Path, n: u64) -> String {
|
||||
manifest(set, n)["journal"]["segments"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.last()
|
||||
.unwrap()["file"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn sha(bytes: &[u8]) -> String {
|
||||
hex::encode(Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_damaged_segment_is_found_by_the_next_backup_and_the_drill_does_not_hide_it() {
|
||||
// The reviewer's sequence: a byte flips in the segment backup 2 wrote;
|
||||
// backups go on; a drill runs; a restore is made. Before: every later
|
||||
// backup reused the damaged segment and was recorded good, the drill
|
||||
// proved backup 1 and said ok, and a restore returned books from long
|
||||
// ago.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let first_head = s.head();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
more(&mut s, 1);
|
||||
let w2 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert_eq!(w2.number, 2);
|
||||
assert!(w2.repaired.is_empty());
|
||||
let seg = newest_journal_segment(&set_of(&disk), 2);
|
||||
let damaged = set_of(&disk).join(&seg);
|
||||
flip(&damaged);
|
||||
let flipped = std::fs::read(&damaged).unwrap();
|
||||
|
||||
// The very next backup finds it (its proof re-hashes every journal
|
||||
// segment its manifest names) and writes the piece again beside it.
|
||||
more(&mut s, 2);
|
||||
let w3 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(w3.new);
|
||||
assert_eq!(w3.repaired, vec![seg.clone()], "{w3:?}");
|
||||
assert_eq!(
|
||||
std::fs::read(&damaged).unwrap(),
|
||||
flipped,
|
||||
"the damaged file is left exactly where it is"
|
||||
);
|
||||
let again = set_of(&disk).join(format!("{seg}.g1"));
|
||||
assert!(
|
||||
again.is_file(),
|
||||
"the piece is written again as generation 1"
|
||||
);
|
||||
assert_eq!(sha(&std::fs::read(&again).unwrap()), {
|
||||
let m = manifest(&set_of(&disk), 2);
|
||||
m["journal"]["segments"].as_array().unwrap().last().unwrap()["sha256"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
});
|
||||
|
||||
// Many more backups: none reuses the damaged file, none finds more.
|
||||
for n in 3..8 {
|
||||
more(&mut s, n);
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(w.new && w.repaired.is_empty(), "{n}: {w:?}");
|
||||
}
|
||||
let last = s.head();
|
||||
// The drill proves the newest backup, which reaches the live head.
|
||||
let got = drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b.join("journal.jsonl"),
|
||||
&dir.path().join("drill"),
|
||||
Some(&last),
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(got, last);
|
||||
// A restore gives the newest books, not backup 1's.
|
||||
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||
let v = verify_found(&found, &dir.path().join("restore"), &Ctx::new()).unwrap();
|
||||
assert_eq!(v.head, last);
|
||||
assert_ne!(v.head, first_head);
|
||||
assert_eq!(v.passed_over, 0);
|
||||
// Manifests 1, 2, 3, the repair's (4) and the five after it.
|
||||
assert_eq!(v.number, 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drill_never_passes_on_an_older_backup() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
more(&mut s, 1);
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let second_head = s.head();
|
||||
more(&mut s, 2);
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let newest_head = s.head();
|
||||
// The newest backup's own segment is damaged after it was made, and no
|
||||
// backup comes after it to find that.
|
||||
flip(&set_of(&disk).join(newest_journal_segment(&set_of(&disk), 3)));
|
||||
|
||||
// The drill is a failure that says so, with the date of the older one.
|
||||
let err = drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b.join("journal.jsonl"),
|
||||
&dir.path().join("drill"),
|
||||
Some(&newest_head),
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
let words = err.to_string();
|
||||
match &err {
|
||||
BackupError::NewestDamaged {
|
||||
number,
|
||||
older_from,
|
||||
newest_from,
|
||||
} => {
|
||||
assert_eq!(*number, 3);
|
||||
assert!(older_from.is_some() && newest_from.is_some(), "{err:?}");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(words.contains("the newest backup (number 3"), "{words}");
|
||||
assert!(words.contains("is damaged; an older one from "), "{words}");
|
||||
assert!(!dir.path().join("drill").exists());
|
||||
|
||||
// A restore passes over it, and the preview can say so: both dates and
|
||||
// how many it passes over.
|
||||
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||
let v = verify_found(&found, &dir.path().join("restore"), &Ctx::new()).unwrap();
|
||||
assert_eq!(v.number, 2);
|
||||
assert_eq!(v.head, second_head);
|
||||
assert_eq!(v.passed_over, 1);
|
||||
assert!(v.newest_written.is_some() && !v.written.is_empty());
|
||||
|
||||
// Everything damaged: no older one proves whole either, and it says so.
|
||||
for n in [1u64, 2] {
|
||||
flip(&set_of(&disk).join(newest_journal_segment(&set_of(&disk), n)));
|
||||
}
|
||||
let err = drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b.join("journal.jsonl"),
|
||||
&dir.path().join("drill2"),
|
||||
None,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("no older one proves whole either"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drill_needs_the_newest_backup_to_reach_the_last_one_recorded_good() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let have = s.head();
|
||||
more(&mut s, 1);
|
||||
let recorded = s.head();
|
||||
// A backup was recorded good through `recorded`, but the folder's
|
||||
// newest stops at `have` (a manifest lost to a sync conflict, say).
|
||||
let err = drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b.join("journal.jsonl"),
|
||||
&dir.path().join("d"),
|
||||
Some(&recorded),
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("a backup that was made is not there"),
|
||||
"{err}"
|
||||
);
|
||||
// The same head with another hash is no better.
|
||||
let other = (have.0, "0".repeat(64));
|
||||
assert!(
|
||||
drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b.join("journal.jsonl"),
|
||||
&dir.path().join("d"),
|
||||
Some(&other),
|
||||
&Ctx::new(),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
// And it passes when it reaches what was recorded.
|
||||
assert_eq!(
|
||||
drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&b.join("journal.jsonl"),
|
||||
&dir.path().join("d"),
|
||||
Some(&have),
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap(),
|
||||
have
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_stored_file_is_found_by_the_rotation_and_the_next_backup_repairs_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
// Stored files, until one is in the share backup number 2 re-reads
|
||||
// (the share a file belongs to is its hash's first four digits modulo
|
||||
// 16: every stored file is re-read within 16 backups).
|
||||
let mut chosen: Option<(String, Vec<u8>)> = None;
|
||||
for n in 0..400 {
|
||||
let bytes = format!("a stored file, number {n}").into_bytes();
|
||||
s.attach_receipt(None, &format!("s{n}.txt"), "text/plain", &bytes, None)
|
||||
.unwrap();
|
||||
let h = sha(&bytes);
|
||||
if chosen.is_none() && u64::from_str_radix(&h[..4], 16).unwrap() % 16 == 2 {
|
||||
chosen = Some((h, bytes));
|
||||
}
|
||||
if chosen.is_some() && n > 5 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (h, bytes) = chosen.expect("some file is in the share");
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let rel = format!("files/{}/{h}", &h[..2]);
|
||||
let piece = set_of(&disk).join(&rel);
|
||||
flip(&piece);
|
||||
let flipped = std::fs::read(&piece).unwrap();
|
||||
more(&mut s, 1);
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert_eq!(w.number, 2);
|
||||
assert_eq!(w.repaired, vec![rel.clone()], "{w:?}");
|
||||
assert_eq!(std::fs::read(&piece).unwrap(), flipped, "left where it is");
|
||||
let again = set_of(&disk).join(format!("{rel}.g1"));
|
||||
assert_eq!(std::fs::read(&again).unwrap(), bytes);
|
||||
// Every manifest of the set restores with the file whole (the reader
|
||||
// takes the generation that hashes right).
|
||||
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
|
||||
assert_eq!(v.passed_over, 0);
|
||||
assert_eq!(v.head, s.head());
|
||||
let restored = v.tree.join("blobs").join(&h[..2]).join(&h[2..4]).join(&h);
|
||||
assert_eq!(std::fs::read(restored).unwrap(), bytes);
|
||||
// And the next backup carries on without finding it again.
|
||||
more(&mut s, 2);
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(w.new && w.repaired.is_empty(), "{w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_damaged_as_it_is_written_is_repaired_in_the_same_backup() {
|
||||
// A piece that is there under its name but is not what its name says
|
||||
// (a copy that died half way on a disk that takes no links, a bad
|
||||
// sector) is taken as the piece by a put; the proof finds it.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let set = set_of(&disk);
|
||||
let flipped_once = Arc::new(Mutex::new(false));
|
||||
let ctx = {
|
||||
let (set, done) = (set.clone(), flipped_once.clone());
|
||||
Ctx::new().with_faults(Arc::new(move |kind, rel| {
|
||||
if kind == "published" && rel.starts_with("files/") {
|
||||
let mut d = done.lock().unwrap();
|
||||
if !*d {
|
||||
flip(&set.join(rel));
|
||||
*d = true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}))
|
||||
};
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap();
|
||||
assert!(w.new);
|
||||
assert_eq!(w.repaired.len(), 1, "{w:?}");
|
||||
assert!(set.join(format!("{}.g1", w.repaired[0])).is_file());
|
||||
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
|
||||
assert_eq!(v.head, s.head());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_vault_record_and_an_index_segment_are_written_again_too() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let vault_bytes = b"a sealed vault record".to_vec();
|
||||
std::fs::create_dir_all(b.join("vault")).unwrap();
|
||||
std::fs::write(b.join("vault").join("tin-1.bin"), &vault_bytes).unwrap();
|
||||
std::fs::create_dir_all(b.join("keys")).unwrap();
|
||||
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let set = set_of(&disk);
|
||||
flip(&set.join(format!("vault/{}", sha(&vault_bytes))));
|
||||
let index = manifest(&set, 1)["files"]["segments"][0]["file"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
flip(&set.join(&index));
|
||||
more(&mut s, 1);
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(w.new, "{w:?}");
|
||||
assert_eq!(w.repaired.len(), 2, "{w:?}");
|
||||
// The newest manifest names the new generations; the restore proves.
|
||||
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
|
||||
assert_eq!(v.head, s.head());
|
||||
assert_eq!(v.passed_over, 0);
|
||||
assert_eq!(
|
||||
std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(),
|
||||
vault_bytes
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn books_behind_the_destination_are_ahead_and_other_books_are_diverged() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (b, old, other) = (
|
||||
dir.path().join("book"),
|
||||
dir.path().join("old"),
|
||||
dir.path().join("other"),
|
||||
);
|
||||
let mut s = book(&b);
|
||||
// The books as they were: a copy of the folder at this point.
|
||||
copy_tree(&b, &old);
|
||||
more(&mut s, 1);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let before = tree(&disk);
|
||||
|
||||
// Restored from an older backup: the live journal is the beginning of
|
||||
// the destination's. That is ahead, and the words say what to do.
|
||||
let old_store = Store::open(&old).unwrap();
|
||||
let err = write_destination(
|
||||
&plain(&disk),
|
||||
&Cut::take("acme", &old, old_store.head()).unwrap(),
|
||||
true,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, BackupError::Ahead(..)), "{err:?}");
|
||||
let words = err.to_string();
|
||||
assert!(words.contains("a longer history of these books"), "{words}");
|
||||
assert!(words.contains("start a new backup set"), "{words}");
|
||||
assert_eq!(tree(&disk), before, "nothing was written");
|
||||
|
||||
// Another history under the same id is diverged, said as such (not
|
||||
// ahead, whichever is longer).
|
||||
let other_store = book(&other);
|
||||
let err = write_destination(
|
||||
&plain(&disk),
|
||||
&Cut::take("acme", &other, other_store.head()).unwrap(),
|
||||
true,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(err, BackupError::Elsewhere);
|
||||
assert!(err.to_string().contains("diverged"), "{err}");
|
||||
let mut longer = other_store;
|
||||
for n in 0..4 {
|
||||
more(&mut longer, n);
|
||||
}
|
||||
let err = write_destination(
|
||||
&plain(&disk),
|
||||
&Cut::take("acme", &other, longer.head()).unwrap(),
|
||||
true,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(err, BackupError::Elsewhere);
|
||||
assert_eq!(tree(&disk), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_set_begins_beside_the_old_at_the_persons_request_and_the_old_is_never_touched() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (b, old) = (dir.path().join("book"), dir.path().join("old"));
|
||||
let mut s = book(&b);
|
||||
copy_tree(&b, &old);
|
||||
more(&mut s, 1);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
let before = tree(&disk);
|
||||
let mut old_store = Store::open(&old).unwrap();
|
||||
let old_cut = Cut::take("acme", &old, old_store.head()).unwrap();
|
||||
assert!(matches!(
|
||||
write_destination(&plain(&disk), &old_cut, true, &Ctx::new()),
|
||||
Err(BackupError::Ahead(..))
|
||||
));
|
||||
|
||||
// At the person's request: a new set, `.2`, beside it.
|
||||
let w = write_destination_with(
|
||||
&plain(&disk),
|
||||
&old_cut,
|
||||
Options {
|
||||
may_create: true,
|
||||
new_set: true,
|
||||
},
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((w.number, w.new), (1, true));
|
||||
assert!(
|
||||
disk.join("wanderbooks-acme.2/manifests/000001.json")
|
||||
.is_file()
|
||||
);
|
||||
let after = tree(&disk);
|
||||
for (name, bytes) in &before {
|
||||
assert_eq!(
|
||||
after.get(name),
|
||||
Some(bytes),
|
||||
"{name}: the old set is untouched"
|
||||
);
|
||||
}
|
||||
|
||||
// The next ordinary backup goes to the new set, which grows; the old
|
||||
// one stays as it was.
|
||||
more(&mut old_store, 9);
|
||||
let w = write_destination(
|
||||
&plain(&disk),
|
||||
&Cut::take("acme", &old, old_store.head()).unwrap(),
|
||||
true,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(w.number, 2);
|
||||
assert!(
|
||||
disk.join("wanderbooks-acme.2/manifests/000002.json")
|
||||
.is_file()
|
||||
);
|
||||
let after = tree(&disk);
|
||||
for (name, bytes) in &before {
|
||||
assert_eq!(after.get(name), Some(bytes), "{name}");
|
||||
}
|
||||
// A drill takes the newest set too.
|
||||
assert_eq!(
|
||||
drill(
|
||||
&plain(&disk),
|
||||
"acme",
|
||||
&old.join("journal.jsonl"),
|
||||
&dir.path().join("d"),
|
||||
Some(&old_store.head()),
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap(),
|
||||
old_store.head()
|
||||
);
|
||||
// The folder now holds two sets of the same books: a restore from it
|
||||
// asks which (the sets are listed with their dates), never guesses.
|
||||
assert!(matches!(
|
||||
find(&disk, None, &Ctx::new()),
|
||||
Err(BackupError::Several(_))
|
||||
));
|
||||
let listed = ledger_store::backup::list(&disk);
|
||||
assert_eq!(listed.len(), 2);
|
||||
assert!(
|
||||
listed
|
||||
.iter()
|
||||
.all(|c| c.through_seq.is_some() && c.written.is_some())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_folder_is_a_legal_name_whatever_the_books_are_called() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
for id in ["con", "nul", "aux", "prn", "com1", "lpt9"] {
|
||||
let b = dir.path().join(format!("book-{id}"));
|
||||
let s = book(&b);
|
||||
write_destination(
|
||||
&plain(&disk),
|
||||
&Cut::take(id, &b, s.head()).unwrap(),
|
||||
true,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
disk.join(format!("wanderbooks-{id}/manifests/000001.json"))
|
||||
.is_file(),
|
||||
"{id}"
|
||||
);
|
||||
assert!(!disk.join(id).exists(), "{id}: no reserved name is made");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_newest_backup_is_tried_in_the_good_case() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
for n in 0..6 {
|
||||
more(&mut s, n);
|
||||
write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
}
|
||||
// Each backup added one segment, and each manifest names only its own.
|
||||
let segments: usize = (1..=6)
|
||||
.map(|n| {
|
||||
manifest(&set_of(&disk), n)["journal"]["segments"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len()
|
||||
})
|
||||
.sum();
|
||||
assert_eq!(segments, 6);
|
||||
let probes = Arc::new(Mutex::new(0usize));
|
||||
let ctx = {
|
||||
let probes = probes.clone();
|
||||
Ctx::new().with_trace(Arc::new(move |kind, rel| {
|
||||
if kind == "len" && rel.starts_with("journal/") {
|
||||
*probes.lock().unwrap() += 1;
|
||||
}
|
||||
}))
|
||||
};
|
||||
let found = find(&disk, None, &ctx).unwrap();
|
||||
let v = verify_found(&found, &dir.path().join("v"), &ctx).unwrap();
|
||||
assert_eq!(v.number, 6);
|
||||
// One look at each journal segment of the newest manifest to find the
|
||||
// set's book, one to prove it: never the segments of the five older
|
||||
// manifests, which reading every manifest first would have measured
|
||||
// too (1 + 2 + ... + 6 more).
|
||||
assert_eq!(*probes.lock().unwrap(), 2 * segments);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backup_cut_while_the_vault_is_being_written_restores_a_vault_that_matches_the_journal() {
|
||||
// ledger-vault stages a record as `NAME.staged-TAG` and sets the old one
|
||||
// aside as `NAME.purging-TAG` while a call is between its first step and
|
||||
// its last. A backup taken then must hold the vault as the journal says
|
||||
// it is: the staged record is not the books' yet, and the set-aside one
|
||||
// still is.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let mut s = book(&b);
|
||||
let record = b"sealed tin record, party one".to_vec();
|
||||
let party = s.add_party("Mo", &[Role::Member]).unwrap();
|
||||
s.set_party_tin(
|
||||
party,
|
||||
Some(TinFacts {
|
||||
tin_type: TinType::Ssn,
|
||||
last4: "4915".into(),
|
||||
vault_record: Some(sha(&record)),
|
||||
purged: None,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir_all(b.join("vault")).unwrap();
|
||||
std::fs::create_dir_all(b.join("keys")).unwrap();
|
||||
std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap();
|
||||
// The purge of party 1's record is staged: set aside, not yet journaled.
|
||||
let tag = "0123456789abcdef";
|
||||
std::fs::write(
|
||||
b.join("vault").join(format!("tin-1.purging-{tag}")),
|
||||
&record,
|
||||
)
|
||||
.unwrap();
|
||||
// And a new record for party 2 is staged, not the books'.
|
||||
std::fs::write(
|
||||
b.join("vault").join(format!("tin-2.staged-{tag}")),
|
||||
b"staged, not committed",
|
||||
)
|
||||
.unwrap();
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(w.new && w.repaired.is_empty(), "{w:?}");
|
||||
let found = find(&disk, None, &Ctx::new()).unwrap();
|
||||
let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap();
|
||||
let held: Vec<String> = std::fs::read_dir(v.tree.join("vault"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(held, vec!["tin-1.bin".to_string()], "{held:?}");
|
||||
assert_eq!(
|
||||
std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(),
|
||||
record
|
||||
);
|
||||
// No scratch name of the vault is anywhere in the destination.
|
||||
assert!(
|
||||
!tree(&disk)
|
||||
.keys()
|
||||
.any(|n| n.contains(".staged-") || n.contains(".purging-"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proof_cut_short_by_a_close_ends_cleanly_and_is_made_again_by_the_next_backup() {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let b = dir.path().join("book");
|
||||
let s = book(&b);
|
||||
let disk = dir.path().join("disk");
|
||||
std::fs::create_dir(&disk).unwrap();
|
||||
// The books close while the backup's proof is under way (here: as it
|
||||
// replays the chain).
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let ctx = {
|
||||
let stop = stop.clone();
|
||||
Ctx::new()
|
||||
.with_stop(stop.clone())
|
||||
.with_phase_watch(Arc::new(move |p: &str| {
|
||||
if p == "replay" {
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}))
|
||||
};
|
||||
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap_err();
|
||||
assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}");
|
||||
// Nothing of the proof is left behind in the books' folder, and the
|
||||
// manifest that was written is there but is not marked proven.
|
||||
let left: Vec<_> = std::fs::read_dir(b.join("ops"))
|
||||
.map(|d| {
|
||||
d.flatten()
|
||||
.filter(|e| e.file_name().to_string_lossy().starts_with("proof-"))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
assert!(left.is_empty(), "scratch books left: {left:?}");
|
||||
let set = set_of(&disk);
|
||||
assert!(set.join("manifests/000001.json").is_file());
|
||||
assert!(!set.join("proofs/000001").exists());
|
||||
// The next backup has nothing new to write, and still proves it: it
|
||||
// never says good of a backup that was not proven.
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert_eq!(w.number, 1);
|
||||
assert!(!w.new, "{w:?}");
|
||||
assert!(set.join("proofs/000001").is_file());
|
||||
// Once proven, a backup with nothing new is only looked at.
|
||||
let before = tree(&disk);
|
||||
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
|
||||
assert!(!w.new);
|
||||
assert_eq!(tree(&disk), before);
|
||||
}
|
||||
@@ -1338,34 +1338,39 @@ fn books_that_changed_since_the_preview_are_not_adopted() {
|
||||
assert_eq!(report.source_head, now);
|
||||
}
|
||||
|
||||
/// A backup of `store`'s books (in `dir`) in a folder target under
|
||||
/// `home`: its address.
|
||||
fn backed_up(home: &Path, dir: &Path, store: &Store) -> Option<String> {
|
||||
use ledger_store::backup::{self, Git, Target};
|
||||
let git = Git::find().ok()?;
|
||||
backup::commit(&git, dir, "acme", store.head()).unwrap();
|
||||
/// A backup of `store`'s books (in `dir`) in a folder under `home`: the
|
||||
/// folder.
|
||||
fn backed_up(home: &Path, dir: &Path, store: &Store) -> std::path::PathBuf {
|
||||
use ledger_store::backup::{Ctx, Cut, Destination, write_destination};
|
||||
let folder = home.join("disk");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let target = Target::Folder(folder);
|
||||
backup::push(&git, dir, "acme", &target, true).unwrap();
|
||||
Some(target.source("acme"))
|
||||
let cut = Cut::take("acme", dir, store.head()).unwrap();
|
||||
write_destination(
|
||||
&Destination {
|
||||
folder: folder.clone(),
|
||||
key: None,
|
||||
},
|
||||
&cut,
|
||||
true,
|
||||
&Ctx::new(),
|
||||
)
|
||||
.unwrap();
|
||||
folder
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restore_never_moves_books_something_holds() {
|
||||
use ledger_store::backup::Git;
|
||||
let home = tmp("restore-held");
|
||||
let (root, _) = Root::setup(home.path(), None, None).unwrap();
|
||||
let acme = id("acme");
|
||||
let held = root.create_book(&acme, Currency::USD).unwrap();
|
||||
let dir = root.book_dir(&acme);
|
||||
let source = backed_up(home.path(), &dir, &held).expect("git is installed");
|
||||
let git = Git::find().unwrap();
|
||||
let preview = root.restore_preview(&git, &source, &acme).unwrap();
|
||||
let source = backed_up(home.path(), &dir, &held);
|
||||
let preview = root.restore_preview(&source, None, &acme).unwrap();
|
||||
assert!(preview.exists);
|
||||
// Open (its writer lock held): refused, nothing moved.
|
||||
let e = root
|
||||
.restore(&git, &source, &acme, &preview.head, true)
|
||||
.restore(&source, None, &acme, &preview.head, true)
|
||||
.unwrap_err();
|
||||
assert!(e.to_string().contains("are open"), "{e}");
|
||||
assert!(dir.join(JOURNAL_FILE).is_file());
|
||||
@@ -1378,17 +1383,17 @@ fn a_restore_never_moves_books_something_holds() {
|
||||
);
|
||||
// Not over books without --replace; nothing to replace that isn't.
|
||||
let e = root
|
||||
.restore(&git, &source, &acme, &preview.head, false)
|
||||
.restore(&source, None, &acme, &preview.head, false)
|
||||
.unwrap_err();
|
||||
assert!(matches!(e, RootError::Exists(_)), "{e}");
|
||||
let e = root
|
||||
.restore(&git, &source, &id("nobody"), &preview.head, true)
|
||||
.restore(&source, None, &id("nobody"), &preview.head, true)
|
||||
.unwrap_err();
|
||||
assert!(e.to_string().contains("no books called"), "{e}");
|
||||
// Let go: replaced, the old kept whole.
|
||||
drop(held);
|
||||
let r = root
|
||||
.restore(&git, &source, &acme, &preview.head, true)
|
||||
.restore(&source, None, &acme, &preview.head, true)
|
||||
.unwrap();
|
||||
let kept = root.path().join("legacy").join(r.replaced.unwrap());
|
||||
assert!(kept.join(JOURNAL_FILE).is_file());
|
||||
@@ -1831,17 +1836,16 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
|
||||
// restore, over books that exist: they stay as they are.
|
||||
let dir = root.book_dir(&id("adopted"));
|
||||
let store = Store::open(&dir).unwrap();
|
||||
let source = backed_up(home.path(), &dir, &store).expect("git is installed");
|
||||
let source = backed_up(home.path(), &dir, &store);
|
||||
drop(store);
|
||||
let git = ledger_store::backup::Git::find().unwrap();
|
||||
let preview = root.restore_preview(&git, &source, &id("adopted")).unwrap();
|
||||
let preview = root.restore_preview(&source, None, &id("adopted")).unwrap();
|
||||
let phases = ["start", "fetch", "copy", "file", "open", "verify", "place"];
|
||||
for phase in phases {
|
||||
let before = root_files(&root);
|
||||
let (stop, seen) = stopping_at(phase);
|
||||
let e = refused(root.restore_stoppable(
|
||||
&git,
|
||||
&source,
|
||||
None,
|
||||
&id("adopted"),
|
||||
&preview.head,
|
||||
true,
|
||||
@@ -1858,7 +1862,7 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
|
||||
// The preview too: stopped, nothing left of its clone.
|
||||
let before = root_files(&root);
|
||||
let (stop, _) = stopping_at("fetch");
|
||||
let e = refused(root.restore_preview_stoppable(&git, &source, &id("adopted"), &stop));
|
||||
let e = refused(root.restore_preview_stoppable(&source, None, &id("adopted"), &stop));
|
||||
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
|
||||
assert_eq!(root_files(&root), before);
|
||||
// Never stopped, a restore asks `place` last and goes through.
|
||||
@@ -1868,7 +1872,7 @@ fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_i
|
||||
std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string()))
|
||||
});
|
||||
let r = root
|
||||
.restore_stoppable(&git, &source, &id("adopted"), &preview.head, true, &stop)
|
||||
.restore_stoppable(&source, None, &id("adopted"), &preview.head, true, &stop)
|
||||
.unwrap();
|
||||
assert!(r.replaced.is_some());
|
||||
assert_eq!(
|
||||
|
||||
Reference in new issue
Block a user