mv.c revision 196841
1/*-
2 * Copyright (c) 1989, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Ken Smith of The State University of New York at Buffalo.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#if 0
34#ifndef lint
35static char const copyright[] =
36"@(#) Copyright (c) 1989, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41static char sccsid[] = "@(#)mv.c	8.2 (Berkeley) 4/2/94";
42#endif /* not lint */
43#endif
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/bin/mv/mv.c 196841 2009-09-04 21:49:37Z trasz $");
46
47#include <sys/types.h>
48#include <sys/acl.h>
49#include <sys/param.h>
50#include <sys/time.h>
51#include <sys/wait.h>
52#include <sys/stat.h>
53#include <sys/mount.h>
54
55#include <err.h>
56#include <errno.h>
57#include <fcntl.h>
58#include <grp.h>
59#include <limits.h>
60#include <paths.h>
61#include <pwd.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <sysexits.h>
66#include <unistd.h>
67
68/* Exit code for a failed exec. */
69#define EXEC_FAILED 127
70
71int fflg, iflg, nflg, vflg;
72
73static int	copy(const char *, const char *);
74static int	do_move(const char *, const char *);
75static int	fastcopy(const char *, const char *, struct stat *);
76static void	usage(void);
77static void	preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
78		    const char *dest_path);
79
80int
81main(int argc, char *argv[])
82{
83	size_t baselen, len;
84	int rval;
85	char *p, *endp;
86	struct stat sb;
87	int ch;
88	char path[PATH_MAX];
89
90	while ((ch = getopt(argc, argv, "finv")) != -1)
91		switch (ch) {
92		case 'i':
93			iflg = 1;
94			fflg = nflg = 0;
95			break;
96		case 'f':
97			fflg = 1;
98			iflg = nflg = 0;
99			break;
100		case 'n':
101			nflg = 1;
102			fflg = iflg = 0;
103			break;
104		case 'v':
105			vflg = 1;
106			break;
107		default:
108			usage();
109		}
110	argc -= optind;
111	argv += optind;
112
113	if (argc < 2)
114		usage();
115
116	/*
117	 * If the stat on the target fails or the target isn't a directory,
118	 * try the move.  More than 2 arguments is an error in this case.
119	 */
120	if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
121		if (argc > 2)
122			usage();
123		exit(do_move(argv[0], argv[1]));
124	}
125
126	/* It's a directory, move each file into it. */
127	if (strlen(argv[argc - 1]) > sizeof(path) - 1)
128		errx(1, "%s: destination pathname too long", *argv);
129	(void)strcpy(path, argv[argc - 1]);
130	baselen = strlen(path);
131	endp = &path[baselen];
132	if (!baselen || *(endp - 1) != '/') {
133		*endp++ = '/';
134		++baselen;
135	}
136	for (rval = 0; --argc; ++argv) {
137		/*
138		 * Find the last component of the source pathname.  It
139		 * may have trailing slashes.
140		 */
141		p = *argv + strlen(*argv);
142		while (p != *argv && p[-1] == '/')
143			--p;
144		while (p != *argv && p[-1] != '/')
145			--p;
146
147		if ((baselen + (len = strlen(p))) >= PATH_MAX) {
148			warnx("%s: destination pathname too long", *argv);
149			rval = 1;
150		} else {
151			memmove(endp, p, (size_t)len + 1);
152			if (do_move(*argv, path))
153				rval = 1;
154		}
155	}
156	exit(rval);
157}
158
159static int
160do_move(const char *from, const char *to)
161{
162	struct stat sb;
163	int ask, ch, first;
164	char modep[15];
165
166	/*
167	 * Check access.  If interactive and file exists, ask user if it
168	 * should be replaced.  Otherwise if file exists but isn't writable
169	 * make sure the user wants to clobber it.
170	 */
171	if (!fflg && !access(to, F_OK)) {
172
173		/* prompt only if source exist */
174	        if (lstat(from, &sb) == -1) {
175			warn("%s", from);
176			return (1);
177		}
178
179#define YESNO "(y/n [n]) "
180		ask = 0;
181		if (nflg) {
182			if (vflg)
183				printf("%s not overwritten\n", to);
184			return (0);
185		} else if (iflg) {
186			(void)fprintf(stderr, "overwrite %s? %s", to, YESNO);
187			ask = 1;
188		} else if (access(to, W_OK) && !stat(to, &sb)) {
189			strmode(sb.st_mode, modep);
190			(void)fprintf(stderr, "override %s%s%s/%s for %s? %s",
191			    modep + 1, modep[9] == ' ' ? "" : " ",
192			    user_from_uid((unsigned long)sb.st_uid, 0),
193			    group_from_gid((unsigned long)sb.st_gid, 0), to, YESNO);
194			ask = 1;
195		}
196		if (ask) {
197			first = ch = getchar();
198			while (ch != '\n' && ch != EOF)
199				ch = getchar();
200			if (first != 'y' && first != 'Y') {
201				(void)fprintf(stderr, "not overwritten\n");
202				return (0);
203			}
204		}
205	}
206	/*
207	 * Rename on FreeBSD will fail with EISDIR and ENOTDIR, before failing
208	 * with EXDEV.  Therefore, copy() doesn't have to perform the checks
209	 * specified in the Step 3 of the POSIX mv specification.
210	 */
211	if (!rename(from, to)) {
212		if (vflg)
213			printf("%s -> %s\n", from, to);
214		return (0);
215	}
216
217	if (errno == EXDEV) {
218		struct statfs sfs;
219		char path[PATH_MAX];
220
221		/*
222		 * If the source is a symbolic link and is on another
223		 * filesystem, it can be recreated at the destination.
224		 */
225		if (lstat(from, &sb) == -1) {
226			warn("%s", from);
227			return (1);
228		}
229		if (!S_ISLNK(sb.st_mode)) {
230			/* Can't mv(1) a mount point. */
231			if (realpath(from, path) == NULL) {
232				warn("cannot resolve %s: %s", from, path);
233				return (1);
234			}
235			if (!statfs(path, &sfs) &&
236			    !strcmp(path, sfs.f_mntonname)) {
237				warnx("cannot rename a mount point");
238				return (1);
239			}
240		}
241	} else {
242		warn("rename %s to %s", from, to);
243		return (1);
244	}
245
246	/*
247	 * If rename fails because we're trying to cross devices, and
248	 * it's a regular file, do the copy internally; otherwise, use
249	 * cp and rm.
250	 */
251	if (lstat(from, &sb)) {
252		warn("%s", from);
253		return (1);
254	}
255	return (S_ISREG(sb.st_mode) ?
256	    fastcopy(from, to, &sb) : copy(from, to));
257}
258
259static int
260fastcopy(const char *from, const char *to, struct stat *sbp)
261{
262	struct timeval tval[2];
263	static u_int blen;
264	static char *bp;
265	mode_t oldmode;
266	int nread, from_fd, to_fd;
267
268	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
269		warn("%s", from);
270		return (1);
271	}
272	if (blen < sbp->st_blksize) {
273		if (bp != NULL)
274			free(bp);
275		if ((bp = malloc((size_t)sbp->st_blksize)) == NULL) {
276			blen = 0;
277			warnx("malloc failed");
278			return (1);
279		}
280		blen = sbp->st_blksize;
281	}
282	while ((to_fd =
283	    open(to, O_CREAT | O_EXCL | O_TRUNC | O_WRONLY, 0)) < 0) {
284		if (errno == EEXIST && unlink(to) == 0)
285			continue;
286		warn("%s", to);
287		(void)close(from_fd);
288		return (1);
289	}
290	while ((nread = read(from_fd, bp, (size_t)blen)) > 0)
291		if (write(to_fd, bp, (size_t)nread) != nread) {
292			warn("%s", to);
293			goto err;
294		}
295	if (nread < 0) {
296		warn("%s", from);
297err:		if (unlink(to))
298			warn("%s: remove", to);
299		(void)close(from_fd);
300		(void)close(to_fd);
301		return (1);
302	}
303
304	oldmode = sbp->st_mode & ALLPERMS;
305	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
306		warn("%s: set owner/group (was: %lu/%lu)", to,
307		    (u_long)sbp->st_uid, (u_long)sbp->st_gid);
308		if (oldmode & (S_ISUID | S_ISGID)) {
309			warnx(
310"%s: owner/group changed; clearing suid/sgid (mode was 0%03o)",
311			    to, oldmode);
312			sbp->st_mode &= ~(S_ISUID | S_ISGID);
313		}
314	}
315	if (fchmod(to_fd, sbp->st_mode))
316		warn("%s: set mode (was: 0%03o)", to, oldmode);
317	/*
318	 * POSIX 1003.2c states that if _POSIX_ACL_EXTENDED is in effect
319	 * for dest_file, then its ACLs shall reflect the ACLs of the
320	 * source_file.
321	 */
322	preserve_fd_acls(from_fd, to_fd, from, to);
323	(void)close(from_fd);
324	/*
325	 * XXX
326	 * NFS doesn't support chflags; ignore errors unless there's reason
327	 * to believe we're losing bits.  (Note, this still won't be right
328	 * if the server supports flags and we were trying to *remove* flags
329	 * on a file that we copied, i.e., that we didn't create.)
330	 */
331	errno = 0;
332	if (fchflags(to_fd, (u_long)sbp->st_flags))
333		if (errno != EOPNOTSUPP || sbp->st_flags != 0)
334			warn("%s: set flags (was: 0%07o)", to, sbp->st_flags);
335
336	tval[0].tv_sec = sbp->st_atime;
337	tval[1].tv_sec = sbp->st_mtime;
338	tval[0].tv_usec = tval[1].tv_usec = 0;
339	if (utimes(to, tval))
340		warn("%s: set times", to);
341
342	if (close(to_fd)) {
343		warn("%s", to);
344		return (1);
345	}
346
347	if (unlink(from)) {
348		warn("%s: remove", from);
349		return (1);
350	}
351	if (vflg)
352		printf("%s -> %s\n", from, to);
353	return (0);
354}
355
356static int
357copy(const char *from, const char *to)
358{
359	struct stat sb;
360	int pid, status;
361
362	if (lstat(to, &sb) == 0) {
363		/* Destination path exists. */
364		if (S_ISDIR(sb.st_mode)) {
365			if (rmdir(to) != 0) {
366				warn("rmdir %s", to);
367				return (1);
368			}
369		} else {
370			if (unlink(to) != 0) {
371				warn("unlink %s", to);
372				return (1);
373			}
374		}
375	} else if (errno != ENOENT) {
376		warn("%s", to);
377		return (1);
378	}
379
380	/* Copy source to destination. */
381	if (!(pid = vfork())) {
382		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", "--", from, to,
383		    (char *)NULL);
384		_exit(EXEC_FAILED);
385	}
386	if (waitpid(pid, &status, 0) == -1) {
387		warn("%s %s %s: waitpid", _PATH_CP, from, to);
388		return (1);
389	}
390	if (!WIFEXITED(status)) {
391		warnx("%s %s %s: did not terminate normally",
392		    _PATH_CP, from, to);
393		return (1);
394	}
395	switch (WEXITSTATUS(status)) {
396	case 0:
397		break;
398	case EXEC_FAILED:
399		warnx("%s %s %s: exec failed", _PATH_CP, from, to);
400		return (1);
401	default:
402		warnx("%s %s %s: terminated with %d (non-zero) status",
403		    _PATH_CP, from, to, WEXITSTATUS(status));
404		return (1);
405	}
406
407	/* Delete the source. */
408	if (!(pid = vfork())) {
409		execl(_PATH_RM, "mv", "-rf", "--", from, (char *)NULL);
410		_exit(EXEC_FAILED);
411	}
412	if (waitpid(pid, &status, 0) == -1) {
413		warn("%s %s: waitpid", _PATH_RM, from);
414		return (1);
415	}
416	if (!WIFEXITED(status)) {
417		warnx("%s %s: did not terminate normally", _PATH_RM, from);
418		return (1);
419	}
420	switch (WEXITSTATUS(status)) {
421	case 0:
422		break;
423	case EXEC_FAILED:
424		warnx("%s %s: exec failed", _PATH_RM, from);
425		return (1);
426	default:
427		warnx("%s %s: terminated with %d (non-zero) status",
428		    _PATH_RM, from, WEXITSTATUS(status));
429		return (1);
430	}
431	return (0);
432}
433
434static void
435preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
436    const char *dest_path)
437{
438	acl_t acl;
439	acl_type_t acl_type;
440	int acl_supported = 0, ret, trivial;
441
442	ret = fpathconf(source_fd, _PC_ACL_NFS4);
443	if (ret > 0 ) {
444		acl_supported = 1;
445		acl_type = ACL_TYPE_NFS4;
446	} else if (ret < 0 && errno != EINVAL) {
447		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s",
448		    source_path);
449		return;
450	}
451	if (acl_supported == 0) {
452		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
453		if (ret > 0 ) {
454			acl_supported = 1;
455			acl_type = ACL_TYPE_ACCESS;
456		} else if (ret < 0 && errno != EINVAL) {
457			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
458			    source_path);
459			return;
460		}
461	}
462	if (acl_supported == 0)
463		return;
464
465	acl = acl_get_fd_np(source_fd, acl_type);
466	if (acl == NULL) {
467		warn("failed to get acl entries for %s", source_path);
468		return;
469	}
470	if (acl_is_trivial_np(acl, &trivial)) {
471		warn("acl_is_trivial() failed for %s", source_path);
472		acl_free(acl);
473		return;
474	}
475	if (trivial) {
476		acl_free(acl);
477		return;
478	}
479	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
480		warn("failed to set acl entries for %s", dest_path);
481		acl_free(acl);
482		return;
483	}
484	acl_free(acl);
485}
486
487static void
488usage(void)
489{
490
491	(void)fprintf(stderr, "%s\n%s\n",
492		      "usage: mv [-f | -i | -n] [-v] source target",
493		      "       mv [-f | -i | -n] [-v] source ... directory");
494	exit(EX_USAGE);
495}
496