Home | History | Annotate | Line # | Download | only in mv
mv.c revision 1.43.22.2
      1 /* $NetBSD: mv.c,v 1.43.22.2 2016/03/06 18:40:09 martin Exp $ */
      2 
      3 /*
      4  * Copyright (c) 1989, 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  * Ken Smith of The State University of New York at Buffalo.
      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("@(#) Copyright (c) 1989, 1993, 1994\
     38  The Regents of the University of California.  All rights reserved.");
     39 #endif /* not lint */
     40 
     41 #ifndef lint
     42 #if 0
     43 static char sccsid[] = "@(#)mv.c	8.2 (Berkeley) 4/2/94";
     44 #else
     45 __RCSID("$NetBSD: mv.c,v 1.43.22.2 2016/03/06 18:40:09 martin Exp $");
     46 #endif
     47 #endif /* not lint */
     48 
     49 #include <sys/param.h>
     50 #include <sys/time.h>
     51 #include <sys/wait.h>
     52 #include <sys/stat.h>
     53 #include <sys/extattr.h>
     54 
     55 #include <err.h>
     56 #include <errno.h>
     57 #include <fcntl.h>
     58 #include <grp.h>
     59 #include <locale.h>
     60 #include <pwd.h>
     61 #include <stdio.h>
     62 #include <stdlib.h>
     63 #include <string.h>
     64 #include <unistd.h>
     65 
     66 #include "pathnames.h"
     67 
     68 static int fflg, iflg, vflg;
     69 static int stdin_ok;
     70 static sig_atomic_t pinfo;
     71 
     72 static int	copy(char *, char *);
     73 static int	do_move(char *, char *);
     74 static int	fastcopy(char *, char *, struct stat *);
     75 __dead static void	usage(void);
     76 
     77 static void
     78 progress(int sig __unused)
     79 {
     80 
     81 	pinfo++;
     82 }
     83 
     84 int
     85 main(int argc, char *argv[])
     86 {
     87 	int ch, len, rval;
     88 	char *p, *endp;
     89 	struct stat sb;
     90 	char path[MAXPATHLEN + 1];
     91 	size_t baselen;
     92 
     93 	setprogname(argv[0]);
     94 	(void)setlocale(LC_ALL, "");
     95 
     96 	while ((ch = getopt(argc, argv, "ifv")) != -1)
     97 		switch (ch) {
     98 		case 'i':
     99 			fflg = 0;
    100 			iflg = 1;
    101 			break;
    102 		case 'f':
    103 			iflg = 0;
    104 			fflg = 1;
    105 			break;
    106 		case 'v':
    107 			vflg = 1;
    108 			break;
    109 		default:
    110 			usage();
    111 		}
    112 	argc -= optind;
    113 	argv += optind;
    114 
    115 	if (argc < 2)
    116 		usage();
    117 
    118 	stdin_ok = isatty(STDIN_FILENO);
    119 
    120 	(void)signal(SIGINFO, progress);
    121 
    122 	/*
    123 	 * If the stat on the target fails or the target isn't a directory,
    124 	 * try the move.  More than 2 arguments is an error in this case.
    125 	 */
    126 	if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
    127 		if (argc > 2)
    128 			usage();
    129 		exit(do_move(argv[0], argv[1]));
    130 	}
    131 
    132 	/* It's a directory, move each file into it. */
    133 	baselen = strlcpy(path, argv[argc - 1], sizeof(path));
    134 	if (baselen >= sizeof(path))
    135 		errx(1, "%s: destination pathname too long", argv[argc - 1]);
    136 	endp = &path[baselen];
    137 	if (!baselen || *(endp - 1) != '/') {
    138 		*endp++ = '/';
    139 		++baselen;
    140 	}
    141 	for (rval = 0; --argc; ++argv) {
    142 		p = *argv + strlen(*argv) - 1;
    143 		while (*p == '/' && p != *argv)
    144 			*p-- = '\0';
    145 		if ((p = strrchr(*argv, '/')) == NULL)
    146 			p = *argv;
    147 		else
    148 			++p;
    149 
    150 		if ((baselen + (len = strlen(p))) >= MAXPATHLEN) {
    151 			warnx("%s: destination pathname too long", *argv);
    152 			rval = 1;
    153 		} else {
    154 			memmove(endp, p, len + 1);
    155 			if (do_move(*argv, path))
    156 				rval = 1;
    157 		}
    158 	}
    159 	exit(rval);
    160 	/* NOTREACHED */
    161 }
    162 
    163 static int
    164 do_move(char *from, char *to)
    165 {
    166 	struct stat sb;
    167 	char modep[15];
    168 
    169 	/*
    170 	 * (1)	If the destination path exists, the -f option is not specified
    171 	 *	and either of the following conditions are true:
    172 	 *
    173 	 *	(a) The permissions of the destination path do not permit
    174 	 *	    writing and the standard input is a terminal.
    175 	 *	(b) The -i option is specified.
    176 	 *
    177 	 *	the mv utility shall write a prompt to standard error and
    178 	 *	read a line from standard input.  If the response is not
    179 	 *	affirmative, mv shall do nothing more with the current
    180 	 *	source file...
    181 	 */
    182 	if (!fflg && !access(to, F_OK)) {
    183 		int ask = 1;
    184 		int ch;
    185 
    186 		if (iflg) {
    187 			if (access(from, F_OK)) {
    188 				warn("rename %s", from);
    189 				return (1);
    190 			}
    191 			(void)fprintf(stderr, "overwrite %s? ", to);
    192 		} else if (stdin_ok && access(to, W_OK) && !stat(to, &sb)) {
    193 			if (access(from, F_OK)) {
    194 				warn("rename %s", from);
    195 				return (1);
    196 			}
    197 			strmode(sb.st_mode, modep);
    198 			(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
    199 			    modep + 1, modep[9] == ' ' ? "" : " ",
    200 			    user_from_uid(sb.st_uid, 0),
    201 			    group_from_gid(sb.st_gid, 0), to);
    202 		} else
    203 			ask = 0;
    204 		if (ask) {
    205 			if ((ch = getchar()) != EOF && ch != '\n') {
    206 				int ch2;
    207 				while ((ch2 = getchar()) != EOF && ch2 != '\n')
    208 					continue;
    209 			}
    210 			if (ch != 'y' && ch != 'Y')
    211 				return (0);
    212 		}
    213 	}
    214 
    215 	/*
    216 	 * (2)	If rename() succeeds, mv shall do nothing more with the
    217 	 *	current source file.  If it fails for any other reason than
    218 	 *	EXDEV, mv shall write a diagnostic message to the standard
    219 	 *	error and do nothing more with the current source file.
    220 	 *
    221 	 * (3)	If the destination path exists, and it is a file of type
    222 	 *	directory and source_file is not a file of type directory,
    223 	 *	or it is a file not of type directory, and source file is
    224 	 *	a file of type directory, mv shall write a diagnostic
    225 	 *	message to standard error, and do nothing more with the
    226 	 *	current source file...
    227 	 */
    228 	if (!rename(from, to)) {
    229 		if (vflg)
    230 			printf("%s -> %s\n", from, to);
    231 		return (0);
    232 	}
    233 
    234 	if (errno != EXDEV) {
    235 		warn("rename %s to %s", from, to);
    236 		return (1);
    237 	}
    238 
    239 	/*
    240 	 * (4)	If the destination path exists, mv shall attempt to remove it.
    241 	 *	If this fails for any reason, mv shall write a diagnostic
    242 	 *	message to the standard error and do nothing more with the
    243 	 *	current source file...
    244 	 */
    245 	if (!lstat(to, &sb)) {
    246 		if ((S_ISDIR(sb.st_mode)) ? rmdir(to) : unlink(to)) {
    247 			warn("can't remove %s", to);
    248 			return (1);
    249 		}
    250 	}
    251 
    252 	/*
    253 	 * (5)	The file hierarchy rooted in source_file shall be duplicated
    254 	 *	as a file hierarchy rooted in the destination path...
    255 	 */
    256 	if (lstat(from, &sb)) {
    257 		warn("%s", from);
    258 		return (1);
    259 	}
    260 
    261 	return (S_ISREG(sb.st_mode) ?
    262 	    fastcopy(from, to, &sb) : copy(from, to));
    263 }
    264 
    265 static int
    266 fastcopy(char *from, char *to, struct stat *sbp)
    267 {
    268 #if defined(__NetBSD__)
    269 	struct timespec ts[2];
    270 #else
    271 	struct timeval tval[2];
    272 #endif
    273 	static blksize_t blen;
    274 	static char *bp;
    275 	int from_fd, to_fd;
    276 	ssize_t nread;
    277 	off_t total = 0;
    278 
    279 	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
    280 		warn("%s", from);
    281 		return (1);
    282 	}
    283 	if ((to_fd =
    284 	    open(to, O_CREAT | O_TRUNC | O_WRONLY, sbp->st_mode)) < 0) {
    285 		warn("%s", to);
    286 		(void)close(from_fd);
    287 		return (1);
    288 	}
    289 	if (!blen && !(bp = malloc(blen = sbp->st_blksize))) {
    290 		warn(NULL);
    291 		blen = 0;
    292 		(void)close(from_fd);
    293 		(void)close(to_fd);
    294 		return (1);
    295 	}
    296 	while ((nread = read(from_fd, bp, blen)) > 0) {
    297 		if (write(to_fd, bp, nread) != nread) {
    298 			warn("%s", to);
    299 			goto err;
    300 		}
    301 		total += nread;
    302 		if (pinfo) {
    303 			int pcent = (int)((100.0 * total) / sbp->st_size);
    304 
    305 			pinfo = 0;
    306 			(void)fprintf(stderr, "%s => %s %llu/%llu bytes %d%% "
    307 			    "written\n", from, to, (unsigned long long)total,
    308 			    (unsigned long long)sbp->st_size, pcent);
    309 		}
    310 	}
    311 	if (nread < 0) {
    312 		warn("%s", from);
    313 err:		if (unlink(to))
    314 			warn("%s: remove", to);
    315 		(void)close(from_fd);
    316 		(void)close(to_fd);
    317 		return (1);
    318 	}
    319 
    320 	if (fcpxattr(from_fd, to_fd) == -1)
    321 		warn("%s: error copying extended attributes", to);
    322 
    323 	(void)close(from_fd);
    324 #ifdef BSD4_4
    325 #if defined(__NetBSD__)
    326 	ts[0] = sbp->st_atimespec;
    327 	ts[1] = sbp->st_mtimespec;
    328 #else
    329 	TIMESPEC_TO_TIMEVAL(&tval[0], &sbp->st_atimespec);
    330 	TIMESPEC_TO_TIMEVAL(&tval[1], &sbp->st_mtimespec);
    331 #endif
    332 #else
    333 	tval[0].tv_sec = sbp->st_atime;
    334 	tval[1].tv_sec = sbp->st_mtime;
    335 	tval[0].tv_usec = 0;
    336 	tval[1].tv_usec = 0;
    337 #endif
    338 #ifdef __SVR4
    339 	if (utimes(to, tval))
    340 #else
    341 #if defined(__NetBSD__)
    342 	if (futimens(to_fd, ts))
    343 #else
    344 	if (futimes(to_fd, tval))
    345 #endif
    346 #endif
    347 		warn("%s: set times", to);
    348 	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
    349 		if (errno != EPERM)
    350 			warn("%s: set owner/group", to);
    351 		sbp->st_mode &= ~(S_ISUID | S_ISGID);
    352 	}
    353 	if (fchmod(to_fd, sbp->st_mode))
    354 		warn("%s: set mode", to);
    355 	if (fchflags(to_fd, sbp->st_flags) && (errno != EOPNOTSUPP))
    356 		warn("%s: set flags (was: 0%07o)", to, sbp->st_flags);
    357 
    358 	if (close(to_fd)) {
    359 		warn("%s", to);
    360 		return (1);
    361 	}
    362 
    363 	if (unlink(from)) {
    364 		warn("%s: remove", from);
    365 		return (1);
    366 	}
    367 
    368 	if (vflg)
    369 		printf("%s -> %s\n", from, to);
    370 
    371 	return (0);
    372 }
    373 
    374 static int
    375 copy(char *from, char *to)
    376 {
    377 	pid_t pid;
    378 	int status;
    379 
    380 	if ((pid = vfork()) == 0) {
    381 		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", "--", from, to, NULL);
    382 		warn("%s", _PATH_CP);
    383 		_exit(1);
    384 	}
    385 	if (waitpid(pid, &status, 0) == -1) {
    386 		warn("%s: waitpid", _PATH_CP);
    387 		return (1);
    388 	}
    389 	if (!WIFEXITED(status)) {
    390 		warnx("%s: did not terminate normally", _PATH_CP);
    391 		return (1);
    392 	}
    393 	if (WEXITSTATUS(status)) {
    394 		warnx("%s: terminated with %d (non-zero) status",
    395 		    _PATH_CP, WEXITSTATUS(status));
    396 		return (1);
    397 	}
    398 	if (!(pid = vfork())) {
    399 		execl(_PATH_RM, "mv", "-rf", "--", from, NULL);
    400 		warn("%s", _PATH_RM);
    401 		_exit(1);
    402 	}
    403 	if (waitpid(pid, &status, 0) == -1) {
    404 		warn("%s: waitpid", _PATH_RM);
    405 		return (1);
    406 	}
    407 	if (!WIFEXITED(status)) {
    408 		warnx("%s: did not terminate normally", _PATH_RM);
    409 		return (1);
    410 	}
    411 	if (WEXITSTATUS(status)) {
    412 		warnx("%s: terminated with %d (non-zero) status",
    413 		    _PATH_RM, WEXITSTATUS(status));
    414 		return (1);
    415 	}
    416 	return (0);
    417 }
    418 
    419 static void
    420 usage(void)
    421 {
    422 	(void)fprintf(stderr, "usage: %s [-fiv] source target\n"
    423 	    "       %s [-fiv] source ... directory\n", getprogname(),
    424 	    getprogname());
    425 	exit(1);
    426 	/* NOTREACHED */
    427 }
    428