use std::fmt::Write as _; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use crate::hash; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] // FakePackage stays `pub`: the whole `shims` module is `test-support`-gated, so a release build never compiles it. 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 { 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()), } } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] // FakeInstalled stays `pub`: the whole `shims` module is `test-support`-gated, so a release build never compiles it. pub struct FakeInstalled { pub name: String, pub version: String, pub arch: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] // Manifest stays `pub`: returned by `manifest()`, which the shim tests read; the module is `test-support`-gated. pub struct Manifest { pub name: String, pub build: String, pub log_lines: Vec, pub packages: Vec, pub installed: Vec, pub sig: bool, pub vercheck: Option, 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![], } } } /// The shim reads its own manifest while dispatching a tool; tests read it to assert what a build did. #[cfg(feature = "test-support")] pub fn manifest() -> Manifest { manifest_impl() } #[cfg(not(feature = "test-support"))] fn manifest() -> Manifest { manifest_impl() } fn manifest_impl() -> 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(), } } /// Called by `run` to log the invocation; nothing outside `shims` records a shim call. fn record(tool: &str, args: &[String]) { let Ok(dir) = std::env::var("AUR_SHIM_DIR") else { return }; let _ = std::fs::create_dir_all(&dir); let entry = serde_json::json!({ "tool": tool, "args": args, "cwd": std::env::current_dir().map_or_default(|p| p.display().to_string()), }); 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()); } } fn kill_parent_if_asked(tool: &str) { let want = std::env::var("AUR_SHIM_KILL_PARENT").unwrap_or_default(); if want == tool { unsafe { libc::kill(libc::getppid(), libc::SIGKILL); } std::process::exit(137); } } fn forced_fail(tool: &str) -> bool { std::env::var("AUR_SHIM_FAIL").is_ok_and(|v| v == tool) } /// Read back the shim's invocation log. /// /// Test-tier only. The shim *appends* to `invocations.jsonl` in production — /// that is how a fake tool leaves evidence — but nothing in the crate reads the /// file back; `called_with` below is the only reader and it is gated with this. /// The census credited this function with production callers at the two lines /// that name the *filename* in a string, which is not a call. #[cfg(feature = "test-support")] 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(), } } /// How many times the shim recorded `tool` being called with `needle` in its /// arguments. /// /// Test-tier only. The shim *writes* the invocation log in production — that is /// how a fake tool leaves evidence — but nothing in the crate reads it back; /// only tests ask what a build actually did. #[cfg(feature = "test-support")] 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().is_some_and(|a| a.iter().any(|v| v.as_str().is_some_and(|s| s.contains(needle)))) }) .count() } 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" => pacman(&args), other => Err(format!("no shim named {other}")), }; match r { Ok(code) => code, Err(e) => { eprintln!("shim {tool}: {e}"); 1 } } } /// Reached only through `run`, which matches the tool name to it. The tool name appears in test strings, which is not a caller. fn mkarchroot(args: &[String]) -> Result { 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())?; let _ = std::fs::write(Path::new(&target).join("SHIM-ROOT"), "fake chroot\n"); Ok(0) } /// Reached only through `run`, which matches the tool name to it. The tool name appears in test strings, which is not a caller. fn makechrootpkg(args: &[String], m: &Manifest) -> Result { if !args.iter().any(|a| a == "-r") { return Err("makechrootpkg: expected -r ".into()); } let wants_sig = args.iter().any(|a| a.starts_with("-si") || a == "-i" || a == "--sign"); emit_packages(m, "makechrootpkg", wants_sig) } fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result { for l in &m.log_lines { println!("{l}"); } if forced_fail(tool) || 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); } let startdir = std::env::current_dir().map_err(|e| e.to_string())?; if !startdir.join("PKGBUILD").exists() { let found = std::fs::read_dir(&startdir).map_or_default(|rd| { rd.filter_map(std::result::Result::ok) .map(|e| e.file_name().to_string_lossy().into_owned()) .collect::>() }); return Err(format!("{tool}: 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 && wants_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) } 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 {} -> {target}: {e}", link.display()); } } } fn packages_to_emit(m: &Manifest, startdir: &Path) -> Vec { if !m.packages.is_empty() { return m.packages.clone(); } 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() }], } } 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())?; } 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(); let _ = writeln!(s, "pkgname = {}", p.name); let _ = writeln!(s, "pkgbase = {}", p.name); let _ = writeln!(s, "pkgver = {pkgver}-{pkgrel}"); let _ = writeln!(s, "pkgarch = {}", p.arch); let _ = writeln!(s, "pkgdesc = {}", p.desc); let _ = writeln!(s, "url = {}", 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 { let _ = writeln!(s, "license = {l}"); } for d in &p.depends { let _ = writeln!(s, "depend = {d}"); } for d in &p.makedepends { let _ = writeln!(s, "makedepend = {d}"); } for d in &p.checkdepends { let _ = writeln!(s, "checkdepend = {d}"); } for d in &p.provides { let _ = writeln!(s, "provides = {d}"); } for d in &p.conflicts { let _ = writeln!(s, "conflicts = {d}"); } for b in &p.backup { let _ = writeln!(s, "backup = {b}"); } s } fn buildinfo(p: &FakePackage, pkgver: &str, pkgrel: &str, m: &Manifest) -> String { let mut s = String::new(); s.push_str("format = 2\n"); let _ = writeln!(s, "pkgname = {}", p.name); let _ = writeln!(s, "pkgbase = {}", p.name); let _ = writeln!(s, "pkgver = {pkgver}-{pkgrel}"); let _ = writeln!(s, "pkgarch = {}", 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 { let _ = writeln!(s, " {} {} {} -", 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() } /// Reached only through `run`, which matches the tool name to it. The tool name appears in test strings, which is not a caller. 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 { let _ = writeln!(s, "pkgbase = {}", r.pkgbase); let _ = writeln!(s, "\tpkgver = {}", r.pkgver); let _ = writeln!(s, "\tpkgrel = {}", r.pkgrel); if r.epoch != "0" { let _ = writeln!(s, "\tepoch = {}", r.epoch); } for a in &r.arch { let _ = writeln!(s, "\tarch = {a}"); } for d in &r.depends { let _ = writeln!(s, "\tdepends = {d}"); } for src in &r.source { let _ = writeln!(s, "\tsource = {src}"); } for c in &r.sha256sums { let _ = writeln!(s, "\tsha256sums = {c}"); } for n in &r.pkgnames { let _ = writeln!(s, "pkgname = {n}"); } } print!("{s}"); Ok(0) } Err(e) => { eprintln!("makepkg: {e}"); Ok(1) } } } else { emit_packages(m, "makepkg", false) } } /// Reached only through `run`, which matches the tool name to it. The tool name appears in test strings, which is not a caller. fn pacman(args: &[String]) -> Result { if args.iter().any(|a| a == "-U") { for path in args.iter().filter(|a| !a.starts_with('-')) { let p = std::path::Path::new(path); let claimed = p.file_name().and_then(|s| s.to_str()).ok_or_else(|| format!("pacman: bad blob path {path}"))?; let bytes = std::fs::read(p).map_err(|e| format!("pacman: {path}: {e}"))?; if crate::hash::hex(&bytes) != claimed { return Err(format!("pacman: {claimed} does not hash to the digest its name claims")); } let pkginfo = crate::pkginfo::pkginfo_text(&bytes)?; let info = crate::pkginfo::parse_pkginfo(&pkginfo); if let Some(db) = installed_db() { use std::io::Write; if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(db) { let _ = writeln!(f, "{} {}", info.name, info.version); } } println!(":: installing {}-{}", info.name, info.version); } return Ok(0); } if args.iter().any(|a| a == "-Q") { if let Some(db) = installed_db() { if let Ok(text) = std::fs::read_to_string(db) { print!("{text}"); } } return Ok(0); } Ok(0) } fn installed_db() -> Option { std::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt")) } const DB_SUFFIXES: [&str; 5] = [".db.tar", ".db.tar.gz", ".db.tar.zst", ".db.tar.bz2", ".db.tar.xz"]; /// The shim validates its own `--db` argument; tests check the verdicts. #[cfg(feature = "test-support")] pub fn valid_db_arg(p: &Path) -> bool { valid_db_arg_impl(p) } #[cfg(not(feature = "test-support"))] fn valid_db_arg(p: &Path) -> bool { valid_db_arg_impl(p) } fn valid_db_arg_impl(p: &Path) -> bool { let name = p.file_name().map_or_default(|s| s.to_string_lossy().into_owned()); !name.is_empty() && DB_SUFFIXES.iter().any(|sfx| name.ends_with(sfx)) } fn repo_add(args: &[String], _m: &Manifest) -> Result { 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()), }; if !valid_db_arg(&db_path) { 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()))?; let pkginfo = crate::pkginfo::pkginfo_text(&bytes)?; let (name, version, arch, extra) = pkginfo_fields(&bytes)?; let mut entry = String::new(); let _ = write!(entry, "%FILENAME%\n{}\n\n", pkg.file_name().unwrap().to_string_lossy()); let _ = write!(entry, "%NAME%\n{name}\n\n"); let _ = write!(entry, "%BASE%\n{name}\n\n"); let _ = write!(entry, "%VERSION%\n{version}\n\n"); let _ = write!(entry, "%ARCH%\n{arch}\n\n"); let _ = write!(entry, "%CSIZE%\n{}\n\n", bytes.len()); entry.push_str("%DSIZE%\n42\n\n"); let _ = write!(entry, "%MD5SUM%\n{}\n\n", hash::hex(&bytes)); let _ = write!(entry, "%SHA256SUM%\n{}\n\n", hash::hex(&bytes)); if !extra.is_empty() { let _ = writeln!(entry, "{extra}"); } 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())?; 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) } fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String), String> { let text = crate::pkginfo::pkginfo_text(pkg_bytes)?; let info = crate::pkginfo::parse_pkginfo(&text); let mut extra = String::new(); { let mut push = |tag: &str, vals: &[String]| { if !vals.is_empty() { let _ = write!(extra, "{tag}\n{}\n\n", vals.join("\n")); } }; let one = |s: &str| -> Vec { if s.is_empty() { vec![] } else { vec![s.to_string()] } }; push("%DESC%", &one(&info.desc)); push("%URL%", &one(&info.url)); push("%LICENSE%", &info.license); push("%DEPENDS%", &info.depends); push("%OPTDEPENDS%", &info.optdepends); push("%PROVIDES%", &info.provides); push("%CONFLICTS%", &info.conflicts); push("%REPLACES%", &info.replaces); push("%GROUPS%", &info.groups); } Ok((info.name, info.version, info.arch, extra)) } /// Reached only through `run`, which matches the tool name to it. The tool name appears in test strings, which is not a caller. 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 Some(target) = target else { 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) }