cp.c revision 14157
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 *	$Id: cp.c,v 1.8 1996/02/19 00:43:42 wosch Exp $
37 */
38
39#ifndef lint
40static char copyright[] =
41"@(#) Copyright (c) 1988, 1993, 1994\n\
42	The Regents of the University of California.  All rights reserved.\n";
43#endif /* not lint */
44
45#ifndef lint
46static char sccsid[] = "@(#)cp.c	8.2 (Berkeley) 4/1/94";
47#endif /* not lint */
48
49/*
50 * Cp copies source files to target files.
51 *
52 * The global PATH_T structure "to" always contains the path to the
53 * current target file.  Since fts(3) does not change directories,
54 * this path can be either absolute or dot-realative.
55 *
56 * The basic algorithm is to initialize "to" and use fts(3) to traverse
57 * the file hierarchy rooted in the argument list.  A trivial case is the
58 * case of 'cp file1 file2'.  The more interesting case is the case of
59 * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
60 * path (relative to the root of the traversal) is appended to dir (stored
61 * in "to") to form the final target path.
62 */
63
64#include <sys/param.h>
65#include <sys/stat.h>
66#include <sys/mman.h>
67#include <sys/time.h>
68
69#include <dirent.h>
70#include <err.h>
71#include <errno.h>
72#include <fcntl.h>
73#include <fts.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
86PATH_T to = { to.p_path, "" };
87
88uid_t myuid;
89int Rflag, iflag, pflag, rflag;
90int myumask;
91
92enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
93
94int copy __P((char *[], enum op, int));
95int mastercmp __P((const FTSENT **, const FTSENT **));
96
97int
98main(argc, argv)
99	int argc;
100	char *argv[];
101{
102	struct stat to_stat, tmp_stat;
103	enum op type;
104	int Hflag, Lflag, Pflag, ch, fts_options, r;
105	char *target;
106
107	Hflag = Lflag = Pflag = 0;
108	while ((ch = getopt(argc, argv, "HLPRfipr")) != EOF)
109		switch (ch) {
110		case 'H':
111			Hflag = 1;
112			Lflag = Pflag = 0;
113			break;
114		case 'L':
115			Lflag = 1;
116			Hflag = Pflag = 0;
117			break;
118		case 'P':
119			Pflag = 1;
120			Hflag = Lflag = 0;
121			break;
122		case 'R':
123			Rflag = 1;
124			break;
125		case 'f':
126			iflag = 0;
127			break;
128		case 'i':
129			iflag = isatty(fileno(stdin));
130			break;
131		case 'p':
132			pflag = 1;
133			break;
134		case 'r':
135			rflag = 1;
136			break;
137		default:
138			usage();
139			break;
140		}
141	argc -= optind;
142	argv += optind;
143
144	if (argc < 2)
145		usage();
146
147	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
148	if (rflag) {
149		if (Rflag)
150			errx(1,
151		    "the -R and -r options may not be specified together.");
152		if (Hflag || Lflag || Pflag)
153			errx(1,
154	"the -H, -L, and -P options may not be specified with the -r option.");
155		fts_options &= ~FTS_PHYSICAL;
156		fts_options |= FTS_LOGICAL;
157	}
158	if (Rflag) {
159		if (Hflag)
160			fts_options |= FTS_COMFOLLOW;
161		if (Lflag) {
162			fts_options &= ~FTS_PHYSICAL;
163			fts_options |= FTS_LOGICAL;
164		}
165	} else {
166		fts_options &= ~FTS_PHYSICAL;
167		fts_options |= FTS_LOGICAL;
168	}
169
170	myuid = getuid();
171
172	/* Copy the umask for explicit mode setting. */
173	myumask = umask(0);
174	(void)umask(myumask);
175
176	/* Save the target base in "to". */
177	target = argv[--argc];
178	if (strlen(target) > MAXPATHLEN)
179		errx(1, "%s: name too long", target);
180	(void)strcpy(to.p_path, 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        STRIP_TRAILING_SLASH(to);
187	to.target_end = to.p_end;
188
189	/* Set end of argument list for fts(3). */
190	argv[argc] = NULL;
191
192	/*
193	 * Cp has two distinct cases:
194	 *
195	 * cp [-R] source target
196	 * cp [-R] source1 ... sourceN directory
197	 *
198	 * In both cases, source can be either a file or a directory.
199	 *
200	 * In (1), the target becomes a copy of the source. That is, if the
201	 * source is a file, the target will be a file, and likewise for
202	 * directories.
203	 *
204	 * In (2), the real target is not directory, but "directory/source".
205	 */
206	r = stat(to.p_path, &to_stat);
207	if (r == -1 && errno != ENOENT)
208		err(1, "%s", to.p_path);
209	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
210		/*
211		 * Case (1).  Target is not a directory.
212		 */
213		if (argc > 1) {
214			usage();
215			exit(1);
216		}
217		/*
218		 * Need to detect the case:
219		 *	cp -R dir foo
220		 * Where dir is a directory and foo does not exist, where
221		 * we want pathname concatenations turned on but not for
222		 * the initial mkdir().
223		 */
224		if (r == -1) {
225			if (rflag || (Rflag && (Lflag || Hflag)))
226				stat(*argv, &tmp_stat);
227			else
228				lstat(*argv, &tmp_stat);
229
230			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
231				type = DIR_TO_DNE;
232			else
233				type = FILE_TO_FILE;
234		} else
235			type = FILE_TO_FILE;
236	} else
237		/*
238		 * Case (2).  Target is a directory.
239		 */
240		type = FILE_TO_DIR;
241
242	exit (copy(argv, type, fts_options));
243}
244
245int
246copy(argv, type, fts_options)
247	char *argv[];
248	enum op type;
249	int fts_options;
250{
251	struct stat to_stat;
252	FTS *ftsp;
253	FTSENT *curr;
254	int base, dne, nlen, rval;
255	char *p, *target_mid;
256
257	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
258		err(1, NULL);
259	for (rval = 0; (curr = fts_read(ftsp)) != NULL;) {
260		switch (curr->fts_info) {
261		case FTS_NS:
262		case FTS_ERR:
263			warnx("%s: %s",
264			    curr->fts_path, strerror(curr->fts_errno));
265			rval = 1;
266			continue;
267		case FTS_DC:			/* Warn, continue. */
268			warnx("%s: directory causes a cycle", curr->fts_path);
269			rval = 1;
270			continue;
271		case FTS_DP:			/* Ignore, continue. */
272			continue;
273		}
274
275		/*
276		 * If we are in case (2) or (3) above, we need to append the
277                 * source name to the target name.
278                 */
279		if (type != FILE_TO_FILE) {
280			/*
281			 * Need to remember the roots of traversals to create
282			 * correct pathnames.  If there's a directory being
283			 * copied to a non-existent directory, e.g.
284			 *	cp -R a/dir noexist
285			 * the resulting path name should be noexist/foo, not
286			 * noexist/dir/foo (where foo is a file in dir), which
287			 * is the case where the target exists.
288			 *
289			 * Also, check for "..".  This is for correct path
290			 * concatentation for paths ending in "..", e.g.
291			 *	cp -R .. /tmp
292			 * Paths ending in ".." are changed to ".".  This is
293			 * tricky, but seems the easiest way to fix the problem.
294			 *
295			 * XXX
296			 * Since the first level MUST be FTS_ROOTLEVEL, base
297			 * is always initialized.
298			 */
299			if (curr->fts_level == FTS_ROOTLEVEL)
300				if (type != DIR_TO_DNE) {
301					p = strrchr(curr->fts_path, '/');
302					base = (p == NULL) ? 0 :
303					    (int)(p - curr->fts_path + 1);
304
305					if (!strcmp(&curr->fts_path[base],
306					    ".."))
307						base += 1;
308				} else
309					base = curr->fts_pathlen;
310
311			p = &curr->fts_path[base];
312			nlen = curr->fts_pathlen - base;
313			target_mid = to.target_end;
314			if (*p != '/' && target_mid[-1] != '/')
315				*target_mid++ = '/';
316			*target_mid = 0;
317			if (target_mid - to.p_path + nlen > MAXPATHLEN) {
318				warnx("%s%s: name too long (not copied)",
319				    to.p_path, p);
320				rval = 1;
321				continue;
322			}
323			(void)strncat(target_mid, p, nlen);
324			to.p_end = target_mid + nlen;
325			*to.p_end = 0;
326			STRIP_TRAILING_SLASH(to);
327		}
328
329		/* Not an error but need to remember it happened */
330		if (stat(to.p_path, &to_stat) == -1)
331			dne = 1;
332		else {
333			if (to_stat.st_dev == curr->fts_statp->st_dev &&
334			    to_stat.st_ino == curr->fts_statp->st_ino) {
335				warnx("%s and %s are identical (not copied).",
336				    to.p_path, curr->fts_path);
337				rval = 1;
338				if (S_ISDIR(curr->fts_statp->st_mode))
339					(void)fts_set(ftsp, curr, FTS_SKIP);
340				continue;
341			}
342			dne = 0;
343		}
344
345		switch (curr->fts_statp->st_mode & S_IFMT) {
346		case S_IFLNK:
347			if (copy_link(curr, !dne))
348				rval = 1;
349			break;
350		case S_IFDIR:
351			if (!Rflag && !rflag) {
352				warnx("%s is a directory (not copied).",
353				    curr->fts_path);
354				(void)fts_set(ftsp, curr, FTS_SKIP);
355				rval = 1;
356				break;
357			}
358			/*
359			 * If the directory doesn't exist, create the new
360			 * one with the from file mode plus owner RWX bits,
361			 * modified by the umask.  Trade-off between being
362			 * able to write the directory (if from directory is
363			 * 555) and not causing a permissions race.  If the
364			 * umask blocks owner writes, we fail..
365			 */
366			if (dne) {
367				if (mkdir(to.p_path,
368				    curr->fts_statp->st_mode | S_IRWXU) < 0)
369					err(1, "%s", to.p_path);
370			} else if (!S_ISDIR(to_stat.st_mode)) {
371				errno = ENOTDIR;
372				err(1, "%s", to.p_path);
373			}
374			/*
375			 * If not -p and directory didn't exist, set it to be
376			 * the same as the from directory, umodified by the
377                         * umask; arguably wrong, but it's been that way
378                         * forever.
379			 */
380			if (pflag && setfile(curr->fts_statp, 0))
381				rval = 1;
382			else if (dne)
383				(void)chmod(to.p_path,
384				    curr->fts_statp->st_mode);
385			break;
386		case S_IFBLK:
387		case S_IFCHR:
388			if (Rflag) {
389				if (copy_special(curr->fts_statp, !dne))
390					rval = 1;
391			} else {
392				if (copy_file(curr, dne))
393					rval = 1;
394			}
395			break;
396		case S_IFIFO:
397			if (Rflag) {
398				if (copy_fifo(curr->fts_statp, !dne))
399					rval = 1;
400			} else {
401				if (copy_file(curr, dne))
402					rval = 1;
403			}
404			break;
405		default:
406			if (copy_file(curr, dne))
407				rval = 1;
408			break;
409		}
410	}
411	if (errno)
412		err(1, "fts_read");
413	return (rval);
414}
415
416/*
417 * mastercmp --
418 *	The comparison function for the copy order.  The order is to copy
419 *	non-directory files before directory files.  The reason for this
420 *	is because files tend to be in the same cylinder group as their
421 *	parent directory, whereas directories tend not to be.  Copying the
422 *	files first reduces seeking.
423 */
424int
425mastercmp(a, b)
426	const FTSENT **a, **b;
427{
428	int a_info, b_info;
429
430	a_info = (*a)->fts_info;
431	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
432		return (0);
433	b_info = (*b)->fts_info;
434	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
435		return (0);
436	if (a_info == FTS_D)
437		return (-1);
438	if (b_info == FTS_D)
439		return (1);
440	return (0);
441}
442