]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd.c
Merge remote branch 'sf/branch-allea' into branch-allea
[netatalk.git] / etc / cnid_dbd / cmd_dbd.c
1 /* 
2    Copyright (c) 2009 Frank Lahm <franklahm@gmail.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 <unistd.h>
20 #include <sys/types.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <stdarg.h>
24 #include <limits.h>
25 #include <signal.h>
26 #include <string.h>
27 #include <errno.h>
28
29 #include <atalk/logger.h>
30 #include <atalk/cnid_dbd_private.h>
31 #include <atalk/globals.h>
32 #include <atalk/netatalk_conf.h>
33 #include <atalk/util.h>
34
35 #include "cmd_dbd.h"
36 #include "dbd.h"
37 #include "dbif.h"
38 #include "db_param.h"
39 #include "pack.h"
40
41 #define DBOPTIONS (DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN)
42
43 int nocniddb = 0;               /* Dont open CNID database, only scan filesystem */
44 volatile sig_atomic_t alarmed;  /* flags for signals */
45 int db_locked;                  /* have we got the fcntl lock on lockfile ? */
46
47 static DBD *dbd;
48 static int verbose;             /* Logging flag */
49 static int exclusive;           /* Exclusive volume access */
50 static struct db_param db_param = {
51     NULL,                       /* Volume dirpath */
52     1,                          /* bdb logfile autoremove */
53     64 * 1024,                  /* bdb cachesize (64 MB) */
54     DEFAULT_MAXLOCKS,           /* maxlocks */
55     DEFAULT_MAXLOCKOBJS,        /* maxlockobjs */
56     0,                          /* flush_interval */
57     0,                          /* flush_frequency */
58     0,                          /* usock_file */
59     -1,                         /* fd_table_size */
60     -1,                         /* idle_timeout */
61     -1                          /* max_vols */
62 };
63 static char dbpath[MAXPATHLEN+1];   /* Path to the dbd database */
64
65 /* 
66    Provide some logging
67  */
68 void dbd_log(enum logtype lt, char *fmt, ...)
69 {
70     int len;
71     static char logbuffer[1024];
72     va_list args;
73
74     if ( (lt == LOGSTD) || (verbose == 1)) {
75         va_start(args, fmt);
76         len = vsnprintf(logbuffer, 1023, fmt, args);
77         va_end(args);
78         logbuffer[1023] = 0;
79
80         printf("%s\n", logbuffer);
81     }
82 }
83
84 /* 
85    SIGNAL handling:
86    catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
87  */
88
89 static void sig_handler(int signo)
90 {
91     alarmed = 1;
92     return;
93 }
94
95 static void set_signal(void)
96 {
97     struct sigaction sv;
98
99     sv.sa_handler = sig_handler;
100     sv.sa_flags = SA_RESTART;
101     sigemptyset(&sv.sa_mask);
102     if (sigaction(SIGTERM, &sv, NULL) < 0) {
103         dbd_log( LOGSTD, "error in sigaction(SIGTERM): %s", strerror(errno));
104         exit(EXIT_FAILURE);
105     }        
106     if (sigaction(SIGINT, &sv, NULL) < 0) {
107         dbd_log( LOGSTD, "error in sigaction(SIGINT): %s", strerror(errno));
108         exit(EXIT_FAILURE);
109     }        
110
111     memset(&sv, 0, sizeof(struct sigaction));
112     sv.sa_handler = SIG_IGN;
113     sigemptyset(&sv.sa_mask);
114
115     if (sigaction(SIGABRT, &sv, NULL) < 0) {
116         dbd_log( LOGSTD, "error in sigaction(SIGABRT): %s", strerror(errno));
117         exit(EXIT_FAILURE);
118     }        
119     if (sigaction(SIGHUP, &sv, NULL) < 0) {
120         dbd_log( LOGSTD, "error in sigaction(SIGHUP): %s", strerror(errno));
121         exit(EXIT_FAILURE);
122     }        
123     if (sigaction(SIGQUIT, &sv, NULL) < 0) {
124         dbd_log( LOGSTD, "error in sigaction(SIGQUIT): %s", strerror(errno));
125         exit(EXIT_FAILURE);
126     }        
127 }
128
129 static void usage (void)
130 {
131     printf("dbd (Netatalk %s)\n"
132            "Usage: dbd [-etvxF] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
133            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
134            "dbd must be run with appropiate permissions i.e. as root.\n\n"
135            "Main commands are:\n"
136            "   -d Dump CNID database\n"
137            "      Option: -i dump indexes too\n\n"
138            "   -s Scan volume:\n"
139            "      1. Compare CNIDs in database with volume\n"
140            "      2. Check if .AppleDouble dirs exist\n"
141            "      3. Check if  AppleDouble file exist\n"
142            "      4. Report orphaned AppleDouble files\n"
143            "      5. Check for directories inside AppleDouble directories\n"
144            "      6. Check name encoding by roundtripping, log on error\n"
145            "      7. Check for orphaned CNIDs in database (requires -e)\n"
146            "      8. Open and close adouble files\n"
147            "      Options: -c Don't check .AppleDouble stuff, only ckeck orphaned.\n"
148            "               -n Don't open CNID database, skip CNID checks.\n\n"
149            "   -r Rebuild volume:\n"
150            "      1. Sync CNIDSs in database with volume\n"
151            "      2. Make sure .AppleDouble dir exist, create if missing\n"
152            "      3. Make sure AppleDouble file exists, create if missing\n"
153            "      4. Delete orphaned AppleDouble files\n"
154            "      5. Check for directories inside AppleDouble directories\n"
155            "      6. Check name encoding by roundtripping, log on error\n"
156            "      7. Check for orphaned CNIDs in database (requires -e)\n"
157            "      8. Open and close adouble files\n"
158            "      Options: -c Don't create .AppleDouble stuff, only cleanup orphaned.\n"
159            "               -f wipe database and rebuild from IDs stored in AppleDouble\n"
160            "                  files, only available for volumes without 'nocnidcache'\n"
161            "                  option. Implies -e.\n\n"
162            "   -u Upgrade:\n"
163            "      Opens the database which triggers any necessary upgrades,\n"
164            "      then closes and exits.\n\n"
165            "General options:\n"
166            "   -F location of the afp.conf config file\n"
167            "   -e only work on inactive volumes and lock them (exclusive)\n"
168            "   -x rebuild indexes (just for completeness, mostly useless!)\n"
169            "   -t show statistics while running\n"
170            "   -v verbose\n\n"
171            "WARNING:\n"
172            "For -r -f restore of the CNID database from the adouble files,\n"
173            "the CNID must of course be synched to them files first with a plain -r rebuild!\n"
174            , VERSION
175         );
176 }
177
178 int main(int argc, char **argv)
179 {
180     int c, lockfd, ret = -1;
181     int dump=0, scan=0, rebuild=0, prep_upgrade=0, rebuildindexes=0, dumpindexes=0, force=0;
182     dbd_flags_t flags = 0;
183     char *volpath;
184     int cdir;
185     AFPObj obj = { 0 };
186     struct vol *vol;
187
188     if (geteuid() != 0) {
189         usage();
190         exit(EXIT_FAILURE);
191     }
192     /* Inhereting perms in ad_mkdir etc requires this */
193     ad_setfuid(0);
194
195     while ((c = getopt(argc, argv, ":cdefFinrstuvx")) != -1) {
196         switch(c) {
197         case 'c':
198             flags |= DBD_FLAGS_CLEANUP;
199             break;
200         case 'd':
201             dump = 1;
202             break;
203         case 'i':
204             dumpindexes = 1;
205             break;
206         case 's':
207             scan = 1;
208             flags |= DBD_FLAGS_SCAN;
209             break;
210         case 'n':
211             nocniddb = 1; /* FIXME: this could/should be a flag too for consistency */
212             break;
213         case 'r':
214             rebuild = 1;
215             break;
216         case 't':
217             flags |= DBD_FLAGS_STATS;
218             break;
219         case 'u':
220             prep_upgrade = 1;
221             break;
222         case 'v':
223             verbose = 1;
224             break;
225         case 'e':
226             exclusive = 1;
227             flags |= DBD_FLAGS_EXCL;
228             break;
229         case 'x':
230             rebuildindexes = 1;
231             break;
232         case 'f':
233             force = 1;
234             exclusive = 1;
235             flags |= DBD_FLAGS_FORCE | DBD_FLAGS_EXCL;
236             break;
237         case 'F':
238             obj.cmdlineconfigfile = strdup(optarg);
239             break;
240         case ':':
241         case '?':
242             usage();
243             exit(EXIT_FAILURE);
244             break;
245         }
246     }
247
248     if ((dump + scan + rebuild + prep_upgrade) != 1) {
249         usage();
250         exit(EXIT_FAILURE);
251     }
252
253     if ( (optind + 1) != argc ) {
254         usage();
255         exit(EXIT_FAILURE);
256     }
257     volpath = argv[optind];
258
259     setvbuf(stdout, (char *) NULL, _IONBF, 0);
260
261     /* Remember cwd */
262     if ((cdir = open(".", O_RDONLY)) < 0) {
263         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
264         exit(EXIT_FAILURE);
265     }
266         
267     /* Setup signal handling */
268     set_signal();
269
270     /* Setup logging. Should be portable among *NIXes */
271     if (!verbose)
272         setuplog("default:info", "/dev/tty");
273     else
274         setuplog("default:debug", "/dev/tty");
275
276     /* Load config */
277     if (afp_config_parse(&obj) != 0) {
278         dbd_log( LOGSTD, "Couldn't load afp.conf");
279         exit(EXIT_FAILURE);
280     }
281
282     if (load_volumes(&obj, NULL) != 0) {
283         dbd_log( LOGSTD, "Couldn't load volumes");
284         exit(EXIT_FAILURE);
285     }
286
287     if ((vol = getvolbypath(volpath)) == NULL) {
288         dbd_log( LOGSTD, "Couldn't find volume for '%s'", volpath);
289         exit(EXIT_FAILURE);
290     }
291     pack_setvol(vol);
292
293     if (vol->v_adouble == AD_VERSION_EA)
294         dbd_log( LOGDEBUG, "adouble:ea volume");
295     else if (vol->v_adouble == AD_VERSION2)
296         dbd_log( LOGDEBUG, "adouble:v2 volume");
297     else {
298         dbd_log( LOGSTD, "unknown adouble volume");
299         exit(EXIT_FAILURE);
300     }
301
302     /* Sanity checks to ensure we can touch this volume */
303     if (vol->v_vfs_ea != AFPVOL_EA_AD && vol->v_vfs_ea != AFPVOL_EA_SYS) {
304         dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", vol->v_vfs_ea);
305         exit(EXIT_FAILURE);        
306     }
307
308     /* Enuser dbpath is there, create if necessary */
309     struct stat st;
310     if (stat(vol->v_dbpath, &st) != 0) {
311         if (errno != ENOENT) {
312             dbd_log( LOGSTD, "Can't stat dbpath \"%s\": %s", vol->v_dbpath, strerror(errno));
313             exit(EXIT_FAILURE);        
314         }
315         if ((mkdir(vol->v_dbpath, 0755)) != 0) {
316             dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", vol->v_dbpath, strerror(errno));
317             exit(EXIT_FAILURE);
318         }        
319     }
320
321     /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
322     if ( (strlen(vol->v_dbpath) + strlen("/.AppleDB")) > MAXPATHLEN ) {
323         dbd_log( LOGSTD, "Volume pathname too long");
324         exit(EXIT_FAILURE);        
325     }
326     strncpy(dbpath, vol->v_dbpath, MAXPATHLEN - strlen("/.AppleDB"));
327     strcat(dbpath, "/.AppleDB");
328
329     /* Check or create dbpath */
330     int dbdirfd = open(dbpath, O_RDONLY);
331     if (dbdirfd == -1 && errno == ENOENT) {
332         if (errno == ENOENT) {
333             if ((mkdir(dbpath, 0755)) != 0) {
334                 dbd_log( LOGSTD, "Can't create .AppleDB for \"%s\": %s", dbpath, strerror(errno));
335                 exit(EXIT_FAILURE);
336             }
337         } else {
338             dbd_log( LOGSTD, "Somethings wrong with .AppleDB for \"%s\", giving up: %s", dbpath, strerror(errno));
339             exit(EXIT_FAILURE);
340         }
341     } else {
342         close(dbdirfd);
343     }
344
345     /* Get db lock */
346     if ((db_locked = get_lock(LOCK_EXCL, dbpath)) == -1)
347         goto exit_noenv;
348     if (db_locked != LOCK_EXCL) {
349         /* Couldn't get exclusive lock, try shared lock if -e wasn't requested */
350         if (exclusive) {
351             dbd_log(LOGSTD, "Database is in use and exlusive was requested");
352             goto exit_noenv;
353         }
354         if ((db_locked = get_lock(LOCK_SHRD, NULL)) != LOCK_SHRD)
355             goto exit_noenv;
356     }
357
358     /* Check if -f is requested and wipe db if yes */
359     if ((flags & DBD_FLAGS_FORCE) && rebuild) {
360         char cmd[8 + MAXPATHLEN];
361         if ((db_locked = get_lock(LOCK_FREE, NULL)) != 0)
362             goto exit_noenv;
363
364         snprintf(cmd, 8 + MAXPATHLEN, "rm -rf \"%s\"", dbpath);
365         dbd_log( LOGDEBUG, "Removing old database of volume: '%s'", volpath);
366         system(cmd);
367         if ((mkdir(dbpath, 0755)) != 0) {
368             dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", dbpath, strerror(errno));
369             exit(EXIT_FAILURE);
370         }
371         dbd_log( LOGDEBUG, "Removed old database.");
372         if ((db_locked = get_lock(LOCK_EXCL, dbpath)) == -1)
373             goto exit_noenv;
374     }
375
376     /* 
377        Lets start with the BerkeleyDB stuff
378     */
379     if ( ! nocniddb) {
380         if ((dbd = dbif_init(dbpath, "cnid2.db")) == NULL)
381             goto exit_noenv;
382         
383         if (dbif_env_open(dbd,
384                           &db_param,
385                           (db_locked == LOCK_EXCL) ? (DBOPTIONS | DB_RECOVER) : DBOPTIONS) < 0) {
386             dbd_log( LOGSTD, "error opening database!");
387             goto exit_noenv;
388         }
389
390         if (db_locked == LOCK_EXCL)
391             dbd_log( LOGDEBUG, "Finished recovery.");
392
393         if (dbif_open(dbd, NULL, rebuildindexes) < 0) {
394             dbif_close(dbd);
395             goto exit_failure;
396         }
397
398         /* Prepare upgrade ? We're done */
399         if (prep_upgrade) {
400             (void)dbif_txn_close(dbd, 1);
401             goto cleanup;
402         }
403     }
404
405     /* Downgrade db lock if not running exclusive */
406     if (!exclusive && (db_locked == LOCK_EXCL)) {
407         if (get_lock(LOCK_UNLOCK, NULL) != 0)
408             goto exit_failure;
409         if (get_lock(LOCK_SHRD, NULL) != LOCK_SHRD)
410             goto exit_failure;
411     }
412
413     /* Now execute given command scan|rebuild|dump */
414     if (dump && ! nocniddb) {
415         if (dbif_dump(dbd, dumpindexes) < 0) {
416             dbd_log( LOGSTD, "Error dumping database");
417         }
418     } else if ((rebuild && ! nocniddb) || scan) {
419         if (cmd_dbd_scanvol(dbd, vol, flags) < 0) {
420             dbd_log( LOGSTD, "Error repairing database.");
421         }
422     }
423
424 cleanup:
425     /* Cleanup */
426     dbd_log(LOGDEBUG, "Closing db");
427     if (! nocniddb) {
428         if (dbif_close(dbd) < 0) {
429             dbd_log( LOGSTD, "Error closing database");
430             goto exit_failure;
431         }
432     }
433
434 exit_success:
435     ret = 0;
436
437 exit_failure:
438     if (dbif_env_remove(dbpath) < 0) {
439         dbd_log( LOGSTD, "Error removing BerkeleyDB database environment");
440         ret++;
441     }
442     get_lock(0, NULL);
443
444 exit_noenv:    
445     if ((fchdir(cdir)) < 0)
446         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));
447
448     if (ret == 0)
449         exit(EXIT_SUCCESS);
450     else
451         exit(EXIT_FAILURE);
452 }