Home | History | Annotate | Line # | Download | only in cp
utils.c revision 1.39
      1 /* $NetBSD: utils.c,v 1.39 2011/02/06 12:37:49 darcy Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 #if 0
     35 static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
     36 #else
     37 __RCSID("$NetBSD: utils.c,v 1.39 2011/02/06 12:37:49 darcy Exp $");
     38 #endif
     39 #endif /* not lint */
     40 
     41 #include <sys/mman.h>
     42 #include <sys/param.h>
     43 #include <sys/stat.h>
     44 #include <sys/time.h>
     45 
     46 #include <err.h>
     47 #include <errno.h>
     48 #include <fcntl.h>
     49 #include <fts.h>
     50 #include <stdbool.h>
     51 #include <stdio.h>
     52 #include <stdlib.h>
     53 #include <string.h>
     54 #include <unistd.h>
     55 
     56 #include "extern.h"
     57 
     58 #define	MMAP_MAX_SIZE	(8 * 1048576)
     59 #define	MMAP_MAX_WRITE	(64 * 1024)
     60 
     61 int
     62 set_utimes(const char *file, struct stat *fs)
     63 {
     64     static struct timeval tv[2];
     65 
     66     TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
     67     TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
     68 
     69     if (lutimes(file, tv)) {
     70 	warn("lutimes: %s", file);
     71 	return (1);
     72     }
     73     return (0);
     74 }
     75 
     76 int
     77 copy_file(FTSENT *entp, int dne)
     78 {
     79 	static char buf[MAXBSIZE];
     80 	struct stat to_stat, *fs;
     81 	int ch, checkch, from_fd, rcount, rval, to_fd, tolnk, wcount;
     82 	char *p;
     83 
     84 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
     85 		warn("%s", entp->fts_path);
     86 		return (1);
     87 	}
     88 
     89 	to_fd = -1;
     90 	fs = entp->fts_statp;
     91 	tolnk = ((Rflag && !(Lflag || Hflag)) || Pflag);
     92 
     93 	/*
     94 	 * If the file exists and we're interactive, verify with the user.
     95 	 * If the file DNE, set the mode to be the from file, minus setuid
     96 	 * bits, modified by the umask; arguably wrong, but it makes copying
     97 	 * executables work right and it's been that way forever.  (The
     98 	 * other choice is 666 or'ed with the execute bits on the from file
     99 	 * modified by the umask.)
    100 	 */
    101 	if (!dne) {
    102 		struct stat sb;
    103 		int sval;
    104 
    105 		if (iflag) {
    106 			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
    107 			checkch = ch = getchar();
    108 			while (ch != '\n' && ch != EOF)
    109 				ch = getchar();
    110 			if (checkch != 'y' && checkch != 'Y') {
    111 				(void)close(from_fd);
    112 				return (0);
    113 			}
    114 		}
    115 
    116 		sval = tolnk ?
    117 			lstat(to.p_path, &sb) : stat(to.p_path, &sb);
    118 		if (sval == -1) {
    119 			warn("stat: %s", to.p_path);
    120 			(void)close(from_fd);
    121 			return (1);
    122 		}
    123 
    124 		if (!(tolnk && S_ISLNK(sb.st_mode)))
    125 			to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
    126 	} else
    127 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
    128 		    fs->st_mode & ~(S_ISUID | S_ISGID));
    129 
    130 	if (to_fd == -1 && (fflag || tolnk)) {
    131 		/*
    132 		 * attempt to remove existing destination file name and
    133 		 * create a new file
    134 		 */
    135 		(void)unlink(to.p_path);
    136 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
    137 			     fs->st_mode & ~(S_ISUID | S_ISGID));
    138 	}
    139 
    140 	if (to_fd == -1) {
    141 		warn("%s", to.p_path);
    142 		(void)close(from_fd);
    143 		return (1);
    144 	}
    145 
    146 	rval = 0;
    147 
    148 	/* if hard linking then simply close the open fds, link and return */
    149 	if (lflag) {
    150 		(void)close(from_fd);
    151 		(void)close(to_fd);
    152 		(void)unlink(to.p_path);
    153 		if (link(entp->fts_path, to.p_path)) {
    154 			warn("%s", to.p_path);
    155 			return (1);
    156 		}
    157 		return (0);
    158 	}
    159 	/* NOTREACHED */
    160 
    161 	/*
    162 	 * There's no reason to do anything other than close the file
    163 	 * now if it's empty, so let's not bother.
    164 	 */
    165 	if (fs->st_size > 0) {
    166 		/*
    167 		 * Mmap and write if less than 8M (the limit is so
    168 		 * we don't totally trash memory on big files).
    169 		 * This is really a minor hack, but it wins some CPU back.
    170 		 */
    171 		bool use_read;
    172 
    173 		use_read = true;
    174 		if (fs->st_size <= MMAP_MAX_SIZE) {
    175 			size_t fsize = (size_t)fs->st_size;
    176 			p = mmap(NULL, fsize, PROT_READ, MAP_FILE|MAP_SHARED,
    177 			    from_fd, (off_t)0);
    178 			if (p != MAP_FAILED) {
    179 				size_t remainder;
    180 
    181 				use_read = false;
    182 
    183 				(void) madvise(p, (size_t)fs->st_size,
    184 				     MADV_SEQUENTIAL);
    185 
    186 				/*
    187 				 * Write out the data in small chunks to
    188 				 * avoid locking the output file for a
    189 				 * long time if the reading the data from
    190 				 * the source is slow.
    191 				 */
    192 				remainder = fsize;
    193 				do {
    194 					ssize_t chunk;
    195 
    196 					chunk = (remainder > MMAP_MAX_WRITE) ?
    197 					    MMAP_MAX_WRITE : remainder;
    198 					if (write(to_fd, &p[fsize - remainder],
    199 					    chunk) != chunk) {
    200 						warn("%s", to.p_path);
    201 						rval = 1;
    202 						break;
    203 					}
    204 					remainder -= chunk;
    205 				} while (remainder > 0);
    206 
    207 				if (munmap(p, fsize) < 0) {
    208 					warn("%s", entp->fts_path);
    209 					rval = 1;
    210 				}
    211 			}
    212 		}
    213 
    214 		if (use_read) {
    215 			while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
    216 				wcount = write(to_fd, buf, (size_t)rcount);
    217 				if (rcount != wcount || wcount == -1) {
    218 					warn("%s", to.p_path);
    219 					rval = 1;
    220 					break;
    221 				}
    222 			}
    223 			if (rcount < 0) {
    224 				warn("%s", entp->fts_path);
    225 				rval = 1;
    226 			}
    227 		}
    228 	}
    229 
    230 	(void)close(from_fd);
    231 
    232 	if (rval == 1) {
    233 		(void)close(to_fd);
    234 		return (1);
    235 	}
    236 
    237 	if (pflag && setfile(fs, to_fd))
    238 		rval = 1;
    239 	/*
    240 	 * If the source was setuid or setgid, lose the bits unless the
    241 	 * copy is owned by the same user and group.
    242 	 */
    243 #define	RETAINBITS \
    244 	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
    245 	if (!pflag && dne
    246 	    && fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
    247 		if (fstat(to_fd, &to_stat)) {
    248 			warn("%s", to.p_path);
    249 			rval = 1;
    250 		} else if (fs->st_gid == to_stat.st_gid &&
    251 		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
    252 			warn("%s", to.p_path);
    253 			rval = 1;
    254 		}
    255 	}
    256 	if (close(to_fd)) {
    257 		warn("%s", to.p_path);
    258 		rval = 1;
    259 	}
    260 	/* set the mod/access times now after close of the fd */
    261 	if (pflag && set_utimes(to.p_path, fs)) {
    262 	    rval = 1;
    263 	}
    264 	return (rval);
    265 }
    266 
    267 int
    268 copy_link(FTSENT *p, int exists)
    269 {
    270 	int len;
    271 	char target[MAXPATHLEN];
    272 
    273 	if ((len = readlink(p->fts_path, target, sizeof(target)-1)) == -1) {
    274 		warn("readlink: %s", p->fts_path);
    275 		return (1);
    276 	}
    277 	target[len] = '\0';
    278 	if (exists && unlink(to.p_path)) {
    279 		warn("unlink: %s", to.p_path);
    280 		return (1);
    281 	}
    282 	if (symlink(target, to.p_path)) {
    283 		warn("symlink: %s", target);
    284 		return (1);
    285 	}
    286 	return (pflag ? setfile(p->fts_statp, 0) : 0);
    287 }
    288 
    289 int
    290 copy_fifo(struct stat *from_stat, int exists)
    291 {
    292 	if (exists && unlink(to.p_path)) {
    293 		warn("unlink: %s", to.p_path);
    294 		return (1);
    295 	}
    296 	if (mkfifo(to.p_path, from_stat->st_mode)) {
    297 		warn("mkfifo: %s", to.p_path);
    298 		return (1);
    299 	}
    300 	return (pflag ? setfile(from_stat, 0) : 0);
    301 }
    302 
    303 int
    304 copy_special(struct stat *from_stat, int exists)
    305 {
    306 	if (exists && unlink(to.p_path)) {
    307 		warn("unlink: %s", to.p_path);
    308 		return (1);
    309 	}
    310 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
    311 		warn("mknod: %s", to.p_path);
    312 		return (1);
    313 	}
    314 	return (pflag ? setfile(from_stat, 0) : 0);
    315 }
    316 
    317 
    318 /*
    319  * Function: setfile
    320  *
    321  * Purpose:
    322  *   Set the owner/group/permissions for the "to" file to the information
    323  *   in the stat structure.  If fd is zero, also call set_utimes() to set
    324  *   the mod/access times.  If fd is non-zero, the caller must do a utimes
    325  *   itself after close(fd).
    326  */
    327 int
    328 setfile(struct stat *fs, int fd)
    329 {
    330 	int rval, islink;
    331 
    332 	rval = 0;
    333 	islink = S_ISLNK(fs->st_mode);
    334 	fs->st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
    335 
    336 	/*
    337 	 * Changing the ownership probably won't succeed, unless we're root
    338 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
    339 	 * the mode; current BSD behavior is to remove all setuid bits on
    340 	 * chown.  If chown fails, lose setuid/setgid bits.
    341 	 */
    342 	if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
    343 	    lchown(to.p_path, fs->st_uid, fs->st_gid)) {
    344 		if (errno != EPERM) {
    345 			warn("chown: %s", to.p_path);
    346 			rval = 1;
    347 		}
    348 		fs->st_mode &= ~(S_ISUID | S_ISGID);
    349 	}
    350 	if (fd ? fchmod(fd, fs->st_mode) : lchmod(to.p_path, fs->st_mode)) {
    351 		warn("chmod: %s", to.p_path);
    352 		rval = 1;
    353 	}
    354 
    355 	if (!islink && !Nflag) {
    356 		unsigned long fflags = fs->st_flags;
    357 		/*
    358 		 * XXX
    359 		 * NFS doesn't support chflags; ignore errors unless
    360 		 * there's reason to believe we're losing bits.
    361 		 * (Note, this still won't be right if the server
    362 		 * supports flags and we were trying to *remove* flags
    363 		 * on a file that we copied, i.e., that we didn't create.)
    364 		 */
    365 		errno = 0;
    366 		if ((fd ? fchflags(fd, fflags) :
    367 		    chflags(to.p_path, fflags)) == -1)
    368 			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
    369 				warn("chflags: %s", to.p_path);
    370 				rval = 1;
    371 			}
    372 	}
    373 	/* if fd is non-zero, caller must call set_utimes() after close() */
    374 	if (fd == 0 && set_utimes(to.p_path, fs))
    375 	    rval = 1;
    376 	return (rval);
    377 }
    378 
    379 void
    380 usage(void)
    381 {
    382 	(void)fprintf(stderr,
    383 	    "usage: %s [-R [-H | -L | -P]] [-f | -i] [-alNpv] src target\n"
    384 	    "       %s [-R [-H | -L | -P]] [-f | -i] [-alNpv] src1 ... srcN directory\n",
    385 	    getprogname(), getprogname());
    386 	exit(1);
    387 	/* NOTREACHED */
    388 }
    389