#!/usr/bin/env python3 """Measure TAR member selection on self-created, bounded fixtures only.""" import argparse from collections import Counter from datetime import datetime, timezone import gzip import hashlib import io import json import os from pathlib import Path import platform import shutil import subprocess import tarfile import tempfile import zlib NAME = "record.txt" PAYLOADS = {"A": b"generation=A\n", "B": b"generation=B\n"} DESIGNS = {"a-b": ["A", "B"], "b-a": ["B", "A"], "b-b": ["B", "B"], "single-b": ["B"]} METHODS = ["gnu-disk", "gnu-stdout", "gnu-first", "gnu-second", "python-name", "python-first-member", "python-members", "python-name-loop"] def require(ok, message): if not ok: raise RuntimeError(message) def digest(data): return hashlib.sha256(data).hexdigest() def make_archive(order): buffer = io.BytesIO() with tarfile.open(fileobj=buffer, mode="w", format=tarfile.USTAR_FORMAT) as archive: for label in order: info = tarfile.TarInfo(NAME) info.size = len(PAYLOADS[label]) info.mtime = 200 if label == "A" else 100 info.mode = 0o600 archive.addfile(info, io.BytesIO(PAYLOADS[label])) return buffer.getvalue() def run_tar(binary, args, cwd): env = dict(os.environ) env.pop("TAR_OPTIONS", None) env.update(LC_ALL="C", TZ="UTC") proc = subprocess.run([binary, *args], cwd=cwd, env=env, capture_output=True, timeout=10, check=False) return proc def observe(work_root=None): binary = shutil.which("tar") require(binary is not None, "GNU tar is required") version = run_tar(binary, ["--version"], work_root).stdout.decode().splitlines()[0] require("GNU tar" in version, "This protocol requires GNU tar") cases = [] with tempfile.TemporaryDirectory(prefix="hesela-tar-members-", dir=work_root) as temporary: root = Path(temporary) for case_id, order in DESIGNS.items(): directory = root / case_id directory.mkdir() raw = make_archive(order) compressed = gzip.compress(raw, mtime=0) decoded = gzip.decompress(compressed) require(decoded == raw, "Outer gzip round trip changed TAR bytes") archive_path = directory / "fixture.tar" archive_path.write_bytes(decoded) before = digest(archive_path.read_bytes()) listing = run_tar(binary, ["-tf", "fixture.tar"], directory) require(listing.returncode == 0, "Listing failed") require(listing.stdout.decode().splitlines() == [NAME] * len(order), "Member count mismatch") with tarfile.open(archive_path, "r:") as archive: members = archive.getmembers() inventory = [] counts = Counter() for member in members: require(member.isreg() and member.name == NAME, "Unexpected fixture member") counts[member.name] += 1 payload = archive.extractfile(member).read() inventory.append({"name": member.name, "occurrence": counts[member.name], "headerOffset": member.offset, "mtime": member.mtime, "bytes": member.size, "sha256": digest(payload)}) observations = [] for method in METHODS: exit_code, stderr, command = None, "", None if method.startswith("gnu-"): flags = { "gnu-disk": ["-xf", "fixture.tar", "-C", "restored", "--", NAME], "gnu-stdout": ["-xOf", "fixture.tar", "--", NAME], "gnu-first": ["-xOf", "fixture.tar", "--occurrence=1", "--", NAME], "gnu-second": ["-xOf", "fixture.tar", "--occurrence=2", "--", NAME], }[method] if method == "gnu-disk": (directory / "restored").mkdir() proc = run_tar(binary, flags, directory) exit_code, stderr, command = proc.returncode, proc.stderr.decode(), ["tar", *flags] output = ((directory / "restored" / NAME).read_bytes() if method == "gnu-disk" else proc.stdout) else: with tarfile.open(archive_path, "r:") as archive: members = archive.getmembers() if method == "python-name": output = archive.extractfile(NAME).read() elif method == "python-first-member": output = archive.extractfile(members[0]).read() elif method == "python-members": output = b"".join(archive.extractfile(m).read() for m in members) else: output = b"".join(archive.extractfile(m.name).read() for m in members) success = exit_code in (None, 0) expected = { "gnu-disk": PAYLOADS[order[-1]], "gnu-stdout": b"".join(PAYLOADS[x] for x in order), "gnu-first": PAYLOADS[order[0]], "gnu-second": PAYLOADS[order[1]] if len(order) > 1 else b"", "python-name": PAYLOADS[order[-1]], "python-first-member": PAYLOADS[order[0]], "python-members": b"".join(PAYLOADS[x] for x in order), "python-name-loop": PAYLOADS[order[-1]] * len(order), }[method] require(output == expected, case_id + "/" + method + ": unexpected bytes") require(success == (method != "gnu-second" or len(order) > 1), case_id + "/" + method + ": unexpected status") observations.append({"method": method, "command": command, "exitCode": exit_code, "callSucceeded": success, "stderr": stderr, "outputBytes": len(output), "outputSha256": digest(output), "outputText": output.decode(), "matchesRequiredB": output == PAYLOADS["B"], "accepted": success and output == PAYLOADS["B"]}) require(digest(archive_path.read_bytes()) == before, "Archive mutated during reads") cases.append({"id": case_id, "order": order, "tarBytes": len(raw), "tarSha256": before, "gzipSha256": digest(compressed), "gzipRoundTripExact": True, "archiveUnchanged": True, "memberCount": len(inventory), "distinctNames": len(counts), "duplicateNameRejectedByStrictPolicy": any(n > 1 for n in counts.values()), "listingExitCode": listing.returncode, "members": inventory, "observations": observations}) return {"schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "kind": "designed software conformance demonstration", "environment": {"python": platform.python_version(), "tar": version, "system": platform.system(), "machine": platform.machine(), "zlib": zlib.ZLIB_RUNTIME_VERSION, "tarBinarySha256": digest(Path(binary).read_bytes()), "tarfileModuleSha256": digest(Path(tarfile.__file__).read_bytes())}, "scriptSha256": digest(Path(__file__).read_bytes()), "acceptance": {"requiredPayload": PAYLOADS["B"].decode(), "requiredSha256": digest(PAYLOADS["B"]), "rule": "Successful call and exact equality with independently chosen B payload."}, "design": {"format": "USTAR", "name": NAME, "mtimeByPayload": {"A": 200, "B": 100}, "input": "Synthetic fixtures only; plain TAR after an exact gzip round trip.", "limits": "No hostile archive, symlink, path alias, metadata restoration, crash or field-rate claim. Not a general archive validator."}, "sources": [ "https://www.gnu.org/software/tar/manual/html_node/append.html", "https://www.gnu.org/software/tar/manual/html_node/Writing-to-Standard-Output.html", "https://www.gnu.org/software/tar/manual/html_node/Option-Summary.html", "https://docs.python.org/3.12/library/tarfile.html#tarfile.TarFile.getmember"], "cases": cases} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, default=Path.cwd()) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() require(args.work_root.is_dir(), "Work root must already exist") require(not args.output.exists(), "Refusing to overwrite an existing output") report = observe(args.work_root) with args.output.open("x", encoding="utf-8") as handle: json.dump(report, handle, indent=2) handle.write("\n") print("Verified 4 designed archives and 32 reader operations.") if __name__ == "__main__": main()