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