]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd.c
Locking was still not right, oh my
[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
86 static DBD *dbd;
87 static int verbose;             /* Logging flag */
88 static int exclusive;           /* Exclusive volume access */
89 static struct db_param db_param = {
90     NULL,                       /* Volume dirpath */
91     1,                          /* bdb logfile autoremove */
92     64 * 1024,                  /* bdb cachesize (64 MB) */
93     0,                          /* flush_interval */
94     0,                          /* flush_frequency */
95     1000,                       /* txn_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 static int get_lock(const char *dbpath)
168 {
169     int lockfd;
170     char lockpath[PATH_MAX];
171     struct flock lock;
172     struct stat st;
173
174     if ( (strlen(dbpath) + strlen(LOCKFILENAME+1)) > (PATH_MAX - 1) ) {
175         dbd_log( LOGSTD, ".AppleDB pathname too long");
176         exit(EXIT_FAILURE);
177     }
178     strncpy(lockpath, dbpath, PATH_MAX - 1);
179     strcat(lockpath, "/");
180     strcat(lockpath, LOCKFILENAME);
181
182     if ((lockfd = open(lockpath, O_RDWR | O_CREAT, 0644)) < 0) {
183         dbd_log( LOGSTD, "Error opening lockfile: %s", strerror(errno));
184         exit(EXIT_FAILURE);
185     }
186
187     if ((stat(dbpath, &st)) != 0) {
188         dbd_log( LOGSTD, "Error statting lockfile: %s", strerror(errno));
189         exit(EXIT_FAILURE);
190     }
191
192     if ((chown(lockpath, st.st_uid, st.st_gid)) != 0) {
193         dbd_log( LOGSTD, "Error inheriting lockfile permissions: %s", strerror(errno));
194         exit(EXIT_FAILURE);
195     }
196     
197     lock.l_start  = 0;
198     lock.l_whence = SEEK_SET;
199     lock.l_len    = 0;
200     lock.l_type   = F_WRLCK;
201
202     if (fcntl(lockfd, F_SETLK, &lock) < 0) {
203         if (errno == EACCES || errno == EAGAIN) {
204             if (exclusive) {
205                 dbd_log( LOGSTD, "Database is in use and exlusive was requested", strerror(errno));        
206                 exit(EXIT_FAILURE);
207             };
208         } else {
209             dbd_log( LOGSTD, "Error getting fcntl F_WRLCK on lockfile: %s", strerror(errno));
210             exit(EXIT_FAILURE);
211        }
212     }
213     
214     return lockfd;
215 }
216
217 static void free_lock(int lockfd)
218 {
219     struct flock lock;
220
221     lock.l_start  = 0;
222     lock.l_whence = SEEK_SET;
223     lock.l_len    = 0;
224     lock.l_type = F_UNLCK;
225     fcntl(lockfd, F_SETLK, &lock);
226     close(lockfd);
227 }
228
229 static void usage (void)
230 {
231     printf("Usage: dbd [-e|-t|-v|-x] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
232            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
233            "dbd must be run with appropiate permissions i.e. as root.\n\n"
234            "Main commands are:\n"
235            "   -d Dump CNID database\n"
236            "      Option: -i dump indexes too\n\n"
237            "   -s Scan volume:\n"
238            "      1. Compare CNIDs in database with volume\n"
239            "      2. Check if .AppleDouble dirs exist\n"
240            "      3. Check if  AppleDouble file exist\n"
241            "      4. Report orphaned AppleDouble files\n"
242            "      5. Check for directories inside AppleDouble directories\n"
243            "      6. Check name encoding by roundtripping, log on error\n"
244            "      7. Check for orphaned CNIDs in database (requires -e)\n"
245            "      8. Open and close adouble files\n"
246            "      Options: -c Don't check .AppleDouble stuff, only ckeck orphaned.\n"
247            "               -n Don't open CNID database, skip CNID checks\n\n"
248            "   -r Rebuild volume:\n"
249            "      1. Sync CNIDSs in database with volume\n"
250            "      2. Make sure .AppleDouble dir exist, create if missing\n"
251            "      3. Make sure AppleDouble file exists, create if missing\n"
252            "      4. Delete orphaned AppleDouble files\n"
253            "      5. Check for directories inside AppleDouble directories\n"
254            "      6. Check name encoding by roundtripping, log on error\n"
255            "      7. Check for orphaned CNIDs in database (requires -e)\n"
256            "      8. Open and close adouble files\n"
257            "      Options: -c Don't create .AppleDouble stuff, only cleanup orphaned.\n"
258            "               -f wipe database and rebuild from IDs stored in AppleDouble files,\n"
259            "                  only available for volumes without 'nocnidcache' option. Implies -e.\n\n"
260            "   -u Prepare upgrade:\n"
261            "      Before installing an upgraded version of Netatalk that is linked against\n"
262            "      a newer BerkeleyDB lib, run `dbd -u ...` from the OLD Netatalk pior to\n"
263            "      upgrading on all volumes. This removes the BerkleyDB environment.\n"
264            "      On exit cnid_dbd does this automatically, so normally calling dbd -u should not be necessary.\n\n"
265            "General options:\n"
266            "   -e only work on inactive volumes and lock them (exclusive)\n"
267            "   -x rebuild indexes (just for completeness, mostly useless!)\n"
268            "   -t show statistics while running\n"
269            "   -v verbose\n\n"
270            "WARNING:\n"
271            "For -r -f restore of the CNID database from the adouble files, the CNID must of course\n"
272            "be synched to them files first with a plain -r rebuild !\n"
273         );
274 }
275
276 int main(int argc, char **argv)
277 {
278     int c, lockfd, ret = -1;
279     int dump=0, scan=0, rebuild=0, prep_upgrade=0, rebuildindexes=0, dumpindexes=0, force=0;
280     dbd_flags_t flags = 0;
281     char *volpath;
282     struct volinfo volinfo;
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, ":cdefinrstuvx")) != -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 't':
314             flags |= DBD_FLAGS_STATS;
315             break;
316         case 'u':
317             prep_upgrade = 1;
318             break;
319         case 'v':
320             verbose = 1;
321             break;
322         case 'e':
323             exclusive = 1;
324             flags |= DBD_FLAGS_EXCL;
325             break;
326         case 'x':
327             rebuildindexes = 1;
328             break;
329         case 'f':
330             force = 1;
331             exclusive = 1;
332             flags |= DBD_FLAGS_FORCE | DBD_FLAGS_EXCL;
333             break;
334         case ':':
335         case '?':
336             usage();
337             exit(EXIT_FAILURE);
338             break;
339         }
340     }
341
342     if ((dump + scan + rebuild + prep_upgrade) != 1) {
343         usage();
344         exit(EXIT_FAILURE);
345     }
346
347     if ( (optind + 1) != argc ) {
348         usage();
349         exit(EXIT_FAILURE);
350     }
351     volpath = argv[optind];
352
353     setvbuf(stdout, (char *) NULL, _IONBF, 0);
354
355     /* Remember cwd */
356     if ((cdir = open(".", O_RDONLY)) < 0) {
357         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
358         exit(EXIT_FAILURE);
359     }
360         
361     /* Setup signal handling */
362     set_signal();
363
364     /* Setup logging. Should be portable among *NIXes */
365     if (!verbose)
366         setuplog("default log_info /dev/tty");
367     else
368         setuplog("default log_debug /dev/tty");
369
370     /* Load .volinfo file */
371     if (loadvolinfo(volpath, &volinfo) == -1) {
372         dbd_log( LOGSTD, "Not a Netatalk volume at '%s', no .volinfo file at '%s/.AppleDesktop/.volinfo' or unknown volume options", volpath, volpath);
373         exit(EXIT_FAILURE);
374     }
375     if (vol_load_charsets(&volinfo) == -1) {
376         dbd_log( LOGSTD, "Error loading charsets!");
377         exit(EXIT_FAILURE);
378     }
379
380     /* Sanity checks to ensure we can touch this volume */
381     if (volinfo.v_vfs_ea != AFPVOL_EA_AD && volinfo.v_vfs_ea != AFPVOL_EA_SYS) {
382         dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", volinfo.v_vfs_ea);
383         exit(EXIT_FAILURE);        
384     }
385
386     /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
387     if ( (strlen(volinfo.v_dbpath) + strlen("/.AppleDB")) > (PATH_MAX - 1) ) {
388         dbd_log( LOGSTD, "Volume pathname too long");
389         exit(EXIT_FAILURE);        
390     }
391     strncpy(dbpath, volinfo.v_dbpath, PATH_MAX - 9 - 1);
392     strcat(dbpath, "/.AppleDB");
393
394     /* Check or create dbpath */
395     int dbdirfd = open(dbpath, O_RDONLY);
396     if (dbdirfd == -1 && errno == ENOENT) {
397         if (errno == ENOENT) {
398             if ((mkdir(dbpath, 0755)) != 0) {
399                 dbd_log( LOGSTD, "Can't create .AppleDB for \"%s\": %s", dbpath, strerror(errno));
400                 exit(EXIT_FAILURE);
401             }
402         } else {
403             dbd_log( LOGSTD, "Somethings wrong with .AppleDB for \"%s\", giving up: %s", dbpath, strerror(errno));
404             exit(EXIT_FAILURE);
405         }
406     } else {
407         close(dbdirfd);
408     }
409
410     /* 
411        Before we do anything else, check if there is an instance of cnid_dbd
412        running already and silently exit if yes.
413     */
414     lockfd = get_lock(dbpath);
415
416     /* Prepare upgrade ? */
417     if (prep_upgrade) {
418         if (dbif_prep_upgrade(dbpath))
419             goto exit_failure;
420         goto exit_success;
421     }        
422
423     /* Check if -f is requested and wipe db if yes */
424     if ((flags & DBD_FLAGS_FORCE) && rebuild && (volinfo.v_flags & AFPVOL_CACHE)) {
425         char cmd[8 + MAXPATHLEN];
426         close(lockfd);
427         snprintf(cmd, 8 + MAXPATHLEN, "rm -f %s/*", dbpath);
428         dbd_log( LOGDEBUG, "Removing old database of volume: '%s'", volpath);
429         system(cmd);
430         dbd_log( LOGDEBUG, "Removed old database.");
431         lockfd = get_lock(dbpath);
432     }
433
434     /* 
435        Lets start with the BerkeleyDB stuff
436     */
437     if ( ! nocniddb) {
438         if ((dbd = dbif_init(dbpath, "cnid2.db")) == NULL)
439             goto exit_failure;
440         
441         if (dbif_env_open(dbd, &db_param, exclusive ? (DBOPTIONS | DB_RECOVER) : DBOPTIONS) < 0) {
442             dbd_log( LOGSTD, "error opening database!");
443             goto exit_failure;
444         }
445
446         if (exclusive)
447             dbd_log( LOGDEBUG, "Finished recovery.");
448
449         if (dbif_open(dbd, NULL, rebuildindexes) < 0) {
450             dbif_close(dbd);
451             goto exit_failure;
452         }
453
454         if (dbd_stamp(dbd) < 0) {
455             dbif_close(dbd);
456             goto exit_failure;
457         }
458     }
459
460     /* Now execute given command scan|rebuild|dump */
461     if (dump && ! nocniddb) {
462         if (dbif_dump(dbd, dumpindexes) < 0) {
463             dbd_log( LOGSTD, "Error dumping database");
464         }
465     } else if ((rebuild && ! nocniddb) || scan) {
466         if (cmd_dbd_scanvol(dbd, &volinfo, flags) < 0) {
467             dbd_log( LOGSTD, "Error repairing database.");
468         }
469     }
470
471     /* Cleanup */
472     dbd_log(LOGDEBUG, "Closing db");
473     if (! nocniddb) {
474         if (dbif_close(dbd) < 0) {
475             dbd_log( LOGSTD, "Error closing database");
476             goto exit_failure;
477         }
478     }
479
480 exit_success:
481     ret = 0;
482
483 exit_failure:
484     free_lock(lockfd);
485     
486     if ((fchdir(cdir)) < 0)
487         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));
488
489     if (ret == 0)
490         exit(EXIT_SUCCESS);
491     else
492         exit(EXIT_FAILURE);
493 }