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