Skip to content

gh-84481: Make ZipFile.data_offset more robust #132178

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 8, 2025
Merged
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
8 changes: 7 additions & 1 deletion Lib/test/test_zipfile/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3348,6 +3348,12 @@ def test_data_offset_write_with_prefix(self):
with zipfile.ZipFile(fp, "w") as zipfp:
self.assertEqual(zipfp.data_offset, 16)

def test_data_offset_append_with_bad_zip(self):
with io.BytesIO() as fp:
fp.write(b"this is a prefix")
with zipfile.ZipFile(fp, "a") as zipfp:
self.assertEqual(zipfp.data_offset, 16)

def test_data_offset_write_no_tell(self):
# The initializer in ZipFile checks if tell raises AttributeError or
# OSError when creating a file in write mode when deducing the offset
Expand All @@ -3357,7 +3363,7 @@ def tell(self):
raise OSError("Unimplemented!")
with NoTellBytesIO() as fp:
with zipfile.ZipFile(fp, "w") as zipfp:
self.assertIs(zipfp.data_offset, None)
self.assertIsNone(zipfp.data_offset)


class EncodedMetadataTests(unittest.TestCase):
Expand Down
3 changes: 2 additions & 1 deletion Lib/zipfile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1403,6 +1403,7 @@ def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True,
self._lock = threading.RLock()
self._seekable = True
self._writing = False
self._data_offset = None

try:
if mode == 'r':
Expand All @@ -1418,7 +1419,6 @@ def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True,
self.fp = _Tellable(self.fp)
self.start_dir = 0
self._seekable = False
self._data_offset = None
else:
# Some file-like objects can provide tell() but not seek()
try:
Expand All @@ -1439,6 +1439,7 @@ def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True,
# even if no files are added to the archive
self._didModify = True
self.start_dir = self.fp.tell()
self._data_offset = self.start_dir
else:
raise ValueError("Mode must be 'r', 'w', 'x', or 'a'")
except:
Expand Down
Loading