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