mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 08:58:36 +00:00
rpf9_carve: publish index.json atomically and guard stream outputs aliasing input archive
This commit is contained in:
@ -8,10 +8,13 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
import zlib
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = os.path.join(ROOT, "tools", "rpf9_carve.py")
|
||||
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
||||
import rpf9_carve # noqa: E402
|
||||
|
||||
|
||||
class Rpf9CarveWriteErrorTests(unittest.TestCase):
|
||||
@ -72,6 +75,92 @@ class Rpf9CarveWriteErrorTests(unittest.TestCase):
|
||||
with open(arch, "rb") as f:
|
||||
self.assertEqual(f.read(), original)
|
||||
|
||||
def test_bin_output_aliasing_input_archive_is_refused(self):
|
||||
zdata = zlib.compress(b"A" * 128)
|
||||
out_dir = os.path.join(self.tmp.name, "out_bin_alias")
|
||||
os.makedirs(out_dir)
|
||||
arch = os.path.join(out_dir, f"{16:012x}.bin")
|
||||
with open(arch, "wb") as f:
|
||||
f.write(b"9FPR" + struct.pack("<I", 16) + b"\x00" * 8 + zdata)
|
||||
with open(arch, "rb") as f:
|
||||
original = f.read()
|
||||
p = subprocess.run([sys.executable, "-I", TOOL, arch, out_dir], capture_output=True, text=True)
|
||||
self.assertNotEqual(p.returncode, 0)
|
||||
self.assertIn("must not overwrite input archive", p.stderr)
|
||||
self.assertNotIn("Traceback", p.stderr)
|
||||
with open(arch, "rb") as f:
|
||||
self.assertEqual(f.read(), original)
|
||||
|
||||
def test_bk2_output_aliasing_input_archive_is_refused(self):
|
||||
blen = 64
|
||||
bk2 = bytearray(blen)
|
||||
bk2[0:4] = b"KB2i"
|
||||
struct.pack_into("<II", bk2, 4, blen - 8, 10)
|
||||
struct.pack_into("<II", bk2, 0x14, 1280, 720)
|
||||
out_dir = os.path.join(self.tmp.name, "out_bk2_alias")
|
||||
os.makedirs(out_dir)
|
||||
arch = os.path.join(out_dir, f"{16:012x}.bk2")
|
||||
with open(arch, "wb") as f:
|
||||
f.write(b"9FPR" + struct.pack("<I", 16) + b"\x00" * 8 + bytes(bk2))
|
||||
with open(arch, "rb") as f:
|
||||
original = f.read()
|
||||
p = subprocess.run([sys.executable, "-I", TOOL, arch, out_dir], capture_output=True, text=True)
|
||||
self.assertNotEqual(p.returncode, 0)
|
||||
self.assertIn("must not overwrite input archive", p.stderr)
|
||||
self.assertNotIn("Traceback", p.stderr)
|
||||
with open(arch, "rb") as f:
|
||||
self.assertEqual(f.read(), original)
|
||||
|
||||
def test_failed_index_replace_preserves_previous_and_cleans_staging(self):
|
||||
rpf = self._write_archive("ok.rpf", zlib.compress(b"B" * 128), base=16)
|
||||
out_dir = os.path.join(self.tmp.name, "out_ro")
|
||||
os.makedirs(out_dir)
|
||||
idx = os.path.join(out_dir, "index.json")
|
||||
previous = '{"previous": true}\n'
|
||||
with open(idx, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(previous)
|
||||
with mock.patch.object(rpf9_carve.json, "dump", side_effect=OSError("disk full")):
|
||||
with self.assertRaises(SystemExit) as cm:
|
||||
rpf9_carve.main([rpf, out_dir, "--index-only"])
|
||||
self.assertIn("cannot write", str(cm.exception))
|
||||
with open(idx, encoding="utf-8") as f:
|
||||
self.assertEqual(f.read(), previous)
|
||||
self.assertEqual([n for n in os.listdir(out_dir) if n.startswith(".rpf9_carve-")], [])
|
||||
|
||||
os.chmod(idx, 0o444)
|
||||
try:
|
||||
with mock.patch.object(os, "replace", side_effect=PermissionError("replace denied")):
|
||||
with self.assertRaises(SystemExit) as cm:
|
||||
rpf9_carve.main([rpf, out_dir, "--index-only"])
|
||||
self.assertIn("cannot write", str(cm.exception))
|
||||
with open(idx, encoding="utf-8") as f:
|
||||
self.assertEqual(f.read(), previous)
|
||||
self.assertEqual([n for n in os.listdir(out_dir) if n.startswith(".rpf9_carve-")], [])
|
||||
if os.name == "nt":
|
||||
p = subprocess.run([sys.executable, "-I", TOOL, rpf, out_dir, "--index-only"],
|
||||
capture_output=True, text=True)
|
||||
self.assertNotEqual(p.returncode, 0)
|
||||
self.assertIn("cannot write", p.stderr)
|
||||
self.assertNotIn("Traceback", p.stderr)
|
||||
with open(idx, encoding="utf-8") as f:
|
||||
self.assertEqual(f.read(), previous)
|
||||
self.assertEqual([n for n in os.listdir(out_dir) if n.startswith(".rpf9_carve-")], [])
|
||||
finally:
|
||||
for entry in os.listdir(out_dir):
|
||||
try:
|
||||
os.chmod(os.path.join(out_dir, entry), 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_index_json_ends_with_newline(self):
|
||||
rpf = self._write_archive("nl.rpf", zlib.compress(b"C" * 128), base=16)
|
||||
out_dir = os.path.join(self.tmp.name, "out_nl")
|
||||
rc = rpf9_carve.main([rpf, out_dir, "--index-only"])
|
||||
self.assertEqual(rc, 0)
|
||||
with open(os.path.join(out_dir, "index.json"), "rb") as f:
|
||||
data = f.read()
|
||||
self.assertTrue(data.endswith(b"\n"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -26,10 +26,13 @@ import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import zlib
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from file_mode import published_mode # noqa: E402
|
||||
from replace_retry import replace as replace_retry # noqa: E402
|
||||
from rsc8_audio import parse_adat_header_bytes # noqa: E402
|
||||
from report_paths import same_report_path # noqa: E402
|
||||
from restofworld_model_join import ModelSystemPages # noqa: E402
|
||||
@ -115,6 +118,34 @@ def first_adat_bank(m, start, end):
|
||||
return None
|
||||
|
||||
|
||||
def _write_index_atomic(index_path, payload):
|
||||
"""Write index.json cleanly on rename so failed publishes preserve the previous index."""
|
||||
dest = os.path.abspath(index_path)
|
||||
directory = os.path.dirname(dest) or "."
|
||||
staged = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w", encoding="utf-8", newline="\n", delete=False,
|
||||
dir=directory, prefix=".rpf9_carve-", suffix=".tmp",
|
||||
) as f:
|
||||
staged = f.name
|
||||
json.dump(payload, f)
|
||||
f.write("\n")
|
||||
os.chmod(staged, published_mode(dest))
|
||||
replace_retry(staged, dest)
|
||||
staged = None
|
||||
finally:
|
||||
if staged is not None:
|
||||
try:
|
||||
os.chmod(staged, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.unlink(staged)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("archive")
|
||||
@ -207,6 +238,8 @@ def main(argv=None) -> int:
|
||||
"frames": struct.unpack_from("<I", m, s + 8)[0], "pre": "", "head": m[s:s + 16].hex()})
|
||||
if not a.index_only:
|
||||
out_file = os.path.join(a.out, f"{s:012x}.bk2")
|
||||
if same_report_path(out_file, a.archive):
|
||||
sys.exit(f"{out_file}: output must not overwrite input archive {a.archive}")
|
||||
try:
|
||||
with open(out_file, "wb") as f:
|
||||
f.write(m[s:s + blen])
|
||||
@ -244,6 +277,8 @@ def main(argv=None) -> int:
|
||||
"head": out[:16].hex()})
|
||||
if not a.index_only:
|
||||
out_file = os.path.join(a.out, f"{s:012x}.bin")
|
||||
if same_report_path(out_file, a.archive):
|
||||
sys.exit(f"{out_file}: output must not overwrite input archive {a.archive}")
|
||||
try:
|
||||
with open(out_file, "wb") as f:
|
||||
f.write(out)
|
||||
@ -251,7 +286,7 @@ def main(argv=None) -> int:
|
||||
sys.exit(f"{out_file}: cannot write: {e.strerror or e}")
|
||||
last = pos = s + used
|
||||
if len(rows) % 2000 == 0:
|
||||
done = (pos - (a.start or 0)) / max(1, end - (a.start or 0))
|
||||
done = (pos - base) / max(1, end - base)
|
||||
print(f"[{done:6.1%}] {len(rows)} files, {time.time() - t0:.0f}s", flush=True)
|
||||
account(last, end)
|
||||
total = sum(r["stored"] for r in rows)
|
||||
@ -266,8 +301,7 @@ def main(argv=None) -> int:
|
||||
summary["first_adat_bank"] = boundary # None: no bank in the window, the whole window was scanned
|
||||
index_path = os.path.join(a.out, "index.json")
|
||||
try:
|
||||
with open(index_path, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump({"summary": summary, "files": rows, "unread": unread_ranges}, f)
|
||||
_write_index_atomic(index_path, {"summary": summary, "files": rows, "unread": unread_ranges})
|
||||
except OSError as e:
|
||||
sys.exit(f"{index_path}: cannot write: {e.strerror or e}")
|
||||
print(json.dumps(summary, indent=1))
|
||||
|
||||
Reference in New Issue
Block a user