Skip to content

Commit efdf316

Browse files
bpo-34341: Fix appending to ZIP archives with the ZIP64 extension. (GH-8683)
(cherry picked from commit 9bdb7be) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent e2c0aea commit efdf316

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

Lib/test/test_zipfile.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,20 @@ def test_absolute_arcnames(self):
750750
with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
751751
self.assertEqual(zipfp.namelist(), ["absolute"])
752752

753+
def test_append(self):
754+
# Test that appending to the Zip64 archive doesn't change
755+
# extra fields of existing entries.
756+
with zipfile.ZipFile(TESTFN2, "w", allowZip64=True) as zipfp:
757+
zipfp.writestr("strfile", self.data)
758+
with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
759+
zinfo = zipfp.getinfo("strfile")
760+
extra = zinfo.extra
761+
with zipfile.ZipFile(TESTFN2, "a", allowZip64=True) as zipfp:
762+
zipfp.writestr("strfile2", self.data)
763+
with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
764+
zinfo = zipfp.getinfo("strfile")
765+
self.assertEqual(zinfo.extra, extra)
766+
753767
@requires_zlib
754768
class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
755769
unittest.TestCase):

Lib/zipfile.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,27 @@ class LargeZipFile(Exception):
159159
_CD64_DIRECTORY_SIZE = 8
160160
_CD64_OFFSET_START_CENTDIR = 9
161161

162+
_EXTRA_FIELD_STRUCT = struct.Struct('<HH')
163+
164+
def _strip_extra(extra, xids):
165+
# Remove Extra Fields with specified IDs.
166+
unpack = _EXTRA_FIELD_STRUCT.unpack
167+
modified = False
168+
buffer = []
169+
start = i = 0
170+
while i + 4 <= len(extra):
171+
xid, xlen = unpack(extra[i : i + 4])
172+
j = i + 4 + xlen
173+
if xid in xids:
174+
if i != start:
175+
buffer.append(extra[start : i])
176+
start = j
177+
modified = True
178+
i = j
179+
if not modified:
180+
return extra
181+
return b''.join(buffer)
182+
162183
def _check_zipfile(fp):
163184
try:
164185
if _EndRecData(fp):
@@ -1813,6 +1834,7 @@ def _write_end_record(self):
18131834
min_version = 0
18141835
if extra:
18151836
# Append a ZIP64 field to the extra's
1837+
extra_data = _strip_extra(extra_data, (1,))
18161838
extra_data = struct.pack(
18171839
'<HH' + 'Q'*len(extra),
18181840
1, 8*len(extra), *extra) + extra_data
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Appending to the ZIP archive with the ZIP64 extension no longer grows the
2+
size of extra fields of existing entries.

0 commit comments

Comments
 (0)