xref: /openbsd/bin/mv/mv.c (revision f6aab3d8)
1 /*	$OpenBSD: mv.c,v 1.47 2021/10/24 21:24:21 deraadt Exp $	*/
2 /*	$NetBSD: mv.c,v 1.9 1995/03/21 09:06:52 cgd Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993, 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Ken Smith of The State University of New York at Buffalo.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/time.h>
37 #include <sys/wait.h>
38 #include <sys/stat.h>
39 #include <sys/mount.h>
40 
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <limits.h>
49 #include <pwd.h>
50 #include <grp.h>
51 
52 extern char *__progname;
53 
54 int fflg, iflg, vflg;
55 int stdin_ok;
56 
57 extern int cpmain(int argc, char **argv);
58 extern int rmmain(int argc, char **argv);
59 
60 int	mvcopy(char *, char *);
61 int	do_move(char *, char *);
62 int	fastcopy(char *, char *, struct stat *);
63 void	usage(void);
64 
65 int
66 main(int argc, char *argv[])
67 {
68 	int baselen, len, rval;
69 	char *p, *endp;
70 	struct stat sb;
71 	int ch;
72 	char path[PATH_MAX];
73 
74 	while ((ch = getopt(argc, argv, "ifv")) != -1)
75 		switch (ch) {
76 		case 'i':
77 			fflg = 0;
78 			iflg = 1;
79 			break;
80 		case 'f':
81 			iflg = 0;
82 			fflg = 1;
83 			break;
84 		case 'v':
85 			vflg = 1;
86 			break;
87 		default:
88 			usage();
89 		}
90 	argc -= optind;
91 	argv += optind;
92 
93 	if (argc < 2)
94 		usage();
95 
96 	stdin_ok = isatty(STDIN_FILENO);
97 
98 	/*
99 	 * If the stat on the target fails or the target isn't a directory,
100 	 * try the move.  More than 2 arguments is an error in this case.
101 	 */
102 	if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
103 		if (argc > 2)
104 			usage();
105 		exit(do_move(argv[0], argv[1]));
106 	}
107 
108 	/* It's a directory, move each file into it. */
109 	if (strlcpy(path, argv[argc - 1], sizeof path) >= sizeof path)
110 		errx(1, "%s: destination pathname too long", *argv);
111 	baselen = strlen(path);
112 	endp = &path[baselen];
113 	if (*(endp - 1) != '/') {
114 		*endp++ = '/';
115 		++baselen;
116 	}
117 	for (rval = 0; --argc; ++argv) {
118 		char *current_arg = *argv;
119 
120 		/*
121 		 * Get the name of the file to create from
122 		 * the argument. This is a bit tricky because
123 		 * in the case of b/ we actually want b and empty
124 		 * string
125 		 */
126 		if ((p = strrchr(current_arg, '/')) == NULL)
127 			p = current_arg;
128 		else {
129 			/* Special case foo/ */
130 			if (!*(p+1)) {
131 				while (p >= current_arg && *p == '/')
132 					p--;
133 
134 				while (p >= current_arg && *p != '/')
135 					p--;
136 			}
137 
138 			p++;
139 		}
140 
141 		if ((baselen + (len = strlen(p))) >= PATH_MAX) {
142 			warnx("%s: destination pathname too long", *argv);
143 			rval = 1;
144 		} else {
145 			memmove(endp, p, len + 1);
146 			if (do_move(current_arg, path))
147 				rval = 1;
148 		}
149 	}
150 	exit(rval);
151 }
152 
153 int
154 do_move(char *from, char *to)
155 {
156 	struct stat sb, fsb;
157 	char modep[15];
158 
159 	/* Source path must exist (symlink is OK). */
160 	if (lstat(from, &fsb)) {
161 		warn("%s", from);
162 		return (1);
163 	}
164 
165 	/*
166 	 * (1)	If the destination path exists, the -f option is not specified
167 	 *	and either of the following conditions are true:
168 	 *
169 	 *	(a) The permissions of the destination path do not permit
170 	 *	    writing and the standard input is a terminal.
171 	 *	(b) The -i option is specified.
172 	 *
173 	 *	the mv utility shall write a prompt to standard error and
174 	 *	read a line from standard input.  If the response is not
175 	 *	affirmative, mv shall do nothing more with the current
176 	 *	source file...
177 	 */
178 	if (!fflg && !access(to, F_OK)) {
179 		int ask = 1;
180 		int ch, first;
181 
182 		if (iflg && !access(from, F_OK)) {
183 			(void)fprintf(stderr, "overwrite %s? ", to);
184 		} else if (stdin_ok && access(to, W_OK) && !stat(to, &sb)) {
185 			strmode(sb.st_mode, modep);
186 			(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
187 			    modep + 1, modep[9] == ' ' ? "" : " ",
188 			    user_from_uid(sb.st_uid, 0),
189 			    group_from_gid(sb.st_gid, 0), to);
190 		} else
191 			ask = 0;
192 		if (ask) {
193 			first = ch = getchar();
194 			while (ch != '\n' && ch != EOF)
195 				ch = getchar();
196 			if (first != 'y' && first != 'Y')
197 				return (0);
198 		}
199 	}
200 
201 	/*
202 	 * (2)	If rename() succeeds, mv shall do nothing more with the
203 	 *	current source file.  If it fails for any other reason than
204 	 *	EXDEV, mv shall write a diagnostic message to the standard
205 	 *	error and do nothing more with the current source file.
206 	 *
207 	 * (3)	If the destination path exists, and it is a file of type
208 	 *	directory and source_file is not a file of type directory,
209 	 *	or it is a file not of type directory, and source file is
210 	 *	a file of type directory, mv shall write a diagnostic
211 	 *	message to standard error, and do nothing more with the
212 	 *	current source file...
213 	 */
214 	if (!rename(from, to)) {
215 		if (vflg)
216 			(void)fprintf(stdout, "%s -> %s\n", from, to);
217 		return (0);
218 	}
219 
220 	if (errno != EXDEV) {
221 		warn("rename %s to %s", from, to);
222 		return (1);
223 	}
224 
225 	/* Disallow moving a mount point. */
226 	if (S_ISDIR(fsb.st_mode)) {
227 		struct statfs sfs;
228 		char path[PATH_MAX];
229 
230 		if (realpath(from, path) == NULL) {
231 			warnx("cannot resolve %s", from);
232 			return (1);
233 		}
234 		if (!statfs(path, &sfs) && !strcmp(path, sfs.f_mntonname)) {
235 			warnx("cannot rename a mount point");
236 			return (1);
237 		}
238 	}
239 
240 	/*
241 	 * (4)	If the destination path exists, mv shall attempt to remove it.
242 	 *	If this fails for any reason, mv shall write a diagnostic
243 	 *	message to the standard error and do nothing more with the
244 	 *	current source file...
245 	 */
246 	if (!lstat(to, &sb)) {
247 		if ((S_ISDIR(sb.st_mode)) ? rmdir(to) : unlink(to)) {
248 			warn("can't remove %s", to);
249 			return (1);
250 		}
251 	}
252 
253 	/*
254 	 * (5)	The file hierarchy rooted in source_file shall be duplicated
255 	 *	as a file hierarchy rooted in the destination path...
256 	 */
257 	return (S_ISREG(fsb.st_mode) ?
258 	    fastcopy(from, to, &fsb) : mvcopy(from, to));
259 }
260 
261 int
262 fastcopy(char *from, char *to, struct stat *sbp)
263 {
264 	struct timespec ts[2];
265 	static u_int32_t blen;
266 	static char *bp;
267 	int nread, from_fd, to_fd;
268 	int badchown = 0, serrno = 0;
269 
270 	if (!blen) {
271 		blen = sbp->st_blksize;
272 		if ((bp = malloc(blen)) == NULL) {
273 			warn(NULL);
274 			blen = 0;
275 			return (1);
276 		}
277 	}
278 
279 	if ((from_fd = open(from, O_RDONLY)) == -1) {
280 		warn("%s", from);
281 		return (1);
282 	}
283 	if ((to_fd = open(to, O_CREAT | O_TRUNC | O_WRONLY, 0600)) == -1) {
284 		warn("%s", to);
285 		(void)close(from_fd);
286 		return (1);
287 	}
288 
289 	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
290 		serrno = errno;
291 		badchown = 1;
292 	}
293 	(void) fchmod(to_fd, sbp->st_mode & ~(S_ISUID|S_ISGID));
294 
295 	while ((nread = read(from_fd, bp, blen)) > 0)
296 		if (write(to_fd, bp, nread) != nread) {
297 			warn("%s", to);
298 			goto err;
299 		}
300 	if (nread == -1) {
301 		warn("%s", from);
302 err:		if (unlink(to))
303 			warn("%s: remove", to);
304 		(void)close(from_fd);
305 		(void)close(to_fd);
306 		return (1);
307 	}
308 	(void)close(from_fd);
309 
310 	if (badchown) {
311 		if ((sbp->st_mode & (S_ISUID|S_ISGID)))  {
312 			warnc(serrno,
313 			    "%s: set owner/group; not setting setuid/setgid",
314 			    to);
315 			sbp->st_mode &= ~(S_ISUID|S_ISGID);
316 		} else if (!fflg)
317 			warnc(serrno, "%s: set owner/group", to);
318 	}
319 	if (fchmod(to_fd, sbp->st_mode))
320 		warn("%s: set mode", to);
321 
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 	errno = 0;
330 	if (fchflags(to_fd, sbp->st_flags))
331 		if (errno != EOPNOTSUPP || sbp->st_flags != 0)
332 			warn("%s: set flags", to);
333 
334 	ts[0] = sbp->st_atim;
335 	ts[1] = sbp->st_mtim;
336 	if (futimens(to_fd, ts))
337 		warn("%s: set times", to);
338 
339 	if (close(to_fd)) {
340 		warn("%s", to);
341 		return (1);
342 	}
343 
344 	if (unlink(from)) {
345 		warn("%s: remove", from);
346 		return (1);
347 	}
348 
349 	if (vflg)
350 		(void)fprintf(stdout, "%s -> %s\n", from, to);
351 
352 	return (0);
353 }
354 
355 int
356 mvcopy(char *from, char *to)
357 {
358 	char *argv[3];
359 
360 	argv[0] = from;
361 	argv[1] = to;
362 	argv[2] = NULL;
363 	if (cpmain(2, argv)) {
364 		warn("cp failed");
365 		_exit(1);
366 	}
367 
368 	argv[0] = from;
369 	argv[1] = NULL;
370 	if (rmmain(1, argv)) {
371 		warn("rm failed");
372 		_exit(1);
373 	}
374 
375 	/*
376 	 * XXX
377 	 * The external cpmain(), rmmain() approach (to avoid
378 	 * fork+exec) hides some of the details on what was moved.
379 	 * This can be improved upon during a refactor.
380 	 */
381 	if (vflg)
382 		(void)fprintf(stdout, "%s -> %s\n", from, to);
383 
384 	return (0);
385 }
386 
387 void
388 usage(void)
389 {
390 	(void)fprintf(stderr, "usage: %s [-fiv] source target\n", __progname);
391 	(void)fprintf(stderr, "       %s [-fiv] source ... directory\n",
392 	    __progname);
393 	exit(1);
394 }
395