xref: /freebsd/bin/cp/cp.c (revision 716fd348e01c5f2ba125f878a634a753436c2994)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1988, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * David Hitz of Auspex Systems Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #if 0
36 #ifndef lint
37 static char const copyright[] =
38 "@(#) Copyright (c) 1988, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif /* not lint */
41 
42 #ifndef lint
43 static char sccsid[] = "@(#)cp.c	8.2 (Berkeley) 4/1/94";
44 #endif /* not lint */
45 #endif
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
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-relative.
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/types.h>
65 #include <sys/stat.h>
66 
67 #include <assert.h>
68 #include <err.h>
69 #include <errno.h>
70 #include <fts.h>
71 #include <limits.h>
72 #include <signal.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 
85 static char emptystring[] = "";
86 
87 PATH_T to = { to.p_path, emptystring, "" };
88 
89 int fflag, iflag, lflag, nflag, pflag, sflag, vflag;
90 static int Hflag, Lflag, Rflag, rflag;
91 volatile sig_atomic_t info;
92 
93 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
94 
95 static int copy(char *[], enum op, int, struct stat *);
96 static void siginfo(int __unused);
97 
98 int
99 main(int argc, char *argv[])
100 {
101 	struct stat to_stat, tmp_stat;
102 	enum op type;
103 	int Pflag, ch, fts_options, r, have_trailing_slash;
104 	char *target;
105 
106 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
107 	Pflag = 0;
108 	while ((ch = getopt(argc, argv, "HLPRafilnprsvx")) != -1)
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 'a':
126 			pflag = 1;
127 			Rflag = 1;
128 			Pflag = 1;
129 			Hflag = Lflag = 0;
130 			break;
131 		case 'f':
132 			fflag = 1;
133 			iflag = nflag = 0;
134 			break;
135 		case 'i':
136 			iflag = 1;
137 			fflag = nflag = 0;
138 			break;
139 		case 'l':
140 			lflag = 1;
141 			break;
142 		case 'n':
143 			nflag = 1;
144 			fflag = iflag = 0;
145 			break;
146 		case 'p':
147 			pflag = 1;
148 			break;
149 		case 'r':
150 			rflag = Lflag = 1;
151 			Hflag = Pflag = 0;
152 			break;
153 		case 's':
154 			sflag = 1;
155 			break;
156 		case 'v':
157 			vflag = 1;
158 			break;
159 		case 'x':
160 			fts_options |= FTS_XDEV;
161 			break;
162 		default:
163 			usage();
164 			break;
165 		}
166 	argc -= optind;
167 	argv += optind;
168 
169 	if (argc < 2)
170 		usage();
171 
172 	if (Rflag && rflag)
173 		errx(1, "the -R and -r options may not be specified together");
174 	if (lflag && sflag)
175 		errx(1, "the -l and -s options may not be specified together");
176 	if (rflag)
177 		Rflag = 1;
178 	if (Rflag) {
179 		if (Hflag)
180 			fts_options |= FTS_COMFOLLOW;
181 		if (Lflag) {
182 			fts_options &= ~FTS_PHYSICAL;
183 			fts_options |= FTS_LOGICAL;
184 		}
185 	} else if (!Pflag) {
186 		fts_options &= ~FTS_PHYSICAL;
187 		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
188 	}
189 	(void)signal(SIGINFO, siginfo);
190 
191 	/* Save the target base in "to". */
192 	target = argv[--argc];
193 	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
194 		errx(1, "%s: name too long", target);
195 	to.p_end = to.p_path + strlen(to.p_path);
196 	if (to.p_path == to.p_end) {
197 		*to.p_end++ = '.';
198 		*to.p_end = 0;
199 	}
200 	have_trailing_slash = (to.p_end[-1] == '/');
201 	if (have_trailing_slash)
202 		STRIP_TRAILING_SLASH(to);
203 	to.target_end = to.p_end;
204 
205 	/* Set end of argument list for fts(3). */
206 	argv[argc] = NULL;
207 
208 	/*
209 	 * Cp has two distinct cases:
210 	 *
211 	 * cp [-R] source target
212 	 * cp [-R] source1 ... sourceN directory
213 	 *
214 	 * In both cases, source can be either a file or a directory.
215 	 *
216 	 * In (1), the target becomes a copy of the source. That is, if the
217 	 * source is a file, the target will be a file, and likewise for
218 	 * directories.
219 	 *
220 	 * In (2), the real target is not directory, but "directory/source".
221 	 */
222 	r = stat(to.p_path, &to_stat);
223 	if (r == -1 && errno != ENOENT)
224 		err(1, "%s", to.p_path);
225 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
226 		/*
227 		 * Case (1).  Target is not a directory.
228 		 */
229 		if (argc > 1)
230 			errx(1, "%s is not a directory", to.p_path);
231 
232 		/*
233 		 * Need to detect the case:
234 		 *	cp -R dir foo
235 		 * Where dir is a directory and foo does not exist, where
236 		 * we want pathname concatenations turned on but not for
237 		 * the initial mkdir().
238 		 */
239 		if (r == -1) {
240 			if (Rflag && (Lflag || Hflag))
241 				stat(*argv, &tmp_stat);
242 			else
243 				lstat(*argv, &tmp_stat);
244 
245 			if (S_ISDIR(tmp_stat.st_mode) && Rflag)
246 				type = DIR_TO_DNE;
247 			else
248 				type = FILE_TO_FILE;
249 		} else
250 			type = FILE_TO_FILE;
251 
252 		if (have_trailing_slash && type == FILE_TO_FILE) {
253 			if (r == -1) {
254 				errx(1, "directory %s does not exist",
255 				    to.p_path);
256 			} else
257 				errx(1, "%s is not a directory", to.p_path);
258 		}
259 	} else
260 		/*
261 		 * Case (2).  Target is a directory.
262 		 */
263 		type = FILE_TO_DIR;
264 
265 	/*
266 	 * For DIR_TO_DNE, we could provide copy() with the to_stat we've
267 	 * already allocated on the stack here that isn't being used for
268 	 * anything.  Not doing so, though, simplifies later logic a little bit
269 	 * as we need to skip checking root_stat on the first iteration and
270 	 * ensure that we set it with the first mkdir().
271 	 */
272 	exit (copy(argv, type, fts_options, (type == DIR_TO_DNE ? NULL :
273 	    &to_stat)));
274 }
275 
276 /* Does the right thing based on -R + -H/-L/-P */
277 static int
278 copy_stat(const char *path, struct stat *sb)
279 {
280 
281 	/*
282 	 * For -R -H/-P, we need to lstat() instead; copy() cares about the link
283 	 * itself rather than the target if we're not following links during the
284 	 * traversal.
285 	 */
286 	if (!Rflag || Lflag)
287 		return (stat(path, sb));
288 	return (lstat(path, sb));
289 }
290 
291 
292 static int
293 copy(char *argv[], enum op type, int fts_options, struct stat *root_stat)
294 {
295 	char rootname[NAME_MAX];
296 	struct stat created_root_stat, to_stat;
297 	FTS *ftsp;
298 	FTSENT *curr;
299 	int base = 0, dne, badcp, rval;
300 	size_t nlen;
301 	char *p, *recurse_path, *target_mid;
302 	mode_t mask, mode;
303 
304 	/*
305 	 * Keep an inverted copy of the umask, for use in correcting
306 	 * permissions on created directories when not using -p.
307 	 */
308 	mask = ~umask(0777);
309 	umask(~mask);
310 
311 	recurse_path = NULL;
312 	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
313 		err(1, "fts_open");
314 	for (badcp = rval = 0; errno = 0, (curr = fts_read(ftsp)) != NULL;
315             badcp = 0) {
316 		switch (curr->fts_info) {
317 		case FTS_NS:
318 		case FTS_DNR:
319 		case FTS_ERR:
320 			warnx("%s: %s",
321 			    curr->fts_path, strerror(curr->fts_errno));
322 			badcp = rval = 1;
323 			continue;
324 		case FTS_DC:			/* Warn, continue. */
325 			warnx("%s: directory causes a cycle", curr->fts_path);
326 			badcp = rval = 1;
327 			continue;
328 		default:
329 			;
330 		}
331 
332 		/*
333 		 * Stash the root basename off for detecting recursion later.
334 		 *
335 		 * This will be essential if the root is a symlink and we're
336 		 * rolling with -L or -H.  The later bits will need this bit in
337 		 * particular.
338 		 */
339 		if (curr->fts_level == FTS_ROOTLEVEL) {
340 			strlcpy(rootname, curr->fts_name, sizeof(rootname));
341 		}
342 
343 		/*
344 		 * If we are in case (2) or (3) above, we need to append the
345 		 * source name to the target name.
346 		 */
347 		if (type != FILE_TO_FILE) {
348 			/*
349 			 * Need to remember the roots of traversals to create
350 			 * correct pathnames.  If there's a directory being
351 			 * copied to a non-existent directory, e.g.
352 			 *	cp -R a/dir noexist
353 			 * the resulting path name should be noexist/foo, not
354 			 * noexist/dir/foo (where foo is a file in dir), which
355 			 * is the case where the target exists.
356 			 *
357 			 * Also, check for "..".  This is for correct path
358 			 * concatenation for paths ending in "..", e.g.
359 			 *	cp -R .. /tmp
360 			 * Paths ending in ".." are changed to ".".  This is
361 			 * tricky, but seems the easiest way to fix the problem.
362 			 *
363 			 * XXX
364 			 * Since the first level MUST be FTS_ROOTLEVEL, base
365 			 * is always initialized.
366 			 */
367 			if (curr->fts_level == FTS_ROOTLEVEL) {
368 				if (type != DIR_TO_DNE) {
369 					p = strrchr(curr->fts_path, '/');
370 					base = (p == NULL) ? 0 :
371 					    (int)(p - curr->fts_path + 1);
372 
373 					if (!strcmp(&curr->fts_path[base],
374 					    ".."))
375 						base += 1;
376 				} else
377 					base = curr->fts_pathlen;
378 			}
379 
380 			p = &curr->fts_path[base];
381 			nlen = curr->fts_pathlen - base;
382 			target_mid = to.target_end;
383 			if (*p != '/' && target_mid[-1] != '/')
384 				*target_mid++ = '/';
385 			*target_mid = 0;
386 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
387 				warnx("%s%s: name too long (not copied)",
388 				    to.p_path, p);
389 				badcp = rval = 1;
390 				continue;
391 			}
392 			(void)strncat(target_mid, p, nlen);
393 			to.p_end = target_mid + nlen;
394 			*to.p_end = 0;
395 			STRIP_TRAILING_SLASH(to);
396 
397 			/*
398 			 * We're on the verge of recursing on ourselves.  Either
399 			 * we need to stop right here (we knowingly just created
400 			 * it), or we will in an immediate descendant.  Record
401 			 * the path of the immediate descendant to make our
402 			 * lives a little less complicated looking.
403 			 */
404 			if (curr->fts_info == FTS_D && root_stat != NULL &&
405 			    root_stat->st_dev == curr->fts_statp->st_dev &&
406 			    root_stat->st_ino == curr->fts_statp->st_ino) {
407 				assert(recurse_path == NULL);
408 
409 				if (root_stat == &created_root_stat) {
410 					/*
411 					 * This directory didn't exist when we
412 					 * started, we created it as part of
413 					 * traversal.  Stop right here before we
414 					 * do something silly.
415 					 */
416 					fts_set(ftsp, curr, FTS_SKIP);
417 					continue;
418 				}
419 
420 
421 				if (asprintf(&recurse_path, "%s/%s", to.p_path,
422 				    rootname) == -1)
423 					err(1, "asprintf");
424 			}
425 
426 			if (recurse_path != NULL &&
427 			    strcmp(to.p_path, recurse_path) == 0) {
428 				fts_set(ftsp, curr, FTS_SKIP);
429 				continue;
430 			}
431 		}
432 
433 		if (curr->fts_info == FTS_DP) {
434 			/*
435 			 * We are nearly finished with this directory.  If we
436 			 * didn't actually copy it, or otherwise don't need to
437 			 * change its attributes, then we are done.
438 			 */
439 			if (!curr->fts_number)
440 				continue;
441 			/*
442 			 * If -p is in effect, set all the attributes.
443 			 * Otherwise, set the correct permissions, limited
444 			 * by the umask.  Optimise by avoiding a chmod()
445 			 * if possible (which is usually the case if we
446 			 * made the directory).  Note that mkdir() does not
447 			 * honour setuid, setgid and sticky bits, but we
448 			 * normally want to preserve them on directories.
449 			 */
450 			if (pflag) {
451 				if (setfile(curr->fts_statp, -1))
452 					rval = 1;
453 				if (preserve_dir_acls(curr->fts_statp,
454 				    curr->fts_accpath, to.p_path) != 0)
455 					rval = 1;
456 			} else {
457 				mode = curr->fts_statp->st_mode;
458 				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
459 				    ((mode | S_IRWXU) & mask) != (mode & mask))
460 					if (chmod(to.p_path, mode & mask) !=
461 					    0) {
462 						warn("chmod: %s", to.p_path);
463 						rval = 1;
464 					}
465 			}
466 			continue;
467 		}
468 
469 		/* Not an error but need to remember it happened. */
470 		if (copy_stat(to.p_path, &to_stat) == -1)
471 			dne = 1;
472 		else {
473 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
474 			    to_stat.st_ino == curr->fts_statp->st_ino) {
475 				warnx("%s and %s are identical (not copied).",
476 				    to.p_path, curr->fts_path);
477 				badcp = rval = 1;
478 				if (S_ISDIR(curr->fts_statp->st_mode))
479 					(void)fts_set(ftsp, curr, FTS_SKIP);
480 				continue;
481 			}
482 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
483 			    S_ISDIR(to_stat.st_mode)) {
484 				warnx("cannot overwrite directory %s with "
485 				    "non-directory %s",
486 				    to.p_path, curr->fts_path);
487 				badcp = rval = 1;
488 				continue;
489 			}
490 			dne = 0;
491 		}
492 
493 		switch (curr->fts_statp->st_mode & S_IFMT) {
494 		case S_IFLNK:
495 			/* Catch special case of a non-dangling symlink. */
496 			if ((fts_options & FTS_LOGICAL) ||
497 			    ((fts_options & FTS_COMFOLLOW) &&
498 			    curr->fts_level == 0)) {
499 				if (copy_file(curr, dne))
500 					badcp = rval = 1;
501 			} else {
502 				if (copy_link(curr, !dne))
503 					badcp = rval = 1;
504 			}
505 			break;
506 		case S_IFDIR:
507 			if (!Rflag) {
508 				warnx("%s is a directory (not copied).",
509 				    curr->fts_path);
510 				(void)fts_set(ftsp, curr, FTS_SKIP);
511 				badcp = rval = 1;
512 				break;
513 			}
514 			/*
515 			 * If the directory doesn't exist, create the new
516 			 * one with the from file mode plus owner RWX bits,
517 			 * modified by the umask.  Trade-off between being
518 			 * able to write the directory (if from directory is
519 			 * 555) and not causing a permissions race.  If the
520 			 * umask blocks owner writes, we fail.
521 			 */
522 			if (dne) {
523 				if (mkdir(to.p_path,
524 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
525 					err(1, "%s", to.p_path);
526 				/*
527 				 * First DNE with a NULL root_stat is the root
528 				 * path, so set root_stat.  We can't really
529 				 * tell in all cases if the target path is
530 				 * within the src path, so we just stat() the
531 				 * first directory we created and use that.
532 				 */
533 				if (root_stat == NULL &&
534 				    stat(to.p_path, &created_root_stat) == -1) {
535 					err(1, "stat");
536 				} else if (root_stat == NULL) {
537 					root_stat = &created_root_stat;
538 				}
539 			} else if (!S_ISDIR(to_stat.st_mode)) {
540 				errno = ENOTDIR;
541 				err(1, "%s", to.p_path);
542 			}
543 			/*
544 			 * Arrange to correct directory attributes later
545 			 * (in the post-order phase) if this is a new
546 			 * directory, or if the -p flag is in effect.
547 			 */
548 			curr->fts_number = pflag || dne;
549 			break;
550 		case S_IFBLK:
551 		case S_IFCHR:
552 			if (Rflag && !sflag) {
553 				if (copy_special(curr->fts_statp, !dne))
554 					badcp = rval = 1;
555 			} else {
556 				if (copy_file(curr, dne))
557 					badcp = rval = 1;
558 			}
559 			break;
560 		case S_IFSOCK:
561 			warnx("%s is a socket (not copied).",
562 			    curr->fts_path);
563 			break;
564 		case S_IFIFO:
565 			if (Rflag && !sflag) {
566 				if (copy_fifo(curr->fts_statp, !dne))
567 					badcp = rval = 1;
568 			} else {
569 				if (copy_file(curr, dne))
570 					badcp = rval = 1;
571 			}
572 			break;
573 		default:
574 			if (copy_file(curr, dne))
575 				badcp = rval = 1;
576 			break;
577 		}
578 		if (vflag && !badcp)
579 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
580 	}
581 	if (errno)
582 		err(1, "fts_read");
583 	fts_close(ftsp);
584 	free(recurse_path);
585 	return (rval);
586 }
587 
588 static void
589 siginfo(int sig __unused)
590 {
591 
592 	info = 1;
593 }
594