[dev] [sbase] [PATCH 1/2] ln: only check existence of src/to for hardlinks

From: Eivind Uggedal <eivind_AT_uggedal.com>
Date: Fri, 8 May 2015 08:16:57 +0000

This allows for creating dangling symlinks with force applied:

    # Before:
    $ ln -sf non-existant target
    ln: stat non-existent: No such file or directory
    $ ls -l target
    ls: lstat target: No such file or directory

    # After:
    $ ln -sf non-existant target
    $ ls -l target
    lrwxrwxrwx 1 eu users 12 May 08 07:50 target -> non-existent

This also allows creating relative non-dangling symlinks with force applied:

    touch existant; mkdir dir

    # Before
    $ ln -sf ../existant dir
    ln: stat ../existant: No such file or directory
    $ ls -l dir

    # After
    $ ln -sf ../existant dir
    $ ls -l dir
    lrwxrwxrwx 1 eu users 11 May 08 07:53 existant -> ../existant

The check for whether each src and to pairs are on the same device with the
same inode are only needed for hardlinks so that a forcefull link does
not remove the underlying file:

    touch f; mkdir dir

    # Before:
    $ ln -f f f dir
    ln: f and f are the same file
    $ ls -i f dir/f
    3670611 dir/f
    3670611 f

    # After:
    $ ln -f f f dir
    ln: f and f are the same file
    $ ls -i f dir/f
    4332236 dir/f
    4332236 f
---
 ln.c | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)
diff --git a/ln.c b/ln.c
index b63e75c64b95..2bfdbbdeacc6 100644
--- a/ln.c
+++ b/ln.c
_AT_@ -61,21 +61,20 @@ main(int argc, char *argv[])
 	for (; *argv; argc--, argv++) {
 		if (!hasto)
 			to = basename(*argv);
-		if (fflag) {
+		if (!sflag) {
 			if (stat(*argv, &st) < 0) {
 				weprintf("stat %s:", *argv);
 				continue;
 			} else if (fstatat(dirfd, to, &tost, AT_SYMLINK_NOFOLLOW) < 0) {
 				if (errno != ENOENT)
 					eprintf("stat %s:", to);
-			} else {
-				if (st.st_dev == tost.st_dev && st.st_ino == tost.st_ino) {
-					weprintf("%s and %s are the same file\n", *argv, *argv);
-					continue;
-				}
-				unlinkat(dirfd, to, 0);
+			} else if (st.st_dev == tost.st_dev && st.st_ino == tost.st_ino) {
+				weprintf("%s and %s are the same file\n", *argv, *argv);
+				continue;
 			}
 		}
+		if (fflag)
+			unlinkat(dirfd, to, 0);
 		if ((!sflag ? linkat(AT_FDCWD, *argv, dirfd, to, flags)
 		            : symlinkat(*argv, dirfd, to)) < 0) {
 			weprintf("%s %s <- %s:", fname, *argv, to);
-- 
2.4.0
Received on Fri May 08 2015 - 10:16:57 CEST

This archive was generated by hypermail 2.3.0 : Fri May 08 2015 - 10:24:12 CEST