Skip to content

Commit 0d606d6

Browse files
authored
gh-153679: Raise ZipImportError for an invalid UTF-8 file name in zipimport (#153680)
1 parent 34889af commit 0d606d6

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
@@ -1206,6 +1206,24 @@ def testNotZipFile(self):
12061206
fp.close()
12071207
self.assertZipFailure(TESTMOD)
12081208

1209+
def testInvalidUTF8FileName(self):
1210+
# A UTF-8-flagged file name that is not valid UTF-8 raises ZipImportError.
1211+
UTF8_FLAG = 0x800
1212+
name = b'\xff\xfe\xff'
1213+
cdh = b'PK\x01\x02' + struct.pack(
1214+
'<HHHHHHIIIHHHHHII',
1215+
20, 20, UTF8_FLAG, 0, 0, 0, 0, 50, 100,
1216+
len(name), 0, 0, 0, 0, 0, 0)
1217+
cdh += name
1218+
eocd = b'PK\x05\x06' + struct.pack(
1219+
'<HHHHIIH', 0, 0, 1, 1, len(cdh), 0, 0)
1220+
os_helper.unlink(TESTMOD)
1221+
with open(TESTMOD, 'wb') as fp:
1222+
fp.write(cdh + eocd)
1223+
with self.assertRaises(zipimport.ZipImportError) as cm:
1224+
zipimport.zipimporter(TESTMOD)
1225+
self.assertIsInstance(cm.exception.__cause__, UnicodeDecodeError)
1226+
12091227
# XXX: disabled until this works on Big-endian machines
12101228
def _testBogusZipFile(self):
12111229
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)