#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch the pinned references into reference/ (git-ignored), or verify what is there. python -I scripts/fetch_references.py # fetch whatever is missing python -I scripts/fetch_references.py --verify # hash what is present; fetch nothing python -I scripts/fetch_references.py --only shaker27.dsk Every entry of scripts/pinned_files.json names a URL, a path under reference/ and a SHA-256. A download whose hash differs from its pin is refused and not kept. Nothing fetched is executed or unpacked by this script, and nothing fetched is committed. Before an entry is added, its site's robots.txt is read (docs/sources.md, "Site rules"): a site that blocks AI crawlers or serves an anti-AI challenge is not fetched from, and no copy of it is fetched from elsewhere to get round that. The Wayback Machine copies pinned here are of pages whose own site had no such rule when it was last served (Kevin Thacker's cpctech pages, now gone from their host). Wayback entries are fetched slowly (a pause between requests), because the archive refuses connections from a client that asks too fast. """ from __future__ import annotations import argparse import hashlib import json import subprocess import sys import tempfile import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PINS = ROOT / "scripts" / "pinned_files.json" USER_AGENT = "Mozilla/5.0 (reference fetch)" WAYBACK_PAUSE = 8.0 def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1 << 20), b""): digest.update(block) return digest.hexdigest() def download(url: str, target: Path) -> None: for attempt in range(3): result = subprocess.run( ["curl", "-sSfL", "--max-time", "600", "-A", USER_AGENT, "-o", str(target), url], capture_output=True, check=False, ) if not result.returncode: return time.sleep(30 * (attempt + 1)) raise OSError(result.stderr.decode("utf-8", "replace").strip()) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="hash what is present, fetch nothing") parser.add_argument("--only", action="append", default=[], help="file name(s) to handle") args = parser.parse_args() entries = json.loads(PINS.read_text(encoding="utf-8")) ok = missing = bad = 0 for entry in entries: path = ROOT / entry["path"] if args.only and path.name not in args.only: continue if path.exists(): if sha256(path) == entry["sha256"]: ok += 1 else: print(f"MISMATCH {entry['path']}") bad += 1 continue if args.verify: print(f"missing {entry['path']}") missing += 1 continue path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: partial = Path(handle.name) try: download(entry["url"], partial) except OSError as error: partial.unlink(missing_ok=True) print(f"ERROR {entry['url']}: {error}") bad += 1 continue digest = sha256(partial) if digest != entry["sha256"]: partial.unlink() print(f"REFUSED {entry['path']}: SHA-256 {digest}, pinned {entry['sha256']}") bad += 1 continue partial.replace(path) print(f"fetched {entry['path']}") ok += 1 if "web.archive.org" in entry["url"]: time.sleep(WAYBACK_PAUSE) print(f"{ok} ok, {missing} missing, {bad} bad, of {len(entries)} pinned") return 1 if missing or bad else 0 if __name__ == "__main__": sys.exit(main())