]> git.ipfire.org Git - pbs.git/commitdiff
backend: Make unlink() safer and tidier
authorMichael Tremer <michael.tremer@ipfire.org>
Tue, 18 Oct 2022 13:39:26 +0000 (13:39 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Tue, 18 Oct 2022 13:39:26 +0000 (13:39 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/buildservice/__init__.py

index 7473863e85736001db7b73dd531ef45095715552..c2b76f17a29252b9d4ec8849dfbe6365b5c7fe5f 100644 (file)
@@ -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):
                """