Home | History | Annotate | Line # | Download | only in cp
cp.c revision 1.31
      1 /* $NetBSD: cp.c,v 1.31 2001/09/13 09:53:59 wiz 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. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 __COPYRIGHT(
     42 "@(#) Copyright (c) 1988, 1993, 1994\n\
     43 	The Regents of the University of California.  All rights reserved.\n");
     44 #endif /* not lint */
     45 
     46 #ifndef lint
     47 #if 0
     48 static char sccsid[] = "@(#)cp.c	8.5 (Berkeley) 4/29/95";
     49 #else
     50 __RCSID("$NetBSD: cp.c,v 1.31 2001/09/13 09:53:59 wiz Exp $");
     51 #endif
     52 #endif /* not lint */
     53 
     54 /*
     55  * Cp copies source files to target files.
     56  *
     57  * The global PATH_T structure "to" always contains the path to the
     58  * current target file.  Since fts(3) does not change directories,
     59  * this path can be either absolute or dot-relative.
     60  *
     61  * The basic algorithm is to initialize "to" and use fts(3) to traverse
     62  * the file hierarchy rooted in the argument list.  A trivial case is the
     63  * case of 'cp file1 file2'.  The more interesting case is the case of
     64  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
     65  * path (relative to the root of the traversal) is appended to dir (stored
     66  * in "to") to form the final target path.
     67  */
     68 
     69 #include <sys/param.h>
     70 #include <sys/stat.h>
     71 
     72 #include <err.h>
     73 #include <errno.h>
     74 #include <fts.h>
     75 #include <locale.h>
     76 #include <stdlib.h>
     77 #include <stdio.h>
     78 #include <string.h>
     79 #include <unistd.h>
     80 
     81 #include "extern.h"
     82 
     83 #define	STRIP_TRAILING_SLASH(p) {					\
     84         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
     85                 *--(p).p_end = '\0';					\
     86 }
     87 
     88 PATH_T to = { to.p_path, "" };
     89 
     90 uid_t myuid;
     91 int Rflag, fflag, iflag, pflag, rflag;
     92 mode_t myumask;
     93 
     94 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
     95 
     96 int main(int, char *[]);
     97 int copy(char *[], enum op, int);
     98 int mastercmp(const FTSENT **, const FTSENT **);
     99 
    100 int
    101 main(int argc, char *argv[])
    102 {
    103 	struct stat to_stat, tmp_stat;
    104 	enum op type;
    105 	int Hflag, Lflag, Pflag, ch, fts_options, r;
    106 	char *target;
    107 
    108 	(void)setlocale(LC_ALL, "");
    109 
    110 	Hflag = Lflag = Pflag = Rflag = 0;
    111 	while ((ch = getopt(argc, argv, "HLPRfipr")) != -1)
    112 		switch (ch) {
    113 		case 'H':
    114 			Hflag = 1;
    115 			Lflag = Pflag = 0;
    116 			break;
    117 		case 'L':
    118 			Lflag = 1;
    119 			Hflag = Pflag = 0;
    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 '?':
    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(1,
    157 		    "the -R and -r options may not be specified together.");
    158 		if (Hflag || Lflag || Pflag)
    159 			errx(1,
    160 	"the -H, -L, and -P options may not be specified with the -r option.");
    161 		fts_options &= ~FTS_PHYSICAL;
    162 		fts_options |= FTS_LOGICAL;
    163 	}
    164 	if (Rflag) {
    165 		if (Hflag)
    166 			fts_options |= FTS_COMFOLLOW;
    167 		if (Lflag) {
    168 			fts_options &= ~FTS_PHYSICAL;
    169 			fts_options |= FTS_LOGICAL;
    170 		}
    171 	} else {
    172 		fts_options &= ~FTS_PHYSICAL;
    173 		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
    174 	}
    175 
    176 	myuid = getuid();
    177 
    178 	/* Copy the umask for explicit mode setting. */
    179 	myumask = umask(0);
    180 	(void)umask(myumask);
    181 
    182 	/* Save the target base in "to". */
    183 	target = argv[--argc];
    184 	if (strlen(target) > MAXPATHLEN)
    185 		errx(1, "%s: name too long", target);
    186 	(void)strcpy(to.p_path, target);
    187 	to.p_end = to.p_path + strlen(to.p_path);
    188         if (to.p_path == to.p_end) {
    189 		*to.p_end++ = '.';
    190 		*to.p_end = 0;
    191 	}
    192         STRIP_TRAILING_SLASH(to);
    193 	to.target_end = to.p_end;
    194 
    195 	/* Set end of argument list for fts(3). */
    196 	argv[argc] = NULL;
    197 
    198 	/*
    199 	 * Cp has two distinct cases:
    200 	 *
    201 	 * cp [-R] source target
    202 	 * cp [-R] source1 ... sourceN directory
    203 	 *
    204 	 * In both cases, source can be either a file or a directory.
    205 	 *
    206 	 * In (1), the target becomes a copy of the source. That is, if the
    207 	 * source is a file, the target will be a file, and likewise for
    208 	 * directories.
    209 	 *
    210 	 * In (2), the real target is not directory, but "directory/source".
    211 	 */
    212 	r = stat(to.p_path, &to_stat);
    213 	if (r == -1 && errno != ENOENT)
    214 		err(1, "%s", to.p_path);
    215 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
    216 		/*
    217 		 * Case (1).  Target is not a directory.
    218 		 */
    219 		if (argc > 1) {
    220 			usage();
    221 			exit(1);
    222 		}
    223 		/*
    224 		 * Need to detect the case:
    225 		 *	cp -R dir foo
    226 		 * Where dir is a directory and foo does not exist, where
    227 		 * we want pathname concatenations turned on but not for
    228 		 * the initial mkdir().
    229 		 */
    230 		if (r == -1) {
    231 			if (rflag || (Rflag && (Lflag || Hflag)))
    232 				r = stat(*argv, &tmp_stat);
    233 			else
    234 				r = lstat(*argv, &tmp_stat);
    235 			if (r == -1)
    236 				err(1, "%s", *argv);
    237 
    238 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
    239 				type = DIR_TO_DNE;
    240 			else
    241 				type = FILE_TO_FILE;
    242 		} else
    243 			type = FILE_TO_FILE;
    244 	} else {
    245 		/*
    246 		 * Case (2).  Target is a directory.
    247 		 */
    248 		type = FILE_TO_DIR;
    249 	}
    250 
    251 	exit(copy(argv, type, fts_options));
    252 	/* NOTREACHED */
    253 }
    254 
    255 int
    256 copy(char *argv[], enum op type, int fts_options)
    257 {
    258 	struct stat to_stat;
    259 	FTS *ftsp;
    260 	FTSENT *curr;
    261 	int base, dne, nlen, rval;
    262 	char *p, *tmp;
    263 
    264 	base = 0;	/* XXX gcc -Wuninitialized (see comment below) */
    265 
    266 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
    267 		err(1, "%s", argv[0]);
    268 	for (rval = 0; (curr = fts_read(ftsp)) != NULL;) {
    269 		switch (curr->fts_info) {
    270 		case FTS_NS:
    271 		case FTS_DNR:
    272 		case FTS_ERR:
    273 			warnx("%s: %s",
    274 			    curr->fts_path, strerror(curr->fts_errno));
    275 			rval = 1;
    276 			continue;
    277 		case FTS_DC:			/* Warn, continue. */
    278 			warnx("%s: directory causes a cycle", curr->fts_path);
    279 			rval = 1;
    280 			continue;
    281 		}
    282 
    283 		/*
    284 		 * If we are in case (2) or (3) above, we need to append the
    285                  * source name to the target name.
    286                  */
    287 		if (type != FILE_TO_FILE) {
    288 			if ((curr->fts_namelen +
    289 			    to.target_end - to.p_path + 1) > MAXPATHLEN) {
    290 				warnx("%s/%s: name too long (not copied)",
    291 				    to.p_path, curr->fts_name);
    292 				rval = 1;
    293 				continue;
    294 			}
    295 
    296 			/*
    297 			 * Need to remember the roots of traversals to create
    298 			 * correct pathnames.  If there's a directory being
    299 			 * copied to a non-existent directory, e.g.
    300 			 *	cp -R a/dir noexist
    301 			 * the resulting path name should be noexist/foo, not
    302 			 * noexist/dir/foo (where foo is a file in dir), which
    303 			 * is the case where the target exists.
    304 			 *
    305 			 * Also, check for "..".  This is for correct path
    306 			 * concatentation for paths ending in "..", e.g.
    307 			 *	cp -R .. /tmp
    308 			 * Paths ending in ".." are changed to ".".  This is
    309 			 * tricky, but seems the easiest way to fix the problem.
    310 			 *
    311 			 * XXX
    312 			 * Since the first level MUST be FTS_ROOTLEVEL, base
    313 			 * is always initialized.
    314 			 */
    315 			if (curr->fts_level == FTS_ROOTLEVEL) {
    316 				if (type != DIR_TO_DNE) {
    317 					p = strrchr(curr->fts_path, '/');
    318 					base = (p == NULL) ? 0 :
    319 					    (int)(p - curr->fts_path + 1);
    320 
    321 					if (!strcmp(&curr->fts_path[base],
    322 					    ".."))
    323 						base += 1;
    324 				} else
    325 					base = curr->fts_pathlen;
    326 			}
    327 
    328 			p = &curr->fts_path[base];
    329 			nlen = curr->fts_pathlen - base;
    330 
    331 			tmp = to.target_end;
    332 			if (*p != '/' && *(tmp - 1) != '/')
    333 				*tmp++ = '/';
    334 			*tmp = 0;
    335 
    336 			(void)strncat(tmp, p, nlen);
    337 			to.p_end = tmp + nlen;
    338 			*to.p_end = 0;
    339 			STRIP_TRAILING_SLASH(to);
    340 		}
    341 
    342 		/* Not an error but need to remember it happened */
    343 		if (stat(to.p_path, &to_stat) == -1)
    344 			dne = 1;
    345 		else {
    346 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
    347 			    to_stat.st_ino == curr->fts_statp->st_ino) {
    348 				warnx("%s and %s are identical (not copied).",
    349 				    to.p_path, curr->fts_path);
    350 				rval = 1;
    351 				if (S_ISDIR(curr->fts_statp->st_mode))
    352 					(void)fts_set(ftsp, curr, FTS_SKIP);
    353 				continue;
    354 			}
    355 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
    356 			    S_ISDIR(to_stat.st_mode)) {
    357 		warnx("cannot overwrite directory %s with non-directory %s",
    358 				    to.p_path, curr->fts_path);
    359 				rval = 1;
    360 				continue;
    361 			}
    362 			dne = 0;
    363 		}
    364 
    365 		switch (curr->fts_statp->st_mode & S_IFMT) {
    366 		case S_IFLNK:
    367 			/* Catch special case of a non dangling symlink */
    368 			if((fts_options & FTS_LOGICAL) ||
    369 			   ((fts_options & FTS_COMFOLLOW) && curr->fts_level == 0)) {
    370 				if (copy_file(curr, dne))
    371 					rval = 1;
    372 			} else {
    373 				if (copy_link(curr, !dne))
    374 					rval = 1;
    375 			}
    376 			break;
    377 		case S_IFDIR:
    378 			if (!Rflag && !rflag) {
    379 				if (curr->fts_info == FTS_D)
    380 					warnx("%s is a directory (not copied).",
    381 					    curr->fts_path);
    382 				(void)fts_set(ftsp, curr, FTS_SKIP);
    383 				rval = 1;
    384 				break;
    385 			}
    386 
    387                         /*
    388                          * Directories get noticed twice:
    389                          *  In the first pass, create it if needed.
    390                          *  In the second pass, after the children have been copied, set the permissions.
    391                          */
    392 			if (curr->fts_info == FTS_D) /* First pass */
    393 			{
    394 				/*
    395 				 * If the directory doesn't exist, create the new
    396 				 * one with the from file mode plus owner RWX bits,
    397 				 * modified by the umask.  Trade-off between being
    398 				 * able to write the directory (if from directory is
    399 				 * 555) and not causing a permissions race.  If the
    400 				 * umask blocks owner writes, we fail..
    401 				 */
    402 				if (dne) {
    403 					if (mkdir(to.p_path,
    404 					    curr->fts_statp->st_mode | S_IRWXU) < 0)
    405 						err(1, "%s", to.p_path);
    406 				} else if (!S_ISDIR(to_stat.st_mode)) {
    407 					errno = ENOTDIR;
    408 					err(1, "%s", to.p_path);
    409 				}
    410 			}
    411 			else if (curr->fts_info == FTS_DP) /* Second pass */
    412 			{
    413 	                        /*
    414 				 * If not -p and directory didn't exist, set it to be
    415 				 * the same as the from directory, umodified by the
    416                         	 * umask; arguably wrong, but it's been that way
    417                         	 * forever.
    418 				 */
    419 				if (pflag && setfile(curr->fts_statp, 0))
    420 					rval = 1;
    421 				else if (dne)
    422 					(void)chmod(to.p_path,
    423 					    curr->fts_statp->st_mode);
    424 			}
    425 			else
    426                         {
    427                         	warnx("directory %s encountered when not expected.", curr->fts_path);
    428                         	rval = 1;
    429                                 break;
    430                         }
    431 
    432 			break;
    433 		case S_IFBLK:
    434 		case S_IFCHR:
    435 			if (Rflag) {
    436 				if (copy_special(curr->fts_statp, !dne))
    437 					rval = 1;
    438 			} else
    439 				if (copy_file(curr, dne))
    440 					rval = 1;
    441 			break;
    442 		case S_IFIFO:
    443 			if (Rflag) {
    444 				if (copy_fifo(curr->fts_statp, !dne))
    445 					rval = 1;
    446 			} else
    447 				if (copy_file(curr, dne))
    448 					rval = 1;
    449 			break;
    450 		default:
    451 			if (copy_file(curr, dne))
    452 				rval = 1;
    453 			break;
    454 		}
    455 	}
    456 	if (errno)
    457 		err(1, "fts_read");
    458 	return (rval);
    459 }
    460 
    461 /*
    462  * mastercmp --
    463  *	The comparison function for the copy order.  The order is to copy
    464  *	non-directory files before directory files.  The reason for this
    465  *	is because files tend to be in the same cylinder group as their
    466  *	parent directory, whereas directories tend not to be.  Copying the
    467  *	files first reduces seeking.
    468  */
    469 int
    470 mastercmp(const FTSENT **a, const FTSENT **b)
    471 {
    472 	int a_info, b_info;
    473 
    474 	a_info = (*a)->fts_info;
    475 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
    476 		return (0);
    477 	b_info = (*b)->fts_info;
    478 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
    479 		return (0);
    480 	if (a_info == FTS_D)
    481 		return (-1);
    482 	if (b_info == FTS_D)
    483 		return (1);
    484 	return (0);
    485 }
    486