]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd.c
Create dbpath if not existent
[netatalk.git] / etc / cnid_dbd / cmd_dbd.c
1 /* 
2    $Id: cmd_dbd.c,v 1.26 2010-04-20 16:46:20 hat001 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     64 * 1024,                  /* bdb cachesize (64 MB) */
95     5000,                       /* maxlocks */
96     5000,                       /* maxlockobjs */
97     -1,                         /* not used ... */
98     -1,
99     "",
100     -1,
101     -1,
102     -1
103 };
104 static char dbpath[PATH_MAX];   /* 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 static int get_lock(const char *dbpath)
171 {
172     int lockfd;
173     char lockpath[PATH_MAX];
174     struct flock lock;
175     struct stat st;
176
177     if ( (strlen(dbpath) + strlen(LOCKFILENAME+1)) > (PATH_MAX - 1) ) {
178         dbd_log( LOGSTD, ".AppleDB pathname too long");
179         exit(EXIT_FAILURE);
180     }
181     strncpy(lockpath, dbpath, PATH_MAX - 1);
182     strcat(lockpath, "/");
183     strcat(lockpath, LOCKFILENAME);
184
185     if ((lockfd = open(lockpath, O_RDWR | O_CREAT, 0644)) < 0) {
186         dbd_log( LOGSTD, "Error opening lockfile: %s", strerror(errno));
187         exit(EXIT_FAILURE);
188     }
189
190     if ((stat(dbpath, &st)) != 0) {
191         dbd_log( LOGSTD, "Error statting lockfile: %s", strerror(errno));
192         exit(EXIT_FAILURE);
193     }
194
195     if ((chown(lockpath, st.st_uid, st.st_gid)) != 0) {
196         dbd_log( LOGSTD, "Error inheriting lockfile permissions: %s", strerror(errno));
197         exit(EXIT_FAILURE);
198     }
199     
200     lock.l_start  = 0;
201     lock.l_whence = SEEK_SET;
202     lock.l_len    = 0;
203     lock.l_type   = F_WRLCK;
204
205     if (fcntl(lockfd, F_SETLK, &lock) < 0) {
206         if (errno == EACCES || errno == EAGAIN) {
207             if (exclusive) {
208                 dbd_log( LOGSTD, "Database is in use and exlusive was requested", strerror(errno));        
209                 exit(EXIT_FAILURE);
210             };
211         } else {
212             dbd_log( LOGSTD, "Error getting fcntl F_WRLCK on lockfile: %s", strerror(errno));
213             exit(EXIT_FAILURE);
214        }
215     }
216     
217     return lockfd;
218 }
219
220 static void free_lock(int lockfd)
221 {
222     struct flock lock;
223
224     lock.l_start  = 0;
225     lock.l_whence = SEEK_SET;
226     lock.l_len    = 0;
227     lock.l_type = F_UNLCK;
228     fcntl(lockfd, F_SETLK, &lock);
229     close(lockfd);
230 }
231
232 static void usage (void)
233 {
234     printf("Usage: dbd [-e|-v|-x] -d [-i] | -s [-c|-n]| -r [-c|-f] | -u <path to netatalk volume>\n"
235            "dbd can dump, scan, reindex and rebuild Netatalk dbd CNID databases.\n"
236            "dbd must be run with appropiate permissions i.e. as root.\n\n"
237            "Main commands are:\n"
238            "   -d Dump CNID database\n"
239            "      Option: -i dump indexes too\n\n"
240            "   -s Scan volume:\n"
241            "      1. Compare CNIDs in database with volume\n"
242            "      2. Check if .AppleDouble dirs exist\n"
243            "      3. Check if  AppleDouble file exist\n"
244            "      4. Report orphaned AppleDouble files\n"
245            "      5. Check for directories inside AppleDouble directories\n"
246            "      6. Check name encoding by roundtripping, log on error\n"
247            "      7. Check for orphaned CNIDs in database (requires -e)\n"
248            "      8. Open and close adouble files\n"
249            "      Options: -c Don't check .AppleDouble stuff, only ckeck orphaned.\n"
250            "               -n Don't open CNID database, skip CNID checks\n\n"
251            "   -r Rebuild volume:\n"
252            "      1. Sync CNIDSs in database with volume\n"
253            "      2. Make sure .AppleDouble dir exist, create if missing\n"
254            "      3. Make sure AppleDouble file exists, create if missing\n"
255            "      4. Delete orphaned AppleDouble files\n"
256            "      5. Check for directories inside AppleDouble directories\n"
257            "      6. Check name encoding by roundtripping, log on error\n"
258            "      7. Check for orphaned CNIDs in database (requires -e)\n"
259            "      8. Open and close adouble files\n"
260            "      Options: -c Don't create .AppleDouble stuff, only cleanup orphaned.\n"
261            "               -f wipe database and rebuild from IDs stored in AppleDouble files,\n"
262            "                  only available for volumes without 'nocnidcache' option. Implies -e.\n\n"
263            "   -u Prepare upgrade:\n"
264            "      Before installing an upgraded version of Netatalk that is linked against\n"
265            "      a newer BerkeleyDB lib, run `dbd -u ...` from the OLD Netatalk pior to\n"
266            "      upgrading on all volumes. This removes the BerkleyDB environment.\n"
267            "      On exit cnid_dbd does this automatically, so normally calling dbd -u should not be necessary.\n\n"
268            "General options:\n"
269            "   -e only work on inactive volumes and lock them (exclusive)\n"
270            "   -x rebuild indexes (just for completeness, mostly useless!)\n"
271            "   -v verbose\n\n"
272            "WARNING:\n"
273            "For -r -f restore of the CNID database from the adouble files, the CNID must of course\n"
274            "be synched to them files first with a plain -r rebuild !\n"
275         );
276 }
277
278 int main(int argc, char **argv)
279 {
280     int c, lockfd, ret = -1;
281     int dump=0, scan=0, rebuild=0, prep_upgrade=0, rebuildindexes=0, dumpindexes=0, force=0;
282     dbd_flags_t flags = 0;
283     char *volpath;
284     struct volinfo volinfo;
285     int cdir;
286
287     if (geteuid() != 0) {
288         usage();
289         exit(EXIT_FAILURE);
290     }
291     /* Inhereting perms in ad_mkdir etc requires this */
292     ad_setfuid(0);
293
294     while ((c = getopt(argc, argv, ":cdefinrsuvx")) != -1) {
295         switch(c) {
296         case 'c':
297             flags |= DBD_FLAGS_CLEANUP;
298             break;
299         case 'd':
300             dump = 1;
301             break;
302         case 'i':
303             dumpindexes = 1;
304             break;
305         case 's':
306             scan = 1;
307             flags |= DBD_FLAGS_SCAN;
308             break;
309         case 'n':
310             nocniddb = 1; /* FIXME: this could/should be a flag too for consistency */
311             break;
312         case 'r':
313             rebuild = 1;
314             break;
315         case 'u':
316             prep_upgrade = 1;
317             break;
318         case 'v':
319             verbose = 1;
320             break;
321         case 'e':
322             exclusive = 1;
323             flags |= DBD_FLAGS_EXCL;
324             break;
325         case 'x':
326             rebuildindexes = 1;
327             break;
328         case 'f':
329             force = 1;
330             exclusive = 1;
331             flags |= DBD_FLAGS_FORCE | DBD_FLAGS_EXCL;
332             break;
333         case ':':
334         case '?':
335             usage();
336             exit(EXIT_FAILURE);
337             break;
338         }
339     }
340
341     if ((dump + scan + rebuild + prep_upgrade) != 1) {
342         usage();
343         exit(EXIT_FAILURE);
344     }
345
346     if ( (optind + 1) != argc ) {
347         usage();
348         exit(EXIT_FAILURE);
349     }
350     volpath = argv[optind];
351
352     setvbuf(stdout, (char *) NULL, _IONBF, 0);
353
354     /* Remember cwd */
355     if ((cdir = open(".", O_RDONLY)) < 0) {
356         dbd_log( LOGSTD, "Can't open dir: %s", strerror(errno));
357         exit(EXIT_FAILURE);
358     }
359         
360     /* Setup signal handling */
361     set_signal();
362
363     /* Setup logging. Should be portable among *NIXes */
364     if (!verbose)
365         setuplog("default log_info /dev/tty");
366     else
367         setuplog("default log_debug /dev/tty");
368
369     /* Load .volinfo file */
370     if (loadvolinfo(volpath, &volinfo) == -1) {
371         dbd_log( LOGSTD, "Not a Netatalk volume at '%s', no .volinfo file at '%s/.AppleDesktop/.volinfo' or unknown volume options", volpath, volpath);
372         exit(EXIT_FAILURE);
373     }
374     if (vol_load_charsets(&volinfo) == -1) {
375         dbd_log( LOGSTD, "Error loading charsets!");
376         exit(EXIT_FAILURE);
377     }
378
379     /* Sanity checks to ensure we can touch this volume */
380     if (volinfo.v_vfs_ea != AFPVOL_EA_AD && volinfo.v_vfs_ea != AFPVOL_EA_SYS) {
381         dbd_log( LOGSTD, "Unknown Extended Attributes option: %u", volinfo.v_vfs_ea);
382         exit(EXIT_FAILURE);        
383     }
384
385     /* Enuser dbpath is there, create if necessary */
386     struct stat st;
387     if (stat(volinfo.v_dbpath, &st) != 0) {
388         if (errno != ENOENT) {
389             dbd_log( LOGSTD, "Can't stat dbpath \"%s\": %s", volinfo.v_dbpath, strerror(errno));
390             exit(EXIT_FAILURE);        
391         }
392         if ((mkdir(volinfo.v_dbpath, 0755)) != 0) {
393             dbd_log( LOGSTD, "Can't create dbpath \"%s\": %s", dbpath, strerror(errno));
394             exit(EXIT_FAILURE);
395         }        
396     }
397
398     /* Put "/.AppleDB" at end of volpath, get path from volinfo file */
399     if ( (strlen(volinfo.v_dbpath) + strlen("/.AppleDB")) > (PATH_MAX - 1) ) {
400         dbd_log( LOGSTD, "Volume pathname too long");
401         exit(EXIT_FAILURE);        
402     }
403     strncpy(dbpath, volinfo.v_dbpath, PATH_MAX - 9 - 1);
404     strcat(dbpath, "/.AppleDB");
405
406     /* Check or create dbpath */
407     int dbdirfd = open(dbpath, O_RDONLY);
408     if (dbdirfd == -1 && errno == ENOENT) {
409         if (errno == ENOENT) {
410             if ((mkdir(dbpath, 0755)) != 0) {
411                 dbd_log( LOGSTD, "Can't create .AppleDB for \"%s\": %s", dbpath, strerror(errno));
412                 exit(EXIT_FAILURE);
413             }
414         } else {
415             dbd_log( LOGSTD, "Somethings wrong with .AppleDB for \"%s\", giving up: %s", dbpath, strerror(errno));
416             exit(EXIT_FAILURE);
417         }
418     } else {
419         close(dbdirfd);
420     }
421
422     /* 
423        Before we do anything else, check if there is an instance of cnid_dbd
424        running already and silently exit if yes.
425     */
426     lockfd = get_lock(dbpath);
427
428     /* Prepare upgrade ? */
429     if (prep_upgrade) {
430         if (dbif_env_remove(dbpath))
431             goto exit_failure;
432         goto exit_success;
433     }        
434
435     /* Check if -f is requested and wipe db if yes */
436     if ((flags & DBD_FLAGS_FORCE) && rebuild && (volinfo.v_flags & AFPVOL_CACHE)) {
437         char cmd[8 + MAXPATHLEN];
438         snprintf(cmd, 8 + MAXPATHLEN, "rm -f %s/*", dbpath);
439         dbd_log( LOGDEBUG, "Removing old database of volume: '%s'", volpath);
440         system(cmd);
441         dbd_log( LOGDEBUG, "Removed old database.");
442     }
443
444     /* 
445        Lets start with the BerkeleyDB stuff
446     */
447     if ( ! nocniddb) {
448         if ((dbd = dbif_init(dbpath, "cnid2.db")) == NULL)
449             goto exit_failure;
450         
451         if (dbif_env_open(dbd, &db_param, exclusive ? (DBOPTIONS | DB_RECOVER) : DBOPTIONS) < 0) {
452             dbd_log( LOGSTD, "error opening database!");
453             goto exit_failure;
454         }
455
456         if (exclusive)
457             dbd_log( LOGDEBUG, "Finished recovery.");
458
459         if (dbif_open(dbd, NULL, rebuildindexes) < 0) {
460             dbif_close(dbd);
461             goto exit_failure;
462         }
463
464         if (dbd_stamp(dbd) < 0) {
465             dbif_close(dbd);
466             goto exit_failure;
467         }
468     }
469
470     /* Now execute given command scan|rebuild|dump */
471     if (dump && ! nocniddb) {
472         if (dbif_dump(dbd, dumpindexes) < 0) {
473             dbd_log( LOGSTD, "Error dumping database");
474         }
475     } else if ((rebuild && ! nocniddb) || scan) {
476         if (cmd_dbd_scanvol(dbd, &volinfo, flags) < 0) {
477             dbd_log( LOGSTD, "Error repairing database.");
478         }
479     }
480
481     /* Cleanup */
482     if (! nocniddb && dbif_close(dbd) < 0) {
483         dbd_log( LOGSTD, "Error closing database");
484         goto exit_failure;
485     }
486
487 exit_success:
488     ret = 0;
489
490 exit_failure:
491     free_lock(lockfd);
492     
493     if ((fchdir(cdir)) < 0)
494         dbd_log(LOGSTD, "fchdir: %s", strerror(errno));
495
496     if (ret == 0)
497         exit(EXIT_SUCCESS);
498     else
499         exit(EXIT_FAILURE);
500 }