From 10bd70bca4ffccb612d0c2944ef566056dbf7624 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:47:13 +0100 Subject: [PATCH] feat: look files up by hash in Software Heritage Software Heritage archives every public forge, deleted repositories included, and serves a file by its sha1 or sha256. auto_fetch asks it before archive.org (step 3b), and --sha1 looks files up without a platform: the database first, then Software Heritage and archive.org's per-file metadata. What it finds is re-hashed and written to tmp/acquire/, never into bios/. --- scripts/auto_fetch.py | 125 +++++++++++++++++++++++++++++++- tests/test_auto_fetch_lookup.py | 111 ++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+), 1 deletion(-) create mode 100644 tests/test_auto_fetch_lookup.py diff --git a/scripts/auto_fetch.py b/scripts/auto_fetch.py index 08d7b3afe..aed1bfe6a 100644 --- a/scripts/auto_fetch.py +++ b/scripts/auto_fetch.py @@ -21,6 +21,7 @@ import hashlib import http.client import json import os +import re import subprocess import sys import urllib.error @@ -62,6 +63,12 @@ PUBLIC_REPOS = [ "https://raw.githubusercontent.com/BatoceraPLUS/Batocera.PLUS-bios/main/{name}", ] +# Software Heritage archives the source of every public forge, deleted +# repositories and rewritten histories included, and finds a file by its +# hash: a ROM once committed anywhere answers here even when no forge still +# serves it. Anonymous use allows 120 requests an hour. +SOFTWARE_HERITAGE = "https://archive.softwareheritage.org/api/1/content" + ARCHIVE_ORG_COLLECTIONS = [ "RetroarchSystemFiles", "retroarch_bios", @@ -306,6 +313,26 @@ def step3_search_public_repos(entry: dict) -> bytes | None: return None +def step3b_software_heritage(entry: dict) -> bytes | None: + """Ask Software Heritage for the file by each accepted sha1, then + sha256: its archive answers by content, whatever the file was named.""" + for field in ("sha1", "sha256"): + for value in sorted(_accepted(entry, field)): + url = f"{SOFTWARE_HERITAGE}/{field}:{value}/raw/" + try: + req = urllib.request.Request( + url, headers={"User-Agent": "retrobios-fetch/1.0"} + ) + with urllib.request.urlopen(req, timeout=60) as resp: + data = _read_limited(resp) + except urllib.error.URLError as exc: + _unanswered(url, exc) + continue + if data is not None and verify_content(data, entry): + return data + return None + + def step4_search_archive_org(entry: dict) -> bytes | None: """Search archive.org firmware collections by direct download.""" name = entry["name"] @@ -426,7 +453,7 @@ def fetch_missing( continue if dry_run: - print(" [DRY RUN] Would search branches, repos, archive.org") + print(" [DRY RUN] Would search branches, repos, Software Heritage, archive.org") still_missing.append(entry) stats["not_found"] += 1 continue @@ -445,6 +472,13 @@ def fetch_missing( stats["found"] += 1 continue + data = step3b_software_heritage(entry) + if data: + path = place_file(data, entry, bios_dir, db) + print(f" [3b] Found in Software Heritage, saved to: {path}") + stats["found"] += 1 + continue + data = step4_search_archive_org(entry) if data: path = place_file(data, entry, bios_dir, db) @@ -467,6 +501,84 @@ def fetch_missing( return {"stats": stats, "still_missing": still_missing} +ACQUIRE_DIR = Path("tmp") / "acquire" + + +def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False) -> int: + """--sha1: each file looked for by its hash alone, without a platform. + Found bytes are verified, then saved as tmp/acquire/, never into + bios/: placing a file is a decision the collection makes. 0 when every + one was found, 1 otherwise.""" + missing = 0 + for raw in sha1s: + sha1 = raw.strip().lower() + if not re.fullmatch(r"[0-9a-f]{40}", sha1): + print(f" {raw}: not a sha1", file=sys.stderr) + missing += 1 + continue + entry = {"name": sha1, "sha1": sha1, "system": ""} + _UNANSWERED.clear() + held = step1_crossref_db(entry, db) + if held: + print(f" {sha1}: already held at {held}") + continue + if dry_run: + print(f" {sha1}: would ask Software Heritage and archive.org") + continue + data = step3b_software_heritage(entry) + where = "Software Heritage" + if data is None: + data, where = _archive_org_by_sha1(sha1), "archive.org" + if data is None: + note = f", {len(_UNANSWERED)} source(s) did not answer" if _UNANSWERED else "" + print(f" {sha1}: not found{note}") + missing += 1 + continue + ACQUIRE_DIR.mkdir(parents=True, exist_ok=True) + out = ACQUIRE_DIR / sha1 + out.write_bytes(data) + print(f" {sha1}: found in {where}, {len(data)} bytes, saved to {out}") + return 1 if missing else 0 + + +def _archive_org_by_sha1(sha1: str) -> bytes | None: + """The first archive.org file whose metadata names sha1, read and checked.""" + search = ("https://archive.org/advancedsearch.php?q=" + f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5") + try: + with urllib.request.urlopen(urllib.request.Request( + search, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=30) as resp: + docs = json.loads(resp.read()).get("response", {}).get("docs", []) + except (urllib.error.URLError, json.JSONDecodeError) as exc: + _unanswered(search, exc) + return None + for doc in docs: + identifier = doc.get("identifier") + meta = f"https://archive.org/metadata/{identifier}/files" + try: + with urllib.request.urlopen(urllib.request.Request( + meta, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=30) as resp: + files = json.loads(resp.read()).get("result", []) + except (urllib.error.URLError, json.JSONDecodeError) as exc: + _unanswered(meta, exc) + continue + for item in files: + if str(item.get("sha1", "")).lower() != sha1: + continue + url = (f"https://archive.org/download/{identifier}/" + f"{urllib.parse.quote(item['name'])}") + try: + with urllib.request.urlopen(urllib.request.Request( + url, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=60) as resp: + data = _read_limited(resp) + except urllib.error.URLError as exc: + _unanswered(url, exc) + continue + if data is not None and hashlib.sha1(data).hexdigest() == sha1: + return data + return None + + CONTRIBUTING_URL = "https://github.com/Abdess/retrobios/blob/main/CONTRIBUTING.md" @@ -516,8 +628,19 @@ def main() -> None: parser.add_argument( "--create-issues", action="store_true", help="Output GitHub Issue bodies" ) + parser.add_argument( + "--sha1", action="append", metavar="SHA1", + help="look for one file by its sha1 in the database, Software Heritage and " + "archive.org, and save what is found under tmp/acquire/ (repeatable)", + ) args = parser.parse_args() require_directory(args.bios_dir) + if args.sha1: + if args.platform or args.all or args.create_issues: + parser.error("--sha1 looks for files by hash alone: it takes no " + "--platform, --all or --create-issues") + db = load_database(args.db) if os.path.exists(args.db) else {"files": {}} + sys.exit(lookup_sha1s(args.sha1, db, args.dry_run)) if not os.path.exists(args.db): print(f"Error: {args.db} not found. Run generate_db.py first.", file=sys.stderr) diff --git a/tests/test_auto_fetch_lookup.py b/tests/test_auto_fetch_lookup.py new file mode 100644 index 000000000..e166df0cd --- /dev/null +++ b/tests/test_auto_fetch_lookup.py @@ -0,0 +1,111 @@ +"""auto_fetch.py looks a file up by its hash: Software Heritage answers by +content, and nothing it serves is kept unless every declared hash holds.""" + +from __future__ import annotations + +import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache + +import contextlib +import hashlib +import io +import os +import sys +import tempfile +import unittest +import urllib.error +from pathlib import Path +from unittest import mock + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT / "scripts")) + +import auto_fetch # noqa: E402 + +PAYLOAD = b"keyboard mcu" +SHA1 = hashlib.sha1(PAYLOAD).hexdigest() + + +class _Answer(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def _serving(payloads: dict[str, bytes]): + """An urlopen that answers the URLs it knows and 404s the others.""" + asked: list[str] = [] + + def urlopen(request, timeout=None): + url = request.full_url + asked.append(url) + for prefix, body in payloads.items(): + if url.startswith(prefix): + return _Answer(body) + raise urllib.error.HTTPError(url, 404, "Not Found", {}, None) + + return urlopen, asked + + +class SoftwareHeritageAnswersByContent(unittest.TestCase): + def test_the_bytes_it_serves_are_kept_when_the_hash_holds(self): + urlopen, asked = _serving({f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD}) + with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen): + data = auto_fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1}) + self.assertEqual(data, PAYLOAD) + self.assertEqual(asked, [f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/"]) + + def test_other_bytes_under_the_hash_are_refused(self): + urlopen, _asked = _serving({auto_fetch.SOFTWARE_HERITAGE: b"something else"}) + with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen): + data = auto_fetch.step3b_software_heritage({"name": "x", "sha1": SHA1}) + self.assertIsNone(data) + + def test_an_absent_file_is_not_counted_as_a_source_that_did_not_answer(self): + urlopen, _asked = _serving({}) + auto_fetch._UNANSWERED.clear() + with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen): + self.assertIsNone(auto_fetch.step3b_software_heritage({"name": "x", "sha1": SHA1})) + self.assertEqual(auto_fetch._UNANSWERED, []) + + +class LookupBySha1(unittest.TestCase): + def setUp(self): + self.cwd = os.getcwd() + self.root = Path(tempfile.mkdtemp()) + os.chdir(self.root) + self.addCleanup(os.chdir, self.cwd) + + def test_a_found_file_goes_to_tmp_acquire_never_to_bios(self): + urlopen, _asked = _serving({f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD}) + with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \ + contextlib.redirect_stdout(io.StringIO()) as out: + code = auto_fetch.lookup_sha1s([SHA1.upper()], {"files": {}}) + self.assertEqual(code, 0) + self.assertEqual((self.root / "tmp" / "acquire" / SHA1).read_bytes(), PAYLOAD) + self.assertFalse((self.root / "bios").exists()) + self.assertIn("found in Software Heritage", out.getvalue()) + + def test_a_held_file_is_named_and_not_fetched(self): + urlopen, asked = _serving({}) + db = {"files": {SHA1: {"path": "bios/Commodore/Amiga/x.rom"}}} + with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \ + contextlib.redirect_stdout(io.StringIO()) as out: + code = auto_fetch.lookup_sha1s([SHA1], db) + self.assertEqual((code, asked), (0, [])) + self.assertIn("already held at bios/Commodore/Amiga/x.rom", out.getvalue()) + + def test_nothing_found_and_a_malformed_hash_end_with_one(self): + urlopen, _asked = _serving({}) + with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \ + contextlib.redirect_stdout(io.StringIO()) as out, \ + contextlib.redirect_stderr(io.StringIO()) as err: + code = auto_fetch.lookup_sha1s([SHA1, "not-a-hash"], {"files": {}}) + self.assertEqual(code, 1) + self.assertIn(f"{SHA1}: not found", out.getvalue()) + self.assertIn("not-a-hash: not a sha1", err.getvalue()) + + +if __name__ == "__main__": + unittest.main()