]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/dbd.c
Fixes a serious error in the way recovery was run on db_env opening.
[netatalk.git] / etc / cnid_dbd / dbd.c
1 /* 
2    $Id: dbd.c,v 1.3 2009-05-06 11:54:24 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 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif /* HAVE_CONFIG_H */
20
21 #include <unistd.h>
22 #include <sys/types.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <limits.h>
27 #include <signal.h>
28 #include <string.h>
29 #include <errno.h>
30
31 #include <atalk/logger.h>
32 #include <atalk/cnid_dbd_private.h>
33 #include <atalk/volinfo.h>
34 #include "cmd_dbd.h"
35 #include "dbif.h"
36 #include "db_param.h"
37
38 #define LOCKFILENAME  "lock"
39 #define DBOPTIONS (DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN)
40
41 static DBD *dbd;
42
43 static volatile sig_atomic_t alarmed;
44 static int verbose;             /* Logging flag */
45 static int exclusive;           /* Exclusive volume access */
46 static struct db_param db_param = {
47     NULL,                       /* Volume dirpath */
48     1,                          /* bdb logfile autoremove */
49     16384,                      /* bdb cachesize */
50     -1,                         /* not used ... */
51     -1,
52     "",
53     -1,
54     -1,
55     -1
56 };
57
58 /* 
59    Provide some logging
60  */
61 void dbd_log(enum logtype lt, char *fmt, ...)
62 {
63     int len;
64     static char logbuffer[1024];
65     va_list args;
66
67     if ( (lt == LOGSTD) || (verbose == 1)) {
68         va_start(args, fmt);
69         len = vsnprintf(logbuffer, 1023, fmt, args);
70         va_end(args);
71         logbuffer[1023] = 0;
72
73         printf("%s\n", logbuffer);
74     }
75 }
76
77 /* 
78    SIGNAL handling:
79    ignore everything except SIGTERM which we catch and which causes
80    a clean exit.
81  */
82
83 static void sig_handler(int signo)
84 {
85     alarmed = 1;
86     return;
87 }
88
89 void set_signal(void)
90 {
91     struct sigaction sv;
92
93     sv.sa_handler = sig_handler;
94     sv.sa_flags = SA_RESTART;
95     sigemptyset(&sv.sa_mask);
96     sigaddset(&sv.sa_mask, SIGTERM);
97     if (sigaction(SIGTERM, &sv, NULL) < 0) {
98         dbd_log( LOGSTD, "error in sigaction(SIGTERM): %s", strerror(errno));
99         exit(EXIT_FAILURE);
100     }        
101
102     memset(&sv, 0, sizeof(struct sigaction));
103     sv.sa_handler = SIG_IGN;
104     sigemptyset(&sv.sa_mask);
105
106     if (sigaction(SIGINT, &sv, NULL) < 0) {
107         dbd_log( LOGSTD, "error in sigaction(SIGINT): %s", strerror(errno));
108         exit(EXIT_FAILURE);
109     }        
110     if (sigaction(SIGABRT, &sv, NULL) < 0) {
111         dbd_log( LOGSTD, "error in sigaction(SIGABRT): %s", strerror(errno));
112         exit(EXIT_FAILURE);
113     }        
114     if (sigaction(SIGHUP, &sv, NULL) < 0) {
115         dbd_log( LOGSTD, "error in sigaction(SIGHUP): %s", strerror(errno));
116         exit(EXIT_FAILURE);
117     }        
118     if (sigaction(SIGQUIT, &sv, NULL) < 0) {
119         dbd_log( LOGSTD, "error in sigaction(SIGQUIT): %s", strerror(errno));
120         exit(EXIT_FAILURE);
121     }        
122 }
123
124 #if 0
125 static void block_sigs_onoff(int block)
126 {
127     sigset_t set;
128     
129     sigemptyset(&set);
130     sigaddset(&set, SIGINT);
131     sigaddset(&set, SIGTERM);
132     if (block)
133         sigprocmask(SIG_BLOCK, &set, NULL);
134     else
135         sigprocmask(SIG_UNBLOCK, &set, NULL);
136     return;
137 }
138 #endif
139
140 int get_lock(void)
141 {
142     int lockfd;
143     struct flock lock;
144
145     if ((lockfd = open(LOCKFILENAME, O_RDWR | O_CREAT, 0644)) < 0) {
146         dbd_log( LOGSTD, "Error opening lockfile: %s", strerror(errno));
147         exit(EXIT_FAILURE);
148     }
149     
150     lock.l_start  = 0;
151     lock.l_whence = SEEK_SET;
152     lock.l_len    = 0;
153     lock.l_type   = F_WRLCK;
154
155     if (fcntl(lockfd, F_SETLK, &lock) < 0) {
156         if (errno == EACCES || errno == EAGAIN) {
157             if (exclusive) {
158                 dbd_log( LOGSTD, "Database is in use and exlusive was requested", strerror(errno));        
159                 exit(EXIT_FAILURE);
160             };
161         } else {
162             dbd_log( LOGSTD, "Error getting fcntl F_WRLCK on lockfile: %s", strerror(errno));
163             exit(EXIT_FAILURE);
164        }
165     }
166     
167     return lockfd;
168 }
169
170 void free_lock(int lockfd)
171 {
172     struct flock lock;
173
174     lock.l_start  = 0;
175     lock.l_whence = SEEK_SET;
176     lock.l_len    = 0;
177     lock.l_type = F_UNLCK;
178     fcntl(lockfd, F_SETLK, &lock);
179     close(lockfd);
180 }
181
182 static void usage ()
183 {
184     printf("Usage: dbd [-e|-v|-x] -d [-i] | -s | -r [-f] <path to netatalk volume>\n"
185            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
186            "dbd must be run with appropiate permissions i.e. as root.\n\n"
187            "Main commands are:\n"
188            "   -d Dump CNID database\n"
189            "      Option: -i dump indexes too\n"
190            "   -s Scan volume:\n"
191            "      1. Compare database with volume\n"
192            "      2. Check if .AppleDouble dirs exist\n"
193            "      3. Check if  AppleDouble file exist\n"
194            "      4. Report orphaned AppleDouble files\n"
195            "      5. Check for directories inside AppleDouble directories\n"
196            "      6. Check name encoding by roundtripping, log on error\n"
197            "   -r Rebuild volume:\n"
198            "      1. Sync database with volume\n"
199            "      2. Make sure .AppleDouble dir exist, create if missing\n"
200            "      3. Make sure AppleDouble file exists, create if missing\n"
201            "      4. Delete orphaned AppleDouble files\n"
202            "      5. Check for directories inside AppleDouble directories\n"
203            "      6. Check name encoding by roundtripping, log on error\n"
204            "      Option: -f wipe database and rebuild from IDs stored in AppleDouble files,\n"
205            "                 only available for volumes with 'cachecnid' option\n\n"
206            "General options:\n"
207            "   -e only work on inactive volumes and lock them (exclusive)\n"
208            "   -x rebuild indexes\n"
209            "   -v verbose\n"
210            "\n"
211            "05-05-2009: -s and -r already check/repair the AppleDouble stuff and encoding,\n"
212            "            no CNID database maintanance is done yet\n"
213         );
214 }
215
216 int main(int argc, char **argv)
217 {
218     int c, lockfd;
219     int dump=0, scan=0, rebuild=0, rebuildindexes=0, dumpindexes=0, force=0;
220     dbd_flags_t flags = 0;
221     char *volpath;
222     struct volinfo volinfo;
223
224     if (geteuid() != 0) {
225         usage();
226         exit(EXIT_FAILURE);
227     }
228
229     while ((c = getopt(argc, argv, ":dsrvxife")) != -1) {
230         switch(c) {
231         case 'd':
232             dump = 1;
233             break;
234         case 'i':
235             dumpindexes = 1;
236             break;
237         case 's':
238             scan = 1;
239             flags = DBD_FLAGS_SCAN;
240             break;
241         case 'r':
242             rebuild = 1;
243             break;
244         case 'v':
245             verbose = 1;
246             break;
247         case 'e':
248             exclusive = 1;
249             break;
250         case 'x':
251             rebuildindexes = 1;
252             break;
253         case 'f':
254             force = 1;
255             flags = DBD_FLAGS_FORCE;
256             break;
257         case ':':
258         case '?':
259             usage();
260             exit(EXIT_FAILURE);
261             break;
262         }
263     }
264
265     if ((dump + scan + rebuild) != 1) {
266         usage();
267         exit(EXIT_FAILURE);
268     }
269
270     if ( (optind + 1) != argc ) {
271         usage();
272         exit(EXIT_FAILURE);
273     }
274     volpath = argv[optind];
275
276     /* Put "/.AppleDB" at end of volpath */
277     if ( (strlen(volpath) + strlen("/.AppleDB")) > (PATH_MAX -1) ) {
278         dbd_log( LOGSTD, "Volume pathname too long");
279         exit(EXIT_FAILURE);        
280     }
281     char dbpath[PATH_MAX];
282     strncpy(dbpath, volpath, PATH_MAX - 1);
283     strcat(dbpath, "/.AppleDB");
284
285     /* cd to .AppleDB dir */
286     int cdir;
287     if ((cdir = open(".", O_RDONLY)) < 0) {
288         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
289         exit(EXIT_FAILURE);
290     }
291     if (chdir(dbpath) < 0) {
292         dbd_log( LOGSTD, "chdir to %s failed: %s", dbpath, strerror(errno));
293         exit(EXIT_FAILURE);
294     }
295         
296     /* 
297        Before we do anything else, check if there is an instance of cnid_dbd
298        running already and silently exit if yes.
299     */
300     lockfd = get_lock();
301     
302     /* Ignore everything except SIGTERM */
303     set_signal();
304
305     /* Setup logging. Should be portable among *NIXes */
306     if (!verbose)
307         setuplog("default log_info /dev/tty");
308     else
309         setuplog("default log_debug /dev/tty");
310
311     /* Load .volinfo file */
312     if ( -1 == loadvolinfo(volpath, &volinfo)) {
313         dbd_log( LOGSTD, "Unkown volume options!");
314         exit(EXIT_FAILURE);
315     }
316     if ( -1 == vol_load_charsets(&volinfo)) {
317         dbd_log( LOGSTD, "Error loading charsets!");
318         exit(EXIT_FAILURE);
319     }
320
321     /* 
322        Lets start with the BerkeleyDB stuff
323     */
324     if (NULL == (dbd = dbif_init("cnid2.db")))
325         exit(2);
326
327     if (dbif_env_open(dbd, &db_param, DBOPTIONS) < 0) {
328         dbd_log( LOGSTD, "error opening database!");
329         exit(EXIT_FAILURE);
330     }
331
332     dbd_log( LOGDEBUG, "Finished opening BerkeleyDB databases including recovery.");
333
334     if (dbif_open(dbd, &db_param, rebuildindexes) < 0) {
335         dbif_close(dbd);
336         exit(EXIT_FAILURE);
337     }
338
339     if ((fchdir(cdir)) < 0) {
340         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));        
341         goto cleanup;
342     }
343
344     if (dump) {
345         if (dbif_dump(dbd, dumpindexes) < 0) {
346             dbd_log( LOGSTD, "Error dumping database");
347         }
348     } else if (rebuild || scan) {
349         if (cmd_dbd_scanvol(dbd, &volinfo, flags) < 0) {
350             dbd_log( LOGSTD, "Fatal error repairing database. Please rm -r it.");
351         }
352     }
353
354 cleanup:
355     if (dbif_close(dbd) < 0)
356         exit(EXIT_FAILURE);
357
358     free_lock(lockfd);
359
360     return 0;
361 }