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