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