| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | use std::fs::{self, File, OpenOptions}; |
| 16 | use std::io::Read as _; |
| 17 | use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; |
| 18 | use std::path::{Component, Path, PathBuf}; |
| 19 | |
| 20 | use serde::{Deserialize, Serialize}; |
| 21 | |
| 22 | use crate::config::Config; |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | #[derive(Serialize, Deserialize)] |
| 29 | struct Manifest { |
| 30 | version: u32, |
| 31 | packed_at: String, |
| 32 | services: Vec<PackedService>, |
| 33 | } |
| 34 | |
| 35 | #[derive(Serialize, Deserialize)] |
| 36 | struct PackedService { |
| 37 | key: String, |
| 38 | |
| 39 | |
| 40 | files: Vec<String>, |
| 41 | } |
| 42 | |
| 43 | const MANIFEST_NAME: &str = "manifest.json"; |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | pub async fn family_keys(config: &Config) -> Vec<String> { |
| 50 | let store = im_core::store::Store::open(&config.database) |
| 51 | .await |
| 52 | .expect("failed to open the database"); |
| 53 | let services = im_core::services::list(&store) |
| 54 | .await |
| 55 | .expect("failed to read the services table"); |
| 56 | drop(store); |
| 57 | |
| 58 | let mut keys = vec![im_core::services::SELF_OWNER.to_string()]; |
| 59 | for service in services { |
| 60 | if !keys.contains(&service.key) { |
| 61 | keys.push(service.key); |
| 62 | } |
| 63 | } |
| 64 | keys |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | pub async fn pack_command(config: &Config, root: Option<&str>, out: Option<&str>) { |
| 72 | let keys = family_keys(config).await; |
| 73 | let root = root.map(PathBuf::from).unwrap_or_else(default_root); |
| 74 | let out = out.map(PathBuf::from).unwrap_or_else(archive_name); |
| 75 | println!( |
| 76 | "im packing {} service tree(s) from {}", |
| 77 | keys.len(), |
| 78 | root.display() |
| 79 | ); |
| 80 | match pack(&root, &keys, &out) { |
| 81 | Ok(()) => println!("im packed {}", out.display()), |
| 82 | Err(problem) => { |
| 83 | eprintln!("im: {problem}"); |
| 84 | std::process::exit(1); |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | |
| 90 | |
| 91 | pub fn unpack_command(archive: &str, root: Option<&str>, force: bool) { |
| 92 | let root = root.map(PathBuf::from).unwrap_or_else(default_root); |
| 93 | println!("im restoring {archive} into {}", root.display()); |
| 94 | match unpack(Path::new(archive), &root, force) { |
| 95 | Ok(restored) => println!("im restored {restored} file(s)"), |
| 96 | Err(problem) => { |
| 97 | eprintln!("im: {problem}"); |
| 98 | std::process::exit(1); |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | pub fn pack(root: &Path, keys: &[String], out: &Path) -> Result<(), String> { |
| 108 | let mut packed = Vec::new(); |
| 109 | for key in keys { |
| 110 | let home = root.join(key); |
| 111 | if !home.is_dir() { |
| 112 | eprintln!("im {key}: no tree at {}, skipping", home.display()); |
| 113 | continue; |
| 114 | } |
| 115 | let mut files = Vec::new(); |
| 116 | |
| 117 | |
| 118 | for name in [ |
| 119 | format!("{key}.db"), |
| 120 | format!("{key}.db-wal"), |
| 121 | format!("{key}.db-shm"), |
| 122 | format!("{key}.key"), |
| 123 | ] { |
| 124 | if home.join(&name).is_file() { |
| 125 | files.push(format!("{key}/{name}")); |
| 126 | } else { |
| 127 | eprintln!("im {key}: {name} not present, skipped"); |
| 128 | } |
| 129 | } |
| 130 | for dir in ["config", "storage"] { |
| 131 | let tree = home.join(dir); |
| 132 | if !tree.exists() { |
| 133 | eprintln!("im {key}: {dir}/ not present, skipped"); |
| 134 | continue; |
| 135 | } |
| 136 | if !tree.is_dir() { |
| 137 | return Err(format!("{} is not a directory", tree.display())); |
| 138 | } |
| 139 | files.extend(walk(&tree, root)?); |
| 140 | } |
| 141 | if files.is_empty() { |
| 142 | eprintln!("im {key}: nothing to pack, skipped"); |
| 143 | continue; |
| 144 | } |
| 145 | files.sort(); |
| 146 | packed.push(PackedService { |
| 147 | key: key.clone(), |
| 148 | files, |
| 149 | }); |
| 150 | } |
| 151 | if packed.is_empty() { |
| 152 | return Err("nothing to pack: none of the family trees holds a file".into()); |
| 153 | } |
| 154 | |
| 155 | let manifest = Manifest { |
| 156 | version: 1, |
| 157 | packed_at: time::OffsetDateTime::now_utc() |
| 158 | .format(&time::format_description::well_known::Rfc3339) |
| 159 | .unwrap_or_else(|_| "unknown".into()), |
| 160 | services: packed, |
| 161 | }; |
| 162 | let manifest_body = serde_json::to_vec_pretty(&manifest) |
| 163 | .map_err(|e| format!("failed to write the manifest: {e}"))?; |
| 164 | |
| 165 | if let Some(parent) = out.parent() { |
| 166 | if !parent.as_os_str().is_empty() { |
| 167 | fs::create_dir_all(parent) |
| 168 | .map_err(|e| format!("failed to create {}: {e}", parent.display()))?; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | |
| 173 | let file = OpenOptions::new() |
| 174 | .create(true) |
| 175 | .truncate(true) |
| 176 | .write(true) |
| 177 | .mode(0o600) |
| 178 | .open(out) |
| 179 | .map_err(|e| format!("failed to create {}: {e}", out.display()))?; |
| 180 | let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( |
| 181 | file, |
| 182 | flate2::Compression::default(), |
| 183 | )); |
| 184 | let mut header = tar::Header::new_gnu(); |
| 185 | header.set_size(manifest_body.len() as u64); |
| 186 | header.set_mode(0o600); |
| 187 | header.set_cksum(); |
| 188 | tar.append_data(&mut header, MANIFEST_NAME, manifest_body.as_slice()) |
| 189 | .map_err(|e| format!("failed to add {MANIFEST_NAME}: {e}"))?; |
| 190 | for service in &manifest.services { |
| 191 | for relative in &service.files { |
| 192 | let path = root.join(relative); |
| 193 | tar.append_path_with_name(&path, relative) |
| 194 | .map_err(|e| format!("failed to add {relative}: {e}"))?; |
| 195 | } |
| 196 | } |
| 197 | tar.into_inner() |
| 198 | .map_err(|e| format!("failed to seal {PART}: {e}", PART = out.display()))? |
| 199 | .finish() |
| 200 | .map_err(|e| format!("failed to seal {}: {e}", out.display()))?; |
| 201 | Ok(()) |
| 202 | } |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | pub fn unpack(archive: &Path, root: &Path, force: bool) -> Result<usize, String> { |
| 209 | let manifest = read_manifest(archive)?; |
| 210 | if manifest.version != 1 { |
| 211 | return Err(format!( |
| 212 | "archive manifest version {} is not understood here", |
| 213 | manifest.version |
| 214 | )); |
| 215 | } |
| 216 | if !force { |
| 217 | let in_the_way: Vec<&str> = manifest |
| 218 | .services |
| 219 | .iter() |
| 220 | .filter(|service| { |
| 221 | root.join(&service.key) |
| 222 | .join(format!("{}.db", service.key)) |
| 223 | .is_file() |
| 224 | }) |
| 225 | .map(|service| service.key.as_str()) |
| 226 | .collect(); |
| 227 | if !in_the_way.is_empty() { |
| 228 | return Err(format!( |
| 229 | "refusing to overwrite an existing database for {} — pass --force to unpack over it", |
| 230 | in_the_way.join(", ") |
| 231 | )); |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | let file = File::open(archive).map_err(|e| format!("failed to open {}: {e}", archive.display()))?; |
| 236 | let mut restored = 0; |
| 237 | for entry in tar::Archive::new(flate2::read::GzDecoder::new(file)) |
| 238 | .entries() |
| 239 | .map_err(|e| format!("failed to read {}: {e}", archive.display()))? |
| 240 | { |
| 241 | let mut entry = |
| 242 | entry.map_err(|e| format!("{} is damaged: {e}", archive.display()))?; |
| 243 | let name = entry |
| 244 | .path() |
| 245 | .map_err(|e| format!("{} is damaged: {e}", archive.display()))? |
| 246 | .to_path_buf(); |
| 247 | let Some(relative) = safe_relative(&name) else { |
| 248 | return Err(format!( |
| 249 | "archive member {name:?} is not a safe relative path" |
| 250 | )); |
| 251 | }; |
| 252 | if relative == Path::new(MANIFEST_NAME) { |
| 253 | continue; |
| 254 | } |
| 255 | |
| 256 | |
| 257 | |
| 258 | if !entry.header().entry_type().is_file() { |
| 259 | return Err(format!("archive member {relative:?} is not a regular file")); |
| 260 | } |
| 261 | let destination = root.join(relative); |
| 262 | if let Some(parent) = destination.parent() { |
| 263 | fs::create_dir_all(parent) |
| 264 | .map_err(|e| format!("failed to create {}: {e}", parent.display()))?; |
| 265 | } |
| 266 | entry |
| 267 | .unpack(&destination) |
| 268 | .map_err(|e| format!("failed to restore {}: {e}", destination.display()))?; |
| 269 | if let Some(secret) = secret_mode(&destination) { |
| 270 | fs::set_permissions(&destination, fs::Permissions::from_mode(secret)) |
| 271 | .map_err(|e| format!("failed to tighten {}: {e}", destination.display()))?; |
| 272 | } |
| 273 | restored += 1; |
| 274 | } |
| 275 | Ok(restored) |
| 276 | } |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | fn walk(dir: &Path, root: &Path) -> Result<Vec<String>, String> { |
| 283 | let mut files = Vec::new(); |
| 284 | let mut stack = vec![dir.to_path_buf()]; |
| 285 | while let Some(current) = stack.pop() { |
| 286 | let entries = fs::read_dir(¤t) |
| 287 | .map_err(|e| format!("failed to read {}: {e}", current.display()))?; |
| 288 | for entry in entries { |
| 289 | let entry = entry |
| 290 | .map_err(|e| format!("failed to read {}: {e}", current.display()))?; |
| 291 | let path = entry.path(); |
| 292 | let kind = entry |
| 293 | .file_type() |
| 294 | .map_err(|e| format!("failed to read {}: {e}", path.display()))?; |
| 295 | if kind.is_dir() { |
| 296 | stack.push(path); |
| 297 | } else if kind.is_file() { |
| 298 | let relative = path |
| 299 | .strip_prefix(root) |
| 300 | .map_err(|e| format!("failed to name {}: {e}", path.display()))? |
| 301 | .to_string_lossy() |
| 302 | .into_owned(); |
| 303 | files.push(relative); |
| 304 | } else { |
| 305 | eprintln!("im skipping {}: not a regular file", path.display()); |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | Ok(files) |
| 310 | } |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | fn safe_relative(name: &Path) -> Option<&Path> { |
| 316 | if name.is_absolute() || name.as_os_str().is_empty() { |
| 317 | return None; |
| 318 | } |
| 319 | for component in name.components() { |
| 320 | match component { |
| 321 | Component::Normal(_) | Component::CurDir => {} |
| 322 | _ => return None, |
| 323 | } |
| 324 | } |
| 325 | Some(name) |
| 326 | } |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | fn secret_mode(path: &Path) -> Option<u32> { |
| 332 | let shown = path.to_string_lossy(); |
| 333 | if shown.ends_with(".toml") || shown.ends_with(".keys") || shown.ends_with(".key") { |
| 334 | Some(0o600) |
| 335 | } else { |
| 336 | None |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | |
| 341 | |
| 342 | fn read_manifest(archive: &Path) -> Result<Manifest, String> { |
| 343 | let file = |
| 344 | File::open(archive).map_err(|e| format!("failed to open {}: {e}", archive.display()))?; |
| 345 | for entry in tar::Archive::new(flate2::read::GzDecoder::new(file)) |
| 346 | .entries() |
| 347 | .map_err(|e| format!("failed to read {}: {e}", archive.display()))? |
| 348 | { |
| 349 | let mut entry = |
| 350 | entry.map_err(|e| format!("{} is damaged: {e}", archive.display()))?; |
| 351 | let is_manifest = entry |
| 352 | .path() |
| 353 | .map_err(|e| format!("{} is damaged: {e}", archive.display()))? |
| 354 | == Path::new(MANIFEST_NAME); |
| 355 | if is_manifest { |
| 356 | let mut body = String::new(); |
| 357 | entry |
| 358 | .read_to_string(&mut body) |
| 359 | .map_err(|e| format!("failed to read {MANIFEST_NAME}: {e}"))?; |
| 360 | return serde_json::from_str(&body) |
| 361 | .map_err(|e| format!("{}'s manifest does not parse: {e}", archive.display())); |
| 362 | } |
| 363 | } |
| 364 | Err(format!("{} carries no {MANIFEST_NAME}", archive.display())) |
| 365 | } |
| 366 | |
| 367 | |
| 368 | |
| 369 | fn default_root() -> PathBuf { |
| 370 | let cwd = match std::env::current_dir() { |
| 371 | Ok(cwd) => cwd, |
| 372 | Err(e) => { |
| 373 | eprintln!("im: cannot read the working directory: {e}"); |
| 374 | std::process::exit(2); |
| 375 | } |
| 376 | }; |
| 377 | match cwd.parent() { |
| 378 | Some(parent) => parent.to_path_buf(), |
| 379 | None => { |
| 380 | eprintln!("im: no family root above {}", cwd.display()); |
| 381 | eprintln!("usage: pass --root DIR"); |
| 382 | std::process::exit(2); |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | |
| 388 | fn archive_name() -> PathBuf { |
| 389 | const STAMP: &[time::format_description::BorrowedFormatItem<'static>] = |
| 390 | time::macros::format_description!( |
| 391 | "im-pack-[year][month][day]-[hour][minute][second].tar.gz" |
| 392 | ); |
| 393 | PathBuf::from( |
| 394 | time::OffsetDateTime::now_utc() |
| 395 | .format(STAMP) |
| 396 | .unwrap_or_else(|_| "im-pack.tar.gz".into()), |
| 397 | ) |
| 398 | } |
| 399 | |
| 400 | #[cfg(test)] |
| 401 | mod tests { |
| 402 | use super::*; |
| 403 | |
| 404 | |
| 405 | struct TempDir(PathBuf); |
| 406 | |
| 407 | impl TempDir { |
| 408 | fn new(label: &str) -> TempDir { |
| 409 | let path = std::env::temp_dir() |
| 410 | .join(format!("im-pack-{label}-{}", ulid::Ulid::generate())); |
| 411 | fs::create_dir_all(&path).unwrap(); |
| 412 | TempDir(path) |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | impl Drop for TempDir { |
| 417 | fn drop(&mut self) { |
| 418 | let _ = fs::remove_dir_all(&self.0); |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | fn write(path: &Path, bytes: &[u8]) { |
| 423 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 424 | fs::write(path, bytes).unwrap(); |
| 425 | } |
| 426 | |
| 427 | fn mode_of(path: &Path) -> u32 { |
| 428 | fs::metadata(path).unwrap().permissions().mode() & 0o777 |
| 429 | } |
| 430 | |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | |
| 436 | #[test] |
| 437 | fn roundtrip_im_and_xy() { |
| 438 | let source = TempDir::new("src"); |
| 439 | |
| 440 | write(&source.0.join("im/im.db"), b"im-db"); |
| 441 | write(&source.0.join("im/im.db-wal"), b"im-wal"); |
| 442 | write(&source.0.join("im/im.db-shm"), b"im-shm"); |
| 443 | write(&source.0.join("im/im.key"), b"im-key"); |
| 444 | write(&source.0.join("im/config/im.toml"), b"listen = \"127.0.0.1:7650\"\n"); |
| 445 | write(&source.0.join("im/storage/a/blob"), b"im-blob"); |
| 446 | |
| 447 | |
| 448 | write(&source.0.join("xy/xy.db"), b"xy-db"); |
| 449 | write(&source.0.join("xy/config/xy.toml"), b"listen = \"127.0.0.1:8000\"\n"); |
| 450 | |
| 451 | let keys = ["im".to_string(), "xy".to_string(), "zz".to_string()]; |
| 452 | let out = source.0.join("pack.tar.gz"); |
| 453 | pack(&source.0, &keys, &out).expect("pack succeeds"); |
| 454 | assert!(out.is_file()); |
| 455 | assert_eq!(mode_of(&out), 0o600, "the archive lands 0600"); |
| 456 | |
| 457 | let destination = TempDir::new("dest"); |
| 458 | unpack(&out, &destination.0, false).expect("unpack into an empty root"); |
| 459 | for (relative, bytes) in [ |
| 460 | ("im/im.db", &b"im-db"[..]), |
| 461 | ("im/im.db-wal", b"im-wal"), |
| 462 | ("im/im.db-shm", b"im-shm"), |
| 463 | ("im/im.key", b"im-key"), |
| 464 | ("im/config/im.toml", b"listen = \"127.0.0.1:7650\"\n"), |
| 465 | ("im/storage/a/blob", b"im-blob"), |
| 466 | ("xy/xy.db", b"xy-db"), |
| 467 | ("xy/config/xy.toml", b"listen = \"127.0.0.1:8000\"\n"), |
| 468 | ] { |
| 469 | assert_eq!( |
| 470 | fs::read(destination.0.join(relative)).unwrap(), |
| 471 | bytes, |
| 472 | "{relative} must roundtrip" |
| 473 | ); |
| 474 | } |
| 475 | for secret in ["im/im.key", "im/config/im.toml", "xy/config/xy.toml"] { |
| 476 | assert_eq!( |
| 477 | mode_of(&destination.0.join(secret)), |
| 478 | 0o600, |
| 479 | "{secret} must land 0600" |
| 480 | ); |
| 481 | } |
| 482 | |
| 483 | |
| 484 | |
| 485 | let problem = unpack(&out, &destination.0, false) |
| 486 | .expect_err("an existing database must refuse the unpack"); |
| 487 | assert!(problem.contains("--force"), "the refusal names the way out: {problem}"); |
| 488 | assert_eq!( |
| 489 | fs::read(destination.0.join("im/im.db")).unwrap(), |
| 490 | b"im-db", |
| 491 | "the refused unpack left the tree alone" |
| 492 | ); |
| 493 | unpack(&out, &destination.0, true).expect("--force unpacks over it"); |
| 494 | assert_eq!(fs::read(destination.0.join("im/im.db")).unwrap(), b"im-db"); |
| 495 | } |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | |
| 501 | #[test] |
| 502 | fn unpack_refuses_escaping_names() { |
| 503 | use std::io::Write as _; |
| 504 | |
| 505 | let source = TempDir::new("evil-src"); |
| 506 | let archive = source.0.join("evil.tar.gz"); |
| 507 | |
| 508 | let mut tar = Vec::new(); |
| 509 | raw_member( |
| 510 | &mut tar, |
| 511 | MANIFEST_NAME, |
| 512 | br#"{"version":1,"packed_at":"now","services":[{"key":"xy","files":[]}]}"#, |
| 513 | ); |
| 514 | raw_member(&mut tar, "../escape", b"gotcha"); |
| 515 | tar.extend_from_slice(&[0u8; 1024]); |
| 516 | let mut gz = flate2::write::GzEncoder::new( |
| 517 | File::create(&archive).unwrap(), |
| 518 | flate2::Compression::default(), |
| 519 | ); |
| 520 | gz.write_all(&tar).unwrap(); |
| 521 | gz.finish().unwrap(); |
| 522 | |
| 523 | let destination = TempDir::new("evil-dest"); |
| 524 | let problem = unpack(&archive, &destination.0, false) |
| 525 | .expect_err("an escaping member must refuse the unpack"); |
| 526 | assert!(problem.contains("safe relative"), "{problem}"); |
| 527 | assert!( |
| 528 | !destination.0.parent().unwrap().join("escape").exists(), |
| 529 | "nothing may land outside the root" |
| 530 | ); |
| 531 | } |
| 532 | |
| 533 | |
| 534 | |
| 535 | fn raw_member(tar: &mut Vec<u8>, name: &str, body: &[u8]) { |
| 536 | let mut header = [0u8; 512]; |
| 537 | header[..name.len()].copy_from_slice(name.as_bytes()); |
| 538 | header[124..136].copy_from_slice(format!("{:011o}\0", body.len()).as_bytes()); |
| 539 | header[136..148].copy_from_slice(b"00000000000\0"); |
| 540 | header[148..156].copy_from_slice(b" "); |
| 541 | header[156] = b'0'; |
| 542 | header[257..263].copy_from_slice(b"ustar\0"); |
| 543 | header[263..265].copy_from_slice(b"00"); |
| 544 | let sum: u32 = header.iter().map(|byte| u32::from(*byte)).sum(); |
| 545 | header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); |
| 546 | tar.extend_from_slice(&header); |
| 547 | tar.extend_from_slice(body); |
| 548 | tar.extend(std::iter::repeat_n(0u8, (512 - body.len() % 512) % 512)); |
| 549 | } |
| 550 | |
| 551 | |
| 552 | |
| 553 | #[test] |
| 554 | fn unpack_refuses_a_future_manifest() { |
| 555 | let source = TempDir::new("future-src"); |
| 556 | let archive = source.0.join("future.tar.gz"); |
| 557 | let file = File::create(&archive).unwrap(); |
| 558 | let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( |
| 559 | file, |
| 560 | flate2::Compression::default(), |
| 561 | )); |
| 562 | let manifest = br#"{"version":99,"packed_at":"tomorrow","services":[]}"#; |
| 563 | let mut header = tar::Header::new_gnu(); |
| 564 | header.set_size(manifest.len() as u64); |
| 565 | header.set_cksum(); |
| 566 | tar.append_data(&mut header, MANIFEST_NAME, &manifest[..]).unwrap(); |
| 567 | tar.into_inner().unwrap().finish().unwrap(); |
| 568 | |
| 569 | let destination = TempDir::new("future-dest"); |
| 570 | let problem = unpack(&archive, &destination.0, false) |
| 571 | .expect_err("an unknown manifest version must refuse"); |
| 572 | assert!(problem.contains("version"), "{problem}"); |
| 573 | } |
| 574 | } |