1 /* ln.c - Create filesystem links
2 *
3 * Copyright 2012 Andre Renaud <[email protected]>
4 *
5 * See http://opengroup.org/onlinepubs/9699919799/utilities/ln.html
6
7 USE_LN(NEWTOY(ln, "<1rt:Tvnfs", TOYFLAG_BIN))
8
9 config LN
10 bool "ln"
11 default y
12 help
13 usage: ln [-fnrsTv] [-t DIR] [FROM...] TO
14
15 Create a link between FROM and TO.
16 One/two/many arguments work like "mv" or "cp".
17
18 -f Force the creation of the link, even if TO already exists
19 -n Symlink at TO treated as file
20 -r Create relative symlink from -> to
21 -s Create a symbolic link
22 -t Create links in DIR
23 -T TO always treated as file, max 2 arguments
24 -v Verbose
25 */
26
27 #define FOR_ln
28 #include "toys.h"
29
GLOBALS(char * t;)30 GLOBALS(
31 char *t;
32 )
33
34 void ln_main(void)
35 {
36 char *dest = TT.t ? TT.t : toys.optargs[--toys.optc], *new;
37 struct stat buf;
38 int i, rc;
39
40 if (FLAG(T) && toys.optc>1) help_exit("Max 2 arguments");
41
42 // With one argument, create link in current directory.
43 if (!toys.optc) {
44 toys.optc++;
45 dest = ".";
46 }
47
48 // Is destination a directory?
49 if (!((FLAG(n)||FLAG(T)) ? lstat : stat)(dest, &buf)) {
50 if ((i = S_ISDIR(buf.st_mode)) ? FLAG(T) : (toys.optc>1 || TT.t))
51 error_exit("'%s' %s a directory", dest, i ? "is" : "not");
52 } else buf.st_mode = 0;
53
54 for (i=0; i<toys.optc; i++) {
55 char *oldnew = 0, *try = toys.optargs[i], *ss;
56
57 if (S_ISDIR(buf.st_mode)) new = xmprintf("%s/%s", dest, basename(try));
58 else new = dest;
59
60 if (FLAG(r)) {
61 ss = xstrdup(new);
62 try = relative_path(dirname(ss), try, 1);
63 free(ss);
64 if (!try) {
65 if (new != dest) free(new);
66 continue;
67 }
68 toys.optflags |= FLAG_s;
69 }
70
71 // Force needs to unlink the existing target (if any). Do that by creating
72 // a temp version and renaming it over the old one, so we can retain the
73 // old file in cases we can't replace it (such as hardlink between mounts).
74 oldnew = new;
75 if (FLAG(f)) {
76 new = xmprintf("%s_XXXXXX", new);
77 rc = mkstemp(new);
78 if (rc >= 0) {
79 close(rc);
80 if (unlink(new)) perror_msg("unlink '%s'", new);
81 }
82 }
83
84 rc = FLAG(s) ? symlink(try, new) : link(try, new);
85 if (FLAG(f)) {
86 if (!rc) {
87 int temp;
88
89 rc = rename(new, oldnew);
90 temp = errno;
91 if (rc && unlink(new)) perror_msg("unlink '%s'", new);
92 errno = temp;
93 }
94 free(new);
95 new = oldnew;
96 }
97 if (rc) perror_msg("cannot create %s link from '%s' to '%s'",
98 FLAG(s) ? "symbolic" : "hard", try, new);
99 else if (FLAG(v)) fprintf(stderr, "'%s' -> '%s'\n", new, try);
100
101 if (try != toys.optargs[i]) free(try);
102 if (new != dest) free(new);
103 }
104 }
105