xref: /freebsd/bin/cp/cp.c (revision bdcbfde31e8e9b343f113a1956384bdf30d1ed62)
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 #endif
43 #include <sys/cdefs.h>
44 /*
45  * Cp copies source files to target files.
46  *
47  * The global PATH_T structure "to" always contains the path to the
48  * current target file.  Since fts(3) does not change directories,
49  * this path can be either absolute or dot-relative.
50  *
51  * The basic algorithm is to initialize "to" and use fts(3) to traverse
52  * the file hierarchy rooted in the argument list.  A trivial case is the
53  * case of 'cp file1 file2'.  The more interesting case is the case of
54  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
55  * path (relative to the root of the traversal) is appended to dir (stored
56  * in "to") to form the final target path.
57  */
58 
59 #include <sys/types.h>
60 #include <sys/stat.h>
61 
62 #include <assert.h>
63 #include <err.h>
64 #include <errno.h>
65 #include <fts.h>
66 #include <limits.h>
67 #include <signal.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <unistd.h>
72 
73 #include "extern.h"
74 
75 #define	STRIP_TRAILING_SLASH(p) {					\
76 	while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
77 	*--(p).p_end = 0;						\
78 }
79 
80 static char emptystring[] = "";
81 
82 PATH_T to = { to.p_path, emptystring, "" };
83 
84 int fflag, iflag, lflag, nflag, pflag, sflag, vflag;
85 static int Hflag, Lflag, Rflag, rflag;
86 volatile sig_atomic_t info;
87 
88 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
89 
90 static int copy(char *[], enum op, int, struct stat *);
91 static void siginfo(int __unused);
92 
93 int
94 main(int argc, char *argv[])
95 {
96 	struct stat to_stat, tmp_stat;
97 	enum op type;
98 	int Pflag, ch, fts_options, r, have_trailing_slash;
99 	char *target;
100 
101 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
102 	Pflag = 0;
103 	while ((ch = getopt(argc, argv, "HLPRafilnprsvx")) != -1)
104 		switch (ch) {
105 		case 'H':
106 			Hflag = 1;
107 			Lflag = Pflag = 0;
108 			break;
109 		case 'L':
110 			Lflag = 1;
111 			Hflag = Pflag = 0;
112 			break;
113 		case 'P':
114 			Pflag = 1;
115 			Hflag = Lflag = 0;
116 			break;
117 		case 'R':
118 			Rflag = 1;
119 			break;
120 		case 'a':
121 			pflag = 1;
122 			Rflag = 1;
123 			Pflag = 1;
124 			Hflag = Lflag = 0;
125 			break;
126 		case 'f':
127 			fflag = 1;
128 			iflag = nflag = 0;
129 			break;
130 		case 'i':
131 			iflag = 1;
132 			fflag = nflag = 0;
133 			break;
134 		case 'l':
135 			lflag = 1;
136 			break;
137 		case 'n':
138 			nflag = 1;
139 			fflag = iflag = 0;
140 			break;
141 		case 'p':
142 			pflag = 1;
143 			break;
144 		case 'r':
145 			rflag = Lflag = 1;
146 			Hflag = Pflag = 0;
147 			break;
148 		case 's':
149 			sflag = 1;
150 			break;
151 		case 'v':
152 			vflag = 1;
153 			break;
154 		case 'x':
155 			fts_options |= FTS_XDEV;
156 			break;
157 		default:
158 			usage();
159 			break;
160 		}
161 	argc -= optind;
162 	argv += optind;
163 
164 	if (argc < 2)
165 		usage();
166 
167 	if (Rflag && rflag)
168 		errx(1, "the -R and -r options may not be specified together");
169 	if (lflag && sflag)
170 		errx(1, "the -l and -s options may not be specified together");
171 	if (rflag)
172 		Rflag = 1;
173 	if (Rflag) {
174 		if (Hflag)
175 			fts_options |= FTS_COMFOLLOW;
176 		if (Lflag) {
177 			fts_options &= ~FTS_PHYSICAL;
178 			fts_options |= FTS_LOGICAL;
179 		}
180 	} else if (!Pflag) {
181 		fts_options &= ~FTS_PHYSICAL;
182 		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
183 	}
184 	(void)signal(SIGINFO, siginfo);
185 
186 	/* Save the target base in "to". */
187 	target = argv[--argc];
188 	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
189 		errx(1, "%s: name too long", target);
190 	to.p_end = to.p_path + strlen(to.p_path);
191 	if (to.p_path == to.p_end) {
192 		*to.p_end++ = '.';
193 		*to.p_end = 0;
194 	}
195 	have_trailing_slash = (to.p_end[-1] == '/');
196 	if (have_trailing_slash)
197 		STRIP_TRAILING_SLASH(to);
198 	to.target_end = to.p_end;
199 
200 	/* Set end of argument list for fts(3). */
201 	argv[argc] = NULL;
202 
203 	/*
204 	 * Cp has two distinct cases:
205 	 *
206 	 * cp [-R] source target
207 	 * cp [-R] source1 ... sourceN directory
208 	 *
209 	 * In both cases, source can be either a file or a directory.
210 	 *
211 	 * In (1), the target becomes a copy of the source. That is, if the
212 	 * source is a file, the target will be a file, and likewise for
213 	 * directories.
214 	 *
215 	 * In (2), the real target is not directory, but "directory/source".
216 	 */
217 	r = stat(to.p_path, &to_stat);
218 	if (r == -1 && errno != ENOENT)
219 		err(1, "%s", to.p_path);
220 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
221 		/*
222 		 * Case (1).  Target is not a directory.
223 		 */
224 		if (argc > 1)
225 			errx(1, "%s is not a directory", to.p_path);
226 
227 		/*
228 		 * Need to detect the case:
229 		 *	cp -R dir foo
230 		 * Where dir is a directory and foo does not exist, where
231 		 * we want pathname concatenations turned on but not for
232 		 * the initial mkdir().
233 		 */
234 		if (r == -1) {
235 			if (Rflag && (Lflag || Hflag))
236 				stat(*argv, &tmp_stat);
237 			else
238 				lstat(*argv, &tmp_stat);
239 
240 			if (S_ISDIR(tmp_stat.st_mode) && Rflag)
241 				type = DIR_TO_DNE;
242 			else
243 				type = FILE_TO_FILE;
244 		} else
245 			type = FILE_TO_FILE;
246 
247 		if (have_trailing_slash && type == FILE_TO_FILE) {
248 			if (r == -1) {
249 				errx(1, "directory %s does not exist",
250 				    to.p_path);
251 			} else
252 				errx(1, "%s is not a directory", to.p_path);
253 		}
254 	} else
255 		/*
256 		 * Case (2).  Target is a directory.
257 		 */
258 		type = FILE_TO_DIR;
259 
260 	/*
261 	 * For DIR_TO_DNE, we could provide copy() with the to_stat we've
262 	 * already allocated on the stack here that isn't being used for
263 	 * anything.  Not doing so, though, simplifies later logic a little bit
264 	 * as we need to skip checking root_stat on the first iteration and
265 	 * ensure that we set it with the first mkdir().
266 	 */
267 	exit (copy(argv, type, fts_options, (type == DIR_TO_DNE ? NULL :
268 	    &to_stat)));
269 }
270 
271 /* Does the right thing based on -R + -H/-L/-P */
272 static int
273 copy_stat(const char *path, struct stat *sb)
274 {
275 
276 	/*
277 	 * For -R -H/-P, we need to lstat() instead; copy() cares about the link
278 	 * itself rather than the target if we're not following links during the
279 	 * traversal.
280 	 */
281 	if (!Rflag || Lflag)
282 		return (stat(path, sb));
283 	return (lstat(path, sb));
284 }
285 
286 
287 static int
288 copy(char *argv[], enum op type, int fts_options, struct stat *root_stat)
289 {
290 	char rootname[NAME_MAX];
291 	struct stat created_root_stat, to_stat;
292 	FTS *ftsp;
293 	FTSENT *curr;
294 	int base = 0, dne, badcp, rval;
295 	size_t nlen;
296 	char *p, *recurse_path, *target_mid;
297 	mode_t mask, mode;
298 
299 	/*
300 	 * Keep an inverted copy of the umask, for use in correcting
301 	 * permissions on created directories when not using -p.
302 	 */
303 	mask = ~umask(0777);
304 	umask(~mask);
305 
306 	recurse_path = NULL;
307 	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
308 		err(1, "fts_open");
309 	for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
310 		switch (curr->fts_info) {
311 		case FTS_NS:
312 		case FTS_DNR:
313 		case FTS_ERR:
314 			warnx("%s: %s",
315 			    curr->fts_path, strerror(curr->fts_errno));
316 			badcp = rval = 1;
317 			continue;
318 		case FTS_DC:			/* Warn, continue. */
319 			warnx("%s: directory causes a cycle", curr->fts_path);
320 			badcp = rval = 1;
321 			continue;
322 		default:
323 			;
324 		}
325 
326 		/*
327 		 * Stash the root basename off for detecting recursion later.
328 		 *
329 		 * This will be essential if the root is a symlink and we're
330 		 * rolling with -L or -H.  The later bits will need this bit in
331 		 * particular.
332 		 */
333 		if (curr->fts_level == FTS_ROOTLEVEL) {
334 			strlcpy(rootname, curr->fts_name, sizeof(rootname));
335 		}
336 
337 		/*
338 		 * If we are in case (2) or (3) above, we need to append the
339 		 * source name to the target name.
340 		 */
341 		if (type != FILE_TO_FILE) {
342 			/*
343 			 * Need to remember the roots of traversals to create
344 			 * correct pathnames.  If there's a directory being
345 			 * copied to a non-existent directory, e.g.
346 			 *	cp -R a/dir noexist
347 			 * the resulting path name should be noexist/foo, not
348 			 * noexist/dir/foo (where foo is a file in dir), which
349 			 * is the case where the target exists.
350 			 *
351 			 * Also, check for "..".  This is for correct path
352 			 * concatenation for paths ending in "..", e.g.
353 			 *	cp -R .. /tmp
354 			 * Paths ending in ".." are changed to ".".  This is
355 			 * tricky, but seems the easiest way to fix the problem.
356 			 *
357 			 * XXX
358 			 * Since the first level MUST be FTS_ROOTLEVEL, base
359 			 * is always initialized.
360 			 */
361 			if (curr->fts_level == FTS_ROOTLEVEL) {
362 				if (type != DIR_TO_DNE) {
363 					p = strrchr(curr->fts_path, '/');
364 					base = (p == NULL) ? 0 :
365 					    (int)(p - curr->fts_path + 1);
366 
367 					if (!strcmp(&curr->fts_path[base],
368 					    ".."))
369 						base += 1;
370 				} else
371 					base = curr->fts_pathlen;
372 			}
373 
374 			p = &curr->fts_path[base];
375 			nlen = curr->fts_pathlen - base;
376 			target_mid = to.target_end;
377 			if (*p != '/' && target_mid[-1] != '/')
378 				*target_mid++ = '/';
379 			*target_mid = 0;
380 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
381 				warnx("%s%s: name too long (not copied)",
382 				    to.p_path, p);
383 				badcp = rval = 1;
384 				continue;
385 			}
386 			(void)strncat(target_mid, p, nlen);
387 			to.p_end = target_mid + nlen;
388 			*to.p_end = 0;
389 			STRIP_TRAILING_SLASH(to);
390 
391 			/*
392 			 * We're on the verge of recursing on ourselves.  Either
393 			 * we need to stop right here (we knowingly just created
394 			 * it), or we will in an immediate descendant.  Record
395 			 * the path of the immediate descendant to make our
396 			 * lives a little less complicated looking.
397 			 */
398 			if (curr->fts_info == FTS_D && root_stat != NULL &&
399 			    root_stat->st_dev == curr->fts_statp->st_dev &&
400 			    root_stat->st_ino == curr->fts_statp->st_ino) {
401 				assert(recurse_path == NULL);
402 
403 				if (root_stat == &created_root_stat) {
404 					/*
405 					 * This directory didn't exist when we
406 					 * started, we created it as part of
407 					 * traversal.  Stop right here before we
408 					 * do something silly.
409 					 */
410 					fts_set(ftsp, curr, FTS_SKIP);
411 					continue;
412 				}
413 
414 
415 				if (asprintf(&recurse_path, "%s/%s", to.p_path,
416 				    rootname) == -1)
417 					err(1, "asprintf");
418 			}
419 
420 			if (recurse_path != NULL &&
421 			    strcmp(to.p_path, recurse_path) == 0) {
422 				fts_set(ftsp, curr, FTS_SKIP);
423 				continue;
424 			}
425 		}
426 
427 		if (curr->fts_info == FTS_DP) {
428 			/*
429 			 * We are nearly finished with this directory.  If we
430 			 * didn't actually copy it, or otherwise don't need to
431 			 * change its attributes, then we are done.
432 			 */
433 			if (!curr->fts_number)
434 				continue;
435 			/*
436 			 * If -p is in effect, set all the attributes.
437 			 * Otherwise, set the correct permissions, limited
438 			 * by the umask.  Optimise by avoiding a chmod()
439 			 * if possible (which is usually the case if we
440 			 * made the directory).  Note that mkdir() does not
441 			 * honour setuid, setgid and sticky bits, but we
442 			 * normally want to preserve them on directories.
443 			 */
444 			if (pflag) {
445 				if (setfile(curr->fts_statp, -1))
446 					rval = 1;
447 				if (preserve_dir_acls(curr->fts_statp,
448 				    curr->fts_accpath, to.p_path) != 0)
449 					rval = 1;
450 			} else {
451 				mode = curr->fts_statp->st_mode;
452 				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
453 				    ((mode | S_IRWXU) & mask) != (mode & mask))
454 					if (chmod(to.p_path, mode & mask) !=
455 					    0) {
456 						warn("chmod: %s", to.p_path);
457 						rval = 1;
458 					}
459 			}
460 			continue;
461 		}
462 
463 		/* Not an error but need to remember it happened. */
464 		if (copy_stat(to.p_path, &to_stat) == -1)
465 			dne = 1;
466 		else {
467 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
468 			    to_stat.st_ino == curr->fts_statp->st_ino) {
469 				warnx("%s and %s are identical (not copied).",
470 				    to.p_path, curr->fts_path);
471 				badcp = rval = 1;
472 				if (S_ISDIR(curr->fts_statp->st_mode))
473 					(void)fts_set(ftsp, curr, FTS_SKIP);
474 				continue;
475 			}
476 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
477 			    S_ISDIR(to_stat.st_mode)) {
478 				warnx("cannot overwrite directory %s with "
479 				    "non-directory %s",
480 				    to.p_path, curr->fts_path);
481 				badcp = rval = 1;
482 				continue;
483 			}
484 			dne = 0;
485 		}
486 
487 		switch (curr->fts_statp->st_mode & S_IFMT) {
488 		case S_IFLNK:
489 			/* Catch special case of a non-dangling symlink. */
490 			if ((fts_options & FTS_LOGICAL) ||
491 			    ((fts_options & FTS_COMFOLLOW) &&
492 			    curr->fts_level == 0)) {
493 				if (copy_file(curr, dne))
494 					badcp = rval = 1;
495 			} else {
496 				if (copy_link(curr, !dne))
497 					badcp = rval = 1;
498 			}
499 			break;
500 		case S_IFDIR:
501 			if (!Rflag) {
502 				warnx("%s is a directory (not copied).",
503 				    curr->fts_path);
504 				(void)fts_set(ftsp, curr, FTS_SKIP);
505 				badcp = rval = 1;
506 				break;
507 			}
508 			/*
509 			 * If the directory doesn't exist, create the new
510 			 * one with the from file mode plus owner RWX bits,
511 			 * modified by the umask.  Trade-off between being
512 			 * able to write the directory (if from directory is
513 			 * 555) and not causing a permissions race.  If the
514 			 * umask blocks owner writes, we fail.
515 			 */
516 			if (dne) {
517 				if (mkdir(to.p_path,
518 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
519 					err(1, "%s", to.p_path);
520 				/*
521 				 * First DNE with a NULL root_stat is the root
522 				 * path, so set root_stat.  We can't really
523 				 * tell in all cases if the target path is
524 				 * within the src path, so we just stat() the
525 				 * first directory we created and use that.
526 				 */
527 				if (root_stat == NULL &&
528 				    stat(to.p_path, &created_root_stat) == -1) {
529 					err(1, "stat");
530 				} else if (root_stat == NULL) {
531 					root_stat = &created_root_stat;
532 				}
533 			} else if (!S_ISDIR(to_stat.st_mode)) {
534 				errno = ENOTDIR;
535 				err(1, "%s", to.p_path);
536 			}
537 			/*
538 			 * Arrange to correct directory attributes later
539 			 * (in the post-order phase) if this is a new
540 			 * directory, or if the -p flag is in effect.
541 			 */
542 			curr->fts_number = pflag || dne;
543 			break;
544 		case S_IFBLK:
545 		case S_IFCHR:
546 			if (Rflag && !sflag) {
547 				if (copy_special(curr->fts_statp, !dne))
548 					badcp = rval = 1;
549 			} else {
550 				if (copy_file(curr, dne))
551 					badcp = rval = 1;
552 			}
553 			break;
554 		case S_IFSOCK:
555 			warnx("%s is a socket (not copied).",
556 			    curr->fts_path);
557 			break;
558 		case S_IFIFO:
559 			if (Rflag && !sflag) {
560 				if (copy_fifo(curr->fts_statp, !dne))
561 					badcp = rval = 1;
562 			} else {
563 				if (copy_file(curr, dne))
564 					badcp = rval = 1;
565 			}
566 			break;
567 		default:
568 			if (copy_file(curr, dne))
569 				badcp = rval = 1;
570 			break;
571 		}
572 		if (vflag && !badcp)
573 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
574 	}
575 	if (errno)
576 		err(1, "fts_read");
577 	fts_close(ftsp);
578 	free(recurse_path);
579 	return (rval);
580 }
581 
582 static void
583 siginfo(int sig __unused)
584 {
585 
586 	info = 1;
587 }
588