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