xref: /freebsd/bin/ln/ln.c (revision 21d30ec18d673020b701750a4d498a4e75cde516)
1 /*-
2  * Copyright (c) 1987, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if 0
31 #ifndef lint
32 static char const copyright[] =
33 "@(#) Copyright (c) 1987, 1993, 1994\n\
34 	The Regents of the University of California.  All rights reserved.\n";
35 #endif /* not lint */
36 
37 #ifndef lint
38 static char sccsid[] = "@(#)ln.c	8.2 (Berkeley) 3/31/94";
39 #endif /* not lint */
40 #endif
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #include <sys/stat.h>
46 
47 #include <err.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <libgen.h>
51 #include <limits.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 int	fflag;				/* Unlink existing files. */
58 int	Fflag;				/* Remove empty directories also. */
59 int	hflag;				/* Check new name for symlink first. */
60 int	iflag;				/* Interactive mode. */
61 int	Pflag;				/* Create hard links to symlinks. */
62 int	sflag;				/* Symbolic, not hard, link. */
63 int	vflag;				/* Verbose output. */
64 int	wflag;				/* Warn if symlink target does not
65 					 * exist, and -f is not enabled. */
66 char	linkch;
67 
68 int	linkit(const char *, const char *, int);
69 void	usage(void);
70 
71 int
72 main(int argc, char *argv[])
73 {
74 	struct stat sb;
75 	char *p, *targetdir;
76 	int ch, exitval;
77 
78 	/*
79 	 * Test for the special case where the utility is called as
80 	 * "link", for which the functionality provided is greatly
81 	 * simplified.
82 	 */
83 	if ((p = rindex(argv[0], '/')) == NULL)
84 		p = argv[0];
85 	else
86 		++p;
87 	if (strcmp(p, "link") == 0) {
88 		while (getopt(argc, argv, "") != -1)
89 			usage();
90 		argc -= optind;
91 		argv += optind;
92 		if (argc != 2)
93 			usage();
94 		exit(linkit(argv[0], argv[1], 0));
95 	}
96 
97 	while ((ch = getopt(argc, argv, "FLPfhinsvw")) != -1)
98 		switch (ch) {
99 		case 'F':
100 			Fflag = 1;
101 			break;
102 		case 'L':
103 			Pflag = 0;
104 			break;
105 		case 'P':
106 			Pflag = 1;
107 			break;
108 		case 'f':
109 			fflag = 1;
110 			iflag = 0;
111 			wflag = 0;
112 			break;
113 		case 'h':
114 		case 'n':
115 			hflag = 1;
116 			break;
117 		case 'i':
118 			iflag = 1;
119 			fflag = 0;
120 			break;
121 		case 's':
122 			sflag = 1;
123 			break;
124 		case 'v':
125 			vflag = 1;
126 			break;
127 		case 'w':
128 			wflag = 1;
129 			break;
130 		case '?':
131 		default:
132 			usage();
133 		}
134 
135 	argv += optind;
136 	argc -= optind;
137 
138 	linkch = sflag ? '-' : '=';
139 	if (sflag == 0)
140 		Fflag = 0;
141 	if (Fflag == 1 && iflag == 0) {
142 		fflag = 1;
143 		wflag = 0;		/* Implied when fflag != 0 */
144 	}
145 
146 	switch(argc) {
147 	case 0:
148 		usage();
149 		/* NOTREACHED */
150 	case 1:				/* ln source */
151 		exit(linkit(argv[0], ".", 1));
152 	case 2:				/* ln source target */
153 		exit(linkit(argv[0], argv[1], 0));
154 	default:
155 		;
156 	}
157 					/* ln source1 source2 directory */
158 	targetdir = argv[argc - 1];
159 	if (hflag && lstat(targetdir, &sb) == 0 && S_ISLNK(sb.st_mode)) {
160 		/*
161 		 * We were asked not to follow symlinks, but found one at
162 		 * the target--simulate "not a directory" error
163 		 */
164 		errno = ENOTDIR;
165 		err(1, "%s", targetdir);
166 	}
167 	if (stat(targetdir, &sb))
168 		err(1, "%s", targetdir);
169 	if (!S_ISDIR(sb.st_mode))
170 		usage();
171 	for (exitval = 0; *argv != targetdir; ++argv)
172 		exitval |= linkit(*argv, targetdir, 1);
173 	exit(exitval);
174 }
175 
176 /*
177  * Two pathnames refer to the same directory entry if the directories match
178  * and the final components' names match.
179  */
180 static int
181 samedirent(const char *path1, const char *path2)
182 {
183 	const char *file1, *file2;
184 	char pathbuf[PATH_MAX];
185 	struct stat sb1, sb2;
186 
187 	if (strcmp(path1, path2) == 0)
188 		return 1;
189 	file1 = strrchr(path1, '/');
190 	if (file1 != NULL)
191 		file1++;
192 	else
193 		file1 = path1;
194 	file2 = strrchr(path2, '/');
195 	if (file2 != NULL)
196 		file2++;
197 	else
198 		file2 = path2;
199 	if (strcmp(file1, file2) != 0)
200 		return 0;
201 	if (file1 - path1 >= PATH_MAX || file2 - path2 >= PATH_MAX)
202 		return 0;
203 	if (file1 == path1)
204 		memcpy(pathbuf, ".", 2);
205 	else {
206 		memcpy(pathbuf, path1, file1 - path1);
207 		pathbuf[file1 - path1] = '\0';
208 	}
209 	if (stat(pathbuf, &sb1) != 0)
210 		return 0;
211 	if (file2 == path2)
212 		memcpy(pathbuf, ".", 2);
213 	else {
214 		memcpy(pathbuf, path2, file2 - path2);
215 		pathbuf[file2 - path2] = '\0';
216 	}
217 	if (stat(pathbuf, &sb2) != 0)
218 		return 0;
219 	return sb1.st_dev == sb2.st_dev && sb1.st_ino == sb2.st_ino;
220 }
221 
222 int
223 linkit(const char *source, const char *target, int isdir)
224 {
225 	struct stat sb;
226 	const char *p;
227 	int ch, exists, first;
228 	char path[PATH_MAX];
229 	char wbuf[PATH_MAX];
230 	char bbuf[PATH_MAX];
231 
232 	if (!sflag) {
233 		/* If source doesn't exist, quit now. */
234 		if ((Pflag ? lstat : stat)(source, &sb)) {
235 			warn("%s", source);
236 			return (1);
237 		}
238 		/* Only symbolic links to directories. */
239 		if (S_ISDIR(sb.st_mode)) {
240 			errno = EISDIR;
241 			warn("%s", source);
242 			return (1);
243 		}
244 	}
245 
246 	/*
247 	 * If the target is a directory (and not a symlink if hflag),
248 	 * append the source's name.
249 	 */
250 	if (isdir ||
251 	    (lstat(target, &sb) == 0 && S_ISDIR(sb.st_mode)) ||
252 	    (!hflag && stat(target, &sb) == 0 && S_ISDIR(sb.st_mode))) {
253 		if (strlcpy(bbuf, source, sizeof(bbuf)) >= sizeof(bbuf) ||
254 		    (p = basename(bbuf)) == NULL ||
255 		    snprintf(path, sizeof(path), "%s/%s", target, p) >=
256 		    (ssize_t)sizeof(path)) {
257 			errno = ENAMETOOLONG;
258 			warn("%s", source);
259 			return (1);
260 		}
261 		target = path;
262 	}
263 
264 	/*
265 	 * If the link source doesn't exist, and a symbolic link was
266 	 * requested, and -w was specified, give a warning.
267 	 */
268 	if (sflag && wflag) {
269 		if (*source == '/') {
270 			/* Absolute link source. */
271 			if (stat(source, &sb) != 0)
272 				 warn("warning: %s inaccessible", source);
273 		} else {
274 			/*
275 			 * Relative symlink source.  Try to construct the
276 			 * absolute path of the source, by appending `source'
277 			 * to the parent directory of the target.
278 			 */
279 			strlcpy(bbuf, target, sizeof(bbuf));
280 			p = dirname(bbuf);
281 			if (p != NULL) {
282 				(void)snprintf(wbuf, sizeof(wbuf), "%s/%s",
283 						p, source);
284 				if (stat(wbuf, &sb) != 0)
285 					warn("warning: %s", source);
286 			}
287 		}
288 	}
289 
290 	/*
291 	 * If the file exists, first check it is not the same directory entry.
292 	 */
293 	exists = !lstat(target, &sb);
294 	if (exists) {
295 		if (!sflag && samedirent(source, target)) {
296 			warnx("%s and %s are the same directory entry",
297 			    source, target);
298 			return (1);
299 		}
300 	}
301 	/*
302 	 * Then unlink it forcibly if -f was specified
303 	 * and interactively if -i was specified.
304 	 */
305 	if (fflag && exists) {
306 		if (Fflag && S_ISDIR(sb.st_mode)) {
307 			if (rmdir(target)) {
308 				warn("%s", target);
309 				return (1);
310 			}
311 		} else if (unlink(target)) {
312 			warn("%s", target);
313 			return (1);
314 		}
315 	} else if (iflag && exists) {
316 		fflush(stdout);
317 		fprintf(stderr, "replace %s? ", target);
318 
319 		first = ch = getchar();
320 		while(ch != '\n' && ch != EOF)
321 			ch = getchar();
322 		if (first != 'y' && first != 'Y') {
323 			fprintf(stderr, "not replaced\n");
324 			return (1);
325 		}
326 
327 		if (Fflag && S_ISDIR(sb.st_mode)) {
328 			if (rmdir(target)) {
329 				warn("%s", target);
330 				return (1);
331 			}
332 		} else if (unlink(target)) {
333 			warn("%s", target);
334 			return (1);
335 		}
336 	}
337 
338 	/* Attempt the link. */
339 	if (sflag ? symlink(source, target) :
340 	    linkat(AT_FDCWD, source, AT_FDCWD, target,
341 	    Pflag ? 0 : AT_SYMLINK_FOLLOW)) {
342 		warn("%s", target);
343 		return (1);
344 	}
345 	if (vflag)
346 		(void)printf("%s %c> %s\n", target, linkch, source);
347 	return (0);
348 }
349 
350 void
351 usage(void)
352 {
353 	(void)fprintf(stderr, "%s\n%s\n%s\n",
354 	    "usage: ln [-s [-F] | -L | -P] [-f | -i] [-hnv] source_file [target_file]",
355 	    "       ln [-s [-F] | -L | -P] [-f | -i] [-hnv] source_file ... target_dir",
356 	    "       link source_file target_file");
357 	exit(1);
358 }
359