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