]> arthur.barton.de Git - netatalk.git/blob - bin/ad/ad_mv.c
Merge master
[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 void preserve_fd_acls(int source_fd, int dest_fd, const char *source_path,
64                              const char *dest_path);
65 /*
66   Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop"
67   Returns pointer to name or NULL.
68 */
69 static const char *check_netatalk_dirs(const char *name)
70 {
71     int c;
72
73     for (c=0; netatalk_dirs[c]; c++) {
74         if ((strcmp(name, netatalk_dirs[c])) == 0)
75             return netatalk_dirs[c];
76     }
77     return NULL;
78 }
79
80 /*
81   SIGNAL handling:
82   catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
83 */
84
85 static void sig_handler(int signo)
86 {
87     alarmed = 1;
88     return;
89 }
90
91 static void set_signal(void)
92 {
93     struct sigaction sv;
94
95     sv.sa_handler = sig_handler;
96     sv.sa_flags = SA_RESTART;
97     sigemptyset(&sv.sa_mask);
98     if (sigaction(SIGTERM, &sv, NULL) < 0)
99         ERROR("error in sigaction(SIGTERM): %s", strerror(errno));
100
101     if (sigaction(SIGINT, &sv, NULL) < 0)
102         ERROR("error in sigaction(SIGINT): %s", strerror(errno));
103
104     memset(&sv, 0, sizeof(struct sigaction));
105     sv.sa_handler = SIG_IGN;
106     sigemptyset(&sv.sa_mask);
107
108     if (sigaction(SIGABRT, &sv, NULL) < 0)
109         ERROR("error in sigaction(SIGABRT): %s", strerror(errno));
110
111     if (sigaction(SIGHUP, &sv, NULL) < 0)
112         ERROR("error in sigaction(SIGHUP): %s", strerror(errno));
113
114     if (sigaction(SIGQUIT, &sv, NULL) < 0)
115         ERROR("error in sigaction(SIGQUIT): %s", strerror(errno));
116 }
117
118 static void usage_mv(void)
119 {
120     printf(
121         "Usage: ad mv [-f | -i | -n] [-v] source target\n"
122         "       ad mv [-f | -i | -n] [-v] source ... directory\n\n"
123         "Move files around within an AFP volume, updating the CNID\n"
124         "database as needed. If either:\n"
125         " - source or destination is not an AFP volume\n"
126         " - source volume != destinatio volume\n"
127         "the files are copied and removed from the source.\n\n"
128         "The following options are available:\n\n"
129         "   -f   Do not prompt for confirmation before overwriting the destination\n"
130         "        path.  (The -f option overrides any previous -i or -n options.)\n"
131         "   -i   Cause mv to write a prompt to standard error before moving a file\n"
132         "        that would overwrite an existing file.  If the response from the\n"
133         "        standard input begins with the character `y' or `Y', the move is\n"
134         "        attempted.  (The -i option overrides any previous -f or -n\n"
135         "        options.)\n"
136         "   -n   Do not overwrite an existing file.  (The -n option overrides any\n"
137         "        previous -f or -i options.)\n"
138         "   -v   Cause mv to be verbose, showing files after they are moved.\n"
139         );
140     exit(EXIT_FAILURE);
141 }
142
143 int ad_mv(int argc, char *argv[])
144 {
145     size_t baselen, len;
146     int rval;
147     char *p, *endp;
148     struct stat sb;
149     int ch;
150     char path[MAXPATHLEN];
151
152
153     pdid = htonl(1);
154     did = htonl(2);
155
156     argc--;
157     argv++;
158
159     while ((ch = getopt(argc, argv, "finv")) != -1)
160         switch (ch) {
161         case 'i':
162             iflg = 1;
163             fflg = nflg = 0;
164             break;
165         case 'f':
166             fflg = 1;
167             iflg = nflg = 0;
168             break;
169         case 'n':
170             nflg = 1;
171             fflg = iflg = 0;
172             break;
173         case 'v':
174             vflg = 1;
175             break;
176         default:
177             usage_mv();
178         }
179
180     argc -= optind;
181     argv += optind;
182
183     if (argc < 2)
184         usage_mv();
185
186     set_signal();
187     cnid_init();
188     if (openvol(argv[argc - 1], &dvolume) != 0) {
189         SLOG("Error opening CNID database for %s: ", argv[argc - 1]);
190         return 1;
191     }
192
193     /*
194      * If the stat on the target fails or the target isn't a directory,
195      * try the move.  More than 2 arguments is an error in this case.
196      */
197     if (stat(argv[argc - 1], &sb) || !S_ISDIR(sb.st_mode)) {
198         if (argc > 2)
199             usage_mv();
200         if (openvol(argv[0], &svolume) != 0) {
201             SLOG("Error opening CNID database for %s: ", argv[0]);
202             return 1;
203         }
204         rval = do_move(argv[0], argv[1]);
205         closevol(&svolume);
206         closevol(&dvolume);
207         return 1;
208     }
209
210     /* It's a directory, move each file into it. */
211     if (strlen(argv[argc - 1]) > sizeof(path) - 1)
212         ERROR("%s: destination pathname too long", *argv);
213
214     (void)strcpy(path, argv[argc - 1]);
215     baselen = strlen(path);
216     endp = &path[baselen];
217     if (!baselen || *(endp - 1) != '/') {
218         *endp++ = '/';
219         ++baselen;
220     }
221
222     for (rval = 0; --argc; ++argv) {
223         /*
224          * Find the last component of the source pathname.  It
225          * may have trailing slashes.
226          */
227         p = *argv + strlen(*argv);
228         while (p != *argv && p[-1] == '/')
229             --p;
230         while (p != *argv && p[-1] != '/')
231             --p;
232
233         if ((baselen + (len = strlen(p))) >= PATH_MAX) {
234             SLOG("%s: destination pathname too long", *argv);
235             rval = 1;
236         } else {
237             memmove(endp, p, (size_t)len + 1);
238             if (openvol(*argv, &svolume) != 0) {
239                 SLOG("Error opening CNID database for %s: ", argv[0]);
240                 rval = 1;
241                 goto exit;
242             }
243             if (do_move(*argv, path))
244                 rval = 1;
245             closevol(&svolume);
246         }
247     }
248
249 exit:
250     closevol(&dvolume);
251     return rval;
252 }
253
254 static int do_move(const char *from, const char *to)
255 {
256     struct stat sb;
257     int ask, ch, first;
258
259     /*
260      * Check access.  If interactive and file exists, ask user if it
261      * should be replaced.  Otherwise if file exists but isn't writable
262      * make sure the user wants to clobber it.
263      */
264     if (!fflg && !access(to, F_OK)) {
265
266         /* prompt only if source exist */
267         if (lstat(from, &sb) == -1) {
268             SLOG("%s: %s", from, strerror(errno));
269             return (1);
270         }
271
272         ask = 0;
273         if (nflg) {
274             if (vflg)
275                 printf("%s not overwritten\n", to);
276             return (0);
277         } else if (iflg) {
278             (void)fprintf(stderr, "overwrite %s? (y/n [n]) ", to);
279             ask = 1;
280         } else if (access(to, W_OK) && !stat(to, &sb)) {
281             (void)fprintf(stderr, "override for %s? (y/n [n]) ", to);
282             ask = 1;
283         }
284         if (ask) {
285             first = ch = getchar();
286             while (ch != '\n' && ch != EOF)
287                 ch = getchar();
288             if (first != 'y' && first != 'Y') {
289                 (void)fprintf(stderr, "not overwritten\n");
290                 return (0);
291             }
292         }
293     }
294
295     int mustcopy = 0;
296     /* 
297      * Besides the usual EXDEV we copy instead of moving if
298      * 1) source AFP volume != dest AFP volume
299      * 2) either source or dest isn't even an AFP volume
300      */
301     if (!svolume.volinfo.v_path
302         || !dvolume.volinfo.v_path
303         || strcmp(svolume.volinfo.v_path, dvolume.volinfo.v_path) != 0)
304         mustcopy = 1;
305     
306     cnid_t cnid = 0;
307     if (!mustcopy) {
308         if ((cnid = cnid_for_path(&svolume, from, &did)) == CNID_INVALID) {
309             SLOG("Couldn't resolve CNID for %s", from);
310             return -1;
311         }
312
313         if (stat(from, &sb) != 0) {
314             SLOG("Cant stat %s: %s", to, strerror(errno));
315             return -1;
316         }
317
318         if (rename(from, to) != 0) {
319             if (errno == EXDEV) {
320                 mustcopy = 1;
321                 char path[MAXPATHLEN];
322
323                 /*
324                  * If the source is a symbolic link and is on another
325                  * filesystem, it can be recreated at the destination.
326                  */
327                 if (lstat(from, &sb) == -1) {
328                     SLOG("%s: %s", from, strerror(errno));
329                     return (-1);
330                 }
331                 if (!S_ISLNK(sb.st_mode)) {
332                     /* Can't mv(1) a mount point. */
333                     if (realpath(from, path) == NULL) {
334                         SLOG("cannot resolve %s: %s: %s", from, path, strerror(errno));
335                         return (1);
336                     }
337                 }
338             } else { /* != EXDEV */
339                 SLOG("rename %s to %s: %s", from, to, strerror(errno));
340                 return (1);
341             }
342         } /* rename != 0*/
343         
344         switch (sb.st_mode & S_IFMT) {
345         case S_IFREG:
346             if (dvolume.volume.vfs->vfs_renamefile(&dvolume.volume, -1, from, to) != 0) {
347                 SLOG("Error moving adouble file for %s", from);
348                 return -1;
349             }
350             break;
351         case S_IFDIR:
352             break;
353         default:
354             SLOG("Not a file or dir: %s", from);
355             return -1;
356         }
357     
358         /* get CNID of new parent dir */
359         cnid_t newpdid, newdid;
360         if ((newdid = cnid_for_paths_parent(&dvolume, to, &newpdid)) == CNID_INVALID) {
361             SLOG("Couldn't resolve CNID for parent of %s", to);
362             return -1;
363         }
364
365         if (stat(to, &sb) != 0) {
366             SLOG("Cant stat %s: %s", to, strerror(errno));
367             return 1;
368         }
369
370         char *p = strdup(to);
371         char *name = basename(p);
372         if (cnid_update(dvolume.volume.v_cdb, cnid, &sb, newdid, name, strlen(name)) != 0) {
373             SLOG("Cant update CNID for: %s", to);
374             return 1;
375         }
376         free(p);
377
378         struct adouble ad;
379         ad_init(&ad, dvolume.volinfo.v_adouble, dvolume.volinfo.v_ad_options);
380         if (ad_open(&ad, to, S_ISDIR(sb.st_mode) ? (ADFLAGS_DIR | ADFLAGS_HF) : ADFLAGS_HF, O_RDWR) != 0) {
381             SLOG("Error opening adouble for: %s", to);
382             return 1;
383         }
384         ad_setid(&ad, sb.st_dev, sb.st_ino, cnid, newdid, dvolume.db_stamp);
385         ad_flush(&ad);
386         ad_close_metadata(&ad);
387
388         if (vflg)
389             printf("%s -> %s\n", from, to);
390         return (0);
391     }
392     
393     if (mustcopy)
394         return copy(from, to);
395
396     /* If we get here it's an error */
397     return -1;
398 }
399
400 static int copy(const char *from, const char *to)
401 {
402     struct stat sb;
403     int pid, status;
404
405     if (lstat(to, &sb) == 0) {
406         /* Destination path exists. */
407         if (S_ISDIR(sb.st_mode)) {
408             if (rmdir(to) != 0) {
409                 SLOG("rmdir %s: %s", to, strerror(errno));
410                 return (1);
411             }
412         } else {
413             if (unlink(to) != 0) {
414                 SLOG("unlink %s: %s", to, strerror(errno));
415                 return (1);
416             }
417         }
418     } else if (errno != ENOENT) {
419         SLOG("%s: %s", to, strerror(errno));
420         return (1);
421     }
422
423     /* Copy source to destination. */
424     if (!(pid = fork())) {
425         execl(_PATH_AD, "ad", "cp", vflg ? "-Rpv" : "-Rp", from, to, (char *)NULL);
426         _exit(1);
427     }
428     while ((waitpid(pid, &status, 0)) == -1) {
429         if (errno == EINTR)
430             continue;
431         SLOG("%s cp -R %s %s: waitpid: %s", _PATH_AD, from, to, strerror(errno));
432         return (1);
433     }
434     if (!WIFEXITED(status)) {
435         SLOG("%s cp -R %s %s: did not terminate normally", _PATH_AD, from, to);
436         return (1);
437     }
438     switch (WEXITSTATUS(status)) {
439     case 0:
440         break;
441     default:
442         SLOG("%s cp -R %s %s: terminated with %d (non-zero) status",
443              _PATH_AD, from, to, WEXITSTATUS(status));
444         return (1);
445     }
446
447     /* Delete the source. */
448     if (!(pid = fork())) {
449         execl(_PATH_AD, "ad", "rm", "-R", from, (char *)NULL);
450         _exit(1);
451     }
452     while ((waitpid(pid, &status, 0)) == -1) {
453         if (errno == EINTR)
454             continue;
455         SLOG("%s rm -R %s: waitpid: %s", _PATH_AD, from, strerror(errno));
456         return (1);
457     }
458     if (!WIFEXITED(status)) {
459         SLOG("%s rm -R %s: did not terminate normally", _PATH_AD, from);
460         return (1);
461     }
462     switch (WEXITSTATUS(status)) {
463     case 0:
464         break;
465     default:
466         SLOG("%s rm -R %s: terminated with %d (non-zero) status",
467               _PATH_AD, from, WEXITSTATUS(status));
468         return (1);
469     }
470     return 0;
471 }
472
473 static void
474 preserve_fd_acls(int source_fd,
475                  int dest_fd,
476                  const char *source_path,
477                  const char *dest_path)
478 {
479     ;
480 }