diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/pipeline/publish.rs | 147 | ||||
| -rw-r--r-- | src/shims/mod.rs | 41 |
2 files changed, 154 insertions, 34 deletions
diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs index fd2fdd1..f8efeff 100644 --- a/src/pipeline/publish.rs +++ b/src/pipeline/publish.rs @@ -2,9 +2,9 @@ //! //! Publishing is the only externally visible step, and it is atomic and //! serialized per repo (I4). The served database is a materialized view of the -//! DB: we render it to `.tmp`, fsync, commit the DB, then `rename` over the real -//! one. A crash anywhere in there leaves the *old* index intact, and -//! [`reconcile`] re-materializes from the DB on startup. +//! DB: we render it in scratch space beside the live file, fsync, commit the DB, +//! then `rename` over the real one. A crash anywhere in there leaves the *old* +//! index intact, and [`reconcile`] re-materializes from the DB on startup. use std::collections::BTreeSet; use std::path::{Path, PathBuf}; @@ -20,8 +20,8 @@ use crate::time; /// One writer to the served repo at a time. /// /// This is *the* serialization guarantee for the index (§8.2, §9, I4): a publish -/// renders a new pacman database to `.tmp`, commits the DB, then renames over -/// the live one, and a second writer interleaving anywhere in that sequence +/// renders a new pacman database in scratch space, commits the DB, then renames +/// over the live one, and a second writer interleaving anywhere in that sequence /// would produce an index that matches neither DB state. It is held by /// [`publish`] for the whole of it — staging, render, DB commit, rename, sign — /// and by [`withdraw_package`] for the same reason. With @@ -61,7 +61,7 @@ pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> { } /// Package files that belong in the served index right now, plus the extra ones -/// being published (which are not in the DB yet when we render `.tmp`). +/// being published (which are not in the DB yet when the new index is rendered). fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> { let mut out: Vec<PathBuf> = Vec::new(); for p in db::index_packages(db)? { @@ -91,6 +91,9 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { // Artifacts are copied into the served tree under their real filenames. let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new(); + // Set once the render starts, so the failure path below can sweep the scratch + // directory even when the publish died after repo-add returned. + let mut scratch_dir: Option<PathBuf> = None; // Files this publish created that were not there before. If the publish does // not land, they are orphans: no index names them and no consumer will ever // ask for them (§6 m-16). A file that already existed belongs to the release @@ -119,17 +122,16 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { } let outcome = (|| -> Result<i64> { - // 1. render the new database to .tmp and fsync it. The old one is untouched. + // 1. render the new database and fsync it. The live one is untouched + // until step 3's rename. let db_name = ctx.cfg.repo_db_name(); let final_db = arch_dir.join(format!("{db_name}.tar.gz")); - let tmp_db = arch_dir.join(format!("{db_name}.tar.gz.tmp")); let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?; // Deduplicate: the same package name must appear once, newest wins. pkgs = dedupe_by_name(pkgs); - run_repo_add(&ctx.cfg, &tmp_db, &pkgs)?; - fsync_file(&tmp_db)?; + let rendered = render_db(&ctx.cfg, &arch_dir, "publish", &pkgs, &mut scratch_dir)?; - // Fault injection so I4 can be tested for real: die between the tmp write + // Fault injection so I4 can be tested for real: die between the render // and the rename, and the old index must still be what consumers get. // Compiled out of a production build (§6 M-9). #[cfg(feature = "test-support")] @@ -141,15 +143,9 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { // transaction, with the pointer moved by compare-and-swap. let release_id = commit_release(ctx, &collect)?; - // 3. atomic swap: rename over the real database, then sign and swap the sig. - std::fs::rename(&tmp_db, &final_db)?; - fsync_dir(&arch_dir)?; + // 3. atomic swap: rename over the real database, then sign the new bytes. + rendered.swap_into(&final_db)?; sign(&ctx.cfg, &final_db)?; - let sig = arch_dir.join(format!("{db_name}.tar.gz.sig")); - let tmp_sig = arch_dir.join(format!("{db_name}.tar.gz.sig.tmp")); - if tmp_sig.exists() { - std::fs::rename(&tmp_sig, &sig)?; - } // 4. a publish can unblock builds waiting on a dependency we just added. let unblocked = builds::requeue_blocked(&ctx.db)?; @@ -178,6 +174,9 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { for p in &fresh { let _ = std::fs::remove_file(p); } + if let Some(s) = &scratch_dir { + let _ = std::fs::remove_dir_all(s); + } } outcome } @@ -281,14 +280,93 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { }) } -/// `repo-add -s -p <key> -R <db> <pkgs...>` (§9: both packages and the database -/// are signed so consumers can run `SigLevel = Required`). +/// Remove scratch directories a crash left behind. [`render_db`] cleans up after +/// itself on every path it controls; these are the ones it did not get to, and +/// they are unambiguous — the leading dot means nothing a consumer asks for, and +/// only a render creates one. +pub fn sweep_render_dirs(arch_dir: &Path) { + let Ok(entries) = std::fs::read_dir(arch_dir) else { + return; + }; + for entry in entries.flatten() { + if entry.file_name().to_string_lossy().starts_with(".render-") { + let _ = std::fs::remove_dir_all(entry.path()); + } + } +} + +/// A database repo-add has rendered, and the scratch directory it rendered into. +struct Rendered { + db: PathBuf, + dir: PathBuf, + arch_dir: PathBuf, +} + +impl Rendered { + /// The publish point: rename the rendered database over the live one, fsync + /// the directory entry, then drop the scratch directory. Before the rename a + /// consumer still gets the old index; after it, the new one. + fn swap_into(self, final_db: &Path) -> Result<()> { + std::fs::rename(&self.db, final_db)?; + fsync_dir(&self.arch_dir)?; + let _ = std::fs::remove_dir_all(&self.dir); + Ok(()) + } +} + +/// Render a fresh database with repo-add, ready to be renamed into place. +/// +/// repo-add refuses any database argument that is not a name pacman itself would +/// accept (`<repo>.db.tar.gz` and friends) — a `.tmp` suffix is a usage error to +/// it, not a convention. So the render cannot happen at `<db>.tar.gz.tmp` beside +/// the live file, which is what this code used to do: every publish of a real +/// package failed the moment it met a real repo-add, while 200+ tests stayed +/// green because the shim accepted any filename. It renders instead into a +/// scratch directory *under* the served directory, under the exact name a +/// consumer will download. Same filesystem, so the caller's `rename` is still the +/// atomic swap I4 requires, and the live database is never the file repo-add is +/// writing into. +/// +/// `scratch` is filled in as soon as the directory exists, so the caller can +/// sweep it even if this function is never reached again. +fn render_db( + cfg: &Config, + arch_dir: &Path, + tag: &str, + pkgs: &[PathBuf], + scratch: &mut Option<PathBuf>, +) -> Result<Rendered> { + static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = arch_dir.join(format!(".render-{}-{n}-{tag}", std::process::id())); + std::fs::create_dir_all(&dir)?; + *scratch = Some(dir.clone()); + let db = dir.join(format!("{}.tar.gz", cfg.repo_db_name())); + let rendered = Rendered { db, dir, arch_dir: arch_dir.to_path_buf() }; + // Anything that can still fail lives here, so the scratch directory does not + // outlive the attempt on the error path. + let attempt = (|| -> Result<()> { + run_repo_add(cfg, &rendered.db, pkgs)?; + fsync_file(&rendered.db)?; + Ok(()) + })(); + if let Err(e) = attempt { + let _ = std::fs::remove_dir_all(&rendered.dir); + *scratch = None; + return Err(e); + } + Ok(rendered) +} + +/// `repo-add -R <db> <pkgs...>`. +/// +/// Deliberately *not* `-s`: repo-add would sign the database into whatever +/// directory it was rendered in, which is scratch space that gets deleted, and +/// the hub signs the live file itself in [`sign`] — one key, one code path, and +/// the signature is always over the bytes that were renamed into place (§9). fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> { let mut cmd = Command::new(&cfg.repo_add_bin); cmd.arg("-R"); - if !cfg.signing_key_id.is_empty() { - cmd.args(["-s", "-p", &cfg.signing_key_id]); - } cmd.arg(db_path); for p in pkgs { cmd.arg(p); @@ -338,10 +416,10 @@ pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> { Ok(()) } -/// fsync, and *say so* when it fails (m-7). The whole point of writing to -/// `.tmp`, fsyncing, and renaming is the promise that a consumer never sees a -/// half-written database; swallowing the error made that a comment rather than -/// a guarantee — on a filesystem that refuses `fsync` (full, read-only, a +/// fsync, and *say so* when it fails (m-7). The whole point of writing to a +/// scratch file, fsyncing, and renaming is the promise that a consumer never +/// sees a half-written database; swallowing the error made that a comment rather +/// than a guarantee — on a filesystem that refuses `fsync` (full, read-only, a /// network mount that dropped), the rename still "succeeded". fn fsync_file(p: &Path) -> Result<()> { let f = std::fs::File::open(p) @@ -419,9 +497,10 @@ pub fn reconcile(cfg: &Config, db: &Db) -> Result<usize> { return Ok(0); } let arch_dir = cfg.repo_arch_dir(); - let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); - run_repo_add(cfg, &tmp, &dedupe_by_name(files.clone()))?; - std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + sweep_render_dirs(&arch_dir); + let mut scratch = None; + let rendered = render_db(cfg, &arch_dir, "reconcile", &dedupe_by_name(files.clone()), &mut scratch)?; + rendered.swap_into(&arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; Ok(files.len()) } @@ -432,10 +511,10 @@ pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> { let n = name.to_string(); db.writer.tx(move |tx| db::remove_package_by_name_in(tx, rid, &n))?; let arch_dir = cfg.repo_arch_dir(); - let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); + let mut scratch = None; let files = index_artifacts(db, &[])?; - run_repo_add(cfg, &tmp, &dedupe_by_name(files))?; - std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + let rendered = render_db(cfg, &arch_dir, "withdraw", &dedupe_by_name(files), &mut scratch)?; + rendered.swap_into(&arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; db::audit(&db.writer, "human", "cli", "withdraw.publish", "package", name, serde_json::json!({}))?; Ok(()) } diff --git a/src/shims/mod.rs b/src/shims/mod.rs index d0c253d..7118283 100644 --- a/src/shims/mod.rs +++ b/src/shims/mod.rs @@ -562,6 +562,38 @@ fn installed_db() -> Option<std::path::PathBuf> { /// The real tool appends; `-R` replaces an existing entry. We rebuild the whole /// db from the packages given, which is what our publish step does anyway (it /// passes exactly the packages that belong in the index). +/// The database filenames pacman's repo-add accepts — and therefore the ones +/// this shim must accept, and no others. +/// +/// A shim that is more permissive than the tool it stands in for is worse than no +/// shim: the pipeline used to render its database to `<db>.tar.gz.tmp` and rename +/// it into place, real repo-add rejects that filename as a usage error, and every +/// publish test in the suite passed because the shim would write anywhere. That +/// is how the first real package anyone tried to publish died at the last step. +/// This list is the accepted set as measured against `repo-add (pacman) 7.1.0`: +/// the `.db.tar` forms with or without a compression suffix, and nothing else — +/// not `aur.db`, not `aur.db.gz`, and not the `.files.*` forms, which belong to +/// `repo-files`. +pub const DB_SUFFIXES: [&str; 5] = [ + ".db.tar", + ".db.tar.gz", + ".db.tar.zst", + ".db.tar.bz2", + ".db.tar.xz", +]; + +/// Whether repo-add would accept this path as its database argument. +pub fn valid_db_arg(p: &Path) -> bool { + let name = p + .file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + !name.is_empty() + && DB_SUFFIXES + .iter() + .any(|sfx| name.ends_with(sfx)) +} + pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { // `-p <key>` and friends take a value; a naive filter would treat the key id // as a package path. @@ -584,6 +616,15 @@ pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { Some((db, rest)) => (PathBuf::from(db), rest.iter().map(|p| PathBuf::from(p.as_str())).collect::<Vec<_>>()), None => return Err("repo-add: no database given".into()), }; + if !valid_db_arg(&db_path) { + // Same wording and same exit status as the real tool, so a caller that + // learns to branch on one learns to branch on the other. + eprintln!( + "==> ERROR: '{}' does not have a valid database archive extension.", + db_path.display() + ); + return Ok(1); + } let mut ar = tar::Builder::new(Vec::new()); for pkg in &pkgs { let bytes = std::fs::read(pkg).map_err(|e| format!("repo-add: {}: {e}", pkg.display()))?; |
