mv.c revision 1.18
1/*	$NetBSD: mv.c,v 1.18 1998/07/28 05:31:26 mycroft Exp $	*/
2
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. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the University of
21 *	California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 *    may be used to endorse or promote products derived from this software
24 *    without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 */
38
39#include <sys/cdefs.h>
40#ifndef lint
41__COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\n\
42	The Regents of the University of California.  All rights reserved.\n");
43#endif /* not lint */
44
45#ifndef lint
46#if 0
47static char sccsid[] = "@(#)mv.c	8.2 (Berkeley) 4/2/94";
48#else
49__RCSID("$NetBSD: mv.c,v 1.18 1998/07/28 05:31:26 mycroft Exp $");
50#endif
51#endif /* not lint */
52
53#include <sys/param.h>
54#include <sys/time.h>
55#include <sys/wait.h>
56#include <sys/stat.h>
57
58#include <err.h>
59#include <errno.h>
60#include <fcntl.h>
61#include <locale.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <unistd.h>
66#include <pwd.h>
67#include <grp.h>
68
69#include "pathnames.h"
70
71int fflg, iflg;
72int stdin_ok;
73
74int	copy __P((char *, char *));
75int	do_move __P((char *, char *));
76int	fastcopy __P((char *, char *, struct stat *));
77void	usage __P((void));
78int	main __P((int, char *[]));
79
80int
81main(argc, argv)
82	int argc;
83	char *argv[];
84{
85	int baselen, len, rval;
86	char *p, *endp;
87	struct stat sb;
88	int ch;
89	char path[MAXPATHLEN + 1];
90
91	(void)setlocale(LC_ALL, "");
92
93	while ((ch = getopt(argc, argv, "if")) != -1)
94		switch (ch) {
95		case 'i':
96			fflg = 0;
97			iflg = 1;
98			break;
99		case 'f':
100			iflg = 0;
101			fflg = 1;
102			break;
103		case '?':
104		default:
105			usage();
106		}
107	argc -= optind;
108	argv += optind;
109
110	if (argc < 2)
111		usage();
112
113	stdin_ok = isatty(STDIN_FILENO);
114
115	/*
116	 * If the stat on the target fails or the target isn't a directory,
117	 * try the move.  More than 2 arguments is an error in this case.
118	 */
119	if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
120		if (argc > 2)
121			usage();
122		exit(do_move(argv[0], argv[1]));
123		/* NOTREACHED */
124	}
125
126	/* It's a directory, move each file into it. */
127	(void)strcpy(path, argv[argc - 1]);
128	baselen = strlen(path);
129	endp = &path[baselen];
130	*endp++ = '/';
131	++baselen;
132	for (rval = 0; --argc; ++argv) {
133		p = *argv + strlen(*argv) - 1;
134		while (*p == '/' && p != *argv)
135			*p-- = '\0';
136		if ((p = strrchr(*argv, '/')) == NULL)
137			p = *argv;
138		else
139			++p;
140
141		if ((baselen + (len = strlen(p))) >= MAXPATHLEN) {
142			warnx("%s: destination pathname too long", *argv);
143			rval = 1;
144		} else {
145			memmove(endp, p, len + 1);
146			if (do_move(*argv, path))
147				rval = 1;
148		}
149	}
150	exit(rval);
151	/* NOTREACHED */
152}
153
154int
155do_move(from, to)
156	char *from, *to;
157{
158	struct stat sb;
159	char modep[15];
160
161	/*
162	 * (1)	If the destination path exists, the -f option is not specified
163	 *	and either of the following conditions are true:
164	 *
165	 *	(a) The perimissions of the destination path do not permit
166	 *	    writing and the standard input is a terminal.
167	 *	(b) The -i option is specified.
168	 *
169	 *	the mv utility shall write a prompt to standard error and
170	 *	read a line from standard input.  If the response is not
171	 *	affirmative, mv shall do nothing more with the current
172	 *	source file...
173	 */
174	if (!fflg && !access(to, F_OK)) {
175		int ask = 1;
176		int ch;
177
178		if (iflg) {
179			(void)fprintf(stderr, "overwrite %s? ", to);
180		} else if (stdin_ok && access(to, W_OK) && !stat(to, &sb)) {
181			strmode(sb.st_mode, modep);
182			(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
183			    modep + 1, modep[9] == ' ' ? "" : " ",
184			    user_from_uid(sb.st_uid, 0),
185			    group_from_gid(sb.st_gid, 0), to);
186		} else
187			ask = 0;
188		if (ask) {
189			if ((ch = getchar()) != EOF && ch != '\n')
190				while (getchar() != '\n');
191			if (ch != 'y' && ch != 'Y')
192				return (0);
193		}
194	}
195
196	/*
197	 * (2)	If rename() succeeds, mv shall do nothing more with the
198	 *	current source file.  If it fails for any other reason than
199	 *	EXDEV, mv shall write a diagnostic message to the standard
200	 *	error and do nothing more with the current source file.
201	 *
202	 * (3)	If the destination path exists, and it is a file of type
203	 *	directory and source_file is not a file of type directory,
204	 *	or it is a file not of type directory, and source file is
205	 *	a file of type directory, mv shall write a diagnostic
206	 *	message to standard error, and do nothing more with the
207	 *	current source file...
208	 */
209	if (!rename(from, to))
210		return (0);
211
212	if (errno != EXDEV) {
213		warn("rename %s to %s", from, to);
214		return (1);
215	}
216
217	/*
218	 * (4)	If the destination path exists, mv shall attempt to remove it.
219	 *	If this fails for any reason, mv shall write a diagnostic
220	 *	message to the standard error and do nothing more with the
221	 *	current source file...
222	 */
223	if (!lstat(to, &sb)) {
224		if ((S_ISDIR(sb.st_mode)) ? rmdir(to) : unlink(to)) {
225			warn("can't remove %s", to);
226			return (1);
227		}
228	}
229
230	/*
231	 * (5)	The file hierarchy rooted in source_file shall be duplicated
232	 *	as a file hierarchy rooted in the destination path...
233	 */
234	if (lstat(from, &sb)) {
235		warn("%s", from);
236		return (1);
237	}
238	return (S_ISREG(sb.st_mode) ?
239	    fastcopy(from, to, &sb) : copy(from, to));
240}
241
242int
243fastcopy(from, to, sbp)
244	char *from, *to;
245	struct stat *sbp;
246{
247	struct timeval tval[2];
248	static u_int blen;
249	static char *bp;
250	int nread, from_fd, to_fd;
251
252	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
253		warn("%s", from);
254		return (1);
255	}
256	if ((to_fd =
257	    open(to, O_CREAT | O_TRUNC | O_WRONLY, sbp->st_mode)) < 0) {
258		warn("%s", to);
259		(void)close(from_fd);
260		return (1);
261	}
262	if (!blen && !(bp = malloc(blen = sbp->st_blksize))) {
263		warn("%s", "");
264		return (1);
265	}
266	while ((nread = read(from_fd, bp, blen)) > 0)
267		if (write(to_fd, bp, nread) != nread) {
268			warn("%s", to);
269			goto err;
270		}
271	if (nread < 0) {
272		warn("%s", from);
273err:		if (unlink(to))
274			warn("%s: remove", to);
275		(void)close(from_fd);
276		(void)close(to_fd);
277		return (1);
278	}
279	(void)close(from_fd);
280
281	TIMESPEC_TO_TIMEVAL(&tval[0], &sbp->st_atimespec);
282	TIMESPEC_TO_TIMEVAL(&tval[1], &sbp->st_mtimespec);
283	if (futimes(to_fd, tval))
284		warn("%s: set times", to);
285	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
286		if (errno != EPERM)
287			warn("%s: set owner/group", to);
288		sbp->st_mode &= ~(S_ISUID | S_ISGID);
289	}
290	if (fchmod(to_fd, sbp->st_mode))
291		warn("%s: set mode", to);
292
293	if (close(to_fd)) {
294		warn("%s", to);
295		return (1);
296	}
297
298	if (unlink(from)) {
299		warn("%s: remove", from);
300		return (1);
301	}
302	return (0);
303}
304
305int
306copy(from, to)
307	char *from, *to;
308{
309	int pid, status;
310
311	if ((pid = vfork()) == 0) {
312		execl(_PATH_CP, "mv", "-PRp", from, to, NULL);
313		warn("%s", _PATH_CP);
314		_exit(1);
315		/* NOTREACHED */
316	}
317	if (waitpid(pid, &status, 0) == -1) {
318		warn("%s: waitpid", _PATH_CP);
319		return (1);
320	}
321	if (!WIFEXITED(status)) {
322		warn("%s: did not terminate normally", _PATH_CP);
323		return (1);
324	}
325	if (WEXITSTATUS(status)) {
326		warn("%s: terminated with %d (non-zero) status",
327		    _PATH_CP, WEXITSTATUS(status));
328		return (1);
329	}
330	if (!(pid = vfork())) {
331		execl(_PATH_RM, "mv", "-rf", from, NULL);
332		warn("%s", _PATH_RM);
333		_exit(1);
334		/* NOTREACHED */
335	}
336	if (waitpid(pid, &status, 0) == -1) {
337		warn("%s: waitpid", _PATH_RM);
338		return (1);
339	}
340	if (!WIFEXITED(status)) {
341		warn("%s: did not terminate normally", _PATH_RM);
342		return (1);
343	}
344	if (WEXITSTATUS(status)) {
345		warn("%s: terminated with %d (non-zero) status",
346		    _PATH_RM, WEXITSTATUS(status));
347		return (1);
348	}
349	return (0);
350}
351
352void
353usage()
354{
355
356	(void)fprintf(stderr, "usage: mv [-fi] source target\n");
357	(void)fprintf(stderr, "       mv [-fi] source ... directory\n");
358	exit(1);
359	/* NOTREACHED */
360}
361