Skip to content

Commit 7a17da3

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

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
@@ -1059,6 +1059,24 @@ def testNotZipFile(self):
10591059
fp.close()
10601060
self.assertZipFailure(TESTMOD)
10611061

1062+
def testInvalidUTF8FileName(self):
1063+
# A UTF-8-flagged file name that is not valid UTF-8 raises ZipImportError.
1064+
UTF8_FLAG = 0x800
1065+
name = b'\xff\xfe\xff'
1066+
cdh = b'PK\x01\x02' + struct.pack(
1067+
'<HHHHHHIIIHHHHHII',
1068+
20, 20, UTF8_FLAG, 0, 0, 0, 0, 50, 100,
1069+
len(name), 0, 0, 0, 0, 0, 0)
1070+
cdh += name
1071+
eocd = b'PK\x05\x06' + struct.pack(
1072+
'<HHHHIIH', 0, 0, 1, 1, len(cdh), 0, 0)
1073+
os_helper.unlink(TESTMOD)
1074+
with open(TESTMOD, 'wb') as fp:
1075+
fp.write(cdh + eocd)
1076+
with self.assertRaises(zipimport.ZipImportError) as cm:
1077+
zipimport.zipimporter(TESTMOD)
1078+
self.assertIsInstance(cm.exception.__cause__, UnicodeDecodeError)
1079+
10621080
# XXX: disabled until this works on Big-endian machines
10631081
def _testBogusZipFile(self):
10641082
os_helper.unlink(TESTMOD)

‎Lib/zipimport.py‎

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

479479
if flags & 0x800:
480480
# UTF-8 file names extension
481-
name = name.decode()
481+
try:
482+
name = name.decode()
483+
except UnicodeDecodeError as exc:
484+
raise ZipImportError(
485+
f"can't decode file name in Zip file: {archive!r}",
486+
path=archive) from exc
482487
else:
483488
# Historical ZIP filename encoding
484489
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)