Merge pull request #1351: the NSZ block reader skips stored padding after a raw block and bounds each compressed block by its declared size, as nsz's reader does; a block of the wrong size is still a damaged file (ICUMADETHIS)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-22 16:12:24 +03:00
commit 6322727b67
2 files changed
+96 -3

No files matched your search

+78
View File
@@ -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()
@@ -88,6 +117,25 @@ class UnpackTest(unittest.TestCase):
def expected(self):
return pfs0([(self.name + '.nca', self.nca), ('a.tik', self.tik)])
def padded_nsz(self, indices, truncate=False):
"""Store selected blocks raw, followed by padding included in the stored length, not the NCA body."""
def pad(data):
head = ncz.HEADER + 16 + 0x40 * len(SECTIONS)
exponent = data[head + 11]
count = struct.unpack_from('<I', data, head + 12)[0]
for index in indices:
index %= count
lengths = struct.unpack_from(f'<{count}I', data, head + 24)
start = head + 24 + 4 * count + sum(lengths[:index])
plain = self.body[index << exponent:(index + 1) << exponent]
padding = bytes(max(16, (1 << exponent) - len(plain)))
stored = plain + padding
data[start:start + lengths[index]] = stored
struct.pack_into('<I', data, head + 24 + 4 * index, len(stored))
return data[:-1] if truncate else data
return self.nsz(blocks=True, damage=pad)
def test_stream_comes_back_byte_for_byte(self):
src = self.nsz()
self.assertEqual(ncz.compressed(src)[0], 'nsz')
@@ -102,6 +150,36 @@ class UnpackTest(unittest.TestCase):
ncz.unpack(self.nsz(blocks=True), self.dir / 'out.nsp')
self.assertEqual((self.dir / 'out.nsp').read_bytes(), self.expected())
def test_raw_block_padding_is_not_written_into_the_nca(self):
for indices in ((0,), (-1,), (0, -1)):
with self.subTest(indices=indices):
seen = []
ncz.unpack(self.padded_nsz(indices), self.dir / 'out.nsp', lambda d, t: seen.append((d, t)))
self.assertEqual((self.dir / 'out.nsp').read_bytes(), self.expected())
self.assertEqual(seen[-1], (len(self.expected()), len(self.expected())))
def test_a_raw_block_cannot_claim_padding_outside_its_entry(self):
with self.assertRaisesRegex(ValueError, 'Truncated NCZ block'):
ncz.unpack(self.padded_nsz((-1,), truncate=True), self.dir / 'out.nsp')
self.assertFalse((self.dir / 'out.nsp').exists())
def test_block_of_the_wrong_size_is_a_damaged_file(self):
"""The installer turns DamagedFile into check.input_damaged, which asks for a fresh copy of the file."""
def short(data):
head = ncz.HEADER + 16 + 0x40 * len(SECTIONS)
count = struct.unpack_from('<I', data, head + 12)[0]
lengths = struct.unpack_from(f'<{count}I', data, head + 24)
start = head + 24 + 4 * count + lengths[0]
frame = zstd.compress(self.body[1 << 14:(2 << 14) - 100]) # block 1 is zeros, stored compressed
data[start:start + lengths[1]] = frame
struct.pack_into('<I', data, head + 24 + 4, len(frame))
return data
with self.assertRaises(ncz.DamagedFile) as e:
ncz.unpack(self.nsz(blocks=True, damage=short), self.dir / 'out.nsp')
self.assertIn('decompressed size', e.exception.detail)
self.assertFalse((self.dir / 'out.nsp').exists())
def test_plain_nsp_is_not_compressed(self):
path = self.dir / 'plain.nsp'
path.write_bytes(self.expected())
+18 -3
View File
@@ -35,6 +35,10 @@ class DamagedFile(ValueError):
super().__init__(f'{self.path} is damaged or incomplete ({detail})')
class BlockSizeError(ValueError):
"""An NCZBLOCK block whose data decompresses to more or fewer bytes than its header declares."""
def compressed(path):
"""('nsz' or 'xcz', entries) for a game file holding NCZ files, else None. Raises ValueError for a file that is
neither an NSP nor an XCI."""
@@ -126,9 +130,18 @@ def blocks(f, pos, end, total):
for i, length in enumerate(stored):
plain = min(1 << exponent, size - (i << exponent))
require(pos + length <= end, 'Truncated NCZ block')
data = read_at(f, pos, length)
# nsz's BlockDecompressorReader.py __decompressBlock skips padding in a raw block: only plain bytes belong
# 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)
if len(data) != plain:
raise BlockSizeError(f'NCZ block decompressed size does not match its header (block {i})')
yield data
def stream(f, pos, end, total):
@@ -176,7 +189,9 @@ def unpack_ncz(f, start, end, out, name, source, progress):
progress(n)
if at == total:
break
except (zstd.ZstdError, EOFError) as e: # EOFError: the stream ends before its end-of-frame marker
# EOFError: the stream ends before its end-of-frame marker. BlockSizeError: a block's data is damaged; like the
# other two it is a damaged file, so the installer asks for a fresh copy (installer/steps.py, Check.unpack).
except (zstd.ZstdError, EOFError, BlockSizeError) as e:
raise DamagedFile(source, f'{name}: {e}') from None
if at != total or pending:
raise DamagedFile(source, f'{name}: {at - HEADER:,} of {total - HEADER:,} bytes')