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 opt_complementary = "-1";
66 opts = getopt32(argv, "sfnbS:vT", &suffix);
67
68 last = argv[argc - 1];
69 argv += optind;
70 argc -= optind;
71
72 if ((opts & LN_LINKFILE) && argc > 2) {
73 bb_error_msg_and_die("-T accepts 2 args max");
74 }
75
76 if (!argv[1]) {
77
78 *--argv = last;
79
80
81
82 last = bb_get_last_path_component_strip(xstrdup(last));
83 }
84
85 do {
86 src_name = NULL;
87 src = last;
88
89 if (is_directory(src,
90 (opts & LN_NODEREFERENCE) ^ LN_NODEREFERENCE
91 )
92 ) {
93 if (opts & LN_LINKFILE) {
94 bb_error_msg_and_die("'%s' is a directory", src);
95 }
96 src_name = xstrdup(*argv);
97 src = concat_path_file(src, bb_get_last_path_component_strip(src_name));
98 free(src_name);
99 src_name = src;
100 }
101 if (!(opts & LN_SYMLINK) && stat(*argv, &statbuf)) {
102
103 if (lstat(*argv, &statbuf) || !S_ISLNK(statbuf.st_mode)) {
104 bb_simple_perror_msg(*argv);
105 status = EXIT_FAILURE;
106 free(src_name);
107 continue;
108 }
109 }
110
111 if (opts & LN_BACKUP) {
112 char *backup;
113 backup = xasprintf("%s%s", src, suffix);
114 if (rename(src, backup) < 0 && errno != ENOENT) {
115 bb_simple_perror_msg(src);
116 status = EXIT_FAILURE;
117 free(backup);
118 continue;
119 }
120 free(backup);
121
122
123
124
125
126 unlink(src);
127 } else if (opts & LN_FORCE) {
128 unlink(src);
129 }
130
131 link_func = link;
132 if (opts & LN_SYMLINK) {
133 link_func = symlink;
134 }
135
136 if (opts & LN_VERBOSE) {
137 printf("'%s' -> '%s'\n", src, *argv);
138 }
139
140 if (link_func(*argv, src) != 0) {
141 bb_simple_perror_msg(src);
142 status = EXIT_FAILURE;
143 }
144
145 free(src_name);
146 } while ((++argv)[1]);
147
148 return status;
149}
150