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