xref: /freebsd/bin/mv/mv.c (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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 exist */
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 	static u_int blen = MAXPHYS;
266 	static char *bp = NULL;
267 	mode_t oldmode;
268 	int nread, from_fd, to_fd;
269 	struct stat tsb;
270 
271 	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
272 		warn("fastcopy: open() failed (from): %s", from);
273 		return (1);
274 	}
275 	if (bp == NULL && (bp = malloc((size_t)blen)) == NULL) {
276 		warnx("malloc(%u) failed", blen);
277 		(void)close(from_fd);
278 		return (1);
279 	}
280 	while ((to_fd =
281 	    open(to, O_CREAT | O_EXCL | O_TRUNC | O_WRONLY, 0)) < 0) {
282 		if (errno == EEXIST && unlink(to) == 0)
283 			continue;
284 		warn("fastcopy: open() failed (to): %s", to);
285 		(void)close(from_fd);
286 		return (1);
287 	}
288 	while ((nread = read(from_fd, bp, (size_t)blen)) > 0)
289 		if (write(to_fd, bp, (size_t)nread) != nread) {
290 			warn("fastcopy: write() failed: %s", to);
291 			goto err;
292 		}
293 	if (nread < 0) {
294 		warn("fastcopy: read() failed: %s", from);
295 err:		if (unlink(to))
296 			warn("%s: remove", to);
297 		(void)close(from_fd);
298 		(void)close(to_fd);
299 		return (1);
300 	}
301 
302 	oldmode = sbp->st_mode & ALLPERMS;
303 	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
304 		warn("%s: set owner/group (was: %lu/%lu)", to,
305 		    (u_long)sbp->st_uid, (u_long)sbp->st_gid);
306 		if (oldmode & (S_ISUID | S_ISGID)) {
307 			warnx(
308 "%s: owner/group changed; clearing suid/sgid (mode was 0%03o)",
309 			    to, oldmode);
310 			sbp->st_mode &= ~(S_ISUID | S_ISGID);
311 		}
312 	}
313 	if (fchmod(to_fd, sbp->st_mode))
314 		warn("%s: set mode (was: 0%03o)", to, oldmode);
315 	/*
316 	 * POSIX 1003.2c states that if _POSIX_ACL_EXTENDED is in effect
317 	 * for dest_file, then its ACLs shall reflect the ACLs of the
318 	 * source_file.
319 	 */
320 	preserve_fd_acls(from_fd, to_fd, from, to);
321 	(void)close(from_fd);
322 	/*
323 	 * XXX
324 	 * NFS doesn't support chflags; ignore errors unless there's reason
325 	 * to believe we're losing bits.  (Note, this still won't be right
326 	 * if the server supports flags and we were trying to *remove* flags
327 	 * on a file that we copied, i.e., that we didn't create.)
328 	 */
329 	if (fstat(to_fd, &tsb) == 0) {
330 		if ((sbp->st_flags  & ~UF_ARCHIVE) !=
331 		    (tsb.st_flags & ~UF_ARCHIVE)) {
332 			if (fchflags(to_fd,
333 			    sbp->st_flags | (tsb.st_flags & UF_ARCHIVE)))
334 				if (errno != EOPNOTSUPP ||
335 				    ((sbp->st_flags & ~UF_ARCHIVE) != 0))
336 					warn("%s: set flags (was: 0%07o)",
337 					    to, sbp->st_flags);
338 		}
339 	} else
340 		warn("%s: cannot stat", to);
341 
342 	ts[0] = sbp->st_atim;
343 	ts[1] = sbp->st_mtim;
344 	if (futimens(to_fd, ts))
345 		warn("%s: set times", to);
346 
347 	if (close(to_fd)) {
348 		warn("%s", to);
349 		return (1);
350 	}
351 
352 	if (unlink(from)) {
353 		warn("%s: remove", from);
354 		return (1);
355 	}
356 	if (vflg)
357 		printf("%s -> %s\n", from, to);
358 	return (0);
359 }
360 
361 static int
362 copy(const char *from, const char *to)
363 {
364 	struct stat sb;
365 	int pid, status;
366 
367 	if (lstat(to, &sb) == 0) {
368 		/* Destination path exists. */
369 		if (S_ISDIR(sb.st_mode)) {
370 			if (rmdir(to) != 0) {
371 				warn("rmdir %s", to);
372 				return (1);
373 			}
374 		} else {
375 			if (unlink(to) != 0) {
376 				warn("unlink %s", to);
377 				return (1);
378 			}
379 		}
380 	} else if (errno != ENOENT) {
381 		warn("%s", to);
382 		return (1);
383 	}
384 
385 	/* Copy source to destination. */
386 	if (!(pid = vfork())) {
387 		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", "--", from, to,
388 		    (char *)NULL);
389 		_exit(EXEC_FAILED);
390 	}
391 	if (waitpid(pid, &status, 0) == -1) {
392 		warn("%s %s %s: waitpid", _PATH_CP, from, to);
393 		return (1);
394 	}
395 	if (!WIFEXITED(status)) {
396 		warnx("%s %s %s: did not terminate normally",
397 		    _PATH_CP, from, to);
398 		return (1);
399 	}
400 	switch (WEXITSTATUS(status)) {
401 	case 0:
402 		break;
403 	case EXEC_FAILED:
404 		warnx("%s %s %s: exec failed", _PATH_CP, from, to);
405 		return (1);
406 	default:
407 		warnx("%s %s %s: terminated with %d (non-zero) status",
408 		    _PATH_CP, from, to, WEXITSTATUS(status));
409 		return (1);
410 	}
411 
412 	/* Delete the source. */
413 	if (!(pid = vfork())) {
414 		execl(_PATH_RM, "mv", "-rf", "--", from, (char *)NULL);
415 		_exit(EXEC_FAILED);
416 	}
417 	if (waitpid(pid, &status, 0) == -1) {
418 		warn("%s %s: waitpid", _PATH_RM, from);
419 		return (1);
420 	}
421 	if (!WIFEXITED(status)) {
422 		warnx("%s %s: did not terminate normally", _PATH_RM, from);
423 		return (1);
424 	}
425 	switch (WEXITSTATUS(status)) {
426 	case 0:
427 		break;
428 	case EXEC_FAILED:
429 		warnx("%s %s: exec failed", _PATH_RM, from);
430 		return (1);
431 	default:
432 		warnx("%s %s: terminated with %d (non-zero) status",
433 		    _PATH_RM, from, WEXITSTATUS(status));
434 		return (1);
435 	}
436 	return (0);
437 }
438 
439 static void
440 preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
441     const char *dest_path)
442 {
443 	acl_t acl;
444 	acl_type_t acl_type;
445 	int acl_supported = 0, ret, trivial;
446 
447 	ret = fpathconf(source_fd, _PC_ACL_NFS4);
448 	if (ret > 0 ) {
449 		acl_supported = 1;
450 		acl_type = ACL_TYPE_NFS4;
451 	} else if (ret < 0 && errno != EINVAL) {
452 		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s",
453 		    source_path);
454 		return;
455 	}
456 	if (acl_supported == 0) {
457 		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
458 		if (ret > 0 ) {
459 			acl_supported = 1;
460 			acl_type = ACL_TYPE_ACCESS;
461 		} else if (ret < 0 && errno != EINVAL) {
462 			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
463 			    source_path);
464 			return;
465 		}
466 	}
467 	if (acl_supported == 0)
468 		return;
469 
470 	acl = acl_get_fd_np(source_fd, acl_type);
471 	if (acl == NULL) {
472 		warn("failed to get acl entries for %s", source_path);
473 		return;
474 	}
475 	if (acl_is_trivial_np(acl, &trivial)) {
476 		warn("acl_is_trivial() failed for %s", source_path);
477 		acl_free(acl);
478 		return;
479 	}
480 	if (trivial) {
481 		acl_free(acl);
482 		return;
483 	}
484 	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
485 		warn("failed to set acl entries for %s", dest_path);
486 		acl_free(acl);
487 		return;
488 	}
489 	acl_free(acl);
490 }
491 
492 static void
493 usage(void)
494 {
495 
496 	(void)fprintf(stderr, "%s\n%s\n",
497 		      "usage: mv [-f | -i | -n] [-hv] source target",
498 		      "       mv [-f | -i | -n] [-v] source ... directory");
499 	exit(EX_USAGE);
500 }
501