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