Skip to content

Commit 17e09a1

Browse files
[3.15] gh-153679: Raise ZipImportError for an invalid UTF-8 file name in zipimport (GH-153680) (#160617)
(cherry picked from commit 0d606d6) Co-authored-by: tonghuaroot (童话) <tonghuaroot@gmail.com>
1 parent 21a5089 commit 17e09a1

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

‎Lib/test/test_zipimport.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1150,6 +1150,24 @@ def testNotZipFile(self):
11501150
fp.close()
11511151
self.assertZipFailure(TESTMOD)
11521152

1153+
def testInvalidUTF8FileName(self):
1154+
# A UTF-8-flagged file name that is not valid UTF-8 raises ZipImportError.
1155+
UTF8_FLAG = 0x800
1156+
name = b'\xff\xfe\xff'
1157+
cdh = b'PK\x01\x02' + struct.pack(
1158+
'<HHHHHHIIIHHHHHII',
1159+
20, 20, UTF8_FLAG, 0, 0, 0, 0, 50, 100,
1160+
len(name), 0, 0, 0, 0, 0, 0)
1161+
cdh += name
1162+
eocd = b'PK\x05\x06' + struct.pack(
1163+
'<HHHHIIH', 0, 0, 1, 1, len(cdh), 0, 0)
1164+
os_helper.unlink(TESTMOD)
1165+
with open(TESTMOD, 'wb') as fp:
1166+
fp.write(cdh + eocd)
1167+
with self.assertRaises(zipimport.ZipImportError) as cm:
1168+
zipimport.zipimporter(TESTMOD)
1169+
self.assertIsInstance(cm.exception.__cause__, UnicodeDecodeError)
1170+
11531171
# XXX: disabled until this works on Big-endian machines
11541172
def _testBogusZipFile(self):
11551173
os_helper.unlink(TESTMOD)

‎Lib/zipimport.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,12 @@ def _read_directory(archive):
428428

429429
if flags & 0x800:
430430
# UTF-8 file names extension
431-
name = name.decode()
431+
try:
432+
name = name.decode()
433+
except UnicodeDecodeError as exc:
434+
raise ZipImportError(
435+
f"can't decode file name in Zip file: {archive!r}",
436+
path=archive) from exc
432437
else:
433438
# Historical ZIP filename encoding
434439
try:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:class:`zipimport.zipimporter` now raises :exc:`zipimport.ZipImportError`
2+
instead of :exc:`UnicodeDecodeError` for a UTF-8-flagged file name that is not
3+
valid UTF-8. Patch by tonghuaroot.

0 commit comments

Comments
 (0)