Skip to content

Commit 7f96291

Browse files
[3.15] gh-127636: Fix tarfile extracting trailing slash member names (GH-152984) (#157167)
Co-authored-by: Xiao Yuan <47032563+yuanx749@users.noreply.github.com>
1 parent 5333939 commit 7f96291

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
@@ -2210,7 +2210,9 @@ def getmember(self, name):
22102210
than once in the archive, its last occurrence is assumed to be the
22112211
most up-to-date version.
22122212
"""
2213-
tarinfo = self._getmember(name.rstrip('/'))
2213+
tarinfo = self._getmember(name)
2214+
if tarinfo is None and name.endswith('/'):
2215+
tarinfo = self._getmember(name.rstrip('/'))
22142216
if tarinfo is None:
22152217
raise KeyError("filename %r not found" % name)
22162218
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)