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