vinix-ports / tools / repack-public-modes.py
190 lines · 170 sloc · 9.39 KB · cc8c330a72b201321079bf89185a5c578ee1bd6d
Raw
1"""Repackage the compiler and X11 permission fixes from verified Vinix archives."""
2
3import argparse
4import csv
5import hashlib
6import os
7from pathlib import Path, PurePosixPath
8import re
9import stat
10import subprocess
11import tarfile
12import tempfile
13
14
15DIR_MODE = ' run("find", string-append(pkgdir(), "/usr"), "-type", "d", "-exec", "chmod", "755", "{}", "+")'
16GCC_MODE = ' run("find", string-append(pkgdir(), "/usr"), "-type", "f", "-exec", "chmod", "a+rX", "{}", "+")'
17XINIT_MODE = (' run("find", string-append(pkgdir(), "/etc"), string-append(pkgdir(), "/usr"),\n'
18 ' "-type", "d", "-exec", "chmod", "755", "{}", "+")')
19REVISIONS = {
20 "binutils": (5, DIR_MODE), "gcc": (3, GCC_MODE), "freeglut": (2, DIR_MODE),
21 "xf86-video-fbdev": (2, DIR_MODE), "xinit": (2, XINIT_MODE), "xorg-server": (2, DIR_MODE),
22}
23METADATA = (".PKGINFO", ".BUILDINFO", ".MTREE")
24
25
26def digest(path):
27 with path.open("rb") as stream:
28 return hashlib.file_digest(stream, "sha256").hexdigest()
29
30
31def revised_recipe(path, package):
32 release, commands = REVISIONS[package]
33 original = path.read_text()
34 recipe, count = re.subn(r"^ #:pkgrel, .*,$", f" #:pkgrel, {release},", original, flags=re.MULTILINE)
35 if count != 1 or not recipe.endswith(" })\n"):
36 raise ValueError(f"{path}: expected one package release and the closing package function")
37 return recipe.removesuffix(" })\n") + commands + "\n })\n"
38
39
40def package_entries(path):
41 payload, metadata = {}, {}
42 with subprocess.Popen(["zstd", "-qdc", "--", path], stdout=subprocess.PIPE) as proc:
43 with tarfile.open(fileobj=proc.stdout, mode="r|") as archive:
44 for entry in archive:
45 name = PurePosixPath(entry.name)
46 if (name.is_absolute() or ".." in name.parts or not name.parts
47 or str(name) != entry.name or entry.uid != 0 or entry.gid != 0):
48 raise ValueError(f"{path}: unexpected archived path or owner: {entry.name}")
49 if name.as_posix() in METADATA:
50 if not entry.isfile() or name.name in metadata or entry.size > 2**20:
51 raise ValueError(f"{path}: unexpected metadata member {entry.name}")
52 with archive.extractfile(entry) as stream:
53 metadata[name.name] = stream.read()
54 continue
55 if name.parts[0].startswith(".") or name in payload:
56 raise ValueError(f"{path}: unsupported or duplicate package member {entry.name}")
57 if entry.isfile():
58 with archive.extractfile(entry) as stream:
59 content = hashlib.file_digest(stream, "sha256").hexdigest()
60 elif entry.issym() or entry.islnk():
61 content = entry.linkname
62 elif entry.isdir():
63 content = ""
64 else:
65 raise ValueError(f"{path}: unsupported entry type at {entry.name}")
66 payload[name] = (entry.type, stat.S_IMODE(entry.mode), content)
67 while proc.stdout.read(65536):
68 pass
69 if proc.wait():
70 raise ValueError(f"{path}: could not decompress package")
71 if set(metadata) != set(METADATA) or not payload:
72 raise ValueError(f"{path}: missing package metadata or payload")
73 return payload, metadata
74
75
76def public_mode(package, path, entry_type, old_mode):
77 if package == "gcc":
78 if path.parts[0] == "usr" and entry_type in (tarfile.REGTYPE, tarfile.AREGTYPE, tarfile.LNKTYPE):
79 return old_mode | 0o444 | (0o111 if old_mode & 0o111 else 0)
80 elif entry_type == tarfile.DIRTYPE:
81 if path.parts[0] == "usr" or (package == "xinit" and path.parts[0] == "etc"):
82 return 0o755
83 return old_mode
84
85
86def replace_field(text, name, before, after):
87 prefix = f"{name} = "
88 found = [line for line in text.splitlines() if line.startswith(prefix)]
89 if found != [prefix + before] or not text.endswith("\n"):
90 raise ValueError(f"expected exactly one {name} field with value {before!r}")
91 return text.replace(prefix + before + "\n", prefix + after + "\n", 1)
92
93
94def repack(args):
95 package = args.package
96 with args.coverage.open() as stream:
97 row, = [entry for entry in csv.DictReader(stream, delimiter="\t") if entry["package"] == package]
98 original = Path(row["archive"]).resolve()
99 if row["status"] != "verified" or row["source_recipe"] != package:
100 raise ValueError(f"{package}: missing verified source archive")
101 if digest(original) != row["archive_sha256"] or digest(args.old_recipe) != row["recipe_sha256"]:
102 raise ValueError(f"{package}: original archive or recipe checksum changed")
103 if args.recipe.read_text() != revised_recipe(args.old_recipe, package):
104 raise ValueError(f"{package}: recipe changes exceed the package release and permission fix")
105
106 version, previous = row["version"].rsplit("-", 1)
107 release, _ = REVISIONS[package]
108 old_version, new_version = row["version"], f"{version}-{release}"
109 if release <= int(previous) or original.name != f"{package}-{old_version}-{args.arch}.pkg.tar.zst":
110 raise ValueError(f"{original}: archive architecture or package release mismatch")
111 before, metadata = package_entries(original)
112 info = metadata[".PKGINFO"].decode()
113 build = metadata[".BUILDINFO"].decode()
114 for field, value in (("pkgname", package), ("pkgbase", package), ("arch", args.arch)):
115 replace_field(info, field, value, value)
116 for field, value in (("pkgname", package), ("pkgbase", package), ("pkgarch", args.arch),
117 ("buildtool", "vpac")):
118 replace_field(build, field, value, value)
119 info = replace_field(info, "pkgver", old_version, new_version)
120 build = replace_field(build, "pkgver", old_version, new_version)
121 recipe_hash = digest(args.recipe)
122 build = replace_field(build, "pkgbuild_sha256sum", row["recipe_sha256"], recipe_hash)
123 build += f"pkgsource_sha256sum = {row['archive_sha256']}\n"
124 build += f"pkgsource_pkgbuild_sha256sum = {row['recipe_sha256']}\n"
125
126 args.output.mkdir(exist_ok=True, parents=True)
127 archive_path = args.output / f"{package}-{new_version}-{args.arch}.pkg.tar.zst"
128 receipt = args.output / f"{package}.sha256"
129 if archive_path.exists() or receipt.exists():
130 raise ValueError(f"{package}: use a new output directory")
131 changed = {}
132 expected = {}
133 for name, (entry_type, old_mode, content) in before.items():
134 mode = public_mode(package, name, entry_type, old_mode)
135 if mode != old_mode:
136 changed[name] = old_mode, mode
137 expected[name] = (entry_type, mode, content)
138
139 with tempfile.TemporaryDirectory(prefix=f".{package}-", dir=args.output) as directory:
140 work = Path(directory)
141 root = work / "pkg"
142 root.mkdir()
143 subprocess.run(["bsdtar", "-xpf", original, "--no-same-owner", "-C", root], check=True)
144 for path, (_, mode) in changed.items():
145 (root / path).chmod(mode, follow_symlinks=False)
146 (root / ".PKGINFO").write_text(info)
147 (root / ".BUILDINFO").write_text(build)
148 members = [".PKGINFO", ".BUILDINFO", *sorted({path.parts[0] for path in expected})]
149 member_list = work / "members"
150 member_list.write_bytes(b"\0".join(os.fsencode(name) for name in members) + b"\0")
151 flags = ["--uid", "0", "--gid", "0", "--uname", "root", "--gname", "root",
152 "-C", root, "--null", "-T", member_list]
153 subprocess.run(["bsdtar", "-czf", root / ".MTREE", "--format=mtree",
154 "--options=!all,use-set,type,uid,gid,mode,time,size,sha256,link", *flags], check=True)
155 members.insert(1, ".MTREE")
156 member_list.write_bytes(b"\0".join(os.fsencode(name) for name in members) + b"\0")
157 output = work / archive_path.name
158 subprocess.run(["bsdtar", "-cf", output, "--zstd", "--format=pax", *flags], check=True)
159 actual, written = package_entries(output)
160 if actual != expected:
161 mismatch = sorted(path for path in actual.keys() | expected.keys()
162 if actual.get(path) != expected.get(path))
163 raise ValueError(f"{package}: unexpected payload changes at {', '.join(map(str, mismatch[:10]))}")
164 if written[".PKGINFO"].decode() != info or written[".BUILDINFO"].decode() != build:
165 raise ValueError(f"{package}: unexpected package metadata changes")
166 sha = digest(output)
167 staged_receipt = work / receipt.name
168 staged_receipt.write_text(f"{sha} {archive_path.name}\n")
169 os.link(output, archive_path)
170 try:
171 os.link(staged_receipt, receipt)
172 except OSError:
173 archive_path.unlink()
174 raise
175 print(f"{package} {new_version} {args.arch}: verified {len(expected)} paths, {len(changed)} mode changes")
176 for path, (old_mode, mode) in sorted(changed.items()):
177 print(f"{old_mode:04o}\t{mode:04o}\t{path}")
178
179
180if __name__ == "__main__":
181 parser = argparse.ArgumentParser(description=__doc__)
182 parser.add_argument("arch", choices=("aarch64", "x86_64"))
183 parser.add_argument("package", choices=sorted(REVISIONS))
184 for arg in ("coverage", "old_recipe", "recipe", "output"):
185 parser.add_argument(arg, type=lambda path: Path(path).resolve())
186 args = parser.parse_args()
187 try:
188 repack(args)
189 except (ValueError, OSError, subprocess.SubprocessError) as err:
190 parser.exit(1, f"{err}\n")
191