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