| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::fs::{DirBuilder, Permissions}; |
| 15 | use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; |
| 16 | use std::path::{Path, PathBuf}; |
| 17 | use std::process::ExitCode; |
| 18 | |
| 19 | use iz_core::config::Config; |
| 20 | use iz_core::manifest::{self, Manifest}; |
| 21 | use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; |
| 22 | use iz_core::store::export::{ReadOnly, migrations_problem}; |
| 23 | use iz_core::store::new_id; |
| 24 | |
| 25 | use super::{describe, existing_data_dir, fail, file_stamp, instance_key, take_lock}; |
| 26 | |
| 27 | |
| 28 | const SET_DB: &str = "iz.db"; |
| 29 | |
| 30 | const STAGING_PREFIX: &str = "restore-staging-"; |
| 31 | |
| 32 | |
| 33 | pub async fn run(config_path: &Path, from: &Path) -> ExitCode { |
| 34 | let config = match Config::load(config_path) { |
| 35 | Ok(config) => config, |
| 36 | Err(error) => return fail(describe(&error)), |
| 37 | }; |
| 38 | if let Err(error) = std::fs::create_dir_all(&config.data_dir) |
| 39 | .and_then(|()| std::fs::set_permissions(&config.data_dir, Permissions::from_mode(0o700))) |
| 40 | { |
| 41 | return fail(format!( |
| 42 | "the data directory {} cannot be created: {error}", |
| 43 | config.data_dir.display() |
| 44 | )); |
| 45 | } |
| 46 | let data_dir = match existing_data_dir(&config) { |
| 47 | Ok(dir) => dir, |
| 48 | Err(message) => return fail(message), |
| 49 | }; |
| 50 | let _lock = match take_lock(&data_dir) { |
| 51 | Ok(lock) => lock, |
| 52 | Err(code) => return code, |
| 53 | }; |
| 54 | let key = match instance_key(&data_dir) { |
| 55 | Ok(key) => key, |
| 56 | Err(message) => return fail(message), |
| 57 | }; |
| 58 | match restore(&config, &data_dir, from, &key).await { |
| 59 | Ok(summary) => { |
| 60 | println!("{summary}"); |
| 61 | ExitCode::SUCCESS |
| 62 | } |
| 63 | Err(message) => fail(message), |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | fn canonical_id(name: &str) -> Option<String> { |
| 70 | |
| 71 | blob_path(Path::new("."), name) |
| 72 | .ok() |
| 73 | .map(|_| name.to_owned()) |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | fn plan_set(manifest: &Manifest) -> Result<Vec<String>, String> { |
| 79 | let mut attachments = Vec::new(); |
| 80 | let mut has_db = false; |
| 81 | for file in &manifest.files { |
| 82 | if file.path == SET_DB { |
| 83 | has_db = true; |
| 84 | } else if let Some(id) = file |
| 85 | .path |
| 86 | .strip_prefix("attachments/") |
| 87 | .and_then(canonical_id) |
| 88 | { |
| 89 | attachments.push(id); |
| 90 | } else { |
| 91 | return Err(format!("the set lists an unexpected file: {}", file.path)); |
| 92 | } |
| 93 | } |
| 94 | if !has_db { |
| 95 | return Err(format!("the set has no {SET_DB}")); |
| 96 | } |
| 97 | Ok(attachments) |
| 98 | } |
| 99 | |
| 100 | |
| 101 | |
| 102 | fn database_target(config: &Config, data_dir: &Path) -> Result<PathBuf, String> { |
| 103 | let name = config.database.file_name().ok_or_else(|| { |
| 104 | format!( |
| 105 | "the database path has no file name: {}", |
| 106 | config.database.display() |
| 107 | ) |
| 108 | })?; |
| 109 | let parent = config |
| 110 | .database |
| 111 | .parent() |
| 112 | .filter(|p| !p.as_os_str().is_empty()) |
| 113 | .unwrap_or_else(|| Path::new(".")); |
| 114 | let parent = parent.canonicalize().map_err(|error| { |
| 115 | format!( |
| 116 | "the database directory {} cannot be used: {error}", |
| 117 | parent.display() |
| 118 | ) |
| 119 | })?; |
| 120 | if !parent.starts_with(data_dir) { |
| 121 | return Err(format!( |
| 122 | "the database {} is outside the data directory; restore refuses to replace it", |
| 123 | config.database.display() |
| 124 | )); |
| 125 | } |
| 126 | let target = parent.join(name); |
| 127 | if let Ok(meta) = std::fs::symlink_metadata(&target) |
| 128 | && !meta.file_type().is_file() |
| 129 | { |
| 130 | return Err(format!( |
| 131 | "the database {} is not a regular file", |
| 132 | target.display() |
| 133 | )); |
| 134 | } |
| 135 | Ok(target) |
| 136 | } |
| 137 | |
| 138 | |
| 139 | |
| 140 | fn copy_checked( |
| 141 | manifest: &Manifest, |
| 142 | relative: &str, |
| 143 | source: &Path, |
| 144 | dest: &Path, |
| 145 | ) -> Result<(), String> { |
| 146 | let expected = manifest |
| 147 | .files |
| 148 | .iter() |
| 149 | .find(|file| file.path == relative) |
| 150 | .ok_or_else(|| format!("the set does not list {relative}"))?; |
| 151 | std::fs::copy(source, dest).map_err(|error| format!("cannot copy {relative}: {error}"))?; |
| 152 | std::fs::set_permissions(dest, Permissions::from_mode(0o600)) |
| 153 | .map_err(|error| format!("cannot set the mode of {}: {error}", dest.display()))?; |
| 154 | let (size, digest) = manifest::digest_file(dest) |
| 155 | .map_err(|error| format!("cannot read the copy of {relative}: {}", describe(&error)))?; |
| 156 | if size != expected.size || digest != expected.sha256 { |
| 157 | return Err(format!("the set changed while it was copied: {relative}")); |
| 158 | } |
| 159 | Ok(()) |
| 160 | } |
| 161 | |
| 162 | |
| 163 | struct Staging { |
| 164 | dir: PathBuf, |
| 165 | } |
| 166 | |
| 167 | impl Staging { |
| 168 | |
| 169 | fn create(data_dir: &Path) -> Result<Staging, String> { |
| 170 | let dir = data_dir.join(format!("{STAGING_PREFIX}{}", new_id())); |
| 171 | DirBuilder::new() |
| 172 | .mode(0o700) |
| 173 | .create(&dir) |
| 174 | .map_err(|error| format!("cannot create {}: {error}", dir.display()))?; |
| 175 | Ok(Staging { dir }) |
| 176 | } |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | fn discard(&self) { |
| 182 | let _ = remove_regular_files(&self.dir); |
| 183 | let attachments = self.dir.join(ATTACHMENTS_DIR); |
| 184 | let _ = remove_regular_files(&attachments); |
| 185 | let _ = std::fs::remove_dir(&attachments); |
| 186 | let _ = std::fs::remove_dir(&self.dir); |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | |
| 191 | fn remove_regular_files(dir: &Path) -> std::io::Result<()> { |
| 192 | for entry in std::fs::read_dir(dir)? { |
| 193 | let entry = entry?; |
| 194 | if entry.file_type()?.is_file() { |
| 195 | std::fs::remove_file(entry.path())?; |
| 196 | } |
| 197 | } |
| 198 | Ok(()) |
| 199 | } |
| 200 | |
| 201 | |
| 202 | |
| 203 | async fn check_staged(staged_db: &Path) -> Result<(), String> { |
| 204 | { |
| 205 | let db = ReadOnly::open(staged_db) |
| 206 | .await |
| 207 | .map_err(|error| describe(&error))?; |
| 208 | let rows = db |
| 209 | .integrity_check() |
| 210 | .await |
| 211 | .map_err(|error| describe(&error))?; |
| 212 | if rows != ["ok"] { |
| 213 | return Err(format!( |
| 214 | "the set's database fails integrity_check: {}", |
| 215 | rows.join("; ") |
| 216 | )); |
| 217 | } |
| 218 | let versions = db |
| 219 | .migration_versions() |
| 220 | .await |
| 221 | .map_err(|error| describe(&error))?; |
| 222 | if let Some(problem) = migrations_problem(&versions) { |
| 223 | return Err(format!("the set's database is refused: {problem}")); |
| 224 | } |
| 225 | } |
| 226 | for suffix in ["-wal", "-shm"] { |
| 227 | let mut sidecar = staged_db.as_os_str().to_owned(); |
| 228 | sidecar.push(suffix); |
| 229 | let sidecar = PathBuf::from(sidecar); |
| 230 | match std::fs::symlink_metadata(&sidecar) { |
| 231 | Err(_) => {} |
| 232 | Ok(meta) if meta.len() == 0 => { |
| 233 | std::fs::remove_file(&sidecar) |
| 234 | .map_err(|error| format!("cannot remove {}: {error}", sidecar.display()))?; |
| 235 | } |
| 236 | Ok(meta) => { |
| 237 | return Err(format!( |
| 238 | "the staged database has {} bytes in {}", |
| 239 | meta.len(), |
| 240 | sidecar.display() |
| 241 | )); |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | Ok(()) |
| 246 | } |
| 247 | |
| 248 | |
| 249 | async fn restore( |
| 250 | config: &Config, |
| 251 | data_dir: &Path, |
| 252 | from: &Path, |
| 253 | key: &[u8; 32], |
| 254 | ) -> Result<String, String> { |
| 255 | let manifest = manifest::verify_set(from, key).map_err(|error| describe(&error))?; |
| 256 | let attachment_ids = plan_set(&manifest)?; |
| 257 | let db_target = database_target(config, data_dir)?; |
| 258 | let attachments_dir = data_dir.join(ATTACHMENTS_DIR); |
| 259 | if let Ok(meta) = std::fs::symlink_metadata(&attachments_dir) |
| 260 | && !meta.file_type().is_dir() |
| 261 | { |
| 262 | return Err(format!("{} is not a directory", attachments_dir.display())); |
| 263 | } |
| 264 | |
| 265 | |
| 266 | let staging = Staging::create(data_dir)?; |
| 267 | let staged = stage(&staging, from, &manifest, &attachment_ids).await; |
| 268 | if let Err(message) = staged { |
| 269 | staging.discard(); |
| 270 | return Err(message); |
| 271 | } |
| 272 | |
| 273 | let stamp = file_stamp(); |
| 274 | let result = swap_into_place(&staging.dir, &db_target, data_dir, &stamp); |
| 275 | match result { |
| 276 | Ok(moved) => { |
| 277 | if let Err(error) = std::fs::remove_dir(&staging.dir) { |
| 278 | eprintln!( |
| 279 | "iz: the staging directory {} could not be removed: {error}", |
| 280 | staging.dir.display() |
| 281 | ); |
| 282 | } |
| 283 | Ok(format!( |
| 284 | "restored from {}: {} attachments; previous files kept as {}", |
| 285 | from.display(), |
| 286 | attachment_ids.len(), |
| 287 | moved.join(", ") |
| 288 | )) |
| 289 | } |
| 290 | Err(message) => { |
| 291 | staging.discard(); |
| 292 | Err(message) |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | |
| 298 | |
| 299 | async fn stage( |
| 300 | staging: &Staging, |
| 301 | from: &Path, |
| 302 | manifest: &Manifest, |
| 303 | attachment_ids: &[String], |
| 304 | ) -> Result<(), String> { |
| 305 | let staged_db = staging.dir.join(SET_DB); |
| 306 | copy_checked(manifest, SET_DB, &from.join(SET_DB), &staged_db)?; |
| 307 | let staged_attachments = staging.dir.join(ATTACHMENTS_DIR); |
| 308 | DirBuilder::new() |
| 309 | .mode(0o700) |
| 310 | .create(&staged_attachments) |
| 311 | .map_err(|error| format!("cannot create {}: {error}", staged_attachments.display()))?; |
| 312 | for id in attachment_ids { |
| 313 | let relative = format!("{ATTACHMENTS_DIR}/{id}"); |
| 314 | copy_checked( |
| 315 | manifest, |
| 316 | &relative, |
| 317 | &from.join(ATTACHMENTS_DIR).join(id), |
| 318 | &staged_attachments.join(id), |
| 319 | )?; |
| 320 | } |
| 321 | check_staged(&staged_db).await |
| 322 | } |
| 323 | |
| 324 | |
| 325 | enum Move { |
| 326 | |
| 327 | Aside(PathBuf, PathBuf), |
| 328 | |
| 329 | Placed(PathBuf, PathBuf), |
| 330 | } |
| 331 | |
| 332 | |
| 333 | |
| 334 | fn swap_into_place( |
| 335 | staging: &Path, |
| 336 | db_target: &Path, |
| 337 | data_dir: &Path, |
| 338 | stamp: &str, |
| 339 | ) -> Result<Vec<String>, String> { |
| 340 | let attachments = data_dir.join(ATTACHMENTS_DIR); |
| 341 | let mut old: Vec<(PathBuf, PathBuf)> = Vec::new(); |
| 342 | for current in [ |
| 343 | db_target.to_path_buf(), |
| 344 | with_suffix(db_target, "-wal"), |
| 345 | with_suffix(db_target, "-shm"), |
| 346 | attachments.clone(), |
| 347 | ] { |
| 348 | if std::fs::symlink_metadata(¤t).is_ok() { |
| 349 | let aside = with_suffix(¤t, &format!(".{stamp}")); |
| 350 | if std::fs::symlink_metadata(&aside).is_ok() { |
| 351 | return Err(format!( |
| 352 | "{} already exists; nothing was changed", |
| 353 | aside.display() |
| 354 | )); |
| 355 | } |
| 356 | old.push((current, aside)); |
| 357 | } |
| 358 | } |
| 359 | let staged_db = staging.join(SET_DB); |
| 360 | let staged_attachments = staging.join(ATTACHMENTS_DIR); |
| 361 | |
| 362 | let mut done: Vec<Move> = Vec::new(); |
| 363 | let outcome = (|| -> std::io::Result<()> { |
| 364 | for (current, aside) in &old { |
| 365 | std::fs::rename(current, aside)?; |
| 366 | done.push(Move::Aside(current.clone(), aside.clone())); |
| 367 | } |
| 368 | std::fs::rename(&staged_db, db_target)?; |
| 369 | done.push(Move::Placed(staged_db.clone(), db_target.to_path_buf())); |
| 370 | std::fs::rename(&staged_attachments, &attachments)?; |
| 371 | done.push(Move::Placed( |
| 372 | staged_attachments.clone(), |
| 373 | attachments.clone(), |
| 374 | )); |
| 375 | std::fs::File::open(data_dir)?.sync_all() |
| 376 | })(); |
| 377 | |
| 378 | match outcome { |
| 379 | Ok(()) => Ok(old |
| 380 | .iter() |
| 381 | .map(|(_, aside)| aside.display().to_string()) |
| 382 | .collect()), |
| 383 | Err(error) => { |
| 384 | |
| 385 | let mut stuck = Vec::new(); |
| 386 | for step in done.into_iter().rev() { |
| 387 | |
| 388 | let undone = match &step { |
| 389 | Move::Aside(original, aside) => std::fs::rename(aside, original), |
| 390 | Move::Placed(staged, target) => std::fs::rename(target, staged), |
| 391 | }; |
| 392 | if let Err(undo_error) = undone { |
| 393 | stuck.push(undo_error.to_string()); |
| 394 | } |
| 395 | } |
| 396 | if stuck.is_empty() { |
| 397 | Err(format!("restore failed and was undone: {error}")) |
| 398 | } else { |
| 399 | Err(format!( |
| 400 | "restore failed: {error}; some moves could not be undone: {}", |
| 401 | stuck.join("; ") |
| 402 | )) |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | |
| 409 | fn with_suffix(path: &Path, suffix: &str) -> PathBuf { |
| 410 | let mut text = path.as_os_str().to_owned(); |
| 411 | text.push(suffix); |
| 412 | PathBuf::from(text) |
| 413 | } |
| 414 | |
| 415 | #[cfg(test)] |
| 416 | mod tests { |
| 417 | use super::*; |
| 418 | use iz_core::manifest::write_manifest; |
| 419 | |
| 420 | |
| 421 | |
| 422 | #[tokio::test] |
| 423 | async fn restore_refuses_a_tampered_set_and_changes_nothing() { |
| 424 | let root = tempfile::tempdir().expect("temp dir"); |
| 425 | let set = root.path().join("set"); |
| 426 | let data = root.path().join("data"); |
| 427 | std::fs::create_dir_all(&set).expect("set dir"); |
| 428 | std::fs::create_dir_all(&data).expect("data dir"); |
| 429 | let key = [5u8; 32]; |
| 430 | let db = data.join("iz.db"); |
| 431 | std::fs::write(&db, b"current database").expect("current db"); |
| 432 | std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db"); |
| 433 | write_manifest( |
| 434 | &set, |
| 435 | &key, |
| 436 | "2026-10-28T00:00:00.000000000Z", |
| 437 | "test", |
| 438 | &[SET_DB.to_owned()], |
| 439 | ) |
| 440 | .expect("manifest"); |
| 441 | |
| 442 | let mut bytes = std::fs::read(set.join(SET_DB)).expect("read"); |
| 443 | bytes[0] ^= 0x01; |
| 444 | std::fs::write(set.join(SET_DB), bytes).expect("tamper"); |
| 445 | |
| 446 | let config = Config::parse(&format!( |
| 447 | "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", |
| 448 | db.display(), |
| 449 | data.display(), |
| 450 | )) |
| 451 | .expect("config"); |
| 452 | let error = restore( |
| 453 | &config, |
| 454 | &data.canonicalize().expect("canonical"), |
| 455 | &set, |
| 456 | &key, |
| 457 | ) |
| 458 | .await |
| 459 | .expect_err("tampered set must be refused"); |
| 460 | assert!( |
| 461 | error.contains("changed since the set was written"), |
| 462 | "got: {error}" |
| 463 | ); |
| 464 | assert_eq!( |
| 465 | std::fs::read(&db).expect("db still there"), |
| 466 | b"current database" |
| 467 | ); |
| 468 | let entries: Vec<_> = std::fs::read_dir(&data) |
| 469 | .expect("list") |
| 470 | .map(|e| e.expect("entry").file_name()) |
| 471 | .collect(); |
| 472 | assert_eq!(entries.len(), 1, "only the database remains: {entries:?}"); |
| 473 | } |
| 474 | } |