]> arthur.barton.de Git - netatalk.git/blob - bin/ad/ad_mv.c
Better EC_EXIT
[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 #include <libgen.h>
30
31 #include <atalk/ftw.h>
32 #include <atalk/adouble.h>
33 #include <atalk/vfs.h>
34 #include <atalk/util.h>
35 #include <atalk/unix.h>
36 #include <atalk/volume.h>
37 #include <atalk/volinfo.h>
38 #include <atalk/bstrlib.h>
39 #include <atalk/bstradd.h>
40 #include <atalk/queue.h>
41
42 #include "ad.h"
43
44 #define STRIP_TRAILING_SLASH(p) {                                   \
45         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')  \
46             *--(p).p_end = 0;                                       \
47     }
48
49 static int fflg, iflg, nflg, vflg;
50
51 static afpvol_t svolume, dvolume;
52 static cnid_t did, pdid;
53 static volatile sig_atomic_t alarmed;
54 static char *adexecp;
55 static char           *netatalk_dirs[] = {
56     ".AppleDouble",
57     ".AppleDB",
58     ".AppleDesktop",
59     NULL
60 };
61
62 static int copy(const char *, const char *);
63 static int do_move(const char *, const char *);
64 static int fastcopy(const char *, const char *, struct stat *);
65 static void preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
66                              const char *dest_path);
67 /*
68   Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop"
69   Returns pointer to name or NULL.
70 */
71 static const char *check_netatalk_dirs(const char *name)
72 {
73     int c;
74
75     for (c=0; netatalk_dirs[c]; c++) {
76         if ((strcmp(name, netatalk_dirs[c])) == 0)
77             return netatalk_dirs[c];
78     }
79     return NULL;
80 }
81
82 /*
83   SIGNAL handling:
84   catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
85 */
86
87 static void sig_handler(int signo)
88 {
89     alarmed = 1;
90     return;
91 }
92
93 static void set_signal(void)
94 {
95     struct sigaction sv;
96
97     sv.sa_handler = sig_handler;
98     sv.sa_flags = SA_RESTART;
99     sigemptyset(&sv.sa_mask);
100     if (sigaction(SIGTERM, &sv, NULL) < 0)
101         ERROR("error in sigaction(SIGTERM): %s", strerror(errno));
102
103     if (sigaction(SIGINT, &sv, NULL) < 0)
104         ERROR("error in sigaction(SIGINT): %s", strerror(errno));
105
106     memset(&sv, 0, sizeof(struct sigaction));
107     sv.sa_handler = SIG_IGN;
108     sigemptyset(&sv.sa_mask);
109
110     if (sigaction(SIGABRT, &sv, NULL) < 0)
111         ERROR("error in sigaction(SIGABRT): %s", strerror(errno));
112
113     if (sigaction(SIGHUP, &sv, NULL) < 0)
114         ERROR("error in sigaction(SIGHUP): %s", strerror(errno));
115
116     if (sigaction(SIGQUIT, &sv, NULL) < 0)
117         ERROR("error in sigaction(SIGQUIT): %s", strerror(errno));
118 }
119
120 static void usage_mv(void)
121 {
122     printf(
123         "Usage: ad mv [-f | -i | -n] [-v] source target\n"
124         "       ad mv [-f | -i | -n] [-v] source ... directory\n\n"
125         "Move files around within an AFP volume, updating the CNID\n"
126         "database as needed. If either:\n"
127         " - source or destination is not an AFP volume\n"
128         " - source volume != destinatio volume\n"
129         "the files are copied and removed from the source.\n\n"
130         "The following options are available:\n\n"
131         "   -f   Do not prompt for confirmation before overwriting the destination\n"
132         "        path.  (The -f option overrides any previous -i or -n options.)\n"
133         "   -i   Cause mv to write a prompt to standard error before moving a file\n"
134         "        that would overwrite an existing file.  If the response from the\n"
135         "        standard input begins with the character `y' or `Y', the move is\n"
136         "        attempted.  (The -i option overrides any previous -f or -n\n"
137         "        options.)\n"
138         "   -n   Do not overwrite an existing file.  (The -n option overrides any\n"
139         "        previous -f or -i options.)\n"
140         "   -v   Cause mv to be verbose, showing files after they are moved.\n"
141         );
142     exit(EXIT_FAILURE);
143 }
144
145 int ad_mv(int argc, char *argv[])
146 {
147     size_t baselen, len;
148     int rval;
149     char *p, *endp;
150     struct stat sb;
151     int ch;
152     char path[MAXPATHLEN];
153
154
155     pdid = htonl(1);
156     did = htonl(2);
157
158     adexecp = argv[0];
159     argc--;
160     argv++;
161
162     while ((ch = getopt(argc, argv, "finv")) != -1)
163         switch (ch) {
164         case 'i':
165             iflg = 1;
166             fflg = nflg = 0;
167             break;
168         case 'f':
169             fflg = 1;
170             iflg = nflg = 0;
171             break;
172         case 'n':
173             nflg = 1;
174             fflg = iflg = 0;
175             break;
176         case 'v':
177             vflg = 1;
178             break;
179         default:
180             usage_mv();
181         }
182
183     argc -= optind;
184     argv += optind;
185
186     if (argc < 2)
187         usage_mv();
188
189     set_signal();
190     cnid_init();
191     if (openvol(argv[argc - 1], &dvolume) != 0) {
192         SLOG("Error opening CNID database for %s: ", argv[argc - 1]);
193         return 1;
194     }
195
196     /*
197      * If the stat on the target fails or the target isn't a directory,
198      * try the move.  More than 2 arguments is an error in this case.
199      */
200     if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
201         if (argc > 2)
202             usage_mv();
203         if (openvol(argv[0], &svolume) != 0) {
204             SLOG("Error opening CNID database for %s: ", argv[0]);
205             return 1;
206         }
207         rval = do_move(argv[0], argv[1]);
208         closevol(&svolume);
209         closevol(&dvolume);
210         return 1;
211     }
212
213     /* It's a directory, move each file into it. */
214     if (strlen(argv[argc - 1]) > sizeof(path) - 1)
215         ERROR("%s: destination pathname too long", *argv);
216
217     (void)strcpy(path, argv[argc - 1]);
218     baselen = strlen(path);
219     endp = &path[baselen];
220     if (!baselen || *(endp - 1) != '/') {
221         *endp++ = '/';
222         ++baselen;
223     }
224
225     for (rval = 0; --argc; ++argv) {
226         /*
227          * Find the last component of the source pathname.  It
228          * may have trailing slashes.
229          */
230         p = *argv + strlen(*argv);
231         while (p != *argv && p[-1] == '/')
232             --p;
233         while (p != *argv && p[-1] != '/')
234             --p;
235
236         if ((baselen + (len = strlen(p))) >= PATH_MAX) {
237             SLOG("%s: destination pathname too long", *argv);
238             rval = 1;
239         } else {
240             memmove(endp, p, (size_t)len + 1);
241             if (openvol(*argv, &svolume) != 0) {
242                 SLOG("Error opening CNID database for %s: ", argv[0]);
243                 rval = 1;
244                 goto exit;
245             }
246             if (do_move(*argv, path))
247                 rval = 1;
248             closevol(&svolume);
249         }
250     }
251
252 exit:
253     closevol(&dvolume);
254     return rval;
255 }
256
257 static int do_move(const char *from, const char *to)
258 {
259     struct stat sb;
260     int ask, ch, first;
261
262     /*
263      * Check access.  If interactive and file exists, ask user if it
264      * should be replaced.  Otherwise if file exists but isn't writable
265      * make sure the user wants to clobber it.
266      */
267     if (!fflg && !access(to, F_OK)) {
268
269         /* prompt only if source exist */
270         if (lstat(from, &sb) == -1) {
271             SLOG("%s: %s", from, strerror(errno));
272             return (1);
273         }
274
275         ask = 0;
276         if (nflg) {
277             if (vflg)
278                 printf("%s not overwritten\n", to);
279             return (0);
280         } else if (iflg) {
281             (void)fprintf(stderr, "overwrite %s? (y/n [n]) ", to);
282             ask = 1;
283         } else if (access(to, W_OK) && !stat(to, &sb)) {
284             (void)fprintf(stderr, "override for %s? (y/n [n]) ", to);
285             ask = 1;
286         }
287         if (ask) {
288             first = ch = getchar();
289             while (ch != '\n' && ch != EOF)
290                 ch = getchar();
291             if (first != 'y' && first != 'Y') {
292                 (void)fprintf(stderr, "not overwritten\n");
293                 return (0);
294             }
295         }
296     }
297
298     int mustcopy = 0;
299     /* 
300      * Besides the usual EXDEV we copy instead of moving if
301      * 1) source AFP volume != dest AFP volume
302      * 2) either source or dest isn't even an AFP volume
303      */
304     if (!svolume.volinfo.v_path
305         || !dvolume.volinfo.v_path
306         || strcmp(svolume.volinfo.v_path, dvolume.volinfo.v_path) != 0)
307         mustcopy = 1;
308     
309     cnid_t cnid = 0;
310     if (!mustcopy) {
311         if ((cnid = cnid_for_path(&svolume, from, &did)) == CNID_INVALID) {
312             SLOG("Couldn't resolve CNID for %s", from);
313             return -1;
314         }
315
316         if (stat(from, &sb) != 0) {
317             SLOG("Cant stat %s: %s", to, strerror(errno));
318             return -1;
319         }
320
321         if (rename(from, to) != 0) {
322             if (errno == EXDEV) {
323                 mustcopy = 1;
324                 char path[MAXPATHLEN];
325
326                 /*
327                  * If the source is a symbolic link and is on another
328                  * filesystem, it can be recreated at the destination.
329                  */
330                 if (lstat(from, &sb) == -1) {
331                     SLOG("%s: %s", from, strerror(errno));
332                     return (-1);
333                 }
334                 if (!S_ISLNK(sb.st_mode)) {
335                     /* Can't mv(1) a mount point. */
336                     if (realpath(from, path) == NULL) {
337                         SLOG("cannot resolve %s: %s: %s", from, path, strerror(errno));
338                         return (1);
339                     }
340                 }
341             } else { /* != EXDEV */
342                 SLOG("rename %s to %s: %s", from, to, strerror(errno));
343                 return (1);
344             }
345         } /* rename != 0*/
346         
347         switch (sb.st_mode & S_IFMT) {
348         case S_IFREG:
349             if (dvolume.volume.vfs->vfs_renamefile(&dvolume.volume, -1, from, to) != 0) {
350                 SLOG("Error moving adouble file for %s", from);
351                 return -1;
352             }
353             break;
354         case S_IFDIR:
355             break;
356         default:
357             SLOG("Not a file or dir: %s", from);
358             return -1;
359         }
360     
361         /* get CNID of new parent dir */
362         cnid_t newpdid, newdid;
363         if ((newdid = cnid_for_paths_parent(&dvolume, to, &newpdid)) == CNID_INVALID) {
364             SLOG("Couldn't resolve CNID for parent of %s", to);
365             return -1;
366         }
367
368         if (stat(to, &sb) != 0) {
369             SLOG("Cant stat %s: %s", to, strerror(errno));
370             return 1;
371         }
372
373         char *p = strdup(to);
374         char *name = basename(p);
375         if (cnid_update(dvolume.volume.v_cdb, cnid, &sb, newdid, name, strlen(name)) != 0) {
376             SLOG("Cant update CNID for: %s", to);
377             return 1;
378         }
379         free(p);
380
381         struct adouble ad;
382         ad_init(&ad, dvolume.volinfo.v_adouble, dvolume.volinfo.v_ad_options);
383         if (ad_open_metadata(to, S_ISDIR(sb.st_mode) ? ADFLAGS_DIR : 0, O_RDWR, &ad) != 0) {
384             SLOG("Error opening adouble for: %s", to);
385             return 1;
386         }
387         ad_setid(&ad, sb.st_dev, sb.st_ino, cnid, newdid, dvolume.db_stamp);
388         ad_flush(&ad);
389         ad_close_metadata(&ad);
390
391         if (vflg)
392             printf("%s -> %s\n", from, to);
393         return (0);
394     }
395     
396     if (mustcopy) {
397         /*
398          * If rename fails because we're trying to cross devices, and
399          * it's a regular file, do the copy internally; otherwise, use
400          * cp and rm.
401          */
402         if (lstat(from, &sb)) {
403             SLOG("%s: %s", from, strerror(errno));
404             return (1);
405         }
406         return (S_ISREG(sb.st_mode) ?
407                 fastcopy(from, to, &sb) : copy(from, to));
408     }
409     return 1;
410 }
411
412 static int fastcopy(const char *from, const char *to, struct stat *sbp)
413 {
414     struct timeval tval[2];
415     static u_int blen;
416     static char *bp;
417     mode_t oldmode;
418     int nread, from_fd, to_fd;
419
420     if ((from_fd = open(from, O_RDONLY, 0)) < 0) {
421         SLOG("%s: %s", from, strerror(errno));
422         return (1);
423     }
424     if (blen < sbp->st_blksize) {
425         if (bp != NULL)
426             free(bp);
427         if ((bp = malloc((size_t)sbp->st_blksize)) == NULL) {
428             blen = 0;
429             SLOG("malloc failed");
430             return (1);
431         }
432         blen = sbp->st_blksize;
433     }
434     while ((to_fd = open(to, O_CREAT | O_EXCL | O_TRUNC | O_WRONLY, 0)) < 0) {
435         if (errno == EEXIST && unlink(to) == 0)
436             continue;
437         SLOG("%s: %s", to, strerror(errno));
438         (void)close(from_fd);
439         return (1);
440     }
441     while ((nread = read(from_fd, bp, (size_t)blen)) > 0)
442         if (write(to_fd, bp, (size_t)nread) != nread) {
443             SLOG("%s: %s", to, strerror(errno));
444             goto err;
445         }
446     if (nread < 0) {
447         SLOG("%s: %s", from, strerror(errno));
448     err:
449         if (unlink(to))
450             SLOG("%s: remove", to, strerror(errno));
451         (void)close(from_fd);
452         (void)close(to_fd);
453         return (1);
454     }
455
456     oldmode = sbp->st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID);
457     if (fchown(to_fd, sbp->st_uid, sbp->st_gid)) {
458         SLOG("%s: set owner/group (was: %lu/%lu)", to,
459              (u_long)sbp->st_uid, (u_long)sbp->st_gid, strerror(errno));
460         if (oldmode & S_ISUID) {
461             SLOG("%s: owner/group changed; clearing suid (mode was 0%03o)",
462                  to, oldmode);
463             sbp->st_mode &= ~S_ISUID;
464         }
465     }
466     if (fchmod(to_fd, sbp->st_mode))
467         SLOG("%s: set mode (was: 0%03o): %s", to, oldmode, strerror(errno));
468     /*
469      * POSIX 1003.2c states that if _POSIX_ACL_EXTENDED is in effect
470      * for dest_file, then its ACLs shall reflect the ACLs of the
471      * source_file.
472      */
473     preserve_fd_acls(from_fd, to_fd, from, to);
474     (void)close(from_fd);
475
476     tval[0].tv_sec = sbp->st_atime;
477     tval[1].tv_sec = sbp->st_mtime;
478     tval[0].tv_usec = tval[1].tv_usec = 0;
479     if (utimes(to, tval))
480         SLOG("%s: set times: %s", to, strerror(errno));
481
482     if (close(to_fd)) {
483         SLOG("%s: %s", to, strerror(errno));
484         return (1);
485     }
486
487     if (unlink(from)) {
488         SLOG("%s: remove: %s", from, strerror(errno));
489         return (1);
490     }
491     if (vflg)
492         printf("%s -> %s\n", from, to);
493     return 0;
494 }
495
496 static int copy(const char *from, const char *to)
497 {
498     struct stat sb;
499     int pid, status;
500
501     if (lstat(to, &sb) == 0) {
502         /* Destination path exists. */
503         if (S_ISDIR(sb.st_mode)) {
504             if (rmdir(to) != 0) {
505                 SLOG("rmdir %s: %s", to, strerror(errno));
506                 return (1);
507             }
508         } else {
509             if (unlink(to) != 0) {
510                 SLOG("unlink %s: %s", to, strerror(errno));
511                 return (1);
512             }
513         }
514     } else if (errno != ENOENT) {
515         SLOG("%s: %s", to, strerror(errno));
516         return (1);
517     }
518
519     /* Copy source to destination. */
520     if (!(pid = fork())) {
521         execl(adexecp, "ad", "cp", vflg ? "-Rpv" : "-Rp", from, to, (char *)NULL);
522         _exit(1);
523     }
524     while ((waitpid(pid, &status, 0)) == -1) {
525         if (errno == EINTR)
526             continue;
527         SLOG("%s %s %s: waitpid: %s", adexecp, from, to, strerror(errno));
528         return (1);
529     }
530     if (!WIFEXITED(status)) {
531         SLOG("%s %s %s: did not terminate normally", adexecp, from, to);
532         return (1);
533     }
534     switch (WEXITSTATUS(status)) {
535     case 0:
536         break;
537     default:
538         SLOG("%s cp %s %s: terminated with %d (non-zero) status",
539               adexecp, from, to, WEXITSTATUS(status));
540         return (1);
541     }
542
543     /* Delete the source. */
544     if (!(pid = fork())) {
545         execl(adexecp, "ad", "rm", "-R", from, (char *)NULL);
546         _exit(1);
547     }
548     while ((waitpid(pid, &status, 0)) == -1) {
549         if (errno == EINTR)
550             continue;
551         SLOG("%s rm %s: waitpid: %s", adexecp, from, strerror(errno));
552         return (1);
553     }
554     if (!WIFEXITED(status)) {
555         SLOG("%s rm %s: did not terminate normally", adexecp, from);
556         return (1);
557     }
558     switch (WEXITSTATUS(status)) {
559     case 0:
560         break;
561     default:
562         SLOG("%s rm %s: terminated with %d (non-zero) status",
563               adexecp, from, WEXITSTATUS(status));
564         return (1);
565     }
566     return 0;
567 }
568
569 static void
570 preserve_fd_acls(int source_fd,
571                  int dest_fd,
572                  const char *source_path,
573                  const char *dest_path)
574 {
575     ;
576 }