cp.c revision 208821
1/*-
2 * Copyright (c) 1988, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * David Hitz of Auspex Systems Inc.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#if 0
34#ifndef lint
35static char const copyright[] =
36"@(#) Copyright (c) 1988, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41static char sccsid[] = "@(#)cp.c	8.2 (Berkeley) 4/1/94";
42#endif /* not lint */
43#endif
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/bin/cp/cp.c 208821 2010-06-05 08:50:39Z trasz $");
46
47/*
48 * Cp copies source files to target files.
49 *
50 * The global PATH_T structure "to" always contains the path to the
51 * current target file.  Since fts(3) does not change directories,
52 * this path can be either absolute or dot-relative.
53 *
54 * The basic algorithm is to initialize "to" and use fts(3) to traverse
55 * the file hierarchy rooted in the argument list.  A trivial case is the
56 * case of 'cp file1 file2'.  The more interesting case is the case of
57 * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
58 * path (relative to the root of the traversal) is appended to dir (stored
59 * in "to") to form the final target path.
60 */
61
62#include <sys/types.h>
63#include <sys/stat.h>
64
65#include <err.h>
66#include <errno.h>
67#include <fts.h>
68#include <limits.h>
69#include <signal.h>
70#include <stdio.h>
71#include <stdlib.h>
72#include <string.h>
73#include <unistd.h>
74
75#include "extern.h"
76
77#define	STRIP_TRAILING_SLASH(p) {					\
78        while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
79                *--(p).p_end = 0;					\
80}
81
82static char emptystring[] = "";
83
84PATH_T to = { to.p_path, emptystring, "" };
85
86int fflag, iflag, lflag, nflag, pflag, vflag;
87static int Rflag, rflag;
88volatile sig_atomic_t info;
89
90enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
91
92static int copy(char *[], enum op, int);
93static int mastercmp(const FTSENT * const *, const FTSENT * const *);
94static void siginfo(int __unused);
95
96int
97main(int argc, char *argv[])
98{
99	struct stat to_stat, tmp_stat;
100	enum op type;
101	int Hflag, Lflag, Pflag, ch, fts_options, r, have_trailing_slash;
102	char *target;
103
104	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
105	Hflag = Lflag = Pflag = 0;
106	while ((ch = getopt(argc, argv, "HLPRafilnprvx")) != -1)
107		switch (ch) {
108		case 'H':
109			Hflag = 1;
110			Lflag = Pflag = 0;
111			break;
112		case 'L':
113			Lflag = 1;
114			Hflag = Pflag = 0;
115			break;
116		case 'P':
117			Pflag = 1;
118			Hflag = Lflag = 0;
119			break;
120		case 'R':
121			Rflag = 1;
122			break;
123		case 'a':
124			Pflag = 1;
125			pflag = 1;
126			Rflag = 1;
127			Hflag = Lflag = 0;
128			break;
129		case 'f':
130			fflag = 1;
131			iflag = nflag = 0;
132			break;
133		case 'i':
134			iflag = 1;
135			fflag = nflag = 0;
136			break;
137		case 'l':
138			lflag = 1;
139			break;
140		case 'n':
141			nflag = 1;
142			fflag = iflag = 0;
143			break;
144		case 'p':
145			pflag = 1;
146			break;
147		case 'r':
148			rflag = Lflag = 1;
149			Hflag = Pflag = 0;
150			break;
151		case 'v':
152			vflag = 1;
153			break;
154		case 'x':
155			fts_options |= FTS_XDEV;
156			break;
157		default:
158			usage();
159			break;
160		}
161	argc -= optind;
162	argv += optind;
163
164	if (argc < 2)
165		usage();
166
167	if (Rflag && rflag)
168		errx(1, "the -R and -r options may not be specified together");
169	if (rflag)
170		Rflag = 1;
171	if (Rflag) {
172		if (Hflag)
173			fts_options |= FTS_COMFOLLOW;
174		if (Lflag) {
175			fts_options &= ~FTS_PHYSICAL;
176			fts_options |= FTS_LOGICAL;
177		}
178	} else {
179		fts_options &= ~FTS_PHYSICAL;
180		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
181	}
182	(void)signal(SIGINFO, siginfo);
183
184	/* Save the target base in "to". */
185	target = argv[--argc];
186	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
187		errx(1, "%s: name too long", target);
188	to.p_end = to.p_path + strlen(to.p_path);
189        if (to.p_path == to.p_end) {
190		*to.p_end++ = '.';
191		*to.p_end = 0;
192	}
193	have_trailing_slash = (to.p_end[-1] == '/');
194	if (have_trailing_slash)
195		STRIP_TRAILING_SLASH(to);
196	to.target_end = to.p_end;
197
198	/* Set end of argument list for fts(3). */
199	argv[argc] = NULL;
200
201	/*
202	 * Cp has two distinct cases:
203	 *
204	 * cp [-R] source target
205	 * cp [-R] source1 ... sourceN directory
206	 *
207	 * In both cases, source can be either a file or a directory.
208	 *
209	 * In (1), the target becomes a copy of the source. That is, if the
210	 * source is a file, the target will be a file, and likewise for
211	 * directories.
212	 *
213	 * In (2), the real target is not directory, but "directory/source".
214	 */
215	r = stat(to.p_path, &to_stat);
216	if (r == -1 && errno != ENOENT)
217		err(1, "%s", to.p_path);
218	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
219		/*
220		 * Case (1).  Target is not a directory.
221		 */
222		if (argc > 1)
223			errx(1, "%s is not a directory", to.p_path);
224
225		/*
226		 * Need to detect the case:
227		 *	cp -R dir foo
228		 * Where dir is a directory and foo does not exist, where
229		 * we want pathname concatenations turned on but not for
230		 * the initial mkdir().
231		 */
232		if (r == -1) {
233			if (Rflag && (Lflag || Hflag))
234				stat(*argv, &tmp_stat);
235			else
236				lstat(*argv, &tmp_stat);
237
238			if (S_ISDIR(tmp_stat.st_mode) && Rflag)
239				type = DIR_TO_DNE;
240			else
241				type = FILE_TO_FILE;
242		} else
243			type = FILE_TO_FILE;
244
245		if (have_trailing_slash && type == FILE_TO_FILE) {
246			if (r == -1)
247				errx(1, "directory %s does not exist",
248				     to.p_path);
249			else
250				errx(1, "%s is not a directory", to.p_path);
251		}
252	} else
253		/*
254		 * Case (2).  Target is a directory.
255		 */
256		type = FILE_TO_DIR;
257
258	exit (copy(argv, type, fts_options));
259}
260
261static int
262copy(char *argv[], enum op type, int fts_options)
263{
264	struct stat to_stat;
265	FTS *ftsp;
266	FTSENT *curr;
267	int base = 0, dne, badcp, rval;
268	size_t nlen;
269	char *p, *target_mid;
270	mode_t mask, mode;
271
272	/*
273	 * Keep an inverted copy of the umask, for use in correcting
274	 * permissions on created directories when not using -p.
275	 */
276	mask = ~umask(0777);
277	umask(~mask);
278
279	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
280		err(1, "fts_open");
281	for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
282		switch (curr->fts_info) {
283		case FTS_NS:
284		case FTS_DNR:
285		case FTS_ERR:
286			warnx("%s: %s",
287			    curr->fts_path, strerror(curr->fts_errno));
288			badcp = rval = 1;
289			continue;
290		case FTS_DC:			/* Warn, continue. */
291			warnx("%s: directory causes a cycle", curr->fts_path);
292			badcp = rval = 1;
293			continue;
294		default:
295			;
296		}
297
298		/*
299		 * If we are in case (2) or (3) above, we need to append the
300                 * source name to the target name.
301                 */
302		if (type != FILE_TO_FILE) {
303			/*
304			 * Need to remember the roots of traversals to create
305			 * correct pathnames.  If there's a directory being
306			 * copied to a non-existent directory, e.g.
307			 *	cp -R a/dir noexist
308			 * the resulting path name should be noexist/foo, not
309			 * noexist/dir/foo (where foo is a file in dir), which
310			 * is the case where the target exists.
311			 *
312			 * Also, check for "..".  This is for correct path
313			 * concatenation for paths ending in "..", e.g.
314			 *	cp -R .. /tmp
315			 * Paths ending in ".." are changed to ".".  This is
316			 * tricky, but seems the easiest way to fix the problem.
317			 *
318			 * XXX
319			 * Since the first level MUST be FTS_ROOTLEVEL, base
320			 * is always initialized.
321			 */
322			if (curr->fts_level == FTS_ROOTLEVEL) {
323				if (type != DIR_TO_DNE) {
324					p = strrchr(curr->fts_path, '/');
325					base = (p == NULL) ? 0 :
326					    (int)(p - curr->fts_path + 1);
327
328					if (!strcmp(&curr->fts_path[base],
329					    ".."))
330						base += 1;
331				} else
332					base = curr->fts_pathlen;
333			}
334
335			p = &curr->fts_path[base];
336			nlen = curr->fts_pathlen - base;
337			target_mid = to.target_end;
338			if (*p != '/' && target_mid[-1] != '/')
339				*target_mid++ = '/';
340			*target_mid = 0;
341			if (target_mid - to.p_path + nlen >= PATH_MAX) {
342				warnx("%s%s: name too long (not copied)",
343				    to.p_path, p);
344				badcp = rval = 1;
345				continue;
346			}
347			(void)strncat(target_mid, p, nlen);
348			to.p_end = target_mid + nlen;
349			*to.p_end = 0;
350			STRIP_TRAILING_SLASH(to);
351		}
352
353		if (curr->fts_info == FTS_DP) {
354			/*
355			 * We are nearly finished with this directory.  If we
356			 * didn't actually copy it, or otherwise don't need to
357			 * change its attributes, then we are done.
358			 */
359			if (!curr->fts_number)
360				continue;
361			/*
362			 * If -p is in effect, set all the attributes.
363			 * Otherwise, set the correct permissions, limited
364			 * by the umask.  Optimise by avoiding a chmod()
365			 * if possible (which is usually the case if we
366			 * made the directory).  Note that mkdir() does not
367			 * honour setuid, setgid and sticky bits, but we
368			 * normally want to preserve them on directories.
369			 */
370			if (pflag) {
371				if (setfile(curr->fts_statp, -1))
372					rval = 1;
373				if (preserve_dir_acls(curr->fts_statp,
374				    curr->fts_accpath, to.p_path) != 0)
375					rval = 1;
376			} else {
377				mode = curr->fts_statp->st_mode;
378				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
379				    ((mode | S_IRWXU) & mask) != (mode & mask))
380					if (chmod(to.p_path, mode & mask) != 0){
381						warn("chmod: %s", to.p_path);
382						rval = 1;
383					}
384			}
385			continue;
386		}
387
388		/* Not an error but need to remember it happened */
389		if (stat(to.p_path, &to_stat) == -1)
390			dne = 1;
391		else {
392			if (to_stat.st_dev == curr->fts_statp->st_dev &&
393			    to_stat.st_ino == curr->fts_statp->st_ino) {
394				warnx("%s and %s are identical (not copied).",
395				    to.p_path, curr->fts_path);
396				badcp = rval = 1;
397				if (S_ISDIR(curr->fts_statp->st_mode))
398					(void)fts_set(ftsp, curr, FTS_SKIP);
399				continue;
400			}
401			if (!S_ISDIR(curr->fts_statp->st_mode) &&
402			    S_ISDIR(to_stat.st_mode)) {
403				warnx("cannot overwrite directory %s with "
404				    "non-directory %s",
405				    to.p_path, curr->fts_path);
406				badcp = rval = 1;
407				continue;
408			}
409			dne = 0;
410		}
411
412		switch (curr->fts_statp->st_mode & S_IFMT) {
413		case S_IFLNK:
414			/* Catch special case of a non-dangling symlink */
415			if ((fts_options & FTS_LOGICAL) ||
416			    ((fts_options & FTS_COMFOLLOW) &&
417			    curr->fts_level == 0)) {
418				if (copy_file(curr, dne))
419					badcp = rval = 1;
420			} else {
421				if (copy_link(curr, !dne))
422					badcp = rval = 1;
423			}
424			break;
425		case S_IFDIR:
426			if (!Rflag) {
427				warnx("%s is a directory (not copied).",
428				    curr->fts_path);
429				(void)fts_set(ftsp, curr, FTS_SKIP);
430				badcp = rval = 1;
431				break;
432			}
433			/*
434			 * If the directory doesn't exist, create the new
435			 * one with the from file mode plus owner RWX bits,
436			 * modified by the umask.  Trade-off between being
437			 * able to write the directory (if from directory is
438			 * 555) and not causing a permissions race.  If the
439			 * umask blocks owner writes, we fail..
440			 */
441			if (dne) {
442				if (mkdir(to.p_path,
443				    curr->fts_statp->st_mode | S_IRWXU) < 0)
444					err(1, "%s", to.p_path);
445			} else if (!S_ISDIR(to_stat.st_mode)) {
446				errno = ENOTDIR;
447				err(1, "%s", to.p_path);
448			}
449			/*
450			 * Arrange to correct directory attributes later
451			 * (in the post-order phase) if this is a new
452			 * directory, or if the -p flag is in effect.
453			 */
454			curr->fts_number = pflag || dne;
455			break;
456		case S_IFBLK:
457		case S_IFCHR:
458			if (Rflag) {
459				if (copy_special(curr->fts_statp, !dne))
460					badcp = rval = 1;
461			} else {
462				if (copy_file(curr, dne))
463					badcp = rval = 1;
464			}
465			break;
466		case S_IFSOCK:
467			warnx("%s is a socket (not copied).",
468				    curr->fts_path);
469			break;
470		case S_IFIFO:
471			if (Rflag) {
472				if (copy_fifo(curr->fts_statp, !dne))
473					badcp = rval = 1;
474			} else {
475				if (copy_file(curr, dne))
476					badcp = rval = 1;
477			}
478			break;
479		default:
480			if (copy_file(curr, dne))
481				badcp = rval = 1;
482			break;
483		}
484		if (vflag && !badcp)
485			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
486	}
487	if (errno)
488		err(1, "fts_read");
489	fts_close(ftsp);
490	return (rval);
491}
492
493/*
494 * mastercmp --
495 *	The comparison function for the copy order.  The order is to copy
496 *	non-directory files before directory files.  The reason for this
497 *	is because files tend to be in the same cylinder group as their
498 *	parent directory, whereas directories tend not to be.  Copying the
499 *	files first reduces seeking.
500 */
501static int
502mastercmp(const FTSENT * const *a, const FTSENT * const *b)
503{
504	int a_info, b_info;
505
506	a_info = (*a)->fts_info;
507	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
508		return (0);
509	b_info = (*b)->fts_info;
510	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
511		return (0);
512	if (a_info == FTS_D)
513		return (-1);
514	if (b_info == FTS_D)
515		return (1);
516	return (0);
517}
518
519static void
520siginfo(int sig __unused)
521{
522
523	info = 1;
524}
525