xref: /freebsd/bin/cp/cp.c (revision 8bd5e2f15cc9756e7d6b7feb43ec47f18a38e2bf)
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 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 Hflag, Lflag, ch, fts_options, r, have_trailing_slash;
104 	char *target;
105 
106 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
107 	Hflag = Lflag = 0;
108 	while ((ch = getopt(argc, argv, "HLPRafilnprsvx")) != -1)
109 		switch (ch) {
110 		case 'H':
111 			Hflag = 1;
112 			Lflag = 0;
113 			break;
114 		case 'L':
115 			Lflag = 1;
116 			Hflag = 0;
117 			break;
118 		case 'P':
119 			Hflag = Lflag = 0;
120 			break;
121 		case 'R':
122 			Rflag = 1;
123 			break;
124 		case 'a':
125 			pflag = 1;
126 			Rflag = 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 = 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 {
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 static int
275 copy(char *argv[], enum op type, int fts_options, struct stat *root_stat)
276 {
277 	struct stat created_root_stat, to_stat;
278 	FTS *ftsp;
279 	FTSENT *curr;
280 	int base = 0, dne, badcp, rval;
281 	size_t nlen;
282 	char *p, *recurse_path, *target_mid;
283 	mode_t mask, mode;
284 
285 	/*
286 	 * Keep an inverted copy of the umask, for use in correcting
287 	 * permissions on created directories when not using -p.
288 	 */
289 	mask = ~umask(0777);
290 	umask(~mask);
291 
292 	recurse_path = NULL;
293 	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
294 		err(1, "fts_open");
295 	for (badcp = rval = 0; errno = 0, (curr = fts_read(ftsp)) != NULL;
296             badcp = 0) {
297 		switch (curr->fts_info) {
298 		case FTS_NS:
299 		case FTS_DNR:
300 		case FTS_ERR:
301 			warnx("%s: %s",
302 			    curr->fts_path, strerror(curr->fts_errno));
303 			badcp = rval = 1;
304 			continue;
305 		case FTS_DC:			/* Warn, continue. */
306 			warnx("%s: directory causes a cycle", curr->fts_path);
307 			badcp = rval = 1;
308 			continue;
309 		default:
310 			;
311 		}
312 
313 		if (curr->fts_info == FTS_D && type != FILE_TO_FILE &&
314 		    root_stat != NULL &&
315 		    root_stat->st_dev == curr->fts_statp->st_dev &&
316 		    root_stat->st_ino == curr->fts_statp->st_ino) {
317 			assert(recurse_path == NULL);
318 			if (curr->fts_level > FTS_ROOTLEVEL) {
319 				/*
320 				 * If the recursion isn't at the immediate
321 				 * level, we can just not traverse into this
322 				 * directory.
323 				 */
324 				fts_set(ftsp, curr, FTS_SKIP);
325 				continue;
326 			} else {
327 				const char *slash;
328 
329 				/*
330 				 * Grab the last path component and double it,
331 				 * to make life easier later and ensure that
332 				 * we work even with fts_level == 0 is a couple
333 				 * of components deep in fts_path.  No path
334 				 * separators are fine and expected in the
335 				 * common case, though.
336 				 */
337 				slash = strrchr(curr->fts_path, '/');
338 				if (slash != NULL)
339 					slash++;
340 				else
341 					slash = curr->fts_path;
342 				if (asprintf(&recurse_path, "%s/%s",
343 				    curr->fts_path, slash) == -1)
344 					err(1, "asprintf");
345 			}
346 		}
347 
348 		if (recurse_path != NULL &&
349 		    strcmp(curr->fts_path, recurse_path) == 0) {
350 			fts_set(ftsp, curr, FTS_SKIP);
351 			continue;
352 		}
353 
354 		/*
355 		 * If we are in case (2) or (3) above, we need to append the
356 		 * source name to the target name.
357 		 */
358 		if (type != FILE_TO_FILE) {
359 			/*
360 			 * Need to remember the roots of traversals to create
361 			 * correct pathnames.  If there's a directory being
362 			 * copied to a non-existent directory, e.g.
363 			 *	cp -R a/dir noexist
364 			 * the resulting path name should be noexist/foo, not
365 			 * noexist/dir/foo (where foo is a file in dir), which
366 			 * is the case where the target exists.
367 			 *
368 			 * Also, check for "..".  This is for correct path
369 			 * concatenation for paths ending in "..", e.g.
370 			 *	cp -R .. /tmp
371 			 * Paths ending in ".." are changed to ".".  This is
372 			 * tricky, but seems the easiest way to fix the problem.
373 			 *
374 			 * XXX
375 			 * Since the first level MUST be FTS_ROOTLEVEL, base
376 			 * is always initialized.
377 			 */
378 			if (curr->fts_level == FTS_ROOTLEVEL) {
379 				if (type != DIR_TO_DNE) {
380 					p = strrchr(curr->fts_path, '/');
381 					base = (p == NULL) ? 0 :
382 					    (int)(p - curr->fts_path + 1);
383 
384 					if (!strcmp(&curr->fts_path[base],
385 					    ".."))
386 						base += 1;
387 				} else
388 					base = curr->fts_pathlen;
389 			}
390 
391 			p = &curr->fts_path[base];
392 			nlen = curr->fts_pathlen - base;
393 			target_mid = to.target_end;
394 			if (*p != '/' && target_mid[-1] != '/')
395 				*target_mid++ = '/';
396 			*target_mid = 0;
397 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
398 				warnx("%s%s: name too long (not copied)",
399 				    to.p_path, p);
400 				badcp = rval = 1;
401 				continue;
402 			}
403 			(void)strncat(target_mid, p, nlen);
404 			to.p_end = target_mid + nlen;
405 			*to.p_end = 0;
406 			STRIP_TRAILING_SLASH(to);
407 		}
408 
409 		if (curr->fts_info == FTS_DP) {
410 			/*
411 			 * We are nearly finished with this directory.  If we
412 			 * didn't actually copy it, or otherwise don't need to
413 			 * change its attributes, then we are done.
414 			 */
415 			if (!curr->fts_number)
416 				continue;
417 			/*
418 			 * If -p is in effect, set all the attributes.
419 			 * Otherwise, set the correct permissions, limited
420 			 * by the umask.  Optimise by avoiding a chmod()
421 			 * if possible (which is usually the case if we
422 			 * made the directory).  Note that mkdir() does not
423 			 * honour setuid, setgid and sticky bits, but we
424 			 * normally want to preserve them on directories.
425 			 */
426 			if (pflag) {
427 				if (setfile(curr->fts_statp, -1))
428 					rval = 1;
429 				if (preserve_dir_acls(curr->fts_statp,
430 				    curr->fts_accpath, to.p_path) != 0)
431 					rval = 1;
432 			} else {
433 				mode = curr->fts_statp->st_mode;
434 				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
435 				    ((mode | S_IRWXU) & mask) != (mode & mask))
436 					if (chmod(to.p_path, mode & mask) !=
437 					    0) {
438 						warn("chmod: %s", to.p_path);
439 						rval = 1;
440 					}
441 			}
442 			continue;
443 		}
444 
445 		/* Not an error but need to remember it happened. */
446 		if (stat(to.p_path, &to_stat) == -1)
447 			dne = 1;
448 		else {
449 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
450 			    to_stat.st_ino == curr->fts_statp->st_ino) {
451 				warnx("%s and %s are identical (not copied).",
452 				    to.p_path, curr->fts_path);
453 				badcp = rval = 1;
454 				if (S_ISDIR(curr->fts_statp->st_mode))
455 					(void)fts_set(ftsp, curr, FTS_SKIP);
456 				continue;
457 			}
458 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
459 			    S_ISDIR(to_stat.st_mode)) {
460 				warnx("cannot overwrite directory %s with "
461 				    "non-directory %s",
462 				    to.p_path, curr->fts_path);
463 				badcp = rval = 1;
464 				continue;
465 			}
466 			dne = 0;
467 		}
468 
469 		switch (curr->fts_statp->st_mode & S_IFMT) {
470 		case S_IFLNK:
471 			/* Catch special case of a non-dangling symlink. */
472 			if ((fts_options & FTS_LOGICAL) ||
473 			    ((fts_options & FTS_COMFOLLOW) &&
474 			    curr->fts_level == 0)) {
475 				if (copy_file(curr, dne))
476 					badcp = rval = 1;
477 			} else {
478 				if (copy_link(curr, !dne))
479 					badcp = rval = 1;
480 			}
481 			break;
482 		case S_IFDIR:
483 			if (!Rflag) {
484 				warnx("%s is a directory (not copied).",
485 				    curr->fts_path);
486 				(void)fts_set(ftsp, curr, FTS_SKIP);
487 				badcp = rval = 1;
488 				break;
489 			}
490 			/*
491 			 * If the directory doesn't exist, create the new
492 			 * one with the from file mode plus owner RWX bits,
493 			 * modified by the umask.  Trade-off between being
494 			 * able to write the directory (if from directory is
495 			 * 555) and not causing a permissions race.  If the
496 			 * umask blocks owner writes, we fail.
497 			 */
498 			if (dne) {
499 				if (mkdir(to.p_path,
500 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
501 					err(1, "%s", to.p_path);
502 				/*
503 				 * First DNE with a NULL root_stat is the root
504 				 * path, so set root_stat.  We can't really
505 				 * tell in all cases if the target path is
506 				 * within the src path, so we just stat() the
507 				 * first directory we created and use that.
508 				 */
509 				if (root_stat == NULL &&
510 				    stat(to.p_path, &created_root_stat) == -1) {
511 					err(1, "stat");
512 				} else if (root_stat == NULL) {
513 					root_stat = &created_root_stat;
514 				}
515 			} else if (!S_ISDIR(to_stat.st_mode)) {
516 				errno = ENOTDIR;
517 				err(1, "%s", to.p_path);
518 			}
519 			/*
520 			 * Arrange to correct directory attributes later
521 			 * (in the post-order phase) if this is a new
522 			 * directory, or if the -p flag is in effect.
523 			 */
524 			curr->fts_number = pflag || dne;
525 			break;
526 		case S_IFBLK:
527 		case S_IFCHR:
528 			if (Rflag && !sflag) {
529 				if (copy_special(curr->fts_statp, !dne))
530 					badcp = rval = 1;
531 			} else {
532 				if (copy_file(curr, dne))
533 					badcp = rval = 1;
534 			}
535 			break;
536 		case S_IFSOCK:
537 			warnx("%s is a socket (not copied).",
538 			    curr->fts_path);
539 			break;
540 		case S_IFIFO:
541 			if (Rflag && !sflag) {
542 				if (copy_fifo(curr->fts_statp, !dne))
543 					badcp = rval = 1;
544 			} else {
545 				if (copy_file(curr, dne))
546 					badcp = rval = 1;
547 			}
548 			break;
549 		default:
550 			if (copy_file(curr, dne))
551 				badcp = rval = 1;
552 			break;
553 		}
554 		if (vflag && !badcp)
555 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
556 	}
557 	if (errno)
558 		err(1, "fts_read");
559 	fts_close(ftsp);
560 	free(recurse_path);
561 	return (rval);
562 }
563 
564 static void
565 siginfo(int sig __unused)
566 {
567 
568 	info = 1;
569 }
570