xref: /netbsd-src/bin/cp/cp.c (revision 2d48ac808c43ea6701ba8f33cfc3645685301f79)
1 /* $NetBSD: cp.c,v 1.51 2008/07/20 00:52:39 lukem Exp $ */
2 
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 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT(
38 "@(#) Copyright (c) 1988, 1993, 1994\
39  The Regents of the University of California.  All rights reserved.");
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)cp.c	8.5 (Berkeley) 4/29/95";
45 #else
46 __RCSID("$NetBSD: cp.c,v 1.51 2008/07/20 00:52:39 lukem Exp $");
47 #endif
48 #endif /* not lint */
49 
50 /*
51  * Cp copies source files to target files.
52  *
53  * The global PATH_T structure "to" always contains the path to the
54  * current target file.  Since fts(3) does not change directories,
55  * this path can be either absolute or dot-relative.
56  *
57  * The basic algorithm is to initialize "to" and use fts(3) to traverse
58  * the file hierarchy rooted in the argument list.  A trivial case is the
59  * case of 'cp file1 file2'.  The more interesting case is the case of
60  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
61  * path (relative to the root of the traversal) is appended to dir (stored
62  * in "to") to form the final target path.
63  */
64 
65 #include <sys/param.h>
66 #include <sys/stat.h>
67 
68 #include <err.h>
69 #include <errno.h>
70 #include <fts.h>
71 #include <locale.h>
72 #include <stdlib.h>
73 #include <stdio.h>
74 #include <string.h>
75 #include <unistd.h>
76 
77 #include "extern.h"
78 
79 #define	STRIP_TRAILING_SLASH(p) {					\
80         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
81                 *--(p).p_end = '\0';					\
82 }
83 
84 static char empty[] = "";
85 PATH_T to = { .p_end = to.p_path, .target_end = empty  };
86 
87 uid_t myuid;
88 int Hflag, Lflag, Rflag, Pflag, fflag, iflag, pflag, rflag, vflag, Nflag;
89 mode_t myumask;
90 
91 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
92 
93 int 	main(int, char *[]);
94 int 	copy(char *[], enum op, int);
95 int 	mastercmp(const FTSENT **, const FTSENT **);
96 
97 int
98 main(int argc, char *argv[])
99 {
100 	struct stat to_stat, tmp_stat;
101 	enum op type;
102 	int ch, fts_options, r, have_trailing_slash;
103 	char *target, **src;
104 
105 	setprogname(argv[0]);
106 	(void)setlocale(LC_ALL, "");
107 
108 	Hflag = Lflag = Pflag = Rflag = 0;
109 	while ((ch = getopt(argc, argv, "HLNPRfiprv")) != -1)
110 		switch (ch) {
111 		case 'H':
112 			Hflag = 1;
113 			Lflag = Pflag = 0;
114 			break;
115 		case 'L':
116 			Lflag = 1;
117 			Hflag = Pflag = 0;
118 			break;
119 		case 'N':
120 			Nflag = 1;
121 			break;
122 		case 'P':
123 			Pflag = 1;
124 			Hflag = Lflag = 0;
125 			break;
126 		case 'R':
127 			Rflag = 1;
128 			break;
129 		case 'f':
130 			fflag = 1;
131 			iflag = 0;
132 			break;
133 		case 'i':
134 			iflag = isatty(fileno(stdin));
135 			fflag = 0;
136 			break;
137 		case 'p':
138 			pflag = 1;
139 			break;
140 		case 'r':
141 			rflag = 1;
142 			break;
143 		case 'v':
144 			vflag = 1;
145 			break;
146 		case '?':
147 		default:
148 			usage();
149 			/* NOTREACHED */
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) {
159 		if (Rflag) {
160 			errx(EXIT_FAILURE,
161 		    "the -R and -r options may not be specified together.");
162 			/* NOTREACHED */
163 		}
164 		if (Hflag || Lflag || Pflag) {
165 			errx(EXIT_FAILURE,
166 	"the -H, -L, and -P options may not be specified with the -r option.");
167 			/* NOTREACHED */
168 		}
169 		fts_options &= ~FTS_PHYSICAL;
170 		fts_options |= FTS_LOGICAL;
171 	}
172 
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 if (!Pflag) {
181 		fts_options &= ~FTS_PHYSICAL;
182 		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
183 	}
184 
185 	myuid = getuid();
186 
187 	/* Copy the umask for explicit mode setting. */
188 	myumask = umask(0);
189 	(void)umask(myumask);
190 
191 	/* Save the target base in "to". */
192 	target = argv[--argc];
193 	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
194 		errx(EXIT_FAILURE, "%s: name too long", target);
195 	to.p_end = to.p_path + strlen(to.p_path);
196 	have_trailing_slash = (to.p_end[-1] == '/');
197 	if (have_trailing_slash)
198 		STRIP_TRAILING_SLASH(to);
199 	to.target_end = to.p_end;
200 
201 	/* Set end of argument list for fts(3). */
202 	argv[argc] = NULL;
203 
204 	/*
205 	 * Cp has two distinct cases:
206 	 *
207 	 * cp [-R] source target
208 	 * cp [-R] source1 ... sourceN directory
209 	 *
210 	 * In both cases, source can be either a file or a directory.
211 	 *
212 	 * In (1), the target becomes a copy of the source. That is, if the
213 	 * source is a file, the target will be a file, and likewise for
214 	 * directories.
215 	 *
216 	 * In (2), the real target is not directory, but "directory/source".
217 	 */
218 	if (Pflag)
219 		r = lstat(to.p_path, &to_stat);
220 	else
221 		r = stat(to.p_path, &to_stat);
222 	if (r == -1 && errno != ENOENT) {
223 		err(EXIT_FAILURE, "%s", to.p_path);
224 		/* NOTREACHED */
225 	}
226 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
227 		/*
228 		 * Case (1).  Target is not a directory.
229 		 */
230 		if (argc > 1)
231 			usage();
232 		/*
233 		 * Need to detect the case:
234 		 *	cp -R dir foo
235 		 * Where dir is a directory and foo does not exist, where
236 		 * we want pathname concatenations turned on but not for
237 		 * the initial mkdir().
238 		 */
239 		if (r == -1) {
240 			if (rflag || (Rflag && (Lflag || Hflag)))
241 				r = stat(*argv, &tmp_stat);
242 			else
243 				r = lstat(*argv, &tmp_stat);
244 			if (r == -1) {
245 				err(EXIT_FAILURE, "%s", *argv);
246 				/* NOTREACHED */
247 			}
248 
249 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
250 				type = DIR_TO_DNE;
251 			else
252 				type = FILE_TO_FILE;
253 		} else
254 			type = FILE_TO_FILE;
255 
256 		if (have_trailing_slash && type == FILE_TO_FILE) {
257 			if (r == -1)
258 				errx(1, "directory %s does not exist",
259 				     to.p_path);
260 			else
261 				errx(1, "%s is not a directory", to.p_path);
262 		}
263 	} else {
264 		/*
265 		 * Case (2).  Target is a directory.
266 		 */
267 		type = FILE_TO_DIR;
268 	}
269 
270 	/*
271 	 * make "cp -rp src/ dst" behave like "cp -rp src dst" not
272 	 * like "cp -rp src/. dst"
273 	 */
274 	for (src = argv; *src; src++) {
275 		size_t len = strlen(*src);
276 		while (len-- > 1 && (*src)[len] == '/')
277 			(*src)[len] = '\0';
278 	}
279 
280 	exit(copy(argv, type, fts_options));
281 	/* NOTREACHED */
282 }
283 
284 int
285 copy(char *argv[], enum op type, int fts_options)
286 {
287 	struct stat to_stat;
288 	FTS *ftsp;
289 	FTSENT *curr;
290 	int base, dne, sval;
291 	int this_failed, any_failed;
292 	size_t nlen;
293 	char *p, *target_mid;
294 
295 	dne = 0;
296 	base = 0;	/* XXX gcc -Wuninitialized (see comment below) */
297 
298 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
299 		err(EXIT_FAILURE, "%s", argv[0]);
300 		/* NOTREACHED */
301 	for (any_failed = 0; (curr = fts_read(ftsp)) != NULL;) {
302 		this_failed = 0;
303 		switch (curr->fts_info) {
304 		case FTS_NS:
305 		case FTS_DNR:
306 		case FTS_ERR:
307 			warnx("%s: %s", curr->fts_path,
308 					strerror(curr->fts_errno));
309 			this_failed = any_failed = 1;
310 			continue;
311 		case FTS_DC:			/* Warn, continue. */
312 			warnx("%s: directory causes a cycle", curr->fts_path);
313 			this_failed = any_failed = 1;
314 			continue;
315 		}
316 
317 		/*
318 		 * If we are in case (2) or (3) above, we need to append the
319                  * source name to the target name.
320                  */
321 		if (type != FILE_TO_FILE) {
322 			if ((curr->fts_namelen +
323 			    to.target_end - to.p_path + 1) > MAXPATHLEN) {
324 				warnx("%s/%s: name too long (not copied)",
325 						to.p_path, curr->fts_name);
326 				this_failed = any_failed = 1;
327 				continue;
328 			}
329 
330 			/*
331 			 * Need to remember the roots of traversals to create
332 			 * correct pathnames.  If there's a directory being
333 			 * copied to a non-existent directory, e.g.
334 			 *	cp -R a/dir noexist
335 			 * the resulting path name should be noexist/foo, not
336 			 * noexist/dir/foo (where foo is a file in dir), which
337 			 * is the case where the target exists.
338 			 *
339 			 * Also, check for "..".  This is for correct path
340 			 * concatentation for paths ending in "..", e.g.
341 			 *	cp -R .. /tmp
342 			 * Paths ending in ".." are changed to ".".  This is
343 			 * tricky, but seems the easiest way to fix the problem.
344 			 *
345 			 * XXX
346 			 * Since the first level MUST be FTS_ROOTLEVEL, base
347 			 * is always initialized.
348 			 */
349 			if (curr->fts_level == FTS_ROOTLEVEL) {
350 				if (type != DIR_TO_DNE) {
351 					p = strrchr(curr->fts_path, '/');
352 					base = (p == NULL) ? 0 :
353 					    (int)(p - curr->fts_path + 1);
354 
355 					if (!strcmp(&curr->fts_path[base],
356 					    ".."))
357 						base += 1;
358 				} else
359 					base = curr->fts_pathlen;
360 			}
361 
362 			p = &curr->fts_path[base];
363 			nlen = curr->fts_pathlen - base;
364 			target_mid = to.target_end;
365 			if (*p != '/' && target_mid[-1] != '/')
366 				*target_mid++ = '/';
367 			*target_mid = 0;
368 
369 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
370 				warnx("%s%s: name too long (not copied)",
371 				    to.p_path, p);
372 				this_failed = any_failed = 1;
373 				continue;
374 			}
375 			(void)strncat(target_mid, p, nlen);
376 			to.p_end = target_mid + nlen;
377 			*to.p_end = 0;
378 			STRIP_TRAILING_SLASH(to);
379 		}
380 
381 		sval = Pflag ? lstat(to.p_path, &to_stat) : stat(to.p_path, &to_stat);
382 		/* Not an error but need to remember it happened */
383 		if (sval == -1)
384 			dne = 1;
385 		else {
386 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
387 			    to_stat.st_ino == curr->fts_statp->st_ino) {
388 				warnx("%s and %s are identical (not copied).",
389 				    to.p_path, curr->fts_path);
390 				this_failed = any_failed = 1;
391 				if (S_ISDIR(curr->fts_statp->st_mode))
392 					(void)fts_set(ftsp, curr, FTS_SKIP);
393 				continue;
394 			}
395 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
396 			    S_ISDIR(to_stat.st_mode)) {
397 		warnx("cannot overwrite directory %s with non-directory %s",
398 				    to.p_path, curr->fts_path);
399 				this_failed = any_failed = 1;
400 				continue;
401 			}
402 			if (!S_ISDIR(curr->fts_statp->st_mode))
403 				dne = 0;
404 		}
405 
406 		switch (curr->fts_statp->st_mode & S_IFMT) {
407 		case S_IFLNK:
408 			/* Catch special case of a non dangling symlink */
409 			if((fts_options & FTS_LOGICAL) ||
410 			   ((fts_options & FTS_COMFOLLOW) && curr->fts_level == 0)) {
411 				if (copy_file(curr, dne))
412 					this_failed = any_failed = 1;
413 			} else {
414 				if (copy_link(curr, !dne))
415 					this_failed = any_failed = 1;
416 			}
417 			break;
418 		case S_IFDIR:
419 			if (!Rflag && !rflag) {
420 				if (curr->fts_info == FTS_D)
421 					warnx("%s is a directory (not copied).",
422 					    curr->fts_path);
423 				(void)fts_set(ftsp, curr, FTS_SKIP);
424 				this_failed = any_failed = 1;
425 				break;
426 			}
427 
428                         /*
429                          * Directories get noticed twice:
430                          *  In the first pass, create it if needed.
431                          *  In the second pass, after the children have been copied, set the permissions.
432                          */
433 			if (curr->fts_info == FTS_D) /* First pass */
434 			{
435 				/*
436 				 * If the directory doesn't exist, create the new
437 				 * one with the from file mode plus owner RWX bits,
438 				 * modified by the umask.  Trade-off between being
439 				 * able to write the directory (if from directory is
440 				 * 555) and not causing a permissions race.  If the
441 				 * umask blocks owner writes, we fail..
442 				 */
443 				if (dne) {
444 					if (mkdir(to.p_path,
445 					    curr->fts_statp->st_mode | S_IRWXU) < 0)
446 						err(EXIT_FAILURE, "%s",
447 						    to.p_path);
448 						/* NOTREACHED */
449 				} else if (!S_ISDIR(to_stat.st_mode)) {
450 					errno = ENOTDIR;
451 					err(EXIT_FAILURE, "%s",
452 						to.p_path);
453 					/* NOTREACHED */
454 				}
455 			}
456 			else if (curr->fts_info == FTS_DP) /* Second pass */
457 			{
458 	                        /*
459 				 * If not -p and directory didn't exist, set it to be
460 				 * the same as the from directory, umodified by the
461                         	 * umask; arguably wrong, but it's been that way
462                         	 * forever.
463 				 */
464 				if (pflag && setfile(curr->fts_statp, 0))
465 					this_failed = any_failed = 1;
466 				else if (dne)
467 					(void)chmod(to.p_path,
468 					    curr->fts_statp->st_mode);
469 
470 				/*
471 				 * Since this is the second pass, we already
472 				 * noted (and acted on) the existence of the
473 				 * directory.
474 				 */
475 				dne = 0;
476 			}
477 			else
478 			{
479 				warnx("directory %s encountered when not expected.",
480 				    curr->fts_path);
481 				this_failed = any_failed = 1;
482 				break;
483 			}
484 
485 			break;
486 		case S_IFBLK:
487 		case S_IFCHR:
488 			if (Rflag) {
489 				if (copy_special(curr->fts_statp, !dne))
490 					this_failed = any_failed = 1;
491 			} else
492 				if (copy_file(curr, dne))
493 					this_failed = any_failed = 1;
494 			break;
495 		case S_IFIFO:
496 			if (Rflag) {
497 				if (copy_fifo(curr->fts_statp, !dne))
498 					this_failed = any_failed = 1;
499 			} else
500 				if (copy_file(curr, dne))
501 					this_failed = any_failed = 1;
502 			break;
503 		default:
504 			if (copy_file(curr, dne))
505 				this_failed = any_failed = 1;
506 			break;
507 		}
508 		if (vflag && !this_failed)
509 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
510 	}
511 	if (errno) {
512 		err(EXIT_FAILURE, "fts_read");
513 		/* NOTREACHED */
514 	}
515 	(void)fts_close(ftsp);
516 	return (any_failed);
517 }
518 
519 /*
520  * mastercmp --
521  *	The comparison function for the copy order.  The order is to copy
522  *	non-directory files before directory files.  The reason for this
523  *	is because files tend to be in the same cylinder group as their
524  *	parent directory, whereas directories tend not to be.  Copying the
525  *	files first reduces seeking.
526  */
527 int
528 mastercmp(const FTSENT **a, const FTSENT **b)
529 {
530 	int a_info, b_info;
531 
532 	a_info = (*a)->fts_info;
533 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
534 		return (0);
535 	b_info = (*b)->fts_info;
536 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
537 		return (0);
538 	if (a_info == FTS_D)
539 		return (-1);
540 	if (b_info == FTS_D)
541 		return (1);
542 	return (0);
543 }
544