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