Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions Lib/test/test_zipfile/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,36 @@ class ZstdTestsWithSourceFile(AbstractTestsWithSourceFile,
unittest.TestCase):
compression = zipfile.ZIP_ZSTANDARD

def test_read_multiframe(self):
first = b'first frame' * 20
second = b'second frame' * 20
data = first + second

class MultiframeCompressor:
def compress(self, value):
value = bytes(value)
return (zipfile.zstd.compress(value[:len(first)]) +
zipfile.zstd.compress(value[len(first):]))

def flush(self):
return b''

archive = io.BytesIO()
with mock.patch.object(zipfile, '_get_compressor',
return_value=MultiframeCompressor()):
with zipfile.ZipFile(archive, 'w', self.compression) as zipfp:
zipfp.writestr('multiframe', data)

with zipfile.ZipFile(archive) as zipfp:
self.assertEqual(zipfp.read('multiframe'), data)

# Exercise a frame boundary between two reads from the archive.
with zipfile.ZipFile(archive) as zipfp:
with zipfp.open('multiframe') as fp:
fp.MIN_READ_SIZE = 1
self.assertEqual(b''.join(iter(lambda: fp.read(1), b'')),
data)

class AbstractTestZip64InSmallFiles:
# These tests test the ZIP64 functionality without using large files,
# see test_zipfile64 for proper tests.
Expand Down
11 changes: 11 additions & 0 deletions Lib/zipfile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1186,6 +1186,13 @@ def _read1(self, n):
data = self._decompressor.unconsumed_tail
if n > len(data):
data += self._read2(n - len(data))
elif (self._compress_type == ZIP_ZSTANDARD and
self._decompressor.eof):
# Continue with the next Zstandard frame.
data = self._decompressor.unused_data
self._decompressor = _get_decompressor(self._compress_type)
if not data:
data = self._read2(n)
else:
data = self._read2(n)

Expand All @@ -1199,6 +1206,10 @@ def _read1(self, n):
not self._decompressor.unconsumed_tail)
if self._eof:
data += self._decompressor.flush()
elif self._compress_type == ZIP_ZSTANDARD:
data = self._decompressor.decompress(data)
self._eof = (self._compress_left <= 0 and
not self._decompressor.unused_data)
else:
data = self._decompressor.decompress(data)
self._eof = self._decompressor.eof or self._compress_left <= 0
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :mod:`zipfile` to correctly read Zstandard-compressed archive members
that could previously be truncated or incorrectly rejected.
Loading