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