changeset 1531:3ff823086c99 draft

Teach ln -f to leave original target alone if link creation fails. Suggested by Ashwini Sharma, I wound up implementing it by creating the new link at a temporary name and renaming it over the old one instead of renaming the old file out of the way and putting it back if it failed. (Because "mkdir -p one/one/blah && ln -sf /bin/one one" would otherwise rename one/one out of the way and only notice it can't delete it way at the end when recovery's darn awkward, vs create new thing and if rename fails (including EISDIR) that's the main error path. And yes the temporary name is in the same directory as the destination so we never rename between mounts.) link over the old one instead of renaming the old file and renaming it back.
author Rob Landley <rob@landley.net>
date Wed, 22 Oct 2014 17:11:06 -0500
parents 3eafa445c1a6
children bf2c5216d726
files toys/posix/ln.c
diffstat 1 files changed, 30 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/toys/posix/ln.c	Mon Oct 20 21:07:16 2014 -0500
+++ b/toys/posix/ln.c	Wed Oct 22 17:11:06 2014 -0500
@@ -46,19 +46,43 @@
 
   for (i=0; i<toys.optc; i++) {
     int rc;
-    char *try = toys.optargs[i];
+    char *oldnew, *try = toys.optargs[i];
 
     if (S_ISDIR(buf.st_mode)) new = xmprintf("%s/%s", dest, basename(try));
     else new = dest;
-    // Silently unlink the existing target (if any)
-    if (toys.optflags & FLAG_f) unlink(new);
+
+    // Force needs to unlink the existing target (if any). Do that by creating
+    // a temp version and renaming it over the old one, so we can retain the
+    // old file in cases we can't replace it (such as hardlink between mounts).
+    oldnew = new;
+    if (toys.optflags & FLAG_f) {
+      new = xmprintf("%s_XXXXXX", new);
+      rc = mkstemp(new);
+      if (rc >= 0) {
+        close(rc);
+        if (unlink(new)) perror_msg("unlink '%s'", new);
+      }
+    }
 
     rc = (toys.optflags & FLAG_s) ? symlink(try, new) : link(try, new);
+    if (toys.optflags & FLAG_f) {
+      if (!rc) {
+        int temp;
+
+        rc = rename(new, oldnew);
+        temp = errno;
+        if (rc && unlink(new)) perror_msg("unlink '%s'", new);
+        errno = temp;
+      }
+      free(new);
+      new = oldnew;
+    }
     if (rc)
-      perror_exit("cannot create %s link from '%s' to '%s'",
+      perror_msg("cannot create %s link from '%s' to '%s'",
         (toys.optflags & FLAG_s) ? "symbolic" : "hard", try, new);
-    else if (toys.optflags & FLAG_v)
-      fprintf(stderr, "'%s' -> '%s'\n", new, try);
+    else
+      if (toys.optflags & FLAG_v) fprintf(stderr, "'%s' -> '%s'\n", new, try);
+
     if (new != dest) free(new);
   }
 }