//! The command line of `in`. `in [--config ] [serve]` runs the server, and a bare `in` does the same. //! The other commands operate on a stopped instance: each takes the data-directory lock, so a server that is //! running makes them refuse with a message instead of racing it. //! //! Exit status: 0 for success, 1 for a failure or a check that found problems, 2 for a usage error (clap //! reports those itself). use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::time::SystemTime; use clap::{Parser, Subcommand}; use in_core::backup; use in_core::config::{Backend, Config}; use in_core::error::Error; use in_core::export::export_member; use in_core::fsck; use in_core::store::members::MemberFields; use in_core::time::now_stamp; use crate::boot; /// The parsed command line. #[derive(Debug, Parser)] #[command(name = "in", about = "The family's file drive", version)] pub struct Cli { /// Configuration file. Without it, `IN_CONFIG` is used, then `config/in.toml`. #[arg(long, global = true, value_name = "PATH")] pub config: Option, /// The command. A bare `in` runs the server. #[command(subcommand)] pub command: Option, } /// The commands. #[derive(Debug, Subcommand)] pub enum Command { /// Run the server. This is the default. Serve, /// Copy one person's live files into a folder tree that uses their folder and file names. Export { /// The person: their subject id, or their email address. #[arg(long, value_name = "SUB|EMAIL")] member: String, /// The directory to write into. It is created when missing. #[arg(long, value_name = "DIR")] out: PathBuf, }, /// Check the database and the blob tree against each other. Changes nothing unless `--quarantine` is given. Fsck { /// Also hash every blob and compare it with its row. Reads every byte, so it is slow. #[arg(long)] hash: bool, /// Move orphan blobs that are over an hour old into `quarantine/` under the data directory. Local /// storage only. Nothing is deleted. #[arg(long)] quarantine: bool, }, /// Replace the database with the one in a backup set. The server must be stopped. Restore { /// The backup set directory (the one holding `in.db`, `manifest.json` and `manifest.mac`). #[arg(long, value_name = "SET")] from: PathBuf, }, /// Quota maintenance. Quota { /// What to do. #[command(subcommand)] action: QuotaCommand, }, } /// The quota subcommands. #[derive(Debug, Subcommand)] pub enum QuotaCommand { /// Recompute every person's used bytes from their files, and print the ones that were wrong. Recompute, } /// Runs the command and maps the outcome to an exit status. pub async fn run(config: &Path, command: Command) -> ExitCode { let outcome = match command { Command::Serve => return serve(config).await, Command::Export { member, out } => export(config, &member, &out).await, Command::Fsck { hash, quarantine } => fsck_cmd(config, hash, quarantine).await, Command::Restore { from } => restore(config, &from).await, Command::Quota { action: QuotaCommand::Recompute, } => recompute(config).await, }; match outcome { Ok(true) => ExitCode::SUCCESS, Ok(false) => ExitCode::FAILURE, // A conflict here is the lock: say so in plain words, without the "conflict:" prefix. Err(Error::Conflict(message)) => { eprintln!("in: {message}"); ExitCode::FAILURE } Err(error) => { eprintln!("in: {error}"); ExitCode::FAILURE } } } /// Runs the server and maps its outcome. async fn serve(config: &Path) -> ExitCode { match boot::serve(config).await { Ok(()) => ExitCode::SUCCESS, Err(error) => { tracing::error!(error = %error, "in stopped with an error"); ExitCode::FAILURE } } } /// Finds the person named by a subject id or an email address. async fn find_member(store: &in_core::store::Store, who: &str) -> Result { let member = if who.contains('@') { store.member_by_email(who).await? } else { store.member(who).await? }; let member = member.ok_or_else(|| Error::Invalid(format!("no person named {who}")))?; Ok(MemberFields { sub: member.sub, email: member.email, name: member.name, is_admin: member.is_admin, locale: member.locale, zoneinfo: member.zoneinfo, picture_version: member.picture_version, im_updated_at: member.im_updated_at, }) } /// `in export`. True when every file was written and verified. async fn export(config: &Path, who: &str, out: &Path) -> Result { let offline = boot::open_offline(config).await?; let person = find_member(&offline.store, who).await?; let report = export_member(&offline.store, offline.blobs.as_ref(), &person.sub, out).await?; println!( "exported {} files ({} bytes) and {} folders to {}", report.files, report.bytes, report.folders, out.display() ); for id in &report.failed { println!("failed: file {id} did not verify and was not written"); } Ok(report.failed.is_empty()) } /// `in fsck`. True when the check found nothing wrong. Orphans are reported but do not fail the check. async fn fsck_cmd(config_path: &Path, hash: bool, quarantine: bool) -> Result { let config = Config::load(config_path)?; if quarantine && !matches!(config.storage.backend, Backend::Local) { return Err(Error::Config( "fsck --quarantine moves files on local disk, so it works only with the local blob backend".into(), )); } let offline = boot::open_offline(config_path).await?; let report = fsck::check(&offline.store, offline.blobs.as_ref(), hash).await?; println!("database: {}", report.integrity.replace('\n', "; ")); println!("rows checked: {}", report.rows_checked); println!("missing blobs: {}", report.missing_count); for key in &report.missing { println!(" missing {key}"); } println!("size mismatches: {}", report.size_mismatch.len()); for key in &report.size_mismatch { println!(" size {key}"); } if hash { println!("hash mismatches: {}", report.hash_mismatch.len()); for key in &report.hash_mismatch { println!(" hash {key}"); } } println!("orphan blobs (no row names them): {}", report.orphan_count); for key in &report.orphans { println!(" orphan {key}"); } if quarantine { quarantine_orphans(&config, &offline).await?; } Ok(report.is_clean()) } /// Moves the orphan blobs that are at least an hour old into the quarantine directory, and prints each one. async fn quarantine_orphans(config: &Config, offline: &boot::Offline) -> Result<(), Error> { let data_dir = config.data_dir.canonicalize()?; let found = fsck::orphans(&offline.store, offline.blobs.as_ref()).await?; let moved = fsck::quarantine( &data_dir.join(boot::BLOB_DIR), &data_dir.join(fsck::QUARANTINE_DIR), &found, SystemTime::now(), )?; println!( "quarantined {} orphan blobs to {}; {} younger than an hour were left in place", moved.len(), data_dir.join(fsck::QUARANTINE_DIR).display(), found.len() - moved.len() ); for key in &moved { println!(" moved {key}"); } Ok(()) } /// `in restore`. Opens nothing of the database itself: the manifest's MAC is checked first (with the instance /// key, which must already exist), then the snapshot is verified, and only then is the file replaced. True /// when the restore completed. async fn restore(config_path: &Path, from: &Path) -> Result { let config = Config::load(config_path)?; let _lock = boot::lock_data_dir(&config.data_dir)?; let data_dir = config.data_dir.canonicalize()?; // Read, never create: a missing key would make every set fail its MAC, and creating one here would hide that. let key = in_core::secret::read_key(&data_dir.join(boot::KEY_FILE))?; let stamp = now_stamp().replace([':', '.'], "-"); // The blob tree is opened only after the set has passed its checks, so a refusal creates nothing in it. let outcome = match backup::restore( &data_dir, &config.database, from, || boot::open_blobs(&config, &data_dir), &key, &stamp, ) .await { Ok(outcome) => outcome, Err(Error::Invalid(code)) => match refusal_words(&code) { Some(words) => { eprintln!("in: {words}"); return Ok(false); } None => return Err(Error::Invalid(code)), }, Err(error) => return Err(error), }; println!( "restored from {}: {} blobs listed, {} not in the blob tree", from.display(), outcome.blobs_listed, outcome.blobs_missing ); if let Some(previous) = &outcome.previous { println!("the replaced database is kept at {}", previous.display()); } Ok(true) } /// The plain words for a refused restore. The codes are what `in-core` returns and its tests match on them. fn refusal_words(code: &str) -> Option<&'static str> { Some(match code { "backup_hash" => { "the backup's database does not match its manifest hash: the set is damaged" } "backup_mac_bad" => { "the backup manifest's MAC does not verify: the set was changed, or this is not the instance key it was made with" } "backup_mac_missing" => "the backup set has no manifest MAC: the set is incomplete", "backup_manifest_missing" => "the backup set has no manifest: the set is incomplete", "backup_manifest_bad" => { "the backup manifest is unreadable or from another format: the set cannot be restored by this build" } "backup_snapshot_missing" => "the backup set has no database file: the set is incomplete", "backup_integrity" => "the backup's database fails its integrity check: the set is damaged", _ => return None, }) } /// `in quota recompute`. True when it ran; drift that it corrected is printed, not failed. async fn recompute(config: &Path) -> Result { let offline = boot::open_offline(config).await?; let drift = offline.store.reconcile_quota().await?; println!("corrected {} people", drift.len()); for item in &drift { println!( " {}: stored {} bytes, now {} bytes", item.sub, item.stored, item.actual ); } Ok(true) }