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