#!/usr/bin/env python3 """Measure selected-member reads and full listings on three synthetic TAR files.""" import argparse from datetime import datetime, timezone import hashlib import io import json import os from pathlib import Path import platform import shutil import subprocess import tarfile import tempfile PAYLOADS = {"record.txt": b"first\n", "tail.txt": b"later\n"} METHODS = { "first-occurrence": ["-xOf", "fixture.tar", "--occurrence=1", "--", "record.txt"], "first-default": ["-xOf", "fixture.tar", "--", "record.txt"], "list-all": ["-tf", "fixture.tar"], "tail-default": ["-xOf", "fixture.tar", "--", "tail.txt"], } def require(ok, message): if not ok: raise RuntimeError(message) def digest(data): return hashlib.sha256(data).hexdigest() def fixtures(): buffer = io.BytesIO() with tarfile.open(fileobj=buffer, mode="w", format=tarfile.USTAR_FORMAT) as archive: for name, payload in PAYLOADS.items(): info = tarfile.TarInfo(name) info.size, info.mode, info.mtime = len(payload), 0o600, 0 archive.addfile(info, io.BytesIO(payload)) clean = buffer.getvalue() with tarfile.open(fileobj=io.BytesIO(clean), mode="r:") as archive: tail = archive.getmember("tail.txt") header, data = tail.offset, tail.offset_data variants = [] for name, offset in [("clean", None), ("tail-header-bit", header), ("tail-payload-bit", data)]: raw = bytearray(clean) if offset is not None: raw[offset] ^= 1 changes = [i for i, (a, b) in enumerate(zip(clean, raw)) if a != b] require(changes == ([] if offset is None else [offset]), "Unexpected mutation") variants.append((name, bytes(raw), offset)) return clean, variants, {"tailHeader": header, "tailPayload": data} def run(binary, args, cwd): env = dict(os.environ) env.pop("TAR_OPTIONS", None) env.update(LC_ALL="C", TZ="UTC") return subprocess.run([binary, *args], cwd=cwd, env=env, capture_output=True, timeout=10, check=False) def expected(case, method): if method == "list-all": return (2, b"record.txt\n") if case == "tail-header-bit" else (0, b"record.txt\ntail.txt\n") if method == "first-occurrence": return 0, b"first\n" if method == "first-default": return (2 if case == "tail-header-bit" else 0), b"first\n" if case == "tail-header-bit": return 2, b"" return 0, (b"mater\n" if case == "tail-payload-bit" else b"later\n") def observe(work_root=None): binary = shutil.which("tar") require(binary is not None, "GNU tar is required") version = run(binary, ["--version"], work_root) require(version.returncode == 0, "Cannot identify tar") version_text = version.stdout.decode().splitlines()[0] require("GNU tar" in version_text, "This protocol requires GNU tar") clean, variants, offsets = fixtures() cases = [] with tempfile.TemporaryDirectory(prefix="hesela-tar-coverage-", dir=work_root) as temp: root = Path(temp) for case_id, raw, offset in variants: directory = root / case_id directory.mkdir() path = directory / "fixture.tar" path.write_bytes(raw) observations = [] for method, args in METHODS.items(): proc = run(binary, args, directory) code, output = expected(case_id, method) require((proc.returncode, proc.stdout) == (code, output), case_id + "/" + method + ": observed behavior differs from protocol") require(bool(proc.stderr) == (code != 0), "Unexpected diagnostic presence") target = (None if method == "list-all" else "tail.txt" if method == "tail-default" else "record.txt") match = None if target is None else proc.stdout == PAYLOADS[target] observations.append({ "method": method, "command": ["tar", *args], "exitCode": proc.returncode, "stdoutText": proc.stdout.decode(), "stdoutBytes": len(proc.stdout), "stdoutSha256": digest(proc.stdout), "stderr": proc.stderr.decode(), "target": target, "matchesExpectedPayload": match, "selectedPayloadAccepted": None if target is None else code == 0 and match, }) require(path.read_bytes() == raw, "Input archive changed") cases.append({ "id": case_id, "tarBytes": len(raw), "tarSha256": digest(raw), "matchesTrustedArchive": raw == clean, "mutation": None if offset is None else { "offset": offset, "xorMask": 1, "before": clean[offset], "after": raw[offset], "region": "header" if case_id == "tail-header-bit" else "payload", }, "observations": observations, }) return { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "kind": "designed software conformance demonstration", "environment": {"python": platform.python_version(), "tar": version_text, "system": platform.system(), "machine": platform.machine(), "tarBinarySha256": digest(Path(binary).read_bytes()), "tarfileModuleSha256": digest(Path(tarfile.__file__).read_bytes())}, "scriptSha256": digest(Path(__file__).read_bytes()), "design": { "format": "USTAR", "input": "Plain TAR; no compression wrapper or external archive.", "offsets": offsets, "trustedArchiveSha256": digest(clean), "expectedPayloads": {name: {"text": payload.decode(), "bytes": len(payload), "sha256": digest(payload)} for name, payload in PAYLOADS.items()}, "acceptance": "Selected payload: exit zero plus exact expected bytes. Listing has no payload oracle.", "limits": "Three designed fixtures, not failure rates or a general archive validator. No syscall read tracing, hostile paths, links, metadata restore, power loss or compressed-input coverage.", }, "sources": ["https://www.gnu.org/software/tar/manual/html_node/Option-Summary.html", "https://www.gnu.org/software/tar/manual/html_node/Standard.html"], "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 output: json.dump(report, output, indent=2) output.write("\n") print("Verified 3 synthetic TAR fixtures and 12 reader operations.") if __name__ == "__main__": main()