"""Repackage the compiler and X11 permission fixes from verified Vinix archives.""" import argparse import csv import hashlib import os from pathlib import Path, PurePosixPath import re import stat import subprocess import tarfile import tempfile DIR_MODE = ' run("find", string-append(pkgdir(), "/usr"), "-type", "d", "-exec", "chmod", "755", "{}", "+")' GCC_MODE = ' run("find", string-append(pkgdir(), "/usr"), "-type", "f", "-exec", "chmod", "a+rX", "{}", "+")' XINIT_MODE = (' run("find", string-append(pkgdir(), "/etc"), string-append(pkgdir(), "/usr"),\n' ' "-type", "d", "-exec", "chmod", "755", "{}", "+")') REVISIONS = { "binutils": (5, DIR_MODE), "gcc": (3, GCC_MODE), "freeglut": (2, DIR_MODE), "xf86-video-fbdev": (2, DIR_MODE), "xinit": (2, XINIT_MODE), "xorg-server": (2, DIR_MODE), } METADATA = (".PKGINFO", ".BUILDINFO", ".MTREE") def digest(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def revised_recipe(path, package): release, commands = REVISIONS[package] original = path.read_text() recipe, count = re.subn(r"^ #:pkgrel, .*,$", f" #:pkgrel, {release},", original, flags=re.MULTILINE) if count != 1 or not recipe.endswith(" })\n"): raise ValueError(f"{path}: expected one package release and the closing package function") return recipe.removesuffix(" })\n") + commands + "\n })\n" def package_entries(path): payload, metadata = {}, {} with subprocess.Popen(["zstd", "-qdc", "--", path], stdout=subprocess.PIPE) as proc: with tarfile.open(fileobj=proc.stdout, mode="r|") as archive: for entry in archive: name = PurePosixPath(entry.name) if (name.is_absolute() or ".." in name.parts or not name.parts or str(name) != entry.name or entry.uid != 0 or entry.gid != 0): raise ValueError(f"{path}: unexpected archived path or owner: {entry.name}") if name.as_posix() in METADATA: if not entry.isfile() or name.name in metadata or entry.size > 2**20: raise ValueError(f"{path}: unexpected metadata member {entry.name}") with archive.extractfile(entry) as stream: metadata[name.name] = stream.read() continue if name.parts[0].startswith(".") or name in payload: raise ValueError(f"{path}: unsupported or duplicate package member {entry.name}") if entry.isfile(): with archive.extractfile(entry) as stream: content = hashlib.file_digest(stream, "sha256").hexdigest() elif entry.issym() or entry.islnk(): content = entry.linkname elif entry.isdir(): content = "" else: raise ValueError(f"{path}: unsupported entry type at {entry.name}") payload[name] = (entry.type, stat.S_IMODE(entry.mode), content) while proc.stdout.read(65536): pass if proc.wait(): raise ValueError(f"{path}: could not decompress package") if set(metadata) != set(METADATA) or not payload: raise ValueError(f"{path}: missing package metadata or payload") return payload, metadata def public_mode(package, path, entry_type, old_mode): if package == "gcc": if path.parts[0] == "usr" and entry_type in (tarfile.REGTYPE, tarfile.AREGTYPE, tarfile.LNKTYPE): return old_mode | 0o444 | (0o111 if old_mode & 0o111 else 0) elif entry_type == tarfile.DIRTYPE: if path.parts[0] == "usr" or (package == "xinit" and path.parts[0] == "etc"): return 0o755 return old_mode def replace_field(text, name, before, after): prefix = f"{name} = " found = [line for line in text.splitlines() if line.startswith(prefix)] if found != [prefix + before] or not text.endswith("\n"): raise ValueError(f"expected exactly one {name} field with value {before!r}") return text.replace(prefix + before + "\n", prefix + after + "\n", 1) def repack(args): package = args.package with args.coverage.open() as stream: row, = [entry for entry in csv.DictReader(stream, delimiter="\t") if entry["package"] == package] original = Path(row["archive"]).resolve() if row["status"] != "verified" or row["source_recipe"] != package: raise ValueError(f"{package}: missing verified source archive") if digest(original) != row["archive_sha256"] or digest(args.old_recipe) != row["recipe_sha256"]: raise ValueError(f"{package}: original archive or recipe checksum changed") if args.recipe.read_text() != revised_recipe(args.old_recipe, package): raise ValueError(f"{package}: recipe changes exceed the package release and permission fix") version, previous = row["version"].rsplit("-", 1) release, _ = REVISIONS[package] old_version, new_version = row["version"], f"{version}-{release}" if release <= int(previous) or original.name != f"{package}-{old_version}-{args.arch}.pkg.tar.zst": raise ValueError(f"{original}: archive architecture or package release mismatch") before, metadata = package_entries(original) info = metadata[".PKGINFO"].decode() build = metadata[".BUILDINFO"].decode() for field, value in (("pkgname", package), ("pkgbase", package), ("arch", args.arch)): replace_field(info, field, value, value) for field, value in (("pkgname", package), ("pkgbase", package), ("pkgarch", args.arch), ("buildtool", "vpac")): replace_field(build, field, value, value) info = replace_field(info, "pkgver", old_version, new_version) build = replace_field(build, "pkgver", old_version, new_version) recipe_hash = digest(args.recipe) build = replace_field(build, "pkgbuild_sha256sum", row["recipe_sha256"], recipe_hash) build += f"pkgsource_sha256sum = {row['archive_sha256']}\n" build += f"pkgsource_pkgbuild_sha256sum = {row['recipe_sha256']}\n" args.output.mkdir(exist_ok=True, parents=True) archive_path = args.output / f"{package}-{new_version}-{args.arch}.pkg.tar.zst" receipt = args.output / f"{package}.sha256" if archive_path.exists() or receipt.exists(): raise ValueError(f"{package}: use a new output directory") changed = {} expected = {} for name, (entry_type, old_mode, content) in before.items(): mode = public_mode(package, name, entry_type, old_mode) if mode != old_mode: changed[name] = old_mode, mode expected[name] = (entry_type, mode, content) with tempfile.TemporaryDirectory(prefix=f".{package}-", dir=args.output) as directory: work = Path(directory) root = work / "pkg" root.mkdir() subprocess.run(["bsdtar", "-xpf", original, "--no-same-owner", "-C", root], check=True) for path, (_, mode) in changed.items(): (root / path).chmod(mode, follow_symlinks=False) (root / ".PKGINFO").write_text(info) (root / ".BUILDINFO").write_text(build) members = [".PKGINFO", ".BUILDINFO", *sorted({path.parts[0] for path in expected})] member_list = work / "members" member_list.write_bytes(b"\0".join(os.fsencode(name) for name in members) + b"\0") flags = ["--uid", "0", "--gid", "0", "--uname", "root", "--gname", "root", "-C", root, "--null", "-T", member_list] subprocess.run(["bsdtar", "-czf", root / ".MTREE", "--format=mtree", "--options=!all,use-set,type,uid,gid,mode,time,size,sha256,link", *flags], check=True) members.insert(1, ".MTREE") member_list.write_bytes(b"\0".join(os.fsencode(name) for name in members) + b"\0") output = work / archive_path.name subprocess.run(["bsdtar", "-cf", output, "--zstd", "--format=pax", *flags], check=True) actual, written = package_entries(output) if actual != expected: mismatch = sorted(path for path in actual.keys() | expected.keys() if actual.get(path) != expected.get(path)) raise ValueError(f"{package}: unexpected payload changes at {', '.join(map(str, mismatch[:10]))}") if written[".PKGINFO"].decode() != info or written[".BUILDINFO"].decode() != build: raise ValueError(f"{package}: unexpected package metadata changes") sha = digest(output) staged_receipt = work / receipt.name staged_receipt.write_text(f"{sha} {archive_path.name}\n") os.link(output, archive_path) try: os.link(staged_receipt, receipt) except OSError: archive_path.unlink() raise print(f"{package} {new_version} {args.arch}: verified {len(expected)} paths, {len(changed)} mode changes") for path, (old_mode, mode) in sorted(changed.items()): print(f"{old_mode:04o}\t{mode:04o}\t{path}") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("arch", choices=("aarch64", "x86_64")) parser.add_argument("package", choices=sorted(REVISIONS)) for arg in ("coverage", "old_recipe", "recipe", "output"): parser.add_argument(arg, type=lambda path: Path(path).resolve()) args = parser.parse_args() try: repack(args) except (ValueError, OSError, subprocess.SubprocessError) as err: parser.exit(1, f"{err}\n")