6c7d6a3f0aa4f07db2e50779c7c3ebcce48d578b
[dragonfly.git] / bin / mv / mv.c
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #include <sys/param.h>
34 #include <sys/time.h>
35 #include <sys/wait.h>
36 #include <sys/stat.h>
37 #include <sys/mount.h>
38
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <grp.h>
43 #include <limits.h>
44 #include <paths.h>
45 #include <pwd.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sysexits.h>
51 #include <unistd.h>
52
53 /* Exit code for a failed exec. */
54 #define EXEC_FAILED 127
55
56 static int      fflg, hflg, iflg, nflg, vflg;
57 volatile sig_atomic_t info;
58
59 static int      copy(const char *, const char *);
60 static int      do_move(const char *, const char *);
61 static int      fastcopy(const char *, const char *, struct stat *);
62 static void     usage(void);
63 static void     siginfo(int);
64
65 int
66 main(int argc, char *argv[])
67 {
68         size_t baselen, len;
69         int rval;
70         char *p, *endp;
71         struct stat sb;
72         int ch;
73         char path[PATH_MAX];
74
75         while ((ch = getopt(argc, argv, "fhinv")) != -1)
76                 switch (ch) {
77                 case 'h':
78                         hflg = 1;
79                         break;
80                 case 'i':
81                         iflg = 1;
82                         fflg = nflg = 0;
83                         break;
84                 case 'f':
85                         fflg = 1;
86                         iflg = nflg = 0;
87                         break;
88                 case 'n':
89                         nflg = 1;
90                         fflg = iflg = 0;
91                         break;
92                 case 'v':
93                         vflg = 1;
94                         break;
95                 default:
96                         usage();
97                 }
98         argc -= optind;
99         argv += optind;
100
101         signal(SIGINFO, siginfo);
102
103         if (argc < 2)
104                 usage();
105
106         /*
107          * If the stat on the target fails or the target isn't a directory,
108          * try the move.  More than 2 arguments is an error in this case.
109          */
110         if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
111                 if (argc > 2)
112                         usage();
113                 exit(do_move(argv[0], argv[1]));
114         }
115
116         /*
117          * If -h was specified, treat the target as a symlink instead of
118          * directory.
119          */
120         if (hflg) {
121                 if (argc > 2)
122                         usage();
123                 if (lstat(argv[1], &sb) == 0 && S_ISLNK(sb.st_mode))
124                         exit(do_move(argv[0], argv[1]));
125         }
126
127         /* It's a directory, move each file into it. */
128         if (strlen(argv[argc - 1]) > sizeof(path) - 1)
129                 errx(1, "%s: destination pathname too long", *argv);
130         (void)strcpy(path, argv[argc - 1]);
131         baselen = strlen(path);
132         endp = &path[baselen];
133         if (!baselen || *(endp - 1) != '/') {
134                 *endp++ = '/';
135                 ++baselen;
136         }
137         for (rval = 0; --argc; ++argv) {
138                 /*
139                  * Find the last component of the source pathname.  It
140                  * may have trailing slashes.
141                  */
142                 p = *argv + strlen(*argv);
143                 while (p != *argv && p[-1] == '/')
144                         --p;
145                 while (p != *argv && p[-1] != '/')
146                         --p;
147
148                 if ((baselen + (len = strlen(p))) >= PATH_MAX) {
149                         warnx("%s: destination pathname too long", *argv);
150                         rval = 1;
151                 } else {
152                         memmove(endp, p, (size_t)len + 1);
153                         if (do_move(*argv, path))
154                                 rval = 1;
155                 }
156         }
157         exit(rval);
158 }
159
160 static int
161 do_move(const char *from, const char *to)
162 {
163         struct stat sb;
164         int ask, ch, first;
165         char modep[15];
166
167         /*
168          * Check access.  If interactive and file exists, ask user if it
169          * should be replaced.  Otherwise if file exists but isn't writable
170          * make sure the user wants to clobber it.
171          */
172         if (!fflg && !access(to, F_OK)) {
173
174                 /* prompt only if source exist */
175                 if (lstat(from, &sb) == -1) {
176                         warn("%s", from);
177                         return (1);
178                 }
179
180 #define YESNO "(y/n [n]) "
181                 ask = 0;
182                 if (nflg) {
183                         if (vflg)
184                                 printf("%s not overwritten\n", to);
185                         return (0);
186                 } else if (iflg) {
187                         (void)fprintf(stderr, "overwrite %s? %s", to, YESNO);
188                         ask = 1;
189                 } else if (access(to, W_OK) && !stat(to, &sb) && isatty(STDIN_FILENO)) {
190                         strmode(sb.st_mode, modep);
191                         (void)fprintf(stderr, "override %s%s%s/%s for %s? %s",
192                             modep + 1, modep[9] == ' ' ? "" : " ",
193                             user_from_uid((unsigned long)sb.st_uid, 0),
194                             group_from_gid((unsigned long)sb.st_gid, 0), to, YESNO);
195                         ask = 1;
196                 }
197                 if (ask) {
198                         first = ch = getchar();
199                         while (ch != '\n' && ch != EOF)
200                                 ch = getchar();
201                         if (first != 'y' && first != 'Y') {
202                                 (void)fprintf(stderr, "not overwritten\n");
203                                 return (0);
204                         }
205                 }
206         }
207         /*
208          * Rename on FreeBSD will fail with EISDIR and ENOTDIR, before failing
209          * with EXDEV.  Therefore, copy() doesn't have to perform the checks
210          * specified in the Step 3 of the POSIX mv specification.
211          */
212         if (!rename(from, to)) {
213                 if (vflg)
214                         printf("%s -> %s\n", from, to);
215                 return (0);
216         }
217
218         if (errno == EXDEV) {
219                 struct statfs sfs;
220                 char path[PATH_MAX];
221                 int target_is_file = 0;
222
223                 if (!lstat(to, &sb) && S_ISREG(sb.st_mode))
224                         target_is_file = 1;
225                 /*
226                  * If the source is a symbolic link and is on another
227                  * filesystem, it can be recreated at the destination.
228                  */
229                 if (lstat(from, &sb) == -1) {
230                         warn("%s", from);
231                         return (1);
232                 }
233                 /* Can't mv(1) directory into a file ever. */
234                 if (target_is_file && S_ISDIR(sb.st_mode)) {
235                         warn("cannot overwrite %s with directory", to);
236                         return (1);
237                 }
238                 if (!S_ISLNK(sb.st_mode)) {
239                         /* Can't mv(1) a mount point. */
240                         if (realpath(from, path) == NULL) {
241                                 warn("cannot resolve %s: %s", from, path);
242                                 return (1);
243                         }
244                         if (!statfs(path, &sfs) &&
245                             !strcmp(path, sfs.f_mntonname)) {
246                                 warnx("cannot rename a mount point");
247                                 return (1);
248                         }
249                 }
250         } else {
251                 warn("rename %s to %s", from, to);
252                 return (1);
253         }
254
255         /*
256          * If rename fails because we're trying to cross devices, and
257          * it's a regular file, do the copy internally; otherwise, use
258          * cp and rm.
259          */
260         if (lstat(from, &sb)) {
261                 warn("%s", from);
262                 return (1);
263         }
264         return (S_ISREG(sb.st_mode) ?
265             fastcopy(from, to, &sb) : copy(from, to));
266 }
267
268 static int
269 fastcopy(const char *from, const char *to, struct stat *sbp)
270 {
271         struct timeval tval[2];
272         static u_int blen = MAXPHYS;
273         static char *bp = NULL;
274         mode_t oldmode;
275         int from_fd, to_fd;
276         ssize_t nread;
277
278         if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
279                 warn("fastcopy: open() failed (from): %s", from);
280                 return (1);
281         }
282         if (bp == NULL && (bp = malloc((size_t)blen)) == NULL) {
283                 warnx("malloc(%u) failed", blen);
284                 return (1);
285         }
286         while ((to_fd =
287             open(to, O_CREAT | O_EXCL | O_TRUNC | O_WRONLY, 0)) < 0) {
288                 if (errno == EEXIST && unlink(to) == 0)
289                         continue;
290                 warn("fastcopy: open() failed (to): %s", to);
291                 (void)close(from_fd);
292                 return (1);
293         }
294         while ((nread = read(from_fd, bp, (size_t)blen)) > 0)
295                 if (write(to_fd, bp, (size_t)nread) != nread) {
296                         warn("fastcopy: write() failed: %s", to);
297                         goto err;
298                 }
299         if (nread < 0) {
300                 warn("fastcopy: read() failed: %s", from);
301 err:            if (unlink(to))
302                         warn("%s: remove", to);
303                 (void)close(from_fd);
304                 (void)close(to_fd);
305                 return (1);
306         }
307
308         oldmode = sbp->st_mode & ALLPERMS;
309         if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
310                 warn("%s: set owner/group (was: %lu/%lu)", to,
311                     (u_long)sbp->st_uid, (u_long)sbp->st_gid);
312                 if (oldmode & (S_ISUID | S_ISGID)) {
313                         warnx(
314 "%s: owner/group changed; clearing suid/sgid (mode was 0%03o)",
315                             to, oldmode);
316                         sbp->st_mode &= ~(S_ISUID | S_ISGID);
317                 }
318         }
319         if (fchmod(to_fd, sbp->st_mode))
320                 warn("%s: set mode (was: 0%03o)", to, oldmode);
321
322         (void)close(from_fd);
323         /*
324          * XXX
325          * NFS doesn't support chflags; ignore errors unless there's reason
326          * to believe we're losing bits.  (Note, this still won't be right
327          * if the server supports flags and we were trying to *remove* flags
328          * on a file that we copied, i.e., that we didn't create.)
329          */
330         errno = 0;
331         if (fchflags(to_fd, (u_long)sbp->st_flags))
332                 if (errno != EOPNOTSUPP || sbp->st_flags != 0)
333                         warn("%s: set flags (was: 0%07o)", to, sbp->st_flags);
334
335         tval[0].tv_sec = sbp->st_atime;
336         tval[1].tv_sec = sbp->st_mtime;
337         tval[0].tv_usec = tval[1].tv_usec = 0;
338         if (utimes(to, tval))
339                 warn("%s: set times", to);
340
341         if (close(to_fd)) {
342                 warn("%s", to);
343                 return (1);
344         }
345
346         if (unlink(from)) {
347                 warn("%s: remove", from);
348                 return (1);
349         }
350         if (vflg)
351                 printf("%s -> %s\n", from, to);
352         return (0);
353 }
354
355 static int
356 copy(const char *from, const char *to)
357 {
358         struct stat sb;
359         int pid, status;
360
361         if (lstat(to, &sb) == 0) {
362                 /* Destination path exists. */
363                 if (S_ISDIR(sb.st_mode)) {
364                         if (rmdir(to) != 0) {
365                                 warn("rmdir %s", to);
366                                 return (1);
367                         }
368                 } else {
369                         if (unlink(to) != 0) {
370                                 warn("unlink %s", to);
371                                 return (1);
372                         }
373                 }
374         } else if (errno != ENOENT) {
375                 warn("%s", to);
376                 return (1);
377         }
378
379         /* Copy source to destination. */
380         if (!(pid = vfork())) {
381                 execl(_PATH_CP, "mv", vflg ? "-PRpv" : "-PRp", "--", from, to,
382                     (char *)NULL);
383                 _exit(EXEC_FAILED);
384         }
385         if (waitpid(pid, &status, 0) == -1) {
386                 warn("%s %s %s: waitpid", _PATH_CP, from, to);
387                 return (1);
388         }
389         if (!WIFEXITED(status)) {
390                 warnx("%s %s %s: did not terminate normally",
391                     _PATH_CP, from, to);
392                 return (1);
393         }
394         switch (WEXITSTATUS(status)) {
395         case 0:
396                 break;
397         case EXEC_FAILED:
398                 warnx("%s %s %s: exec failed", _PATH_CP, from, to);
399                 return (1);
400         default:
401                 warnx("%s %s %s: terminated with %d (non-zero) status",
402                     _PATH_CP, from, to, WEXITSTATUS(status));
403                 return (1);
404         }
405
406         /* Delete the source. */
407         if (!(pid = vfork())) {
408                 execl(_PATH_RM, "mv", "-rf", "--", from, (char *)NULL);
409                 _exit(EXEC_FAILED);
410         }
411         if (waitpid(pid, &status, 0) == -1) {
412                 warn("%s %s: waitpid", _PATH_RM, from);
413                 return (1);
414         }
415         if (!WIFEXITED(status)) {
416                 warnx("%s %s: did not terminate normally", _PATH_RM, from);
417                 return (1);
418         }
419         switch (WEXITSTATUS(status)) {
420         case 0:
421                 break;
422         case EXEC_FAILED:
423                 warnx("%s %s: exec failed", _PATH_RM, from);
424                 return (1);
425         default:
426                 warnx("%s %s: terminated with %d (non-zero) status",
427                     _PATH_RM, from, WEXITSTATUS(status));
428                 return (1);
429         }
430         return (0);
431 }
432
433 static void
434 usage(void)
435 {
436
437         (void)fprintf(stderr, "%s\n%s\n",
438                       "usage: mv [-f | -i | -n] [-hv] source target",
439                       "       mv [-f | -i | -n] [-v] source ... directory");
440         exit(EX_USAGE);
441 }
442
443 static void
444 siginfo(int notused __unused)
445 {
446         info = 1;
447 }