refactor: the server, restore and the window's seams on the plain-folder backup; git removed from the store
Restore reads a destination folder, a set's folder, or a backup file with an optional passphrase; the server cuts the books under the store's lock and writes the folder outside it; the format upgrade proves a local backup in the book's folder (the same form) before it moves the format. The old backup (git processes, their locks, the output drain) and every test of it are gone; what each test protected is held by the new form's tests (table in the report). Old settings and an old history in a book's folder are said in the status and left alone. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
9f4529b078
commit
a6cd89d2a6
35 files changed
+1150
-6636
No files matched your search
File diff suppressed because it is too large.
Load diff
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
|
||||
//! Where a backup's files live, behind one seam: a folder on a disk
|
||||
//! ([`DirSet`]), or the one-file form ([`crate::backups::single`]).
|
||||
//! ([`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
|
||||
File renamed without changes.
File renamed without changes.
@@ -137,6 +137,13 @@ impl BackupKey {
|
||||
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)
|
||||
File renamed without changes.
File renamed without changes.
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -21,17 +21,14 @@
|
||||
pub mod access;
|
||||
pub mod auth;
|
||||
pub mod backup;
|
||||
pub mod backups;
|
||||
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;
|
||||
|
||||
@@ -1146,6 +1146,10 @@ 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 and were passed over.
|
||||
pub passed_over: u64,
|
||||
}
|
||||
|
||||
/// What [`Root::restore`] did.
|
||||
@@ -1166,21 +1170,22 @@ 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,
|
||||
with_files: bool,
|
||||
) -> 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 +1199,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, with_files, &ctx));
|
||||
match proven {
|
||||
Ok(v) => Ok((scratch, v)),
|
||||
Err(e) => {
|
||||
// What the verification wrote goes with it (a stop leaves the
|
||||
@@ -1214,19 +1221,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 +1241,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, false)?;
|
||||
let vault = scratch.join(VAULT_DIR);
|
||||
let vault_files = if vault.is_dir() {
|
||||
std::fs::read_dir(&vault)
|
||||
@@ -1250,6 +1257,8 @@ 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,
|
||||
})
|
||||
})()
|
||||
.map_err(|e| self.hide(e))
|
||||
@@ -1264,13 +1273,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 +1296,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 +1316,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 +1353,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, true)?;
|
||||
let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id()));
|
||||
let built = (|| -> Result<RestoreReport, RootError> {
|
||||
stop.at("copy", "restored")?;
|
||||
@@ -1377,11 +1393,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(
|
||||
|
||||
Reference in new issue
Block a user