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