diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 65b7898d6..388906a42 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -193,7 +193,6 @@ from utils.validation import ( from utils.zip_cache import ( BULK_CACHE_MAX_ROMS, ZipFileEntry, - ensure_zipfile_writable, get_bulk_namespace, get_cache_key, get_cached_zip, @@ -1774,7 +1773,6 @@ async def get_rom_content( zip_buffer = BytesIO() now = datetime.now() - ensure_zipfile_writable() with ZipFile(zip_buffer, "w") as zip_file: # Add content files for file in files: diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index 1e4f3b1f0..985192b94 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -104,7 +104,6 @@ from utils.uploads import ( sanitize_asset_filename, ) from utils.validation import RomIdScope, narrow_rom_id_scope -from utils.zip_cache import ensure_zipfile_writable def _build_save_schema( @@ -860,8 +859,6 @@ def _restored_response(restored: RestoredFiles, save: Save) -> Response: SAVE_PATH_HEADER: quote(path), }, ) - # `zipfile_inflate64`, imported for ROM archives, breaks `writestr()` until this runs. - ensure_zipfile_writable() buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf: for path, data in sorted(restored.items()): diff --git a/backend/handler/streaming/imports.py b/backend/handler/streaming/imports.py index f39863370..f3d4b0910 100644 --- a/backend/handler/streaming/imports.py +++ b/backend/handler/streaming/imports.py @@ -18,7 +18,6 @@ from handler.streaming.config import ResolvedContainer, emulator_labels from logger.logger import log from models.assets import Save, State from models.rom import Rom -from utils.zip_cache import ensure_zipfile_writable # Charged on each entry's expanded size, so a small, highly compressible # upload cannot inflate past the ceiling any stored save archive has. @@ -156,7 +155,6 @@ def build_import_archive( Returns: The archive bytes, and the manifest's `files` list actually written. """ - ensure_zipfile_writable() staged: _Staged = {} budget = _ArchiveBudget() if base is not None: diff --git a/backend/handler/sync/retroarch/psp.py b/backend/handler/sync/retroarch/psp.py index 9b7a2aca6..87fc6d1f2 100644 --- a/backend/handler/sync/retroarch/psp.py +++ b/backend/handler/sync/retroarch/psp.py @@ -40,7 +40,6 @@ from models.rom import Rom from models.user import User from utils.memory_cards import content_hash_of_bytes from utils.uploads import apply_datetime_tag -from utils.zip_cache import ensure_zipfile_writable _IGNORED_CATEGORY = "SYSTEM" _SAVEDATA_CATEGORY = "SAVEDATA" @@ -323,9 +322,6 @@ def _load_bundle_member_names(path: Path) -> list[str]: def _write_bundle(entries: dict[str, bytes]) -> bytes: - # `zipfile_inflate64` is imported elsewhere for ROM archive reading, and - # breaks `writestr()` until this runs. - ensure_zipfile_writable() buffer = BytesIO() with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf: for name, data in entries.items(): diff --git a/backend/tests/endpoints/roms/test_patch.py b/backend/tests/endpoints/roms/test_patch.py index 1624db039..6ec29c654 100644 --- a/backend/tests/endpoints/roms/test_patch.py +++ b/backend/tests/endpoints/roms/test_patch.py @@ -23,7 +23,6 @@ from models.rom import Rom, RomFile, RomFileCategory from models.user import User from utils.nginx import content_disposition from utils.rom_patcher import PatcherInputError -from utils.zip_cache import ensure_zipfile_writable def _patch_file(rom: Rom) -> RomFile: @@ -226,7 +225,6 @@ class TestPatchingALibraryFile: node: None, ): archive = io.BytesIO() - ensure_zipfile_writable() with zipfile.ZipFile(archive, "w") as zipped: zipped.writestr("game.sfc", b"rom") zipped.writestr("readme.txt", b"hi") diff --git a/backend/tests/endpoints/test_save_conversion.py b/backend/tests/endpoints/test_save_conversion.py index 26e108bd1..37eb30f59 100644 --- a/backend/tests/endpoints/test_save_conversion.py +++ b/backend/tests/endpoints/test_save_conversion.py @@ -38,7 +38,6 @@ from models.device import Device from models.permission import HiddenEntity, PermEntity from models.rom import Rom, RomFile from models.user import User -from utils.zip_cache import ensure_zipfile_writable UNIT = b"stored unit" GAME = SigilGame(result=SimpleNamespace(platform="psx"), game_ids=("SLUS-01041",)) @@ -57,7 +56,6 @@ def _stored(save: Save, data: bytes = UNIT) -> Save: def _neutral_gba_unit() -> bytes: - ensure_zipfile_writable() buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as zf: zf.writestr("save.sram", b"battery") diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index cc5c30e6a..0c66a8f45 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -117,7 +117,6 @@ from models.rom import Rom, RomFile, RomFileCategory, SaveTargetLayout from models.user import Role, User from utils.memory_cards import content_hash_of_bytes from utils.uploads import apply_datetime_tag -from utils.zip_cache import ensure_zipfile_writable # ── Fixtures / helpers ──────────────────────────────────────────────────────── @@ -6507,7 +6506,6 @@ def _exit_archive( ) -> bytes: """A webstation exit archive whose manifest labels each member with its kind, each member stamped with its `written` time when one is given.""" - ensure_zipfile_writable() buf = io.BytesIO() with zipfile.ZipFile(buf, "w") as zf: for path, (_kind, content) in members.items(): diff --git a/backend/tests/utils/test_archives.py b/backend/tests/utils/test_archives.py index e83de8915..894837e83 100644 --- a/backend/tests/utils/test_archives.py +++ b/backend/tests/utils/test_archives.py @@ -17,7 +17,6 @@ import pytest from logger.logger import log from utils import archives -from utils.zip_cache import ensure_zipfile_writable def _fake_7z_listing(names: list[str]) -> str: @@ -712,9 +711,6 @@ def _tar_bytes(members: dict[str, bytes]) -> bytes: 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(): @@ -1049,3 +1045,23 @@ def test_real_ppmd_zip_hashes_through_7zz(tmp_path): ("Game (USA) (Track 01).bin", len(track), hashlib.sha1(track).hexdigest()), ("Game (USA).cue", len(cue), hashlib.sha1(cue).hexdigest()), ] + + +@pytest.mark.parametrize( + "compression", + [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED, zipfile.ZIP_ZSTANDARD], +) +def test_zip_writes_after_inflate64_patch(compression: int, tmp_path: Path) -> None: + src = tmp_path / "src.bin" + src.write_bytes(b"from disk") + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", compression, compresslevel=1) as z: + z.writestr("a.txt", b"hello") + z.write(src, arcname="b.bin") + with z.open("c.txt", "w") as member: + member.write(b"streamed") + + with zipfile.ZipFile(buf) as z: + assert z.read("a.txt") == b"hello" + assert z.read("b.bin") == b"from disk" + assert z.read("c.txt") == b"streamed" diff --git a/backend/tests/utils/test_rom_patcher.py b/backend/tests/utils/test_rom_patcher.py index 79d920450..1193eee0d 100644 --- a/backend/tests/utils/test_rom_patcher.py +++ b/backend/tests/utils/test_rom_patcher.py @@ -24,7 +24,6 @@ from utils.rom_patcher.patcher import ( MIN_PATCH_OUTPUT_GROWTH_BYTES, max_patch_output_size, ) -from utils.zip_cache import ensure_zipfile_writable def _write_zip( @@ -33,7 +32,6 @@ def _write_zip( *, comment: bytes = b"", ) -> None: - ensure_zipfile_writable() with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive: archive.comment = comment for name, content in members.items(): diff --git a/backend/tests/utils/test_zip_cache.py b/backend/tests/utils/test_zip_cache.py index 1248ff857..1a7fa001e 100644 --- a/backend/tests/utils/test_zip_cache.py +++ b/backend/tests/utils/test_zip_cache.py @@ -428,25 +428,6 @@ class TestZipFileEntryFromRomFile: ) -class TestEnsureZipfileWritable: - def test_writestr_works_after_inflate64_patch(self, library, mocker): - # Simulates the zipfile_inflate64 patch: a wrapper that drops the - # compresslevel argument, which breaks ZipFile.write() on CPython 3.13. - import zipfile - - original = zipfile._get_compressor # type: ignore[attr-defined] - - def one_arg_wrapper(compress_type): - return original(compress_type) - - mocker.patch.object(zipfile, "_get_compressor", one_arg_wrapper) - - result = build_library_zip(m3u_content=b"a.bin", m3u_filename="game.m3u") - with ZipFile(result) as zf: - assert zf.read("a.bin") == b"data" - assert zf.read("game.m3u") == b"a.bin" - - class TestCachedZipReadability: def test_build_leaves_archive_nginx_readable(self, library): result = build_library_zip() diff --git a/backend/utils/archives.py b/backend/utils/archives.py index 5e57cc537..92e007c78 100644 --- a/backend/utils/archives.py +++ b/backend/utils/archives.py @@ -29,6 +29,17 @@ from utils.filesystem import ( ArchiveFormat, ) +_inflate64_get_compressor = zipfile._get_compressor # type: ignore[attr-defined] + + +def _get_compressor(compress_type: int, compresslevel: int | None = None) -> object: + # zipfile_inflate64's patch takes only compress_type, but CPython passes + # compresslevel too, so every zip write would raise TypeError without this. + return _inflate64_get_compressor(compress_type) + + +zipfile._get_compressor = _get_compressor # type: ignore[attr-defined] + # 7zip archives are read through 7zz. SEVEN_ZIP_PATH = "/usr/bin/7zz" # RAR archives are read through bsdtar. diff --git a/backend/utils/rom_patcher/patcher.py b/backend/utils/rom_patcher/patcher.py index d0a6328a7..3cacf1ad8 100644 --- a/backend/utils/rom_patcher/patcher.py +++ b/backend/utils/rom_patcher/patcher.py @@ -27,7 +27,6 @@ from utils.archives import ( read_zip_archive_files, ) from utils.filesystem import COMPRESSED_FILE_EXTENSIONS -from utils.zip_cache import ensure_zipfile_writable PATCHER_SCRIPT = Path(__file__).parent / "patcher.js" @@ -189,7 +188,6 @@ def _rebuild_zip( except (EOFError, OSError, RuntimeError, zipfile.BadZipFile, zlib.error) as e: raise PatcherInputError("The ROM archive could not be read") from e - ensure_zipfile_writable() try: with ( source_archive, diff --git a/backend/utils/zip_cache.py b/backend/utils/zip_cache.py index a44e0d1be..3820da2bb 100644 --- a/backend/utils/zip_cache.py +++ b/backend/utils/zip_cache.py @@ -120,36 +120,6 @@ def _namespace_build_lock(namespace_dir: Path) -> Generator[None]: os.close(fd) -def ensure_zipfile_writable() -> None: - """Restore ``zipfile._get_compressor`` to a writable signature. - - ``zipfile_inflate64`` (imported in ``handler/filesystem/roms_handler.py`` - to support Enhanced Deflate) replaces ``zipfile._get_compressor`` with a - wrapper that only accepts ``compress_type``. CPython 3.13 calls it with - ``(compress_type, compresslevel)``, so ``ZipFile.write()``/``writestr()`` - raise ``TypeError``. Wrap it once with a signature-compatible shim that - drops the extra arg, matching inflate64's own behavior (it already ignores - ``compresslevel``). Idempotent and safe to call from any thread. - """ - current = zipfile._get_compressor # type: ignore[attr-defined] - if getattr(current, "_romm_compresslevel_safe", False): - return - - # Probe with two args: the stdlib accepts them, inflate64's wrapper does not. - try: - current(zipfile.ZIP_STORED, None) - return - except TypeError: - pass - - @functools.wraps(current) - def _get_compressor(compress_type: int, compresslevel: int | None = None) -> object: - return current(compress_type) - - _get_compressor._romm_compresslevel_safe = True # type: ignore[attr-defined] - zipfile._get_compressor = _get_compressor # type: ignore[attr-defined] - - def build_cached_zip( namespace: str, entries: list[ZipFileEntry], @@ -184,7 +154,6 @@ def _write_cached_zip( os.close(fd) try: os.chmod(tmp_path, SERVED_FILE_MODE) - ensure_zipfile_writable() with zipfile.ZipFile(tmp_path, "w") as zf: for entry in entries: src = Path(LIBRARY_BASE_PATH) / entry.full_path