]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd.c
Merge branch 'master' of ssh://netatalk.git.sourceforge.net/gitroot/netatalk/netatalk
[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 /*
16   dbd specs and implementation progress
17   =====================================
18
19   St := Status
20
21   Force option
22   ------------
23   
24   St Spec
25   -- ----
26   OK If -f is requested, ensure -e is too.
27      Check if volumes is using AFPVOL_CACHE, then wipe db from disk. Rebuild from ad-files.
28
29   1st pass: Scan volume
30   --------------------
31
32   St Type Check
33   -- ---- -----
34   OK F/D  Make sure ad file exists
35   OK D    Make sure .AppleDouble dir exist, create if missing. Error creating
36           it is fatal as that shouldn't happen as root.
37   OK F/D  Delete orphaned ad-files, log dirs in ad-dir
38   OK F/D  Check name encoding by roundtripping, log on error
39   OK F/D  try: read CNID from ad file (if cnid caching is on)
40           try: fetch CNID from database
41           -> on mismatch: use CNID from file, update database (deleting both found CNIDs first)
42           -> if no CNID in ad file: write CNID from database to ad file
43           -> if no CNID in database: add CNID from ad file to database
44           -> on no CNID at all: create one and store in both places
45   OK F/D  Add found CNID, DID, filename, dev/inode, stamp to rebuild database
46   OK F/D  Check/update stamp (implicitly done while checking CNIDs)
47
48
49   2nd pass: Delete unused CNIDs
50   -----------------------------
51
52   St Spec
53   -- ----
54   OK Step through dbd (the one on disk) and rebuild-db from pass 1 and delete any CNID from
55      dbd not in rebuild db. This in only done in exclusive mode.
56 */
57
58 #ifdef HAVE_CONFIG_H
59 #include "config.h"
60 #endif /* HAVE_CONFIG_H */
61
62 #include <unistd.h>
63 #include <sys/types.h>
64 #include <stdlib.h>
65 #include <stdio.h>
66 #include <stdarg.h>
67 #include <limits.h>
68 #include <signal.h>
69 #include <string.h>
70 #include <errno.h>
71
72 #include <atalk/logger.h>
73 #include <atalk/cnid_dbd_private.h>
74 #include <atalk/volinfo.h>
75 #include "cmd_dbd.h"
76 #include "dbd.h"
77 #include "dbif.h"
78 #include "db_param.h"
79
80 #define LOCKFILENAME  "lock"
81 #define DBOPTIONS (DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN)
82
83 int nocniddb = 0;               /* Dont open CNID database, only scan filesystem */
84 volatile sig_atomic_t alarmed;
85 struct volinfo volinfo; /* needed by pack.c:idxname() */
86
87 static DBD *dbd;
88 static int verbose;             /* Logging flag */
89 static int exclusive;           /* Exclusive volume access */
90 static struct db_param db_param = {
91     NULL,                       /* Volume dirpath */
92     1,                          /* bdb logfile autoremove */
93     256 * 1024,                  /* bdb cachesize (256 MB) */
94     5000,                       /* maxlocks */
95     5000,                       /* maxlockobjs */
96     -1,                         /* not used ... */
97     -1,
98     "",
99     -1,
100     -1,
101     -1
102 };
103 static char dbpath[MAXPATHLEN+1];   /* Path to the dbd database */
104
105 /* 
106    Provide some logging
107  */
108 void dbd_log(enum logtype lt, char *fmt, ...)
109 {
110     int len;
111     static char logbuffer[1024];
112     va_list args;
113
114     if ( (lt == LOGSTD) || (verbose == 1)) {
115         va_start(args, fmt);
116         len = vsnprintf(logbuffer, 1023, fmt, args);
117         va_end(args);
118         logbuffer[1023] = 0;
119
120         printf("%s\n", logbuffer);
121     }
122 }
123
124 /* 
125    SIGNAL handling:
126    catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
127  */
128
129 static void sig_handler(int signo)
130 {
131     alarmed = 1;
132     return;
133 }
134
135 static void set_signal(void)
136 {
137     struct sigaction sv;
138
139     sv.sa_handler = sig_handler;
140     sv.sa_flags = SA_RESTART;
141     sigemptyset(&sv.sa_mask);
142     if (sigaction(SIGTERM, &sv, NULL) < 0) {
143         dbd_log( LOGSTD, "error in sigaction(SIGTERM): %s", strerror(errno));
144         exit(EXIT_FAILURE);
145     }        
146     if (sigaction(SIGINT, &sv, NULL) < 0) {
147         dbd_log( LOGSTD, "error in sigaction(SIGINT): %s", strerror(errno));
148         exit(EXIT_FAILURE);
149     }        
150
151     memset(&sv, 0, sizeof(struct sigaction));
152     sv.sa_handler = SIG_IGN;
153     sigemptyset(&sv.sa_mask);
154
155     if (sigaction(SIGABRT, &sv, NULL) < 0) {
156         dbd_log( LOGSTD, "error in sigaction(SIGABRT): %s", strerror(errno));
157         exit(EXIT_FAILURE);
158     }        
159     if (sigaction(SIGHUP, &sv, NULL) < 0) {
160         dbd_log( LOGSTD, "error in sigaction(SIGHUP): %s", strerror(errno));
161         exit(EXIT_FAILURE);
162     }        
163     if (sigaction(SIGQUIT, &sv, NULL) < 0) {
164         dbd_log( LOGSTD, "error in sigaction(SIGQUIT): %s", strerror(errno));
165         exit(EXIT_FAILURE);
166     }        
167 }
168
169 static int get_lock(const char *dbpath)
170 {
171     int lockfd;
172     char lockpath[PATH_MAX];
173     struct flock lock;
174     struct stat st;
175
176     if ( (strlen(dbpath) + strlen(LOCKFILENAME+1)) > (PATH_MAX - 1) ) {
177         dbd_log( LOGSTD, ".AppleDB pathname too long");
178         exit(EXIT_FAILURE);
179     }
180     strncpy(lockpath, dbpath, PATH_MAX - 1);
181     strcat(lockpath, "/");
182     strcat(lockpath, LOCKFILENAME);
183
184     if ((lockfd = open(lockpath, O_RDWR | O_CREAT, 0644)) < 0) {
185         dbd_log( LOGSTD, "Error opening lockfile: %s", strerror(errno));
186         exit(EXIT_FAILURE);
187     }
188
189     if ((stat(dbpath, &st)) != 0) {
190         dbd_log( LOGSTD, "Error statting lockfile: %s", strerror(errno));
191         exit(EXIT_FAILURE);
192     }
193
194     if ((chown(lockpath, st.st_uid, st.st_gid)) != 0) {
195         dbd_log( LOGSTD, "Error inheriting lockfile permissions: %s", strerror(errno));
196         exit(EXIT_FAILURE);
197     }
198     
199     lock.l_start  = 0;
200     lock.l_whence = SEEK_SET;
201     lock.l_len    = 0;
202     lock.l_type   = F_WRLCK;
203
204     if (fcntl(lockfd, F_SETLK, &lock) < 0) {
205         if (errno == EACCES || errno == EAGAIN) {
206             if (exclusive) {
207                 dbd_log( LOGSTD, "Database is in use and exlusive was requested", strerror(errno));        
208                 exit(EXIT_FAILURE);
209             };
210         } else {
211             dbd_log( LOGSTD, "Error getting fcntl F_WRLCK on lockfile: %s", strerror(errno));
212             exit(EXIT_FAILURE);
213        }
214     }
215     
216     return lockfd;
217 }
218
219 static void free_lock(int lockfd)
220 {
221     struct flock lock;
222
223     lock.l_start  = 0;
224     lock.l_whence = SEEK_SET;
225     lock.l_len    = 0;
226     lock.l_type = F_UNLCK;
227     fcntl(lockfd, F_SETLK, &lock);
228     close(lockfd);
229 }
230
231 static void usage (void)
232 {
233     printf("Usage: dbd [-e|-v|-x] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
234            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
235            "dbd must be run with appropiate permissions i.e. as root.\n\n"
236            "Main commands are:\n"
237            "   -d Dump CNID database\n"
238            "      Option: -i dump indexes too\n\n"
239            "   -s Scan volume:\n"
240            "      1. Compare CNIDs in database with volume\n"
241            "      2. Check if .AppleDouble dirs exist\n"
242            "      3. Check if  AppleDouble file exist\n"
243            "      4. Report orphaned AppleDouble files\n"
244            "      5. Check for directories inside AppleDouble directories\n"
245            "      6. Check name encoding by roundtripping, log on error\n"
246            "      7. Check for orphaned CNIDs in database (requires -e)\n"
247            "      8. Open and close adouble files\n"
248            "      Options: -c Don't check .AppleDouble stuff, only ckeck orphaned.\n"
249            "               -n Don't open CNID database, skip CNID checks\n\n"
250            "   -r Rebuild volume:\n"
251            "      1. Sync CNIDSs in database with volume\n"
252            "      2. Make sure .AppleDouble dir exist, create if missing\n"
253            "      3. Make sure AppleDouble file exists, create if missing\n"
254            "      4. Delete orphaned AppleDouble files\n"
255            "      5. Check for directories inside AppleDouble directories\n"
256            "      6. Check name encoding by roundtripping, log on error\n"
257            "      7. Check for orphaned CNIDs in database (requires -e)\n"
258            "      8. Open and close adouble files\n"
259            "      Options: -c Don't create .AppleDouble stuff, only cleanup orphaned.\n"
260            "               -f wipe database and rebuild from IDs stored in AppleDouble files,\n"
261            "                  only available for volumes without 'nocnidcache' option. Implies -e.\n\n"
262            "   -u Prepare upgrade:\n"
263            "      Before installing an upgraded version of Netatalk that is linked against\n"
264            "      a newer BerkeleyDB lib, run `dbd -u ...` from the OLD Netatalk pior to\n"
265            "      upgrading on all volumes. This removes the BerkleyDB environment.\n"
266            "      On exit cnid_dbd does this automatically, so normally calling dbd -u should not be necessary.\n\n"
267            "General options:\n"
268            "   -e only work on inactive volumes and lock them (exclusive)\n"
269            "   -x rebuild indexes (just for completeness, mostly useless!)\n"
270            "   -v verbose\n\n"
271            "WARNING:\n"
272            "For -r -f restore of the CNID database from the adouble files, the CNID must of course\n"
273            "be synched to them files first with a plain -r rebuild !\n"
274         );
275 }
276
277 int main(int argc, char **argv)
278 {
279     int c, lockfd, ret = -1;
280     int dump=0, scan=0, rebuild=0, prep_upgrade=0, rebuildindexes=0, dumpindexes=0, force=0;
281     dbd_flags_t flags = 0;
282     char *volpath;
283     int cdir;
284
285     if (geteuid() != 0) {
286         usage();
287         exit(EXIT_FAILURE);
288     }
289     /* Inhereting perms in ad_mkdir etc requires this */
290     ad_setfuid(0);
291
292     while ((c = getopt(argc, argv, ":cdefinrsuvx")) != -1) {
293         switch(c) {
294         case 'c':
295             flags |= DBD_FLAGS_CLEANUP;
296             break;
297         case 'd':
298             dump = 1;
299             break;
300         case 'i':
301             dumpindexes = 1;
302             break;
303         case 's':
304             scan = 1;
305             flags |= DBD_FLAGS_SCAN;
306             break;
307         case 'n':
308             nocniddb = 1; /* FIXME: this could/should be a flag too for consistency */
309             break;
310         case 'r':
311             rebuild = 1;
312             break;
313         case 'u':
314             prep_upgrade = 1;
315             break;
316         case 'v':
317             verbose = 1;
318             break;
319         case 'e':
320             exclusive = 1;
321             flags |= DBD_FLAGS_EXCL;
322             break;
323         case 'x':
324             rebuildindexes = 1;
325             break;
326         case 'f':
327             force = 1;
328             exclusive = 1;
329             flags |= DBD_FLAGS_FORCE | DBD_FLAGS_EXCL;
330             break;
331         case ':':
332         case '?':
333             usage();
334             exit(EXIT_FAILURE);
335             break;
336         }
337     }
338
339     if ((dump + scan + rebuild + prep_upgrade) != 1) {
340         usage();
341         exit(EXIT_FAILURE);
342     }
343
344     if ( (optind + 1) != argc ) {
345         usage();
346         exit(EXIT_FAILURE);
347     }
348     volpath = argv[optind];
349
350     setvbuf(stdout, (char *) NULL, _IONBF, 0);
351
352     /* Remember cwd */
353     if ((cdir = open(".", O_RDONLY)) < 0) {
354         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
355         exit(EXIT_FAILURE);
356     }
357         
358     /* Setup signal handling */
359     set_signal();
360
361     /* Setup logging. Should be portable among *NIXes */
362     if (!verbose)
363         setuplog("default log_info /dev/tty");
364     else
365         setuplog("default log_debug /dev/tty");
366
367     /* Load .volinfo file */
368     if (loadvolinfo(volpath, &volinfo) == -1) {
369         dbd_log( LOGSTD, "Not a Netatalk volume at '%s', no .volinfo file at '%s/.AppleDesktop/.volinfo' or unknown volume options", volpath, volpath);
370         exit(EXIT_FAILURE);
371     }
372     if (vol_load_charsets(&volinfo) == -1) {
373         dbd_log( LOGSTD, "Error loading charsets!");
374         exit(EXIT_FAILURE);
375     }
376
377     /* Sanity checks to ensure we can touch this volume */
378     if (volinfo.v_vfs_ea != AFPVOL_EA_AD && volinfo.v_vfs_ea != AFPVOL_EA_SYS) {
379         dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", volinfo.v_vfs_ea);
380         exit(EXIT_FAILURE);        
381     }
382
383     /* Enuser dbpath is there, create if necessary */
384     struct stat st;
385     if (stat(volinfo.v_dbpath, &st) != 0) {
386         if (errno != ENOENT) {
387             dbd_log( LOGSTD, "Can't stat dbpath \"%s\": %s", volinfo.v_dbpath, strerror(errno));
388             exit(EXIT_FAILURE);        
389         }
390         if ((mkdir(volinfo.v_dbpath, 0755)) != 0) {
391             dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", dbpath, strerror(errno));
392             exit(EXIT_FAILURE);
393         }        
394     }
395
396     /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
397     if ( (strlen(volinfo.v_dbpath) + strlen("/.AppleDB")) > MAXPATHLEN ) {
398         dbd_log( LOGSTD, "Volume pathname too long");
399         exit(EXIT_FAILURE);        
400     }
401     strncpy(dbpath, volinfo.v_dbpath, MAXPATHLEN - strlen("/.AppleDB"));
402     strcat(dbpath, "/.AppleDB");
403
404     /* Check or create dbpath */
405     int dbdirfd = open(dbpath, O_RDONLY);
406     if (dbdirfd == -1 && errno == ENOENT) {
407         if (errno == ENOENT) {
408             if ((mkdir(dbpath, 0755)) != 0) {
409                 dbd_log( LOGSTD, "Can't create .AppleDB for \"%s\": %s", dbpath, strerror(errno));
410                 exit(EXIT_FAILURE);
411             }
412         } else {
413             dbd_log( LOGSTD, "Somethings wrong with .AppleDB for \"%s\", giving up: %s", dbpath, strerror(errno));
414             exit(EXIT_FAILURE);
415         }
416     } else {
417         close(dbdirfd);
418     }
419
420     /* 
421        Before we do anything else, check if there is an instance of cnid_dbd
422        running already and silently exit if yes.
423     */
424     lockfd = get_lock(dbpath);
425
426     /* Prepare upgrade ? */
427     if (prep_upgrade) {
428         if (dbif_env_remove(dbpath))
429             goto exit_failure;
430         goto exit_success;
431     }        
432
433     /* Check if -f is requested and wipe db if yes */
434     if ((flags & DBD_FLAGS_FORCE) && rebuild && (volinfo.v_flags & AFPVOL_CACHE)) {
435         char cmd[8 + MAXPATHLEN];
436         snprintf(cmd, 8 + MAXPATHLEN, "rm -rf \"%s\"", dbpath);
437         dbd_log( LOGDEBUG, "Removing old database of volume: '%s'", volpath);
438         system(cmd);
439         if ((mkdir(dbpath, 0755)) != 0) {
440             dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", dbpath, strerror(errno));
441             exit(EXIT_FAILURE);
442         }
443         dbd_log( LOGDEBUG, "Removed old database.");
444     }
445
446     /* 
447        Lets start with the BerkeleyDB stuff
448     */
449     if ( ! nocniddb) {
450         if ((dbd = dbif_init(dbpath, "cnid2.db")) == NULL)
451             goto exit_failure;
452         
453         if (dbif_env_open(dbd, &db_param, exclusive ? (DBOPTIONS | DB_RECOVER) : DBOPTIONS) < 0) {
454             dbd_log( LOGSTD, "error opening database!");
455             goto exit_failure;
456         }
457
458         if (exclusive)
459             dbd_log( LOGDEBUG, "Finished recovery.");
460
461         if (dbif_open(dbd, NULL, rebuildindexes) < 0) {
462             dbif_close(dbd);
463             goto exit_failure;
464         }
465     }
466
467     /* Now execute given command scan|rebuild|dump */
468     if (dump && ! nocniddb) {
469         if (dbif_dump(dbd, dumpindexes) < 0) {
470             dbd_log( LOGSTD, "Error dumping database");
471         }
472     } else if ((rebuild && ! nocniddb) || scan) {
473         if (cmd_dbd_scanvol(dbd, &volinfo, flags) < 0) {
474             dbd_log( LOGSTD, "Error repairing database.");
475         }
476     }
477
478     /* Cleanup */
479     if (! nocniddb && dbif_close(dbd) < 0) {
480         dbd_log( LOGSTD, "Error closing database");
481         goto exit_failure;
482     }
483
484 exit_success:
485     ret = 0;
486
487 exit_failure:
488     free_lock(lockfd);
489     
490     if ((fchdir(cdir)) < 0)
491         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));
492
493     if (ret == 0)
494         exit(EXIT_SUCCESS);
495     else
496         exit(EXIT_FAILURE);
497 }