From d2e588d94fabacfeb5b08790365161a015a00b98 Mon Sep 17 00:00:00 2001
From: Colin Walters <walters@verbum.org>
Date: Fri, 8 Jul 2016 13:06:47 -0400
Subject: [PATCH] fdio: Add unlinkat() in error paths for tmpfiles

This is kind of an ABI change but it's for the better I think; on
error we consistently clean up the temp file.

This is obviously necessary without `O_TMPFILE`.  With it, we still
need an error cleanup in the case where we're trying to replace an
existing file.  I noticed this in ostree's `tests/test-refs.sh` which
intentionally tries to rename a file over a directory path.
---
 glnx-fdio.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/glnx-fdio.c b/glnx-fdio.c
index 55eef098d..f4648ed8d 100644
--- a/glnx-fdio.c
+++ b/glnx-fdio.c
@@ -199,6 +199,7 @@ glnx_link_tmpfile_at (int dfd,
            */
           if (renameat (dfd, tmpfile_path, target_dfd, target) < 0)
             {
+              (void) unlinkat (dfd, tmpfile_path, 0);
               glnx_set_error_from_errno (error);
               return FALSE;
             }
@@ -209,7 +210,10 @@ glnx_link_tmpfile_at (int dfd,
           if (!rename_file_noreplace_at (dfd, tmpfile_path, target_dfd, target,
                                          ignore_eexist,
                                          error))
-            return FALSE;
+            {
+              (void) unlinkat (dfd, tmpfile_path, 0);
+              return FALSE;
+            }
         }
     }
   else
@@ -257,6 +261,10 @@ glnx_link_tmpfile_at (int dfd,
             }
           if (renameat (target_dfd, tmpname_buf, target_dfd, target) < 0)
             {
+              /* This is currently the only case where we need to have
+               * a cleanup unlinkat() still with O_TMPFILE.
+               */
+              (void) unlinkat (target_dfd, tmpname_buf, 0);
               glnx_set_error_from_errno (error);
               return FALSE;
             }
-- 
GitLab