Skip to content

Commit 7a562c4

Browse files
authored
gh-127636: Fix tarfile extracting trailing slash member names (GH-152984)
Fixes tarfile.TarFile.extract to accept archive member names with a trailing forward slash, including those returned by tarfile.TarFile.getnames very old style tar files may have these. new archivers likely do not do this.
1 parent 5ddd59f commit 7a562c4

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

Lib/tarfile.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2196,7 +2196,9 @@ def getmember(self, name):
21962196
than once in the archive, its last occurrence is assumed to be the
21972197
most up-to-date version.
21982198
"""
2199-
tarinfo = self._getmember(name.rstrip('/'))
2199+
tarinfo = self._getmember(name)
2200+
if tarinfo is None and name.endswith('/'):
2201+
tarinfo = self._getmember(name.rstrip('/'))
22002202
if tarinfo is None:
22012203
raise KeyError("filename %r not found" % name)
22022204
return tarinfo

Lib/test/test_tarfile.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,19 @@ def test_add_dir_getmember(self):
255255
self.add_dir_and_getmember('bar')
256256
self.add_dir_and_getmember('a'*101)
257257

258+
def test_extract_name_with_trailing_slash(self):
259+
# gh-127636: './mydir/' is deliberately a regular-file member
260+
# (REGTYPE, not DIRTYPE) whose stored name ends in a slash. It
261+
# extracts as a file. Do not "fix" this by setting DIRTYPE; the
262+
# trailing-slash name on a non-directory is what is being tested.
263+
with tarfile.open(tmpname, 'w') as tar:
264+
tar.addfile(tarfile.TarInfo('./mydir/'))
265+
with os_helper.temp_dir() as tmpdir, tarfile.open(tmpname) as tar:
266+
names = tar.getnames()
267+
self.assertEqual(names, ['./mydir/'])
268+
tar.extract(names[0], tmpdir, filter='fully_trusted')
269+
self.assertTrue(os.path.isfile(os.path.join(tmpdir, 'mydir')))
270+
258271
@unittest.skipUnless(hasattr(os, "getuid") and hasattr(os, "getgid"),
259272
"Missing getuid or getgid implementation")
260273
def add_dir_and_getmember(self, name):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :meth:`tarfile.TarFile.extract` to accept archive member names with a
2+
trailing forward slash, including those returned by
3+
:meth:`tarfile.TarFile.getnames`. Contributed by Xiao Yuan.

0 commit comments

Comments
 (0)