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