mv.c revision 1.32
1/* $NetBSD: mv.c,v 1.32 2003/08/13 03:22:03 itojun 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. 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#include <sys/cdefs.h>
36#ifndef lint
37__COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\n\
38	The Regents of the University of California.  All rights reserved.\n");
39#endif /* not lint */
40
41#ifndef lint
42#if 0
43static char sccsid[] = "@(#)mv.c	8.2 (Berkeley) 4/2/94";
44#else
45__RCSID("$NetBSD: mv.c,v 1.32 2003/08/13 03:22:03 itojun Exp $");
46#endif
47#endif /* not lint */
48
49#include <sys/param.h>
50#include <sys/time.h>
51#include <sys/wait.h>
52#include <sys/stat.h>
53
54#include <err.h>
55#include <errno.h>
56#include <fcntl.h>
57#include <grp.h>
58#include <locale.h>
59#include <pwd.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <unistd.h>
64#include <vis.h>
65
66#include "pathnames.h"
67
68int fflg, iflg, vflg;
69int stdin_ok, stdout_ok;
70
71int	copy(char *, char *);
72int	do_move(char *, char *);
73int	fastcopy(char *, char *, struct stat *);
74void	usage(void);
75int	main(int, char *[]);
76char	*printescaped(const char *);
77
78int
79main(int argc, char *argv[])
80{
81	int baselen, ch, len, rval;
82	char *p, *endp;
83	struct stat sb;
84	char path[MAXPATHLEN + 1];
85
86	setprogname(argv[0]);
87	(void)setlocale(LC_ALL, "");
88
89	while ((ch = getopt(argc, argv, "ifv")) != -1)
90		switch (ch) {
91		case 'i':
92			fflg = 0;
93			iflg = 1;
94			break;
95		case 'f':
96			iflg = 0;
97			fflg = 1;
98			break;
99		case 'v':
100			vflg = 1;
101			break;
102		case '?':
103		default:
104			usage();
105		}
106	argc -= optind;
107	argv += optind;
108
109	if (argc < 2)
110		usage();
111
112	stdin_ok = isatty(STDIN_FILENO);
113	stdout_ok = isatty(STDOUT_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	}
124
125	/* It's a directory, move each file into it. */
126	(void)strlcpy(path, argv[argc - 1], sizeof(path));
127	baselen = strlen(path);
128	endp = &path[baselen];
129	*endp++ = '/';
130	++baselen;
131	for (rval = 0; --argc; ++argv) {
132		p = *argv + strlen(*argv) - 1;
133		while (*p == '/' && p != *argv)
134			*p-- = '\0';
135		if ((p = strrchr(*argv, '/')) == NULL)
136			p = *argv;
137		else
138			++p;
139
140		if ((baselen + (len = strlen(p))) >= MAXPATHLEN) {
141			char *fn = printescaped(*argv);
142			warnx("%s: destination pathname too long", fn);
143			free(fn);
144			rval = 1;
145		} else {
146			memmove(endp, p, len + 1);
147			if (do_move(*argv, path))
148				rval = 1;
149		}
150	}
151	exit(rval);
152	/* NOTREACHED */
153}
154
155int
156do_move(char *from, char *to)
157{
158	struct stat sb;
159	char modep[15];
160	char *fn, *tn;
161
162	fn = printescaped(from);
163	tn = printescaped(to);
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;
181
182		if (iflg) {
183			if (access(from, F_OK)) {
184				warn("rename %s", fn);
185				free(fn);
186				free(tn);
187				return (1);
188			}
189			(void)fprintf(stderr, "overwrite %s? ", tn);
190		} else if (stdin_ok && access(to, W_OK) && !stat(to, &sb)) {
191			if (access(from, F_OK)) {
192				warn("rename %s", fn);
193				free(fn);
194				free(tn);
195				return (1);
196			}
197			strmode(sb.st_mode, modep);
198			(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
199			    modep + 1, modep[9] == ' ' ? "" : " ",
200			    user_from_uid(sb.st_uid, 0),
201			    group_from_gid(sb.st_gid, 0), tn);
202		} else
203			ask = 0;
204		if (ask) {
205			if ((ch = getchar()) != EOF && ch != '\n')
206				while (getchar() != '\n');
207			if (ch != 'y' && ch != 'Y') {
208				free(fn);
209				free(tn);
210				return (0);
211			}
212		}
213	}
214
215	/*
216	 * (2)	If rename() succeeds, mv shall do nothing more with the
217	 *	current source file.  If it fails for any other reason than
218	 *	EXDEV, mv shall write a diagnostic message to the standard
219	 *	error and do nothing more with the current source file.
220	 *
221	 * (3)	If the destination path exists, and it is a file of type
222	 *	directory and source_file is not a file of type directory,
223	 *	or it is a file not of type directory, and source file is
224	 *	a file of type directory, mv shall write a diagnostic
225	 *	message to standard error, and do nothing more with the
226	 *	current source file...
227	 */
228	if (!rename(from, to)) {
229		if (vflg)
230			printf("%s -> %s\n", fn, tn);
231		free(fn);
232		free(tn);
233		return (0);
234	}
235
236	if (errno != EXDEV) {
237		warn("rename %s to %s", fn, tn);
238		free(fn);
239		free(tn);
240		return (1);
241	}
242
243	/*
244	 * (4)	If the destination path exists, mv shall attempt to remove it.
245	 *	If this fails for any reason, mv shall write a diagnostic
246	 *	message to the standard error and do nothing more with the
247	 *	current source file...
248	 */
249	if (!lstat(to, &sb)) {
250		if ((S_ISDIR(sb.st_mode)) ? rmdir(to) : unlink(to)) {
251			warn("can't remove %s", tn);
252			free(fn);
253			free(tn);
254			return (1);
255		}
256	}
257
258	/*
259	 * (5)	The file hierarchy rooted in source_file shall be duplicated
260	 *	as a file hierarchy rooted in the destination path...
261	 */
262	if (lstat(from, &sb)) {
263		warn("%s", fn);
264		free(fn);
265		free(tn);
266		return (1);
267	}
268
269	free(fn);
270	free(tn);
271
272	return (S_ISREG(sb.st_mode) ?
273	    fastcopy(from, to, &sb) : copy(from, to));
274}
275
276int
277fastcopy(char *from, char *to, struct stat *sbp)
278{
279	struct timeval tval[2];
280	static u_int blen;
281	static char *bp;
282	int nread, from_fd, to_fd;
283	char *fn, *tn;
284
285	fn = printescaped(from);
286	tn = printescaped(to);
287
288	if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
289		warn("%s", fn);
290		free(fn);
291		free(tn);
292		return (1);
293	}
294	if ((to_fd =
295	    open(to, O_CREAT | O_TRUNC | O_WRONLY, sbp->st_mode)) < 0) {
296		warn("%s", tn);
297		free(fn);
298		free(tn);
299		(void)close(from_fd);
300		return (1);
301	}
302	if (!blen && !(bp = malloc(blen = sbp->st_blksize))) {
303		warn(NULL);
304		free(fn);
305		free(tn);
306		return (1);
307	}
308	while ((nread = read(from_fd, bp, blen)) > 0)
309		if (write(to_fd, bp, nread) != nread) {
310			warn("%s", tn);
311			goto err;
312		}
313	if (nread < 0) {
314		warn("%s", fn);
315err:		if (unlink(to))
316			warn("%s: remove", tn);
317		(void)close(from_fd);
318		(void)close(to_fd);
319		free(fn);
320		free(tn);
321		return (1);
322	}
323	(void)close(from_fd);
324#ifdef BSD4_4
325	TIMESPEC_TO_TIMEVAL(&tval[0], &sbp->st_atimespec);
326	TIMESPEC_TO_TIMEVAL(&tval[1], &sbp->st_mtimespec);
327#else
328	tval[0].tv_sec = sbp->st_atime;
329	tval[1].tv_sec = sbp->st_mtime;
330	tval[0].tv_usec = 0;
331	tval[1].tv_usec = 0;
332#endif
333#ifdef __SVR4
334	if (utimes(to, tval))
335#else
336	if (futimes(to_fd, tval))
337#endif
338		warn("%s: set times", tn);
339	if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
340		if (errno != EPERM)
341			warn("%s: set owner/group", tn);
342		sbp->st_mode &= ~(S_ISUID | S_ISGID);
343	}
344	if (fchmod(to_fd, sbp->st_mode))
345		warn("%s: set mode", tn);
346	if (fchflags(to_fd, sbp->st_flags) && (errno != EOPNOTSUPP))
347		warn("%s: set flags (was: 0%07o)", tn, sbp->st_flags);
348
349	if (close(to_fd)) {
350		warn("%s", tn);
351		free(fn);
352		free(tn);
353		return (1);
354	}
355
356	if (unlink(from)) {
357		warn("%s: remove", fn);
358		free(fn);
359		free(tn);
360		return (1);
361	}
362
363	if (vflg)
364		printf("%s -> %s\n", fn, tn);
365
366	free(fn);
367	free(tn);
368	return (0);
369}
370
371int
372copy(char *from, char *to)
373{
374	int pid, status;
375
376	if ((pid = vfork()) == 0) {
377		execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", from, to, NULL);
378		warn("%s", _PATH_CP);
379		_exit(1);
380	}
381	if (waitpid(pid, &status, 0) == -1) {
382		warn("%s: waitpid", _PATH_CP);
383		return (1);
384	}
385	if (!WIFEXITED(status)) {
386		warn("%s: did not terminate normally", _PATH_CP);
387		return (1);
388	}
389	if (WEXITSTATUS(status)) {
390		warn("%s: terminated with %d (non-zero) status",
391		    _PATH_CP, WEXITSTATUS(status));
392		return (1);
393	}
394	if (!(pid = vfork())) {
395		execl(_PATH_RM, "mv", "-rf", from, NULL);
396		warn("%s", _PATH_RM);
397		_exit(1);
398	}
399	if (waitpid(pid, &status, 0) == -1) {
400		warn("%s: waitpid", _PATH_RM);
401		return (1);
402	}
403	if (!WIFEXITED(status)) {
404		warn("%s: did not terminate normally", _PATH_RM);
405		return (1);
406	}
407	if (WEXITSTATUS(status)) {
408		warn("%s: terminated with %d (non-zero) status",
409		    _PATH_RM, WEXITSTATUS(status));
410		return (1);
411	}
412	return (0);
413}
414
415void
416usage(void)
417{
418	(void)fprintf(stderr, "usage: %s [-fiv] source target\n"
419	    "       %s [-fiv] source ... directory\n", getprogname(),
420	    getprogname());
421	exit(1);
422	/* NOTREACHED */
423}
424
425char *
426printescaped(const char *src)
427{
428	size_t len;
429	char *retval;
430
431	len = strlen(src);
432	if (len != 0 && SIZE_T_MAX/len <= 4) {
433		errx(EXIT_FAILURE, "%s: name too long", src);
434		/* NOTREACHED */
435	}
436
437	retval = (char *)malloc(4*len+1);
438	if (retval != NULL) {
439		if (stdout_ok)
440			(void)strvis(retval, src, VIS_NL | VIS_CSTYLE);
441		else
442			(void)strlcpy(retval, src, 4 * len + 1);
443		return retval;
444	} else
445		errx(EXIT_FAILURE, "out of memory!");
446		/* NOTREACHED */
447}
448