xref: /freebsd/bin/mv/mv.c (revision 1719886f)
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 	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 	ts[0] = sbp->st_atim;
324 	ts[1] = sbp->st_mtim;
325 	if (futimens(to_fd, ts))
326 		warn("%s: set times", to);
327 
328 	/*
329 	 * XXX
330 	 * NFS doesn't support chflags; ignore errors unless there's reason
331 	 * to believe we're losing bits.  (Note, this still won't be right
332 	 * if the server supports flags and we were trying to *remove* flags
333 	 * on a file that we copied, i.e., that we didn't create.)
334 	 */
335 	if (fstat(to_fd, &tsb) == 0) {
336 		if ((sbp->st_flags  & ~UF_ARCHIVE) !=
337 		    (tsb.st_flags & ~UF_ARCHIVE)) {
338 			if (fchflags(to_fd,
339 			    sbp->st_flags | (tsb.st_flags & UF_ARCHIVE)))
340 				if (errno != EOPNOTSUPP ||
341 				    ((sbp->st_flags & ~UF_ARCHIVE) != 0))
342 					warn("%s: set flags (was: 0%07o)",
343 					    to, sbp->st_flags);
344 		}
345 	} else
346 		warn("%s: cannot stat", to);
347 
348 	if (close(to_fd)) {
349 		warn("%s", to);
350 		return (1);
351 	}
352 
353 	if (unlink(from)) {
354 		warn("%s: remove", from);
355 		return (1);
356 	}
357 	if (vflg)
358 		printf("%s -> %s\n", from, to);
359 	return (0);
360 }
361 
362 static int
363 copy(const char *from, const char *to)
364 {
365 	struct stat sb;
366 	int pid, status;
367 
368 	if (lstat(to, &sb) == 0) {
369 		/* Destination path exists. */
370 		if (S_ISDIR(sb.st_mode)) {
371 			if (rmdir(to) != 0) {
372 				warn("rmdir %s", to);
373 				return (1);
374 			}
375 		} else {
376 			if (unlink(to) != 0) {
377 				warn("unlink %s", to);
378 				return (1);
379 			}
380 		}
381 	} else if (errno != ENOENT) {
382 		warn("%s", to);
383 		return (1);
384 	}
385 
386 	/* Copy source to destination. */
387 	if (!(pid = vfork())) {
388 		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", "--", from, to,
389 		    (char *)NULL);
390 		_exit(EXEC_FAILED);
391 	}
392 	if (waitpid(pid, &status, 0) == -1) {
393 		warn("%s %s %s: waitpid", _PATH_CP, from, to);
394 		return (1);
395 	}
396 	if (!WIFEXITED(status)) {
397 		warnx("%s %s %s: did not terminate normally",
398 		    _PATH_CP, from, to);
399 		return (1);
400 	}
401 	switch (WEXITSTATUS(status)) {
402 	case 0:
403 		break;
404 	case EXEC_FAILED:
405 		warnx("%s %s %s: exec failed", _PATH_CP, from, to);
406 		return (1);
407 	default:
408 		warnx("%s %s %s: terminated with %d (non-zero) status",
409 		    _PATH_CP, from, to, WEXITSTATUS(status));
410 		return (1);
411 	}
412 
413 	/* Delete the source. */
414 	if (!(pid = vfork())) {
415 		execl(_PATH_RM, "mv", "-rf", "--", from, (char *)NULL);
416 		_exit(EXEC_FAILED);
417 	}
418 	if (waitpid(pid, &status, 0) == -1) {
419 		warn("%s %s: waitpid", _PATH_RM, from);
420 		return (1);
421 	}
422 	if (!WIFEXITED(status)) {
423 		warnx("%s %s: did not terminate normally", _PATH_RM, from);
424 		return (1);
425 	}
426 	switch (WEXITSTATUS(status)) {
427 	case 0:
428 		break;
429 	case EXEC_FAILED:
430 		warnx("%s %s: exec failed", _PATH_RM, from);
431 		return (1);
432 	default:
433 		warnx("%s %s: terminated with %d (non-zero) status",
434 		    _PATH_RM, from, WEXITSTATUS(status));
435 		return (1);
436 	}
437 	return (0);
438 }
439 
440 static void
441 preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
442     const char *dest_path)
443 {
444 	acl_t acl;
445 	acl_type_t acl_type;
446 	int acl_supported = 0, ret, trivial;
447 
448 	ret = fpathconf(source_fd, _PC_ACL_NFS4);
449 	if (ret > 0 ) {
450 		acl_supported = 1;
451 		acl_type = ACL_TYPE_NFS4;
452 	} else if (ret < 0 && errno != EINVAL) {
453 		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s",
454 		    source_path);
455 		return;
456 	}
457 	if (acl_supported == 0) {
458 		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
459 		if (ret > 0 ) {
460 			acl_supported = 1;
461 			acl_type = ACL_TYPE_ACCESS;
462 		} else if (ret < 0 && errno != EINVAL) {
463 			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
464 			    source_path);
465 			return;
466 		}
467 	}
468 	if (acl_supported == 0)
469 		return;
470 
471 	acl = acl_get_fd_np(source_fd, acl_type);
472 	if (acl == NULL) {
473 		warn("failed to get acl entries for %s", source_path);
474 		return;
475 	}
476 	if (acl_is_trivial_np(acl, &trivial)) {
477 		warn("acl_is_trivial() failed for %s", source_path);
478 		acl_free(acl);
479 		return;
480 	}
481 	if (trivial) {
482 		acl_free(acl);
483 		return;
484 	}
485 	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
486 		warn("failed to set acl entries for %s", dest_path);
487 		acl_free(acl);
488 		return;
489 	}
490 	acl_free(acl);
491 }
492 
493 static void
494 usage(void)
495 {
496 
497 	(void)fprintf(stderr, "%s\n%s\n",
498 		      "usage: mv [-f | -i | -n] [-hv] source target",
499 		      "       mv [-f | -i | -n] [-v] source ... directory");
500 	exit(EX_USAGE);
501 }
502