ln.c revision 206773
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
32static 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
38static char sccsid[] = "@(#)ln.c	8.2 (Berkeley) 3/31/94";
39#endif /* not lint */
40#endif
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD: head/bin/ln/ln.c 206773 2010-04-17 22:39:53Z jilles $");
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 <limits.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.h>
54#include <unistd.h>
55
56int	fflag;				/* Unlink existing files. */
57int	Fflag;				/* Remove empty directories also. */
58int	hflag;				/* Check new name for symlink first. */
59int	iflag;				/* Interactive mode. */
60int	Pflag;				/* Create hard links to symlinks. */
61int	sflag;				/* Symbolic, not hard, link. */
62int	vflag;				/* Verbose output. */
63int	wflag;				/* Warn if symlink target does not
64					 * exist, and -f is not enabled. */
65char	linkch;
66
67int	linkit(const char *, const char *, int);
68void	usage(void);
69
70int
71main(int argc, char *argv[])
72{
73	struct stat sb;
74	char *p, *targetdir;
75	int ch, exitval;
76
77	/*
78	 * Test for the special case where the utility is called as
79	 * "link", for which the functionality provided is greatly
80	 * simplified.
81	 */
82	if ((p = rindex(argv[0], '/')) == NULL)
83		p = argv[0];
84	else
85		++p;
86	if (strcmp(p, "link") == 0) {
87		while (getopt(argc, argv, "") != -1)
88			usage();
89		argc -= optind;
90		argv += optind;
91		if (argc != 2)
92			usage();
93		exit(linkit(argv[0], argv[1], 0));
94	}
95
96	while ((ch = getopt(argc, argv, "FLPfhinsvw")) != -1)
97		switch (ch) {
98		case 'F':
99			Fflag = 1;
100			break;
101		case 'L':
102			Pflag = 0;
103			break;
104		case 'P':
105			Pflag = 1;
106			break;
107		case 'f':
108			fflag = 1;
109			iflag = 0;
110			wflag = 0;
111			break;
112		case 'h':
113		case 'n':
114			hflag = 1;
115			break;
116		case 'i':
117			iflag = 1;
118			fflag = 0;
119			break;
120		case 's':
121			sflag = 1;
122			break;
123		case 'v':
124			vflag = 1;
125			break;
126		case 'w':
127			wflag = 1;
128			break;
129		case '?':
130		default:
131			usage();
132		}
133
134	argv += optind;
135	argc -= optind;
136
137	linkch = sflag ? '-' : '=';
138	if (sflag == 0)
139		Fflag = 0;
140	if (Fflag == 1 && iflag == 0) {
141		fflag = 1;
142		wflag = 0;		/* Implied when fflag != 0 */
143	}
144
145	switch(argc) {
146	case 0:
147		usage();
148		/* NOTREACHED */
149	case 1:				/* ln source */
150		exit(linkit(argv[0], ".", 1));
151	case 2:				/* ln source target */
152		exit(linkit(argv[0], argv[1], 0));
153	default:
154		;
155	}
156					/* ln source1 source2 directory */
157	targetdir = argv[argc - 1];
158	if (hflag && lstat(targetdir, &sb) == 0 && S_ISLNK(sb.st_mode)) {
159		/*
160		 * We were asked not to follow symlinks, but found one at
161		 * the target--simulate "not a directory" error
162		 */
163		errno = ENOTDIR;
164		err(1, "%s", targetdir);
165	}
166	if (stat(targetdir, &sb))
167		err(1, "%s", targetdir);
168	if (!S_ISDIR(sb.st_mode))
169		usage();
170	for (exitval = 0; *argv != targetdir; ++argv)
171		exitval |= linkit(*argv, targetdir, 1);
172	exit(exitval);
173}
174
175/*
176 * Two pathnames refer to the same directory entry if the directories match
177 * and the final components' names match.
178 */
179static int
180samedirent(const char *path1, const char *path2)
181{
182	const char *file1, *file2;
183	char pathbuf[PATH_MAX];
184	struct stat sb1, sb2;
185
186	if (strcmp(path1, path2) == 0)
187		return 1;
188	file1 = strrchr(path1, '/');
189	if (file1 != NULL)
190		file1++;
191	else
192		file1 = path1;
193	file2 = strrchr(path2, '/');
194	if (file2 != NULL)
195		file2++;
196	else
197		file2 = path2;
198	if (strcmp(file1, file2) != 0)
199		return 0;
200	if (file1 - path1 >= PATH_MAX || file2 - path2 >= PATH_MAX)
201		return 0;
202	if (file1 == path1)
203		memcpy(pathbuf, ".", 2);
204	else {
205		memcpy(pathbuf, path1, file1 - path1);
206		pathbuf[file1 - path1] = '\0';
207	}
208	if (stat(pathbuf, &sb1) != 0)
209		return 0;
210	if (file2 == path2)
211		memcpy(pathbuf, ".", 2);
212	else {
213		memcpy(pathbuf, path2, file2 - path2);
214		pathbuf[file2 - path2] = '\0';
215	}
216	if (stat(pathbuf, &sb2) != 0)
217		return 0;
218	return sb1.st_dev == sb2.st_dev && sb1.st_ino == sb2.st_ino;
219}
220
221int
222linkit(const char *source, const char *target, int isdir)
223{
224	struct stat sb;
225	const char *p;
226	int ch, exists, first;
227	char path[PATH_MAX];
228	char wbuf[PATH_MAX];
229
230	if (!sflag) {
231		/* If source doesn't exist, quit now. */
232		if ((Pflag ? lstat : stat)(source, &sb)) {
233			warn("%s", source);
234			return (1);
235		}
236		/* Only symbolic links to directories. */
237		if (S_ISDIR(sb.st_mode)) {
238			errno = EISDIR;
239			warn("%s", source);
240			return (1);
241		}
242	}
243
244	/*
245	 * If the target is a directory (and not a symlink if hflag),
246	 * append the source's name.
247	 */
248	if (isdir ||
249	    (lstat(target, &sb) == 0 && S_ISDIR(sb.st_mode)) ||
250	    (!hflag && stat(target, &sb) == 0 && S_ISDIR(sb.st_mode))) {
251		if ((p = strrchr(source, '/')) == NULL)
252			p = source;
253		else
254			++p;
255		if (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			p = strrchr(target, '/');
280			if (p != NULL)
281				p++;
282			else
283				p = target;
284			(void)snprintf(wbuf, sizeof(wbuf), "%.*s%s",
285			    (int)(p - target), target, source);
286			if (stat(wbuf, &sb) != 0)
287				warn("warning: %s", source);
288		}
289	}
290
291	/*
292	 * If the file exists, first check it is not the same directory entry.
293	 */
294	exists = !lstat(target, &sb);
295	if (exists) {
296		if (!sflag && samedirent(source, target)) {
297			warnx("%s and %s are the same directory entry",
298			    source, target);
299			return (1);
300		}
301	}
302	/*
303	 * Then unlink it forcibly if -f was specified
304	 * and interactively if -i was specified.
305	 */
306	if (fflag && exists) {
307		if (Fflag && S_ISDIR(sb.st_mode)) {
308			if (rmdir(target)) {
309				warn("%s", target);
310				return (1);
311			}
312		} else if (unlink(target)) {
313			warn("%s", target);
314			return (1);
315		}
316	} else if (iflag && exists) {
317		fflush(stdout);
318		fprintf(stderr, "replace %s? ", target);
319
320		first = ch = getchar();
321		while(ch != '\n' && ch != EOF)
322			ch = getchar();
323		if (first != 'y' && first != 'Y') {
324			fprintf(stderr, "not replaced\n");
325			return (1);
326		}
327
328		if (Fflag && S_ISDIR(sb.st_mode)) {
329			if (rmdir(target)) {
330				warn("%s", target);
331				return (1);
332			}
333		} else if (unlink(target)) {
334			warn("%s", target);
335			return (1);
336		}
337	}
338
339	/* Attempt the link. */
340	if (sflag ? symlink(source, target) :
341	    linkat(AT_FDCWD, source, AT_FDCWD, target,
342	    Pflag ? 0 : AT_SYMLINK_FOLLOW)) {
343		warn("%s", target);
344		return (1);
345	}
346	if (vflag)
347		(void)printf("%s %c> %s\n", target, linkch, source);
348	return (0);
349}
350
351void
352usage(void)
353{
354	(void)fprintf(stderr, "%s\n%s\n%s\n",
355	    "usage: ln [-s [-F] | -L | -P] [-f | -i] [-hnv] source_file [target_file]",
356	    "       ln [-s [-F] | -L | -P] [-f | -i] [-hnv] source_file ... target_dir",
357	    "       link source_file target_file");
358	exit(1);
359}
360