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