]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd.c
9e2aef88783ced3a659c24d493d77f121b21f3c3
[netatalk.git] / etc / cnid_dbd / cmd_dbd.c
1 /* 
2    $Id: cmd_dbd.c,v 1.2 2009-05-18 09:25:25 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 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    catch SIGINT and SIGTERM which cause clean exit. Ignore anything else.
80  */
81
82 static void sig_handler(int signo)
83 {
84     alarmed = 1;
85     return;
86 }
87
88 void set_signal(void)
89 {
90     struct sigaction sv;
91
92     sv.sa_handler = sig_handler;
93     sv.sa_flags = SA_RESTART;
94     sigemptyset(&sv.sa_mask);
95     if (sigaction(SIGTERM, &sv, NULL) < 0) {
96         dbd_log( LOGSTD, "error in sigaction(SIGTERM): %s", strerror(errno));
97         exit(EXIT_FAILURE);
98     }        
99     if (sigaction(SIGINT, &sv, NULL) < 0) {
100         dbd_log( LOGSTD, "error in sigaction(SIGINT): %s", strerror(errno));
101         exit(EXIT_FAILURE);
102     }        
103
104     memset(&sv, 0, sizeof(struct sigaction));
105     sv.sa_handler = SIG_IGN;
106     sigemptyset(&sv.sa_mask);
107
108     if (sigaction(SIGABRT, &sv, NULL) < 0) {
109         dbd_log( LOGSTD, "error in sigaction(SIGABRT): %s", strerror(errno));
110         exit(EXIT_FAILURE);
111     }        
112     if (sigaction(SIGHUP, &sv, NULL) < 0) {
113         dbd_log( LOGSTD, "error in sigaction(SIGHUP): %s", strerror(errno));
114         exit(EXIT_FAILURE);
115     }        
116     if (sigaction(SIGQUIT, &sv, NULL) < 0) {
117         dbd_log( LOGSTD, "error in sigaction(SIGQUIT): %s", strerror(errno));
118         exit(EXIT_FAILURE);
119     }        
120 }
121
122 int get_lock(const char *dbpath)
123 {
124     int lockfd;
125     char lockpath[PATH_MAX];
126     struct flock lock;
127     struct stat st;
128
129     if ( (strlen(dbpath) + strlen(LOCKFILENAME+1)) > (PATH_MAX - 1) ) {
130         dbd_log( LOGSTD, ".AppleDB pathname too long");
131         exit(EXIT_FAILURE);
132     }
133     strncpy(lockpath, dbpath, PATH_MAX - 1);
134     strcat(lockpath, "/");
135     strcat(lockpath, LOCKFILENAME);
136
137     if ((lockfd = open(lockpath, O_RDWR | O_CREAT, 0644)) < 0) {
138         dbd_log( LOGSTD, "Error opening lockfile: %s", strerror(errno));
139         exit(EXIT_FAILURE);
140     }
141
142     if ((stat(dbpath, &st)) != 0) {
143         dbd_log( LOGSTD, "Error statting lockfile: %s", strerror(errno));
144         exit(EXIT_FAILURE);
145     }
146
147     if ((chown(lockpath, st.st_uid, st.st_gid)) != 0) {
148         dbd_log( LOGSTD, "Error inheriting lockfile permissions: %s", strerror(errno));
149         exit(EXIT_FAILURE);
150     }
151     
152     lock.l_start  = 0;
153     lock.l_whence = SEEK_SET;
154     lock.l_len    = 0;
155     lock.l_type   = F_WRLCK;
156
157     if (fcntl(lockfd, F_SETLK, &lock) < 0) {
158         if (errno == EACCES || errno == EAGAIN) {
159             if (exclusive) {
160                 dbd_log( LOGSTD, "Database is in use and exlusive was requested", strerror(errno));        
161                 exit(EXIT_FAILURE);
162             };
163         } else {
164             dbd_log( LOGSTD, "Error getting fcntl F_WRLCK on lockfile: %s", strerror(errno));
165             exit(EXIT_FAILURE);
166        }
167     }
168     
169     return lockfd;
170 }
171
172 void free_lock(int lockfd)
173 {
174     struct flock lock;
175
176     lock.l_start  = 0;
177     lock.l_whence = SEEK_SET;
178     lock.l_len    = 0;
179     lock.l_type = F_UNLCK;
180     fcntl(lockfd, F_SETLK, &lock);
181     close(lockfd);
182 }
183
184 static void usage ()
185 {
186     printf("Usage: dbd [-e|-v|-x] -d [-i] | -s | -r [-f] <path to netatalk volume>\n"
187            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
188            "dbd must be run with appropiate permissions i.e. as root.\n\n"
189            "Main commands are:\n"
190            "   -d Dump CNID database\n"
191            "      Option: -i dump indexes too\n"
192            "   -s Scan volume:\n"
193            "      1. Compare database with volume\n"
194            "      2. Check if .AppleDouble dirs exist\n"
195            "      3. Check if  AppleDouble file exist\n"
196            "      4. Report orphaned AppleDouble files\n"
197            "      5. Check for directories inside AppleDouble directories\n"
198            "      6. Check name encoding by roundtripping, log on error\n"
199            "   -r Rebuild volume:\n"
200            "      1. Sync database with volume\n"
201            "      2. Make sure .AppleDouble dir exist, create if missing\n"
202            "      3. Make sure AppleDouble file exists, create if missing\n"
203            "      4. Delete orphaned AppleDouble files\n"
204            "      5. Check for directories inside AppleDouble directories\n"
205            "      6. Check name encoding by roundtripping, log on error\n"
206            "      Option: -f wipe database and rebuild from IDs stored in AppleDouble files,\n"
207            "                 only available for volumes with 'cachecnid' option\n\n"
208            "General options:\n"
209            "   -e only work on inactive volumes and lock them (exclusive)\n"
210            "   -x rebuild indexes\n"
211            "   -v verbose\n"
212         );
213 }
214
215 int main(int argc, char **argv)
216 {
217     int c, lockfd;
218     int dump=0, scan=0, rebuild=0, rebuildindexes=0, dumpindexes=0, force=0;
219     dbd_flags_t flags = 0;
220     char *volpath;
221     struct volinfo volinfo;
222
223     if (geteuid() != 0) {
224         usage();
225         exit(EXIT_FAILURE);
226     }
227
228     while ((c = getopt(argc, argv, ":dsrvxife")) != -1) {
229         switch(c) {
230         case 'd':
231             dump = 1;
232             break;
233         case 'i':
234             dumpindexes = 1;
235             break;
236         case 's':
237             scan = 1;
238             flags = DBD_FLAGS_SCAN;
239             break;
240         case 'r':
241             rebuild = 1;
242             break;
243         case 'v':
244             verbose = 1;
245             break;
246         case 'e':
247             exclusive = 1;
248             break;
249         case 'x':
250             rebuildindexes = 1;
251             break;
252         case 'f':
253             force = 1;
254             flags = DBD_FLAGS_FORCE;
255             break;
256         case ':':
257         case '?':
258             usage();
259             exit(EXIT_FAILURE);
260             break;
261         }
262     }
263
264     if ((dump + scan + rebuild) != 1) {
265         usage();
266         exit(EXIT_FAILURE);
267     }
268
269     if ( (optind + 1) != argc ) {
270         usage();
271         exit(EXIT_FAILURE);
272     }
273     volpath = argv[optind];
274
275     /* Put "/.AppleDB" at end of volpath */
276     if ( (strlen(volpath) + strlen("/.AppleDB")) > (PATH_MAX - 1) ) {
277         dbd_log( LOGSTD, "Volume pathname too long");
278         exit(EXIT_FAILURE);        
279     }
280     char dbpath[PATH_MAX];
281     strncpy(dbpath, volpath, PATH_MAX - 1);
282     strcat(dbpath, "/.AppleDB");
283
284     /* Remember cwd */
285     int cdir;
286     if ((cdir = open(".", O_RDONLY)) < 0) {
287         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
288         exit(EXIT_FAILURE);
289     }
290         
291     /* 
292        Before we do anything else, check if there is an instance of cnid_dbd
293        running already and silently exit if yes.
294     */
295     lockfd = get_lock(dbpath);
296
297     /* Setup signal handling */
298     set_signal();
299
300     /* Setup logging. Should be portable among *NIXes */
301     if (!verbose)
302         setuplog("default log_info /dev/tty");
303     else
304         setuplog("default log_debug /dev/tty");
305
306     /* Load .volinfo file */
307     if (loadvolinfo(volpath, &volinfo) == -1) {
308         dbd_log( LOGSTD, "Unkown volume options!");
309         exit(EXIT_FAILURE);
310     }
311     if (vol_load_charsets(&volinfo) == -1) {
312         dbd_log( LOGSTD, "Error loading charsets!");
313         exit(EXIT_FAILURE);
314     }
315
316     /* 
317        Lets start with the BerkeleyDB stuff
318     */
319     if ((dbd = dbif_init(dbpath, "cnid2.db")) == NULL)
320         exit(EXIT_FAILURE);
321
322     if (dbif_env_open(dbd, &db_param, exclusive ? (DBOPTIONS | DB_RECOVER) : DBOPTIONS) < 0) {
323         dbd_log( LOGSTD, "error opening database!");
324         exit(EXIT_FAILURE);
325     }
326
327     if (exclusive)
328         dbd_log( LOGDEBUG, "Finished recovery.");
329
330     if (dbif_open(dbd, &db_param, rebuildindexes) < 0) {
331         dbif_close(dbd);
332         exit(EXIT_FAILURE);
333     }
334
335     if (dump) {
336         if (dbif_dump(dbd, dumpindexes) < 0) {
337             dbd_log( LOGSTD, "Error dumping database");
338         }
339     } else if (rebuild || scan) {
340         if (cmd_dbd_scanvol(dbd, &volinfo, flags) < 0) {
341             dbd_log( LOGSTD, "Error repairing database.");
342         }
343     }
344
345     if (dbif_close(dbd) < 0) {
346         dbd_log( LOGSTD, "Error closing database");
347         exit(EXIT_FAILURE);
348     }
349
350     free_lock(lockfd);
351
352     if ((fchdir(cdir)) < 0)
353         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));
354
355     return 0;
356 }