]> arthur.barton.de Git - netatalk.git/blob - bin/ad/ad_mv.c
f9bc64d3986a58293188f7c4715b2a0634c1ff04
[netatalk.git] / bin / ad / ad_mv.c
1 /*
2  * Copyright (c) 2010, Frank Lahm <franklahm@googlemail.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #ifdef HAVE_CONFIG_H
16 #include "config.h"
17 #endif /* HAVE_CONFIG_H */
18
19 #include <sys/types.h>
20 #include <sys/wait.h>
21 #include <sys/stat.h>
22 #include <errno.h>
23 #include <limits.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29
30 #include <atalk/ftw.h>
31 #include <atalk/adouble.h>
32 #include <atalk/vfs.h>
33 #include <atalk/util.h>
34 #include <atalk/unix.h>
35 #include <atalk/volume.h>
36 #include <atalk/volinfo.h>
37 #include <atalk/bstrlib.h>
38 #include <atalk/bstradd.h>
39 #include <atalk/queue.h>
40
41 #include "ad.h"
42
43 #define STRIP_TRAILING_SLASH(p) {                                   \
44         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')  \
45             *--(p).p_end = 0;                                       \
46     }
47
48 static int fflg, iflg, nflg, vflg;
49
50 static afpvol_t svolume, dvolume;
51 static cnid_t did, pdid;
52 static volatile sig_atomic_t alarmed;
53 static char *adexecp;
54 static char           *netatalk_dirs[] = {
55     ".AppleDouble",
56     ".AppleDB",
57     ".AppleDesktop",
58     NULL
59 };
60
61 static int copy(const char *, const char *);
62 static int do_move(const char *, const char *);
63 static int fastcopy(const char *, const char *, struct stat *);
64 static void preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
65                              const char *dest_path);
66 /*
67   Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop"
68   Returns pointer to name or NULL.
69 */
70 static const char *check_netatalk_dirs(const char *name)
71 {
72     int c;
73
74     for (c=0; netatalk_dirs[c]; c++) {
75         if ((strcmp(name, netatalk_dirs[c])) == 0)
76             return netatalk_dirs[c];
77     }
78     return NULL;
79 }
80
81 /*
82   SIGNAL handling:
83   catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
84 */
85
86 static void sig_handler(int signo)
87 {
88     alarmed = 1;
89     return;
90 }
91
92 static void set_signal(void)
93 {
94     struct sigaction sv;
95
96     sv.sa_handler = sig_handler;
97     sv.sa_flags = SA_RESTART;
98     sigemptyset(&sv.sa_mask);
99     if (sigaction(SIGTERM, &sv, NULL) < 0)
100         ERROR("error in sigaction(SIGTERM): %s", strerror(errno));
101
102     if (sigaction(SIGINT, &sv, NULL) < 0)
103         ERROR("error in sigaction(SIGINT): %s", strerror(errno));
104
105     memset(&sv, 0, sizeof(struct sigaction));
106     sv.sa_handler = SIG_IGN;
107     sigemptyset(&sv.sa_mask);
108
109     if (sigaction(SIGABRT, &sv, NULL) < 0)
110         ERROR("error in sigaction(SIGABRT): %s", strerror(errno));
111
112     if (sigaction(SIGHUP, &sv, NULL) < 0)
113         ERROR("error in sigaction(SIGHUP): %s", strerror(errno));
114
115     if (sigaction(SIGQUIT, &sv, NULL) < 0)
116         ERROR("error in sigaction(SIGQUIT): %s", strerror(errno));
117 }
118
119 static void usage_mv(void)
120 {
121     printf(
122         "Usage: ad mv [-f | -i | -n] [-v] source target\n"
123         "       ad mv [-f | -i | -n] [-v] source ... directory\n"
124         );
125     exit(EXIT_FAILURE);
126 }
127
128 int ad_mv(int argc, char *argv[])
129 {
130     size_t baselen, len;
131     int rval;
132     char *p, *endp;
133     struct stat sb;
134     int ch;
135     char path[MAXPATHLEN];
136
137
138     pdid = htonl(1);
139     did = htonl(2);
140
141     adexecp = argv[0];
142     argc--;
143     argv++;
144
145     while ((ch = getopt(argc, argv, "finv")) != -1)
146         switch (ch) {
147         case 'i':
148             iflg = 1;
149             fflg = nflg = 0;
150             break;
151         case 'f':
152             fflg = 1;
153             iflg = nflg = 0;
154             break;
155         case 'n':
156             nflg = 1;
157             fflg = iflg = 0;
158             break;
159         case 'v':
160             vflg = 1;
161             break;
162         default:
163             usage_mv();
164         }
165
166     argc -= optind;
167     argv += optind;
168
169     if (argc < 2)
170         usage_mv();
171
172     set_signal();
173     cnid_init();
174     if (openvol(argv[argc - 1], &dvolume) != 0) {
175         SLOG("Error opening CNID database for %s: ", argv[argc - 1]);
176         return 1;
177     }
178
179     /*
180      * If the stat on the target fails or the target isn't a directory,
181      * try the move.  More than 2 arguments is an error in this case.
182      */
183     if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
184         if (argc > 2)
185             usage_mv();
186         if (openvol(argv[0], &svolume) != 0) {
187             SLOG("Error opening CNID database for %s: ", argv[0]);
188             return 1;
189         }
190         rval = do_move(argv[0], argv[1]);
191         closevol(&svolume);
192         closevol(&dvolume);
193     }
194
195     /* It's a directory, move each file into it. */
196     if (strlen(argv[argc - 1]) > sizeof(path) - 1)
197         ERROR("%s: destination pathname too long", *argv);
198
199     (void)strcpy(path, argv[argc - 1]);
200     baselen = strlen(path);
201     endp = &path[baselen];
202     if (!baselen || *(endp - 1) != '/') {
203         *endp++ = '/';
204         ++baselen;
205     }
206
207     for (rval = 0; --argc; ++argv) {
208         /*
209          * Find the last component of the source pathname.  It
210          * may have trailing slashes.
211          */
212         p = *argv + strlen(*argv);
213         while (p != *argv && p[-1] == '/')
214             --p;
215         while (p != *argv && p[-1] != '/')
216             --p;
217
218         if ((baselen + (len = strlen(p))) >= PATH_MAX) {
219             SLOG("%s: destination pathname too long", *argv);
220             rval = 1;
221         } else {
222             memmove(endp, p, (size_t)len + 1);
223             if (openvol(*argv, &svolume) != 0) {
224                 SLOG("Error opening CNID database for %s: ", argv[0]);
225                 rval = 1;
226                 goto exit;
227             }
228             if (do_move(*argv, path))
229                 rval = 1;
230             closevol(&svolume);
231         }
232     }
233
234 exit:
235     closevol(&dvolume);
236     return rval;
237 }
238
239 static int do_move(const char *from, const char *to)
240 {
241     struct stat sb;
242     int ask, ch, first;
243
244     /*
245      * Check access.  If interactive and file exists, ask user if it
246      * should be replaced.  Otherwise if file exists but isn't writable
247      * make sure the user wants to clobber it.
248      */
249     if (!fflg && !access(to, F_OK)) {
250
251         /* prompt only if source exist */
252         if (lstat(from, &sb) == -1) {
253             SLOG("%s: %s", from, strerror(errno));
254             return (1);
255         }
256
257         ask = 0;
258         if (nflg) {
259             if (vflg)
260                 printf("%s not overwritten\n", to);
261             return (0);
262         } else if (iflg) {
263             (void)fprintf(stderr, "overwrite %s? (y/n [n]) ", to);
264             ask = 1;
265         } else if (access(to, W_OK) && !stat(to, &sb)) {
266             (void)fprintf(stderr, "override for %s? (y/n [n]) ", to);
267             ask = 1;
268         }
269         if (ask) {
270             first = ch = getchar();
271             while (ch != '\n' && ch != EOF)
272                 ch = getchar();
273             if (first != 'y' && first != 'Y') {
274                 (void)fprintf(stderr, "not overwritten\n");
275                 return (0);
276             }
277         }
278     }
279
280     if (!rename(from, to)) {
281         if (vflg)
282             printf("%s -> %s\n", from, to);
283         return (0);
284     }
285
286     if (errno == EXDEV) {
287         char path[MAXPATHLEN];
288
289         /*
290          * If the source is a symbolic link and is on another
291          * filesystem, it can be recreated at the destination.
292          */
293         if (lstat(from, &sb) == -1) {
294             SLOG("%s: %s", from, strerror(errno));
295             return (1);
296         }
297         if (!S_ISLNK(sb.st_mode)) {
298             /* Can't mv(1) a mount point. */
299             if (realpath(from, path) == NULL) {
300                 SLOG("cannot resolve %s: %s: %s", from, path, strerror(errno));
301                 return (1);
302             }
303         }
304     } else {
305         SLOG("rename %s to %s: %s", from, to, strerror(errno));
306         return (1);
307     }
308
309     /*
310      * If rename fails because we're trying to cross devices, and
311      * it's a regular file, do the copy internally; otherwise, use
312      * cp and rm.
313      */
314     if (lstat(from, &sb)) {
315         SLOG("%s: %s", from, strerror(errno));
316         return (1);
317     }
318     return (S_ISREG(sb.st_mode) ?
319             fastcopy(from, to, &sb) : copy(from, to));
320 }
321
322 static int fastcopy(const char *from, const char *to, struct stat *sbp)
323 {
324     struct timeval tval[2];
325     static u_int blen;
326     static char *bp;
327     mode_t oldmode;
328     int nread, from_fd, to_fd;
329
330     if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
331         SLOG("%s: %s", from, strerror(errno));
332         return (1);
333     }
334     if (blen < sbp->st_blksize) {
335         if (bp != NULL)
336             free(bp);
337         if ((bp = malloc((size_t)sbp->st_blksize)) == NULL) {
338             blen = 0;
339             SLOG("malloc failed");
340             return (1);
341         }
342         blen = sbp->st_blksize;
343     }
344     while ((to_fd = open(to, O_CREAT | O_EXCL | O_TRUNC | O_WRONLY, 0)) < 0) {
345         if (errno == EEXIST && unlink(to) == 0)
346             continue;
347         SLOG("%s: %s", to, strerror(errno));
348         (void)close(from_fd);
349         return (1);
350     }
351     while ((nread = read(from_fd, bp, (size_t)blen)) > 0)
352         if (write(to_fd, bp, (size_t)nread) != nread) {
353             SLOG("%s: %s", to, strerror(errno));
354             goto err;
355         }
356     if (nread < 0) {
357         SLOG("%s: %s", from, strerror(errno));
358     err:
359         if (unlink(to))
360             SLOG("%s: remove", to, strerror(errno));
361         (void)close(from_fd);
362         (void)close(to_fd);
363         return (1);
364     }
365
366     oldmode = sbp->st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID);
367     if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
368         SLOG("%s: set owner/group (was: %lu/%lu)", to,
369              (u_long)sbp->st_uid, (u_long)sbp->st_gid, strerror(errno));
370         if (oldmode & S_ISUID) {
371             SLOG("%s: owner/group changed; clearing suid (mode was 0%03o)",
372                  to, oldmode);
373             sbp->st_mode &= ~S_ISUID;
374         }
375     }
376     if (fchmod(to_fd, sbp->st_mode))
377         SLOG("%s: set mode (was: 0%03o): %s", to, oldmode, strerror(errno));
378     /*
379      * POSIX 1003.2c states that if _POSIX_ACL_EXTENDED is in effect
380      * for dest_file, then its ACLs shall reflect the ACLs of the
381      * source_file.
382      */
383     preserve_fd_acls(from_fd, to_fd, from, to);
384     (void)close(from_fd);
385
386     tval[0].tv_sec = sbp->st_atime;
387     tval[1].tv_sec = sbp->st_mtime;
388     tval[0].tv_usec = tval[1].tv_usec = 0;
389     if (utimes(to, tval))
390         SLOG("%s: set times: %s", to, strerror(errno));
391
392     if (close(to_fd)) {
393         SLOG("%s: %s", to, strerror(errno));
394         return (1);
395     }
396
397     if (unlink(from)) {
398         SLOG("%s: remove: %s", from, strerror(errno));
399         return (1);
400     }
401     if (vflg)
402         printf("%s -> %s\n", from, to);
403     return 0;
404 }
405
406 static int copy(const char *from, const char *to)
407 {
408     struct stat sb;
409     int pid, status;
410
411     if (lstat(to, &sb) == 0) {
412         /* Destination path exists. */
413         if (S_ISDIR(sb.st_mode)) {
414             if (rmdir(to) != 0) {
415                 SLOG("rmdir %s: %s", to, strerror(errno));
416                 return (1);
417             }
418         } else {
419             if (unlink(to) != 0) {
420                 SLOG("unlink %s: %s", to, strerror(errno));
421                 return (1);
422             }
423         }
424     } else if (errno != ENOENT) {
425         SLOG("%s: %s", to, strerror(errno));
426         return (1);
427     }
428
429     /* Copy source to destination. */
430     if (!(pid = fork())) {
431         execl(adexecp, "cp", vflg ? "-Rpv" : "-Rp", "--", from, to, (char *)NULL);
432         _exit(1);
433     }
434     if (waitpid(pid, &status, 0) == -1) {
435         SLOG("%s %s %s: waitpid: %s", adexecp, from, to, strerror(errno));
436         return (1);
437     }
438     if (!WIFEXITED(status)) {
439         SLOG("%s %s %s: did not terminate normally", adexecp, from, to);
440         return (1);
441     }
442     switch (WEXITSTATUS(status)) {
443     case 0:
444         break;
445     default:
446         SLOG("%s %s %s: terminated with %d (non-zero) status",
447               adexecp, from, to, WEXITSTATUS(status));
448         return (1);
449     }
450
451     /* Delete the source. */
452     if (!(pid = fork())) {
453         execl(adexecp, "rm", "-Rf", "--", from, (char *)NULL);
454         _exit(1);
455     }
456     if (waitpid(pid, &status, 0) == -1) {
457         SLOG("%s %s: waitpid: %s", adexecp, from, strerror(errno));
458         return (1);
459     }
460     if (!WIFEXITED(status)) {
461         SLOG("%s %s: did not terminate normally", adexecp, from);
462         return (1);
463     }
464     switch (WEXITSTATUS(status)) {
465     case 0:
466         break;
467     default:
468         SLOG("%s %s: terminated with %d (non-zero) status",
469               adexecp, from, WEXITSTATUS(status));
470         return (1);
471     }
472     return 0;
473 }
474
475 static void
476 preserve_fd_acls(int source_fd,
477                  int dest_fd,
478                  const char *source_path,
479                  const char *dest_path)
480 {
481     ;
482 }