1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40#include "libbb.h"
41
42
43
44
45#define LN_SYMLINK (1 << 0)
46#define LN_FORCE (1 << 1)
47#define LN_NODEREFERENCE (1 << 2)
48#define LN_BACKUP (1 << 3)
49#define LN_SUFFIX (1 << 4)
50#define LN_VERBOSE (1 << 5)
51#define LN_LINKFILE (1 << 6)
52
53int ln_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
54int ln_main(int argc, char **argv)
55{
56 int status = EXIT_SUCCESS;
57 int opts;
58 char *last;
59 char *src_name;
60 char *src;
61 char *suffix = (char*)"~";
62 struct stat statbuf;
63 int (*link_func)(const char *, const char *);
64
65 opts = getopt32(argv, "^" "sfnbS:vT" "\0" "-1", &suffix);
66
67 last = argv[argc - 1];
68 argv += optind;
69 argc -= optind;
70
71 if ((opts & LN_LINKFILE) && argc > 2) {
72 bb_error_msg_and_die("-T accepts 2 args max");
73 }
74
75 if (!argv[1]) {
76
77 *--argv = last;
78
79
80
81 last = bb_get_last_path_component_strip(xstrdup(last));
82 }
83
84 do {
85 src_name = NULL;
86 src = last;
87
88 if (is_directory(src,
89 (opts & LN_NODEREFERENCE) ^ LN_NODEREFERENCE
90 )
91 ) {
92 if (opts & LN_LINKFILE) {
93 bb_error_msg_and_die("'%s' is a directory", src);
94 }
95 src_name = xstrdup(*argv);
96 src = concat_path_file(src, bb_get_last_path_component_strip(src_name));
97 free(src_name);
98 src_name = src;
99 }
100 if (!(opts & LN_SYMLINK) && stat(*argv, &statbuf)) {
101
102 if (lstat(*argv, &statbuf) || !S_ISLNK(statbuf.st_mode)) {
103 bb_simple_perror_msg(*argv);
104 status = EXIT_FAILURE;
105 free(src_name);
106 continue;
107 }
108 }
109
110 if (opts & LN_BACKUP) {
111 char *backup;
112 backup = xasprintf("%s%s", src, suffix);
113 if (rename(src, backup) < 0 && errno != ENOENT) {
114 bb_simple_perror_msg(src);
115 status = EXIT_FAILURE;
116 free(backup);
117 continue;
118 }
119 free(backup);
120
121
122
123
124
125 unlink(src);
126 } else if (opts & LN_FORCE) {
127 unlink(src);
128 }
129
130 link_func = link;
131 if (opts & LN_SYMLINK) {
132 link_func = symlink;
133 }
134
135 if (opts & LN_VERBOSE) {
136 printf("'%s' -> '%s'\n", src, *argv);
137 }
138
139 if (link_func(*argv, src) != 0) {
140 bb_simple_perror_msg(src);
141 status = EXIT_FAILURE;
142 }
143
144 free(src_name);
145 } while ((++argv)[1]);
146
147 return status;
148}
149