From: Michael Tremer Date: Tue, 18 Oct 2022 13:39:26 +0000 (+0000) Subject: backend: Make unlink() safer and tidier X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=50110c5ff8d84ab2c398c1a77299b972bbee1822;p=pbs.git backend: Make unlink() safer and tidier Signed-off-by: Michael Tremer --- diff --git a/src/buildservice/__init__.py b/src/buildservice/__init__.py index 7473863e..c2b76f17 100644 --- a/src/buildservice/__init__.py +++ b/src/buildservice/__init__.py @@ -254,12 +254,40 @@ class Backend(object): """ Unlinks path """ + # Normalize the path + path = os.path.abspath(path) + + # Check if the path is within our base directory + if not path.startswith(self.basepath): + raise OSError("Cannot delete %s which is outside %s" % (path, self.basepath)) + log.debug("Unlinking %s" % path) + await asyncio.to_thread(self._unlink, path) + + def _unlink(self, path): + # Unlink the file we were asked to unlink try: - await asyncio.to_thread(os.unlink, path) + os.unlink(path) except OSError as e: - pass + return + + # Try to delete any empty parent directories + while True: + # Get the parent directory + path = os.path.dirname(path) + + # Break if we reached the base path + if path == self.basepath: + break + + # Call rmdir() + try: + os.rmdir(path) + except OSError as e: + break + + log.debug(" Cleaned up %s..." % path) def _write_tempfile(self, content): """