|
| 1 | +//! Importing a backup (spec 14.2). The file is opened and staged while |
| 2 | +//! Botloft runs, and only swapped in on the next start, before the |
| 3 | +//! database opens: nothing has the old data open then. What was there goes |
| 4 | +//! aside, never deleted. |
| 5 | +
|
| 6 | +use std::fs::{self, File}; |
| 7 | +use std::io::{self, BufReader, BufWriter, Read}; |
| 8 | +use std::path::{Path, PathBuf}; |
| 9 | + |
| 10 | +use botloft_core::protocol::BackupManifest; |
| 11 | +use tracing::{info, warn}; |
| 12 | +use zip::ZipArchive; |
| 13 | + |
| 14 | +use super::seal::{SealError, open}; |
| 15 | +use super::{DATABASE_ENTRY, MANIFEST_ENTRY, WORKSPACES_ENTRY}; |
| 16 | +use crate::paths::Paths; |
| 17 | + |
| 18 | +const STAGED: &str = "staged.zip"; |
| 19 | +/// Written when the owner confirms: the next start applies the backup. |
| 20 | +const READY: &str = "READY"; |
| 21 | +/// What the archive unpacks into before the swap. |
| 22 | +const UNPACKED: &str = "unpacked"; |
| 23 | + |
| 24 | +fn restore_dir(paths: &Paths) -> PathBuf { |
| 25 | + paths.home.join("restore") |
| 26 | +} |
| 27 | + |
| 28 | +fn other(err: impl std::fmt::Display) -> io::Error { |
| 29 | + io::Error::other(err.to_string()) |
| 30 | +} |
| 31 | + |
| 32 | +/// "0.10.0" as numbers, to compare. |
| 33 | +fn version(text: &str) -> Vec<u64> { |
| 34 | + text.split('.') |
| 35 | + .map(|part| part.trim().parse().unwrap_or(0)) |
| 36 | + .collect() |
| 37 | +} |
| 38 | + |
| 39 | +/// Opens the backup with the passphrase, checks it, and keeps it staged. |
| 40 | +/// Nothing changes until `confirm` and a restart. |
| 41 | +pub fn stage(paths: &Paths, file: &Path, passphrase: &str) -> Result<BackupManifest, SealError> { |
| 42 | + let dir = restore_dir(paths); |
| 43 | + let _ = fs::remove_dir_all(&dir); |
| 44 | + fs::create_dir_all(&dir)?; |
| 45 | + let staged = dir.join(STAGED); |
| 46 | + let opened = { |
| 47 | + let mut sealed = BufReader::new(File::open(file)?); |
| 48 | + let mut out = BufWriter::new(File::create(&staged)?); |
| 49 | + open(&mut sealed, &mut out, passphrase) |
| 50 | + }; |
| 51 | + if let Err(err) = opened { |
| 52 | + let _ = fs::remove_dir_all(&dir); |
| 53 | + return Err(err); |
| 54 | + } |
| 55 | + let checked = check(&staged); |
| 56 | + if checked.is_err() { |
| 57 | + let _ = fs::remove_dir_all(&dir); |
| 58 | + } |
| 59 | + checked |
| 60 | +} |
| 61 | + |
| 62 | +fn check(staged: &Path) -> Result<BackupManifest, SealError> { |
| 63 | + let mut zip = ZipArchive::new(File::open(staged)?).map_err(|_| SealError::NotABackup)?; |
| 64 | + let mut text = String::new(); |
| 65 | + zip.by_name(MANIFEST_ENTRY) |
| 66 | + .map_err(|_| SealError::NotABackup)? |
| 67 | + .read_to_string(&mut text)?; |
| 68 | + let manifest: BackupManifest = |
| 69 | + serde_json::from_str(&text).map_err(|_| SealError::NotABackup)?; |
| 70 | + if manifest.format != 1 || version(&manifest.version) > version(env!("CARGO_PKG_VERSION")) { |
| 71 | + return Err(SealError::Newer); |
| 72 | + } |
| 73 | + zip.by_name(DATABASE_ENTRY) |
| 74 | + .map_err(|_| SealError::NotABackup)?; |
| 75 | + Ok(manifest) |
| 76 | +} |
| 77 | + |
| 78 | +/// The owner said yes: the staged backup replaces everything on the next |
| 79 | +/// start. |
| 80 | +pub fn confirm(paths: &Paths) -> io::Result<()> { |
| 81 | + let dir = restore_dir(paths); |
| 82 | + if !dir.join(STAGED).is_file() { |
| 83 | + return Err(io::Error::new( |
| 84 | + io::ErrorKind::NotFound, |
| 85 | + "no backup is ready to restore; open it again", |
| 86 | + )); |
| 87 | + } |
| 88 | + fs::write(dir.join(READY), b"") |
| 89 | +} |
| 90 | + |
| 91 | +/// The owner changed their mind: the staged backup goes. |
| 92 | +pub fn cancel(paths: &Paths) { |
| 93 | + let _ = fs::remove_dir_all(restore_dir(paths)); |
| 94 | +} |
| 95 | + |
| 96 | +/// On start, before the database opens: swaps in a confirmed backup. The |
| 97 | +/// database and the crews' folders that were there move aside, to |
| 98 | +/// `<home>\before-restore\<time>` and `<workspaces_root>-before-restore-<time>`. |
| 99 | +/// Returns where the old data went, if a backup was applied. |
| 100 | +pub fn apply_pending(paths: &Paths, stamp: &str) -> io::Result<Option<PathBuf>> { |
| 101 | + let dir = restore_dir(paths); |
| 102 | + if !dir.join(READY).is_file() { |
| 103 | + return Ok(None); |
| 104 | + } |
| 105 | + // Once only: a backup that cannot be applied is not tried forever. |
| 106 | + fs::remove_file(dir.join(READY))?; |
| 107 | + let unpacked = dir.join(UNPACKED); |
| 108 | + let _ = fs::remove_dir_all(&unpacked); |
| 109 | + unpack(&dir.join(STAGED), &unpacked)?; |
| 110 | + |
| 111 | + let aside = paths.home.join("before-restore").join(stamp); |
| 112 | + fs::create_dir_all(&aside)?; |
| 113 | + let db = paths.db(); |
| 114 | + for suffix in ["", "-wal", "-shm"] { |
| 115 | + let file = PathBuf::from(format!("{}{suffix}", db.display())); |
| 116 | + if file.exists() { |
| 117 | + let name = file.file_name().ok_or_else(|| other("no file name"))?; |
| 118 | + fs::rename(&file, aside.join(name))?; |
| 119 | + } |
| 120 | + } |
| 121 | + let root = &paths.workspaces_root; |
| 122 | + if root.exists() { |
| 123 | + let name = root.file_name().ok_or_else(|| other("no folder name"))?; |
| 124 | + let moved = |
| 125 | + root.with_file_name(format!("{}-before-restore-{stamp}", name.to_string_lossy())); |
| 126 | + move_dir(root, &moved)?; |
| 127 | + info!(to = %moved.display(), "the crews' folders were moved aside"); |
| 128 | + } |
| 129 | + let workspaces = unpacked.join(WORKSPACES_ENTRY); |
| 130 | + if workspaces.exists() { |
| 131 | + move_dir(&workspaces, root)?; |
| 132 | + } else { |
| 133 | + fs::create_dir_all(root)?; |
| 134 | + } |
| 135 | + fs::rename(unpacked.join(DATABASE_ENTRY), &db)?; |
| 136 | + if let Err(err) = fs::remove_dir_all(&dir) { |
| 137 | + warn!("could not clean up after restoring: {err}"); |
| 138 | + } |
| 139 | + Ok(Some(aside)) |
| 140 | +} |
| 141 | + |
| 142 | +/// Every entry of the archive under `to`, refusing any that would land |
| 143 | +/// outside it. |
| 144 | +fn unpack(archive: &Path, to: &Path) -> io::Result<()> { |
| 145 | + let mut zip = ZipArchive::new(File::open(archive)?).map_err(other)?; |
| 146 | + for index in 0..zip.len() { |
| 147 | + let mut entry = zip.by_index(index).map_err(other)?; |
| 148 | + let Some(relative) = entry.enclosed_name() else { |
| 149 | + return Err(other("the backup has a file outside its folders")); |
| 150 | + }; |
| 151 | + let target = to.join(relative); |
| 152 | + if entry.is_dir() { |
| 153 | + fs::create_dir_all(&target)?; |
| 154 | + continue; |
| 155 | + } |
| 156 | + if let Some(parent) = target.parent() { |
| 157 | + fs::create_dir_all(parent)?; |
| 158 | + } |
| 159 | + io::copy(&mut entry, &mut BufWriter::new(File::create(&target)?))?; |
| 160 | + } |
| 161 | + Ok(()) |
| 162 | +} |
| 163 | + |
| 164 | +/// Renames, or copies and removes when the two are on different drives. |
| 165 | +fn move_dir(from: &Path, to: &Path) -> io::Result<()> { |
| 166 | + if fs::rename(from, to).is_ok() { |
| 167 | + return Ok(()); |
| 168 | + } |
| 169 | + copy_dir(from, to)?; |
| 170 | + fs::remove_dir_all(from) |
| 171 | +} |
| 172 | + |
| 173 | +fn copy_dir(from: &Path, to: &Path) -> io::Result<()> { |
| 174 | + fs::create_dir_all(to)?; |
| 175 | + for entry in fs::read_dir(from)? { |
| 176 | + let entry = entry?; |
| 177 | + let kind = entry.file_type()?; |
| 178 | + let target = to.join(entry.file_name()); |
| 179 | + if kind.is_dir() { |
| 180 | + copy_dir(&entry.path(), &target)?; |
| 181 | + } else if kind.is_file() { |
| 182 | + fs::copy(entry.path(), target)?; |
| 183 | + } |
| 184 | + } |
| 185 | + Ok(()) |
| 186 | +} |
| 187 | + |
| 188 | +#[cfg(test)] |
| 189 | +mod tests { |
| 190 | + use super::*; |
| 191 | + |
| 192 | + #[test] |
| 193 | + fn versions_compare_by_number() { |
| 194 | + assert!(version("0.10.0") > version("0.9.1")); |
| 195 | + assert!(version("1.0.0") > version("0.10.0")); |
| 196 | + assert_eq!(version("0.10.0"), version("0.10.0")); |
| 197 | + } |
| 198 | +} |
0 commit comments