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