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
22 changes: 22 additions & 0 deletions Lib/test/test_zipfile/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -4498,6 +4498,28 @@ def test_comments(self):
with zipfile.ZipFile(TESTFN,mode="r") as zipf:
self.assertEqual(zipf.comment, b"shorter comment")

def test_member_comment_too_long(self):
stream = io.BytesIO()
with zipfile.ZipFile(stream, mode="w") as zipf:
zinfo = zipfile.ZipInfo("accepted.txt")
zinfo.comment = b"x" * zipfile.ZIP_MAX_COMMENT
zipf.writestr(zinfo, b"content")

zinfo = zipfile.ZipInfo("rejected.txt")
zinfo.comment = b"x" * (zipfile.ZIP_MAX_COMMENT + 1)
with self.assertRaisesRegex(
ValueError,
r"ZipInfo\.comment exceeds the maximum length of 65535 bytes",
):
zipf.writestr(zinfo, b"content")

with zipfile.ZipFile(stream) as zipf:
self.assertEqual(zipf.namelist(), ["accepted.txt"])
self.assertEqual(
zipf.getinfo("accepted.txt").comment,
b"x" * zipfile.ZIP_MAX_COMMENT,
)

def test_unicode_comment(self):
with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Expand Down
5 changes: 5 additions & 0 deletions Lib/zipfile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2528,6 +2528,11 @@ def _extract_member(self, member, targetpath, pwd):

def _writecheck(self, zinfo):
"""Check for errors before writing a file to the archive."""
if len(zinfo.comment) > ZIP_MAX_COMMENT:
raise ValueError(
f"ZipInfo.comment exceeds the maximum length of "
f"{ZIP_MAX_COMMENT} bytes"
)
if zinfo.filename in self.NameToInfo:
warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
if self.mode not in ('w', 'x', 'a'):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Raise :exc:`ValueError` before writing a ZIP member whose
:attr:`~zipfile.ZipInfo.comment` is too long for the ZIP format. This avoids
an opaque :exc:`struct.error` while closing the archive.
Loading