Skip to content

Commit 5c3fde0

Browse files
Zheaoliserhiy-storchaka
authored andcommitted
gh-107398: Fix tarfile stream mode exception when process the file with the gzip extra field (GH-126304)
(cherry picked from commit 65f9932) Co-authored-by: Nadeshiko Manju <me@manjusaka.me> Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 6f72734 commit 5c3fde0

3 files changed

Lines changed: 33 additions & 3 deletions

File tree

Lib/tarfile.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ def _init_read_gz(self):
489489

490490
if flag & 4:
491491
xlen = ord(self.__read(1)) + 256 * ord(self.__read(1))
492-
self.read(xlen)
492+
self.__read(xlen)
493493
if flag & 8:
494494
while True:
495495
s = self.__read(1)

Lib/test/test_tarfile.py

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -884,10 +884,39 @@ def test_extractall_hardlink_on_symlink(self):
884884
self._assert_on_file_content(hardlink_filepath, sha256_regtype)
885885

886886

887+
class GzipReadTestBase:
888+
889+
def test_read_with_extra_field(self):
890+
with open(self.tarname, 'rb') as f:
891+
data = bytearray(f.read())
892+
flags = data[3]
893+
self.assertEqual(flags, 8)
894+
data[3] = flags | 4
895+
data[10:10] = b'\x05\x00extra'
896+
with open(tmpname, 'wb') as f:
897+
f.write(data)
898+
print(self.mode)
899+
with tarfile.open(tmpname, mode=self.mode):
900+
pass
901+
902+
def test_read_with_file_comment(self):
903+
with open(self.tarname, 'rb') as f:
904+
data = bytearray(f.read())
905+
flags = data[3]
906+
self.assertEqual(flags, 8)
907+
data[3] = flags | 16
908+
i = data.index(0, 10) + 1
909+
data[i:i] = b'comment\x00'
910+
with open(tmpname, 'wb') as f:
911+
f.write(data)
912+
with tarfile.open(tmpname, mode=self.mode):
913+
pass
914+
915+
887916
class MiscReadTest(MiscReadTestBase, unittest.TestCase):
888917
test_fail_comp = None
889918

890-
class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
919+
class GzipMiscReadTest(GzipTest, GzipReadTestBase, MiscReadTestBase, unittest.TestCase):
891920
pass
892921

893922
class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
@@ -959,7 +988,7 @@ def test_compare_members(self):
959988
finally:
960989
tar1.close()
961990

962-
class GzipStreamReadTest(GzipTest, StreamReadTest):
991+
class GzipStreamReadTest(GzipTest, GzipReadTestBase, StreamReadTest):
963992
pass
964993

965994
class Bz2StreamReadTest(Bz2Test, StreamReadTest):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :mod:`tarfile` stream mode exception when process the file with the gzip extra field.

0 commit comments

Comments
 (0)