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