xref: /freebsd/bin/cp/cp.c (revision 7bd6fde3951af84ef3b68e4d1eadc1840c2fc1b3)
1 /*-
2  * Copyright (c) 1988, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * David Hitz of Auspex Systems Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #if 0
34 #ifndef lint
35 static char const copyright[] =
36 "@(#) Copyright (c) 1988, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 static char sccsid[] = "@(#)cp.c	8.2 (Berkeley) 4/1/94";
42 #endif /* not lint */
43 #endif
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
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 <err.h>
66 #include <errno.h>
67 #include <fts.h>
68 #include <limits.h>
69 #include <signal.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
74 
75 #include "extern.h"
76 
77 #define	STRIP_TRAILING_SLASH(p) {					\
78         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
79                 *--(p).p_end = 0;					\
80 }
81 
82 static char emptystring[] = "";
83 
84 PATH_T to = { to.p_path, emptystring, "" };
85 
86 int fflag, iflag, lflag, nflag, pflag, vflag;
87 static int Rflag, rflag;
88 volatile sig_atomic_t info;
89 
90 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
91 
92 static int copy(char *[], enum op, int);
93 static int mastercmp(const FTSENT * const *, const FTSENT * const *);
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 Hflag, Lflag, Pflag, ch, fts_options, r, have_trailing_slash;
102 	char *target;
103 
104 	Hflag = Lflag = Pflag = 0;
105 	while ((ch = getopt(argc, argv, "HLPRfilnprv")) != -1)
106 		switch (ch) {
107 		case 'H':
108 			Hflag = 1;
109 			Lflag = Pflag = 0;
110 			break;
111 		case 'L':
112 			Lflag = 1;
113 			Hflag = Pflag = 0;
114 			break;
115 		case 'P':
116 			Pflag = 1;
117 			Hflag = Lflag = 0;
118 			break;
119 		case 'R':
120 			Rflag = 1;
121 			break;
122 		case 'f':
123 			fflag = 1;
124 			iflag = nflag = 0;
125 			break;
126 		case 'i':
127 			iflag = 1;
128 			fflag = nflag = 0;
129 			break;
130 		case 'l':
131 			lflag = 1;
132 			break;
133 		case 'n':
134 			nflag = 1;
135 			fflag = iflag = 0;
136 			break;
137 		case 'p':
138 			pflag = 1;
139 			break;
140 		case 'r':
141 			rflag = Lflag = 1;
142 			Hflag = Pflag = 0;
143 			break;
144 		case 'v':
145 			vflag = 1;
146 			break;
147 		default:
148 			usage();
149 			break;
150 		}
151 	argc -= optind;
152 	argv += optind;
153 
154 	if (argc < 2)
155 		usage();
156 
157 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
158 	if (Rflag && rflag)
159 		errx(1, "the -R and -r options may not be specified together");
160 	if (rflag)
161 		Rflag = 1;
162 	if (Rflag) {
163 		if (Hflag)
164 			fts_options |= FTS_COMFOLLOW;
165 		if (Lflag) {
166 			fts_options &= ~FTS_PHYSICAL;
167 			fts_options |= FTS_LOGICAL;
168 		}
169 	} else {
170 		fts_options &= ~FTS_PHYSICAL;
171 		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
172 	}
173 	(void)signal(SIGINFO, siginfo);
174 
175 	/* Save the target base in "to". */
176 	target = argv[--argc];
177 	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
178 		errx(1, "%s: name too long", target);
179 	to.p_end = to.p_path + strlen(to.p_path);
180         if (to.p_path == to.p_end) {
181 		*to.p_end++ = '.';
182 		*to.p_end = 0;
183 	}
184 	have_trailing_slash = (to.p_end[-1] == '/');
185 	if (have_trailing_slash)
186 		STRIP_TRAILING_SLASH(to);
187 	to.target_end = to.p_end;
188 
189 	/* Set end of argument list for fts(3). */
190 	argv[argc] = NULL;
191 
192 	/*
193 	 * Cp has two distinct cases:
194 	 *
195 	 * cp [-R] source target
196 	 * cp [-R] source1 ... sourceN directory
197 	 *
198 	 * In both cases, source can be either a file or a directory.
199 	 *
200 	 * In (1), the target becomes a copy of the source. That is, if the
201 	 * source is a file, the target will be a file, and likewise for
202 	 * directories.
203 	 *
204 	 * In (2), the real target is not directory, but "directory/source".
205 	 */
206 	r = stat(to.p_path, &to_stat);
207 	if (r == -1 && errno != ENOENT)
208 		err(1, "%s", to.p_path);
209 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
210 		/*
211 		 * Case (1).  Target is not a directory.
212 		 */
213 		if (argc > 1) {
214 			usage();
215 			exit(1);
216 		}
217 		/*
218 		 * Need to detect the case:
219 		 *	cp -R dir foo
220 		 * Where dir is a directory and foo does not exist, where
221 		 * we want pathname concatenations turned on but not for
222 		 * the initial mkdir().
223 		 */
224 		if (r == -1) {
225 			if (Rflag && (Lflag || Hflag))
226 				stat(*argv, &tmp_stat);
227 			else
228 				lstat(*argv, &tmp_stat);
229 
230 			if (S_ISDIR(tmp_stat.st_mode) && Rflag)
231 				type = DIR_TO_DNE;
232 			else
233 				type = FILE_TO_FILE;
234 		} else
235 			type = FILE_TO_FILE;
236 
237 		if (have_trailing_slash && type == FILE_TO_FILE) {
238 			if (r == -1)
239 				errx(1, "directory %s does not exist",
240 				     to.p_path);
241 			else
242 				errx(1, "%s is not a directory", to.p_path);
243 		}
244 	} else
245 		/*
246 		 * Case (2).  Target is a directory.
247 		 */
248 		type = FILE_TO_DIR;
249 
250 	exit (copy(argv, type, fts_options));
251 }
252 
253 static int
254 copy(char *argv[], enum op type, int fts_options)
255 {
256 	struct stat to_stat;
257 	FTS *ftsp;
258 	FTSENT *curr;
259 	int base = 0, dne, badcp, rval;
260 	size_t nlen;
261 	char *p, *target_mid;
262 	mode_t mask, mode;
263 
264 	/*
265 	 * Keep an inverted copy of the umask, for use in correcting
266 	 * permissions on created directories when not using -p.
267 	 */
268 	mask = ~umask(0777);
269 	umask(~mask);
270 
271 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
272 		err(1, "fts_open");
273 	for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
274 		switch (curr->fts_info) {
275 		case FTS_NS:
276 		case FTS_DNR:
277 		case FTS_ERR:
278 			warnx("%s: %s",
279 			    curr->fts_path, strerror(curr->fts_errno));
280 			badcp = rval = 1;
281 			continue;
282 		case FTS_DC:			/* Warn, continue. */
283 			warnx("%s: directory causes a cycle", curr->fts_path);
284 			badcp = rval = 1;
285 			continue;
286 		default:
287 			;
288 		}
289 
290 		/*
291 		 * If we are in case (2) or (3) above, we need to append the
292                  * source name to the target name.
293                  */
294 		if (type != FILE_TO_FILE) {
295 			/*
296 			 * Need to remember the roots of traversals to create
297 			 * correct pathnames.  If there's a directory being
298 			 * copied to a non-existent directory, e.g.
299 			 *	cp -R a/dir noexist
300 			 * the resulting path name should be noexist/foo, not
301 			 * noexist/dir/foo (where foo is a file in dir), which
302 			 * is the case where the target exists.
303 			 *
304 			 * Also, check for "..".  This is for correct path
305 			 * concatenation for paths ending in "..", e.g.
306 			 *	cp -R .. /tmp
307 			 * Paths ending in ".." are changed to ".".  This is
308 			 * tricky, but seems the easiest way to fix the problem.
309 			 *
310 			 * XXX
311 			 * Since the first level MUST be FTS_ROOTLEVEL, base
312 			 * is always initialized.
313 			 */
314 			if (curr->fts_level == FTS_ROOTLEVEL) {
315 				if (type != DIR_TO_DNE) {
316 					p = strrchr(curr->fts_path, '/');
317 					base = (p == NULL) ? 0 :
318 					    (int)(p - curr->fts_path + 1);
319 
320 					if (!strcmp(&curr->fts_path[base],
321 					    ".."))
322 						base += 1;
323 				} else
324 					base = curr->fts_pathlen;
325 			}
326 
327 			p = &curr->fts_path[base];
328 			nlen = curr->fts_pathlen - base;
329 			target_mid = to.target_end;
330 			if (*p != '/' && target_mid[-1] != '/')
331 				*target_mid++ = '/';
332 			*target_mid = 0;
333 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
334 				warnx("%s%s: name too long (not copied)",
335 				    to.p_path, p);
336 				badcp = rval = 1;
337 				continue;
338 			}
339 			(void)strncat(target_mid, p, nlen);
340 			to.p_end = target_mid + nlen;
341 			*to.p_end = 0;
342 			STRIP_TRAILING_SLASH(to);
343 		}
344 
345 		if (curr->fts_info == FTS_DP) {
346 			/*
347 			 * We are nearly finished with this directory.  If we
348 			 * didn't actually copy it, or otherwise don't need to
349 			 * change its attributes, then we are done.
350 			 */
351 			if (!curr->fts_number)
352 				continue;
353 			/*
354 			 * If -p is in effect, set all the attributes.
355 			 * Otherwise, set the correct permissions, limited
356 			 * by the umask.  Optimise by avoiding a chmod()
357 			 * if possible (which is usually the case if we
358 			 * made the directory).  Note that mkdir() does not
359 			 * honour setuid, setgid and sticky bits, but we
360 			 * normally want to preserve them on directories.
361 			 */
362 			if (pflag) {
363 				if (setfile(curr->fts_statp, -1))
364 					rval = 1;
365 				if (preserve_dir_acls(curr->fts_statp,
366 				    curr->fts_accpath, to.p_path) != 0)
367 					rval = 1;
368 			} else {
369 				mode = curr->fts_statp->st_mode;
370 				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
371 				    ((mode | S_IRWXU) & mask) != (mode & mask))
372 					if (chmod(to.p_path, mode & mask) != 0){
373 						warn("chmod: %s", to.p_path);
374 						rval = 1;
375 					}
376 			}
377 			continue;
378 		}
379 
380 		/* Not an error but need to remember it happened */
381 		if (stat(to.p_path, &to_stat) == -1)
382 			dne = 1;
383 		else {
384 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
385 			    to_stat.st_ino == curr->fts_statp->st_ino) {
386 				warnx("%s and %s are identical (not copied).",
387 				    to.p_path, curr->fts_path);
388 				badcp = rval = 1;
389 				if (S_ISDIR(curr->fts_statp->st_mode))
390 					(void)fts_set(ftsp, curr, FTS_SKIP);
391 				continue;
392 			}
393 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
394 			    S_ISDIR(to_stat.st_mode)) {
395 				warnx("cannot overwrite directory %s with "
396 				    "non-directory %s",
397 				    to.p_path, curr->fts_path);
398 				badcp = rval = 1;
399 				continue;
400 			}
401 			dne = 0;
402 		}
403 
404 		switch (curr->fts_statp->st_mode & S_IFMT) {
405 		case S_IFLNK:
406 			/* Catch special case of a non-dangling symlink */
407 			if ((fts_options & FTS_LOGICAL) ||
408 			    ((fts_options & FTS_COMFOLLOW) &&
409 			    curr->fts_level == 0)) {
410 				if (copy_file(curr, dne))
411 					badcp = rval = 1;
412 			} else {
413 				if (copy_link(curr, !dne))
414 					badcp = rval = 1;
415 			}
416 			break;
417 		case S_IFDIR:
418 			if (!Rflag) {
419 				warnx("%s is a directory (not copied).",
420 				    curr->fts_path);
421 				(void)fts_set(ftsp, curr, FTS_SKIP);
422 				badcp = rval = 1;
423 				break;
424 			}
425 			/*
426 			 * If the directory doesn't exist, create the new
427 			 * one with the from file mode plus owner RWX bits,
428 			 * modified by the umask.  Trade-off between being
429 			 * able to write the directory (if from directory is
430 			 * 555) and not causing a permissions race.  If the
431 			 * umask blocks owner writes, we fail..
432 			 */
433 			if (dne) {
434 				if (mkdir(to.p_path,
435 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
436 					err(1, "%s", to.p_path);
437 			} else if (!S_ISDIR(to_stat.st_mode)) {
438 				errno = ENOTDIR;
439 				err(1, "%s", to.p_path);
440 			}
441 			/*
442 			 * Arrange to correct directory attributes later
443 			 * (in the post-order phase) if this is a new
444 			 * directory, or if the -p flag is in effect.
445 			 */
446 			curr->fts_number = pflag || dne;
447 			break;
448 		case S_IFBLK:
449 		case S_IFCHR:
450 			if (Rflag) {
451 				if (copy_special(curr->fts_statp, !dne))
452 					badcp = rval = 1;
453 			} else {
454 				if (copy_file(curr, dne))
455 					badcp = rval = 1;
456 			}
457 			break;
458 		case S_IFSOCK:
459 			warnx("%s is a socket (not copied).",
460 				    curr->fts_path);
461 		case S_IFIFO:
462 			if (Rflag) {
463 				if (copy_fifo(curr->fts_statp, !dne))
464 					badcp = rval = 1;
465 			} else {
466 				if (copy_file(curr, dne))
467 					badcp = rval = 1;
468 			}
469 			break;
470 		default:
471 			if (copy_file(curr, dne))
472 				badcp = rval = 1;
473 			break;
474 		}
475 		if (vflag && !badcp)
476 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
477 	}
478 	if (errno)
479 		err(1, "fts_read");
480 	fts_close(ftsp);
481 	return (rval);
482 }
483 
484 /*
485  * mastercmp --
486  *	The comparison function for the copy order.  The order is to copy
487  *	non-directory files before directory files.  The reason for this
488  *	is because files tend to be in the same cylinder group as their
489  *	parent directory, whereas directories tend not to be.  Copying the
490  *	files first reduces seeking.
491  */
492 static int
493 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
494 {
495 	int a_info, b_info;
496 
497 	a_info = (*a)->fts_info;
498 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
499 		return (0);
500 	b_info = (*b)->fts_info;
501 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
502 		return (0);
503 	if (a_info == FTS_D)
504 		return (-1);
505 	if (b_info == FTS_D)
506 		return (1);
507 	return (0);
508 }
509 
510 static void
511 siginfo(int sig __unused)
512 {
513 
514 	info = 1;
515 }
516