diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 4c0064aee..b971b516c 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -1,16 +1,16 @@ import asyncio import binascii +import copy import fnmatch import hashlib import os import re import struct -import zlib from collections.abc import Mapping, Sequence from dataclasses import dataclass, field, replace from datetime import datetime, timezone from pathlib import Path -from typing import Any, Final, NotRequired, TypedDict +from typing import Any, Final, NotRequired, Self, TypedDict from adapters.services.rom_converto import ( CONVERTO_PLATFORM_SLUGS, @@ -56,19 +56,19 @@ from utils.archives import ( ArchiveReadError, detect_mime_type, extract_chd_hash, - hash_largest_7z_member, + hash_largest_member, is_chd_file, read_7z_archive_files, read_basic_file, - read_bz2_file, - read_gz_file, read_rar_archive_files, read_tar_archive_files, - read_tar_file, read_zip_archive_files, - read_zip_file, ) -from utils.filesystem import COMPRESSED_FILE_SUFFIXES, iter_files +from utils.filesystem import ( + ARCHIVE_FORMAT_BY_SUFFIX, + COMPRESSED_FILE_SUFFIXES, + iter_files, +) from utils.hashing import crc32_to_hex from utils.platform_slugs import UniversalPlatformSlug as UPS @@ -172,23 +172,49 @@ DEFAULT_CRC_C = 0 DEFAULT_MD5_H_DIGEST = hashlib.md5(usedforsecurity=False).digest() DEFAULT_SHA1_H_DIGEST = hashlib.sha1(usedforsecurity=False).digest() +_MULTI_MEMBER_READERS: Final = { + "zip": read_zip_archive_files, + "tar": read_tar_archive_files, + "7z": read_7z_archive_files, + "rar": read_rar_archive_files, +} + ARCHIVE_READERS = { - ".zip": read_zip_archive_files, - ".tar": read_tar_archive_files, - ".tar.gz": read_tar_archive_files, - ".tgz": read_tar_archive_files, - ".tar.bz2": read_tar_archive_files, - ".tbz2": read_tar_archive_files, - ".tar.xz": read_tar_archive_files, - ".txz": read_tar_archive_files, - ".7z": read_7z_archive_files, - ".rar": read_rar_archive_files, + suffix: _MULTI_MEMBER_READERS[archive_format] + for suffix, archive_format in ARCHIVE_FORMAT_BY_SUFFIX + if archive_format in _MULTI_MEMBER_READERS } -def _chd_sha1_hash(file_path: Path) -> str: - """Return the embedded CHD v5 raw+meta SHA-1, or "" for non-CHD files.""" - return extract_chd_hash(file_path) if is_chd_file(file_path) else "" +class _FileHashers: + """One file's hashers, plus the ROM-level accumulators its bytes also feed.""" + + def __init__(self, rom_crc_c: int, rom_md5_h: Any, rom_sha1_h: Any) -> None: + self.crc_c = 0 + self.md5_h: Any = hashlib.md5(usedforsecurity=False) + self.sha1_h: Any = hashlib.sha1(usedforsecurity=False) + self.accumulate = rom_md5_h is not None and rom_sha1_h is not None + self.rom_crc_c = rom_crc_c + self.rom_md5_h = rom_md5_h + self.rom_sha1_h = rom_sha1_h + + def update(self, chunk: bytes | bytearray, /) -> None: + self.md5_h.update(chunk) + self.sha1_h.update(chunk) + self.crc_c = binascii.crc32(chunk, self.crc_c) + if self.accumulate: + self.rom_md5_h.update(chunk) + self.rom_sha1_h.update(chunk) + self.rom_crc_c = binascii.crc32(chunk, self.rom_crc_c) + + def copy(self) -> Self: + other = copy.copy(self) + other.md5_h = self.md5_h.copy() + other.sha1_h = self.sha1_h.copy() + if self.accumulate: + other.rom_md5_h = self.rom_md5_h.copy() + other.rom_sha1_h = self.rom_sha1_h.copy() + return other def _make_file_hash( @@ -886,34 +912,34 @@ class FSRomsHandler(FSHandler): continue if hashable_platform: - try: - if is_top_level: - # Include this file in the main ROM hash calculation - crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = ( - await asyncio.to_thread( - self._calculate_rom_hashes, - abs_file_path, - rom_crc_c, - rom_md5_h, - rom_sha1_h, - ) - ) - else: - # Calculate individual file hash only - crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread( + if is_top_level: + # Include this file in the main ROM hash calculation + ( + crc_c, + rom_crc_c, + md5_h, + rom_md5_h, + sha1_h, + rom_sha1_h, + chd_sha1_hash, + ) = await asyncio.to_thread( + self._calculate_rom_hashes, + abs_file_path, + rom_crc_c, + rom_md5_h, + rom_sha1_h, + ) + else: + # Calculate individual file hash only + crc_c, _, md5_h, _, sha1_h, _, chd_sha1_hash = ( + await asyncio.to_thread( self._calculate_rom_hashes, abs_file_path, ) - except zlib.error: - crc_c = 0 - md5_h = hashlib.md5(usedforsecurity=False) - sha1_h = hashlib.sha1(usedforsecurity=False) + ) file_hash = _make_file_hash( - crc_c, - md5_h, - sha1_h, - chd_sha1_hash=_chd_sha1_hash(abs_file_path), + crc_c, md5_h, sha1_h, chd_sha1_hash=chd_sha1_hash ) else: file_hash = FileHash( @@ -1023,8 +1049,8 @@ class FSRomsHandler(FSHandler): # Empty, malformed, unreadable, or all-excluded archive: hash the archive # file's raw bytes. We avoid `_calculate_rom_hashes` here because # it would decompress based on extension and end up hashing the - # largest internal member, not the archive itself, and would - # crash on an empty zip. `archive_members` stays None. + # largest internal member, not the archive itself. + # `archive_members` stays None. def _hash_raw_archive(crc: int) -> int: for chunk in read_basic_file(rom_dir): crc = binascii.crc32(chunk, crc) @@ -1045,15 +1071,10 @@ class FSRomsHandler(FSHandler): ) else: if hashable_platform: - try: - crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread( - self._calculate_rom_hashes, - Path(abs_fs_path, rom.fs_name), - ) - except zlib.error: - crc_c = 0 - md5_h = hashlib.md5(usedforsecurity=False) - sha1_h = hashlib.sha1(usedforsecurity=False) + crc_c, _, md5_h, _, sha1_h, _, chd_sha1_hash = await asyncio.to_thread( + self._calculate_rom_hashes, + Path(abs_fs_path, rom.fs_name), + ) # A single-file ROM spans exactly one file, so its ROM-level # hashes are that file's hashes. @@ -1069,10 +1090,7 @@ class FSRomsHandler(FSHandler): ) file_hash = _make_file_hash( - crc_c, - md5_h, - sha1_h, - chd_sha1_hash=_chd_sha1_hash(rom_dir), + crc_c, md5_h, sha1_h, chd_sha1_hash=chd_sha1_hash ) else: file_hash = FileHash( @@ -1189,72 +1207,39 @@ class FSRomsHandler(FSHandler): rom_crc_c: int = 0, rom_md5_h: Any = None, rom_sha1_h: Any = None, - ) -> tuple[int, int, Any, Any, Any, Any]: + ) -> tuple[int, int, Any, Any, Any, Any, str]: """Hash one file, optionally folding its bytes into ROM-level accumulators. A ROM-level hash spans every top-level file of a multi-file ROM, so it can only be built by feeding each file through a second set of hashers. Callers that don't need one pass no accumulators, because a second pass over a chunk costs as much as the first. + + Returns: + The file's and ROM-level hashes, then the embedded CHD SHA-1 ("" for + a non-CHD file). """ - extension = Path(file_path).suffix.lower() try: - file_type = detect_mime_type(file_path) - - crc_c = 0 - md5_h = hashlib.md5(usedforsecurity=False) - sha1_h = hashlib.sha1(usedforsecurity=False) - accumulate = rom_md5_h is not None and rom_sha1_h is not None - - def update_hashes(chunk: bytes | bytearray) -> None: - nonlocal crc_c, rom_crc_c - - md5_h.update(chunk) - sha1_h.update(chunk) - crc_c = binascii.crc32(chunk, crc_c) - - if accumulate: - rom_md5_h.update(chunk) - rom_sha1_h.update(chunk) - rom_crc_c = binascii.crc32(chunk, rom_crc_c) - - if extension == ".zip" or file_type == "application/zip": - for chunk in read_zip_file(file_path): - update_hashes(chunk) - - elif extension == ".tar" or file_type == "application/x-tar": - for chunk in read_tar_file(file_path): - update_hashes(chunk) - - elif extension == ".gz" or file_type == "application/x-gzip": - for chunk in read_gz_file(file_path): - update_hashes(chunk) - - elif extension == ".7z" or file_type == "application/x-7z-compressed": - # A failed extraction may have fed part of the member already, - # so the raw-archive fallback starts from the hashers' prior state. - snapshot = ( - crc_c, - rom_crc_c, - md5_h.copy(), - sha1_h.copy(), - rom_md5_h.copy() if accumulate else rom_md5_h, - rom_sha1_h.copy() if accumulate else rom_sha1_h, - ) - if not hash_largest_7z_member(file_path, update_hashes): - crc_c, rom_crc_c, md5_h, sha1_h, rom_md5_h, rom_sha1_h = snapshot - for chunk in read_basic_file(file_path): - update_hashes(chunk) - - elif extension == ".bz2" or file_type == "application/x-bzip2": - for chunk in read_bz2_file(file_path): - update_hashes(chunk) - - else: + mime_type = detect_mime_type(file_path) + chd_sha1_hash = ( + extract_chd_hash(file_path) if is_chd_file(file_path, mime_type) else "" + ) + hashers = _FileHashers(rom_crc_c, rom_md5_h, rom_sha1_h) + fed = hash_largest_member(file_path, hashers, mime_type) + if fed is None: + fed = hashers for chunk in read_basic_file(file_path): - update_hashes(chunk) + fed.update(chunk) - return crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h + return ( + fed.crc_c, + fed.rom_crc_c, + fed.md5_h, + fed.rom_md5_h, + fed.sha1_h, + fed.rom_sha1_h, + chd_sha1_hash, + ) except FileNotFoundError, PermissionError: return ( 0, @@ -1263,6 +1248,7 @@ class FSRomsHandler(FSHandler): rom_md5_h, hashlib.sha1(usedforsecurity=False), rom_sha1_h, + "", ) async def _discover_structured_roms( diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 75607733f..536cd695d 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1,9 +1,11 @@ import binascii +import gzip import hashlib import os import shutil import struct import tempfile +import zipfile from pathlib import Path from types import SimpleNamespace from unittest.mock import AsyncMock, Mock, patch @@ -27,6 +29,7 @@ from handler.filesystem.base_handler import ( REGIONS_BY_SHORTCODE, ) from handler.filesystem.roms_handler import ( + ARCHIVE_READERS, FileHash, FSRomsHandler, _TitleIdSource, @@ -36,7 +39,11 @@ from handler.filesystem.roms_handler import ( ) from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory, SaveTargetLayout -from utils.archives import extract_chd_hash +from utils.archives import ( + LARGEST_MEMBER_READERS, + ArchiveReadError, + extract_chd_hash, +) class TestFSRomsHandler: @@ -1392,7 +1399,7 @@ class TestFSRomsHandler: ).hexdigest() # Test the hash calculation method - crc_result, _, md5_result, _, sha1_result, _ = ( + crc_result, _, md5_result, _, sha1_result, _, _ = ( handler._calculate_rom_hashes( test_file, 0, @@ -1430,6 +1437,78 @@ class TestFSRomsHandler: (rom_dir / "sub", "c.bin"), ] + def test_plain_gzip_hashes_its_content(self, handler: FSRomsHandler, tmp_path): + content = b"Plain gzip ROM content" * 32 + archive = tmp_path / "game.gb.gz" + archive.write_bytes(gzip.compress(content)) + + crc_c, _, md5_h, _, sha1_h, _, _ = handler._calculate_rom_hashes(archive) + + assert crc_c == binascii.crc32(content) + assert md5_h.hexdigest() == hashlib.md5(content).hexdigest() + assert sha1_h.hexdigest() == hashlib.sha1(content).hexdigest() + + @pytest.mark.parametrize("name", ["game.gb", "game.zip", "game.chd"]) + def test_detects_the_mime_type_once( + self, handler: FSRomsHandler, tmp_path, name: str + ): + rom = tmp_path / name + rom.write_bytes(b"not really a " + name.encode()) + + with ( + patch( + "handler.filesystem.roms_handler.detect_mime_type", return_value="" + ) as detect, + patch("utils.archives.detect_mime_type") as inner_detect, + ): + handler._calculate_rom_hashes(rom) + + detect.assert_called_once_with(rom) + inner_detect.assert_not_called() + + def test_reads_the_embedded_chd_hash(self, handler: FSRomsHandler, tmp_path): + rom = tmp_path / "game.chd" + rom.write_bytes(b"not a real chd") + + with patch( + "handler.filesystem.roms_handler.extract_chd_hash", return_value="ab" * 20 + ): + *_, chd_sha1_hash = handler._calculate_rom_hashes(rom) + + assert chd_sha1_hash == "ab" * 20 + + def test_archive_readers_cover_every_multi_member_suffix(self): + assert set(ARCHIVE_READERS) == { + ".zip", + ".tar", + ".tar.gz", + ".tgz", + ".tar.bz2", + ".tbz2", + ".tar.xz", + ".txz", + ".7z", + ".rar", + } + + def test_empty_zip_hashes_the_raw_archive(self, handler: FSRomsHandler, tmp_path): + reload_zipfile() + archive = tmp_path / "empty.zip" + with zipfile.ZipFile(archive, "w"): + pass + archive_bytes = archive.read_bytes() + + rom_sha1_h = hashlib.sha1(b"earlier file", usedforsecurity=False) + _, _, _, _, sha1_h, rom_sha1_h, _ = handler._calculate_rom_hashes( + archive, 0, hashlib.md5(usedforsecurity=False), rom_sha1_h + ) + + assert sha1_h.hexdigest() == hashlib.sha1(archive_bytes).hexdigest() + assert ( + rom_sha1_h.hexdigest() + == hashlib.sha1(b"earlier file" + archive_bytes).hexdigest() + ) + def test_failed_7z_extraction_hashes_only_the_raw_archive( self, handler: FSRomsHandler, tmp_path ): @@ -1439,19 +1518,19 @@ class TestFSRomsHandler: archive = tmp_path / "game.7z" archive.write_bytes(archive_bytes) - def _partial_then_fail(_path, fn_hash_update): - fn_hash_update(b"partial inner member bytes") - return False + def _partial_then_fail(path): + def _chunks(): + yield b"partial inner member bytes" + raise ArchiveReadError(f"Extraction of {path} failed") + + yield _chunks() rom_md5_h = hashlib.md5(b"earlier file", usedforsecurity=False) rom_sha1_h = hashlib.sha1(b"earlier file", usedforsecurity=False) rom_crc_c = binascii.crc32(b"earlier file") - with patch( - "handler.filesystem.roms_handler.hash_largest_7z_member", - side_effect=_partial_then_fail, - ): - crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = ( + with patch.dict(LARGEST_MEMBER_READERS, {"7z": _partial_then_fail}): + crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h, _ = ( handler._calculate_rom_hashes(archive, rom_crc_c, rom_md5_h, rom_sha1_h) ) diff --git a/backend/tests/utils/test_archives.py b/backend/tests/utils/test_archives.py index 13bb0b18f..e83de8915 100644 --- a/backend/tests/utils/test_archives.py +++ b/backend/tests/utils/test_archives.py @@ -1,11 +1,15 @@ +import bz2 +import gzip import hashlib import io +import lzma import shutil import struct import subprocess import tarfile import time import zipfile +from collections.abc import Iterator from pathlib import Path from unittest.mock import MagicMock, patch @@ -155,7 +159,9 @@ def test_largest_member_hashing_terminates_switches_before_the_member(): patch.object(subprocess, "run", return_value=listing), patch.object(subprocess, "Popen", popen), ): - assert archives.hash_largest_7z_member(Path("/fake/game.7z"), MagicMock()) + assert _last_candidate(archives.read_7z_or_rar_file(Path("/fake/game.7z"))) == ( + b"data" + ) command = popen.call_args[0][0] assert command[-2:] == ["--", "-x"] @@ -189,7 +195,8 @@ class TestStalledExtractorIsKilled: @pytest.mark.usefixtures("stalling_7zz") def test_largest_member_hashing_fails(self): start = time.monotonic() - assert not archives.hash_largest_7z_member(Path("/fake/game.7z"), MagicMock()) + with pytest.raises(archives.ArchiveReadError, match="timed out"): + _last_candidate(archives.read_7z_or_rar_file(Path("/fake/game.7z"))) assert time.monotonic() - start < 10 @pytest.mark.usefixtures("stalling_7zz") @@ -565,12 +572,7 @@ class TestZipAndTarReadFailures: """ def _write_zip(self, path: Path, members: dict[str, bytes]) -> None: - # Importing `archives` patches zipfile for Enhanced Deflate, which - # leaves the writer unusable until this is called. - ensure_zipfile_writable() - with zipfile.ZipFile(path, "w", zipfile.ZIP_STORED) as z: - for name, data in members.items(): - z.writestr(name, data) + path.write_bytes(_zip_bytes(members, zipfile.ZIP_STORED)) def test_unopenable_zip_raises(self, tmp_path): path = tmp_path / "game.zip" @@ -642,29 +644,259 @@ class TestZipAndTarReadFailures: raise EOFError("Compressed file ended before the end-of-stream marker") with pytest.raises(archives.ArchiveReadError): - list(archives._iter_chunks(_FailingReader(), Path("/fake.tar.gz"), "a.bin")) + list( + archives._iter_chunks( + _FailingReader(), + Path("/fake.tar.gz"), + "a.bin", + time.monotonic() + 60, + ) + ) class TestReadTarFile: def _write_tar(self, path: Path, members: dict[str, bytes]) -> None: - with tarfile.open(path, "w") as tf: - for name, data in members.items(): - info = tarfile.TarInfo(name) - info.size = len(data) - tf.addfile(info, io.BytesIO(data)) + path.write_bytes(_tar_bytes(members)) def test_streams_the_largest_member(self, tmp_path): path = tmp_path / "game.tar" self._write_tar(path, {"small.bin": b"S" * 16, "large.bin": b"L" * 64}) - assert b"".join(archives.read_tar_file(path)) == b"L" * 64 + assert _last_candidate(archives.read_tar_file(path)) == b"L" * 64 - def test_member_without_a_stream_yields_nothing(self, tmp_path): + def test_a_later_larger_member_wins_in_one_pass(self, tmp_path): + path = tmp_path / "game.tar.gz" + path.write_bytes( + gzip.compress( + _tar_bytes({"a.bin": b"A" * 16, "b.bin": b"B" * 64, "c.bin": b"C" * 32}) + ) + ) + + with patch.object(tarfile, "open", wraps=tarfile.open) as tar_open: + candidates = [b"".join(chunks) for chunks in archives.read_tar_file(path)] + + assert candidates == [b"A" * 16, b"B" * 64] + tar_open.assert_called_once() + + def test_equal_sizes_keep_the_first_member(self, tmp_path): + path = tmp_path / "game.tar" + self._write_tar(path, {"a.bin": b"A" * 16, "b.bin": b"B" * 16}) + + assert _last_candidate(archives.read_tar_file(path)) == b"A" * 16 + + def test_member_without_a_stream_raises(self, tmp_path): path = tmp_path / "game.tar" self._write_tar(path, {"game.bin": b"G" * 16}) - with patch.object(tarfile.TarFile, "extractfile", return_value=None): - assert list(archives.read_tar_file(path)) == [] + with ( + patch.object(tarfile.TarFile, "extractfile", return_value=None), + pytest.raises(archives.ArchiveReadError), + ): + _last_candidate(archives.read_tar_file(path)) + + +ROM = b"Tetris ROM bytes " * 64 +DEFLATE64_METHOD = 9 + + +def _tar_bytes(members: dict[str, bytes]) -> bytes: + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w") as tf: + for name, data in members.items(): + info = tarfile.TarInfo(name) + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + return buf.getvalue() + + +def _zip_bytes( + members: dict[str, bytes], compression: int = zipfile.ZIP_DEFLATED +) -> bytes: + # Importing `archives` patches zipfile for Enhanced Deflate, which + # leaves the writer unusable until this is called. + ensure_zipfile_writable() + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", compression) as z: + for name, data in members.items(): + z.writestr(name, data) + return buf.getvalue() + + +def _write_zip_with_method( + path: Path, members: dict[str, bytes], stamped: frozenset[str], method: int +) -> None: + """Write a stored zip, then relabel the `stamped` members' compression method.""" + raw = bytearray(_zip_bytes(members, zipfile.ZIP_STORED)) + for name in stamped: + encoded = name.encode() + # The name follows a 30-byte local header and a 46-byte central one. + local = raw.index(encoded, raw.index(b"PK\x03\x04")) - 30 + struct.pack_into(" bytes: + content = b"" + for chunks in candidates: + content = b"".join(chunks) + return content + + +class _ContentHasher: + def __init__(self) -> None: + self.content = bytearray() + + def update(self, chunk: bytes | bytearray, /) -> None: + self.content += chunk + + def copy(self) -> "_ContentHasher": + other = _ContentHasher() + other.content = bytearray(self.content) + return other + + +def _hash_content(path: Path) -> bytes | None: + fed = archives.hash_largest_member(path, _ContentHasher()) + return None if fed is None else bytes(fed.content) + + +class TestHashLargestMember: + """Every compressed format hashes its content, never its compressed bytes + (GitHub issue #5328).""" + + TARBALL = _tar_bytes({"small.txt": b"readme", "game.gb": ROM}) + + @pytest.mark.parametrize( + ("name", "data"), + [ + ("game.zip", _zip_bytes({"small.txt": b"readme", "game.gb": ROM})), + ("game.tar", TARBALL), + ("game.tar.gz", gzip.compress(TARBALL)), + ("game.tgz", gzip.compress(TARBALL)), + ("game.tar.bz2", bz2.compress(TARBALL)), + ("game.tbz2", bz2.compress(TARBALL)), + ("game.tar.xz", lzma.compress(TARBALL)), + ("game.txz", lzma.compress(TARBALL)), + ("game.gb.gz", gzip.compress(ROM)), + ("game.gb.bz2", bz2.compress(ROM)), + ("game.gb.xz", lzma.compress(ROM)), + ("tarball.gz", gzip.compress(TARBALL)), + ("trailing.gb.gz", gzip.compress(ROM) + b"padding!"), + ("zero-padded.gb.gz", gzip.compress(ROM) + bytes(64)), + ("multi-member.gb.gz", gzip.compress(ROM[:100]) + gzip.compress(ROM[100:])), + ], + ) + def test_hashes_the_content(self, tmp_path, name, data): + path = tmp_path / name + path.write_bytes(data) + + assert _hash_content(path) == ROM + + @pytest.mark.parametrize( + ("name", "compress"), + [ + ("disc.iso.gz", gzip.compress), + ("disc.iso.bz2", bz2.compress), + ("disc.iso.xz", lzma.compress), + ], + ) + def test_a_zero_filled_opening_is_not_a_tarball(self, tmp_path, name, compress): + image = bytes(4096) + ROM + path = tmp_path / name + path.write_bytes(compress(image)) + + assert _hash_content(path) == image + + @pytest.mark.parametrize( + ("data", "mime"), + [ + (gzip.compress(TARBALL), "application/gzip"), + (gzip.compress(ROM), "application/x-gzip"), + (lzma.compress(ROM), "application/x-xz"), + ], + ) + def test_detects_the_format_by_mime_type(self, tmp_path, data, mime): + path = tmp_path / "game.bin" + path.write_bytes(data) + + with patch.object(archives, "detect_mime_type", return_value=mime): + assert _hash_content(path) == ROM + + @pytest.mark.parametrize( + ("name", "data"), + [ + ("empty.zip", _zip_bytes({})), + ("empty.tar", _tar_bytes({})), + ("empty.tar.gz", gzip.compress(_tar_bytes({}))), + ("empty-member.zip", _zip_bytes({"game.gb": b""})), + ("empty-stream.gb.gz", gzip.compress(b"")), + ("empty-stream.gb.xz", lzma.compress(b"")), + ("corrupt.zip", b"PK\x03\x04 not a zip"), + ("corrupt.gz", gzip.compress(ROM)[:40]), + ("corrupt.xz", lzma.compress(ROM)[:40]), + ], + ) + def test_empty_or_unreadable_archive_reports_failure(self, tmp_path, name, data): + path = tmp_path / name + path.write_bytes(data) + + assert _hash_content(path) is None + + def test_corrupt_deflate64_member_reports_failure(self, tmp_path): + path = tmp_path / "game.zip" + # A reserved deflate block type, so inflate64 rejects the stream. + _write_zip_with_method( + path, {"game.gb": b"\xff" * 64}, frozenset({"game.gb"}), DEFLATE64_METHOD + ) + + assert _hash_content(path) is None + + def test_reading_past_the_deadline_reports_failure(self, tmp_path, monkeypatch): + path = tmp_path / "game.gb.xz" + path.write_bytes(lzma.compress(ROM)) + monkeypatch.setattr(archives, "SEVEN_ZIP_TIMEOUT", -1) + + assert _hash_content(path) is None + + def test_rar_hashes_its_largest_member_through_bsdtar(self, tmp_path): + path = tmp_path / "game.rar" + path.write_bytes(b"Rar!\x1a\x07\x00") + listing = MagicMock( + stdout=_fake_mtree_listing( + ["./readme.txt type=file size=12", "./game.gba type=file size=500"] + ) + ) + popen = _mock_popen_streaming([[b"G" * 500]], [0]) + + with ( + patch.object(subprocess, "run", return_value=listing), + patch.object(subprocess, "Popen", popen), + ): + assert _hash_content(path) == b"G" * 500 + + command = popen.call_args[0][0] + assert command[0] == archives.BSDTAR_PATH + assert command[-1] == "game.gba" + + def test_a_given_mime_type_skips_detection(self, tmp_path): + path = tmp_path / "game.bin" + path.write_bytes(gzip.compress(ROM)) + + with patch.object(archives, "detect_mime_type") as detect: + fed = archives.hash_largest_member( + path, _ContentHasher(), "application/gzip" + ) + + assert fed is not None and bytes(fed.content) == ROM + detect.assert_not_called() + + def test_plain_file_is_not_an_archive(self, tmp_path): + path = tmp_path / "game.gb" + path.write_bytes(ROM) + + assert _hash_content(path) is None class TestZipUndecodableCompression: @@ -677,20 +909,7 @@ class TestZipUndecodableCompression: def _write_zip( self, path: Path, members: dict[str, bytes], stamped: frozenset[str] ) -> None: - ensure_zipfile_writable() - with zipfile.ZipFile(path, "w", zipfile.ZIP_STORED) as z: - for name, data in members.items(): - z.writestr(name, data) - - raw = bytearray(path.read_bytes()) - for name in stamped: - encoded = name.encode() - # The name follows a 30-byte local header and a 46-byte central one. - local = raw.index(encoded, raw.index(b"PK\x03\x04")) - 30 - struct.pack_into(" Iterator[bytes]: yield chunk -def read_zip_file(file: str | os.PathLike[str] | IO[bytes]) -> Iterator[bytes]: - try: - with zipfile.ZipFile(file, "r") as z: - # Find the biggest file in the archive - largest_file = max(z.infolist(), key=lambda x: x.file_size) - with z.open(largest_file, "r") as f: - while chunk := f.read(FILE_READ_CHUNK_SIZE): - yield chunk - except zipfile.BadZipFile, RuntimeError, OSError: - if isinstance(file, Path): - for chunk in read_basic_file(file): - yield chunk +def detect_archive_format( + file_path: Path, mime_type: str | None = None +) -> ArchiveFormat | None: + """Pick an archive format by suffix, then by MIME type. - -def read_tar_file( - file_path: Path, mode: Literal["r", "r:*", "r:", "r:gz", "r:bz2", "r:xz"] = "r" -) -> Iterator[bytes]: - try: - with tarfile.open(file_path, mode) as f: - regular_files = [member for member in f.getmembers() if member.isfile()] - - # Find the largest file among regular files only - largest_file = max(regular_files, key=lambda x: x.size) - ef = f.extractfile(largest_file) - if ef is None: - return - with ef: - while chunk := ef.read(FILE_READ_CHUNK_SIZE): - yield chunk - except tarfile.ReadError: - for chunk in read_basic_file(file_path): - yield chunk - - -def read_gz_file(file_path: Path) -> Iterator[bytes]: - return read_tar_file(file_path, "r:gz") - - -def hash_largest_7z_member( - file_path: Path, - fn_hash_update: Callable[[bytes | bytearray], None], -) -> bool: - """Stream the largest member of a 7z archive through `fn_hash_update`. - - Returns True on success, False if listing/extraction fails or times out, - in which case `fn_hash_update` may already have seen part of the member. + Args: + mime_type: The file's libmagic MIME type, detected here when not given. """ - try: - result = subprocess.run( - [SEVEN_ZIP_PATH, "l", "-slt", "-ba", str(file_path)], - capture_output=True, - text=True, - check=True, - timeout=SEVEN_ZIP_TIMEOUT, - shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated + name = file_path.name.lower() + for suffix, archive_format in ARCHIVE_FORMAT_BY_SUFFIX: + if name.endswith(suffix): + return archive_format + if mime_type is None: + mime_type = detect_mime_type(file_path) + return ARCHIVE_FORMAT_BY_MIME.get(mime_type) + + +def _read_deadline() -> float: + return time.monotonic() + SEVEN_ZIP_TIMEOUT + + +def _check_deadline(deadline: float, file_path: Path) -> None: + if time.monotonic() > deadline: + raise ArchiveReadError( + f"Reading {file_path} timed out after {SEVEN_ZIP_TIMEOUT}s; " + "raise SEVEN_ZIP_TIMEOUT for large archives" ) - largest_file = None - largest_size = 0 - current_file = None - current_size = 0 - for line in result.stdout.split("\n"): - line = line.lstrip() - if line.startswith("Path = "): - current_file = line.split(" = ", 1)[1] - elif line.startswith("Size = "): - try: - current_size = int(line.split(" = ")[1].strip()) - except ValueError: - current_size = 0 - elif line.startswith("Attributes = "): - attrs = line.split(" = ")[1].strip() - if current_file and not attrs.startswith("D"): - if current_size > largest_size: - largest_size = current_size - largest_file = current_file - - if not largest_file: - return False - - log.debug(f"Extracting {largest_file} from {file_path}...") - - deadline = time.monotonic() + SEVEN_ZIP_TIMEOUT - - with ( - subprocess.Popen( - [ - SEVEN_ZIP_PATH, - "e", - str(file_path), - "-so", - "-y", - "-spd", - "--", - largest_file, - ], - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated - ) as process, - _kill_at_deadline(process, deadline) as expired, - ): - if process.stdout: - while chunk := process.stdout.read(FILE_READ_CHUNK_SIZE): - if time.monotonic() > deadline: - process.terminate() - log.error("7z extraction timed out") - return False - fn_hash_update(chunk) - - if expired.is_set(): - log.error("7z extraction stalled and was killed at the timeout") - return False - - if process.returncode != 0: - log.error(f"7z extraction failed with return code {process.returncode}") - return False - - return True - - except ( - subprocess.TimeoutExpired, - subprocess.CalledProcessError, - FileNotFoundError, - ) as e: - log.error(f"Error processing 7z file: {e}") - return False - - -def read_bz2_file(file_path: Path) -> Iterator[bytes]: +def read_zip_file(file_path: Path) -> Iterator[Iterator[bytes]]: + """Yield the largest zip member's chunks, raising `ArchiveReadError` if it can't be read.""" + deadline = _read_deadline() try: - with bz2.BZ2File(file_path, "rb") as f: - while chunk := f.read(FILE_READ_CHUNK_SIZE): + with zipfile.ZipFile(file_path, "r") as z: + largest_file = max( + (info for info in z.infolist() if not info.is_dir()), + key=lambda x: x.file_size, + default=None, + ) + if largest_file is None: + raise ArchiveReadError(f"Zip {file_path} has no members") + if _undecodable_zip_method(z, [largest_file]) is None: + with z.open(largest_file, "r") as f: + yield _iter_chunks(f, file_path, largest_file.filename, deadline) + return + except (zipfile.BadZipFile, RuntimeError, OSError, ValueError) as e: + raise ArchiveReadError(f"Error reading zip {file_path}: {e}") from e + # zipfile can't decode every compression method, and 7zz reads them all. + yield from read_7z_or_rar_file(file_path) + + +def _iter_tar_candidates( + tf: tarfile.TarFile, file_path: Path, deadline: float +) -> Iterator[Iterator[bytes]]: + """Yield each regular member larger than every one before it, in one pass. + + A compressed tarball can't seek back to its largest member without + decompressing again, so every new largest is streamed as it passes. + """ + largest_size = -1 + try: + for member in tf: + _check_deadline(deadline, file_path) + if not member.isfile() or member.size <= largest_size: + continue + largest_size = member.size + ef = tf.extractfile(member) + if ef is None: + raise ArchiveReadError(f"Can't extract {member.name}") + with ef: + yield _iter_chunks(ef, file_path, member.name, deadline) + except _DECOMPRESS_ERRORS as e: + raise ArchiveReadError(f"Error reading tar {file_path}: {e}") from e + if largest_size < 0: + raise ArchiveReadError(f"Tar {file_path} has no members") + + +def read_tar_file(file_path: Path) -> Iterator[Iterator[bytes]]: + """Yield ever-larger tar members' chunks, raising `ArchiveReadError` if one can't be read.""" + deadline = _read_deadline() + try: + tf = tarfile.open(file_path, "r|*") + except _DECOMPRESS_ERRORS as e: + raise ArchiveReadError(f"Error reading tar {file_path}: {e}") from e + with tf: + yield from _iter_tar_candidates(tf, file_path, deadline) + + +def _open_tarball(file_path: Path) -> tarfile.TarFile | None: + try: + tf = tarfile.open(file_path, "r|*") + except _DECOMPRESS_ERRORS: + return None + # tarfile opens a zero-filled first block as an empty archive, which a + # compressed disc image can start with, so require a first member. + try: + if tf.next() is not None: + return tf + except _DECOMPRESS_ERRORS: + pass + tf.close() + return None + + +def _iter_gzip_content(file_path: Path, deadline: float) -> Iterator[bytes]: + """Decompress every gzip member, ignoring trailing bytes the way gunzip does.""" + with open(file_path, "rb") as f: + decompressor = zlib.decompressobj(wbits=_GZIP_WBITS) + data = f.read(FILE_READ_CHUNK_SIZE) + while True: + _check_deadline(deadline, file_path) + chunk = decompressor.decompress(data, FILE_READ_CHUNK_SIZE) + if chunk: yield chunk - except EOFError: - for chunk in read_basic_file(file_path): - yield chunk + if decompressor.eof: + data = decompressor.unused_data + while len(data) < len(_GZIP_MAGIC) and (more := f.read(1)): + data += more + if not data.startswith(_GZIP_MAGIC): + return + decompressor = zlib.decompressobj(wbits=_GZIP_WBITS) + continue + data = decompressor.unconsumed_tail + if not data and not chunk: + data = f.read(FILE_READ_CHUNK_SIZE) + if not data: + raise EOFError( + "Compressed file ended before the end-of-stream marker" + ) -def _iter_chunks(reader: IO[bytes], file_path: Path, name: str) -> Iterator[bytes]: - """Stream a member's bytes, raising `ArchiveReadError` if it can't be read. +def _iter_opened_content( + opener: Callable[[Path], io.BufferedIOBase], +) -> Callable[[Path, float], Iterator[bytes]]: + def _iter_content(file_path: Path, deadline: float) -> Iterator[bytes]: + with opener(file_path) as f: + yield from _iter_chunks(f, file_path, file_path.name, deadline) + + return _iter_content + + +def _wrap_read_errors(chunks: Iterator[bytes], file_path: Path) -> Iterator[bytes]: + try: + yield from chunks + except _DECOMPRESS_ERRORS as e: + raise ArchiveReadError(f"Error reading {file_path}: {e}") from e + + +def _read_compressed_stream( + file_path: Path, iter_content: Callable[[Path, float], Iterator[bytes]] +) -> Iterator[Iterator[bytes]]: + deadline = _read_deadline() + # A tarball under a single-stream suffix (game.gb.gz) hashes like a .tar.gz. + tarball = _open_tarball(file_path) + if tarball is not None: + with tarball: + yield from _iter_tar_candidates(tarball, file_path, deadline) + return + yield _wrap_read_errors(iter_content(file_path, deadline), file_path) + + +def read_gz_file(file_path: Path) -> Iterator[Iterator[bytes]]: + return _read_compressed_stream(file_path, _iter_gzip_content) + + +def read_bz2_file(file_path: Path) -> Iterator[Iterator[bytes]]: + return _read_compressed_stream(file_path, _iter_opened_content(bz2.BZ2File)) + + +def read_xz_file(file_path: Path) -> Iterator[Iterator[bytes]]: + return _read_compressed_stream(file_path, _iter_opened_content(lzma.LZMAFile)) + + +def read_7z_or_rar_file(file_path: Path) -> Iterator[Iterator[bytes]]: + """Yield the largest member's chunks through 7zz (bsdtar for RAR). + + Raises `ArchiveReadError` if it can't be read. + """ + largest_file = max( + _list_archive_file_members(file_path), key=lambda e: e[1], default=None + ) + if largest_file is None: + raise ArchiveReadError(f"Archive {file_path} has no members") + for _name, _size, chunks in _stream_archive_members(file_path, [largest_file]): + yield chunks + + +# Each reader yields the chunks of successively larger members, so the last one +# is the largest; a format that knows its largest member up front yields once. +LARGEST_MEMBER_READERS: Final[ + dict[ArchiveFormat, Callable[[Path], Iterator[Iterator[bytes]]]] +] = { + "zip": read_zip_file, + "tar": read_tar_file, + "gzip": read_gz_file, + "bz2": read_bz2_file, + "xz": read_xz_file, + "7z": read_7z_or_rar_file, + "rar": read_7z_or_rar_file, +} + + +class Hasher(Protocol): + def update(self, chunk: bytes | bytearray, /) -> None: ... + + def copy(self) -> Self: ... + + +def hash_largest_member[H: Hasher]( + file_path: Path, hasher: H, mime_type: str | None = None +) -> H | None: + """Feed a copy of `hasher` with a compressed file's content (its largest member). + + Args: + mime_type: The file's libmagic MIME type, detected here when not given. + + Returns: + The fed copy, or None if the file is not a known archive, holds no + content, or can't be read in full. `hasher` itself is never fed. + """ + archive_format = detect_archive_format(file_path, mime_type) + if archive_format is None: + return None + fed: H | None = None + try: + for chunks in LARGEST_MEMBER_READERS[archive_format](file_path): + candidate = hasher.copy() + has_content = False + for chunk in chunks: + candidate.update(chunk) + has_content = True + # Empty content would leave a non-empty file with blank hashes, + # which an incremental scan reads as changed every time. + fed = candidate if has_content else None + except ArchiveReadError as e: + log.warning(f"{e}. Hashing the file itself instead.") + return None + return fed + + +def _iter_chunks( + reader: IO[bytes] | io.BufferedIOBase, + file_path: Path, + name: str, + deadline: float, +) -> Iterator[bytes]: + """Stream a member's bytes, raising `ArchiveReadError` if it can't be read + or `deadline` passes. Chunks are consumed by the caller, outside the reader's own error handling, so decompression failures (a bad CRC, truncated data) surface @@ -270,12 +399,16 @@ def _iter_chunks(reader: IO[bytes], file_path: Path, name: str) -> Iterator[byte try: while chunk := reader.read(FILE_READ_CHUNK_SIZE): yield chunk + _check_deadline(deadline, file_path) except ( zipfile.BadZipFile, tarfile.TarError, zlib.error, + lzma.LZMAError, EOFError, OSError, + # inflate64 reports a corrupt Deflate64 stream as a ValueError. + ValueError, ) as e: raise ArchiveReadError(f"Error reading {name} from {file_path}: {e}") from e @@ -321,6 +454,7 @@ def read_zip_archive_files( Raises `ArchiveReadError` if the archive can't be read in full, so callers never mistake a partial read for a complete one. """ + deadline = _read_deadline() try: with zipfile.ZipFile(file_path, "r") as z: entries = _eligible_zip_entries(z, excluded_names, excluded_exts) @@ -329,9 +463,11 @@ def read_zip_archive_files( for entry in entries: name = entry.filename with z.open(entry, "r") as f: - yield name, entry.file_size, _iter_chunks(f, file_path, name) + yield name, entry.file_size, _iter_chunks( + f, file_path, name, deadline + ) return - except (zipfile.BadZipFile, RuntimeError, OSError) as e: + except (zipfile.BadZipFile, RuntimeError, OSError, ValueError) as e: raise ArchiveReadError(f"Error reading zip {file_path}: {e}") from e log.debug( @@ -355,6 +491,7 @@ def read_tar_archive_files( Raises `ArchiveReadError` if the archive can't be read in full, so callers never mistake a partial read for a complete one. """ + deadline = _read_deadline() try: with tarfile.open(file_path, "r:*") as tf: members = sorted( @@ -380,7 +517,9 @@ def read_tar_archive_files( continue with ef: - yield member.name, member.size, _iter_chunks(ef, file_path, name) + yield member.name, member.size, _iter_chunks( + ef, file_path, name, deadline + ) except (tarfile.TarError, OSError) as e: raise ArchiveReadError(f"Error reading tar {file_path}: {e}") from e @@ -753,16 +892,17 @@ def extract_largest_archive_member(file_path: Path, dest_dir: Path) -> Path | No return None -def is_chd_file(file_path: Path) -> bool: - """Return True if the file is a CHD by extension or libmagic-detected MIME type.""" +def is_chd_file(file_path: Path, mime_type: str | None = None) -> bool: + """Return True if the file is a CHD by extension or libmagic MIME type. + + Args: + mime_type: The file's libmagic MIME type, detected here when not given. + """ if file_path.suffix.lower() == ".chd": return True - - try: - with _MIME_DETECTOR_LOCK: - return _MIME_DETECTOR.from_file(file_path) == CHD_MIME_TYPE - except OSError, magic.MagicException: - return False + if mime_type is None: + mime_type = detect_mime_type(file_path) + return mime_type == CHD_MIME_TYPE def extract_chd_hash(file_path: Path) -> str: diff --git a/backend/utils/filesystem.py b/backend/utils/filesystem.py index 7ff1a60e0..5532657b2 100644 --- a/backend/utils/filesystem.py +++ b/backend/utils/filesystem.py @@ -4,14 +4,34 @@ import re import shutil from collections.abc import Iterator from pathlib import Path +from typing import Final, Literal from logger.logger import log +ArchiveFormat = Literal["zip", "tar", "gzip", "bz2", "xz", "7z", "rar"] + +# Longest suffix first, so a .tar.gz is not taken for a plain .gz. +ARCHIVE_FORMAT_BY_SUFFIX: Final[tuple[tuple[str, ArchiveFormat], ...]] = ( + (".tar.gz", "tar"), + (".tar.bz2", "tar"), + (".tar.xz", "tar"), + (".tgz", "tar"), + (".tbz2", "tar"), + (".txz", "tar"), + (".tar", "tar"), + (".zip", "zip"), + (".gz", "gzip"), + (".bz2", "bz2"), + (".xz", "xz"), + (".7z", "7z"), + (".rar", "rar"), +) + # Container file extensions treated as compressed archives across modules # (roms_handler for hashing decisions, rahasher for skipping disc-platform # buffer-hash attempts, feeds for PKGi passthrough). COMPRESSED_FILE_EXTENSIONS: frozenset[str] = frozenset( - (".7z", ".bz2", ".gz", ".rar", ".tar", ".zip", ".xz", ".tgz", ".tbz2", ".txz") + suffix for suffix, _ in ARCHIVE_FORMAT_BY_SUFFIX ) # str.endswith takes a tuple, never a set, so it is built once here. diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 7cd5edc78..c079d348e 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -1989,7 +1989,7 @@ Falls back to `FakeRedis` in test mode. | `SCHEDULED_RESCAN_CRON` | `0 3 * * *` | Rescan schedule | | `ENABLE_RESCAN_ON_FILESYSTEM_CHANGE` | `false` | Watch for file changes | | `RESCAN_ON_FILESYSTEM_CHANGE_DELAY` | `5` | Debounce delay (minutes) | -| `SEVEN_ZIP_TIMEOUT` | `180` | Timeout for 7-Zip extraction | +| `SEVEN_ZIP_TIMEOUT` | `180` | Timeout for reading one archive | | `REFRESH_RETROACHIEVEMENTS_CACHE_DAYS` | | RA cache TTL (days) | #### Device Sync diff --git a/env.template b/env.template index 4f6506fc6..908e8da52 100644 --- a/env.template +++ b/env.template @@ -103,7 +103,7 @@ SCAN_TIMEOUT=14400 # Timeout for background scan/rescan tasks in seconds SCAN_WORKERS=4 # How many ROMs a scan processes at once TASK_TIMEOUT=300 # Timeout for other background tasks in seconds TASK_RESULT_TTL=86400 # How long to keep task results in Valkey in seconds -SEVEN_ZIP_TIMEOUT=180 # Timeout for 7-Zip operations in seconds +SEVEN_ZIP_TIMEOUT=180 # Timeout for reading one archive, in seconds ROM_PATCHER_TIMEOUT=120 # Timeout for applying a ROM patch in seconds ROM_PATCHER_MAX_FILE_SIZE_BYTES=4294967296 # Largest ROM or patch file the patcher accepts, in bytes (4 GiB) ROM_PATCHER_MAX_CONCURRENCY=2 # How many ROM patches can run at once per API worker (minimum 1)