Skip to content

Commit e82a65a

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

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
@@ -949,10 +949,13 @@ def __init__(self, suffix=None, prefix=None, dir=None,
949949
@classmethod
950950
def _rmtree(cls, name, ignore_errors=False, repeated=False, dir_fd=None,
951951
fullname=None):
952-
if fullname is None:
953-
fullname = name
952+
953+
# work with str paths throughout
954+
name = _os.fsdecode(name)
955+
fullname = name if fullname is None else _os.fsdecode(fullname)
954956

955957
def onexc(func, path, exc, direntry=None, dir_fd=None):
958+
path = _os.fsdecode(path)
956959
# On DragonFly BSD, UF_NOUNLINK removal fails with EISDIR, not EPERM.
957960
if isinstance(exc, (PermissionError, IsADirectoryError)):
958961
if repeated and path == name:

‎Lib/test/test_shutil.py‎

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

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

‎Lib/test/test_tempfile.py‎

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

1649-
def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
1649+
def do_create(self, dir=None, pre=None, suf=None, recurse=1, dirs=1, files=1,
16501650
ignore_cleanup_errors=False):
16511651
if dir is None:
16521652
dir = tempfile.gettempdir()
1653+
if pre is None:
1654+
pre = type(dir)()
1655+
if suf is None:
1656+
suf = type(dir)()
16531657
tmp = tempfile.TemporaryDirectory(
16541658
dir=dir, prefix=pre, suffix=suf,
16551659
ignore_cleanup_errors=ignore_cleanup_errors)
@@ -1659,13 +1663,17 @@ def do_create(self, dir=None, pre="", suf="", recurse=1, dirs=1, files=1,
16591663

16601664
def do_create2(self, path, recurse=1, dirs=1, files=1):
16611665
# Create subdirectories and some files
1666+
def join(name):
1667+
if isinstance(path, bytes):
1668+
name = os.fsencode(name)
1669+
return os.path.join(path, name)
16621670
if recurse:
16631671
for i in range(dirs):
1664-
name = os.path.join(path, "dir%d" % i)
1672+
name = join("dir%d" % i)
16651673
os.mkdir(name)
16661674
self.do_create2(name, recurse-1, dirs, files)
16671675
for i in range(files):
1668-
with open(os.path.join(path, "test%d.txt" % i), "wb") as f:
1676+
with open(join("test%d.txt" % i), "wb") as f:
16691677
f.write(b"Hello world!")
16701678

16711679
def test_mkdtemp_failure(self):
@@ -1691,6 +1699,15 @@ def test_explicit_cleanup(self):
16911699
finally:
16921700
os.rmdir(dir)
16931701

1702+
def test_explicit_cleanup_bytes(self):
1703+
# A TemporaryDirectory with a bytes name is deleted when cleaned up
1704+
with tempfile.TemporaryDirectory() as working_dir:
1705+
d = self.do_create(dir=os.fsencode(working_dir), recurse=2)
1706+
self.assertIsInstance(d.name, bytes)
1707+
self.assertTrue(os.path.exists(d.name))
1708+
d.cleanup()
1709+
self.assertFalse(os.path.exists(d.name))
1710+
16941711
def test_explicit_cleanup_ignore_errors(self):
16951712
"""Test that cleanup doesn't return an error when ignoring them."""
16961713
with tempfile.TemporaryDirectory() as working_dir:
@@ -1906,6 +1923,87 @@ def hook(path, *, dir_fd=None):
19061923
self.assertTrue(os.path.exists(target_file))
19071924
self.assertEqual(os.stat(target_file).st_mode, target_mode)
19081925

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

2067-
def test_modes(self):
2165+
@support.subTests('bytes_name', (False, True))
2166+
def test_modes(self, bytes_name):
20682167
for mode in range(8):
20692168
mode <<= 6
20702169
with self.subTest(mode=format(mode, '03o')):
2071-
d = self.do_create(recurse=3, dirs=2, files=2)
2170+
if bytes_name:
2171+
d = self.do_create(recurse=3, dirs=2, files=2,
2172+
dir=tempfile.gettempdirb())
2173+
else:
2174+
d = self.do_create(recurse=3, dirs=2, files=2)
2175+
self.assertIsInstance(d.name, bytes if bytes_name else str)
20722176
with d:
20732177
# Change files and directories mode recursively.
20742178
for root, dirs, files in os.walk(d.name, topdown=False):
@@ -2079,13 +2183,17 @@ def test_modes(self):
20792183
self.assertFalse(os.path.exists(d.name))
20802184

20812185
@support.subTests('ignore_errors', (True, False))
2082-
def test_parent_mode_preserved(self, ignore_errors):
2186+
@support.subTests('bytes_name', (False, True))
2187+
def test_parent_mode_preserved(self, ignore_errors, bytes_name):
20832188
# Test that cleanup does not touch the parent directory,
20842189
# even if that prevents removal.
20852190
for mode in range(8):
20862191
mode <<= 6
20872192
with self.subTest(mode=format(mode, '03o')):
2088-
outer = self.do_create()
2193+
if bytes_name:
2194+
outer = self.do_create(dir=tempfile.gettempdirb())
2195+
else:
2196+
outer = self.do_create()
20892197
with outer:
20902198
d = self.do_create(dir=outer.name, dirs=2, files=2,
20912199
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)