mv.c revision 303975
166458Sdfr/*-
266458Sdfr * Copyright (c) 1989, 1993, 1994
396912Smarcel *	The Regents of the University of California.  All rights reserved.
496912Smarcel *
5139790Simp * This code is derived from software contributed to Berkeley by
666458Sdfr * Ken Smith of The State University of New York at Buffalo.
766458Sdfr *
866458Sdfr * Redistribution and use in source and binary forms, with or without
966458Sdfr * modification, are permitted provided that the following conditions
1066458Sdfr * are met:
1166458Sdfr * 1. Redistributions of source code must retain the above copyright
1266458Sdfr *    notice, this list of conditions and the following disclaimer.
1366458Sdfr * 2. Redistributions in binary form must reproduce the above copyright
1466458Sdfr *    notice, this list of conditions and the following disclaimer in the
1566458Sdfr *    documentation and/or other materials provided with the distribution.
1666458Sdfr * 4. Neither the name of the University nor the names of its contributors
1766458Sdfr *    may be used to endorse or promote products derived from this software
1866458Sdfr *    without specific prior written permission.
1966458Sdfr *
2066458Sdfr * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2166458Sdfr * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2266458Sdfr * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2366458Sdfr * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2466458Sdfr * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2566458Sdfr * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2666458Sdfr * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2766458Sdfr * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2866458Sdfr * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2966458Sdfr * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3066458Sdfr * SUCH DAMAGE.
3166458Sdfr */
3266458Sdfr
3366458Sdfr#if 0
3466458Sdfr#ifndef lint
3566458Sdfrstatic char const copyright[] =
3666458Sdfr"@(#) Copyright (c) 1989, 1993, 1994\n\
3766458Sdfr	The Regents of the University of California.  All rights reserved.\n";
3866458Sdfr#endif /* not lint */
3966458Sdfr
4066458Sdfr#ifndef lint
4166458Sdfrstatic char sccsid[] = "@(#)mv.c	8.2 (Berkeley) 4/2/94";
4266458Sdfr#endif /* not lint */
4366458Sdfr#endif
4496912Smarcel#include <sys/cdefs.h>
4566458Sdfr__FBSDID("$FreeBSD: releng/11.0/bin/mv/mv.c 300643 2016-05-25 02:51:15Z truckman $");
4666458Sdfr
47170033Salc#include <sys/types.h>
48170033Salc#include <sys/acl.h>
4966458Sdfr#include <sys/param.h>
50115084Smarcel#include <sys/time.h>
5166458Sdfr#include <sys/wait.h>
5266458Sdfr#include <sys/stat.h>
5366458Sdfr#include <sys/mount.h>
5466458Sdfr
5566458Sdfr#include <err.h>
5666458Sdfr#include <errno.h>
5766458Sdfr#include <fcntl.h>
5866458Sdfr#include <grp.h>
5966458Sdfr#include <limits.h>
6066458Sdfr#include <paths.h>
6166458Sdfr#include <pwd.h>
6266458Sdfr#include <stdio.h>
6366458Sdfr#include <stdlib.h>
6466458Sdfr#include <string.h>
6566458Sdfr#include <sysexits.h>
6666458Sdfr#include <unistd.h>
6766458Sdfr
6892670Speter/* Exit code for a failed exec. */
6966458Sdfr#define EXEC_FAILED 127
7066458Sdfr
7166458Sdfrstatic int	fflg, hflg, iflg, nflg, vflg;
7266458Sdfr
7366458Sdfrstatic int	copy(const char *, const char *);
7466458Sdfrstatic int	do_move(const char *, const char *);
7566458Sdfrstatic int	fastcopy(const char *, const char *, struct stat *);
7666458Sdfrstatic void	usage(void);
7766458Sdfrstatic void	preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
7866458Sdfr		    const char *dest_path);
7966458Sdfr
8066458Sdfrint
8166458Sdfrmain(int argc, char *argv[])
8266458Sdfr{
8366458Sdfr	size_t baselen, len;
8466458Sdfr	int rval;
8566458Sdfr	char *p, *endp;
8666458Sdfr	struct stat sb;
8766458Sdfr	int ch;
8866458Sdfr	char path[PATH_MAX];
8966458Sdfr
9066458Sdfr	while ((ch = getopt(argc, argv, "fhinv")) != -1)
9166458Sdfr		switch (ch) {
9266458Sdfr		case 'h':
9366458Sdfr			hflg = 1;
9466458Sdfr			break;
9566458Sdfr		case 'i':
9666458Sdfr			iflg = 1;
9766458Sdfr			fflg = nflg = 0;
9866458Sdfr			break;
9966458Sdfr		case 'f':
10066458Sdfr			fflg = 1;
10166458Sdfr			iflg = nflg = 0;
102150008Salc			break;
10366458Sdfr		case 'n':
10466458Sdfr			nflg = 1;
10566458Sdfr			fflg = iflg = 0;
10666458Sdfr			break;
10766458Sdfr		case 'v':
10866458Sdfr			vflg = 1;
109106486Smarcel			break;
110106486Smarcel		default:
111106486Smarcel			usage();
112106486Smarcel		}
113106486Smarcel	argc -= optind;
114169291Salc	argv += optind;
115169291Salc
116169291Salc	if (argc < 2)
117169291Salc		usage();
118169291Salc
119170519Salc	/*
120170519Salc	 * If the stat on the target fails or the target isn't a directory,
121170519Salc	 * try the move.  More than 2 arguments is an error in this case.
122170519Salc	 */
123170519Salc	if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
124170519Salc		if (argc > 2)
125172317Salc			errx(1, "%s is not a directory", argv[argc - 1]);
126170519Salc		exit(do_move(argv[0], argv[1]));
127170519Salc	}
128170519Salc
129170519Salc	/*
130172317Salc	 * If -h was specified, treat the target as a symlink instead of
131172317Salc	 * directory.
132170519Salc	 */
133170519Salc	if (hflg) {
134170519Salc		if (argc > 2)
135170519Salc			usage();
136170519Salc		if (lstat(argv[1], &sb) == 0 && S_ISLNK(sb.st_mode))
137170519Salc			exit(do_move(argv[0], argv[1]));
138170519Salc	}
139170519Salc
140170519Salc	/* It's a directory, move each file into it. */
141170519Salc	if (strlen(argv[argc - 1]) > sizeof(path) - 1)
142170519Salc		errx(1, "%s: destination pathname too long", *argv);
143170519Salc	(void)strcpy(path, argv[argc - 1]);
144170519Salc	baselen = strlen(path);
145170519Salc	endp = &path[baselen];
146170519Salc	if (!baselen || *(endp - 1) != '/') {
147170519Salc		*endp++ = '/';
14896912Smarcel		++baselen;
14996912Smarcel	}
15096912Smarcel	for (rval = 0; --argc; ++argv) {
15196912Smarcel		/*
15296912Smarcel		 * Find the last component of the source pathname.  It
15396912Smarcel		 * may have trailing slashes.
15496912Smarcel		 */
15596912Smarcel		p = *argv + strlen(*argv);
15696912Smarcel		while (p != *argv && p[-1] == '/')
157119906Smarcel			--p;
158119906Smarcel		while (p != *argv && p[-1] != '/')
159119906Smarcel			--p;
160119906Smarcel
161119906Smarcel		if ((baselen + (len = strlen(p))) >= PATH_MAX) {
162119906Smarcel			warnx("%s: destination pathname too long", *argv);
163119906Smarcel			rval = 1;
164119906Smarcel		} else {
165119906Smarcel			memmove(endp, p, (size_t)len + 1);
166119906Smarcel			if (do_move(*argv, path))
167121268Smarcel				rval = 1;
168121268Smarcel		}
169119906Smarcel	}
17066458Sdfr	exit(rval);
17166458Sdfr}
17266458Sdfr
17366458Sdfrstatic int
17466458Sdfrdo_move(const char *from, const char *to)
175115084Smarcel{
176115084Smarcel	struct stat sb;
177115084Smarcel	int ask, ch, first;
178115084Smarcel	char modep[15];
17966458Sdfr
18066458Sdfr	/*
181115084Smarcel	 * Check access.  If interactive and file exists, ask user if it
18296912Smarcel	 * should be replaced.  Otherwise if file exists but isn't writable
18366458Sdfr	 * make sure the user wants to clobber it.
18466458Sdfr	 */
18566458Sdfr	if (!fflg && !access(to, F_OK)) {
18666458Sdfr
18766458Sdfr		/* prompt only if source exist */
18866458Sdfr	        if (lstat(from, &sb) == -1) {
18966458Sdfr			warn("%s", from);
190168920Ssepotvin			return (1);
191168920Ssepotvin		}
19266458Sdfr
19366458Sdfr#define YESNO "(y/n [n]) "
19466458Sdfr		ask = 0;
19566458Sdfr		if (nflg) {
19666458Sdfr			if (vflg)
19766458Sdfr				printf("%s not overwritten\n", to);
19866458Sdfr			return (0);
19966458Sdfr		} else if (iflg) {
20066458Sdfr			(void)fprintf(stderr, "overwrite %s? %s", to, YESNO);
20166458Sdfr			ask = 1;
20266458Sdfr		} else if (access(to, W_OK) && !stat(to, &sb) && isatty(STDIN_FILENO)) {
20396912Smarcel			strmode(sb.st_mode, modep);
204			(void)fprintf(stderr, "override %s%s%s/%s for %s? %s",
205			    modep + 1, modep[9] == ' ' ? "" : " ",
206			    user_from_uid((unsigned long)sb.st_uid, 0),
207			    group_from_gid((unsigned long)sb.st_gid, 0), to, YESNO);
208			ask = 1;
209		}
210		if (ask) {
211			first = ch = getchar();
212			while (ch != '\n' && ch != EOF)
213				ch = getchar();
214			if (first != 'y' && first != 'Y') {
215				(void)fprintf(stderr, "not overwritten\n");
216				return (0);
217			}
218		}
219	}
220	/*
221	 * Rename on FreeBSD will fail with EISDIR and ENOTDIR, before failing
222	 * with EXDEV.  Therefore, copy() doesn't have to perform the checks
223	 * specified in the Step 3 of the POSIX mv specification.
224	 */
225	if (!rename(from, to)) {
226		if (vflg)
227			printf("%s -> %s\n", from, to);
228		return (0);
229	}
230
231	if (errno == EXDEV) {
232		struct statfs sfs;
233		char path[PATH_MAX];
234
235		/*
236		 * If the source is a symbolic link and is on another
237		 * filesystem, it can be recreated at the destination.
238		 */
239		if (lstat(from, &sb) == -1) {
240			warn("%s", from);
241			return (1);
242		}
243		if (!S_ISLNK(sb.st_mode)) {
244			/* Can't mv(1) a mount point. */
245			if (realpath(from, path) == NULL) {
246				warn("cannot resolve %s: %s", from, path);
247				return (1);
248			}
249			if (!statfs(path, &sfs) &&
250			    !strcmp(path, sfs.f_mntonname)) {
251				warnx("cannot rename a mount point");
252				return (1);
253			}
254		}
255	} else {
256		warn("rename %s to %s", from, to);
257		return (1);
258	}
259
260	/*
261	 * If rename fails because we're trying to cross devices, and
262	 * it's a regular file, do the copy internally; otherwise, use
263	 * cp and rm.
264	 */
265	if (lstat(from, &sb)) {
266		warn("%s", from);
267		return (1);
268	}
269	return (S_ISREG(sb.st_mode) ?
270	    fastcopy(from, to, &sb) : copy(from, to));
271}
272
273static int
274fastcopy(const char *from, const char *to, struct stat *sbp)
275{
276	struct timespec ts[2];
277	static u_int blen = MAXPHYS;
278	static char *bp = NULL;
279	mode_t oldmode;
280	int nread, from_fd, to_fd;
281	struct stat tsb;
282
283	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
284		warn("fastcopy: open() failed (from): %s", from);
285		return (1);
286	}
287	if (bp == NULL && (bp = malloc((size_t)blen)) == NULL) {
288		warnx("malloc(%u) failed", blen);
289		(void)close(from_fd);
290		return (1);
291	}
292	while ((to_fd =
293	    open(to, O_CREAT | O_EXCL | O_TRUNC | O_WRONLY, 0)) < 0) {
294		if (errno == EEXIST && unlink(to) == 0)
295			continue;
296		warn("fastcopy: open() failed (to): %s", to);
297		(void)close(from_fd);
298		return (1);
299	}
300	while ((nread = read(from_fd, bp, (size_t)blen)) > 0)
301		if (write(to_fd, bp, (size_t)nread) != nread) {
302			warn("fastcopy: write() failed: %s", to);
303			goto err;
304		}
305	if (nread < 0) {
306		warn("fastcopy: read() failed: %s", from);
307err:		if (unlink(to))
308			warn("%s: remove", to);
309		(void)close(from_fd);
310		(void)close(to_fd);
311		return (1);
312	}
313
314	oldmode = sbp->st_mode & ALLPERMS;
315	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
316		warn("%s: set owner/group (was: %lu/%lu)", to,
317		    (u_long)sbp->st_uid, (u_long)sbp->st_gid);
318		if (oldmode & (S_ISUID | S_ISGID)) {
319			warnx(
320"%s: owner/group changed; clearing suid/sgid (mode was 0%03o)",
321			    to, oldmode);
322			sbp->st_mode &= ~(S_ISUID | S_ISGID);
323		}
324	}
325	if (fchmod(to_fd, sbp->st_mode))
326		warn("%s: set mode (was: 0%03o)", to, oldmode);
327	/*
328	 * POSIX 1003.2c states that if _POSIX_ACL_EXTENDED is in effect
329	 * for dest_file, then its ACLs shall reflect the ACLs of the
330	 * source_file.
331	 */
332	preserve_fd_acls(from_fd, to_fd, from, to);
333	(void)close(from_fd);
334	/*
335	 * XXX
336	 * NFS doesn't support chflags; ignore errors unless there's reason
337	 * to believe we're losing bits.  (Note, this still won't be right
338	 * if the server supports flags and we were trying to *remove* flags
339	 * on a file that we copied, i.e., that we didn't create.)
340	 */
341	if (fstat(to_fd, &tsb) == 0) {
342		if ((sbp->st_flags  & ~UF_ARCHIVE) !=
343		    (tsb.st_flags & ~UF_ARCHIVE)) {
344			if (fchflags(to_fd,
345			    sbp->st_flags | (tsb.st_flags & UF_ARCHIVE)))
346				if (errno != EOPNOTSUPP ||
347				    ((sbp->st_flags & ~UF_ARCHIVE) != 0))
348					warn("%s: set flags (was: 0%07o)",
349					    to, sbp->st_flags);
350		}
351	} else
352		warn("%s: cannot stat", to);
353
354	ts[0] = sbp->st_atim;
355	ts[1] = sbp->st_mtim;
356	if (futimens(to_fd, ts))
357		warn("%s: set times", to);
358
359	if (close(to_fd)) {
360		warn("%s", to);
361		return (1);
362	}
363
364	if (unlink(from)) {
365		warn("%s: remove", from);
366		return (1);
367	}
368	if (vflg)
369		printf("%s -> %s\n", from, to);
370	return (0);
371}
372
373static int
374copy(const char *from, const char *to)
375{
376	struct stat sb;
377	int pid, status;
378
379	if (lstat(to, &sb) == 0) {
380		/* Destination path exists. */
381		if (S_ISDIR(sb.st_mode)) {
382			if (rmdir(to) != 0) {
383				warn("rmdir %s", to);
384				return (1);
385			}
386		} else {
387			if (unlink(to) != 0) {
388				warn("unlink %s", to);
389				return (1);
390			}
391		}
392	} else if (errno != ENOENT) {
393		warn("%s", to);
394		return (1);
395	}
396
397	/* Copy source to destination. */
398	if (!(pid = vfork())) {
399		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", "--", from, to,
400		    (char *)NULL);
401		_exit(EXEC_FAILED);
402	}
403	if (waitpid(pid, &status, 0) == -1) {
404		warn("%s %s %s: waitpid", _PATH_CP, from, to);
405		return (1);
406	}
407	if (!WIFEXITED(status)) {
408		warnx("%s %s %s: did not terminate normally",
409		    _PATH_CP, from, to);
410		return (1);
411	}
412	switch (WEXITSTATUS(status)) {
413	case 0:
414		break;
415	case EXEC_FAILED:
416		warnx("%s %s %s: exec failed", _PATH_CP, from, to);
417		return (1);
418	default:
419		warnx("%s %s %s: terminated with %d (non-zero) status",
420		    _PATH_CP, from, to, WEXITSTATUS(status));
421		return (1);
422	}
423
424	/* Delete the source. */
425	if (!(pid = vfork())) {
426		execl(_PATH_RM, "mv", "-rf", "--", from, (char *)NULL);
427		_exit(EXEC_FAILED);
428	}
429	if (waitpid(pid, &status, 0) == -1) {
430		warn("%s %s: waitpid", _PATH_RM, from);
431		return (1);
432	}
433	if (!WIFEXITED(status)) {
434		warnx("%s %s: did not terminate normally", _PATH_RM, from);
435		return (1);
436	}
437	switch (WEXITSTATUS(status)) {
438	case 0:
439		break;
440	case EXEC_FAILED:
441		warnx("%s %s: exec failed", _PATH_RM, from);
442		return (1);
443	default:
444		warnx("%s %s: terminated with %d (non-zero) status",
445		    _PATH_RM, from, WEXITSTATUS(status));
446		return (1);
447	}
448	return (0);
449}
450
451static void
452preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
453    const char *dest_path)
454{
455	acl_t acl;
456	acl_type_t acl_type;
457	int acl_supported = 0, ret, trivial;
458
459	ret = fpathconf(source_fd, _PC_ACL_NFS4);
460	if (ret > 0 ) {
461		acl_supported = 1;
462		acl_type = ACL_TYPE_NFS4;
463	} else if (ret < 0 && errno != EINVAL) {
464		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s",
465		    source_path);
466		return;
467	}
468	if (acl_supported == 0) {
469		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
470		if (ret > 0 ) {
471			acl_supported = 1;
472			acl_type = ACL_TYPE_ACCESS;
473		} else if (ret < 0 && errno != EINVAL) {
474			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
475			    source_path);
476			return;
477		}
478	}
479	if (acl_supported == 0)
480		return;
481
482	acl = acl_get_fd_np(source_fd, acl_type);
483	if (acl == NULL) {
484		warn("failed to get acl entries for %s", source_path);
485		return;
486	}
487	if (acl_is_trivial_np(acl, &trivial)) {
488		warn("acl_is_trivial() failed for %s", source_path);
489		acl_free(acl);
490		return;
491	}
492	if (trivial) {
493		acl_free(acl);
494		return;
495	}
496	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
497		warn("failed to set acl entries for %s", dest_path);
498		acl_free(acl);
499		return;
500	}
501	acl_free(acl);
502}
503
504static void
505usage(void)
506{
507
508	(void)fprintf(stderr, "%s\n%s\n",
509		      "usage: mv [-f | -i | -n] [-hv] source target",
510		      "       mv [-f | -i | -n] [-v] source ... directory");
511	exit(EX_USAGE);
512}
513