mv.c revision 1.28
1/* $NetBSD: mv.c,v 1.28 2002/12/26 21:37:17 jrf 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.28 2002/12/26 21:37:17 jrf 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 <grp.h>
62#include <locale.h>
63#include <pwd.h>
64#include <stdio.h>
65#include <stdlib.h>
66#include <string.h>
67#include <unistd.h>
68
69#include "pathnames.h"
70
71int fflg, iflg, vflg;
72int stdin_ok;
73
74int copy(char *, char *);
75int do_move(char *, char *);
76int fastcopy(char *, char *, struct stat *);
77void usage(void);
78int main(int, char *[]);
79
80int
81main(int argc, char *argv[])
82{
83	int baselen, ch, len, rval;
84	char *p, *endp;
85	struct stat sb;
86	char path[MAXPATHLEN + 1];
87
88	setprogname(argv[0]);
89	(void)setlocale(LC_ALL, "");
90
91	while ((ch = getopt(argc, argv, "ifv")) != -1)
92		switch (ch) {
93		case 'i':
94			fflg = 0;
95			iflg = 1;
96			break;
97		case 'f':
98			iflg = 0;
99			fflg = 1;
100			break;
101		case 'v':
102			vflg = 1;
103			break;
104		case '?':
105		default:
106			usage();
107		}
108	argc -= optind;
109	argv += optind;
110
111	if (argc < 2)
112		usage();
113
114	stdin_ok = isatty(STDIN_FILENO);
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			usage();
123		exit(do_move(argv[0], argv[1]));
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(char *from, char *to)
156{
157	struct stat sb;
158	char modep[15];
159
160	/*
161	 * (1)	If the destination path exists, the -f option is not specified
162	 *	and either of the following conditions are true:
163	 *
164	 *	(a) The permissions of the destination path do not permit
165	 *	    writing and the standard input is a terminal.
166	 *	(b) The -i option is specified.
167	 *
168	 *	the mv utility shall write a prompt to standard error and
169	 *	read a line from standard input.  If the response is not
170	 *	affirmative, mv shall do nothing more with the current
171	 *	source file...
172	 */
173	if (!fflg && !access(to, F_OK)) {
174		int ask = 1;
175		int ch;
176
177		if (iflg) {
178			if (access(from, F_OK)) {
179				warn("rename %s", from);
180				return (1);
181			}
182			(void)fprintf(stderr, "overwrite %s? ", to);
183		} else if (stdin_ok && access(to, W_OK) && !stat(to, &sb)) {
184			if (access(from, F_OK)) {
185				warn("rename %s", from);
186				return (1);
187			}
188			strmode(sb.st_mode, modep);
189			(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
190			    modep + 1, modep[9] == ' ' ? "" : " ",
191			    user_from_uid(sb.st_uid, 0),
192			    group_from_gid(sb.st_gid, 0), to);
193		} else
194			ask = 0;
195		if (ask) {
196			if ((ch = getchar()) != EOF && ch != '\n')
197				while (getchar() != '\n');
198			if (ch != 'y' && ch != 'Y')
199				return (0);
200		}
201	}
202
203	/*
204	 * (2)	If rename() succeeds, mv shall do nothing more with the
205	 *	current source file.  If it fails for any other reason than
206	 *	EXDEV, mv shall write a diagnostic message to the standard
207	 *	error and do nothing more with the current source file.
208	 *
209	 * (3)	If the destination path exists, and it is a file of type
210	 *	directory and source_file is not a file of type directory,
211	 *	or it is a file not of type directory, and source file is
212	 *	a file of type directory, mv shall write a diagnostic
213	 *	message to standard error, and do nothing more with the
214	 *	current source file...
215	 */
216	if (!rename(from, to)) {
217		if (vflg)
218			printf("%s -> %s\n", from, to);
219		return (0);
220	}
221
222	if (errno != EXDEV) {
223		warn("rename %s to %s", from, to);
224		return (1);
225	}
226
227	/*
228	 * (4)	If the destination path exists, mv shall attempt to remove it.
229	 *	If this fails for any reason, mv shall write a diagnostic
230	 *	message to the standard error and do nothing more with the
231	 *	current source file...
232	 */
233	if (!lstat(to, &sb)) {
234		if ((S_ISDIR(sb.st_mode)) ? rmdir(to) : unlink(to)) {
235			warn("can't remove %s", to);
236			return (1);
237		}
238	}
239
240	/*
241	 * (5)	The file hierarchy rooted in source_file shall be duplicated
242	 *	as a file hierarchy rooted in the destination path...
243	 */
244	if (lstat(from, &sb)) {
245		warn("%s", from);
246		return (1);
247	}
248	return (S_ISREG(sb.st_mode) ?
249	    fastcopy(from, to, &sb) : copy(from, to));
250}
251
252int
253fastcopy(char *from, char *to, struct stat *sbp)
254{
255	struct timeval tval[2];
256	static u_int blen;
257	static char *bp;
258	int nread, from_fd, to_fd;
259
260	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
261		warn("%s", from);
262		return (1);
263	}
264	if ((to_fd =
265	    open(to, O_CREAT | O_TRUNC | O_WRONLY, sbp->st_mode)) < 0) {
266		warn("%s", to);
267		(void)close(from_fd);
268		return (1);
269	}
270	if (!blen && !(bp = malloc(blen = sbp->st_blksize))) {
271		warn(NULL);
272		return (1);
273	}
274	while ((nread = read(from_fd, bp, blen)) > 0)
275		if (write(to_fd, bp, nread) != nread) {
276			warn("%s", to);
277			goto err;
278		}
279	if (nread < 0) {
280		warn("%s", from);
281err:		if (unlink(to))
282			warn("%s: remove", to);
283		(void)close(from_fd);
284		(void)close(to_fd);
285		return (1);
286	}
287	(void)close(from_fd);
288#ifdef BSD4_4
289	TIMESPEC_TO_TIMEVAL(&tval[0], &sbp->st_atimespec);
290	TIMESPEC_TO_TIMEVAL(&tval[1], &sbp->st_mtimespec);
291#else
292	tval[0].tv_sec = sbp->st_atime;
293	tval[1].tv_sec = sbp->st_mtime;
294	tval[0].tv_usec = 0;
295	tval[1].tv_usec = 0;
296#endif
297#ifdef __SVR4
298	if (utimes(to, tval))
299#else
300	if (futimes(to_fd, tval))
301#endif
302		warn("%s: set times", to);
303	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
304		if (errno != EPERM)
305			warn("%s: set owner/group", to);
306		sbp->st_mode &= ~(S_ISUID | S_ISGID);
307	}
308	if (fchmod(to_fd, sbp->st_mode))
309		warn("%s: set mode", to);
310	if (fchflags(to_fd, sbp->st_flags) && (errno != EOPNOTSUPP))
311		warn("%s: set flags (was: 0%07o)", to, sbp->st_flags);
312
313	if (close(to_fd)) {
314		warn("%s", to);
315		return (1);
316	}
317
318	if (unlink(from)) {
319		warn("%s: remove", from);
320		return (1);
321	}
322
323	if (vflg)
324		printf("%s -> %s\n", from, to);
325
326	return (0);
327}
328
329int
330copy(char *from, char *to)
331{
332	int pid, status;
333
334	if ((pid = vfork()) == 0) {
335		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", from, to, NULL);
336		warn("%s", _PATH_CP);
337		_exit(1);
338	}
339	if (waitpid(pid, &status, 0) == -1) {
340		warn("%s: waitpid", _PATH_CP);
341		return (1);
342	}
343	if (!WIFEXITED(status)) {
344		warn("%s: did not terminate normally", _PATH_CP);
345		return (1);
346	}
347	if (WEXITSTATUS(status)) {
348		warn("%s: terminated with %d (non-zero) status",
349		    _PATH_CP, WEXITSTATUS(status));
350		return (1);
351	}
352	if (!(pid = vfork())) {
353		execl(_PATH_RM, "mv", "-rf", from, NULL);
354		warn("%s", _PATH_RM);
355		_exit(1);
356	}
357	if (waitpid(pid, &status, 0) == -1) {
358		warn("%s: waitpid", _PATH_RM);
359		return (1);
360	}
361	if (!WIFEXITED(status)) {
362		warn("%s: did not terminate normally", _PATH_RM);
363		return (1);
364	}
365	if (WEXITSTATUS(status)) {
366		warn("%s: terminated with %d (non-zero) status",
367		    _PATH_RM, WEXITSTATUS(status));
368		return (1);
369	}
370	return (0);
371}
372
373void
374usage(void)
375{
376	(void)fprintf(stderr, "usage: %s [-fiv] source target\n"
377	    "       %s [-fiv] source ... directory\n", getprogname(),
378	    getprogname());
379	exit(1);
380	/* NOTREACHED */
381}
382