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