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