]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd_scanvol.c
Set cachesize for rebuild db
[netatalk.git] / etc / cnid_dbd / cmd_dbd_scanvol.c
1 /*
2   $Id: cmd_dbd_scanvol.c,v 1.15 2009-12-21 06:41:09 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 <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <dirent.h>
26 #include <fcntl.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <setjmp.h>
30
31 #include <atalk/adouble.h>
32 #include <atalk/unicode.h>
33 #include <atalk/volinfo.h>
34 #include <atalk/cnid_dbd_private.h>
35 #include <atalk/volume.h>
36 #include <atalk/ea.h>
37 #include <atalk/util.h>
38
39 #include "cmd_dbd.h"
40 #include "dbif.h"
41 #include "db_param.h"
42 #include "dbd.h"
43
44 /* Some defines to ease code parsing */
45 #define ADDIR_OK (addir_ok == 0)
46 #define ADFILE_OK (adfile_ok == 0)
47
48 /* These must be accessible for cmd_dbd_* funcs */
49 struct volinfo        *volinfo;
50 char                  cwdbuf[MAXPATHLEN+1];
51
52 /* Some static vars */
53 static DBD            *dbd;
54 static DBD            *dbd_rebuild;
55 static dbd_flags_t    dbd_flags;
56 static char           stamp[CNID_DEV_LEN];
57 static char           *netatalk_dirs[] = {
58     ".AppleDB",
59     ".AppleDesktop",
60     NULL
61 };
62 static struct cnid_dbd_rqst rqst;
63 static struct cnid_dbd_rply rply;
64 static jmp_buf jmp;
65 static struct vol volume; /* fake it for ea_open */
66 static char pname[MAXPATHLEN] = "../";
67
68 /*
69   Taken form afpd/desktop.c
70 */
71 static char *utompath(char *upath)
72 {
73     static char  mpath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
74     char         *m, *u;
75     uint16_t     flags = CONV_IGNORE | CONV_UNESCAPEHEX;
76     size_t       outlen;
77
78     if (!upath)
79         return NULL;
80
81     m = mpath;
82     u = upath;
83     outlen = strlen(upath);
84
85     if ((volinfo->v_casefold & AFPVOL_UTOMUPPER))
86         flags |= CONV_TOUPPER;
87     else if ((volinfo->v_casefold & AFPVOL_UTOMLOWER))
88         flags |= CONV_TOLOWER;
89
90     if ((volinfo->v_flags & AFPVOL_EILSEQ)) {
91         flags |= CONV__EILSEQ;
92     }
93
94     /* convert charsets */
95     if ((size_t)-1 == ( outlen = convert_charset(volinfo->v_volcharset,
96                                                  CH_UTF8_MAC,
97                                                  volinfo->v_maccharset,
98                                                  u, outlen, mpath, MAXPATHLEN, &flags)) ) {
99         dbd_log( LOGSTD, "Conversion from %s to %s for %s failed.",
100                  volinfo->v_volcodepage, volinfo->v_maccodepage, u);
101         return NULL;
102     }
103
104     return(m);
105 }
106
107 /*
108   Taken form afpd/desktop.c
109 */
110 static char *mtoupath(char *mpath)
111 {
112     static char  upath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
113     char    *m, *u;
114     size_t       inplen;
115     size_t       outlen;
116     u_int16_t    flags = 0;
117
118     if (!mpath)
119         return NULL;
120
121     if ( *mpath == '\0' ) {
122         return( "." );
123     }
124
125     /* set conversion flags */
126     if (!(volinfo->v_flags & AFPVOL_NOHEX))
127         flags |= CONV_ESCAPEHEX;
128     if (!(volinfo->v_flags & AFPVOL_USEDOTS))
129         flags |= CONV_ESCAPEDOTS;
130
131     if ((volinfo->v_casefold & AFPVOL_MTOUUPPER))
132         flags |= CONV_TOUPPER;
133     else if ((volinfo->v_casefold & AFPVOL_MTOULOWER))
134         flags |= CONV_TOLOWER;
135
136     if ((volinfo->v_flags & AFPVOL_EILSEQ)) {
137         flags |= CONV__EILSEQ;
138     }
139
140     m = mpath;
141     u = upath;
142
143     inplen = strlen(m);
144     outlen = MAXPATHLEN;
145
146     if ((size_t)-1 == (outlen = convert_charset(CH_UTF8_MAC,
147                                                 volinfo->v_volcharset,
148                                                 volinfo->v_maccharset,
149                                                 m, inplen, u, outlen, &flags)) ) {
150         dbd_log( LOGSTD, "conversion from UTF8-MAC to %s for %s failed.",
151                  volinfo->v_volcodepage, mpath);
152         return NULL;
153     }
154
155     return( upath );
156 }
157
158 /*
159   Check for wrong encoding e.g. "." at the beginning is not CAP encoded (:2e) although volume is default !AFPVOL_USEDOTS.
160   We do it by roundtripiping from volcharset to UTF8-MAC and back and then compare the result.
161 */
162 static int check_name_encoding(char *uname)
163 {
164     char *roundtripped;
165
166     roundtripped = mtoupath(utompath(uname));
167     if (!roundtripped) {
168         dbd_log( LOGSTD, "Error checking encoding for '%s/%s'", cwdbuf, uname);
169         return -1;
170     }
171
172     if ( STRCMP(uname, !=, roundtripped)) {
173         dbd_log( LOGSTD, "Bad encoding for '%s/%s'", cwdbuf, uname);
174         return -1;
175     }
176
177     return 0;
178 }
179
180 /*
181   Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop"
182   Returns pointer to name or NULL.
183 */
184 static const char *check_netatalk_dirs(const char *name)
185 {
186     int c;
187
188     for (c=0; netatalk_dirs[c]; c++) {
189         if ((strcmp(name, netatalk_dirs[c])) == 0)
190             return netatalk_dirs[c];
191     }
192     return NULL;
193 }
194
195 /*
196   Check for .AppleDouble file, create if missing
197 */
198 static int check_adfile(const char *fname, const struct stat *st)
199 {
200     int ret, adflags;
201     struct adouble ad;
202     char *adname;
203
204     if (S_ISREG(st->st_mode))
205         adflags = 0;
206     else
207         adflags = ADFLAGS_DIR;
208
209     adname = volinfo->ad_path(fname, adflags);
210
211     if ((ret = access( adname, F_OK)) != 0) {
212         if (errno != ENOENT) {
213             dbd_log(LOGSTD, "Access error for ad-file '%s/%s': %s",
214                     cwdbuf, adname, strerror(errno));
215             return -1;
216         }
217         /* Missing. Log and create it */
218         dbd_log(LOGSTD, "Missing AppleDouble file '%s/%s'", cwdbuf, adname);
219
220         if (dbd_flags & DBD_FLAGS_SCAN)
221             /* Scan only requested, dont change anything */
222             return -1;
223
224         /* Create ad file */
225         ad_init(&ad, volinfo->v_adouble, volinfo->v_ad_options);
226
227         if ((ret = ad_open_metadata( fname, adflags, O_CREAT, &ad)) != 0) {
228             dbd_log( LOGSTD, "Error creating AppleDouble file '%s/%s': %s",
229                      cwdbuf, adname, strerror(errno));
230
231             return -1;
232         }
233
234         /* Set name in ad-file */
235         ad_setname(&ad, utompath((char *)fname));
236         ad_flush(&ad);
237         ad_close_metadata(&ad);
238
239         chown(adname, st->st_uid, st->st_gid);
240         /* FIXME: should we inherit mode too here ? */
241 #if 0
242         chmod(adname, st->st_mode);
243 #endif
244     } else {
245         ad_init(&ad, volinfo->v_adouble, volinfo->v_ad_options);
246         if (ad_open_metadata( fname, adflags, O_RDONLY, &ad) != 0) {
247             dbd_log( LOGSTD, "Error opening AppleDouble file for '%s/%s'", cwdbuf, fname);
248             return -1;
249         }
250         ad_close_metadata(&ad);
251     }
252     return 0;
253 }
254
255 /* 
256    Remove all files with file::EA* from adouble dir
257 */
258 static void remove_eafiles(const char *name, struct ea *ea)
259 {
260     DIR *dp = NULL;
261     struct dirent *ep;
262     char eaname[MAXPATHLEN];
263
264     strlcpy(eaname, name, sizeof(eaname));
265     if (strlcat(eaname, "::EA", sizeof(eaname)) >= sizeof(eaname)) {
266         dbd_log(LOGSTD, "name too long: '%s/%s/%s'", cwdbuf, ADv2_DIRNAME, name);
267         return;
268     }
269
270     if ((chdir(ADv2_DIRNAME)) != 0) {
271         dbd_log(LOGSTD, "Couldn't chdir to '%s/%s': %s",
272                 cwdbuf, ADv2_DIRNAME, strerror(errno));
273         return;
274     }
275
276     if ((dp = opendir(".")) == NULL) {
277         dbd_log(LOGSTD, "Couldn't open the directory '%s/%s': %s",
278                 cwdbuf, ADv2_DIRNAME, strerror(errno));
279         return;
280     }
281
282     while ((ep = readdir(dp))) {
283         if (strstr(ep->d_name, eaname) != NULL) {
284             dbd_log(LOGSTD, "Removing EA file: '%s/%s/%s'",
285                     cwdbuf, ADv2_DIRNAME, ep->d_name);
286             if ((unlink(ep->d_name)) != 0) {
287                 dbd_log(LOGSTD, "Error unlinking EA file '%s/%s/%s': %s",
288                         cwdbuf, ADv2_DIRNAME, ep->d_name, strerror(errno));
289             }
290         } /* if */
291     } /* while */
292
293     if (dp)
294         closedir(dp);
295
296 }
297
298 /*
299   Check Extended Attributes files
300 */
301 static int check_eafiles(const char *fname)
302 {
303     unsigned int  count = 0;
304     int ret = 0, remove;
305     struct ea ea;
306     struct stat st;
307     char *eaname;
308
309     if ((ret = ea_open(&volume, fname, EA_RDWR, &ea)) != 0) {
310         if (errno == ENOENT)
311             return 0;
312         dbd_log(LOGSTD, "Error calling ea_open for file: %s/%s, removing EA files",
313                 cwdbuf, fname);
314         if ( ! (dbd_flags & DBD_FLAGS_SCAN))
315             remove_eafiles(fname, &ea);
316         return -1;
317     }
318
319     /* Check all EAs */
320     while (count < ea.ea_count) {        
321         dbd_log(LOGDEBUG, "EA: %s", (*ea.ea_entries)[count].ea_name);
322         remove = 0;
323
324         eaname = ea_path(&ea, (*ea.ea_entries)[count].ea_name, 0);
325
326         if (stat(eaname, &st) != 0) {
327             if (errno == ENOENT)
328                 dbd_log(LOGSTD, "Missing EA: %s/%s", cwdbuf, eaname);
329             else
330                 dbd_log(LOGSTD, "Bogus EA: %s/%s", cwdbuf, eaname);
331             remove = 1;
332         } else if (st.st_size != (*ea.ea_entries)[count].ea_size) {
333             dbd_log(LOGSTD, "Bogus EA: %s/%s, removing it...", cwdbuf, eaname);
334             remove = 1;
335             if ((unlink(eaname)) != 0)
336                 dbd_log(LOGSTD, "Error removing EA file '%s/%s': %s",
337                         cwdbuf, eaname, strerror(errno));
338         }
339
340         if (remove) {
341             /* Be CAREFUL here! This should do what ea_delentry does. ea_close relies on it !*/
342             free((*ea.ea_entries)[count].ea_name);
343             (*ea.ea_entries)[count].ea_name = NULL;
344         }
345
346         count++;
347     } /* while */
348
349     ea_close(&ea);
350     return ret;
351 }
352
353 /*
354   Check for .AppleDouble folder and .Parent, create if missing
355 */
356 static int check_addir(int volroot)
357 {
358     int addir_ok, adpar_ok;
359     struct stat st;
360     struct adouble ad;
361     char *mname = NULL;
362
363     /* Check for ad-dir */
364     if ( (addir_ok = access(ADv2_DIRNAME, F_OK)) != 0) {
365         if (errno != ENOENT) {
366             dbd_log(LOGSTD, "Access error in directory %s: %s", cwdbuf, strerror(errno));
367             return -1;
368         }
369         dbd_log(LOGSTD, "Missing %s for '%s'", ADv2_DIRNAME, cwdbuf);
370     }
371
372     /* Check for ".Parent" */
373     if ( (adpar_ok = access(volinfo->ad_path(".", ADFLAGS_DIR), F_OK)) != 0) {
374         if (errno != ENOENT) {
375             dbd_log(LOGSTD, "Access error on '%s/%s': %s",
376                     cwdbuf, volinfo->ad_path(".", ADFLAGS_DIR), strerror(errno));
377             return -1;
378         }
379         dbd_log(LOGSTD, "Missing .AppleDouble/.Parent for '%s'", cwdbuf);
380     }
381
382     /* Is one missing ? */
383     if ((addir_ok != 0) || (adpar_ok != 0)) {
384         /* Yes, but are we only scanning ? */
385         if (dbd_flags & DBD_FLAGS_SCAN) {
386             /* Yes:  missing .Parent is not a problem, but missing ad-dir
387                causes later checking of ad-files to fail. So we have to return appropiately */
388             if (addir_ok != 0)
389                 return -1;
390             else  /* (adpar_ok != 0) */
391                 return 0;
392         }
393
394         /* Create ad dir and set name */
395         ad_init(&ad, volinfo->v_adouble, volinfo->v_ad_options);
396
397         if (ad_open_metadata( ".", ADFLAGS_DIR, O_CREAT, &ad) != 0) {
398             dbd_log( LOGSTD, "Error creating AppleDouble dir in %s: %s", cwdbuf, strerror(errno));
399             return -1;
400         }
401
402         /* Get basename of cwd from cwdbuf */
403         mname = utompath(strrchr(cwdbuf, '/') + 1);
404
405         /* Update name in ad file */
406         ad_setname(&ad, mname);
407         ad_flush(&ad);
408         ad_close_metadata(&ad);
409
410         /* Inherit owner/group from "." to ".AppleDouble" and ".Parent" */
411         if ((stat(".", &st)) != 0) {
412             dbd_log( LOGSTD, "Couldnt stat %s: %s", cwdbuf, strerror(errno));
413             return -1;
414         }
415         chown(ADv2_DIRNAME, st.st_uid, st.st_gid);
416         chown(volinfo->ad_path(".", ADFLAGS_DIR), st.st_uid, st.st_gid);
417     }
418
419     return 0;
420 }
421
422 /*
423   Check if file cotains "::EA" and if it does check if its correspondig data fork exists.
424   Returns:
425   0 = name is not an EA file
426   1 = name is an EA file and no problem was found
427   -1 = name is an EA file and data fork is gone
428  */
429 static int check_eafile_in_adouble(const char *name)
430 {
431     int ret = 0;
432     char *namep, *namedup = NULL;
433
434     /* Check if this is an AFPVOL_EA_AD vol */
435     if (volinfo->v_vfs_ea == AFPVOL_EA_AD) {
436         /* Does the filename contain "::EA" ? */
437         namedup = strdup(name);
438         if ((namep = strstr(namedup, "::EA")) == NULL) {
439             ret = 0;
440             goto ea_check_done;
441         } else {
442             /* File contains "::EA" so it's an EA file. Check for data file  */
443
444             /* Get string before "::EA" from EA filename */
445             namep[0] = 0;
446             strlcpy(pname + 3, namedup, sizeof(pname)); /* Prepends "../" */
447
448             if ((access( pname, F_OK)) == 0) {
449                 ret = 1;
450                 goto ea_check_done;
451             } else {
452                 ret = -1;
453                 if (errno != ENOENT) {
454                     dbd_log(LOGSTD, "Access error for file '%s/%s': %s",
455                             cwdbuf, name, strerror(errno));
456                     goto ea_check_done;
457                 }
458
459                 /* Orphaned EA file*/
460                 dbd_log(LOGSTD, "Orphaned Extended Attribute file '%s/%s/%s'",
461                         cwdbuf, ADv2_DIRNAME, name);
462
463                 if (dbd_flags & DBD_FLAGS_SCAN)
464                     /* Scan only requested, dont change anything */
465                     goto ea_check_done;
466
467                 if ((unlink(name)) != 0) {
468                     dbd_log(LOGSTD, "Error unlinking orphaned Extended Attribute file '%s/%s/%s'",
469                             cwdbuf, ADv2_DIRNAME, name);
470                 }
471             } /* if (access) */
472         } /* if strstr */
473     } /* if AFPVOL_EA_AD */
474
475 ea_check_done:
476     if (namedup)
477         free(namedup);
478
479     return ret;
480 }
481
482 /*
483   Check files and dirs inside .AppleDouble folder:
484   - remove orphaned files
485   - bail on dirs
486 */
487 static int read_addir(void)
488 {
489     DIR *dp;
490     struct dirent *ep;
491     struct stat st;
492
493     if ((chdir(ADv2_DIRNAME)) != 0) {
494         dbd_log(LOGSTD, "Couldn't chdir to '%s/%s': %s",
495                 cwdbuf, ADv2_DIRNAME, strerror(errno));
496         return -1;
497     }
498
499     if ((dp = opendir(".")) == NULL) {
500         dbd_log(LOGSTD, "Couldn't open the directory '%s/%s': %s",
501                 cwdbuf, ADv2_DIRNAME, strerror(errno));
502         return -1;
503     }
504
505     while ((ep = readdir(dp))) {
506         /* Check if its "." or ".." */
507         if (DIR_DOT_OR_DOTDOT(ep->d_name))
508             continue;
509         /* Skip ".Parent" */
510         if (STRCMP(ep->d_name, ==, ".Parent"))
511             continue;
512
513         if ((stat(ep->d_name, &st)) < 0) {
514             dbd_log( LOGSTD, "Lost file or dir while enumeratin dir '%s/%s/%s', probably removed: %s",
515                      cwdbuf, ADv2_DIRNAME, ep->d_name, strerror(errno));
516             continue;
517         }
518
519         /* Check for dirs */
520         if (S_ISDIR(st.st_mode)) {
521             dbd_log( LOGSTD, "Unexpected directory '%s' in AppleDouble dir '%s/%s'",
522                      ep->d_name, cwdbuf, ADv2_DIRNAME);
523             continue;
524         }
525
526         /* Check if for orphaned and corrupt Extended Attributes file */
527         if (check_eafile_in_adouble(ep->d_name) != 0)
528             continue;
529
530         /* Check for data file */
531         strcpy(pname + 3, ep->d_name);
532         if ((access( pname, F_OK)) != 0) {
533             if (errno != ENOENT) {
534                 dbd_log(LOGSTD, "Access error for file '%s/%s': %s",
535                         cwdbuf, pname, strerror(errno));
536                 continue;
537             }
538             /* Orphaned ad-file*/
539             dbd_log(LOGSTD, "Orphaned AppleDoube file '%s/%s/%s'",
540                     cwdbuf, ADv2_DIRNAME, ep->d_name);
541
542             if (dbd_flags & DBD_FLAGS_SCAN)
543                 /* Scan only requested, dont change anything */
544                 continue;;
545
546             if ((unlink(ep->d_name)) != 0) {
547                 dbd_log(LOGSTD, "Error unlinking orphaned AppleDoube file '%s/%s/%s'",
548                         cwdbuf, ADv2_DIRNAME, ep->d_name);
549
550             }
551         }
552     }
553
554     if ((chdir("..")) != 0) {
555         dbd_log(LOGSTD, "Couldn't chdir back to '%s' from AppleDouble dir: %s",
556                 cwdbuf, strerror(errno));
557         /* This really is EOT! */
558         longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
559     }
560
561     closedir(dp);
562
563     return 0;
564 }
565
566 /*
567   Check CNID for a file/dir, both from db and from ad-file.
568   For detailed specs see intro.
569 */
570 static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfile_ok, int adflags)
571 {
572     int ret;
573     cnid_t db_cnid, ad_cnid;
574     struct adouble ad;
575
576     /* Get CNID from ad-file if volume is using AFPVOL_CACHE */
577     ad_cnid = 0;
578     if ( (volinfo->v_flags & AFPVOL_CACHE) && ADFILE_OK) {
579         ad_init(&ad, volinfo->v_adouble, volinfo->v_ad_options);
580         if (ad_open_metadata( name, adflags, O_RDWR, &ad) != 0) {
581             dbd_log( LOGSTD, "Error opening AppleDouble file for '%s/%s': %s", cwdbuf, name, strerror(errno));
582             return 0;
583         }
584
585         if (dbd_flags & DBD_FLAGS_FORCE) {
586             ad_cnid = ad_forcegetid(&ad);
587             /* This ensures the changed stamp is written */
588             ad_setid( &ad, st->st_dev, st->st_ino, ad_cnid, did, stamp);
589             ad_flush(&ad);
590         }
591         else
592             ad_cnid = ad_getid(&ad, st->st_dev, st->st_ino, did, stamp);
593
594         if (ad_cnid == 0)
595             dbd_log( LOGSTD, "Incorrect CNID data in .AppleDouble data for '%s/%s' (bad stamp?)", cwdbuf, name);
596
597         ad_close_metadata(&ad);
598     }
599
600     /* Get CNID from database */
601
602     /* Prepare request data */
603     memset(&rqst, 0, sizeof(struct cnid_dbd_rqst));
604     memset(&rply, 0, sizeof(struct cnid_dbd_rply));
605     rqst.did = did;
606     rqst.cnid = ad_cnid;
607     if ( ! (volinfo->v_flags & AFPVOL_NODEV))
608         rqst.dev = st->st_dev;
609     rqst.ino = st->st_ino;
610     rqst.type = S_ISDIR(st->st_mode)?1:0;
611     rqst.name = (char *)name;
612     rqst.namelen = strlen(name);
613
614     /* Query the database */
615     ret = dbd_lookup(dbd, &rqst, &rply, (dbd_flags & DBD_FLAGS_SCAN) ? 1 : 0);
616     dbif_txn_close(dbd, ret);
617     if (rply.result == CNID_DBD_RES_OK) {
618         db_cnid = rply.cnid;
619     } else if (rply.result == CNID_DBD_RES_NOTFOUND) {
620         if ( ! (dbd_flags & DBD_FLAGS_FORCE))
621             dbd_log( LOGSTD, "No CNID for '%s/%s' in database", cwdbuf, name);
622         db_cnid = 0;
623     } else {
624         dbd_log( LOGSTD, "Fatal error resolving '%s/%s'", cwdbuf, name);
625         db_cnid = 0;
626     }
627
628     /* Compare results from both CNID searches */
629     if (ad_cnid && db_cnid && (ad_cnid == db_cnid)) {
630         /* Everything is fine */
631         return db_cnid;
632     } else if (ad_cnid && db_cnid && (ad_cnid != db_cnid)) {
633         /* Mismatch ? Delete both from db and re-add data from file */
634         dbd_log( LOGSTD, "CNID mismatch for '%s/%s', db: %u, ad-file: %u", cwdbuf, name, ntohl(db_cnid), ntohl(ad_cnid));
635         if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
636             rqst.cnid = db_cnid;
637             ret = dbd_delete(dbd, &rqst, &rply, DBIF_CNID);
638             dbif_txn_close(dbd, ret);
639
640             rqst.cnid = ad_cnid;
641             ret = dbd_delete(dbd, &rqst, &rply, DBIF_CNID);
642             dbif_txn_close(dbd, ret);
643
644             ret = dbd_rebuild_add(dbd, &rqst, &rply);
645             dbif_txn_close(dbd, ret);
646         }
647         return ad_cnid;
648     } else if (ad_cnid && (db_cnid == 0)) {
649         /* in ad-file but not in db */
650         if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
651             dbd_log( LOGDEBUG, "CNID rebuild add for '%s/%s', adding with CNID from ad-file: %u", cwdbuf, name, ntohl(ad_cnid));
652             rqst.cnid = ad_cnid;
653             ret = dbd_delete(dbd, &rqst, &rply, DBIF_CNID);
654             dbif_txn_close(dbd, ret);
655             ret = dbd_rebuild_add(dbd, &rqst, &rply);
656             dbif_txn_close(dbd, ret);
657         }
658         return ad_cnid;
659     } else if ((db_cnid == 0) && (ad_cnid == 0)) {
660         /* No CNID at all, we clearly have to allocate a fresh one... */
661         /* Note: the next test will use this new CNID too! */
662         if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
663             /* add to db */
664             ret = dbd_add(dbd, &rqst, &rply, 1);
665             dbif_txn_close(dbd, ret);
666             db_cnid = rply.cnid;
667             dbd_log( LOGSTD, "New CNID for '%s/%s': %u", cwdbuf, name, ntohl(db_cnid));
668         }
669     }
670
671     if ((ad_cnid == 0) && db_cnid) {
672         /* in db but zeroID in ad-file, write it to ad-file if AFPVOL_CACHE */
673         if ((volinfo->v_flags & AFPVOL_CACHE) && ADFILE_OK) {
674             if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
675                 dbd_log( LOGSTD, "Writing CNID data for '%s/%s' to AppleDouble file", cwdbuf, name, ntohl(db_cnid));
676                 ad_init(&ad, volinfo->v_adouble, volinfo->v_ad_options);
677                 if (ad_open_metadata( name, adflags, O_RDWR, &ad) != 0) {
678                     dbd_log( LOGSTD, "Error opening AppleDouble file for '%s/%s': %s", cwdbuf, name, strerror(errno));
679                     return 0;
680                 }
681                 ad_setid( &ad, st->st_dev, st->st_ino, db_cnid, did, stamp);
682                 ad_flush(&ad);
683                 ad_close_metadata(&ad);
684             }
685         }
686         return db_cnid;
687     }
688
689     return 0;
690 }
691
692 /*
693   This is called recursively for all dirs.
694   volroot=1 means we're in the volume root dir, 0 means we aren't.
695   We use this when checking for netatalk private folders like .AppleDB.
696   did is our parents CNID.
697 */
698 static int dbd_readdir(int volroot, cnid_t did)
699 {
700     int cwd, ret = 0, adflags, adfile_ok, addir_ok, encoding_ok;
701     cnid_t cnid;
702     const char *name;
703     DIR *dp;
704     struct dirent *ep;
705     static struct stat st;      /* Save some stack space */
706
707     /* Check again for .AppleDouble folder, check_adfile also checks/creates it */
708     if ((addir_ok = check_addir(volroot)) != 0)
709         if ( ! (dbd_flags & DBD_FLAGS_SCAN))
710             /* Fatal on rebuild run, continue if only scanning ! */
711             return -1;
712
713     /* Check AppleDouble files in AppleDouble folder, but only if it exists or could be created */
714     if (ADDIR_OK)
715         if ((read_addir()) != 0)
716             if ( ! (dbd_flags & DBD_FLAGS_SCAN))
717                 /* Fatal on rebuild run, continue if only scanning ! */
718                 return -1;
719
720     if ((dp = opendir (".")) == NULL) {
721         dbd_log(LOGSTD, "Couldn't open the directory: %s",strerror(errno));
722         return -1;
723     }
724
725     while ((ep = readdir (dp))) {
726         /* Check if we got a termination signal */
727         if (alarmed)
728             longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
729
730         /* Check if its "." or ".." */
731         if (DIR_DOT_OR_DOTDOT(ep->d_name))
732             continue;
733
734         /* Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop" */
735         if ((name = check_netatalk_dirs(ep->d_name)) != NULL) {
736             if (! volroot)
737                 dbd_log(LOGSTD, "Nested %s in %s", name, cwdbuf);
738             continue;
739         }
740
741         /* Skip .AppleDouble dir in this loop */
742         if (STRCMP(ep->d_name, == , ADv2_DIRNAME))
743             continue;
744
745         if ((ret = stat(ep->d_name, &st)) < 0) {
746             dbd_log( LOGSTD, "Lost file while reading dir '%s/%s', probably removed: %s", cwdbuf, ep->d_name, strerror(errno));
747             continue;
748         }
749         if (S_ISREG(st.st_mode))
750             adflags = 0;
751         else
752             adflags = ADFLAGS_DIR;
753
754         /**************************************************************************
755            Tests
756         **************************************************************************/
757
758         /* Check encoding */
759         if ( -1 == (encoding_ok = check_name_encoding(ep->d_name)) ) {
760             /* If its a file: skipp all other tests now ! */
761             /* For dirs we could try to get a CNID for it and recurse, but currently I prefer not to */
762             continue;
763         }
764
765         /* Check for appledouble file, create if missing, but only if we have addir */
766         adfile_ok = -1;
767         if (ADDIR_OK)
768             adfile_ok = check_adfile(ep->d_name, &st);
769
770         if ( ! nocniddb) {
771             /* Check CNIDs */
772             cnid = check_cnid(ep->d_name, did, &st, adfile_ok, adflags);
773
774             /* Now add this object to our rebuild dbd */
775             if (cnid) {
776                 rqst.cnid = rply.cnid;
777                 dbd_rebuild_add(dbd_rebuild, &rqst, &rply);
778                 if (rply.result != CNID_DBD_RES_OK) {
779                     dbd_log( LOGDEBUG, "Fatal error adding CNID: %u for '%s/%s' to in-memory rebuild-db",
780                              cnid, cwdbuf, ep->d_name);
781                     longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
782                 }
783             }
784         }
785
786         /* Check EA files */
787         if (volinfo->v_vfs_ea == AFPVOL_EA_AD)
788             check_eafiles(ep->d_name);
789
790         /**************************************************************************
791           Recursion
792         **************************************************************************/
793         if (S_ISDIR(st.st_mode) && (cnid || nocniddb)) { /* If we have no cnid for it we cant recur */
794             strcat(cwdbuf, "/");
795             strcat(cwdbuf, ep->d_name);
796             dbd_log( LOGDEBUG, "Entering directory: %s", cwdbuf);
797             if (-1 == (cwd = open(".", O_RDONLY))) {
798                 dbd_log( LOGSTD, "Cant open directory '%s': %s", cwdbuf, strerror(errno));
799                 continue;
800             }
801             if (0 != chdir(ep->d_name)) {
802                 dbd_log( LOGSTD, "Cant chdir to directory '%s': %s", cwdbuf, strerror(errno));
803                 close(cwd);
804                 continue;
805             }
806
807             ret = dbd_readdir(0, cnid);
808
809             fchdir(cwd);
810             close(cwd);
811             *(strrchr(cwdbuf, '/')) = 0;
812             if (ret < 0)
813                 continue;
814         }
815     }
816
817     /*
818       Use results of previous checks
819     */
820
821     closedir(dp);
822     return ret;
823 }
824
825 static int scanvol(struct volinfo *vi, dbd_flags_t flags)
826 {
827     /* Dont scanvol on no-appledouble vols */
828     if (vi->v_flags & AFPVOL_NOADOUBLE) {
829         dbd_log( LOGSTD, "Volume without AppleDouble support: skipping volume scanning.");
830         return 0;
831     }
832
833     /* Make this stuff accessible from all funcs easily */
834     volinfo = vi;
835     dbd_flags = flags;
836
837     /* Init a fake struct vol with just enough so we can call ea_open and friends */
838     volume.v_adouble = AD_VERSION2;
839     volume.v_vfs_ea = volinfo->v_vfs_ea;
840     initvol_vfs(&volume);
841
842     /* Run with umask 0 */
843     umask(0);
844
845     /* chdir to vol */
846     strcpy(cwdbuf, volinfo->v_path);
847     if (cwdbuf[strlen(cwdbuf) - 1] == '/')
848         cwdbuf[strlen(cwdbuf) - 1] = 0;
849     chdir(volinfo->v_path);
850
851     /* Start recursion */
852     if (dbd_readdir(1, htonl(2)) < 0)  /* 2 = volumeroot CNID */
853         return -1;
854
855     return 0;
856 }
857
858 /*
859   Remove all CNIDs from dbd that are not in dbd_rebuild
860 */
861 static void delete_orphaned_cnids(DBD *dbd, DBD *dbd_rebuild, dbd_flags_t flags)
862 {
863     int ret, deleted = 0;
864     cnid_t dbd_cnid = 0, rebuild_cnid = 0;
865     struct cnid_dbd_rqst rqst;
866     struct cnid_dbd_rply rply;
867
868     /* jump over rootinfo key */
869     if ( dbif_idwalk(dbd, &dbd_cnid, 0) != 1)
870         return;
871     if ( dbif_idwalk(dbd_rebuild, &rebuild_cnid, 0) != 1)
872         return;
873
874     /* Get first id from dbd_rebuild */
875     if ((dbif_idwalk(dbd_rebuild, &rebuild_cnid, 0)) == -1)
876         return;
877
878     /* Start main loop through dbd: get CNID from dbd */
879     while ((dbif_idwalk(dbd, &dbd_cnid, 0)) == 1) {
880
881         if (deleted > 50) {
882             deleted = 0;
883             if (dbif_txn_checkpoint(dbd, 0, 0, 0) < 0) {
884                 dbd_log(LOGSTD, "Error checkpointing!");
885                 goto cleanup;
886             }
887         }
888
889         /* This should be the normal case: CNID is in both dbs */
890         if (dbd_cnid == rebuild_cnid) {
891             /* Get next CNID from rebuild db */
892             if ((ret = dbif_idwalk(dbd_rebuild, &rebuild_cnid, 0)) == -1) {
893                 /* Some error */
894                 goto cleanup;
895             } else if (ret == 0) {
896                 /* end of rebuild_cnid, delete all remaining CNIDs from dbd */
897                 while ((dbif_idwalk(dbd, &dbd_cnid, 0)) == 1) {
898                     dbd_log(LOGSTD, "Orphaned CNID in database: %u", dbd_cnid);
899                     if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
900                         rqst.cnid = htonl(dbd_cnid);
901                         ret = dbd_delete(dbd, &rqst, &rply, DBIF_CNID);
902                         dbif_txn_close(dbd, ret);
903                         deleted++;
904                     }
905                 }
906                 return;
907             } else
908                 /* Normal case (ret=1): continue while loop */
909                 continue;
910         }
911
912         if (dbd_cnid < rebuild_cnid) {
913             /* CNID is orphaned -> delete */
914             dbd_log(LOGSTD, "Orphaned CNID in database: %u.", dbd_cnid);
915             if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
916                 rqst.cnid = htonl(dbd_cnid);
917                 ret = dbd_delete(dbd, &rqst, &rply, DBIF_CNID);
918                 dbif_txn_close(dbd, ret);
919                 deleted++;
920             }
921             continue;
922         }
923
924         if (dbd_cnid > rebuild_cnid) {
925             dbd_log(LOGSTD, "Ghost CNID: %u. This is fatal! Dumping rebuild db:\n", rebuild_cnid);
926             dbif_dump(dbd_rebuild, 0);
927             dbd_log(LOGSTD, "Send this dump and a `dbd -d ...` dump to the Netatalk Dev team!");
928             dbif_txn_close(dbd, ret);
929             dbif_idwalk(dbd, NULL, 1); /* Close cursor */
930             dbif_idwalk(dbd_rebuild, NULL, 1); /* Close cursor */
931             goto cleanup;
932         }
933     }
934
935 cleanup:
936     dbif_idwalk(dbd, NULL, 1); /* Close cursor */
937     dbif_idwalk(dbd_rebuild, NULL, 1); /* Close cursor */
938     return;
939 }
940
941 /*
942   Main func called from cmd_dbd.c
943 */
944 int cmd_dbd_scanvol(DBD *dbd_ref, struct volinfo *volinfo, dbd_flags_t flags)
945 {
946     int ret = 0;
947     struct db_param db_param = { 0 };
948
949     /* Set cachesize for in-memory rebuild db */
950     db_param.cachesize = 128 * 1024 * 1024; /* 128 MB */
951
952     /* Make it accessible for all funcs */
953     dbd = dbd_ref;
954
955     /* We only support unicode volumes ! */
956     if ( volinfo->v_volcharset != CH_UTF8) {
957         dbd_log( LOGSTD, "Not a Unicode volume: %s, %u != %u", volinfo->v_volcodepage, volinfo->v_volcharset, CH_UTF8);
958         return -1;
959     }
960
961     if (! nocniddb) {
962         /* Get volume stamp */
963         dbd_getstamp(dbd, &rqst, &rply);
964         if (rply.result != CNID_DBD_RES_OK)
965             goto exit_cleanup;
966         memcpy(stamp, rply.name, CNID_DEV_LEN);
967
968         /* open/create rebuild dbd, copy rootinfo key */
969         if (NULL == (dbd_rebuild = dbif_init(NULL, NULL)))
970             return -1;
971         if (0 != (dbif_open(dbd_rebuild, &db_param, 0)))
972             return -1;
973         if (0 != (dbif_copy_rootinfokey(dbd, dbd_rebuild)))
974             goto exit_cleanup;
975     }
976
977     if (setjmp(jmp) != 0)
978         goto exit_cleanup;      /* Got signal, jump from dbd_readdir */
979
980     /* scanvol */
981     if ( (scanvol(volinfo, flags)) != 0)
982         return -1;
983
984     if (! nocniddb) {
985         /* We can only do this in exclusive mode, otherwise we might delete CNIDs added from
986            other clients in between our pass 1 and 2 */
987         if (flags & DBD_FLAGS_EXCL)
988             delete_orphaned_cnids(dbd, dbd_rebuild, flags);
989     }
990
991 exit_cleanup:
992     if (! nocniddb)
993         dbif_close(dbd_rebuild);
994     return ret;
995 }