# HG changeset patch
# User Mike Becker <universe@uap-core.de>
# Date 1586072098 -7200
# Node ID 5c2e4da00b0454a0eb14be73a2b44c615d74614c
# Parent  f4da6141e2338f36d0f1115dcd85754703955bfd
cmd_edit: replaces unlink() with sys_unlink() + keep tmp file on resource error

diff -r f4da6141e233 -r 5c2e4da00b04 dav/main.c
--- a/dav/main.c	Sat Mar 28 17:15:47 2020 +0100
+++ b/dav/main.c	Sun Apr 05 09:34:58 2020 +0200
@@ -1246,7 +1246,7 @@
         if(dav_get_content(res, tmp_stream, (dav_write_func)fwrite)) {
             print_resource_error(sn, path);
             close(tmp_fd);
-            unlink(outfile);
+            sys_unlink(outfile);
             return -1;
         }
         fclose(tmp_stream);
@@ -1257,7 +1257,7 @@
     if(sys_stat(outfile, &tmp_stat)) {
         perror("Cannot stat temporary file");
         close(tmp_fd);
-        unlink(outfile);
+        sys_unlink(outfile);
         return -1;
     }
     time_t dl_mtime = tmp_stat.st_mtime;
@@ -1290,6 +1290,7 @@
         } else {
             // check if the file has changed
             if (sys_stat(outfile, &tmp_stat)) {
+                // very rare case when someone concurrently changes permissions
                 perror("Cannot stat temporary file");
                 ret = 1;
             } else if (dl_mtime < tmp_stat.st_mtime) {
@@ -1316,7 +1317,12 @@
     }
     
     close(tmp_fd);
-    unlink(outfile);
+    if(ret) {
+        // if someone went wrong, we are most likely unable to unlink anyway
+        fprintf(stderr, "File location: %s\n", outfile);
+    } else {
+        sys_unlink(outfile);
+    }
     free(path);
     
     return ret;