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