Home | History | Annotate | Line # | Download | only in cp
cp.c revision 1.56
      1 /* $NetBSD: cp.c,v 1.56 2011/08/03 04:11:15 manu 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.56 2011/08/03 04:11:15 manu 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 <assert.h>
     69 #include <err.h>
     70 #include <errno.h>
     71 #include <fts.h>
     72 #include <locale.h>
     73 #include <stdlib.h>
     74 #include <stdio.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 empty[] = "";
     86 PATH_T to = { .p_end = to.p_path, .target_end = empty  };
     87 
     88 uid_t myuid;
     89 int Hflag, Lflag, Rflag, Pflag, fflag, iflag, lflag, pflag, rflag, vflag, Nflag;
     90 mode_t myumask;
     91 
     92 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
     93 
     94 int 	main(int, char *[]);
     95 int 	copy(char *[], enum op, int);
     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, "HLNPRfailprv")) != -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 'a':
    130 			Pflag = 1;
    131 			pflag = 1;
    132 			Rflag = 1;
    133 			Hflag = Lflag = 0;
    134 			break;
    135 		case 'f':
    136 			fflag = 1;
    137 			iflag = 0;
    138 			break;
    139 		case 'i':
    140 			iflag = isatty(fileno(stdin));
    141 			fflag = 0;
    142 			break;
    143 		case 'l':
    144 			lflag = 1;
    145 			break;
    146 		case 'p':
    147 			pflag = 1;
    148 			break;
    149 		case 'r':
    150 			rflag = 1;
    151 			break;
    152 		case 'v':
    153 			vflag = 1;
    154 			break;
    155 		case '?':
    156 		default:
    157 			usage();
    158 			/* NOTREACHED */
    159 		}
    160 	argc -= optind;
    161 	argv += optind;
    162 
    163 	if (argc < 2)
    164 		usage();
    165 
    166 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
    167 	if (rflag) {
    168 		if (Rflag) {
    169 			errx(EXIT_FAILURE,
    170 		    "the -R and -r options may not be specified together.");
    171 			/* NOTREACHED */
    172 		}
    173 		if (Hflag || Lflag || Pflag) {
    174 			errx(EXIT_FAILURE,
    175 	"the -H, -L, and -P options may not be specified with the -r option.");
    176 			/* NOTREACHED */
    177 		}
    178 		fts_options &= ~FTS_PHYSICAL;
    179 		fts_options |= FTS_LOGICAL;
    180 	}
    181 
    182 	if (Rflag) {
    183 		if (Hflag)
    184 			fts_options |= FTS_COMFOLLOW;
    185 		if (Lflag) {
    186 			fts_options &= ~FTS_PHYSICAL;
    187 			fts_options |= FTS_LOGICAL;
    188 		}
    189 	} else if (!Pflag) {
    190 		fts_options &= ~FTS_PHYSICAL;
    191 		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
    192 	}
    193 
    194 	myuid = getuid();
    195 
    196 	/* Copy the umask for explicit mode setting. */
    197 	myumask = umask(0);
    198 	(void)umask(myumask);
    199 
    200 	/*
    201 	 * Warn that system extended attributes will not be preserved
    202 	 * if not root
    203 	 */
    204 	if ((myuid != 0) && pflag)
    205 		warnx("system extended attribute will not be preserved");
    206 
    207 	/* Save the target base in "to". */
    208 	target = argv[--argc];
    209 	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
    210 		errx(EXIT_FAILURE, "%s: name too long", target);
    211 	to.p_end = to.p_path + strlen(to.p_path);
    212 	have_trailing_slash = (to.p_end[-1] == '/');
    213 	if (have_trailing_slash)
    214 		STRIP_TRAILING_SLASH(to);
    215 	to.target_end = to.p_end;
    216 
    217 	/* Set end of argument list for fts(3). */
    218 	argv[argc] = NULL;
    219 
    220 	/*
    221 	 * Cp has two distinct cases:
    222 	 *
    223 	 * cp [-R] source target
    224 	 * cp [-R] source1 ... sourceN directory
    225 	 *
    226 	 * In both cases, source can be either a file or a directory.
    227 	 *
    228 	 * In (1), the target becomes a copy of the source. That is, if the
    229 	 * source is a file, the target will be a file, and likewise for
    230 	 * directories.
    231 	 *
    232 	 * In (2), the real target is not directory, but "directory/source".
    233 	 */
    234 	if (Pflag)
    235 		r = lstat(to.p_path, &to_stat);
    236 	else
    237 		r = stat(to.p_path, &to_stat);
    238 	if (r == -1 && errno != ENOENT) {
    239 		err(EXIT_FAILURE, "%s", to.p_path);
    240 		/* NOTREACHED */
    241 	}
    242 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
    243 		/*
    244 		 * Case (1).  Target is not a directory.
    245 		 */
    246 		if (argc > 1)
    247 			usage();
    248 		/*
    249 		 * Need to detect the case:
    250 		 *	cp -R dir foo
    251 		 * Where dir is a directory and foo does not exist, where
    252 		 * we want pathname concatenations turned on but not for
    253 		 * the initial mkdir().
    254 		 */
    255 		if (r == -1) {
    256 			if (rflag || (Rflag && (Lflag || Hflag)))
    257 				r = stat(*argv, &tmp_stat);
    258 			else
    259 				r = lstat(*argv, &tmp_stat);
    260 			if (r == -1) {
    261 				err(EXIT_FAILURE, "%s", *argv);
    262 				/* NOTREACHED */
    263 			}
    264 
    265 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
    266 				type = DIR_TO_DNE;
    267 			else
    268 				type = FILE_TO_FILE;
    269 		} else
    270 			type = FILE_TO_FILE;
    271 
    272 		if (have_trailing_slash && type == FILE_TO_FILE) {
    273 			if (r == -1)
    274 				errx(1, "directory %s does not exist",
    275 				     to.p_path);
    276 			else
    277 				errx(1, "%s is not a directory", to.p_path);
    278 		}
    279 	} else {
    280 		/*
    281 		 * Case (2).  Target is a directory.
    282 		 */
    283 		type = FILE_TO_DIR;
    284 	}
    285 
    286 	/*
    287 	 * make "cp -rp src/ dst" behave like "cp -rp src dst" not
    288 	 * like "cp -rp src/. dst"
    289 	 */
    290 	for (src = argv; *src; src++) {
    291 		size_t len = strlen(*src);
    292 		while (len-- > 1 && (*src)[len] == '/')
    293 			(*src)[len] = '\0';
    294 	}
    295 
    296 	exit(copy(argv, type, fts_options));
    297 	/* NOTREACHED */
    298 }
    299 
    300 static int dnestack[MAXPATHLEN]; /* unlikely we'll have more nested dirs */
    301 static ssize_t dnesp;
    302 static void
    303 pushdne(int dne)
    304 {
    305 
    306 	dnestack[dnesp++] = dne;
    307 	assert(dnesp < MAXPATHLEN);
    308 }
    309 
    310 static int
    311 popdne(void)
    312 {
    313 	int rv;
    314 
    315 	rv = dnestack[--dnesp];
    316 	assert(dnesp >= 0);
    317 	return rv;
    318 }
    319 
    320 int
    321 copy(char *argv[], enum op type, int fts_options)
    322 {
    323 	struct stat to_stat;
    324 	FTS *ftsp;
    325 	FTSENT *curr;
    326 	int base, dne, sval;
    327 	int this_failed, any_failed;
    328 	size_t nlen;
    329 	char *p, *target_mid;
    330 
    331 	base = 0;	/* XXX gcc -Wuninitialized (see comment below) */
    332 
    333 	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
    334 		err(EXIT_FAILURE, "%s", argv[0]);
    335 		/* NOTREACHED */
    336 	for (any_failed = 0; (curr = fts_read(ftsp)) != NULL;) {
    337 		this_failed = 0;
    338 		switch (curr->fts_info) {
    339 		case FTS_NS:
    340 		case FTS_DNR:
    341 		case FTS_ERR:
    342 			warnx("%s: %s", curr->fts_path,
    343 					strerror(curr->fts_errno));
    344 			this_failed = any_failed = 1;
    345 			continue;
    346 		case FTS_DC:			/* Warn, continue. */
    347 			warnx("%s: directory causes a cycle", curr->fts_path);
    348 			this_failed = any_failed = 1;
    349 			continue;
    350 		}
    351 
    352 		/*
    353 		 * If we are in case (2) or (3) above, we need to append the
    354                  * source name to the target name.
    355                  */
    356 		if (type != FILE_TO_FILE) {
    357 			if ((curr->fts_namelen +
    358 			    to.target_end - to.p_path + 1) > MAXPATHLEN) {
    359 				warnx("%s/%s: name too long (not copied)",
    360 						to.p_path, curr->fts_name);
    361 				this_failed = any_failed = 1;
    362 				continue;
    363 			}
    364 
    365 			/*
    366 			 * Need to remember the roots of traversals to create
    367 			 * correct pathnames.  If there's a directory being
    368 			 * copied to a non-existent directory, e.g.
    369 			 *	cp -R a/dir noexist
    370 			 * the resulting path name should be noexist/foo, not
    371 			 * noexist/dir/foo (where foo is a file in dir), which
    372 			 * is the case where the target exists.
    373 			 *
    374 			 * Also, check for "..".  This is for correct path
    375 			 * concatentation for paths ending in "..", e.g.
    376 			 *	cp -R .. /tmp
    377 			 * Paths ending in ".." are changed to ".".  This is
    378 			 * tricky, but seems the easiest way to fix the problem.
    379 			 *
    380 			 * XXX
    381 			 * Since the first level MUST be FTS_ROOTLEVEL, base
    382 			 * is always initialized.
    383 			 */
    384 			if (curr->fts_level == FTS_ROOTLEVEL) {
    385 				if (type != DIR_TO_DNE) {
    386 					p = strrchr(curr->fts_path, '/');
    387 					base = (p == NULL) ? 0 :
    388 					    (int)(p - curr->fts_path + 1);
    389 
    390 					if (!strcmp(&curr->fts_path[base],
    391 					    ".."))
    392 						base += 1;
    393 				} else
    394 					base = curr->fts_pathlen;
    395 			}
    396 
    397 			p = &curr->fts_path[base];
    398 			nlen = curr->fts_pathlen - base;
    399 			target_mid = to.target_end;
    400 			if (*p != '/' && target_mid[-1] != '/')
    401 				*target_mid++ = '/';
    402 			*target_mid = 0;
    403 
    404 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
    405 				warnx("%s%s: name too long (not copied)",
    406 				    to.p_path, p);
    407 				this_failed = any_failed = 1;
    408 				continue;
    409 			}
    410 			(void)strncat(target_mid, p, nlen);
    411 			to.p_end = target_mid + nlen;
    412 			*to.p_end = 0;
    413 			STRIP_TRAILING_SLASH(to);
    414 		}
    415 
    416 		sval = Pflag ? lstat(to.p_path, &to_stat) : stat(to.p_path, &to_stat);
    417 		/* Not an error but need to remember it happened */
    418 		if (sval == -1)
    419 			dne = 1;
    420 		else {
    421 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
    422 			    to_stat.st_ino == curr->fts_statp->st_ino) {
    423 				warnx("%s and %s are identical (not copied).",
    424 				    to.p_path, curr->fts_path);
    425 				this_failed = any_failed = 1;
    426 				if (S_ISDIR(curr->fts_statp->st_mode))
    427 					(void)fts_set(ftsp, curr, FTS_SKIP);
    428 				continue;
    429 			}
    430 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
    431 			    S_ISDIR(to_stat.st_mode)) {
    432 		warnx("cannot overwrite directory %s with non-directory %s",
    433 				    to.p_path, curr->fts_path);
    434 				this_failed = any_failed = 1;
    435 				continue;
    436 			}
    437 			dne = 0;
    438 		}
    439 
    440 		switch (curr->fts_statp->st_mode & S_IFMT) {
    441 		case S_IFLNK:
    442 			/* Catch special case of a non dangling symlink */
    443 			if((fts_options & FTS_LOGICAL) ||
    444 			   ((fts_options & FTS_COMFOLLOW) && curr->fts_level == 0)) {
    445 				if (copy_file(curr, dne))
    446 					this_failed = any_failed = 1;
    447 			} else {
    448 				if (copy_link(curr, !dne))
    449 					this_failed = any_failed = 1;
    450 			}
    451 			break;
    452 		case S_IFDIR:
    453 			if (!Rflag && !rflag) {
    454 				if (curr->fts_info == FTS_D)
    455 					warnx("%s is a directory (not copied).",
    456 					    curr->fts_path);
    457 				(void)fts_set(ftsp, curr, FTS_SKIP);
    458 				this_failed = any_failed = 1;
    459 				break;
    460 			}
    461 
    462                         /*
    463                          * Directories get noticed twice:
    464                          *  In the first pass, create it if needed.
    465                          *  In the second pass, after the children have been copied, set the permissions.
    466                          */
    467 			if (curr->fts_info == FTS_D) /* First pass */
    468 			{
    469 				/*
    470 				 * If the directory doesn't exist, create the new
    471 				 * one with the from file mode plus owner RWX bits,
    472 				 * modified by the umask.  Trade-off between being
    473 				 * able to write the directory (if from directory is
    474 				 * 555) and not causing a permissions race.  If the
    475 				 * umask blocks owner writes, we fail..
    476 				 */
    477 				pushdne(dne);
    478 				if (dne) {
    479 					if (mkdir(to.p_path,
    480 					    curr->fts_statp->st_mode | S_IRWXU) < 0)
    481 						err(EXIT_FAILURE, "%s",
    482 						    to.p_path);
    483 						/* NOTREACHED */
    484 				} else if (!S_ISDIR(to_stat.st_mode)) {
    485 					errno = ENOTDIR;
    486 					err(EXIT_FAILURE, "%s",
    487 						to.p_path);
    488 					/* NOTREACHED */
    489 				}
    490 			}
    491 			else if (curr->fts_info == FTS_DP) /* Second pass */
    492 			{
    493 	                        /*
    494 				 * If not -p and directory didn't exist, set it to be
    495 				 * the same as the from directory, umodified by the
    496                         	 * umask; arguably wrong, but it's been that way
    497                         	 * forever.
    498 				 */
    499 				if (pflag && setfile(curr->fts_statp, 0))
    500 					this_failed = any_failed = 1;
    501 				else if ((dne = popdne()))
    502 					(void)chmod(to.p_path,
    503 					    curr->fts_statp->st_mode);
    504 			}
    505 			else
    506 			{
    507 				warnx("directory %s encountered when not expected.",
    508 				    curr->fts_path);
    509 				this_failed = any_failed = 1;
    510 				break;
    511 			}
    512 
    513 			break;
    514 		case S_IFBLK:
    515 		case S_IFCHR:
    516 			if (Rflag) {
    517 				if (copy_special(curr->fts_statp, !dne))
    518 					this_failed = any_failed = 1;
    519 			} else
    520 				if (copy_file(curr, dne))
    521 					this_failed = any_failed = 1;
    522 			break;
    523 		case S_IFIFO:
    524 			if (Rflag) {
    525 				if (copy_fifo(curr->fts_statp, !dne))
    526 					this_failed = any_failed = 1;
    527 			} else
    528 				if (copy_file(curr, dne))
    529 					this_failed = any_failed = 1;
    530 			break;
    531 		default:
    532 			if (copy_file(curr, dne))
    533 				this_failed = any_failed = 1;
    534 			break;
    535 		}
    536 		if (vflag && !this_failed)
    537 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
    538 	}
    539 	if (errno) {
    540 		err(EXIT_FAILURE, "fts_read");
    541 		/* NOTREACHED */
    542 	}
    543 	(void)fts_close(ftsp);
    544 	return (any_failed);
    545 }
    546