]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd.c
Fix dbd vs cnid_dbd locking
[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;  /* flags for signals */
85 int db_locked;                  /* have we got the fcntl lock on lockfile ? */
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     64 * 1024,                  /* bdb cachesize (64 MB) */
94     0,                          /* flush_interval */
95     0,                          /* flush_frequency */
96     0,                          /* usock_file */
97     -1,                         /* fd_table_size */
98     -1,                         /* idle_timeout */
99     -1                          /* max_vols */
100 };
101 static char dbpath[PATH_MAX];   /* Path to the dbd database */
102
103 /* 
104    Provide some logging
105  */
106 void dbd_log(enum logtype lt, char *fmt, ...)
107 {
108     int len;
109     static char logbuffer[1024];
110     va_list args;
111
112     if ( (lt == LOGSTD) || (verbose == 1)) {
113         va_start(args, fmt);
114         len = vsnprintf(logbuffer, 1023, fmt, args);
115         va_end(args);
116         logbuffer[1023] = 0;
117
118         printf("%s\n", logbuffer);
119     }
120 }
121
122 /* 
123    SIGNAL handling:
124    catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
125  */
126
127 static void sig_handler(int signo)
128 {
129     alarmed = 1;
130     return;
131 }
132
133 static void set_signal(void)
134 {
135     struct sigaction sv;
136
137     sv.sa_handler = sig_handler;
138     sv.sa_flags = SA_RESTART;
139     sigemptyset(&sv.sa_mask);
140     if (sigaction(SIGTERM, &sv, NULL) < 0) {
141         dbd_log( LOGSTD, "error in sigaction(SIGTERM): %s", strerror(errno));
142         exit(EXIT_FAILURE);
143     }        
144     if (sigaction(SIGINT, &sv, NULL) < 0) {
145         dbd_log( LOGSTD, "error in sigaction(SIGINT): %s", strerror(errno));
146         exit(EXIT_FAILURE);
147     }        
148
149     memset(&sv, 0, sizeof(struct sigaction));
150     sv.sa_handler = SIG_IGN;
151     sigemptyset(&sv.sa_mask);
152
153     if (sigaction(SIGABRT, &sv, NULL) < 0) {
154         dbd_log( LOGSTD, "error in sigaction(SIGABRT): %s", strerror(errno));
155         exit(EXIT_FAILURE);
156     }        
157     if (sigaction(SIGHUP, &sv, NULL) < 0) {
158         dbd_log( LOGSTD, "error in sigaction(SIGHUP): %s", strerror(errno));
159         exit(EXIT_FAILURE);
160     }        
161     if (sigaction(SIGQUIT, &sv, NULL) < 0) {
162         dbd_log( LOGSTD, "error in sigaction(SIGQUIT): %s", strerror(errno));
163         exit(EXIT_FAILURE);
164     }        
165 }
166
167
168 /*!
169  * Get lock on db lock file
170  *
171  * @args cmd       (r) !=0: lock, 0: unlock
172  * @args dbpath    (r) path to lockfile, only used on first call,
173  *                     later the stored fd is used
174  * @returns            1 if lock was acquired, 0 if file is already locked, -1 on error
175  */
176 int get_lock(int cmd, const char *dbpath)
177 {
178     static int lockfd = -1;
179     char lockpath[PATH_MAX];
180     struct flock lock;
181     struct stat st;
182
183     if (cmd == 0) {
184         if (lockfd == -1)
185             return -1;
186
187         lock.l_start  = 0;
188         lock.l_whence = SEEK_SET;
189         lock.l_len    = 0;
190         lock.l_type = F_UNLCK;
191         fcntl(lockfd, F_SETLK, &lock);
192         close(lockfd);
193         lockfd = -1;
194         return 0;
195     }
196
197     if (lockfd == -1) {
198         if ( (strlen(dbpath) + strlen(LOCKFILENAME+1)) > (PATH_MAX - 1) ) {
199             dbd_log( LOGSTD, ".AppleDB pathname too long");
200             return -1;
201         }
202         strncpy(lockpath, dbpath, PATH_MAX - 1);
203         strcat(lockpath, "/");
204         strcat(lockpath, LOCKFILENAME);
205
206         if ((lockfd = open(lockpath, O_RDWR | O_CREAT, 0644)) < 0) {
207             dbd_log( LOGSTD, "Error opening lockfile: %s", strerror(errno));
208             return -1;
209         }
210
211         if ((stat(dbpath, &st)) != 0) {
212             dbd_log( LOGSTD, "Error statting lockfile: %s", strerror(errno));
213             return -1;
214         }
215
216         if ((chown(lockpath, st.st_uid, st.st_gid)) != 0) {
217             dbd_log( LOGSTD, "Error inheriting lockfile permissions: %s", strerror(errno));
218             return -1;
219         }
220     }
221     
222     lock.l_start  = 0;
223     lock.l_whence = SEEK_SET;
224     lock.l_len    = 0;
225     lock.l_type   = F_WRLCK;
226
227     if (fcntl(lockfd, F_SETLK, &lock) < 0) {
228         if (errno == EACCES || errno == EAGAIN) {
229             if (exclusive) {
230                 dbd_log(LOGSTD, "Database is in use and exlusive was requested");
231                 return -1;
232             };
233             dbd_log(LOGDEBUG, "get_lock: couldn't lock");
234             return 0;
235         } else {
236             dbd_log( LOGSTD, "Error getting fcntl F_WRLCK on lockfile: %s", strerror(errno));
237             return -1;
238        }
239     }
240
241     dbd_log(LOGDEBUG, "get_lock: got lock");    
242     return 1;
243 }
244
245 static void usage (void)
246 {
247     printf("Usage: dbd [-e|-t|-v|-x] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
248            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
249            "dbd must be run with appropiate permissions i.e. as root.\n\n"
250            "Main commands are:\n"
251            "   -d Dump CNID database\n"
252            "      Option: -i dump indexes too\n\n"
253            "   -s Scan volume:\n"
254            "      1. Compare CNIDs in database with volume\n"
255            "      2. Check if .AppleDouble dirs exist\n"
256            "      3. Check if  AppleDouble file exist\n"
257            "      4. Report orphaned AppleDouble files\n"
258            "      5. Check for directories inside AppleDouble directories\n"
259            "      6. Check name encoding by roundtripping, log on error\n"
260            "      7. Check for orphaned CNIDs in database (requires -e)\n"
261            "      8. Open and close adouble files\n"
262            "      Options: -c Don't check .AppleDouble stuff, only ckeck orphaned.\n"
263            "               -n Don't open CNID database, skip CNID checks\n\n"
264            "   -r Rebuild volume:\n"
265            "      1. Sync CNIDSs in database with volume\n"
266            "      2. Make sure .AppleDouble dir exist, create if missing\n"
267            "      3. Make sure AppleDouble file exists, create if missing\n"
268            "      4. Delete orphaned AppleDouble files\n"
269            "      5. Check for directories inside AppleDouble directories\n"
270            "      6. Check name encoding by roundtripping, log on error\n"
271            "      7. Check for orphaned CNIDs in database (requires -e)\n"
272            "      8. Open and close adouble files\n"
273            "      Options: -c Don't create .AppleDouble stuff, only cleanup orphaned.\n"
274            "               -f wipe database and rebuild from IDs stored in AppleDouble files,\n"
275            "                  only available for volumes without 'nocnidcache' option. Implies -e.\n\n"
276            "   -u Prepare upgrade:\n"
277            "      Before installing an upgraded version of Netatalk that is linked against\n"
278            "      a newer BerkeleyDB lib, run `dbd -u ...` from the OLD Netatalk pior to\n"
279            "      upgrading on all volumes. This removes the BerkleyDB environment.\n"
280            "      On exit cnid_dbd does this automatically, so normally calling dbd -u should not be necessary.\n\n"
281            "General options:\n"
282            "   -e only work on inactive volumes and lock them (exclusive)\n"
283            "   -x rebuild indexes (just for completeness, mostly useless!)\n"
284            "   -t show statistics while running\n"
285            "   -v verbose\n\n"
286            "WARNING:\n"
287            "For -r -f restore of the CNID database from the adouble files, the CNID must of course\n"
288            "be synched to them files first with a plain -r rebuild !\n"
289         );
290 }
291
292 int main(int argc, char **argv)
293 {
294     int c, lockfd, ret = -1;
295     int dump=0, scan=0, rebuild=0, prep_upgrade=0, rebuildindexes=0, dumpindexes=0, force=0;
296     dbd_flags_t flags = 0;
297     char *volpath;
298     struct volinfo volinfo;
299     int cdir;
300
301     if (geteuid() != 0) {
302         usage();
303         exit(EXIT_FAILURE);
304     }
305     /* Inhereting perms in ad_mkdir etc requires this */
306     ad_setfuid(0);
307
308     while ((c = getopt(argc, argv, ":cdefinrstuvx")) != -1) {
309         switch(c) {
310         case 'c':
311             flags |= DBD_FLAGS_CLEANUP;
312             break;
313         case 'd':
314             dump = 1;
315             break;
316         case 'i':
317             dumpindexes = 1;
318             break;
319         case 's':
320             scan = 1;
321             flags |= DBD_FLAGS_SCAN;
322             break;
323         case 'n':
324             nocniddb = 1; /* FIXME: this could/should be a flag too for consistency */
325             break;
326         case 'r':
327             rebuild = 1;
328             break;
329         case 't':
330             flags |= DBD_FLAGS_STATS;
331             break;
332         case 'u':
333             prep_upgrade = 1;
334             break;
335         case 'v':
336             verbose = 1;
337             break;
338         case 'e':
339             exclusive = 1;
340             flags |= DBD_FLAGS_EXCL;
341             break;
342         case 'x':
343             rebuildindexes = 1;
344             break;
345         case 'f':
346             force = 1;
347             exclusive = 1;
348             flags |= DBD_FLAGS_FORCE | DBD_FLAGS_EXCL;
349             break;
350         case ':':
351         case '?':
352             usage();
353             exit(EXIT_FAILURE);
354             break;
355         }
356     }
357
358     if ((dump + scan + rebuild + prep_upgrade) != 1) {
359         usage();
360         exit(EXIT_FAILURE);
361     }
362
363     if ( (optind + 1) != argc ) {
364         usage();
365         exit(EXIT_FAILURE);
366     }
367     volpath = argv[optind];
368
369     setvbuf(stdout, (char *) NULL, _IONBF, 0);
370
371     /* Remember cwd */
372     if ((cdir = open(".", O_RDONLY)) < 0) {
373         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
374         exit(EXIT_FAILURE);
375     }
376         
377     /* Setup signal handling */
378     set_signal();
379
380     /* Setup logging. Should be portable among *NIXes */
381     if (!verbose)
382         setuplog("default log_info /dev/tty");
383     else
384         setuplog("default log_debug /dev/tty");
385
386     /* Load .volinfo file */
387     if (loadvolinfo(volpath, &volinfo) == -1) {
388         dbd_log( LOGSTD, "Not a Netatalk volume at '%s', no .volinfo file at '%s/.AppleDesktop/.volinfo' or unknown volume options", volpath, volpath);
389         exit(EXIT_FAILURE);
390     }
391     if (vol_load_charsets(&volinfo) == -1) {
392         dbd_log( LOGSTD, "Error loading charsets!");
393         exit(EXIT_FAILURE);
394     }
395
396     /* Sanity checks to ensure we can touch this volume */
397     if (volinfo.v_vfs_ea != AFPVOL_EA_AD && volinfo.v_vfs_ea != AFPVOL_EA_SYS) {
398         dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", volinfo.v_vfs_ea);
399         exit(EXIT_FAILURE);        
400     }
401
402     /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
403     if ( (strlen(volinfo.v_dbpath) + strlen("/.AppleDB")) > (PATH_MAX - 1) ) {
404         dbd_log( LOGSTD, "Volume pathname too long");
405         exit(EXIT_FAILURE);        
406     }
407     strncpy(dbpath, volinfo.v_dbpath, PATH_MAX - 9 - 1);
408     strcat(dbpath, "/.AppleDB");
409
410     /* Check or create dbpath */
411     int dbdirfd = open(dbpath, O_RDONLY);
412     if (dbdirfd == -1 && errno == ENOENT) {
413         if (errno == ENOENT) {
414             if ((mkdir(dbpath, 0755)) != 0) {
415                 dbd_log( LOGSTD, "Can't create .AppleDB for \"%s\": %s", dbpath, strerror(errno));
416                 exit(EXIT_FAILURE);
417             }
418         } else {
419             dbd_log( LOGSTD, "Somethings wrong with .AppleDB for \"%s\", giving up: %s", dbpath, strerror(errno));
420             exit(EXIT_FAILURE);
421         }
422     } else {
423         close(dbdirfd);
424     }
425
426     /* Get db lock, which exits if exclusive was requested and it already is locked */
427     if ((db_locked = get_lock(1, dbpath)) == -1)
428         goto exit_failure;
429
430     /* Prepare upgrade ? */
431     if (prep_upgrade) {
432         if (dbif_prep_upgrade(dbpath))
433             goto exit_failure;
434         goto exit_success;
435     }        
436
437     /* Check if -f is requested and wipe db if yes */
438     if ((flags & DBD_FLAGS_FORCE) && rebuild && (volinfo.v_flags & AFPVOL_CACHE)) {
439         char cmd[8 + MAXPATHLEN];
440         if ((db_locked = get_lock(0, NULL)) != 0)
441             goto exit_failure;
442         snprintf(cmd, 8 + MAXPATHLEN, "rm -f %s/*", dbpath);
443         dbd_log( LOGDEBUG, "Removing old database of volume: '%s'", volpath);
444         system(cmd);
445         dbd_log( LOGDEBUG, "Removed old database.");
446         if ((db_locked = get_lock(1, dbpath)) == -1)
447             goto exit_failure;
448     }
449
450     /* 
451        Lets start with the BerkeleyDB stuff
452     */
453     if ( ! nocniddb) {
454         if ((dbd = dbif_init(dbpath, "cnid2.db")) == NULL)
455             goto exit_failure;
456         
457         if (dbif_env_open(dbd,
458                           &db_param,
459                           exclusive ? (DBOPTIONS | DB_RECOVER) : DBOPTIONS) < 0) {
460             dbd_log( LOGSTD, "error opening database!");
461             goto exit_failure;
462         }
463
464         if (exclusive)
465             dbd_log( LOGDEBUG, "Finished recovery.");
466
467         if (dbif_open(dbd, NULL, rebuildindexes) < 0) {
468             dbif_close(dbd);
469             goto exit_failure;
470         }
471
472         if (dbd_stamp(dbd) < 0) {
473             dbif_close(dbd);
474             goto exit_failure;
475         }
476     }
477
478     /* Now execute given command scan|rebuild|dump */
479     if (dump && ! nocniddb) {
480         if (dbif_dump(dbd, dumpindexes) < 0) {
481             dbd_log( LOGSTD, "Error dumping database");
482         }
483     } else if ((rebuild && ! nocniddb) || scan) {
484         if (cmd_dbd_scanvol(dbd, &volinfo, flags) < 0) {
485             dbd_log( LOGSTD, "Error repairing database.");
486         }
487     }
488
489     /* Cleanup */
490     dbd_log(LOGDEBUG, "Closing db");
491     if (! nocniddb) {
492         if (dbif_close(dbd) < 0) {
493             dbd_log( LOGSTD, "Error closing database");
494             goto exit_failure;
495         }
496     }
497
498 exit_success:
499     ret = 0;
500
501 exit_failure:
502     get_lock(0, NULL);
503     
504     if ((fchdir(cdir)) < 0)
505         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));
506
507     if (ret == 0)
508         exit(EXIT_SUCCESS);
509     else
510         exit(EXIT_FAILURE);
511 }