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