Skip to content

Commit eb63c0f

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

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
@@ -514,7 +514,9 @@ def seek(self, pos=0):
514514
if pos - self.pos >= 0:
515515
blocks, remainder = divmod(pos - self.pos, self.bufsize)
516516
for i in range(blocks):
517-
self.read(self.bufsize)
517+
data = self.read(self.bufsize)
518+
if not data:
519+
break
518520
self.read(remainder)
519521
else:
520522
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
@@ -4292,6 +4292,22 @@ def valueerror_filter(tarinfo, path):
42924292
with self.check_context(arc.open(errorlevel='boo!'), filtererror_filter):
42934293
self.expect_exception(TypeError) # errorlevel is not int
42944294

4295+
@support.subTests('format', [tarfile.GNU_FORMAT, tarfile.PAX_FORMAT])
4296+
def test_getmembers_big_size(self, format):
4297+
# gh-151981: A loop in seek() for streaming files tried to read the
4298+
# declared number of blocks even at EOF
4299+
tinfo = tarfile.TarInfo("huge-file")
4300+
tinfo.size = 1 << 64
4301+
bio = io.BytesIO()
4302+
# Write header without data
4303+
bio.write(tinfo.tobuf(format))
4304+
4305+
# Reset & try to get contents
4306+
bio.seek(0)
4307+
with tarfile.open(fileobj=bio, mode="r|") as tar:
4308+
with self.assertRaises(tarfile.ReadError):
4309+
tar.getmembers()
4310+
42954311

42964312
class OffsetValidationTests(unittest.TestCase):
42974313
tarname = tmpname
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)