mirror of
https://github.com/rommapp/romm.git
synced 2026-12-02 10:08:40 +01:00
Merge pull request #3813 from Spinnich/fix/rahasher-archive-extraction
fix(retroachievements): extract non-zip archives before RAHasher hashing
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
|
||||
@@ -7,6 +8,7 @@ from handler.metadata.ra_handler import RAGamesPlatform
|
||||
from logger.formatter import LIGHTMAGENTA
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.archives import extract_largest_archive_member
|
||||
from utils.filesystem import COMPRESSED_FILE_EXTENSIONS
|
||||
from utils.psp_hasher import calculate_psp_ra_hash, is_psp_native_hash_file
|
||||
from utils.rvz_hasher import (
|
||||
@@ -17,6 +19,11 @@ from utils.rvz_hasher import (
|
||||
|
||||
RAHASHER_VALID_HASH_REGEX = re.compile(r"[0-9a-f]{32}")
|
||||
|
||||
# The only archive format RAHasher decompresses itself (via miniz). Any other
|
||||
# container is hashed as its raw archive bytes, silently producing a hash that
|
||||
# matches nothing on RetroAchievements (issue #3808).
|
||||
RAHASHER_NATIVE_ARCHIVE_EXTENSIONS: tuple[str, ...] = (".zip",)
|
||||
|
||||
# Disc descriptor / playlist files that point RAHasher at the real data
|
||||
# tracks. Handing RAHasher one of these reproduces the hash a shell-expanded
|
||||
# glob would, in priority order: a per-disc descriptor (.cue/.gdi) wins over
|
||||
@@ -179,6 +186,7 @@ RA_BUFFER_HASH_UNSUPPORTED_IDS: frozenset[int] = frozenset(
|
||||
PSP_RA_ID: int = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.PSP]
|
||||
NGC_RA_ID: int = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.NGC]
|
||||
WII_RA_ID: int = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.WII]
|
||||
ARCADE_RA_ID: int = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.ARCADE]
|
||||
|
||||
|
||||
class RAHasherError(Exception): ...
|
||||
@@ -263,6 +271,38 @@ class RAHasherService:
|
||||
if is_native_entry:
|
||||
file_path = entry_str
|
||||
|
||||
# RAHasher only decompresses .zip archives itself; any other container
|
||||
# gets hashed as its raw archive bytes, silently storing a hash that
|
||||
# matches nothing on RetroAchievements (issue #3808). Extract the ROM
|
||||
# to a temp file and hash that instead. Arcade is exempt: its RA hash
|
||||
# is the file's own basename, so the container format never matters
|
||||
# and extraction (which renames the file) would break it.
|
||||
lower_path = file_path.lower()
|
||||
if (
|
||||
lower_path.endswith(tuple(COMPRESSED_FILE_EXTENSIONS))
|
||||
and not lower_path.endswith(RAHASHER_NATIVE_ARCHIVE_EXTENSIONS)
|
||||
and platform["ra_id"] != ARCADE_RA_ID
|
||||
):
|
||||
with tempfile.TemporaryDirectory(prefix="romm_rahasher_") as tmp_dir:
|
||||
extracted = await asyncio.to_thread(
|
||||
extract_largest_archive_member, Path(file_path), Path(tmp_dir)
|
||||
)
|
||||
if extracted is None:
|
||||
log.debug(
|
||||
f"Skipping {hl('RAHasher', color=LIGHTMAGENTA)} for "
|
||||
f"{hl(file_path)}: could not extract a ROM from the archive"
|
||||
)
|
||||
return ""
|
||||
return await self._hash_resolved_file(platform, str(extracted))
|
||||
|
||||
return await self._hash_resolved_file(platform, file_path)
|
||||
|
||||
async def _hash_resolved_file(
|
||||
self, platform: RAGamesPlatform, file_path: str
|
||||
) -> str:
|
||||
"""Hash a single real file: natively for containers RAHasher can't
|
||||
read (PSP compressed ISOs, RVZ/WIA), via the RAHasher binary otherwise.
|
||||
"""
|
||||
# PSP compressed-ISO containers (.cso/.ciso/.zso/.dax) can't be read by
|
||||
# RAHasher ("Could not open track"). Compute the PSP RA hash natively
|
||||
# from the container instead, decompressing only PARAM.SFO + EBOOT.BIN.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1153,6 +1153,260 @@ class TestRAHasherM3uNativeResolution:
|
||||
assert str(disc1) in call_args
|
||||
|
||||
|
||||
class TestRAHasherArchiveExtraction:
|
||||
"""Non-zip archives on buffer-hash platforms must be extracted to a temp
|
||||
file before hashing. RAHasher only decompresses .zip itself; any other
|
||||
container is hashed as raw archive bytes, silently producing a hash that
|
||||
matches nothing on RetroAchievements (GitHub issue #3808)."""
|
||||
|
||||
@pytest.fixture
|
||||
def service(self):
|
||||
return RAHasherService()
|
||||
|
||||
@staticmethod
|
||||
def _fake_extractor(inner_name: str):
|
||||
"""Build an extractor mock that writes `inner_name` into the given
|
||||
destination directory, like the real helper does."""
|
||||
|
||||
def _extract(archive_path, dest_dir):
|
||||
extracted = dest_dir / inner_name
|
||||
extracted.write_bytes(b"rom-bytes")
|
||||
return extracted
|
||||
|
||||
return MagicMock(side_effect=_extract)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"ext", [".7z", ".rar", ".gz", ".bz2", ".xz", ".tar", ".tgz"]
|
||||
)
|
||||
async def test_non_zip_archive_extracted_before_hashing(
|
||||
self, service: RAHasherService, ext
|
||||
):
|
||||
"""RAHasher must receive the extracted ROM file, never the archive."""
|
||||
gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA]
|
||||
extractor = self._fake_extractor("game.gba")
|
||||
|
||||
mock_proc = AsyncMock()
|
||||
mock_proc.wait.return_value = 0
|
||||
mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n"
|
||||
mock_proc.stderr = None
|
||||
|
||||
with (
|
||||
patch(
|
||||
"adapters.services.rahasher.extract_largest_archive_member",
|
||||
extractor,
|
||||
),
|
||||
patch(
|
||||
"asyncio.create_subprocess_exec", return_value=mock_proc
|
||||
) as mock_subprocess,
|
||||
):
|
||||
result = await service.calculate_hash(
|
||||
{"ra_id": gba_id, "slug": "gba"}, f"/roms/gba/game{ext}"
|
||||
)
|
||||
|
||||
assert result == "a1b2c3d4e5f6789012345678901234ab"
|
||||
extractor.assert_called_once()
|
||||
call_args = mock_subprocess.call_args[0]
|
||||
assert any(str(a).endswith("game.gba") for a in call_args)
|
||||
assert not any(str(a).endswith(ext) for a in call_args)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_zip_archive_still_handed_to_rahasher_directly(
|
||||
self, service: RAHasherService
|
||||
):
|
||||
"""RAHasher decompresses .zip natively; no extraction round-trip."""
|
||||
gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA]
|
||||
|
||||
mock_proc = AsyncMock()
|
||||
mock_proc.wait.return_value = 0
|
||||
mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n"
|
||||
mock_proc.stderr = None
|
||||
|
||||
with (
|
||||
patch(
|
||||
"adapters.services.rahasher.extract_largest_archive_member"
|
||||
) as extractor,
|
||||
patch(
|
||||
"asyncio.create_subprocess_exec", return_value=mock_proc
|
||||
) as mock_subprocess,
|
||||
):
|
||||
result = await service.calculate_hash(
|
||||
{"ra_id": gba_id, "slug": "gba"}, "/roms/gba/game.zip"
|
||||
)
|
||||
|
||||
assert result == "a1b2c3d4e5f6789012345678901234ab"
|
||||
extractor.assert_not_called()
|
||||
call_args = mock_subprocess.call_args[0]
|
||||
assert "/roms/gba/game.zip" in call_args
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_extraction_failure_returns_empty_hash_without_rahasher(
|
||||
self, service: RAHasherService
|
||||
):
|
||||
"""When extraction fails (unsupported codec, corrupt archive), no
|
||||
hash is produced at all; the archive must never reach RAHasher,
|
||||
which would silently hash the raw container bytes."""
|
||||
gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA]
|
||||
|
||||
with (
|
||||
patch(
|
||||
"adapters.services.rahasher.extract_largest_archive_member",
|
||||
return_value=None,
|
||||
) as extractor,
|
||||
patch("asyncio.create_subprocess_exec") as mock_subprocess,
|
||||
):
|
||||
result = await service.calculate_hash(
|
||||
{"ra_id": gba_id, "slug": "gba"}, "/roms/gba/game.rar"
|
||||
)
|
||||
|
||||
assert result == ""
|
||||
extractor.assert_called_once()
|
||||
mock_subprocess.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_arcade_archives_bypass_extraction(self, service: RAHasherService):
|
||||
"""Arcade RA hashes are computed from the file's basename, not its
|
||||
contents, so any container format already hashes correctly and
|
||||
extraction (which renames the file) would break it."""
|
||||
arcade_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.ARCADE]
|
||||
|
||||
mock_proc = AsyncMock()
|
||||
mock_proc.wait.return_value = 0
|
||||
mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n"
|
||||
mock_proc.stderr = None
|
||||
|
||||
with (
|
||||
patch(
|
||||
"adapters.services.rahasher.extract_largest_archive_member"
|
||||
) as extractor,
|
||||
patch(
|
||||
"asyncio.create_subprocess_exec", return_value=mock_proc
|
||||
) as mock_subprocess,
|
||||
):
|
||||
result = await service.calculate_hash(
|
||||
{"ra_id": arcade_id, "slug": "arcade"}, "/roms/arcade/sf2.7z"
|
||||
)
|
||||
|
||||
assert result == "a1b2c3d4e5f6789012345678901234ab"
|
||||
extractor.assert_not_called()
|
||||
call_args = mock_subprocess.call_args[0]
|
||||
assert "/roms/arcade/sf2.7z" in call_args
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disc_platform_archives_still_skipped_without_extraction(
|
||||
self, service: RAHasherService
|
||||
):
|
||||
"""Disc platforms keep the existing skip; no extraction is attempted
|
||||
(a multi-gigabyte disc image round-trip is out of scope)."""
|
||||
psx_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.PSX]
|
||||
|
||||
with (
|
||||
patch(
|
||||
"adapters.services.rahasher.extract_largest_archive_member"
|
||||
) as extractor,
|
||||
patch("asyncio.create_subprocess_exec") as mock_subprocess,
|
||||
):
|
||||
result = await service.calculate_hash(
|
||||
{"ra_id": psx_id, "slug": "psx"}, "/roms/psx/game.7z"
|
||||
)
|
||||
|
||||
assert result == ""
|
||||
extractor.assert_not_called()
|
||||
mock_subprocess.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_folder_of_non_zip_archives_extracts_largest(
|
||||
self, service: RAHasherService, tmp_path
|
||||
):
|
||||
"""Folder-based ROM holding non-zip archives: the largest archive is
|
||||
picked (existing behavior) and must then go through extraction."""
|
||||
gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA]
|
||||
(tmp_path / "small.7z").write_bytes(b"s" * 100)
|
||||
large = tmp_path / "large.7z"
|
||||
large.write_bytes(b"l" * 500)
|
||||
extractor = self._fake_extractor("game.gba")
|
||||
|
||||
mock_proc = AsyncMock()
|
||||
mock_proc.wait.return_value = 0
|
||||
mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n"
|
||||
mock_proc.stderr = None
|
||||
|
||||
with (
|
||||
patch(
|
||||
"adapters.services.rahasher.extract_largest_archive_member",
|
||||
extractor,
|
||||
),
|
||||
patch(
|
||||
"asyncio.create_subprocess_exec", return_value=mock_proc
|
||||
) as mock_subprocess,
|
||||
):
|
||||
result = await service.calculate_hash(
|
||||
{"ra_id": gba_id, "slug": "gba"}, f"{tmp_path}/*"
|
||||
)
|
||||
|
||||
assert result == "a1b2c3d4e5f6789012345678901234ab"
|
||||
assert extractor.call_args[0][0] == large
|
||||
call_args = mock_subprocess.call_args[0]
|
||||
assert any(str(a).endswith("game.gba") for a in call_args)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_extracted_rvz_short_circuits_native_hasher(
|
||||
self, service: RAHasherService
|
||||
):
|
||||
"""GameCube is buffer-hash capable, so its archives are extracted;
|
||||
when the archive holds an .rvz the native hasher must see it."""
|
||||
ngc_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.NGC]
|
||||
extractor = self._fake_extractor("game.rvz")
|
||||
|
||||
with (
|
||||
patch(
|
||||
"adapters.services.rahasher.extract_largest_archive_member",
|
||||
extractor,
|
||||
),
|
||||
patch(
|
||||
"adapters.services.rahasher.calculate_gamecube_ra_hash",
|
||||
return_value="a1b2c3d4e5f6789012345678901234ab",
|
||||
) as mock_native,
|
||||
patch("asyncio.create_subprocess_exec") as mock_subprocess,
|
||||
):
|
||||
result = await service.calculate_hash(
|
||||
{"ra_id": ngc_id, "slug": "ngc"}, "/roms/ngc/game.7z"
|
||||
)
|
||||
|
||||
assert result == "a1b2c3d4e5f6789012345678901234ab"
|
||||
assert mock_native.call_args[0][0].endswith("game.rvz")
|
||||
mock_subprocess.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_temp_extraction_dir_removed_after_hashing(
|
||||
self, service: RAHasherService
|
||||
):
|
||||
"""The temp directory holding the extracted ROM must not outlive the
|
||||
hash calculation."""
|
||||
gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA]
|
||||
extractor = self._fake_extractor("game.gba")
|
||||
|
||||
mock_proc = AsyncMock()
|
||||
mock_proc.wait.return_value = 0
|
||||
mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n"
|
||||
mock_proc.stderr = None
|
||||
|
||||
with (
|
||||
patch(
|
||||
"adapters.services.rahasher.extract_largest_archive_member",
|
||||
extractor,
|
||||
),
|
||||
patch("asyncio.create_subprocess_exec", return_value=mock_proc),
|
||||
):
|
||||
result = await service.calculate_hash(
|
||||
{"ra_id": gba_id, "slug": "gba"}, "/roms/gba/game.7z"
|
||||
)
|
||||
|
||||
assert result == "a1b2c3d4e5f6789012345678901234ab"
|
||||
dest_dir = extractor.call_args[0][1]
|
||||
assert not dest_dir.exists()
|
||||
|
||||
|
||||
class TestRAHasherError:
|
||||
"""Test the RAHasherError exception."""
|
||||
|
||||
|
||||
@@ -10,6 +10,55 @@ def _fake_7z_listing(names: list[str]) -> str:
|
||||
return "\n".join(f"Path = {name}\nSize = 10\nAttributes = A\n" for name in names)
|
||||
|
||||
|
||||
def _fake_7z_listing_sized(
|
||||
entries: list[tuple[str, int]], attributes: bool = True
|
||||
) -> str:
|
||||
"""Build a `7zz l -slt -ba` style listing with explicit member sizes.
|
||||
|
||||
Single-stream formats (.gz/.xz) list no Attributes line at all, which
|
||||
`attributes=False` reproduces.
|
||||
"""
|
||||
blocks = []
|
||||
for name, size in entries:
|
||||
block = f"Path = {name}\nSize = {size}\n"
|
||||
if attributes:
|
||||
block += "Attributes = A -rw-rw-r--\n"
|
||||
blocks.append(block)
|
||||
return "\n".join(blocks)
|
||||
|
||||
|
||||
def _mock_popen_streaming(
|
||||
chunk_streams: list[list[bytes]],
|
||||
returncodes: list[int],
|
||||
stderr: bytes = b"",
|
||||
):
|
||||
"""Build a subprocess.Popen mock whose consecutive context-managed calls
|
||||
stream the given chunk lists and finish with the given return codes.
|
||||
|
||||
`stderr` bytes are written into the file object the caller passes as the
|
||||
`stderr` argument, mirroring 7zz writing diagnostics to a file-backed
|
||||
stderr."""
|
||||
popen = MagicMock()
|
||||
processes = []
|
||||
for chunks, returncode in zip(chunk_streams, returncodes, strict=True):
|
||||
process = MagicMock()
|
||||
process.stdout.read.side_effect = [*chunks, b""]
|
||||
process.returncode = returncode
|
||||
processes.append(process)
|
||||
process_iter = iter(processes)
|
||||
|
||||
def _popen_call(*args, **kwargs):
|
||||
stderr_target = kwargs.get("stderr")
|
||||
if stderr and stderr_target is not None:
|
||||
stderr_target.write(stderr)
|
||||
context = MagicMock()
|
||||
context.__enter__.return_value = next(process_iter)
|
||||
return context
|
||||
|
||||
popen.side_effect = _popen_call
|
||||
return popen
|
||||
|
||||
|
||||
def test_stream_7z_chunks_yields_until_eof():
|
||||
process = MagicMock()
|
||||
process.stdout.read.side_effect = [b"abc", b"def", b""]
|
||||
@@ -60,3 +109,188 @@ def test_read_7z_archive_files_timeout_logs_once_without_spam(monkeypatch):
|
||||
assert results == []
|
||||
popen_patch.assert_not_called()
|
||||
assert log_error.call_count == 1
|
||||
|
||||
|
||||
class TestExtractLargestArchiveMember:
|
||||
"""Extraction of an archive's largest member to a destination directory,
|
||||
used to feed RAHasher a real ROM file instead of raw container bytes
|
||||
(GitHub issue #3808)."""
|
||||
|
||||
def test_extracts_largest_member_to_dest_dir(self, tmp_path):
|
||||
listing = MagicMock(
|
||||
stdout=_fake_7z_listing_sized([("small.txt", 10), ("game.gba", 500)])
|
||||
)
|
||||
popen = _mock_popen_streaming([[b"abc", b"def"]], [0])
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", return_value=listing),
|
||||
patch.object(archives.subprocess, "Popen", popen),
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.7z"), tmp_path
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result == tmp_path / "game.gba"
|
||||
assert result.read_bytes() == b"abcdef"
|
||||
# The largest member, not the first, must be requested from 7zz, with
|
||||
# wildcard matching disabled so a member name containing "*" or "?"
|
||||
# can't select (and concatenate) other members.
|
||||
extract_args = popen.call_args[0][0]
|
||||
assert "game.gba" in extract_args
|
||||
assert "-spd" in extract_args
|
||||
|
||||
def test_member_folder_prefix_is_stripped_from_dest_name(self, tmp_path):
|
||||
"""Members nested in archive folders extract to a flat file name."""
|
||||
listing = MagicMock(stdout=_fake_7z_listing_sized([("subdir/game.gba", 500)]))
|
||||
popen = _mock_popen_streaming([[b"abc"]], [0])
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", return_value=listing),
|
||||
patch.object(archives.subprocess, "Popen", popen),
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.7z"), tmp_path
|
||||
)
|
||||
|
||||
assert result == tmp_path / "game.gba"
|
||||
|
||||
def test_listing_without_attributes_still_finds_member(self, tmp_path):
|
||||
"""Single-stream formats (.gz/.xz) list no Attributes line; the member
|
||||
must still be found (7zz omits it for them)."""
|
||||
listing = MagicMock(
|
||||
stdout=_fake_7z_listing_sized([("game.gba", 500)], attributes=False)
|
||||
)
|
||||
popen = _mock_popen_streaming([[b"abc"]], [0])
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", return_value=listing),
|
||||
patch.object(archives.subprocess, "Popen", popen),
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.gba.gz"), tmp_path
|
||||
)
|
||||
|
||||
assert result == tmp_path / "game.gba"
|
||||
|
||||
def test_directory_members_are_ignored(self, tmp_path):
|
||||
listing = MagicMock(
|
||||
stdout=(
|
||||
"Path = folder\nSize = 0\nAttributes = D drwxr-xr-x\n\n"
|
||||
+ _fake_7z_listing_sized([("game.gba", 500)])
|
||||
)
|
||||
)
|
||||
popen = _mock_popen_streaming([[b"abc"]], [0])
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", return_value=listing),
|
||||
patch.object(archives.subprocess, "Popen", popen),
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.7z"), tmp_path
|
||||
)
|
||||
|
||||
assert result == tmp_path / "game.gba"
|
||||
|
||||
def test_nested_archive_is_extracted_once_more(self, tmp_path):
|
||||
"""A .tgz lists only its inner .tar; the ROM inside the tar must be
|
||||
reached through a second extraction pass."""
|
||||
listings = [
|
||||
MagicMock(stdout=_fake_7z_listing_sized([("game.tar", 600)])),
|
||||
MagicMock(stdout=_fake_7z_listing_sized([("game.gba", 500)])),
|
||||
]
|
||||
popen = _mock_popen_streaming([[b"tarbytes"], [b"rombytes"]], [0, 0])
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", side_effect=listings),
|
||||
patch.object(archives.subprocess, "Popen", popen),
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.tgz"), tmp_path
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result == tmp_path / "game.gba"
|
||||
assert result.read_bytes() == b"rombytes"
|
||||
# The intermediate tar must not be left behind.
|
||||
assert not (tmp_path / "game.tar").exists()
|
||||
|
||||
def test_gives_up_on_doubly_nested_archives(self, tmp_path):
|
||||
"""Two levels of nesting is the limit; deeper nesting returns None
|
||||
and leaves no partial files behind."""
|
||||
listings = [
|
||||
MagicMock(stdout=_fake_7z_listing_sized([("inner.tar", 600)])),
|
||||
MagicMock(stdout=_fake_7z_listing_sized([("innermost.7z", 500)])),
|
||||
]
|
||||
popen = _mock_popen_streaming([[b"tarbytes"], [b"7zbytes"]], [0, 0])
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", side_effect=listings),
|
||||
patch.object(archives.subprocess, "Popen", popen),
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.tgz"), tmp_path
|
||||
)
|
||||
|
||||
assert result is None
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
|
||||
def test_returns_none_when_listing_fails(self, tmp_path):
|
||||
with patch.object(
|
||||
archives.subprocess,
|
||||
"run",
|
||||
side_effect=archives.subprocess.CalledProcessError(2, "7zz"),
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.7z"), tmp_path
|
||||
)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_returns_none_when_archive_has_no_members(self, tmp_path):
|
||||
listing = MagicMock(stdout="")
|
||||
|
||||
with patch.object(archives.subprocess, "run", return_value=listing):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.7z"), tmp_path
|
||||
)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_returns_none_and_cleans_up_on_extract_failure(self, tmp_path):
|
||||
"""A codec the 7zz build can't decompress (e.g. RAR) streams nothing
|
||||
and exits non-zero; no partial file may be left behind, and the 7zz
|
||||
reason must reach the error log so scans explain the missing hash."""
|
||||
listing = MagicMock(stdout=_fake_7z_listing_sized([("game.gba", 500)]))
|
||||
popen = _mock_popen_streaming(
|
||||
[[]], [2], stderr=b"ERROR: Unsupported Method : game.gba"
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", return_value=listing),
|
||||
patch.object(archives.subprocess, "Popen", popen),
|
||||
patch.object(archives.log, "error") as log_error,
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.rar"), tmp_path
|
||||
)
|
||||
|
||||
assert result is None
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
assert "Unsupported Method" in log_error.call_args[0][0]
|
||||
|
||||
def test_returns_none_and_cleans_up_on_timeout(self, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(archives, "SEVEN_ZIP_TIMEOUT", -1)
|
||||
listing = MagicMock(stdout=_fake_7z_listing_sized([("game.gba", 500)]))
|
||||
popen = _mock_popen_streaming([[b"abc", b"def"]], [0])
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", return_value=listing),
|
||||
patch.object(archives.subprocess, "Popen", popen),
|
||||
):
|
||||
result = archives.extract_largest_archive_member(
|
||||
Path("/fake/game.7z"), tmp_path
|
||||
)
|
||||
|
||||
assert result is None
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
|
||||
@@ -5,6 +5,7 @@ import fnmatch
|
||||
import os
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
@@ -155,7 +156,7 @@ def _process_largest_7z_member(
|
||||
start_decompression_time = time.monotonic()
|
||||
|
||||
with subprocess.Popen(
|
||||
[SEVEN_ZIP_PATH, "e", str(file_path), largest_file, "-so", "-y"],
|
||||
[SEVEN_ZIP_PATH, "e", str(file_path), largest_file, "-so", "-y", "-spd"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated
|
||||
@@ -369,7 +370,7 @@ def read_7z_archive_files(
|
||||
break
|
||||
try:
|
||||
with subprocess.Popen(
|
||||
[SEVEN_ZIP_PATH, "e", str(file_path), name, "-so", "-y"],
|
||||
[SEVEN_ZIP_PATH, "e", str(file_path), name, "-so", "-y", "-spd"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
shell=False, # trunk-ignore(bandit/B603)
|
||||
@@ -399,11 +400,151 @@ def read_rar_archive_files(
|
||||
) -> Iterator[tuple[str, int, Iterator[bytes]]]:
|
||||
"""Yield eligible files from a RAR archive, sorted by internal path (ASCII).
|
||||
|
||||
Delegates to the 7zz binary, which natively supports RAR (v3-v5, read-only).
|
||||
Delegates to the 7zz binary. Listing RAR members always works, but
|
||||
streaming their contents requires a 7zz build with the RAR codec; the
|
||||
bundled Alpine build lacks it, so content reads fail and log an error.
|
||||
"""
|
||||
return read_7z_archive_files(file_path, excluded_names, excluded_exts)
|
||||
|
||||
|
||||
def _list_archive_file_members(file_path: Path) -> list[tuple[str, int]]:
|
||||
"""List `(member_path, size)` for every file member via `7zz l -slt -ba`.
|
||||
|
||||
Single-stream formats (.gz/.xz) list no `Attributes` line at all, so an
|
||||
entry is committed when the next `Path =` starts or the listing ends,
|
||||
and only dropped when its attributes mark it as a directory.
|
||||
"""
|
||||
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
|
||||
)
|
||||
except (
|
||||
subprocess.TimeoutExpired,
|
||||
subprocess.CalledProcessError,
|
||||
FileNotFoundError,
|
||||
) as e:
|
||||
log.error(f"Error listing archive {file_path}: {e}")
|
||||
return []
|
||||
|
||||
entries: list[tuple[str, int]] = []
|
||||
current_file: str | None = None
|
||||
current_size = 0
|
||||
current_is_dir = False
|
||||
|
||||
def _commit() -> None:
|
||||
if current_file and not current_is_dir:
|
||||
entries.append((current_file, current_size))
|
||||
|
||||
for line in result.stdout.split("\n"):
|
||||
line = line.lstrip()
|
||||
if line.startswith("Path = "):
|
||||
_commit()
|
||||
current_file = line.split(" = ", 1)[1]
|
||||
current_size = 0
|
||||
current_is_dir = False
|
||||
elif line.startswith("Size = "):
|
||||
try:
|
||||
current_size = int(line.split(" = ")[1].strip())
|
||||
except ValueError:
|
||||
current_size = 0
|
||||
elif line.startswith("Attributes = "):
|
||||
current_is_dir = line.split(" = ")[1].strip().startswith("D")
|
||||
_commit()
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def _extract_member_to_dir(
|
||||
file_path: Path, member: str, dest_dir: Path, deadline: float
|
||||
) -> Path | None:
|
||||
"""Stream one archive member into `dest_dir`, named after its basename.
|
||||
|
||||
Returns None (leaving no partial file) when extraction fails, exceeds
|
||||
the deadline, or the 7zz build lacks the codec (it then streams nothing
|
||||
and exits non-zero, e.g. for RAR).
|
||||
"""
|
||||
dest_path = dest_dir / Path(member).name
|
||||
try:
|
||||
# stderr goes to an unlinked temp file rather than a pipe: a pipe can
|
||||
# fill and block 7zz while this thread waits on stdout, stalling past
|
||||
# the deadline. "-spd" disables wildcard matching so a member name
|
||||
# containing "*" or "?" can't select (and concatenate) other members.
|
||||
with tempfile.TemporaryFile() as stderr_file:
|
||||
with (
|
||||
open(dest_path, "wb") as dest_file,
|
||||
subprocess.Popen(
|
||||
[SEVEN_ZIP_PATH, "e", str(file_path), member, "-so", "-y", "-spd"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=stderr_file,
|
||||
shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated
|
||||
) as process,
|
||||
):
|
||||
assert process.stdout is not None
|
||||
while chunk := process.stdout.read(FILE_READ_CHUNK_SIZE):
|
||||
if time.monotonic() > deadline:
|
||||
process.terminate()
|
||||
log.error(f"Extraction of {member} from {file_path} timed out")
|
||||
dest_path.unlink(missing_ok=True)
|
||||
return None
|
||||
dest_file.write(chunk)
|
||||
|
||||
if process.returncode != 0:
|
||||
# Surface the 7zz reason (e.g. "Unsupported Method" from a
|
||||
# build without the RAR codec) so scan logs explain the
|
||||
# missing hash.
|
||||
stderr_file.seek(0)
|
||||
detail = stderr_file.read().decode(errors="replace").strip()
|
||||
log.error(
|
||||
f"Extraction of {member} from {file_path} failed "
|
||||
f"with code {process.returncode}: {detail or 'no error output'}"
|
||||
)
|
||||
dest_path.unlink(missing_ok=True)
|
||||
return None
|
||||
|
||||
return dest_path
|
||||
except OSError as e:
|
||||
log.error(f"Error extracting {member} from {file_path}: {e}")
|
||||
dest_path.unlink(missing_ok=True)
|
||||
return None
|
||||
|
||||
|
||||
def extract_largest_archive_member(file_path: Path, dest_dir: Path) -> Path | None:
|
||||
"""Extract an archive's largest file member into `dest_dir` via 7zz.
|
||||
|
||||
Compressed tarballs (.tgz/.tbz2/.txz) list only their inner .tar, so one
|
||||
nested extraction pass unwraps it; deeper nesting gives up. Returns the
|
||||
extracted file's path, or None on any failure (no partial files remain).
|
||||
"""
|
||||
deadline = time.monotonic() + SEVEN_ZIP_TIMEOUT
|
||||
source = file_path
|
||||
|
||||
for _ in range(2):
|
||||
members = _list_archive_file_members(source)
|
||||
extracted = (
|
||||
_extract_member_to_dir(
|
||||
source, max(members, key=lambda m: m[1])[0], dest_dir, deadline
|
||||
)
|
||||
if members
|
||||
else None
|
||||
)
|
||||
if source != file_path:
|
||||
source.unlink(missing_ok=True)
|
||||
if extracted is None:
|
||||
return None
|
||||
if not str(extracted).lower().endswith(tuple(COMPRESSED_FILE_EXTENSIONS)):
|
||||
return extracted
|
||||
source = extracted
|
||||
|
||||
log.error(f"Archive {file_path} is nested too deeply to extract")
|
||||
source.unlink(missing_ok=True)
|
||||
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."""
|
||||
if file_path.suffix.lower() == ".chd":
|
||||
|
||||
Reference in New Issue
Block a user