cp.c revision 100538
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#ifndef lint
38static char const copyright[] =
39"@(#) Copyright (c) 1988, 1993, 1994\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44#if 0
45static char sccsid[] = "@(#)cp.c	8.2 (Berkeley) 4/1/94";
46#endif
47#endif /* not lint */
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD: head/bin/cp/cp.c 100538 2002-07-23 00:42:56Z johan $");
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/param.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 <stdio.h>
74#include <stdlib.h>
75#include <string.h>
76#include <unistd.h>
77
78#include "extern.h"
79
80#define	STRIP_TRAILING_SLASH(p) {					\
81        while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
82                *--(p).p_end = 0;					\
83}
84
85static char emptystring[] = "";
86
87PATH_T to = { to.p_path, emptystring, "" };
88
89int fflag, iflag, nflag, pflag, vflag;
90static int Rflag, rflag;
91
92enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
93
94static int copy(char *[], enum op, int);
95static int mastercmp(const FTSENT **, const FTSENT **);
96
97int
98main(int argc, char *argv[])
99{
100	struct stat to_stat, tmp_stat;
101	enum op type;
102	int Hflag, Lflag, Pflag, ch, fts_options, r, have_trailing_slash;
103	char *target;
104
105	Hflag = Lflag = Pflag = 0;
106	while ((ch = getopt(argc, argv, "HLPRfinprv")) != -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 'f':
124			fflag = 1;
125			iflag = nflag = 0;
126			break;
127		case 'i':
128			iflag = 1;
129			fflag = nflag = 0;
130			break;
131		case 'n':
132			nflag = 1;
133			fflag = iflag = 0;
134			break;
135		case 'p':
136			pflag = 1;
137			break;
138		case 'r':
139			rflag = 1;
140			break;
141		case 'v':
142			vflag = 1;
143			break;
144		default:
145			usage();
146			break;
147		}
148	argc -= optind;
149	argv += optind;
150
151	if (argc < 2)
152		usage();
153
154	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
155	if (rflag) {
156		if (Rflag)
157			errx(1,
158		    "the -R and -r options may not be specified together.");
159		if (Hflag || Lflag || Pflag)
160			errx(1,
161	"the -H, -L, and -P options may not be specified with the -r option.");
162		fts_options &= ~FTS_PHYSICAL;
163		fts_options |= FTS_LOGICAL;
164	}
165	if (Rflag) {
166		if (Hflag)
167			fts_options |= FTS_COMFOLLOW;
168		if (Lflag) {
169			fts_options &= ~FTS_PHYSICAL;
170			fts_options |= FTS_LOGICAL;
171		}
172	} else {
173		fts_options &= ~FTS_PHYSICAL;
174		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
175	}
176
177	/* Save the target base in "to". */
178	target = argv[--argc];
179	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
180		errx(1, "%s: name too long", target);
181	to.p_end = to.p_path + strlen(to.p_path);
182        if (to.p_path == to.p_end) {
183		*to.p_end++ = '.';
184		*to.p_end = 0;
185	}
186	have_trailing_slash = (to.p_end[-1] == '/');
187	if (have_trailing_slash)
188		STRIP_TRAILING_SLASH(to);
189	to.target_end = to.p_end;
190
191	/* Set end of argument list for fts(3). */
192	argv[argc] = NULL;
193
194	/*
195	 * Cp has two distinct cases:
196	 *
197	 * cp [-R] source target
198	 * cp [-R] source1 ... sourceN directory
199	 *
200	 * In both cases, source can be either a file or a directory.
201	 *
202	 * In (1), the target becomes a copy of the source. That is, if the
203	 * source is a file, the target will be a file, and likewise for
204	 * directories.
205	 *
206	 * In (2), the real target is not directory, but "directory/source".
207	 */
208	r = stat(to.p_path, &to_stat);
209	if (r == -1 && errno != ENOENT)
210		err(1, "%s", to.p_path);
211	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
212		/*
213		 * Case (1).  Target is not a directory.
214		 */
215		if (argc > 1) {
216			usage();
217			exit(1);
218		}
219		/*
220		 * Need to detect the case:
221		 *	cp -R dir foo
222		 * Where dir is a directory and foo does not exist, where
223		 * we want pathname concatenations turned on but not for
224		 * the initial mkdir().
225		 */
226		if (r == -1) {
227			if (rflag || (Rflag && (Lflag || Hflag)))
228				stat(*argv, &tmp_stat);
229			else
230				lstat(*argv, &tmp_stat);
231
232			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
233				type = DIR_TO_DNE;
234			else
235				type = FILE_TO_FILE;
236		} else
237			type = FILE_TO_FILE;
238
239		if (have_trailing_slash && type == FILE_TO_FILE) {
240			if (r == -1)
241				errx(1, "directory %s does not exist",
242				     to.p_path);
243			else
244				errx(1, "%s is not a directory", to.p_path);
245		}
246	} else
247		/*
248		 * Case (2).  Target is a directory.
249		 */
250		type = FILE_TO_DIR;
251
252	exit (copy(argv, type, fts_options));
253}
254
255int
256copy(char *argv[], enum op type, int fts_options)
257{
258	struct stat to_stat;
259	FTS *ftsp;
260	FTSENT *curr;
261	int base = 0, dne, badcp, rval;
262	size_t nlen;
263	char *p, *target_mid;
264	mode_t mask, mode;
265
266	/*
267	 * Keep an inverted copy of the umask, for use in correcting
268	 * permissions on created directories when not using -p.
269	 */
270	mask = ~umask(0777);
271	umask(~mask);
272
273	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
274		err(1, "fts_open");
275	for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
276		switch (curr->fts_info) {
277		case FTS_NS:
278		case FTS_DNR:
279		case FTS_ERR:
280			warnx("%s: %s",
281			    curr->fts_path, strerror(curr->fts_errno));
282			badcp = rval = 1;
283			continue;
284		case FTS_DC:			/* Warn, continue. */
285			warnx("%s: directory causes a cycle", curr->fts_path);
286			badcp = rval = 1;
287			continue;
288		default:
289			;
290		}
291
292		/*
293		 * If we are in case (2) or (3) above, we need to append the
294                 * source name to the target name.
295                 */
296		if (type != FILE_TO_FILE) {
297			/*
298			 * Need to remember the roots of traversals to create
299			 * correct pathnames.  If there's a directory being
300			 * copied to a non-existent directory, e.g.
301			 *	cp -R a/dir noexist
302			 * the resulting path name should be noexist/foo, not
303			 * noexist/dir/foo (where foo is a file in dir), which
304			 * is the case where the target exists.
305			 *
306			 * Also, check for "..".  This is for correct path
307			 * concatenation for paths ending in "..", e.g.
308			 *	cp -R .. /tmp
309			 * Paths ending in ".." are changed to ".".  This is
310			 * tricky, but seems the easiest way to fix the problem.
311			 *
312			 * XXX
313			 * Since the first level MUST be FTS_ROOTLEVEL, base
314			 * is always initialized.
315			 */
316			if (curr->fts_level == FTS_ROOTLEVEL) {
317				if (type != DIR_TO_DNE) {
318					p = strrchr(curr->fts_path, '/');
319					base = (p == NULL) ? 0 :
320					    (int)(p - curr->fts_path + 1);
321
322					if (!strcmp(&curr->fts_path[base],
323					    ".."))
324						base += 1;
325				} else
326					base = curr->fts_pathlen;
327			}
328
329			p = &curr->fts_path[base];
330			nlen = curr->fts_pathlen - base;
331			target_mid = to.target_end;
332			if (*p != '/' && target_mid[-1] != '/')
333				*target_mid++ = '/';
334			*target_mid = 0;
335			if (target_mid - to.p_path + nlen >= PATH_MAX) {
336				warnx("%s%s: name too long (not copied)",
337				    to.p_path, p);
338				badcp = rval = 1;
339				continue;
340			}
341			(void)strncat(target_mid, p, nlen);
342			to.p_end = target_mid + nlen;
343			*to.p_end = 0;
344			STRIP_TRAILING_SLASH(to);
345		}
346
347		if (curr->fts_info == FTS_DP) {
348			/*
349			 * We are nearly finished with this directory.  If we
350			 * didn't actually copy it, or otherwise don't need to
351			 * change its attributes, then we are done.
352			 */
353			if (!curr->fts_number)
354				continue;
355			/*
356			 * If -p is in effect, set all the attributes.
357			 * Otherwise, set the correct permissions, limited
358			 * by the umask.  Optimise by avoiding a chmod()
359			 * if possible (which is usually the case if we
360			 * made the directory).  Note that mkdir() does not
361			 * honour setuid, setgid and sticky bits, but we
362			 * normally want to preserve them on directories.
363			 */
364			if (pflag)
365				rval = setfile(curr->fts_statp, 0);
366			else {
367				mode = curr->fts_statp->st_mode;
368				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
369				    ((mode | S_IRWXU) & mask) != (mode & mask))
370					if (chmod(to.p_path, mode & mask) != 0){
371						warn("chmod: %s", to.p_path);
372						rval = 1;
373					}
374			}
375			continue;
376		}
377
378		/* Not an error but need to remember it happened */
379		if (stat(to.p_path, &to_stat) == -1)
380			dne = 1;
381		else {
382			if (to_stat.st_dev == curr->fts_statp->st_dev &&
383			    to_stat.st_ino == curr->fts_statp->st_ino) {
384				warnx("%s and %s are identical (not copied).",
385				    to.p_path, curr->fts_path);
386				badcp = rval = 1;
387				if (S_ISDIR(curr->fts_statp->st_mode))
388					(void)fts_set(ftsp, curr, FTS_SKIP);
389				continue;
390			}
391			if (!S_ISDIR(curr->fts_statp->st_mode) &&
392			    S_ISDIR(to_stat.st_mode)) {
393				warnx("cannot overwrite directory %s with "
394				    "non-directory %s",
395				    to.p_path, curr->fts_path);
396				badcp = rval = 1;
397				continue;
398			}
399			dne = 0;
400		}
401
402		switch (curr->fts_statp->st_mode & S_IFMT) {
403		case S_IFLNK:
404			/* Catch special case of a non-dangling symlink */
405			if ((fts_options & FTS_LOGICAL) ||
406			    ((fts_options & FTS_COMFOLLOW) &&
407			    curr->fts_level == 0)) {
408				if (copy_file(curr, dne))
409					badcp = rval = 1;
410			} else {
411				if (copy_link(curr, !dne))
412					badcp = rval = 1;
413			}
414			break;
415		case S_IFDIR:
416			if (!Rflag && !rflag) {
417				warnx("%s is a directory (not copied).",
418				    curr->fts_path);
419				(void)fts_set(ftsp, curr, FTS_SKIP);
420				badcp = rval = 1;
421				break;
422			}
423			/*
424			 * If the directory doesn't exist, create the new
425			 * one with the from file mode plus owner RWX bits,
426			 * modified by the umask.  Trade-off between being
427			 * able to write the directory (if from directory is
428			 * 555) and not causing a permissions race.  If the
429			 * umask blocks owner writes, we fail..
430			 */
431			if (dne) {
432				if (mkdir(to.p_path,
433				    curr->fts_statp->st_mode | S_IRWXU) < 0)
434					err(1, "%s", to.p_path);
435			} else if (!S_ISDIR(to_stat.st_mode)) {
436				errno = ENOTDIR;
437				err(1, "%s", to.p_path);
438			}
439			/*
440			 * Arrange to correct directory attributes later
441			 * (in the post-order phase) if this is a new
442			 * directory, or if the -p flag is in effect.
443			 */
444			curr->fts_number = pflag || dne;
445			break;
446		case S_IFBLK:
447		case S_IFCHR:
448			if (Rflag) {
449				if (copy_special(curr->fts_statp, !dne))
450					badcp = rval = 1;
451			} else {
452				if (copy_file(curr, dne))
453					badcp = rval = 1;
454			}
455			break;
456		case S_IFIFO:
457			if (Rflag) {
458				if (copy_fifo(curr->fts_statp, !dne))
459					badcp = rval = 1;
460			} else {
461				if (copy_file(curr, dne))
462					badcp = rval = 1;
463			}
464			break;
465		default:
466			if (copy_file(curr, dne))
467				badcp = rval = 1;
468			break;
469		}
470		if (vflag && !badcp)
471			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
472	}
473	if (errno)
474		err(1, "fts_read");
475	return (rval);
476}
477
478/*
479 * mastercmp --
480 *	The comparison function for the copy order.  The order is to copy
481 *	non-directory files before directory files.  The reason for this
482 *	is because files tend to be in the same cylinder group as their
483 *	parent directory, whereas directories tend not to be.  Copying the
484 *	files first reduces seeking.
485 */
486int
487mastercmp(const FTSENT **a, const FTSENT **b)
488{
489	int a_info, b_info;
490
491	a_info = (*a)->fts_info;
492	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
493		return (0);
494	b_info = (*b)->fts_info;
495	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
496		return (0);
497	if (a_info == FTS_D)
498		return (-1);
499	if (b_info == FTS_D)
500		return (1);
501	return (0);
502}
503