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