diff --git a/scripts/core/ziptools.py b/scripts/core/ziptools.py index 322b084ba..1b5dae489 100644 --- a/scripts/core/ziptools.py +++ b/scripts/core/ziptools.py @@ -8,6 +8,7 @@ from __future__ import annotations from dataclasses import dataclass import functools +import io import os import re import stat @@ -33,6 +34,18 @@ def check_inside_zip(container: str, file_name: str, expected_md5: str) -> str: container, info.st_size, info.st_mtime_ns, file_name.casefold(), expected_md5 != "", ) + return _inside_zip_answer(found, expected_md5) + + +def check_inside_zip_data(data: bytes, file_name: str, expected_md5: str) -> str: + """check_inside_zip on the bytes of an archive, such as a pack member.""" + found = _read_member_md5( + io.BytesIO(data), file_name.casefold(), expected_md5 != "" + ) + return _inside_zip_answer(found, expected_md5) + + +def _inside_zip_answer(found: str, expected_md5: str) -> str: if found in ("not_in_zip", "error"): return found if expected_md5 == "": @@ -51,8 +64,12 @@ def _member_md5( members 4 788 times. Keyed by the archive's size and mtime, so a rewritten archive is read again. """ + return _read_member_md5(container, folded, hashed) + + +def _read_member_md5(source: str | io.BytesIO, folded: str, hashed: bool) -> str: try: - with zipfile.ZipFile(container) as archive: + with zipfile.ZipFile(source) as archive: for fname in archive.namelist(): if fname.casefold() != folded: continue diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index f2cdf230e..1b67ad89f 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -13,14 +13,16 @@ from typing import TYPE_CHECKING, TypedDict from core.artifacts import build_timestamp from packs.paths import MEDIA_MARKER, has_path_conflict from core.ziptools import build_zip_contents_index -from core.ziptools import check_inside_zip from resolve.nativemode import digest_algorithm, platform_mode -from resolve.validation import baseline_verdict, digest_verdict +from resolve.validation import ( + baseline_verdict, digest_verdict, inner_rom_check, inner_rom_data_check, +) from resolve.nativemode import hash_mismatch_excludes_file -import hashlib import sys from resolve.cores import filter_systems_by_target -from core.hashing import compute_hashes, file_digest, md5_composite_of, parse_md5_list, stream_hashes +from core.hashing import ( + compute_hashes, file_digest, md5_composite_of, md5sum, parse_hash_list, stream_hashes, +) from core.options import reject_unknown import io from model.profiles import load_emulator_profiles @@ -56,7 +58,8 @@ def _members_are_held(data: bytes, by_md5: dict, held_inside: dict) -> bool: if not members: return False for info in members: - digest = hashlib.md5(archive.read(info)).hexdigest() + with archive.open(info) as stream: + digest = md5sum(stream) if digest not in by_md5 and digest not in held_inside: return False except (zipfile.BadZipFile, OSError): @@ -327,25 +330,6 @@ def generate_sha256sums(output_dir: str) -> str | None: print(f"\n{sums_path}: {len(entries)} pack checksums") return sums_path -def _hash_matches(declared: str, actual: str) -> bool: - """Compare a declared hash value against an actual hex digest. - - Handles comma-separated multi-hash lists and uppercase (Recalbox) - and MD5s shorter than 32 characters: a declared value shorter than - the digest matches by prefix. - """ - actual = actual.lower() - for cand in declared.split(","): - cand = cand.strip().lower() - if not cand: - continue - if len(cand) < len(actual): - if actual.startswith(cand): - return True - elif actual == cand: - return True - return False - def _check_member_hash( zf: zipfile.ZipFile, member: str, file_entry: dict, mode: str, rule: str = "" ) -> str | None: @@ -356,30 +340,23 @@ def _check_member_hash( (Batocera hashes a ROM inside the ZIP, matched case-insensitively). Returns an error string, or None when the member passes. """ - declared = str(file_entry.get(mode) or "").strip() - if not declared: - return None - zipped_file = file_entry.get("zipped_file") if zipped_file: - import io + # checkInsideZip runs with an empty md5 too, and needs the member. + verdict = inner_rom_data_check(file_entry, zf.read(member)) + if verdict == "ok": + return None + if verdict == "not_in_zip": + return f"{member}: {zipped_file} not found inside ZIP" + if verdict == "error": + return f"{member}: {zipped_file} unreadable inside ZIP" + return ( + f"{member}: {zipped_file} inside-zip md5 != declared " + f"{', '.join(parse_hash_list(file_entry.get('md5')))}" + ) - try: - with zipfile.ZipFile(io.BytesIO(zf.read(member))) as inner: - want = zipped_file.casefold() - target = next( - (n for n in inner.namelist() if n.casefold() == want), None - ) - if target is None: - return f"{member}: {zipped_file} not found inside ZIP" - actual = hashlib.md5(inner.read(target)).hexdigest() - except zipfile.BadZipFile: - return f"{member}: not a valid ZIP" - if not _hash_matches(declared, actual): - return ( - f"{member}: {zipped_file} inside-zip md5 {actual} " - f"!= declared {declared}" - ) + declared = str(file_entry.get(mode) or "").strip() + if not declared: return None # The frontend's own rule, as the builder and verify apply it: RomM's @@ -421,10 +398,9 @@ def _repo_satisfies_declaration( by_name = db.get("indexes", {}).get("by_name", {}) for fe in entries: - declared = str(fe.get(mode) or "").strip() - if not declared: + hashes = parse_hash_list(fe.get(mode)) + if not hashes: continue - hashes = [h.strip().lower() for h in declared.split(",") if h.strip()] for h in hashes: if mode == "sha1": entry = files_db.get(h) @@ -451,12 +427,11 @@ def _repo_satisfies_declaration( def _repo_holds_member(file_entry: dict, db: dict) -> bool: """Whether a held archive of that name carries the declared member.""" files_db = db.get("files", {}) - declared = parse_md5_list(file_entry.get("md5")) for sha1 in db.get("indexes", {}).get("by_name", {}).get(file_entry.get("name", ""), []): path = (files_db.get(sha1) or {}).get("path", "") if not path.endswith(".zip") or not os.path.exists(path): continue - if any(check_inside_zip(path, file_entry["zipped_file"], m) == "ok" for m in declared): + if inner_rom_check(file_entry, path) == "ok": return True return False @@ -905,7 +880,7 @@ def _native_hash_errors( checkable = [ fe for fe in decl_entries - if str(fe.get(digest) or "").strip() + if fe.get("zipped_file") or str(fe.get(digest) or "").strip() ] if not checkable: continue diff --git a/scripts/resolve/validation.py b/scripts/resolve/validation.py index e5f825776..46da34c65 100644 --- a/scripts/resolve/validation.py +++ b/scripts/resolve/validation.py @@ -26,7 +26,7 @@ from core.hashing import compute_hashes, parse_hash_list from core.paths import BIOS_DIR, sanitize_pack_path from core.hashing import md5_composite, parse_md5_list from resolve.nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file -from core.ziptools import check_inside_zip +from core.ziptools import check_inside_zip, check_inside_zip_data if TYPE_CHECKING: from typing_extensions import Unpack @@ -1051,10 +1051,25 @@ def inner_rom_check(file_entry: dict, local_path: str) -> str: matches, else for the last one tried. The pack and the install manifest both read it, so a file one of them ships is a file the other lists. """ - declared = parse_md5_list(file_entry.get("md5")) + return _first_accepted_md5( + file_entry, + lambda md5: check_inside_zip(local_path, file_entry["zipped_file"], md5), + ) + + +def inner_rom_data_check(file_entry: dict, data: bytes) -> str: + """inner_rom_check on the bytes of an archive, as a pack holds it.""" + return _first_accepted_md5( + file_entry, + lambda md5: check_inside_zip_data(data, file_entry["zipped_file"], md5), + ) + + +def _first_accepted_md5(file_entry: dict, check: Callable[[str], str]) -> str: + # With no md5 declared, checkInsideZip still runs and needs the member. result = "not_in_zip" - for candidate in declared or [""]: - result = check_inside_zip(local_path, file_entry["zipped_file"], candidate) + for candidate in parse_md5_list(file_entry.get("md5")) or [""]: + result = check(candidate) if result == "ok": break return result diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index ef4942916..fde5060a0 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -5953,9 +5953,10 @@ class ZippedFileMd5IsParsedOnce(unittest.TestCase): ) def test_the_three_sites_share_the_parser(self): - for module in ("resolve/validation.py", "packs/integrity.py", "verify.py"): + for module in ("resolve/validation.py", "verify.py"): source = script_source(module) self.assertIn("parse_md5_list(", source, module) + self.assertIn("inner_rom_data_check(", script_source("packs/integrity.py")) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 50aeabcbe..cc07acd19 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -5406,18 +5406,6 @@ struct BurnDriver BurnDrvneogeo = { self.assertTrue(result[3][0].startswith("baseline missing: ")) self.assertEqual(result[9], 0) - def test_214_hash_matches_truncated_and_multi(self): - """Declared-hash compare handles truncation, case, multi-values.""" - from packs.integrity import _hash_matches - - full = "85254fbe320ca82a768ec2c26bb08def" - self.assertTrue(_hash_matches(full, full)) - self.assertTrue(_hash_matches(full.upper(), full)) - self.assertTrue(_hash_matches(full[:29], full)) # Batocera truncated - self.assertTrue(_hash_matches(f"deadbeef, {full}", full)) - self.assertFalse(_hash_matches("0" * 32, full)) - self.assertFalse(_hash_matches("", full)) - def test_216_resolve_by_sha256(self): """resolve_local_file matches files by declared sha256.""" import tempfile diff --git a/tests/test_zipped_member.py b/tests/test_zipped_member.py index 54c498e1f..0db7b559f 100644 --- a/tests/test_zipped_member.py +++ b/tests/test_zipped_member.py @@ -58,6 +58,40 @@ class ZippedMemberIsChecked(unittest.TestCase): +class PackIntegrityChecksTheMember(unittest.TestCase): + """Step 6 skipped a zipped_file entry without md5 and matched a cut md5 + by prefix: dragon32.zip without d32.rom passed where Batocera refuses it + (batocera-systems checkInsideZip with md5 "", whole-string compare).""" + + def _verdict(self, members: dict[str, bytes], entry: dict) -> str | None: + import io + + from packs.integrity import _check_member_hash + + inner = io.BytesIO() + with zipfile.ZipFile(inner, "w") as zf: + for name, data in members.items(): + zf.writestr(name, data) + pack = io.BytesIO() + with zipfile.ZipFile(pack, "w") as zf: + zf.writestr("bios/dragon32.zip", inner.getvalue()) + with zipfile.ZipFile(pack) as zf: + return _check_member_hash(zf, "bios/dragon32.zip", entry, "md5") + + def test_member_needed_without_md5(self): + entry = {"name": "dragon32.zip", "zipped_file": "d32.rom"} + self.assertIn("not found inside ZIP", self._verdict({"other.rom": b"x"}, entry)) + self.assertIsNone(self._verdict({"D32.ROM": b"x"}, entry)) + + def test_whole_md5_only(self): + md5 = hashlib.md5(b"x").hexdigest() + members = {"d32.rom": b"x"} + entry = {"name": "dragon32.zip", "zipped_file": "d32.rom"} + self.assertIsNone(self._verdict(members, {**entry, "md5": f"{'0' * 32},{md5}"})) + self.assertIsNone(self._verdict(members, {**entry, "md5": ["0" * 32, md5.upper()]})) + self.assertIsNotNone(self._verdict(members, {**entry, "md5": md5[:29]})) + + class TheMemberIndexIsCachedByContent(unittest.TestCase): """Each pipeline step that resolves a zipped_file decompressed all 54 845 archive members again, about 23 s a step."""