sbase/ln.c
Eivind Uggedal 8f4b2e8689 ln: only check existence of src/to for hardlinks
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
2015-05-08 10:06:58 +01:00

86 lines
1.7 KiB
C

/* See LICENSE file for copyright and license details. */
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <unistd.h>
#include "util.h"
static void
usage(void)
{
eprintf("usage: %s [-f] [-L | -P | -s] target [name]\n"
" %s [-f] [-L | -P | -s] target ... dir\n", argv0, argv0);
}
int
main(int argc, char *argv[])
{
char *fname, *to;
int sflag = 0, fflag = 0, hasto = 0, dirfd = AT_FDCWD, flags = AT_SYMLINK_FOLLOW;
struct stat st, tost;
ARGBEGIN {
case 'f':
fflag = 1;
break;
case 'L':
flags |= AT_SYMLINK_FOLLOW;
break;
case 'P':
flags &= ~AT_SYMLINK_FOLLOW;
break;
case 's':
sflag = 1;
break;
default:
usage();
} ARGEND;
if (!argc)
usage();
fname = sflag ? "symlink" : "link";
if (argc >= 2) {
if (!stat(argv[argc - 1], &st) && S_ISDIR(st.st_mode)) {
if ((dirfd = open(argv[argc - 1], O_RDONLY)) < 0)
eprintf("open %s:", argv[argc - 1]);
} else if (argc == 2) {
to = argv[argc - 1];
hasto = 1;
} else {
eprintf("%s: not a directory\n", argv[argc - 1]);
}
argv[argc - 1] = NULL;
argc--;
}
for (; *argv; argc--, argv++) {
if (!hasto)
to = basename(*argv);
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;
}
}
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);
}
}
return 0;
}