Skip to content

Commit 950f113

Browse files
yuanx749miss-islington
authored andcommitted
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. (cherry picked from commit 7a562c4) Co-authored-by: Xiao Yuan <47032563+yuanx749@users.noreply.github.com>
1 parent cf312cf commit 950f113

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
@@ -2200,7 +2200,9 @@ def getmember(self, name):
22002200
than once in the archive, its last occurrence is assumed to be the
22012201
most up-to-date version.
22022202
"""
2203-
tarinfo = self._getmember(name.rstrip('/'))
2203+
tarinfo = self._getmember(name)
2204+
if tarinfo is None and name.endswith('/'):
2205+
tarinfo = self._getmember(name.rstrip('/'))
22042206
if tarinfo is None:
22052207
raise KeyError("filename %r not found" % name)
22062208
return tarinfo

Lib/test/test_tarfile.py

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

257+
def test_extract_name_with_trailing_slash(self):
258+
# gh-127636: './mydir/' is deliberately a regular-file member
259+
# (REGTYPE, not DIRTYPE) whose stored name ends in a slash. It
260+
# extracts as a file. Do not "fix" this by setting DIRTYPE; the
261+
# trailing-slash name on a non-directory is what is being tested.
262+
with tarfile.open(tmpname, 'w') as tar:
263+
tar.addfile(tarfile.TarInfo('./mydir/'))
264+
with os_helper.temp_dir() as tmpdir, tarfile.open(tmpname) as tar:
265+
names = tar.getnames()
266+
self.assertEqual(names, ['./mydir/'])
267+
tar.extract(names[0], tmpdir, filter='fully_trusted')
268+
self.assertTrue(os.path.isfile(os.path.join(tmpdir, 'mydir')))
269+
257270
@unittest.skipUnless(hasattr(os, "getuid") and hasattr(os, "getgid"),
258271
"Missing getuid or getgid implementation")
259272
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)