#!/usr/bin/env python3 """Build the renderer a release ships: renderer.tar.gz, one tree of the pinned packages and its MANIFEST. scripts/build-renderer-tree.py PIN TAR [--tree DIR] PIN is internal/release/renderer.json. Every amd64 package it pins is fetched from its snapshot URL and refused unless its size and SHA-256 are the pin's. Their data members are unpacked, in the pin's order, into one tree, and MANIFEST lists every entry of it, one line each, sorted by path (relative to the tree's root, MANIFEST itself not listed): dir file link A file's mode is 0755 when its owner could execute it and 0644 otherwise: nothing is group or world writable, setuid or setgid. A link's target is relative and resolves, through any links on the way, to an entry inside the tree. Debian links one top-level directory to another with an absolute target (fontconfig-config's /etc/fonts/conf.d); the tree is the renderer's root, so such a target is written as the same path relative to the link, and must then resolve like any other. The build refuses a target that climbs out of the tree or names nothing in it, a member path that is not inside the tree or goes through a link, a name the MANIFEST cannot hold (white space, control characters), two packages that disagree about a path, and a pin whose program is not an executable file. TAR holds MANIFEST and the tree, in path order, with no owner and no times: the same pin gives the same bytes. It is written whole or not at all. The tree is unpacked in a scratch directory beside TAR and removed, unless --tree names a new directory to keep it in. The MANIFEST's SHA-256, printed on stdout, is the pin make release-runner links into the Linux runner (internal/release rendererSHA256). SOURCES is written beside TAR in the same run, from the same checked debs (scripts/renderer-sources.py): each package, its version and where its source is. It is published with the archive. """ import gzip import hashlib import io import json import os import re import shutil import sys import tarfile import tempfile import urllib.request from concurrent.futures import ThreadPoolExecutor import importlib.util _spec = importlib.util.spec_from_file_location("renderer_sources", os.path.join(os.path.dirname(os.path.abspath(__file__)), "renderer-sources.py")) renderer_sources = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(renderer_sources) SNAPSHOT = "https://snapshot.debian.org/archive/" DIGEST = re.compile(r"[0-9a-f]{64}") LINK_DEPTH = 40 class Refused(Exception): pass def fetch(url): with urllib.request.urlopen(url, timeout=600) as r: return r.read() def packages_of(pin): if "arm64" in pin or not isinstance(pin.get("amd64"), list) or not pin["amd64"]: raise Refused("the pin must list amd64 packages, and only amd64") packages = pin["amd64"] names = [p.get("package") for p in packages] if names != sorted(set(names)): raise Refused("the pin's packages are not sorted and unique") for p in packages: url = p.get("url") if not (isinstance(url, str) and url.startswith(SNAPSHOT) and url.endswith(".deb") and isinstance(p.get("sha256"), str) and DIGEST.fullmatch(p["sha256"]) and isinstance(p.get("size"), int) and p["size"] > 0): raise Refused("%s: want a snapshot.debian.org .deb URL, a SHA-256 and a size" % p.get("package")) return packages def checked(p): """The deb the pin names: its bytes, or a refusal.""" data = fetch(p["url"]) if len(data) != p["size"]: raise Refused("%s: got %d bytes, the pin says %d" % (p["package"], len(data), p["size"])) if hashlib.sha256(data).hexdigest() != p["sha256"]: raise Refused("%s: SHA-256 is not the pin's" % p["package"]) return data def data_member(name, deb): """The data.tar of a deb (an ar archive), opened.""" if deb[:8] != b"!\n": raise Refused("%s: not a deb" % name) i, members = 8, {} while i < len(deb): header = deb[i:i + 60] if len(header) != 60 or header[58:60] != b"`\n": raise Refused("%s: a broken ar header" % name) member = header[:16].decode("ascii", "replace").strip().rstrip("/") size = int(header[48:58]) members.setdefault(member, deb[i + 60:i + 60 + size]) i += 60 + size + (size & 1) if not members.get("debian-binary", b"").startswith(b"2."): raise Refused("%s: not a format 2 deb" % name) data = [m for m in members if m.startswith("data.tar")] modes = {"data.tar": "r:", "data.tar.gz": "r:gz", "data.tar.xz": "r:xz"} if len(data) != 1 or data[0] not in modes: raise Refused("%s: want one data.tar, .tar.gz or .tar.xz member, got %s" % (name, data)) return tarfile.open(fileobj=io.BytesIO(members[data[0]]), mode=modes[data[0]]) def holdable(s): """Whether s fits in a MANIFEST field: no white space or control characters, and valid UTF-8.""" try: s.encode("utf-8") except UnicodeEncodeError: return False return bool(s) and not any(c.isspace() or ord(c) < 0x20 or ord(c) == 0x7f for c in s) def member_path(name): """A data.tar member's path inside the tree ("" for its root), or None when it is not one.""" if name in (".", "./"): return "" if name.startswith("./"): name = name[2:] name = name.rstrip("/") parts = name.split("/") if name.startswith("/") or not holdable(name) or any(p in ("", ".", "..") for p in parts): return None return name class Tree: """The unpacked tree: entries by path, mirrored on disk under root.""" def __init__(self, root): self.root = root self.entries = {} # path -> ("dir",) | ("file", sha256, mode) | ("link", target) self.owner = {} def disk(self, path): return os.path.join(self.root, *path.split("/")) def parents(self, path, package): parts = path.split("/") for i in range(1, len(parts)): parent = "/".join(parts[:i]) e = self.entries.get(parent) if e is None: self.entries[parent], self.owner[parent] = ("dir",), package os.mkdir(self.disk(parent)) os.chmod(self.disk(parent), 0o755) elif e[0] != "dir": raise Refused("%s (%s): goes through a link or file of %s" % (path, package, self.owner[parent])) def add(self, package, m, archive): path = member_path(m.name) if path is None: raise Refused("%s: %r is not a path inside the tree the MANIFEST can hold" % (package, m.name)) if path == "": if not m.isdir(): raise Refused("%s: the tree's root is not a directory" % package) return if path == "MANIFEST": raise Refused("%s: ships MANIFEST, the tree's own list" % package) self.parents(path, package) if m.isdir(): entry, body = ("dir",), None elif m.issym(): target = m.linkname if target.startswith("/"): # The tree is the renderer's root: the same path, relative. target = "../" * path.count("/") + target.lstrip("/") if not holdable(target): raise Refused("%s (%s): link target %r is not one the MANIFEST can hold" % (path, package, m.linkname)) entry, body = ("link", target), None elif m.isfile(): body = archive.extractfile(m).read() entry = ("file", hashlib.sha256(body).hexdigest(), 0o755 if m.mode & 0o100 else 0o644) else: raise Refused("%s (%s): only files, directories and links belong in the tree" % (path, package)) old = self.entries.get(path) if old is not None: if old != entry: raise Refused("%s: %s and %s disagree about it" % (path, self.owner[path], package)) return self.entries[path], self.owner[path] = entry, package disk = self.disk(path) if entry[0] == "dir": os.mkdir(disk) os.chmod(disk, 0o755) elif entry[0] == "link": os.symlink(entry[1], disk) else: fd = os.open(disk, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, "wb") as f: f.write(body) os.chmod(disk, entry[2]) def resolve(self, start, target, depth=0): """Where target, read in directory start (a list of names), leads: a list of names from the root, every step an entry of the tree. As Linux resolves a path, every part after the first, including an empty or "." part (a trailing "/" or "/."), needs a directory before it: "f/" and "f/." fail when f is a file.""" if depth > LINK_DEPTH: raise Refused("too many links") here = list(start) for i, name in enumerate(target.split("/")): if i > 0 and self.kind(here) != "dir": raise Refused("%s is not a directory" % "/".join(here)) if name in ("", "."): continue if name == "..": if not here: raise Refused("climbs out of the tree") here.pop() continue path = "/".join(here + [name]) e = self.entries.get(path) if e is None: raise Refused("%s names nothing in the tree" % path) if e[0] == "link": here = self.resolve(here, e[1], depth + 1) else: here.append(name) return here def kind(self, names): return "dir" if not names else self.entries["/".join(names)][0] def check(self, program): problems = [] for path, e in sorted(self.entries.items()): if e[0] == "link": try: self.resolve(path.split("/")[:-1], e[1]) except Refused as r: problems.append("%s -> %s (%s): %s" % (path, e[1], self.owner[path], r)) try: end = "/".join(self.resolve([], program)) ok = self.entries[end][0] == "file" and self.entries[end][2] == 0o755 except (Refused, KeyError): ok = False if not ok: problems.append("%s: the pin's program is not an executable file in the tree" % program) if problems: raise Refused("\n".join(problems)) def manifest(self): lines = [] for path, e in sorted(self.entries.items()): if e[0] == "dir": lines.append("dir %s\n" % path) elif e[0] == "link": lines.append("link %s %s\n" % (path, e[1])) else: lines.append("file %s %s %04o\n" % (path, e[1], e[2])) return "".join(lines).encode("utf-8") def write_tar(tree, manifest, out): """Write the tar to out: MANIFEST and every entry in path order, no owner, no times, gzip with no name or time.""" def info(path, mode, kind=tarfile.REGTYPE, size=0, link=""): ti = tarfile.TarInfo(path) ti.type, ti.mode, ti.size, ti.linkname = kind, mode, size, link ti.mtime, ti.uid, ti.gid, ti.uname, ti.gname = 0, 0, 0, "", "" return ti entries = dict(tree.entries) entries["MANIFEST"] = None with gzip.GzipFile(filename="", mode="wb", fileobj=out, compresslevel=9, mtime=0) as gz: with tarfile.open(fileobj=gz, mode="w|", format=tarfile.PAX_FORMAT, encoding="utf-8") as tar: for path in sorted(entries): e = entries[path] if e is None: tar.addfile(info(path, 0o644, size=len(manifest)), io.BytesIO(manifest)) elif e[0] == "dir": tar.addfile(info(path, 0o755, tarfile.DIRTYPE)) elif e[0] == "link": tar.addfile(info(path, 0o777, tarfile.SYMTYPE, link=e[1])) else: with open(tree.disk(path), "rb") as f: tar.addfile(info(path, e[2], size=os.fstat(f.fileno()).st_size), f) def build(pin_path, tar_path, keep): with open(pin_path) as f: pin = json.load(f) packages = packages_of(pin) program = pin.get("program") if not isinstance(program, str) or member_path(program) in (None, ""): raise Refused("the pin names no program") out_dir = os.path.dirname(os.path.abspath(tar_path)) with ThreadPoolExecutor(max_workers=4) as pool: debs = list(pool.map(checked, packages)) try: sources = renderer_sources.sources(pin, debs).encode("utf-8") except renderer_sources.Refused as r: raise Refused(str(r)) if keep: os.mkdir(keep, 0o755) root, scratch = keep, None else: scratch = tempfile.mkdtemp(prefix=".renderer-tree-", dir=out_dir) root = scratch fd, partial = tempfile.mkstemp(prefix=".renderer-", suffix=".tar.gz.partial", dir=out_dir) try: tree = Tree(root) for p, deb in zip(packages, debs): with data_member(p["package"], deb) as archive: for m in archive: tree.add(p["package"], m, archive) tree.check(program) manifest = tree.manifest() if keep: # 0644 as in the tar, whatever the umask: the verifier # refuses a group or world writable MANIFEST. path = os.path.join(keep, "MANIFEST") with open(path, "wb") as f: f.write(manifest) os.chmod(path, 0o644) with os.fdopen(fd, "wb") as out: fd = None write_tar(tree, manifest, out) os.chmod(partial, 0o644) sources_path = os.path.join(out_dir, "SOURCES") with open(sources_path + ".partial", "wb") as f: f.write(sources) os.chmod(sources_path + ".partial", 0o644) os.replace(sources_path + ".partial", sources_path) os.replace(partial, tar_path) partial = None except BaseException: if keep: shutil.rmtree(keep, ignore_errors=True) raise finally: if fd is not None: os.close(fd) if partial is not None: os.unlink(partial) if scratch is not None: shutil.rmtree(scratch, ignore_errors=True) files = sum(1 for e in tree.entries.values() if e[0] == "file") print("renderer: %d packages, %d entries (%d files), %s: %d bytes" % ( len(packages), len(tree.entries), files, tar_path, os.path.getsize(tar_path)), file=sys.stderr) return hashlib.sha256(manifest).hexdigest() def main(argv): keep = None if len(argv) == 4 and argv[2] == "--tree": keep = argv[3] elif len(argv) != 2: print(__doc__, file=sys.stderr) return 2 try: print(build(argv[0], argv[1], keep)) except Refused as r: for line in str(r).splitlines(): print("build-renderer-tree: refused: " + line, file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))