mv.c revision 1.11
1/*	$NetBSD: mv.c,v 1.11 1997/07/20 19:07:53 christos 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.11 1997/07/20 19:07:53 christos 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 <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <unistd.h>
65
66#include "pathnames.h"
67
68int fflg, iflg;
69int stdin_ok;
70
71int	copy __P((char *, char *));
72int	do_move __P((char *, char *));
73int	fastcopy __P((char *, char *, struct stat *));
74void	usage __P((void));
75int	main __P((int, char *[]));
76
77int
78main(argc, argv)
79	int argc;
80	char *argv[];
81{
82	int baselen, len, rval;
83	char *p, *endp;
84	struct stat sb;
85	int ch;
86	char path[MAXPATHLEN + 1];
87
88	while ((ch = getopt(argc, argv, "if")) != -1)
89		switch (ch) {
90		case 'i':
91			fflg = 0;
92			iflg = 1;
93			break;
94		case 'f':
95			iflg = 0;
96			fflg = 1;
97			break;
98		case '?':
99		default:
100			usage();
101		}
102	argc -= optind;
103	argv += optind;
104
105	if (argc < 2)
106		usage();
107
108	stdin_ok = isatty(STDIN_FILENO);
109
110	/*
111	 * If the stat on the target fails or the target isn't a directory,
112	 * try the move.  More than 2 arguments is an error in this case.
113	 */
114	if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
115		if (argc > 2)
116			usage();
117		exit(do_move(argv[0], argv[1]));
118	}
119
120	/* It's a directory, move each file into it. */
121	(void)strcpy(path, argv[argc - 1]);
122	baselen = strlen(path);
123	endp = &path[baselen];
124	*endp++ = '/';
125	++baselen;
126	for (rval = 0; --argc; ++argv) {
127		if ((p = strrchr(*argv, '/')) == NULL)
128			p = *argv;
129		else
130			++p;
131		if ((baselen + (len = strlen(p))) >= MAXPATHLEN) {
132			warnx("%s: destination pathname too long", *argv);
133			rval = 1;
134		} else {
135			memmove(endp, p, len + 1);
136			if (do_move(*argv, path))
137				rval = 1;
138		}
139	}
140	exit(rval);
141}
142
143int
144do_move(from, to)
145	char *from, *to;
146{
147	struct stat sb;
148	char modep[15];
149
150	/*
151	 * (1)	If the destination path exists, the -f option is not specified
152	 *	and either of the following conditions are true:
153	 *
154	 *	(a) The perimissions of the destination path do not permit
155	 *	    writing and the standard input is a terminal.
156	 *	(b) The -i option is specified.
157	 *
158	 *	the mv utility shall write a prompt to standard error and
159	 *	read a line from standard input.  If the response is not
160	 *	affirmative, mv shall do nothing more with the current
161	 *	source file...
162	 */
163	if (!fflg && !access(to, F_OK)) {
164		int ask = 1;
165		int ch;
166
167		if (iflg) {
168			(void)fprintf(stderr, "overwrite %s? ", to);
169		} else if (stdin_ok && access(to, W_OK) && !stat(to, &sb)) {
170			strmode(sb.st_mode, modep);
171			(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
172			    modep + 1, modep[9] == ' ' ? "" : " ",
173			    user_from_uid(sb.st_uid, 0),
174			    group_from_gid(sb.st_gid, 0), to);
175		} else
176			ask = 0;
177		if (ask) {
178			if ((ch = getchar()) != EOF && ch != '\n')
179				while (getchar() != '\n');
180			if (ch != 'y' && ch != 'Y')
181				return (0);
182		}
183	}
184
185	/*
186	 * (2)	If rename() succeeds, mv shall do nothing more with the
187	 *	current source file.  If it fails for any other reason than
188	 *	EXDEV, mv shall write a diagnostic message to the standard
189	 *	error and do nothing more with the current source file.
190	 *
191	 * (3)	If the destination path exists, and it is a file of type
192	 *	directory and source_file is not a file of type directory,
193	 *	or it is a file not of type directory, and source file is
194	 *	a file of type directory, mv shall write a diagnostic
195	 *	message to standard error, and do nothing more with the
196	 *	current source file...
197	 */
198	if (!rename(from, to))
199		return (0);
200
201	if (errno != EXDEV) {
202		warn("rename %s to %s", from, to);
203		return (1);
204	}
205
206	/*
207	 * (4)	If the destination path exists, mv shall attempt to remove it.
208	 *	If this fails for any reason, mv shall write a diagnostic
209	 *	message to the standard error and do nothing more with the
210	 *	current source file...
211	 */
212	if (!stat(to, &sb)) {
213		if ((S_ISDIR(sb.st_mode)) ? rmdir(to) : unlink(to)) {
214			warn("can't remove %s", to);
215			return (1);
216		}
217	}
218
219	/*
220	 * (5)	The file hierarchy rooted in source_file shall be duplicated
221	 *	as a file hiearchy rooted in the destination path...
222	 */
223	if (stat(from, &sb)) {
224		warn("%s", from);
225		return (1);
226	}
227	return (S_ISREG(sb.st_mode) ?
228	    fastcopy(from, to, &sb) : copy(from, to));
229}
230
231int
232fastcopy(from, to, sbp)
233	char *from, *to;
234	struct stat *sbp;
235{
236	struct timeval tval[2];
237	static u_int blen;
238	static char *bp;
239	int nread, from_fd, to_fd;
240
241	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
242		warn("%s", from);
243		return (1);
244	}
245	if ((to_fd =
246	    open(to, O_CREAT | O_TRUNC | O_WRONLY, sbp->st_mode)) < 0) {
247		warn("%s", to);
248		(void)close(from_fd);
249		return (1);
250	}
251	if (!blen && !(bp = malloc(blen = sbp->st_blksize))) {
252		warn("%s", "");
253		return (1);
254	}
255	while ((nread = read(from_fd, bp, blen)) > 0)
256		if (write(to_fd, bp, nread) != nread) {
257			warn("%s", to);
258			goto err;
259		}
260	if (nread < 0) {
261		warn("%s", from);
262err:		if (unlink(to))
263			warn("%s: remove", to);
264		(void)close(from_fd);
265		(void)close(to_fd);
266		return (1);
267	}
268	(void)close(from_fd);
269
270	if (fchown(to_fd, sbp->st_uid, sbp->st_gid))
271		warn("%s: set owner/group", to);
272	if (fchmod(to_fd, sbp->st_mode))
273		warn("%s: set mode", to);
274
275	tval[0].tv_sec = sbp->st_atime;
276	tval[1].tv_sec = sbp->st_mtime;
277	tval[0].tv_usec = tval[1].tv_usec = 0;
278	if (utimes(to, tval))
279		warn("%s: set times", to);
280
281	if (close(to_fd)) {
282		warn("%s", to);
283		return (1);
284	}
285
286	if (unlink(from)) {
287		warn("%s: remove", from);
288		return (1);
289	}
290	return (0);
291}
292
293int
294copy(from, to)
295	char *from, *to;
296{
297	int pid, status;
298
299	if ((pid = vfork()) == 0) {
300		execl(_PATH_CP, "mv", "-PRp", from, to, NULL);
301		warn("%s", _PATH_CP);
302		_exit(1);
303	}
304	if (waitpid(pid, &status, 0) == -1) {
305		warn("%s: waitpid", _PATH_CP);
306		return (1);
307	}
308	if (!WIFEXITED(status)) {
309		warn("%s: did not terminate normally", _PATH_CP);
310		return (1);
311	}
312	if (WEXITSTATUS(status)) {
313		warn("%s: terminated with %d (non-zero) status",
314		    _PATH_CP, WEXITSTATUS(status));
315		return (1);
316	}
317	if (!(pid = vfork())) {
318		execl(_PATH_RM, "mv", "-rf", from, NULL);
319		warn("%s", _PATH_RM);
320		_exit(1);
321	}
322	if (waitpid(pid, &status, 0) == -1) {
323		warn("%s: waitpid", _PATH_RM);
324		return (1);
325	}
326	if (!WIFEXITED(status)) {
327		warn("%s: did not terminate normally", _PATH_RM);
328		return (1);
329	}
330	if (WEXITSTATUS(status)) {
331		warn("%s: terminated with %d (non-zero) status",
332		    _PATH_RM, WEXITSTATUS(status));
333		return (1);
334	}
335	return (0);
336}
337
338void
339usage()
340{
341
342	(void)fprintf(stderr, "usage: mv [-fi] source target\n");
343	(void)fprintf(stderr, "       mv [-fi] source ... directory\n");
344	exit(1);
345}
346