xref: /freebsd/bin/mv/mv.c (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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/param.h>
36 #include <sys/acl.h>
37 #include <sys/mount.h>
38 #include <sys/stat.h>
39 #include <sys/time.h>
40 #include <sys/wait.h>
41 
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <grp.h>
46 #include <limits.h>
47 #include <paths.h>
48 #include <pwd.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <sysexits.h>
53 #include <unistd.h>
54 
55 /* Exit code for a failed exec. */
56 #define EXEC_FAILED 127
57 
58 static int	fflg, hflg, iflg, nflg, vflg;
59 
60 static int	copy(const char *, const char *);
61 static int	do_move(const char *, const char *);
62 static int	fastcopy(const char *, const char *, struct stat *);
63 static void	usage(void);
64 static void	preserve_fd_acls(int, int, const char *, const char *);
65 
66 int
67 main(int argc, char *argv[])
68 {
69 	char path[PATH_MAX];
70 	struct stat sb;
71 	char *p, *endp;
72 	size_t baselen, len;
73 	int ch, rval;
74 
75 	while ((ch = getopt(argc, argv, "fhinv")) != -1)
76 		switch (ch) {
77 		case 'h':
78 			hflg = 1;
79 			break;
80 		case 'i':
81 			iflg = 1;
82 			fflg = nflg = 0;
83 			break;
84 		case 'f':
85 			fflg = 1;
86 			iflg = nflg = 0;
87 			break;
88 		case 'n':
89 			nflg = 1;
90 			fflg = iflg = 0;
91 			break;
92 		case 'v':
93 			vflg = 1;
94 			break;
95 		default:
96 			usage();
97 		}
98 	argc -= optind;
99 	argv += optind;
100 
101 	if (argc < 2)
102 		usage();
103 
104 	/*
105 	 * If the stat on the target fails or the target isn't a directory,
106 	 * try the move.  More than 2 arguments is an error in this case.
107 	 */
108 	if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
109 		if (argc > 2)
110 			errx(1, "%s is not a directory", argv[argc - 1]);
111 		exit(do_move(argv[0], argv[1]));
112 	}
113 
114 	/*
115 	 * If -h was specified, treat the target as a symlink instead of
116 	 * directory.
117 	 */
118 	if (hflg) {
119 		if (argc > 2)
120 			usage();
121 		if (lstat(argv[1], &sb) == 0 && S_ISLNK(sb.st_mode))
122 			exit(do_move(argv[0], argv[1]));
123 	}
124 
125 	/* It's a directory, move each file into it. */
126 	if (strlen(argv[argc - 1]) > sizeof(path) - 1)
127 		errx(1, "%s: destination pathname too long", *argv);
128 	(void)strcpy(path, argv[argc - 1]);
129 	baselen = strlen(path);
130 	endp = &path[baselen];
131 	if (!baselen || *(endp - 1) != '/') {
132 		*endp++ = '/';
133 		++baselen;
134 	}
135 	for (rval = 0; --argc; ++argv) {
136 		/*
137 		 * Find the last component of the source pathname.  It
138 		 * may have trailing slashes.
139 		 */
140 		p = *argv + strlen(*argv);
141 		while (p != *argv && p[-1] == '/')
142 			--p;
143 		while (p != *argv && p[-1] != '/')
144 			--p;
145 
146 		if ((baselen + (len = strlen(p))) >= PATH_MAX) {
147 			warnx("%s: destination pathname too long", *argv);
148 			rval = 1;
149 		} else {
150 			memmove(endp, p, (size_t)len + 1);
151 			if (do_move(*argv, path))
152 				rval = 1;
153 		}
154 	}
155 	exit(rval);
156 }
157 
158 static int
159 do_move(const char *from, const char *to)
160 {
161 	char path[PATH_MAX], modep[15];
162 	struct statfs sfs;
163 	struct stat sb;
164 	int ask, ch, first;
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 		/* prompt only if source exists */
173 		if (lstat(from, &sb) == -1) {
174 			warn("%s", from);
175 			return (1);
176 		}
177 
178 #define YESNO "(y/n [n]) "
179 		ask = 0;
180 		if (nflg) {
181 			if (vflg)
182 				printf("%s not overwritten\n", to);
183 			return (0);
184 		} else if (iflg) {
185 			(void)fprintf(stderr, "overwrite %s? %s", to, YESNO);
186 			ask = 1;
187 		} else if (access(to, W_OK) && !stat(to, &sb) && isatty(STDIN_FILENO)) {
188 			strmode(sb.st_mode, modep);
189 			(void)fprintf(stderr, "override %s%s%s/%s for %s? %s",
190 			    modep + 1, modep[9] == ' ' ? "" : " ",
191 			    user_from_uid((unsigned long)sb.st_uid, 0),
192 			    group_from_gid((unsigned long)sb.st_gid, 0), to, YESNO);
193 			ask = 1;
194 		}
195 		if (ask) {
196 			first = ch = getchar();
197 			while (ch != '\n' && ch != EOF)
198 				ch = getchar();
199 			if (first != 'y' && first != 'Y') {
200 				(void)fprintf(stderr, "not overwritten\n");
201 				return (0);
202 			}
203 		}
204 	}
205 	/*
206 	 * Rename on FreeBSD will fail with EISDIR and ENOTDIR, before failing
207 	 * with EXDEV.  Therefore, copy() doesn't have to perform the checks
208 	 * specified in the Step 3 of the POSIX mv specification.
209 	 */
210 	if (!rename(from, to)) {
211 		if (vflg)
212 			printf("%s -> %s\n", from, to);
213 		return (0);
214 	}
215 
216 	if (errno == EXDEV) {
217 		/*
218 		 * If the source is a symbolic link and is on another
219 		 * filesystem, it can be recreated at the destination.
220 		 */
221 		if (lstat(from, &sb) == -1) {
222 			warn("%s", from);
223 			return (1);
224 		}
225 		if (!S_ISLNK(sb.st_mode)) {
226 			/* Can't mv(1) a mount point. */
227 			if (realpath(from, path) == NULL) {
228 				warn("cannot resolve %s: %s", from, path);
229 				return (1);
230 			}
231 			if (!statfs(path, &sfs) &&
232 			    !strcmp(path, sfs.f_mntonname)) {
233 				warnx("cannot rename a mount point");
234 				return (1);
235 			}
236 		}
237 	} else {
238 		warn("rename %s to %s", from, to);
239 		return (1);
240 	}
241 
242 	/*
243 	 * If rename fails because we're trying to cross devices, and
244 	 * it's a regular file, do the copy internally; otherwise, use
245 	 * cp and rm.
246 	 */
247 	if (lstat(from, &sb)) {
248 		warn("%s", from);
249 		return (1);
250 	}
251 	return (S_ISREG(sb.st_mode) ?
252 	    fastcopy(from, to, &sb) : copy(from, to));
253 }
254 
255 static int
256 fastcopy(const char *from, const char *to, struct stat *sbp)
257 {
258 	struct timespec ts[2];
259 	struct stat tsb;
260 	static char *bp = NULL;
261 	static size_t blen = MAXPHYS;
262 	ssize_t nread;
263 	int from_fd, to_fd;
264 	mode_t oldmode;
265 
266 	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
267 		warn("fastcopy: open() failed (from): %s", from);
268 		return (1);
269 	}
270 	if (bp == NULL && (bp = malloc(blen)) == NULL) {
271 		warnx("malloc(%zu) failed", blen);
272 		(void)close(from_fd);
273 		return (1);
274 	}
275 	while ((to_fd =
276 	    open(to, O_CREAT | O_EXCL | O_TRUNC | O_WRONLY, 0)) < 0) {
277 		if (errno == EEXIST && unlink(to) == 0)
278 			continue;
279 		warn("fastcopy: open() failed (to): %s", to);
280 		(void)close(from_fd);
281 		return (1);
282 	}
283 	while ((nread = read(from_fd, bp, blen)) > 0)
284 		if (write(to_fd, bp, (size_t)nread) != nread) {
285 			warn("fastcopy: write() failed: %s", to);
286 			goto err;
287 		}
288 	if (nread < 0) {
289 		warn("fastcopy: read() failed: %s", from);
290 err:		if (unlink(to))
291 			warn("%s: remove", to);
292 		(void)close(from_fd);
293 		(void)close(to_fd);
294 		return (1);
295 	}
296 
297 	oldmode = sbp->st_mode & ALLPERMS;
298 	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
299 		warn("%s: set owner/group (was: %lu/%lu)", to,
300 		    (u_long)sbp->st_uid, (u_long)sbp->st_gid);
301 		if (oldmode & (S_ISUID | S_ISGID)) {
302 			warnx("%s: owner/group changed; "
303 			    "clearing suid/sgid (mode was 0%03o)",
304 			    to, oldmode);
305 			sbp->st_mode &= ~(S_ISUID | S_ISGID);
306 		}
307 	}
308 	if (fchmod(to_fd, sbp->st_mode))
309 		warn("%s: set mode (was: 0%03o)", to, oldmode);
310 	/*
311 	 * POSIX 1003.2c states that if _POSIX_ACL_EXTENDED is in effect
312 	 * for dest_file, then its ACLs shall reflect the ACLs of the
313 	 * source_file.
314 	 */
315 	preserve_fd_acls(from_fd, to_fd, from, to);
316 	(void)close(from_fd);
317 
318 	ts[0] = sbp->st_atim;
319 	ts[1] = sbp->st_mtim;
320 	if (futimens(to_fd, ts))
321 		warn("%s: set times", to);
322 
323 	/*
324 	 * XXX
325 	 * NFS doesn't support chflags; ignore errors unless there's reason
326 	 * to believe we're losing bits.  (Note, this still won't be right
327 	 * if the server supports flags and we were trying to *remove* flags
328 	 * on a file that we copied, i.e., that we didn't create.)
329 	 */
330 	if (fstat(to_fd, &tsb) == 0) {
331 		if ((sbp->st_flags  & ~UF_ARCHIVE) !=
332 		    (tsb.st_flags & ~UF_ARCHIVE)) {
333 			if (fchflags(to_fd,
334 			    sbp->st_flags | (tsb.st_flags & UF_ARCHIVE)))
335 				if (errno != EOPNOTSUPP ||
336 				    ((sbp->st_flags & ~UF_ARCHIVE) != 0))
337 					warn("%s: set flags (was: 0%07o)",
338 					    to, sbp->st_flags);
339 		}
340 	} else
341 		warn("%s: cannot stat", to);
342 
343 	if (close(to_fd)) {
344 		warn("%s", to);
345 		return (1);
346 	}
347 
348 	if (unlink(from)) {
349 		warn("%s: remove", from);
350 		return (1);
351 	}
352 	if (vflg)
353 		printf("%s -> %s\n", from, to);
354 	return (0);
355 }
356 
357 static int
358 copy(const char *from, const char *to)
359 {
360 	struct stat sb;
361 	int pid, status;
362 
363 	if (lstat(to, &sb) == 0) {
364 		/* Destination path exists. */
365 		if (S_ISDIR(sb.st_mode)) {
366 			if (rmdir(to) != 0) {
367 				warn("rmdir %s", to);
368 				return (1);
369 			}
370 		} else {
371 			if (unlink(to) != 0) {
372 				warn("unlink %s", to);
373 				return (1);
374 			}
375 		}
376 	} else if (errno != ENOENT) {
377 		warn("%s", to);
378 		return (1);
379 	}
380 
381 	/* Copy source to destination. */
382 	if (!(pid = vfork())) {
383 		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", "--", from, to,
384 		    (char *)NULL);
385 		_exit(EXEC_FAILED);
386 	}
387 	if (waitpid(pid, &status, 0) == -1) {
388 		warn("%s %s %s: waitpid", _PATH_CP, from, to);
389 		return (1);
390 	}
391 	if (!WIFEXITED(status)) {
392 		warnx("%s %s %s: did not terminate normally",
393 		    _PATH_CP, from, to);
394 		return (1);
395 	}
396 	switch (WEXITSTATUS(status)) {
397 	case 0:
398 		break;
399 	case EXEC_FAILED:
400 		warnx("%s %s %s: exec failed", _PATH_CP, from, to);
401 		return (1);
402 	default:
403 		warnx("%s %s %s: terminated with %d (non-zero) status",
404 		    _PATH_CP, from, to, WEXITSTATUS(status));
405 		return (1);
406 	}
407 
408 	/* Delete the source. */
409 	if (!(pid = vfork())) {
410 		execl(_PATH_RM, "mv", "-rf", "--", from, (char *)NULL);
411 		_exit(EXEC_FAILED);
412 	}
413 	if (waitpid(pid, &status, 0) == -1) {
414 		warn("%s %s: waitpid", _PATH_RM, from);
415 		return (1);
416 	}
417 	if (!WIFEXITED(status)) {
418 		warnx("%s %s: did not terminate normally", _PATH_RM, from);
419 		return (1);
420 	}
421 	switch (WEXITSTATUS(status)) {
422 	case 0:
423 		break;
424 	case EXEC_FAILED:
425 		warnx("%s %s: exec failed", _PATH_RM, from);
426 		return (1);
427 	default:
428 		warnx("%s %s: terminated with %d (non-zero) status",
429 		    _PATH_RM, from, WEXITSTATUS(status));
430 		return (1);
431 	}
432 	return (0);
433 }
434 
435 static void
436 preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
437     const char *dest_path)
438 {
439 	acl_t acl;
440 	acl_type_t acl_type;
441 	int acl_supported = 0, ret, trivial;
442 
443 	ret = fpathconf(source_fd, _PC_ACL_NFS4);
444 	if (ret > 0 ) {
445 		acl_supported = 1;
446 		acl_type = ACL_TYPE_NFS4;
447 	} else if (ret < 0 && errno != EINVAL) {
448 		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s",
449 		    source_path);
450 		return;
451 	}
452 	if (acl_supported == 0) {
453 		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
454 		if (ret > 0 ) {
455 			acl_supported = 1;
456 			acl_type = ACL_TYPE_ACCESS;
457 		} else if (ret < 0 && errno != EINVAL) {
458 			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
459 			    source_path);
460 			return;
461 		}
462 	}
463 	if (acl_supported == 0)
464 		return;
465 
466 	acl = acl_get_fd_np(source_fd, acl_type);
467 	if (acl == NULL) {
468 		warn("failed to get acl entries for %s", source_path);
469 		return;
470 	}
471 	if (acl_is_trivial_np(acl, &trivial)) {
472 		warn("acl_is_trivial() failed for %s", source_path);
473 		acl_free(acl);
474 		return;
475 	}
476 	if (trivial) {
477 		acl_free(acl);
478 		return;
479 	}
480 	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
481 		warn("failed to set acl entries for %s", dest_path);
482 		acl_free(acl);
483 		return;
484 	}
485 	acl_free(acl);
486 }
487 
488 static void
489 usage(void)
490 {
491 	(void)fprintf(stderr, "%s\n%s\n",
492 	    "usage: mv [-f | -i | -n] [-hv] source target",
493 	    "       mv [-f | -i | -n] [-v] source ... directory");
494 	exit(EX_USAGE);
495 }
496