sbase/ln.c

90 lines
1.8 KiB
C
Raw Normal View History

2011-05-24 12:00:30 +00:00
/* See LICENSE file for copyright and license details. */
2015-02-14 20:02:41 +00:00
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
2014-10-17 15:03:41 +00:00
#include <libgen.h>
#include <unistd.h>
2011-05-24 12:00:30 +00:00
#include "util.h"
2013-06-14 18:20:47 +00:00
static void
usage(void)
{
2015-01-31 14:23:59 +00:00
eprintf("usage: %s [-f] [-L | -P | -s] target [name]\n"
" %s [-f] [-L | -P | -s] target ... dir\n", argv0, argv0);
2013-06-14 18:20:47 +00:00
}
2011-05-24 12:00:30 +00:00
int
main(int argc, char *argv[])
{
char *fname, *to;
2015-05-08 08:16:58 +00:00
int sflag = 0, fflag = 0, hasto = 0, dirfd = AT_FDCWD, ret = 0,
flags = AT_SYMLINK_FOLLOW;
struct stat st, tost;
2014-02-17 11:41:37 +00:00
2013-06-14 18:20:47 +00:00
ARGBEGIN {
case 'f':
fflag = 1;
2013-06-14 18:20:47 +00:00
break;
case 'L':
flags |= AT_SYMLINK_FOLLOW;
break;
case 'P':
flags &= ~AT_SYMLINK_FOLLOW;
break;
case 's':
sflag = 1;
break;
2013-06-14 18:20:47 +00:00
default:
usage();
} ARGEND;
if (!argc)
2014-10-17 15:03:41 +00:00
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--;
}
2014-02-17 11:41:37 +00:00
for (; *argv; argc--, argv++) {
if (!hasto)
to = basename(*argv);
if (!sflag) {
if (stat(*argv, &st) < 0) {
weprintf("stat %s:", *argv);
2015-05-08 08:16:58 +00:00
ret = 1;
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);
2015-05-08 08:16:58 +00:00
ret = 1;
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);
2015-05-08 08:16:58 +00:00
ret = 1;
}
}
2013-06-14 18:20:47 +00:00
2015-05-08 08:16:58 +00:00
return ret;
2011-05-24 12:00:30 +00:00
}