//! Toolchain shims (§16a). //! //! The pipeline shells out to `mkarchroot`, `makechrootpkg`, `makepkg`, //! `repo-add`, `gpg` and `pacman`. In test mode the harness prepends a directory //! of fakes to `PATH`; each fake records its invocation, obeys a scripted //! outcome from the fixture manifest, and emits plausible //! `.PKGINFO`/`.BUILDINFO`/`.sig` output. //! //! That is what makes the full step machine, checkpointing, lease/reaper //! recovery, publishing and index regeneration runnable in milliseconds on any //! machine — no Arch host, no root, no network. //! //! Protocol, all via environment so the pipeline needs no test-only code paths: //! //! | var | meaning | //! |---|---| //! | `AUR_SHIM_DIR` | where invocations are recorded (`invocations.jsonl`) | //! | `AUR_SHIM_MANIFEST` | fixture manifest describing the scripted outcome | //! | `AUR_SHIM_FAIL` | optional step name that must fail, e.g. `build` | use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use crate::hash; /// One package the fake toolchain emits. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct FakePackage { pub name: String, pub version: String, pub arch: String, pub desc: String, pub url: String, pub license: Vec, pub depends: Vec, pub makedepends: Vec, pub checkdepends: Vec, pub provides: Vec, pub conflicts: Vec, pub backup: Vec, } impl Default for FakePackage { fn default() -> Self { Self { name: String::new(), version: "1.0-1".into(), arch: "x86_64".into(), desc: "fake package".into(), url: String::new(), license: vec!["MIT".into()], depends: vec![], makedepends: vec![], checkdepends: vec![], provides: vec![], conflicts: vec![], backup: vec![], } } } impl FakePackage { /// `1.0-1` split into the `(pkgver, pkgrel)` pacman expects in `.PKGINFO`. pub fn split_version(&self) -> (String, String) { match self.version.rsplit_once('-') { Some((v, r)) => (v.to_string(), r.to_string()), None => (self.version.clone(), "1".into()), } } } /// A member of the fake chroot world, for `.BUILDINFO` (§10.1). #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] pub struct FakeInstalled { pub name: String, pub version: String, pub arch: String, } /// The scripted outcome of a fixture. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct Manifest { pub name: String, /// `succeed` | `fail` | `check-fail` | `no-pkgver` pub build: String, /// Text the fake build writes to its log, for log-tail tests. pub log_lines: Vec, pub packages: Vec, pub installed: Vec, /// Emit `.sig` files (default true). pub sig: bool, /// `pkgver` the fake `makepkg --vercheck` computes (VCS fixtures, §5.2). pub vercheck: Option, /// Extra files to drop into the package tarball. pub files: Vec, } impl Default for Manifest { fn default() -> Self { Self { name: "fixture".into(), build: "succeed".into(), log_lines: vec!["==> Making package.".into()], packages: vec![], installed: vec![], sig: true, vercheck: None, files: vec![], } } } pub fn manifest() -> Manifest { match std::env::var("AUR_SHIM_MANIFEST") { Ok(p) => match std::fs::read_to_string(&p) { Ok(s) => serde_json::from_str(&s).unwrap_or_default(), Err(_) => Manifest::default(), }, Err(_) => Manifest::default(), } } /// Record that a shim ran, so tests can assert on what the pipeline actually /// invoked rather than what it intended to invoke. pub fn record(tool: &str, args: &[String]) { let dir = match std::env::var("AUR_SHIM_DIR") { Ok(d) => d, Err(_) => return, }; let _ = std::fs::create_dir_all(&dir); let entry = serde_json::json!({ "tool": tool, "args": args, "cwd": std::env::current_dir().map(|p| p.display().to_string()).unwrap_or_default(), }); if let Ok(mut f) = std::fs::OpenOptions::new() .create(true) .append(true) .open(Path::new(&dir).join("invocations.jsonl")) { use std::io::Write; let _ = f.write_all(format!("{entry}\n").as_bytes()); } } /// Test hook: kill the process that invoked us, mid-step, with a signal it /// cannot catch. This is how the crash-resume invariant (I5) is tested for real: /// the pipeline process dies while a step is running, with no chance to clean /// up, and the next process must pick up from the checkpoints. fn kill_parent_if_asked(tool: &str) { let want = std::env::var("AUR_SHIM_KILL_PARENT").unwrap_or_default(); if want == tool { // Flush the invocation log first (record() already closed the file), // then murder the parent. No cleanup, no unwinding, no atexit. unsafe { libc::kill(libc::getppid(), libc::SIGKILL); } // If the kill somehow did not land, do not let the step complete — that // would make the test silently test nothing. std::process::exit(137); } } /// True when the harness asked this tool to fail. fn forced_fail(tool: &str) -> bool { std::env::var("AUR_SHIM_FAIL").map(|v| v == tool).unwrap_or(false) } /// Read the invocation log back (test side). pub fn invocations(dir: &Path) -> Vec { let path = dir.join("invocations.jsonl"); match std::fs::read_to_string(path) { Ok(s) => s .lines() .filter_map(|l| serde_json::from_str(l).ok()) .collect(), Err(_) => Vec::new(), } } /// Entries whose `args` mention `needle`. pub fn called_with(dir: &Path, tool: &str, needle: &str) -> usize { invocations(dir) .iter() .filter(|e| e["tool"] == tool) .filter(|e| { e["args"] .as_array() .map(|a| a.iter().any(|v| v.as_str().is_some_and(|s| s.contains(needle)))) .unwrap_or(false) }) .count() } /// Dispatch table used by every `src/bin/*.rs`. pub fn run(tool: &str) -> i32 { let args: Vec = std::env::args().skip(1).collect(); record(tool, &args); kill_parent_if_asked(tool); let m = manifest(); let r = match tool { "mkarchroot" => mkarchroot(&args), "makechrootpkg" => makechrootpkg(&args, &m), "makepkg" => makepkg(&args, &m), "repo-add" => repo_add(&args, &m), "gpg" => gpg(&args), "pacman" => Ok(0), other => Err(format!("no shim named {other}")), }; match r { Ok(code) => code, Err(e) => { eprintln!("shim {tool}: {e}"); 1 } } } /// `mkarchroot `: create a directory that stands in for a warm root. pub fn mkarchroot(args: &[String]) -> Result { // `mkarchroot [-C pacman.conf] [-M makepkg.conf] `: the config options // take a value, so they cannot be skipped blindly. let mut target = None; let mut skip = false; for a in args { if skip { skip = false; continue; } if matches!(a.as_str(), "-C" | "-M" | "-k") { skip = true; continue; } if !a.starts_with('-') { target = Some(a.clone()); break; } } let target = target.ok_or("mkarchroot: no target")?; std::fs::create_dir_all(&target).map_err(|e| e.to_string())?; // A marker so the pipeline can tell a real root from a fake one. let _ = std::fs::write(Path::new(&target).join("SHIM-ROOT"), "fake chroot\n"); Ok(0) } /// `makechrootpkg -c -r -- -si -f`, run with cwd = the build dir. /// /// Emits one `.pkg.tar.zst` per package in the manifest into the current /// directory, exactly where the real tool leaves them. pub fn makechrootpkg(args: &[String], m: &Manifest) -> Result { for l in &m.log_lines { println!("{l}"); } if forced_fail("makechrootpkg") || m.build == "fail" { eprintln!("==> ERROR: A build function returned error."); return Ok(1); } if m.build == "check-fail" { eprintln!("==> ERROR: A failure occurred in check()."); return Ok(1); } // The pipeline always passes a chroot root; asserting it keeps the fake // honest about the real tool's contract. if !args.iter().any(|a| a == "-r") { return Err("makechrootpkg: expected -r ".into()); } let startdir = std::env::current_dir().map_err(|e| e.to_string())?; // The real tool reads the PKGBUILD it was handed; we assert it is there so a // broken materialize step cannot pass silently. if !startdir.join("PKGBUILD").exists() { let found = std::fs::read_dir(&startdir) .map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().into_owned()).collect::>()) .unwrap_or_default(); return Err(format!( "makechrootpkg: no PKGBUILD in {} (contains {found:?})", startdir.display() )); } let pkgs = packages_to_emit(m, &startdir); for p in &pkgs { let path = write_package(&startdir, p, m)?; println!("==> Creating package '{}'", path.file_name().unwrap().to_string_lossy()); if m.sig { if let Ok(bytes) = std::fs::read(&path) { let sig = path.with_extension("pkg.tar.zst.sig"); let _ = std::fs::write(&sig, fake_sig(&bytes)); } } } plant_link_if_asked(&startdir); Ok(0) } /// I9 test hook: drop a symlink into the srcdir pointing wherever the test names, /// standing in for a PKGBUILD that tries to smuggle outside bytes into the /// artifact store. The pipeline must refuse it; see `collect` in steps.rs. fn plant_link_if_asked(startdir: &Path) { let target = match std::env::var("AUR_SHIM_PLANT_LINK") { Ok(t) if !t.is_empty() => t, _ => return, }; let link = startdir.join("planted.pkg.tar.zst"); #[cfg(unix)] { let _ = std::fs::remove_file(&link); if let Err(e) = std::os::unix::fs::symlink(&target, &link) { eprintln!("shim: could not plant {link:?} -> {target}: {e}"); } } } fn packages_to_emit(m: &Manifest, startdir: &Path) -> Vec { if !m.packages.is_empty() { return m.packages.clone(); } // No explicit manifest: derive one package from the PKGBUILD we were given. let text = std::fs::read_to_string(startdir.join("PKGBUILD")).unwrap_or_default(); let recipe = crate::recipe::parse_pkgbuild(&text).ok(); match recipe { Some(r) => r .pkgnames .iter() .map(|n| FakePackage { name: n.clone(), version: format!("{}-{}", r.pkgver, r.pkgrel), arch: r.arch.first().cloned().unwrap_or_else(|| "x86_64".into()), desc: r.pkgdesc.clone(), url: r.url.clone(), depends: crate::pkgver::dep_names(&r.depends), makedepends: crate::pkgver::dep_names(&r.makedepends), checkdepends: crate::pkgver::dep_names(&r.checkdepends), provides: r.provides.clone(), conflicts: r.conflicts.clone(), ..Default::default() }) .collect(), None => vec![FakePackage { name: "unknown".into(), ..Default::default() }], } } /// Write a `.pkg.tar.zst` containing `.PKGINFO`, `.BUILDINFO` and any scripted /// payload files. pub fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result { let (pkgver, pkgrel) = p.split_version(); let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch); let path = dir.join(&filename); let enc = zstd::Encoder::new(std::io::BufWriter::new( std::fs::File::create(&path).map_err(|e| e.to_string())?, ), 3) .map_err(|e| e.to_string())?; let mut ar = tar::Builder::new(enc); // NOTE: the zstd frame must be finished explicitly or the archive is a // truncated stream that nothing can read back. let pkginfo = pkginfo(p, &pkgver, &pkgrel); write_entry(&mut ar, ".PKGINFO", pkginfo.as_bytes())?; let buildinfo = buildinfo(p, &pkgver, &pkgrel, m); write_entry(&mut ar, ".BUILDINFO", buildinfo.as_bytes())?; for f in &m.files { write_entry(&mut ar, &format!("usr/share/{}/{f}", p.name), f.as_bytes())?; } // A payload file so the artifact has non-metadata bytes and a real size. write_entry(&mut ar, &format!("usr/bin/{}", p.name), b"#!/bin/sh\necho hi\n")?; let enc = ar.into_inner().map_err(|e| e.to_string())?; enc.finish().map_err(|e| e.to_string())?; Ok(path) } fn write_entry(ar: &mut tar::Builder, path: &str, body: &[u8]) -> Result<(), String> { let mut h = tar::Header::new_gnu(); h.set_size(body.len() as u64); h.set_mode(0o644); h.set_mtime(0); h.set_entry_type(tar::EntryType::Regular); ar.append_data(&mut h, path, body).map_err(|e| e.to_string()) } fn pkginfo(p: &FakePackage, pkgver: &str, pkgrel: &str) -> String { let mut s = String::new(); s.push_str(&format!("pkgname = {}\n", p.name)); s.push_str(&format!("pkgbase = {}\n", p.name)); s.push_str(&format!("pkgver = {pkgver}-{pkgrel}\n")); s.push_str(&format!("pkgarch = {}\n", p.arch)); s.push_str(&format!("pkgdesc = {}\n", p.desc)); s.push_str(&format!("url = {}\n", p.url)); s.push_str("builddate = 1700000000\n"); s.push_str("packager = shim \n"); s.push_str("size = 42\n"); for l in &p.license { s.push_str(&format!("license = {l}\n")); } for d in &p.depends { s.push_str(&format!("depend = {d}\n")); } for d in &p.makedepends { s.push_str(&format!("makedepend = {d}\n")); } for d in &p.checkdepends { s.push_str(&format!("checkdepend = {d}\n")); } for d in &p.provides { s.push_str(&format!("provides = {d}\n")); } for d in &p.conflicts { s.push_str(&format!("conflicts = {d}\n")); } for b in &p.backup { s.push_str(&format!("backup = {b}\n")); } s } /// `.BUILDINFO`: the full installed set at build time. Left unfiltered this is /// the whole chroot, which is exactly why §10.1 intersects it with our own /// packages before storing a world snapshot. fn buildinfo(p: &FakePackage, pkgver: &str, pkgrel: &str, m: &Manifest) -> String { let mut s = String::new(); s.push_str("format = 2\n"); s.push_str(&format!("pkgname = {}\n", p.name)); s.push_str(&format!("pkgbase = {}\n", p.name)); s.push_str(&format!("pkgver = {pkgver}-{pkgrel}\n")); s.push_str(&format!("pkgarch = {}\n", p.arch)); s.push_str("packager = shim \n"); s.push_str("builddate = 1700000000\n"); s.push_str("buildenv = (!debug !strip)\n"); s.push_str("installed =\n"); for i in &m.installed { s.push_str(&format!(" {} {} {} -\n", i.name, i.version, if i.arch.is_empty() { "any" } else { &i.arch })); } s } fn fake_sig(bytes: &[u8]) -> Vec { format!("-----BEGIN FAKE PGP SIGNATURE-----\n{}\n-----END FAKE PGP SIGNATURE-----\n", hash::hex(bytes)).into_bytes() } /// `makepkg --printsrcinfo` / `--vercheck` (§5.2 Stage B). pub fn makepkg(args: &[String], m: &Manifest) -> Result { if args.iter().any(|a| a == "--vercheck" || a == "-V-check") { let v = m.vercheck.clone().unwrap_or_else(|| "1.0-1".into()); println!("{v}"); return Ok(0); } if args.iter().any(|a| a == "--printsrcinfo" || a == "-g") { let text = std::fs::read_to_string("PKGBUILD").unwrap_or_default(); match crate::recipe::parse_pkgbuild(&text) { Ok(r) => { let mut s = String::new(); if let Some(si) = r.srcinfo { s = si; } else { s.push_str(&format!("pkgbase = {}\n", r.pkgbase)); s.push_str(&format!("\tpkgver = {}\n", r.pkgver)); s.push_str(&format!("\tpkgrel = {}\n", r.pkgrel)); if r.epoch != "0" { s.push_str(&format!("\tepoch = {}\n", r.epoch)); } for a in &r.arch { s.push_str(&format!("\tarch = {a}\n")); } for d in &r.depends { s.push_str(&format!("\tdepends = {d}\n")); } for src in &r.source { s.push_str(&format!("\tsource = {src}\n")); } for c in &r.sha256sums { s.push_str(&format!("\tsha256sums = {c}\n")); } for n in &r.pkgnames { s.push_str(&format!("pkgname = {n}\n")); } } print!("{s}"); Ok(0) } Err(e) => { eprintln!("makepkg: {e}"); Ok(1) } } } else { // `makepkg -si` style: behave like a local build. makechrootpkg(args, m) } } /// `repo-add [-s -p key -R] `: rebuild the database /// from the packages handed to it. /// /// 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). pub fn repo_add(args: &[String], _m: &Manifest) -> Result { // `-p ` and friends take a value; a naive filter would treat the key id // as a package path. let mut positional: Vec<&String> = Vec::new(); let mut skip = false; for a in args { if skip { skip = false; continue; } if matches!(a.as_str(), "-p" | "--key" | "-o" | "-e") { skip = true; continue; } if !a.starts_with('-') { positional.push(a); } } let (db_path, pkgs) = match positional.split_first() { Some((db, rest)) => (PathBuf::from(db), rest.iter().map(|p| PathBuf::from(p.as_str())).collect::>()), None => return Err("repo-add: no database given".into()), }; 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()))?; let pkginfo = read_pkginfo(&bytes)?; let (name, version, arch, extra) = parse_pkginfo(&pkginfo); let mut entry = String::new(); entry.push_str(&format!("%FILENAME%\n{}\n\n", pkg.file_name().unwrap().to_string_lossy())); entry.push_str(&format!("%NAME%\n{name}\n\n")); entry.push_str(&format!("%BASE%\n{name}\n\n")); entry.push_str(&format!("%VERSION%\n{version}\n\n")); entry.push_str(&format!("%ARCH%\n{arch}\n\n")); entry.push_str(&format!("%CSIZE%\n{}\n\n", bytes.len())); entry.push_str("%DSIZE%\n42\n\n"); entry.push_str(&format!("%MD5SUM%\n{}\n\n", hash::hex(&bytes))); entry.push_str(&format!("%SHA256SUM%\n{}\n\n", hash::hex(&bytes))); if !extra.is_empty() { entry.push_str(&format!("{extra}\n")); } let mut h = tar::Header::new_gnu(); h.set_size(entry.len() as u64); h.set_mode(0o644); h.set_mtime(0); ar.append_data(&mut h, format!("{name}/DESC"), entry.as_bytes()) .map_err(|e| e.to_string())?; let mut h2 = tar::Header::new_gnu(); h2.set_size(pkginfo.len() as u64); h2.set_mode(0o644); h2.set_mtime(0); ar.append_data(&mut h2, format!("{name}/.PKGINFO"), pkginfo.as_bytes()) .map_err(|e| e.to_string())?; } let tar = ar.into_inner().map_err(|e| e.to_string())?; // pacman databases are gzip'd tarballs. let mut enc = flate2::write::GzEncoder::new( std::fs::File::create(&db_path).map_err(|e| e.to_string())?, flate2::Compression::default(), ); use std::io::Write; enc.write_all(&tar).map_err(|e| e.to_string())?; enc.finish().map_err(|e| e.to_string())?; println!("==> Updating repository"); Ok(0) } /// Pull `.PKGINFO` out of a `.pkg.tar.zst`. The real parsing lives in /// `crate::pkginfo`, which the pipeline also uses — the shim and the production /// path must agree about what a package says about itself, or a test that passes /// here would not mean anything. pub fn read_pkginfo(pkg_bytes: &[u8]) -> Result { crate::pkginfo::pkginfo_text(pkg_bytes) } pub fn read_buildinfo(pkg_bytes: &[u8]) -> Result { crate::pkginfo::buildinfo_text(pkg_bytes) } fn parse_pkginfo(s: &str) -> (String, String, String, String) { let mut name = String::new(); let mut version = String::new(); let mut arch = String::new(); let mut groups = Vec::new(); let mut deps = Vec::new(); let mut optdeps = Vec::new(); let mut provides = Vec::new(); let mut conflicts = Vec::new(); let mut replaces = Vec::new(); let mut license = Vec::new(); let mut desc = String::new(); let mut url = String::new(); for line in s.lines() { let (k, v) = match line.split_once('=') { Some((k, v)) => (k.trim(), v.trim()), None => continue, }; match k { "pkgname" => name = v.to_string(), "pkgver" => version = v.to_string(), "pkgarch" => arch = v.to_string(), "pkgdesc" => desc = v.to_string(), "url" => url = v.to_string(), "license" => license.push(v.to_string()), "depend" => deps.push(v.to_string()), "optdepend" => optdeps.push(v.to_string()), "checkdepend" => {} "makedepend" => {} "provides" => provides.push(v.to_string()), "conflict" => conflicts.push(v.to_string()), "replace" => replaces.push(v.to_string()), "group" => groups.push(v.to_string()), _ => {} } } let mut extra = String::new(); let mut push = |tag: &str, vals: &Vec| { if !vals.is_empty() { extra.push_str(&format!("{tag}\n{}\n\n", vals.join("\n"))); } }; push("%DESC%", &desc_vec(&desc)); push("%URL%", &url_vec(&url)); push("%LICENSE%", &license); push("%DEPENDS%", &deps); push("%OPTDEPENDS%", &optdeps); push("%PROVIDES%", &provides); push("%CONFLICTS%", &conflicts); push("%REPLACES%", &replaces); push("%GROUPS%", &groups); (name, version, arch, extra) } fn desc_vec(s: &str) -> Vec { if s.is_empty() { vec![] } else { vec![s.to_string()] } } fn url_vec(s: &str) -> Vec { if s.is_empty() { vec![] } else { vec![s.to_string()] } } /// `gpg --detach-sign --output `: write a deterministic stand-in /// signature so the signing path is exercised end to end. pub fn gpg(args: &[String]) -> Result { let out = args .iter() .position(|a| a == "--output" || a == "-o") .and_then(|i| args.get(i + 1)) .cloned(); let target = args.iter().rev().find(|a| !a.starts_with('-') && Some(*a) != out.as_ref()); let target = match target { Some(t) => t, None => return Err("gpg: nothing to sign".into()), }; let bytes = std::fs::read(target).map_err(|e| format!("gpg: {target}: {e}"))?; let sig = match out { Some(o) => o, None => format!("{target}.sig"), }; std::fs::write(&sig, fake_sig(&bytes)).map_err(|e| e.to_string())?; Ok(0) }