Skip to content

Commit ac0487e

Browse files
miss-islingtonencukouStanFromIreland
authored
[3.14] gh-157579: Fix TemporaryDirectory cleanup fallbacks with bytes paths (GH-162116) (GH-162209)
(cherry picked from commit aa17c68) Co-authored-by: Petr Viktorin <encukou@gmail.com> Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent 00cefa8 commit ac0487e

4 files changed

Lines changed: 180 additions & 9 deletions

File tree

‎Lib/tempfile.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -969,10 +969,13 @@ def __init__(self, suffix=None, prefix=None, dir=None,
969969
@classmethod
970970
def _rmtree(cls, name, ignore_errors=False, repeated=False, dir_fd=None,
971971
fullname=None):
972-
if fullname is None:
973-
fullname = name
972+
973+
# work with str paths throughout
974+
name = _os.fsdecode(name)
975+
fullname = name if fullname is None else _os.fsdecode(fullname)
974976

975977
def onexc(func, path, exc, direntry=None, dir_fd=None):
978+
path = _os.fsdecode(path)
976979
# On DragonFly BSD, UF_NOUNLINK removal fails with EISDIR, not EPERM.
977980
if isinstance(exc, (PermissionError, IsADirectoryError)):
978981
if repeated and path == name:

‎Lib/test/test_shutil.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,63 @@ def onexc(*args):
564564
self.assertTrue(onexc_called)
565565
self.assertFalse(onerror_called)
566566

567+
@unittest.skipUnless(shutil.rmtree.avoids_symlink_attacks,
568+
'requires the fd based implementation of rmtree()')
569+
def test_onexc_kwargs_dir_fd(self):
570+
os.mkdir(TESTFN)
571+
self.addCleanup(os_helper.rmtree, TESTFN)
572+
top_name = os.path.join(TESTFN, 'top')
573+
child_name = os.path.join(TESTFN, 'top', 'child')
574+
os.mkdir(top_name)
575+
os.mkdir(child_name)
576+
parent_fd = os.open(TESTFN, os.O_RDONLY)
577+
self.addCleanup(os.close, parent_fd)
578+
579+
errors = []
580+
def onexc(func, path, err, direntry=None, dir_fd=None):
581+
errors.append((func, path.replace(os.path.sep, '/')))
582+
name = path if direntry is None else direntry.name
583+
self.assertEqual(name, os.path.basename(path))
584+
self.assertTrue(os.path.samestat(
585+
os.stat(os.path.join(TESTFN, path)),
586+
os.stat(name, dir_fd=dir_fd)))
587+
588+
def failing_rmdir(path, *, dir_fd=None):
589+
raise PermissionError(errno.EACCES, 'simulated')
590+
with unittest.mock.patch('os.rmdir', failing_rmdir):
591+
shutil.rmtree('top', dir_fd=parent_fd, onexc=onexc,
592+
_onexc_kwargs=True)
593+
self.assertEqual(
594+
errors,
595+
[(failing_rmdir, 'top/child'), (failing_rmdir, 'top')])
596+
597+
child_stat = os.stat(child_name)
598+
scandir = os.scandir
599+
600+
# Fail for the top-level directory
601+
errors.clear()
602+
def failing_scandir(fd):
603+
raise PermissionError(errno.EACCES, 'simulated')
604+
with unittest.mock.patch('os.scandir', failing_scandir):
605+
shutil.rmtree('top', dir_fd=parent_fd, onexc=onexc,
606+
_onexc_kwargs=True)
607+
self.assertEqual(
608+
errors,
609+
[(failing_scandir, 'top'), (os.rmdir, 'top')])
610+
self.assertTrue(os.path.exists(top_name))
611+
612+
# Fail for the child (which is empty, so the rmdir succeeds)
613+
errors.clear()
614+
def failing_scandir_2(fd):
615+
if not os.path.samestat(os.fstat(fd), child_stat):
616+
return scandir(fd)
617+
raise PermissionError(errno.EACCES, 'simulated')
618+
with unittest.mock.patch('os.scandir', failing_scandir_2):
619+
shutil.rmtree('top', dir_fd=parent_fd, onexc=onexc,
620+
_onexc_kwargs=True)
621+
self.assertEqual(errors, [(failing_scandir_2, 'top/child')])
622+
self.assertFalse(os.path.exists(top_name))
623+
567624
def test_rmtree_does_not_choke_on_failing_lstat(self):
568625
try:
569626
orig_lstat = os.lstat

‎Lib/test/test_tempfile.py‎

Lines changed: 115 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,10 +1639,14 @@ def __exit__(self, *exc_info):
16391639
class TestTemporaryDirectory(BaseTestCase):
16401640
"""Test TemporaryDirectory()."""
16411641

1642-
def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
1642+
def do_create(self, dir=None, pre=None, suf=None, recurse=1, dirs=1, files=1,
16431643
ignore_cleanup_errors=False):
16441644
if dir is None:
16451645
dir = tempfile.gettempdir()
1646+
if pre is None:
1647+
pre = type(dir)()
1648+
if suf is None:
1649+
suf = type(dir)()
16461650
tmp = tempfile.TemporaryDirectory(
16471651
dir=dir, prefix=pre, suffix=suf,
16481652
ignore_cleanup_errors=ignore_cleanup_errors)
@@ -1652,13 +1656,17 @@ def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
16521656

16531657
def do_create2(self, path, recurse=1, dirs=1, files=1):
16541658
# Create subdirectories and some files
1659+
def join(name):
1660+
if isinstance(path, bytes):
1661+
name = os.fsencode(name)
1662+
return os.path.join(path, name)
16551663
if recurse:
16561664
for i in range(dirs):
1657-
name = os.path.join(path, "dir%d" % i)
1665+
name = join("dir%d" % i)
16581666
os.mkdir(name)
16591667
self.do_create2(name, recurse-1, dirs, files)
16601668
for i in range(files):
1661-
with open(os.path.join(path, "test%d.txt" % i), "wb") as f:
1669+
with open(join("test%d.txt" % i), "wb") as f:
16621670
f.write(b"Hello world!")
16631671

16641672
def test_mkdtemp_failure(self):
@@ -1684,6 +1692,15 @@ def test_explicit_cleanup(self):
16841692
finally:
16851693
os.rmdir(dir)
16861694

1695+
def test_explicit_cleanup_bytes(self):
1696+
# A TemporaryDirectory with a bytes name is deleted when cleaned up
1697+
with tempfile.TemporaryDirectory() as working_dir:
1698+
d = self.do_create(dir=os.fsencode(working_dir), recurse=2)
1699+
self.assertIsInstance(d.name, bytes)
1700+
self.assertTrue(os.path.exists(d.name))
1701+
d.cleanup()
1702+
self.assertFalse(os.path.exists(d.name))
1703+
16871704
def test_explicit_cleanup_ignore_errors(self):
16881705
"""Test that cleanup doesn't return an error when ignoring them."""
16891706
with tempfile.TemporaryDirectory() as working_dir:
@@ -1896,6 +1913,87 @@ def hook(path, *, dir_fd=None):
18961913
self.assertTrue(os.path.exists(target_file))
18971914
self.assertEqual(os.stat(target_file).st_mode, target_mode)
18981915

1916+
def _make_unopenable_subdir(self):
1917+
# Create the following structure:
1918+
# work/ - top-level
1919+
# <d>/ - tempdir to clean up (random name)
1920+
# sub/ - an unopenable dir
1921+
# subsub/
1922+
# file
1923+
# Return:
1924+
# - `work` name (str)
1925+
# - `d` (TemporaryDirectory)
1926+
# - `subsub` stat result
1927+
work = self.enterContext(os_helper.temp_dir())
1928+
d = tempfile.TemporaryDirectory(dir=work)
1929+
sub = os.path.join(d.name, 'sub')
1930+
subsub = os.path.join(sub, 'subsub')
1931+
os.mkdir(sub)
1932+
os.mkdir(subsub)
1933+
subsub_stat = os.lstat(subsub)
1934+
with open(os.path.join(subsub, 'file'), 'w') as f:
1935+
f.write("rm me pls")
1936+
os.chmod(sub, 0)
1937+
# If the test fails, make sure everything can still be removed.
1938+
self.addCleanup(d.cleanup)
1939+
@self.addCleanup
1940+
def _clean():
1941+
if os.path.isdir(sub):
1942+
os.chmod(sub, 0o700)
1943+
return work, d, subsub_stat
1944+
1945+
@os_helper.skip_unless_working_chmod
1946+
@support.requires_non_root_user
1947+
@unittest.skipUnless(tempfile._rmtree_use_dir_fd
1948+
and shutil.rmtree.avoids_symlink_attacks,
1949+
'requires the fd based cleanup')
1950+
def test_cleanup_nested_toplevel_error(self):
1951+
# rmtree() reports errors relative to the correct parent directory
1952+
work, d, subsub_stat = self._make_unopenable_subdir()
1953+
# An unrelated directory with the same name; should not be touched
1954+
unrelated = os.path.join(work, 'sub')
1955+
os.mkdir(unrelated)
1956+
1957+
rmdir = os.rmdir
1958+
failed_path = None
1959+
def failing_rmdir(path, *, dir_fd=None):
1960+
nonlocal failed_path
1961+
if path == 'sub' and dir_fd is not None and failed_path is None:
1962+
failed_path = path
1963+
raise PermissionError(errno.EPERM, 'simulated', path)
1964+
return rmdir(path, dir_fd=dir_fd)
1965+
with os_helper.change_cwd(work), mock.patch('os.rmdir', failing_rmdir):
1966+
d.cleanup()
1967+
self.assertEqual(failed_path, 'sub')
1968+
self.assertFalse(os.path.exists(d.name))
1969+
self.assertTrue(os.path.exists(unrelated))
1970+
1971+
@os_helper.skip_unless_working_chmod
1972+
@support.requires_non_root_user
1973+
@unittest.skipUnless(tempfile._rmtree_use_dir_fd
1974+
and shutil.rmtree.avoids_symlink_attacks,
1975+
'requires the fd based cleanup')
1976+
def test_cleanup_nested_scandir_error(self):
1977+
# A scandir() error is reported relative to the parent directory.
1978+
work, d, subsub_stat = self._make_unopenable_subdir()
1979+
1980+
scandir = os.scandir
1981+
failed = False
1982+
def failing_scandir(path='.'):
1983+
nonlocal failed
1984+
if (
1985+
not failed
1986+
and isinstance(path, int)
1987+
and os.path.samestat(os.fstat(path), subsub_stat)
1988+
):
1989+
failed = True
1990+
raise PermissionError(errno.EACCES, 'simulated')
1991+
return scandir(path)
1992+
with os_helper.change_cwd(work), mock.patch('os.scandir', failing_scandir):
1993+
d.cleanup()
1994+
self.assertTrue(failed)
1995+
self.assertFalse(os.path.exists(d.name))
1996+
18991997
@support.cpython_only
19001998
def test_del_on_collection(self):
19011999
# A TemporaryDirectory is deleted when garbage collected
@@ -2054,11 +2152,17 @@ def test_context_manager(self):
20542152
self.assertEqual(name, d.name)
20552153
self.assertFalse(os.path.exists(name))
20562154

2057-
def test_modes(self):
2155+
@support.subTests('bytes_name', (False, True))
2156+
def test_modes(self, bytes_name):
20582157
for mode in range(8):
20592158
mode <<= 6
20602159
with self.subTest(mode=format(mode, '03o')):
2061-
d = self.do_create(recurse=3, dirs=2, files=2)
2160+
if bytes_name:
2161+
d = self.do_create(recurse=3, dirs=2, files=2,
2162+
dir=tempfile.gettempdirb())
2163+
else:
2164+
d = self.do_create(recurse=3, dirs=2, files=2)
2165+
self.assertIsInstance(d.name, bytes if bytes_name else str)
20622166
with d:
20632167
# Change files and directories mode recursively.
20642168
for root, dirs, files in os.walk(d.name, topdown=False):
@@ -2069,13 +2173,17 @@ def test_modes(self):
20692173
self.assertFalse(os.path.exists(d.name))
20702174

20712175
@support.subTests('ignore_errors', (True, False))
2072-
def test_parent_mode_preserved(self, ignore_errors):
2176+
@support.subTests('bytes_name', (False, True))
2177+
def test_parent_mode_preserved(self, ignore_errors, bytes_name):
20732178
# Test that cleanup does not touch the parent directory,
20742179
# even if that prevents removal.
20752180
for mode in range(8):
20762181
mode <<= 6
20772182
with self.subTest(mode=format(mode, '03o')):
2078-
outer = self.do_create()
2183+
if bytes_name:
2184+
outer = self.do_create(dir=tempfile.gettempdirb())
2185+
else:
2186+
outer = self.do_create()
20792187
with outer:
20802188
d = self.do_create(dir=outer.name, dirs=2, files=2,
20812189
ignore_cleanup_errors=ignore_errors)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
The error handler :class:`~tempfile.TemporaryDirectory` uses to clean up
2+
unreadable and inaccessible files no longer fails for temporary directories
3+
created using :class:`bytes` paths.

0 commit comments

Comments
 (0)