Skip to content

Commit e86666c

Browse files
miss-islingtonencukouStanFromIreland
authored
[3.14] gh-151981: Make tarfile._Stream.seek break at EOF (GH-151982) (#151992)
(cherry picked from commit f50bf13) Co-authored-by: Petr Viktorin <encukou@gmail.com> Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent 3ae0639 commit e86666c

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

Lib/tarfile.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -524,7 +524,9 @@ def seek(self, pos=0):
524524
if pos - self.pos >= 0:
525525
blocks, remainder = divmod(pos - self.pos, self.bufsize)
526526
for i in range(blocks):
527-
self.read(self.bufsize)
527+
data = self.read(self.bufsize)
528+
if not data:
529+
break
528530
self.read(remainder)
529531
else:
530532
raise StreamError("seeking backwards is not allowed")

Lib/test/test_tarfile.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4762,6 +4762,22 @@ def valueerror_filter(tarinfo, path):
47624762
with self.check_context(arc.open(errorlevel='boo!'), filtererror_filter):
47634763
self.expect_exception(TypeError) # errorlevel is not int
47644764

4765+
@support.subTests('format', [tarfile.GNU_FORMAT, tarfile.PAX_FORMAT])
4766+
def test_getmembers_big_size(self, format):
4767+
# gh-151981: A loop in seek() for streaming files tried to read the
4768+
# declared number of blocks even at EOF
4769+
tinfo = tarfile.TarInfo("huge-file")
4770+
tinfo.size = 1 << 64
4771+
bio = io.BytesIO()
4772+
# Write header without data
4773+
bio.write(tinfo.tobuf(format))
4774+
4775+
# Reset & try to get contents
4776+
bio.seek(0)
4777+
with tarfile.open(fileobj=bio, mode="r|") as tar:
4778+
with self.assertRaises(tarfile.ReadError):
4779+
tar.getmembers()
4780+
47654781

47664782
class OverwriteTests(archiver_tests.OverwriteTests, unittest.TestCase):
47674783
testdir = os.path.join(TEMPDIR, "testoverwrite")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
In :mod:`tarfile`, seeking a stream now stops when end of the stream is
2+
reached.

0 commit comments

Comments
 (0)