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