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