| 1 | #!/usr/bin/env python3 |
| 2 | """Build the renderer a release ships: renderer.tar.gz, one tree of the |
| 3 | pinned packages and its MANIFEST. |
| 4 | |
| 5 | scripts/build-renderer-tree.py PIN TAR [--tree DIR] |
| 6 | |
| 7 | PIN is internal/release/renderer.json. Every amd64 package it pins is |
| 8 | fetched from its snapshot URL and refused unless its size and SHA-256 are |
| 9 | the pin's. Their data members are unpacked, in the pin's order, into one |
| 10 | tree, and MANIFEST lists every entry of it, one line each, sorted by path |
| 11 | (relative to the tree's root, MANIFEST itself not listed): |
| 12 | |
| 13 | dir <path> |
| 14 | file <path> <sha256> <mode> |
| 15 | link <path> <target> |
| 16 | |
| 17 | A file's mode is 0755 when its owner could execute it and 0644 otherwise: |
| 18 | nothing is group or world writable, setuid or setgid. A link's target is |
| 19 | relative and resolves, through any links on the way, to an entry inside |
| 20 | the tree. Debian links one top-level directory to another with an |
| 21 | absolute target (fontconfig-config's /etc/fonts/conf.d); the tree is the |
| 22 | renderer's root, so such a target is written as the same path relative to |
| 23 | the link, and must then resolve like any other. The build refuses a |
| 24 | target that climbs out of the tree or names nothing in it, a member path |
| 25 | that is not inside the tree or goes through a link, a name the MANIFEST |
| 26 | cannot hold (white space, control characters), two packages that |
| 27 | disagree about a path, and a pin whose program is not an executable file. |
| 28 | |
| 29 | TAR holds MANIFEST and the tree, in path order, with no owner and no |
| 30 | times: the same pin gives the same bytes. It is written whole or not at |
| 31 | all. The tree is unpacked in a scratch directory beside TAR and removed, |
| 32 | unless --tree names a new directory to keep it in. The MANIFEST's SHA-256, |
| 33 | printed on stdout, is the pin make release-runner links into the Linux |
| 34 | runner (internal/release rendererSHA256). |
| 35 | |
| 36 | SOURCES is written beside TAR in the same run, from the same checked debs |
| 37 | (scripts/renderer-sources.py): each package, its version and where its |
| 38 | source is. It is published with the archive. |
| 39 | """ |
| 40 | import gzip |
| 41 | import hashlib |
| 42 | import io |
| 43 | import json |
| 44 | import os |
| 45 | import re |
| 46 | import shutil |
| 47 | import sys |
| 48 | import tarfile |
| 49 | import tempfile |
| 50 | import urllib.request |
| 51 | from concurrent.futures import ThreadPoolExecutor |
| 52 | import importlib.util |
| 53 | |
| 54 | _spec = importlib.util.spec_from_file_location("renderer_sources", os.path.join(os.path.dirname(os.path.abspath(__file__)), "renderer-sources.py")) |
| 55 | renderer_sources = importlib.util.module_from_spec(_spec) |
| 56 | _spec.loader.exec_module(renderer_sources) |
| 57 | |
| 58 | SNAPSHOT = "https://snapshot.debian.org/archive/" |
| 59 | DIGEST = re.compile(r"[0-9a-f]{64}") |
| 60 | LINK_DEPTH = 40 |
| 61 | |
| 62 | |
| 63 | class Refused(Exception): |
| 64 | pass |
| 65 | |
| 66 | |
| 67 | def fetch(url): |
| 68 | with urllib.request.urlopen(url, timeout=600) as r: |
| 69 | return r.read() |
| 70 | |
| 71 | |
| 72 | def packages_of(pin): |
| 73 | if "arm64" in pin or not isinstance(pin.get("amd64"), list) or not pin["amd64"]: |
| 74 | raise Refused("the pin must list amd64 packages, and only amd64") |
| 75 | packages = pin["amd64"] |
| 76 | names = [p.get("package") for p in packages] |
| 77 | if names != sorted(set(names)): |
| 78 | raise Refused("the pin's packages are not sorted and unique") |
| 79 | for p in packages: |
| 80 | url = p.get("url") |
| 81 | if not (isinstance(url, str) and url.startswith(SNAPSHOT) and url.endswith(".deb") |
| 82 | and isinstance(p.get("sha256"), str) and DIGEST.fullmatch(p["sha256"]) |
| 83 | and isinstance(p.get("size"), int) and p["size"] > 0): |
| 84 | raise Refused("%s: want a snapshot.debian.org .deb URL, a SHA-256 and a size" % p.get("package")) |
| 85 | return packages |
| 86 | |
| 87 | |
| 88 | def checked(p): |
| 89 | """The deb the pin names: its bytes, or a refusal.""" |
| 90 | data = fetch(p["url"]) |
| 91 | if len(data) != p["size"]: |
| 92 | raise Refused("%s: got %d bytes, the pin says %d" % (p["package"], len(data), p["size"])) |
| 93 | if hashlib.sha256(data).hexdigest() != p["sha256"]: |
| 94 | raise Refused("%s: SHA-256 is not the pin's" % p["package"]) |
| 95 | return data |
| 96 | |
| 97 | |
| 98 | def data_member(name, deb): |
| 99 | """The data.tar of a deb (an ar archive), opened.""" |
| 100 | if deb[:8] != b"!<arch>\n": |
| 101 | raise Refused("%s: not a deb" % name) |
| 102 | i, members = 8, {} |
| 103 | while i < len(deb): |
| 104 | header = deb[i:i + 60] |
| 105 | if len(header) != 60 or header[58:60] != b"`\n": |
| 106 | raise Refused("%s: a broken ar header" % name) |
| 107 | member = header[:16].decode("ascii", "replace").strip().rstrip("/") |
| 108 | size = int(header[48:58]) |
| 109 | members.setdefault(member, deb[i + 60:i + 60 + size]) |
| 110 | i += 60 + size + (size & 1) |
| 111 | if not members.get("debian-binary", b"").startswith(b"2."): |
| 112 | raise Refused("%s: not a format 2 deb" % name) |
| 113 | data = [m for m in members if m.startswith("data.tar")] |
| 114 | modes = {"data.tar": "r:", "data.tar.gz": "r:gz", "data.tar.xz": "r:xz"} |
| 115 | if len(data) != 1 or data[0] not in modes: |
| 116 | raise Refused("%s: want one data.tar, .tar.gz or .tar.xz member, got %s" % (name, data)) |
| 117 | return tarfile.open(fileobj=io.BytesIO(members[data[0]]), mode=modes[data[0]]) |
| 118 | |
| 119 | |
| 120 | def holdable(s): |
| 121 | """Whether s fits in a MANIFEST field: no white space or control |
| 122 | characters, and valid UTF-8.""" |
| 123 | try: |
| 124 | s.encode("utf-8") |
| 125 | except UnicodeEncodeError: |
| 126 | return False |
| 127 | return bool(s) and not any(c.isspace() or ord(c) < 0x20 or ord(c) == 0x7f for c in s) |
| 128 | |
| 129 | |
| 130 | def member_path(name): |
| 131 | """A data.tar member's path inside the tree ("" for its root), or None |
| 132 | when it is not one.""" |
| 133 | if name in (".", "./"): |
| 134 | return "" |
| 135 | if name.startswith("./"): |
| 136 | name = name[2:] |
| 137 | name = name.rstrip("/") |
| 138 | parts = name.split("/") |
| 139 | if name.startswith("/") or not holdable(name) or any(p in ("", ".", "..") for p in parts): |
| 140 | return None |
| 141 | return name |
| 142 | |
| 143 | |
| 144 | class Tree: |
| 145 | """The unpacked tree: entries by path, mirrored on disk under root.""" |
| 146 | |
| 147 | def __init__(self, root): |
| 148 | self.root = root |
| 149 | self.entries = {} # path -> ("dir",) | ("file", sha256, mode) | ("link", target) |
| 150 | self.owner = {} |
| 151 | |
| 152 | def disk(self, path): |
| 153 | return os.path.join(self.root, *path.split("/")) |
| 154 | |
| 155 | def parents(self, path, package): |
| 156 | parts = path.split("/") |
| 157 | for i in range(1, len(parts)): |
| 158 | parent = "/".join(parts[:i]) |
| 159 | e = self.entries.get(parent) |
| 160 | if e is None: |
| 161 | self.entries[parent], self.owner[parent] = ("dir",), package |
| 162 | os.mkdir(self.disk(parent)) |
| 163 | os.chmod(self.disk(parent), 0o755) |
| 164 | elif e[0] != "dir": |
| 165 | raise Refused("%s (%s): goes through a link or file of %s" % (path, package, self.owner[parent])) |
| 166 | |
| 167 | def add(self, package, m, archive): |
| 168 | path = member_path(m.name) |
| 169 | if path is None: |
| 170 | raise Refused("%s: %r is not a path inside the tree the MANIFEST can hold" % (package, m.name)) |
| 171 | if path == "": |
| 172 | if not m.isdir(): |
| 173 | raise Refused("%s: the tree's root is not a directory" % package) |
| 174 | return |
| 175 | if path == "MANIFEST": |
| 176 | raise Refused("%s: ships MANIFEST, the tree's own list" % package) |
| 177 | self.parents(path, package) |
| 178 | if m.isdir(): |
| 179 | entry, body = ("dir",), None |
| 180 | elif m.issym(): |
| 181 | target = m.linkname |
| 182 | if target.startswith("/"): |
| 183 | # The tree is the renderer's root: the same path, relative. |
| 184 | target = "../" * path.count("/") + target.lstrip("/") |
| 185 | if not holdable(target): |
| 186 | raise Refused("%s (%s): link target %r is not one the MANIFEST can hold" % (path, package, m.linkname)) |
| 187 | entry, body = ("link", target), None |
| 188 | elif m.isfile(): |
| 189 | body = archive.extractfile(m).read() |
| 190 | entry = ("file", hashlib.sha256(body).hexdigest(), 0o755 if m.mode & 0o100 else 0o644) |
| 191 | else: |
| 192 | raise Refused("%s (%s): only files, directories and links belong in the tree" % (path, package)) |
| 193 | old = self.entries.get(path) |
| 194 | if old is not None: |
| 195 | if old != entry: |
| 196 | raise Refused("%s: %s and %s disagree about it" % (path, self.owner[path], package)) |
| 197 | return |
| 198 | self.entries[path], self.owner[path] = entry, package |
| 199 | disk = self.disk(path) |
| 200 | if entry[0] == "dir": |
| 201 | os.mkdir(disk) |
| 202 | os.chmod(disk, 0o755) |
| 203 | elif entry[0] == "link": |
| 204 | os.symlink(entry[1], disk) |
| 205 | else: |
| 206 | fd = os.open(disk, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) |
| 207 | with os.fdopen(fd, "wb") as f: |
| 208 | f.write(body) |
| 209 | os.chmod(disk, entry[2]) |
| 210 | |
| 211 | def resolve(self, start, target, depth=0): |
| 212 | """Where target, read in directory start (a list of names), leads: |
| 213 | a list of names from the root, every step an entry of the tree. |
| 214 | As Linux resolves a path, every part after the first, including an |
| 215 | empty or "." part (a trailing "/" or "/."), needs a directory |
| 216 | before it: "f/" and "f/." fail when f is a file.""" |
| 217 | if depth > LINK_DEPTH: |
| 218 | raise Refused("too many links") |
| 219 | here = list(start) |
| 220 | for i, name in enumerate(target.split("/")): |
| 221 | if i > 0 and self.kind(here) != "dir": |
| 222 | raise Refused("%s is not a directory" % "/".join(here)) |
| 223 | if name in ("", "."): |
| 224 | continue |
| 225 | if name == "..": |
| 226 | if not here: |
| 227 | raise Refused("climbs out of the tree") |
| 228 | here.pop() |
| 229 | continue |
| 230 | path = "/".join(here + [name]) |
| 231 | e = self.entries.get(path) |
| 232 | if e is None: |
| 233 | raise Refused("%s names nothing in the tree" % path) |
| 234 | if e[0] == "link": |
| 235 | here = self.resolve(here, e[1], depth + 1) |
| 236 | else: |
| 237 | here.append(name) |
| 238 | return here |
| 239 | |
| 240 | def kind(self, names): |
| 241 | return "dir" if not names else self.entries["/".join(names)][0] |
| 242 | |
| 243 | def check(self, program): |
| 244 | problems = [] |
| 245 | for path, e in sorted(self.entries.items()): |
| 246 | if e[0] == "link": |
| 247 | try: |
| 248 | self.resolve(path.split("/")[:-1], e[1]) |
| 249 | except Refused as r: |
| 250 | problems.append("%s -> %s (%s): %s" % (path, e[1], self.owner[path], r)) |
| 251 | try: |
| 252 | end = "/".join(self.resolve([], program)) |
| 253 | ok = self.entries[end][0] == "file" and self.entries[end][2] == 0o755 |
| 254 | except (Refused, KeyError): |
| 255 | ok = False |
| 256 | if not ok: |
| 257 | problems.append("%s: the pin's program is not an executable file in the tree" % program) |
| 258 | if problems: |
| 259 | raise Refused("\n".join(problems)) |
| 260 | |
| 261 | def manifest(self): |
| 262 | lines = [] |
| 263 | for path, e in sorted(self.entries.items()): |
| 264 | if e[0] == "dir": |
| 265 | lines.append("dir %s\n" % path) |
| 266 | elif e[0] == "link": |
| 267 | lines.append("link %s %s\n" % (path, e[1])) |
| 268 | else: |
| 269 | lines.append("file %s %s %04o\n" % (path, e[1], e[2])) |
| 270 | return "".join(lines).encode("utf-8") |
| 271 | |
| 272 | |
| 273 | def write_tar(tree, manifest, out): |
| 274 | """Write the tar to out: MANIFEST and every entry in path order, no |
| 275 | owner, no times, gzip with no name or time.""" |
| 276 | def info(path, mode, kind=tarfile.REGTYPE, size=0, link=""): |
| 277 | ti = tarfile.TarInfo(path) |
| 278 | ti.type, ti.mode, ti.size, ti.linkname = kind, mode, size, link |
| 279 | ti.mtime, ti.uid, ti.gid, ti.uname, ti.gname = 0, 0, 0, "", "" |
| 280 | return ti |
| 281 | entries = dict(tree.entries) |
| 282 | entries["MANIFEST"] = None |
| 283 | with gzip.GzipFile(filename="", mode="wb", fileobj=out, compresslevel=9, mtime=0) as gz: |
| 284 | with tarfile.open(fileobj=gz, mode="w|", format=tarfile.PAX_FORMAT, encoding="utf-8") as tar: |
| 285 | for path in sorted(entries): |
| 286 | e = entries[path] |
| 287 | if e is None: |
| 288 | tar.addfile(info(path, 0o644, size=len(manifest)), io.BytesIO(manifest)) |
| 289 | elif e[0] == "dir": |
| 290 | tar.addfile(info(path, 0o755, tarfile.DIRTYPE)) |
| 291 | elif e[0] == "link": |
| 292 | tar.addfile(info(path, 0o777, tarfile.SYMTYPE, link=e[1])) |
| 293 | else: |
| 294 | with open(tree.disk(path), "rb") as f: |
| 295 | tar.addfile(info(path, e[2], size=os.fstat(f.fileno()).st_size), f) |
| 296 | |
| 297 | |
| 298 | def build(pin_path, tar_path, keep): |
| 299 | with open(pin_path) as f: |
| 300 | pin = json.load(f) |
| 301 | packages = packages_of(pin) |
| 302 | program = pin.get("program") |
| 303 | if not isinstance(program, str) or member_path(program) in (None, ""): |
| 304 | raise Refused("the pin names no program") |
| 305 | out_dir = os.path.dirname(os.path.abspath(tar_path)) |
| 306 | with ThreadPoolExecutor(max_workers=4) as pool: |
| 307 | debs = list(pool.map(checked, packages)) |
| 308 | try: |
| 309 | sources = renderer_sources.sources(pin, debs).encode("utf-8") |
| 310 | except renderer_sources.Refused as r: |
| 311 | raise Refused(str(r)) |
| 312 | if keep: |
| 313 | os.mkdir(keep, 0o755) |
| 314 | root, scratch = keep, None |
| 315 | else: |
| 316 | scratch = tempfile.mkdtemp(prefix=".renderer-tree-", dir=out_dir) |
| 317 | root = scratch |
| 318 | fd, partial = tempfile.mkstemp(prefix=".renderer-", suffix=".tar.gz.partial", dir=out_dir) |
| 319 | try: |
| 320 | tree = Tree(root) |
| 321 | for p, deb in zip(packages, debs): |
| 322 | with data_member(p["package"], deb) as archive: |
| 323 | for m in archive: |
| 324 | tree.add(p["package"], m, archive) |
| 325 | tree.check(program) |
| 326 | manifest = tree.manifest() |
| 327 | if keep: |
| 328 | # 0644 as in the tar, whatever the umask: the verifier |
| 329 | # refuses a group or world writable MANIFEST. |
| 330 | path = os.path.join(keep, "MANIFEST") |
| 331 | with open(path, "wb") as f: |
| 332 | f.write(manifest) |
| 333 | os.chmod(path, 0o644) |
| 334 | with os.fdopen(fd, "wb") as out: |
| 335 | fd = None |
| 336 | write_tar(tree, manifest, out) |
| 337 | os.chmod(partial, 0o644) |
| 338 | sources_path = os.path.join(out_dir, "SOURCES") |
| 339 | with open(sources_path + ".partial", "wb") as f: |
| 340 | f.write(sources) |
| 341 | os.chmod(sources_path + ".partial", 0o644) |
| 342 | os.replace(sources_path + ".partial", sources_path) |
| 343 | os.replace(partial, tar_path) |
| 344 | partial = None |
| 345 | except BaseException: |
| 346 | if keep: |
| 347 | shutil.rmtree(keep, ignore_errors=True) |
| 348 | raise |
| 349 | finally: |
| 350 | if fd is not None: |
| 351 | os.close(fd) |
| 352 | if partial is not None: |
| 353 | os.unlink(partial) |
| 354 | if scratch is not None: |
| 355 | shutil.rmtree(scratch, ignore_errors=True) |
| 356 | files = sum(1 for e in tree.entries.values() if e[0] == "file") |
| 357 | print("renderer: %d packages, %d entries (%d files), %s: %d bytes" % ( |
| 358 | len(packages), len(tree.entries), files, tar_path, os.path.getsize(tar_path)), file=sys.stderr) |
| 359 | return hashlib.sha256(manifest).hexdigest() |
| 360 | |
| 361 | |
| 362 | def main(argv): |
| 363 | keep = None |
| 364 | if len(argv) == 4 and argv[2] == "--tree": |
| 365 | keep = argv[3] |
| 366 | elif len(argv) != 2: |
| 367 | print(__doc__, file=sys.stderr) |
| 368 | return 2 |
| 369 | try: |
| 370 | print(build(argv[0], argv[1], keep)) |
| 371 | except Refused as r: |
| 372 | for line in str(r).splitlines(): |
| 373 | print("build-renderer-tree: refused: " + line, file=sys.stderr) |
| 374 | return 1 |
| 375 | return 0 |
| 376 | |
| 377 | |
| 378 | if __name__ == "__main__": |
| 379 | sys.exit(main(sys.argv[1:])) |
| 380 | |