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