mirror of
https://github.com/valentderah/totk-pc-recomp.git
synced 2026-11-22 21:15:57 +00:00
Bound compressed NCZ blocks by their declared output size
This commit is contained in:
1 parent
4ef0e2bd4a
commit
8bbc6c7ade
2 files changed
+36
-1
No files matched your search
@@ -66,6 +66,35 @@ def ncz_file(nca, body, blocks=False):
|
||||
return out + b''.join(stored)
|
||||
|
||||
|
||||
class BlocksTest(unittest.TestCase):
|
||||
def read(self, data, plain=1 << 14):
|
||||
header = b'NCZBLOCK' + bytes([2, 1, 0, 14]) + struct.pack('<IQI', 1, plain, len(data))
|
||||
return ncz.blocks(io.BytesIO(header + data), 0, len(header) + len(data), plain)
|
||||
|
||||
def test_oversized_compressed_block_is_rejected_before_yielding(self):
|
||||
data = zstd.compress(bytes(1 << 20)) # a small fixture, 64 times the declared output
|
||||
with self.assertRaisesRegex(ValueError, 'NCZ block decompressed size'):
|
||||
next(self.read(data))
|
||||
|
||||
def test_short_compressed_block_is_rejected_before_yielding(self):
|
||||
with self.assertRaisesRegex(ValueError, 'NCZ block decompressed size'):
|
||||
next(self.read(zstd.compress(bytes(100))))
|
||||
|
||||
def test_compressed_block_can_contain_multiple_frames(self):
|
||||
plain = bytes(1 << 14)
|
||||
data = zstd.compress(plain[:100]) + zstd.compress(plain[100:])
|
||||
self.assertEqual(b''.join(self.read(data)), plain)
|
||||
|
||||
def test_compressed_final_block_uses_its_actual_plain_size(self):
|
||||
plain = bytes(123)
|
||||
self.assertEqual(b''.join(self.read(zstd.compress(plain), len(plain))), plain)
|
||||
|
||||
def test_compressed_block_must_reach_its_end_marker(self):
|
||||
data = zstd.compress(bytes(1 << 14), options={zstd.CompressionParameter.checksum_flag: True})
|
||||
with self.assertRaises((zstd.ZstdError, EOFError)):
|
||||
next(self.read(data[:-1]))
|
||||
|
||||
|
||||
class UnpackTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
|
||||
+7
-1
@@ -130,7 +130,13 @@ def blocks(f, pos, end, total):
|
||||
# to the NCA, while the full stored length locates the next block.
|
||||
data = read_at(f, pos, min(length, plain))
|
||||
pos += length
|
||||
yield zstd.decompress(data) if length < plain else data
|
||||
if length < plain:
|
||||
# Read at most one byte beyond the declared size: a damaged frame must not allocate its whole output.
|
||||
# ZstdFile also preserves support for concatenated frames within a block.
|
||||
with zstd.ZstdFile(io.BytesIO(data)) as z:
|
||||
data = z.read(plain + 1)
|
||||
require(len(data) == plain, 'NCZ block decompressed size does not match its header')
|
||||
yield data
|
||||
|
||||
|
||||
def stream(f, pos, end, total):
|
||||
|
||||
Reference in new issue
Block a user