use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use super::copy::{coherent_copy, recover};
use super::manifest::{self, Listed};
use crate::conversation::Error;
use crate::store::FileStore;
use crate::store::fileio::{private, private_builder, private_mkdir, remove_tree};
use crate::store::time::Stamp;
pub(crate) const DIRECTORY: &str = "login-import";
const SEALED: &str = "snapshot";
const STORE: &str = "store";
const MANIFEST: &str = "manifest.json";
pub(crate) const LIFETIME_SECONDS: i64 = 86_400;
#[derive(Debug)]
pub(crate) enum Fault {
Exists { id: String },
Changed { path: String },
Unsupported { path: String, what: &'static str },
Busy,
Store(Error),
}
impl From<io::Error> for Fault {
fn from(error: io::Error) -> Self {
Self::Store(error.into())
}
}
impl From<Error> for Fault {
fn from(error: Error) -> Self {
Self::Store(error)
}
}
impl Fault {
pub(crate) fn message(&self) -> String {
match self {
Self::Exists { id } => format!(
"a login import snapshot is already taken ({id}); resume that import or dispose \
of the snapshot first"
),
Self::Changed { path } => format!(
"the login import snapshot changed since it was taken ({path} differs); dispose \
of it and start the import again"
),
Self::Unsupported { path, what } => format!(
"the home holds {what} at {path}; the import copies no link or special file, so \
move it out of the home and try again"
),
Self::Busy => "the home kept changing while it was copied; stop the agents writing \
to it and try again"
.to_string(),
Self::Store(error) => error.text(),
}
}
}
#[derive(Debug)]
pub(crate) struct Snapshot {
pub path: PathBuf,
pub id: String,
pub taken_at: Stamp,
pub files: u64,
pub bytes: u64,
}
impl Snapshot {
pub(crate) fn root(&self) -> PathBuf {
self.path.join(STORE)
}
pub(crate) fn store(&self) -> io::Result<FileStore> {
FileStore::open(&self.root())
}
pub(crate) fn expired(&self, now: Stamp) -> bool {
now.instant() - self.taken_at.instant() > LIFETIME_SECONDS * 1_000_000
}
}
pub(crate) fn take(home: &Path) -> Result<Snapshot, Fault> {
if !home.is_dir() {
let shown = home.display();
return Err(Error::Value(format!("there is no home at {shown} to import")).into());
}
let area = home.join(DIRECTORY);
private_mkdir(&area)?;
if let Some(sealed) = sealed(&area)? {
return Err(Fault::Exists { id: sealed.0 });
}
let partial = area.join(format!("{}.partial", uuid::Uuid::new_v4()));
private_builder().create(&partial)?;
let made = (|| {
let taken_at = Stamp::now();
let copy = partial.join(STORE);
coherent_copy(home, ©)?;
recover(©)?;
let listed = manifest::list(©)?;
let text = manifest::render(taken_at, &listed);
let mut file = private()
.write(true)
.create_new(true)
.open(partial.join(MANIFEST))?;
io::Write::write_all(&mut file, text.as_bytes())?;
file.sync_all()?;
Ok::<_, Fault>((taken_at, listed))
})();
let (taken_at, listed) = match made {
Ok(made) => made,
Err(fault) => {
let _ = remove_tree(&partial);
let _ = fs::remove_dir(&area);
return Err(fault);
}
};
let path = area.join(SEALED);
if let Err(error) = fs::rename(&partial, &path) {
let _ = remove_tree(&partial);
return Err(match sealed(&area)? {
Some((id, _)) => Fault::Exists { id },
None => error.into(),
});
}
Ok(snapshot(path, taken_at, &listed))
}
fn snapshot(path: PathBuf, taken_at: Stamp, listed: &Listed) -> Snapshot {
Snapshot {
path,
id: manifest::id(listed),
taken_at,
files: listed.len() as u64,
bytes: listed.iter().map(|file| file.1).sum(),
}
}
fn plain(path: &Path, dir: bool, shown: &str) -> Result<(), Fault> {
let unsupported = |what| {
let path = shown.to_string();
Err(Fault::Unsupported { path, what })
};
match fs::symlink_metadata(path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
Ok(meta) if meta.file_type().is_symlink() => unsupported("a symbolic link"),
Ok(meta) if meta.is_dir() != dir => unsupported("an unexpected kind of file"),
Ok(_) => Ok(()),
}
}
fn sealed(area: &Path) -> Result<Option<(String, Stamp)>, Fault> {
plain(area, true, DIRECTORY)?;
plain(&area.join(SEALED), true, SEALED)?;
plain(&area.join(SEALED).join(MANIFEST), false, MANIFEST)?;
plain(&area.join(SEALED).join(STORE), true, STORE)?;
let path = area.join(SEALED).join(MANIFEST);
match fs::read_to_string(&path) {
Ok(text) => {
let (taken_at, listed) = manifest::parse(&text).ok_or(Fault::Changed {
path: MANIFEST.to_string(),
})?;
Ok(Some((manifest::id(&listed), taken_at)))
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
if area.join(SEALED).exists() {
return Err(Fault::Changed {
path: MANIFEST.to_string(),
});
}
Ok(None)
}
Err(error) => Err(error.into()),
}
}
pub(crate) fn open(home: &Path) -> Result<Option<Snapshot>, Fault> {
let area = home.join(DIRECTORY);
let Some((_, taken_at)) = sealed(&area)? else {
return Ok(None);
};
let path = area.join(SEALED);
let text = fs::read_to_string(path.join(MANIFEST))?;
let (_, recorded) = manifest::parse(&text).ok_or(Fault::Changed {
path: MANIFEST.to_string(),
})?;
let found = manifest::list(&path.join(STORE))?;
if let Some(path) = manifest::first_difference(&recorded, &found) {
return Err(Fault::Changed { path });
}
Ok(Some(snapshot(path, taken_at, &found)))
}
pub(crate) fn dispose(home: &Path) -> Result<bool, Fault> {
let area = home.join(DIRECTORY);
match fs::symlink_metadata(&area) {
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error.into()),
Ok(meta) if !meta.is_dir() => {
return Err(Fault::Unsupported {
path: DIRECTORY.to_string(),
what: "something other than a directory",
});
}
Ok(_) => {}
}
if area.join(SEALED).exists() {
let doomed = area.join(format!("{}.disposing", uuid::Uuid::new_v4()));
fs::rename(area.join(SEALED), doomed)?;
}
for entry in fs::read_dir(&area)? {
let entry = entry?;
if entry.file_type()?.is_dir() {
remove_tree(&entry.path())?;
} else {
fs::remove_file(entry.path())?;
}
}
fs::remove_dir(&area)?;
Ok(true)
}
pub(crate) fn release(home: &Path) -> Result<(), Fault> {
let area = home.join(DIRECTORY);
if area.join(SEALED).exists() {
let doomed = area.join(format!("{}.disposing", uuid::Uuid::new_v4()));
fs::rename(area.join(SEALED), &doomed)?;
remove_tree(&doomed)?;
}
Ok(())
}