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