Home | History | Annotate | Line # | Download | only in cp
utils.c revision 1.47
      1 /* $NetBSD: utils.c,v 1.47 2019/09/23 18:01:09 christos 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.47 2019/09/23 18:01:09 christos 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 #include <sys/extattr.h>
     46 
     47 #include <err.h>
     48 #include <errno.h>
     49 #include <fcntl.h>
     50 #include <fts.h>
     51 #include <stdbool.h>
     52 #include <stdio.h>
     53 #include <stdlib.h>
     54 #include <string.h>
     55 #include <unistd.h>
     56 
     57 #include "extern.h"
     58 
     59 #define	MMAP_MAX_SIZE	(8 * 1048576)
     60 #define	MMAP_MAX_WRITE	(64 * 1024)
     61 
     62 int
     63 set_utimes(const char *file, struct stat *fs)
     64 {
     65     struct timespec ts[2];
     66 
     67     ts[0] = fs->st_atimespec;
     68     ts[1] = fs->st_mtimespec;
     69 
     70     if (lutimens(file, ts)) {
     71 	warn("lutimens: %s", file);
     72 	return (1);
     73     }
     74     return (0);
     75 }
     76 
     77 struct finfo {
     78 	const char *from;
     79 	const char *to;
     80 	off_t size;
     81 };
     82 
     83 static void
     84 progress(const struct finfo *fi, off_t written)
     85 {
     86 	int pcent = (int)((100.0 * written) / fi->size);
     87 
     88 	pinfo = 0;
     89 	(void)fprintf(stderr, "%s => %s %llu/%llu bytes %d%% written\n",
     90 	    fi->from, fi->to, (unsigned long long)written,
     91 	    (unsigned long long)fi->size, pcent);
     92 }
     93 
     94 int
     95 copy_file(FTSENT *entp, int dne)
     96 {
     97 	static char buf[MAXBSIZE];
     98 	struct stat to_stat, *fs;
     99 	int ch, checkch, from_fd, rcount, rval, to_fd, tolnk, wcount;
    100 	char *p;
    101 	off_t ptotal = 0;
    102 
    103 	/* if hard linking then simply link and return */
    104 	if (lflag) {
    105 		(void)unlink(to.p_path);
    106 		if (link(entp->fts_path, to.p_path)) {
    107 			warn("%s", to.p_path);
    108 			return (1);
    109 		}
    110 		return (0);
    111 	}
    112 
    113 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
    114 		warn("%s", entp->fts_path);
    115 		return (1);
    116 	}
    117 
    118 	to_fd = -1;
    119 	fs = entp->fts_statp;
    120 	tolnk = ((Rflag && !(Lflag || Hflag)) || Pflag);
    121 
    122 	/*
    123 	 * If the file exists and we're interactive, verify with the user.
    124 	 * If the file DNE, set the mode to be the from file, minus setuid
    125 	 * bits, modified by the umask; arguably wrong, but it makes copying
    126 	 * executables work right and it's been that way forever.  (The
    127 	 * other choice is 666 or'ed with the execute bits on the from file
    128 	 * modified by the umask.)
    129 	 */
    130 	if (!dne) {
    131 		struct stat sb;
    132 		int sval;
    133 
    134 		if (iflag) {
    135 			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
    136 			checkch = ch = getchar();
    137 			while (ch != '\n' && ch != EOF)
    138 				ch = getchar();
    139 			if (checkch != 'y' && checkch != 'Y') {
    140 				(void)close(from_fd);
    141 				return (0);
    142 			}
    143 		}
    144 
    145 		sval = tolnk ?
    146 			lstat(to.p_path, &sb) : stat(to.p_path, &sb);
    147 		if (sval == -1) {
    148 			warn("stat: %s", to.p_path);
    149 			(void)close(from_fd);
    150 			return (1);
    151 		}
    152 
    153 		if (!(tolnk && S_ISLNK(sb.st_mode)))
    154 			to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
    155 	} else
    156 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
    157 		    fs->st_mode & ~(S_ISUID | S_ISGID));
    158 
    159 	if (to_fd == -1 && (fflag || tolnk)) {
    160 		/*
    161 		 * attempt to remove existing destination file name and
    162 		 * create a new file
    163 		 */
    164 		(void)unlink(to.p_path);
    165 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
    166 			     fs->st_mode & ~(S_ISUID | S_ISGID));
    167 	}
    168 
    169 	if (to_fd == -1) {
    170 		warn("%s", to.p_path);
    171 		(void)close(from_fd);
    172 		return (1);
    173 	}
    174 
    175 	rval = 0;
    176 
    177 	/*
    178 	 * There's no reason to do anything other than close the file
    179 	 * now if it's regular and empty, so let's not bother.
    180 	 */
    181 	bool need_copy = !S_ISREG(fs->st_mode) || fs->st_size > 0;
    182 
    183 	struct finfo fi;
    184 
    185 	fi.from = entp->fts_path;
    186 	fi.to = to.p_path;
    187 	fi.size = fs->st_size;
    188 
    189 	/*
    190 	 * Mmap and write if less than 8M (the limit is so
    191 	 * we don't totally trash memory on big files).
    192 	 * This is really a minor hack, but it wins some CPU back.
    193 	 */
    194 	if (S_ISREG(fs->st_mode) && fs->st_size && fs->st_size <= MMAP_MAX_SIZE) {
    195 		size_t fsize = (size_t)fs->st_size;
    196 		p = mmap(NULL, fsize, PROT_READ, MAP_FILE|MAP_SHARED,
    197 		    from_fd, (off_t)0);
    198 		if (p != MAP_FAILED) {
    199 			size_t remainder;
    200 
    201 			need_copy = false;
    202 
    203 			(void) madvise(p, (size_t)fs->st_size, MADV_SEQUENTIAL);
    204 
    205 			/*
    206 			 * Write out the data in small chunks to
    207 			 * avoid locking the output file for a
    208 			 * long time if the reading the data from
    209 			 * the source is slow.
    210 			 */
    211 			remainder = fsize;
    212 			do {
    213 				ssize_t chunk;
    214 
    215 				chunk = (remainder > MMAP_MAX_WRITE) ?
    216 				    MMAP_MAX_WRITE : remainder;
    217 				if (write(to_fd, &p[fsize - remainder],
    218 				    chunk) != chunk) {
    219 					warn("%s", to.p_path);
    220 					rval = 1;
    221 					break;
    222 				}
    223 				remainder -= chunk;
    224 				ptotal += chunk;
    225 				if (pinfo)
    226 					progress(&fi, ptotal);
    227 			} while (remainder > 0);
    228 
    229 			if (munmap(p, fsize) < 0) {
    230 				warn("%s", entp->fts_path);
    231 				rval = 1;
    232 			}
    233 		}
    234 	}
    235 
    236 	if (need_copy) {
    237 		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
    238 			wcount = write(to_fd, buf, (size_t)rcount);
    239 			if (rcount != wcount || wcount == -1) {
    240 				warn("%s", to.p_path);
    241 				rval = 1;
    242 				break;
    243 			}
    244 			ptotal += wcount;
    245 			if (pinfo)
    246 				progress(&fi, ptotal);
    247 		}
    248 		if (rcount < 0) {
    249 			warn("%s", entp->fts_path);
    250 			rval = 1;
    251 		}
    252 	}
    253 
    254 	if (pflag && (fcpxattr(from_fd, to_fd) != 0))
    255 		warn("%s: error copying extended attributes", to.p_path);
    256 
    257 	(void)close(from_fd);
    258 
    259 	if (rval == 1) {
    260 		(void)close(to_fd);
    261 		return (1);
    262 	}
    263 
    264 	if (pflag && setfile(fs, to_fd))
    265 		rval = 1;
    266 	/*
    267 	 * If the source was setuid or setgid, lose the bits unless the
    268 	 * copy is owned by the same user and group.
    269 	 */
    270 #define	RETAINBITS \
    271 	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
    272 	if (!pflag && dne
    273 	    && fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
    274 		if (fstat(to_fd, &to_stat)) {
    275 			warn("%s", to.p_path);
    276 			rval = 1;
    277 		} else if (fs->st_gid == to_stat.st_gid &&
    278 		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
    279 			warn("%s", to.p_path);
    280 			rval = 1;
    281 		}
    282 	}
    283 	if (close(to_fd)) {
    284 		warn("%s", to.p_path);
    285 		rval = 1;
    286 	}
    287 	/* set the mod/access times now after close of the fd */
    288 	if (pflag && set_utimes(to.p_path, fs)) {
    289 	    rval = 1;
    290 	}
    291 	return (rval);
    292 }
    293 
    294 int
    295 copy_link(FTSENT *p, int exists)
    296 {
    297 	int len;
    298 	char target[MAXPATHLEN];
    299 
    300 	if ((len = readlink(p->fts_path, target, sizeof(target)-1)) == -1) {
    301 		warn("readlink: %s", p->fts_path);
    302 		return (1);
    303 	}
    304 	target[len] = '\0';
    305 	if (exists && unlink(to.p_path)) {
    306 		warn("unlink: %s", to.p_path);
    307 		return (1);
    308 	}
    309 	if (symlink(target, to.p_path)) {
    310 		warn("symlink: %s", target);
    311 		return (1);
    312 	}
    313 	return (pflag ? setfile(p->fts_statp, 0) : 0);
    314 }
    315 
    316 int
    317 copy_fifo(struct stat *from_stat, int exists)
    318 {
    319 	if (exists && unlink(to.p_path)) {
    320 		warn("unlink: %s", to.p_path);
    321 		return (1);
    322 	}
    323 	if (mkfifo(to.p_path, from_stat->st_mode)) {
    324 		warn("mkfifo: %s", to.p_path);
    325 		return (1);
    326 	}
    327 	return (pflag ? setfile(from_stat, 0) : 0);
    328 }
    329 
    330 int
    331 copy_special(struct stat *from_stat, int exists)
    332 {
    333 	if (exists && unlink(to.p_path)) {
    334 		warn("unlink: %s", to.p_path);
    335 		return (1);
    336 	}
    337 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
    338 		warn("mknod: %s", to.p_path);
    339 		return (1);
    340 	}
    341 	return (pflag ? setfile(from_stat, 0) : 0);
    342 }
    343 
    344 
    345 /*
    346  * Function: setfile
    347  *
    348  * Purpose:
    349  *   Set the owner/group/permissions for the "to" file to the information
    350  *   in the stat structure.  If fd is zero, also call set_utimes() to set
    351  *   the mod/access times.  If fd is non-zero, the caller must do a utimes
    352  *   itself after close(fd).
    353  */
    354 int
    355 setfile(struct stat *fs, int fd)
    356 {
    357 	int rval, islink;
    358 
    359 	rval = 0;
    360 	islink = S_ISLNK(fs->st_mode);
    361 	fs->st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
    362 
    363 	/*
    364 	 * Changing the ownership probably won't succeed, unless we're root
    365 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
    366 	 * the mode; current BSD behavior is to remove all setuid bits on
    367 	 * chown.  If chown fails, lose setuid/setgid bits.
    368 	 */
    369 	if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
    370 	    lchown(to.p_path, fs->st_uid, fs->st_gid)) {
    371 		if (errno != EPERM) {
    372 			warn("chown: %s", to.p_path);
    373 			rval = 1;
    374 		}
    375 		fs->st_mode &= ~(S_ISUID | S_ISGID);
    376 	}
    377 	if (fd ? fchmod(fd, fs->st_mode) : lchmod(to.p_path, fs->st_mode)) {
    378 		warn("chmod: %s", to.p_path);
    379 		rval = 1;
    380 	}
    381 
    382 	if (!islink && !Nflag) {
    383 		unsigned long fflags = fs->st_flags;
    384 		/*
    385 		 * XXX
    386 		 * NFS doesn't support chflags; ignore errors unless
    387 		 * there's reason to believe we're losing bits.
    388 		 * (Note, this still won't be right if the server
    389 		 * supports flags and we were trying to *remove* flags
    390 		 * on a file that we copied, i.e., that we didn't create.)
    391 		 */
    392 		errno = 0;
    393 		if ((fd ? fchflags(fd, fflags) :
    394 		    chflags(to.p_path, fflags)) == -1)
    395 			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
    396 				warn("chflags: %s", to.p_path);
    397 				rval = 1;
    398 			}
    399 	}
    400 	/* if fd is non-zero, caller must call set_utimes() after close() */
    401 	if (fd == 0 && set_utimes(to.p_path, fs))
    402 	    rval = 1;
    403 	return (rval);
    404 }
    405 
    406 void
    407 usage(void)
    408 {
    409 	(void)fprintf(stderr,
    410 	    "usage: %s [-R [-H | -L | -P]] [-f | -i] [-alNpv] src target\n"
    411 	    "       %s [-R [-H | -L | -P]] [-f | -i] [-alNpv] src1 ... srcN directory\n",
    412 	    getprogname(), getprogname());
    413 	exit(1);
    414 	/* NOTREACHED */
    415 }
    416