]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cmd_dbd_scanvol.c
Merge master
[netatalk.git] / etc / cnid_dbd / cmd_dbd_scanvol.c
1 /*
2   Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13 */
14
15 #ifdef HAVE_CONFIG_H
16 #include "config.h"
17 #endif /* HAVE_CONFIG_H */
18
19 #include <unistd.h>
20 #include <stdlib.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <dirent.h>
24 #include <fcntl.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <setjmp.h>
28
29 #include <atalk/adouble.h>
30 #include <atalk/unicode.h>
31 #include <atalk/netatalk_conf.h>
32 #include <atalk/cnid_dbd_private.h>
33 #include <atalk/volume.h>
34 #include <atalk/ea.h>
35 #include <atalk/util.h>
36 #include <atalk/acl.h>
37 #include <atalk/compat.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
49 static struct vol     *myvol;
50 static char           cwdbuf[MAXPATHLEN+1];
51 static DBD            *dbd;
52 static DBD            *dbd_rebuild;
53 static dbd_flags_t    dbd_flags;
54 static char           stamp[CNID_DEV_LEN];
55 static char           *netatalk_dirs[] = {
56     ".AppleDB",
57     ".AppleDesktop",
58     NULL
59 };
60 static char           *special_dirs[] = {
61     ".zfs",
62     NULL
63 };
64 static struct cnid_dbd_rqst rqst;
65 static struct cnid_dbd_rply rply;
66 static jmp_buf jmp;
67 static char pname[MAXPATHLEN] = "../";
68
69 /*
70   Taken form afpd/desktop.c
71 */
72 static char *utompath(char *upath)
73 {
74     static char  mpath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
75     char         *m, *u;
76     uint16_t     flags = CONV_IGNORE | CONV_UNESCAPEHEX;
77     size_t       outlen;
78
79     if (!upath)
80         return NULL;
81
82     m = mpath;
83     u = upath;
84     outlen = strlen(upath);
85
86     if ((myvol->v_casefold & AFPVOL_UTOMUPPER))
87         flags |= CONV_TOUPPER;
88     else if ((myvol->v_casefold & AFPVOL_UTOMLOWER))
89         flags |= CONV_TOLOWER;
90
91     if ((myvol->v_flags & AFPVOL_EILSEQ)) {
92         flags |= CONV__EILSEQ;
93     }
94
95     /* convert charsets */
96     if ((size_t)-1 == ( outlen = convert_charset(myvol->v_volcharset,
97                                                  CH_UTF8_MAC,
98                                                  myvol->v_maccharset,
99                                                  u, outlen, mpath, MAXPATHLEN, &flags)) ) {
100         dbd_log( LOGSTD, "Conversion from %s to %s for %s failed.",
101                  myvol->v_volcodepage, myvol->v_maccodepage, u);
102         return NULL;
103     }
104
105     return(m);
106 }
107
108 /*
109   Taken form afpd/desktop.c
110 */
111 static char *mtoupath(char *mpath)
112 {
113     static char  upath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
114     char    *m, *u;
115     size_t       inplen;
116     size_t       outlen;
117     u_int16_t    flags = 0;
118
119     if (!mpath)
120         return NULL;
121
122     if ( *mpath == '\0' ) {
123         return( "." );
124     }
125
126     /* set conversion flags */
127     if (!(myvol->v_flags & AFPVOL_NOHEX))
128         flags |= CONV_ESCAPEHEX;
129     if (!(myvol->v_flags & AFPVOL_USEDOTS))
130         flags |= CONV_ESCAPEDOTS;
131
132     if ((myvol->v_casefold & AFPVOL_MTOUUPPER))
133         flags |= CONV_TOUPPER;
134     else if ((myvol->v_casefold & AFPVOL_MTOULOWER))
135         flags |= CONV_TOLOWER;
136
137     if ((myvol->v_flags & AFPVOL_EILSEQ)) {
138         flags |= CONV__EILSEQ;
139     }
140
141     m = mpath;
142     u = upath;
143
144     inplen = strlen(m);
145     outlen = MAXPATHLEN;
146
147     if ((size_t)-1 == (outlen = convert_charset(CH_UTF8_MAC,
148                                                 myvol->v_volcharset,
149                                                 myvol->v_maccharset,
150                                                 m, inplen, u, outlen, &flags)) ) {
151         dbd_log( LOGSTD, "conversion from UTF8-MAC to %s for %s failed.",
152                  myvol->v_volcodepage, mpath);
153         return NULL;
154     }
155
156     return( upath );
157 }
158
159 /*
160   Check for wrong encoding e.g. "." at the beginning is not CAP encoded (:2e) although volume is default !AFPVOL_USEDOTS.
161   We do it by roundtripiping from volcharset to UTF8-MAC and back and then compare the result.
162 */
163 static int check_name_encoding(char *uname)
164 {
165     char *roundtripped;
166
167     roundtripped = mtoupath(utompath(uname));
168     if (!roundtripped) {
169         dbd_log( LOGSTD, "Error checking encoding for '%s/%s'", cwdbuf, uname);
170         return -1;
171     }
172
173     if ( STRCMP(uname, !=, roundtripped)) {
174         dbd_log( LOGSTD, "Bad encoding for '%s/%s'", cwdbuf, uname);
175         return -1;
176     }
177
178     return 0;
179 }
180
181 /*
182   Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop"
183   Returns pointer to name or NULL.
184 */
185 static const char *check_netatalk_dirs(const char *name)
186 {
187     int c;
188
189     for (c=0; netatalk_dirs[c]; c++) {
190         if ((strcmp(name, netatalk_dirs[c])) == 0)
191             return netatalk_dirs[c];
192     }
193     return NULL;
194 }
195
196 /*
197   Check for special names
198   Returns pointer to name or NULL.
199 */
200 static const char *check_special_dirs(const char *name)
201 {
202     int c;
203
204     for (c=0; special_dirs[c]; c++) {
205         if ((strcmp(name, special_dirs[c])) == 0)
206             return special_dirs[c];
207     }
208     return NULL;
209 }
210
211 /*
212   Check for .AppleDouble file, create if missing
213 */
214 static int check_adfile(const char *fname, const struct stat *st)
215 {
216     int ret;
217     int adflags = ADFLAGS_HF;
218     struct adouble ad;
219     const char *adname;
220
221     if (myvol->v_adouble == AD_VERSION_EA) {
222         if (!(dbd_flags & DBD_FLAGS_V2TOEA))
223             return 0;
224         if (ad_convert(fname, st, myvol) != 0) {
225             switch (errno) {
226             case ENOENT:
227                 break;
228             default:
229                 dbd_log(LOGSTD, "Conversion error for \"%s/%s\": %s", cwdbuf, fname, strerror(errno));
230                 break;
231             }
232         }
233         return 0;
234     }
235     
236     if (dbd_flags & DBD_FLAGS_CLEANUP)
237         return 0;
238
239     if (S_ISDIR(st->st_mode))
240         adflags |= ADFLAGS_DIR;
241
242     adname = myvol->ad_path(fname, adflags);
243
244     if ((ret = access( adname, F_OK)) != 0) {
245         if (errno != ENOENT) {
246             dbd_log(LOGSTD, "Access error for ad-file '%s/%s': %s",
247                     cwdbuf, adname, strerror(errno));
248             return -1;
249         }
250         /* Missing. Log and create it */
251         dbd_log(LOGSTD, "Missing AppleDouble file '%s/%s'", cwdbuf, adname);
252
253         if (dbd_flags & DBD_FLAGS_SCAN)
254             /* Scan only requested, dont change anything */
255             return -1;
256
257         /* Create ad file */
258         ad_init(&ad, myvol);
259
260         if ((ret = ad_open(&ad, fname, adflags | ADFLAGS_CREATE | ADFLAGS_RDWR, 0666)) != 0) {
261             dbd_log( LOGSTD, "Error creating AppleDouble file '%s/%s': %s",
262                      cwdbuf, adname, strerror(errno));
263
264             return -1;
265         }
266
267         /* Set name in ad-file */
268         ad_setname(&ad, utompath((char *)fname));
269         ad_flush(&ad);
270         ad_close(&ad, ADFLAGS_HF);
271
272         chown(adname, st->st_uid, st->st_gid);
273         /* FIXME: should we inherit mode too here ? */
274 #if 0
275         chmod(adname, st->st_mode);
276 #endif
277     } else {
278         ad_init(&ad, myvol);
279         if (ad_open(&ad, fname, adflags | ADFLAGS_RDONLY) != 0) {
280             dbd_log( LOGSTD, "Error opening AppleDouble file for '%s/%s'", cwdbuf, fname);
281             return -1;
282         }
283         ad_close(&ad, ADFLAGS_HF);
284     }
285     return 0;
286 }
287
288 /* 
289    Remove all files with file::EA* from adouble dir
290 */
291 static void remove_eafiles(const char *name, struct ea *ea)
292 {
293     DIR *dp = NULL;
294     struct dirent *ep;
295     char eaname[MAXPATHLEN];
296
297     strlcpy(eaname, name, sizeof(eaname));
298     if (strlcat(eaname, "::EA", sizeof(eaname)) >= sizeof(eaname)) {
299         dbd_log(LOGSTD, "name too long: '%s/%s/%s'", cwdbuf, ADv2_DIRNAME, name);
300         return;
301     }
302
303     if ((chdir(ADv2_DIRNAME)) != 0) {
304         dbd_log(LOGSTD, "Couldn't chdir to '%s/%s': %s",
305                 cwdbuf, ADv2_DIRNAME, strerror(errno));
306         return;
307     }
308
309     if ((dp = opendir(".")) == NULL) {
310         dbd_log(LOGSTD, "Couldn't open the directory '%s/%s': %s",
311                 cwdbuf, ADv2_DIRNAME, strerror(errno));
312         goto exit;
313     }
314
315     while ((ep = readdir(dp))) {
316         if (strstr(ep->d_name, eaname) != NULL) {
317             dbd_log(LOGSTD, "Removing EA file: '%s/%s/%s'",
318                     cwdbuf, ADv2_DIRNAME, ep->d_name);
319             if ((unlink(ep->d_name)) != 0) {
320                 dbd_log(LOGSTD, "Error unlinking EA file '%s/%s/%s': %s",
321                         cwdbuf, ADv2_DIRNAME, ep->d_name, strerror(errno));
322             }
323         } /* if */
324     } /* while */
325
326 exit:
327     if (dp)
328         closedir(dp);
329     if ((chdir("..")) != 0) {
330         dbd_log(LOGSTD, "Couldn't chdir to '%s': %s", cwdbuf, strerror(errno));
331         /* we can't proceed */
332         longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
333     }    
334 }
335
336 /*
337   Check Extended Attributes files
338 */
339 static int check_eafiles(const char *fname)
340 {
341     unsigned int  count = 0;
342     int ret = 0, remove;
343     struct ea ea;
344     struct stat st;
345     char *eaname;
346
347     if ((ret = ea_open(myvol, fname, EA_RDWR, &ea)) != 0) {
348         if (errno == ENOENT)
349             return 0;
350         dbd_log(LOGSTD, "Error calling ea_open for file: %s/%s, removing EA files", cwdbuf, fname);
351         if ( ! (dbd_flags & DBD_FLAGS_SCAN))
352             remove_eafiles(fname, &ea);
353         return -1;
354     }
355
356     /* Check all EAs */
357     while (count < ea.ea_count) {        
358         dbd_log(LOGDEBUG, "EA: %s", (*ea.ea_entries)[count].ea_name);
359         remove = 0;
360
361         eaname = ea_path(&ea, (*ea.ea_entries)[count].ea_name, 0);
362
363         if (lstat(eaname, &st) != 0) {
364             if (errno == ENOENT)
365                 dbd_log(LOGSTD, "Missing EA: %s/%s", cwdbuf, eaname);
366             else
367                 dbd_log(LOGSTD, "Bogus EA: %s/%s", cwdbuf, eaname);
368             remove = 1;
369         } else if (st.st_size != (*ea.ea_entries)[count].ea_size) {
370             dbd_log(LOGSTD, "Bogus EA: %s/%s, removing it...", cwdbuf, eaname);
371             remove = 1;
372             if ((unlink(eaname)) != 0)
373                 dbd_log(LOGSTD, "Error removing EA file '%s/%s': %s",
374                         cwdbuf, eaname, strerror(errno));
375         }
376
377         if (remove) {
378             /* Be CAREFUL here! This should do what ea_delentry does. ea_close relies on it !*/
379             free((*ea.ea_entries)[count].ea_name);
380             (*ea.ea_entries)[count].ea_name = NULL;
381         }
382
383         count++;
384     } /* while */
385
386     ea_close(&ea);
387     return ret;
388 }
389
390 /*
391   Check for .AppleDouble folder and .Parent, create if missing
392 */
393 static int check_addir(int volroot)
394 {
395     int addir_ok, adpar_ok;
396     struct stat st;
397     struct adouble ad;
398     char *mname = NULL;
399
400     if (dbd_flags & DBD_FLAGS_CLEANUP)
401         return 0;
402
403     if (myvol->v_adouble == AD_VERSION_EA)
404         return 0;
405
406     /* Check for ad-dir */
407     if ( (addir_ok = access(ADv2_DIRNAME, F_OK)) != 0) {
408         if (errno != ENOENT) {
409             dbd_log(LOGSTD, "Access error in directory %s: %s", cwdbuf, strerror(errno));
410             return -1;
411         }
412         dbd_log(LOGSTD, "Missing %s for '%s'", ADv2_DIRNAME, cwdbuf);
413     }
414
415     /* Check for ".Parent" */
416     if ( (adpar_ok = access(myvol->ad_path(".", ADFLAGS_DIR), F_OK)) != 0) {
417         if (errno != ENOENT) {
418             dbd_log(LOGSTD, "Access error on '%s/%s': %s",
419                     cwdbuf, myvol->ad_path(".", ADFLAGS_DIR), strerror(errno));
420             return -1;
421         }
422         dbd_log(LOGSTD, "Missing .AppleDouble/.Parent for '%s'", cwdbuf);
423     }
424
425     /* Is one missing ? */
426     if ((addir_ok != 0) || (adpar_ok != 0)) {
427         /* Yes, but are we only scanning ? */
428         if (dbd_flags & DBD_FLAGS_SCAN) {
429             /* Yes:  missing .Parent is not a problem, but missing ad-dir
430                causes later checking of ad-files to fail. So we have to return appropiately */
431             if (addir_ok != 0)
432                 return -1;
433             else  /* (adpar_ok != 0) */
434                 return 0;
435         }
436
437         /* Create ad dir and set name */
438         ad_init(&ad, myvol);
439
440         if (ad_open(&ad, ".", ADFLAGS_HF | ADFLAGS_DIR | ADFLAGS_CREATE | ADFLAGS_RDWR, 0777) != 0) {
441             dbd_log( LOGSTD, "Error creating AppleDouble dir in %s: %s", cwdbuf, strerror(errno));
442             return -1;
443         }
444
445         /* Get basename of cwd from cwdbuf */
446         mname = utompath(strrchr(cwdbuf, '/') + 1);
447
448         /* Update name in ad file */
449         ad_setname(&ad, mname);
450         ad_flush(&ad);
451         ad_close(&ad, ADFLAGS_HF);
452
453         /* Inherit owner/group from "." to ".AppleDouble" and ".Parent" */
454         if ((lstat(".", &st)) != 0) {
455             dbd_log( LOGSTD, "Couldnt stat %s: %s", cwdbuf, strerror(errno));
456             return -1;
457         }
458         chown(ADv2_DIRNAME, st.st_uid, st.st_gid);
459         chown(myvol->ad_path(".", ADFLAGS_DIR), st.st_uid, st.st_gid);
460     }
461
462     return 0;
463 }
464
465 /*
466   Check if file cotains "::EA" and if it does check if its correspondig data fork exists.
467   Returns:
468   0 = name is not an EA file
469   1 = name is an EA file and no problem was found
470   -1 = name is an EA file and data fork is gone
471  */
472 static int check_eafile_in_adouble(const char *name)
473 {
474     int ret = 0;
475     char *namep, *namedup = NULL;
476
477     /* Check if this is an AFPVOL_EA_AD vol */
478     if (myvol->v_vfs_ea == AFPVOL_EA_AD) {
479         /* Does the filename contain "::EA" ? */
480         namedup = strdup(name);
481         if ((namep = strstr(namedup, "::EA")) == NULL) {
482             ret = 0;
483             goto ea_check_done;
484         } else {
485             /* File contains "::EA" so it's an EA file. Check for data file  */
486
487             /* Get string before "::EA" from EA filename */
488             namep[0] = 0;
489             strlcpy(pname + 3, namedup, sizeof(pname)); /* Prepends "../" */
490
491             if ((access( pname, F_OK)) == 0) {
492                 ret = 1;
493                 goto ea_check_done;
494             } else {
495                 ret = -1;
496                 if (errno != ENOENT) {
497                     dbd_log(LOGSTD, "Access error for file '%s/%s': %s",
498                             cwdbuf, name, strerror(errno));
499                     goto ea_check_done;
500                 }
501
502                 /* Orphaned EA file*/
503                 dbd_log(LOGSTD, "Orphaned Extended Attribute file '%s/%s/%s'",
504                         cwdbuf, ADv2_DIRNAME, name);
505
506                 if (dbd_flags & DBD_FLAGS_SCAN)
507                     /* Scan only requested, dont change anything */
508                     goto ea_check_done;
509
510                 if ((unlink(name)) != 0) {
511                     dbd_log(LOGSTD, "Error unlinking orphaned Extended Attribute file '%s/%s/%s'",
512                             cwdbuf, ADv2_DIRNAME, name);
513                 }
514             } /* if (access) */
515         } /* if strstr */
516     } /* if AFPVOL_EA_AD */
517
518 ea_check_done:
519     if (namedup)
520         free(namedup);
521
522     return ret;
523 }
524
525 /*
526   Check files and dirs inside .AppleDouble folder:
527   - remove orphaned files
528   - bail on dirs
529 */
530 static int read_addir(void)
531 {
532     DIR *dp;
533     struct dirent *ep;
534     struct stat st;
535
536     if ((chdir(ADv2_DIRNAME)) != 0) {
537         if (myvol->v_adouble == AD_VERSION_EA) {
538             return 0;
539         }
540         dbd_log(LOGSTD, "Couldn't chdir to '%s/%s': %s",
541                 cwdbuf, ADv2_DIRNAME, strerror(errno));
542         return -1;
543     }
544
545     if ((dp = opendir(".")) == NULL) {
546         dbd_log(LOGSTD, "Couldn't open the directory '%s/%s': %s",
547                 cwdbuf, ADv2_DIRNAME, strerror(errno));
548         return -1;
549     }
550
551     while ((ep = readdir(dp))) {
552         /* Check if its "." or ".." */
553         if (DIR_DOT_OR_DOTDOT(ep->d_name))
554             continue;
555
556         /* Skip ".Parent" */
557         if (STRCMP(ep->d_name, ==, ".Parent"))
558             continue;
559
560         if ((lstat(ep->d_name, &st)) < 0) {
561             dbd_log( LOGSTD, "Lost file or dir while enumeratin dir '%s/%s/%s', probably removed: %s",
562                      cwdbuf, ADv2_DIRNAME, ep->d_name, strerror(errno));
563             continue;
564         }
565
566         /* Check for dirs */
567         if (S_ISDIR(st.st_mode)) {
568             dbd_log( LOGSTD, "Unexpected directory '%s' in AppleDouble dir '%s/%s'",
569                      ep->d_name, cwdbuf, ADv2_DIRNAME);
570             continue;
571         }
572
573         /* Check if for orphaned and corrupt Extended Attributes file */
574         if (check_eafile_in_adouble(ep->d_name) != 0)
575             continue;
576
577         /* Check for data file */
578         strcpy(pname + 3, ep->d_name);
579         if ((access( pname, F_OK)) != 0) {
580             if (errno != ENOENT) {
581                 dbd_log(LOGSTD, "Access error for file '%s/%s': %s",
582                         cwdbuf, pname, strerror(errno));
583                 continue;
584             }
585             /* Orphaned ad-file*/
586             dbd_log(LOGSTD, "Orphaned AppleDoube file '%s/%s/%s'",
587                     cwdbuf, ADv2_DIRNAME, ep->d_name);
588
589             if (dbd_flags & DBD_FLAGS_SCAN)
590                 /* Scan only requested, dont change anything */
591                 continue;;
592
593             if ((unlink(ep->d_name)) != 0) {
594                 dbd_log(LOGSTD, "Error unlinking orphaned AppleDoube file '%s/%s/%s'",
595                         cwdbuf, ADv2_DIRNAME, ep->d_name);
596
597             }
598         }
599     }
600
601     if ((chdir("..")) != 0) {
602         dbd_log(LOGSTD, "Couldn't chdir back to '%s' from AppleDouble dir: %s",
603                 cwdbuf, strerror(errno));
604         /* This really is EOT! */
605         longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
606     }
607
608     closedir(dp);
609
610     return 0;
611 }
612
613 /*
614   Check CNID for a file/dir, both from db and from ad-file.
615   For detailed specs see intro.
616
617   @return Correct CNID of object or CNID_INVALID (ie 0) on error
618 */
619 static cnid_t check_cnid(const char *name, cnid_t did, struct stat *st, int adfile_ok)
620 {
621     int ret, adflags = ADFLAGS_HF;
622     cnid_t db_cnid, ad_cnid;
623     struct adouble ad;
624
625     adflags = ADFLAGS_HF | (S_ISDIR(st->st_mode) ? ADFLAGS_DIR : 0);
626
627     /* Force checkout every X items */
628     static int cnidcount = 0;
629     cnidcount++;
630     if (cnidcount > 10000) {
631         cnidcount = 0;
632         if (dbif_txn_checkpoint(dbd, 0, 0, 0) < 0) {
633             dbd_log(LOGSTD, "Error checkpointing!");
634             return CNID_INVALID;
635         }
636     }
637
638     /* Get CNID from ad-file */
639     ad_cnid = 0;
640     if (ADFILE_OK) {
641         ad_init(&ad, myvol);
642         if (ad_open(&ad, name, adflags | ADFLAGS_RDWR) != 0) {
643             
644             if (dbd_flags & DBD_FLAGS_CLEANUP)
645                 return CNID_INVALID;
646
647             if (myvol->v_adouble != AD_VERSION_EA) {
648                 dbd_log( LOGSTD, "Error opening AppleDouble file for '%s/%s': %s", cwdbuf, name, strerror(errno));
649                 return CNID_INVALID;
650             }
651             dbd_log( LOGDEBUG, "File without meta EA: \"%s/%s\"", cwdbuf, name);
652             adfile_ok = 1;
653         } else {
654
655             if (dbd_flags & DBD_FLAGS_FORCE) {
656                 ad_cnid = ad_forcegetid(&ad);
657                 /* This ensures the changed stamp is written */
658                 ad_setid( &ad, st->st_dev, st->st_ino, ad_cnid, did, stamp);
659                 ad_flush(&ad);
660             } else
661                 ad_cnid = ad_getid(&ad, st->st_dev, st->st_ino, 0, stamp);
662
663             if (ad_cnid == 0)
664                 dbd_log( LOGSTD, "Bad CNID in adouble file of '%s/%s'", cwdbuf, name);
665             else
666                 dbd_log( LOGDEBUG, "CNID from .AppleDouble file for '%s/%s': %u", cwdbuf, name, ntohl(ad_cnid));
667             ad_close(&ad, ADFLAGS_HF);
668         }
669     }
670
671     /* Get CNID from database */
672
673     /* Prepare request data */
674     memset(&rqst, 0, sizeof(struct cnid_dbd_rqst));
675     memset(&rply, 0, sizeof(struct cnid_dbd_rply));
676     rqst.did = did;
677     rqst.cnid = ad_cnid;
678     if ( ! (myvol->v_flags & AFPVOL_NODEV))
679         rqst.dev = st->st_dev;
680     rqst.ino = st->st_ino;
681     rqst.type = S_ISDIR(st->st_mode)?1:0;
682     rqst.name = (char *)name;
683     rqst.namelen = strlen(name);
684
685     /* Query the database */
686     ret = dbd_lookup(dbd, &rqst, &rply, (dbd_flags & DBD_FLAGS_SCAN) ? 1 : 0);
687     if (dbif_txn_close(dbd, ret) != 0)
688         return CNID_INVALID;
689     if (rply.result == CNID_DBD_RES_OK) {
690         db_cnid = rply.cnid;
691     } else if (rply.result == CNID_DBD_RES_NOTFOUND) {
692         if ( ! (dbd_flags & DBD_FLAGS_FORCE))
693             dbd_log( LOGSTD, "No CNID for '%s/%s' in database", cwdbuf, name);
694         db_cnid = 0;
695     } else {
696         dbd_log( LOGSTD, "Fatal error resolving '%s/%s'", cwdbuf, name);
697         db_cnid = 0;
698     }
699
700     /* Compare results from both CNID searches */
701     if (ad_cnid && db_cnid && (ad_cnid == db_cnid)) {
702         /* Everything is fine */
703         return db_cnid;
704     } else if (ad_cnid && db_cnid && (ad_cnid != db_cnid)) {
705         /* Mismatch, overwrite ad file with value from db */
706         dbd_log( LOGSTD, "CNID mismatch for '%s/%s', db: %u, ad-file: %u", cwdbuf, name, ntohl(db_cnid), ntohl(ad_cnid));
707         if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
708             dbd_log(LOGSTD, "Updating AppleDouble file for '%s/%s' with CNID: %u from database",
709                             cwdbuf, name, ntohl(db_cnid));
710             ad_init(&ad, myvol);
711             if (ad_open(&ad, name, adflags | ADFLAGS_HF | ADFLAGS_RDWR) != 0) {
712                 dbd_log(LOGSTD, "Error opening AppleDouble file for '%s/%s': %s",
713                         cwdbuf, name, strerror(errno));
714                 return CNID_INVALID;
715             }
716             ad_setid( &ad, st->st_dev, st->st_ino, db_cnid, did, stamp);
717             ad_flush(&ad);
718             ad_close(&ad, ADFLAGS_HF);
719         }
720         return db_cnid;
721     } else if (ad_cnid && (db_cnid == 0)) {
722         /* in ad-file but not in db */
723         if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
724             /* Ensure the cnid from the ad-file is not already occupied by another file */
725             dbd_log(LOGDEBUG, "Checking whether CNID %u from ad-file is occupied",
726                     ntohl(ad_cnid));
727
728             rqst.cnid = ad_cnid;
729             ret = dbd_resolve(dbd, &rqst, &rply);
730             if (rply.result == CNID_DBD_RES_OK) {
731                 /* Occupied! Choose another, update ad-file */
732                 ret = dbd_add(dbd, &rqst, &rply, 1);
733                 if (dbif_txn_close(dbd, ret) != 0)
734                     return CNID_INVALID;
735                 db_cnid = rply.cnid;
736                 dbd_log(LOGSTD, "New CNID for '%s/%s': %u", cwdbuf, name, ntohl(db_cnid));
737
738                 if (ADFILE_OK && ( ! (dbd_flags & DBD_FLAGS_SCAN))) {
739                     dbd_log(LOGSTD, "Writing CNID data for '%s/%s' to AppleDouble file",
740                             cwdbuf, name, ntohl(db_cnid));
741                     ad_init(&ad, myvol);
742                     if (ad_open(&ad, name, adflags | ADFLAGS_RDWR) != 0) {
743                         dbd_log(LOGSTD, "Error opening AppleDouble file for '%s/%s': %s",
744                                 cwdbuf, name, strerror(errno));
745                         return CNID_INVALID;
746                     }
747                     ad_setid( &ad, st->st_dev, st->st_ino, db_cnid, did, stamp);
748                     ad_flush(&ad);
749                     ad_close(&ad, ADFLAGS_HF);
750                 }
751                 return db_cnid;
752             }
753
754             dbd_log(LOGDEBUG, "CNID rebuild add '%s/%s' with CNID from ad-file %u",
755                     cwdbuf, name, ntohl(ad_cnid));
756             rqst.cnid = ad_cnid;
757             ret = dbd_rebuild_add(dbd, &rqst, &rply);
758             if (dbif_txn_close(dbd, ret) != 0)
759                 return CNID_INVALID;
760         }
761         return ad_cnid;
762     } else if ((db_cnid == 0) && (ad_cnid == 0)) {
763         /* No CNID at all, we clearly have to allocate a fresh one... */
764         /* Note: the next test will use this new CNID too! */
765         if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
766             /* add to db */
767             ret = dbd_add(dbd, &rqst, &rply, 1);
768             if (dbif_txn_close(dbd, ret) != 0)
769                 return CNID_INVALID;
770             db_cnid = rply.cnid;
771             dbd_log(LOGSTD, "New CNID for '%s/%s': %u", cwdbuf, name, ntohl(db_cnid));
772         }
773     }
774
775     if ((ad_cnid == 0) && db_cnid) {
776         /* in db but zeroID in ad-file, write it to ad-file */
777         if (ADFILE_OK && ! (dbd_flags & DBD_FLAGS_SCAN)) {            
778             dbd_log(LOGSTD, "Writing CNID data for '%s/%s' to AppleDouble file",
779                     cwdbuf, name, ntohl(db_cnid));
780             ad_init(&ad, myvol);
781             if (ad_open(&ad, name, adflags | ADFLAGS_RDWR) != 0) {
782                 dbd_log(LOGSTD, "Error opening AppleDouble file for '%s/%s': %s",
783                         cwdbuf, name, strerror(errno));
784                 return CNID_INVALID;
785             }
786             ad_setid( &ad, st->st_dev, st->st_ino, db_cnid, did, stamp);
787             ad_flush(&ad);
788             ad_close(&ad, ADFLAGS_HF);
789         }
790         return db_cnid;
791     }
792
793     return CNID_INVALID;
794 }
795
796 /*
797   This is called recursively for all dirs.
798   volroot=1 means we're in the volume root dir, 0 means we aren't.
799   We use this when checking for netatalk private folders like .AppleDB.
800   did is our parents CNID.
801 */
802 static int dbd_readdir(int volroot, cnid_t did)
803 {
804     int cwd, ret = 0, adfile_ok, addir_ok, encoding_ok;
805     cnid_t cnid = 0;
806     const char *name;
807     DIR *dp;
808     struct dirent *ep;
809     static struct stat st;      /* Save some stack space */
810
811     /* Check again for .AppleDouble folder, check_adfile also checks/creates it */
812     if ((addir_ok = check_addir(volroot)) != 0)
813         if ( ! (dbd_flags & DBD_FLAGS_SCAN))
814             /* Fatal on rebuild run, continue if only scanning ! */
815             return -1;
816
817     /* Check AppleDouble files in AppleDouble folder, but only if it exists or could be created */
818     if (ADDIR_OK)
819         if ((read_addir()) != 0)
820             if ( ! (dbd_flags & DBD_FLAGS_SCAN))
821                 /* Fatal on rebuild run, continue if only scanning ! */
822                 return -1;
823
824     if ((dp = opendir (".")) == NULL) {
825         dbd_log(LOGSTD, "Couldn't open the directory: %s",strerror(errno));
826         return -1;
827     }
828
829     while ((ep = readdir (dp))) {
830         /* Check if we got a termination signal */
831         if (alarmed)
832             longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
833
834         /* Check if its "." or ".." */
835         if (DIR_DOT_OR_DOTDOT(ep->d_name))
836             continue;
837
838         /* Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop" */
839         if ((name = check_netatalk_dirs(ep->d_name)) != NULL) {
840             if (! volroot)
841                 dbd_log(LOGSTD, "Nested %s in %s", name, cwdbuf);
842             continue;
843         }
844
845         /* Check for special folders in volume root e.g. ".zfs" */
846         if (volroot) {
847             if ((name = check_special_dirs(ep->d_name)) != NULL) {
848                 dbd_log(LOGSTD, "Ignoring special dir \"%s\"", name);
849                 continue;
850             }
851         }
852
853         /* Skip .AppleDouble dir in this loop */
854         if (STRCMP(ep->d_name, == , ADv2_DIRNAME))
855             continue;
856
857         if ((ret = lstat(ep->d_name, &st)) < 0) {
858             dbd_log( LOGSTD, "Lost file while reading dir '%s/%s', probably removed: %s",
859                      cwdbuf, ep->d_name, strerror(errno));
860             continue;
861         }
862         
863         switch (st.st_mode & S_IFMT) {
864         case S_IFREG:
865         case S_IFDIR:
866             break;
867         case S_IFLNK:
868             dbd_log(LOGDEBUG, "Ignoring symlink %s/%s", cwdbuf, ep->d_name);
869             continue;
870         default:
871             dbd_log(LOGSTD, "Bad filetype: %s/%s", cwdbuf, ep->d_name);
872             if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
873                 if ((unlink(ep->d_name)) != 0) {
874                     dbd_log(LOGSTD, "Error removing: %s/%s: %s", cwdbuf, ep->d_name, strerror(errno));
875                 }
876             }
877             continue;
878         }
879
880         /**************************************************************************
881            Statistics
882          **************************************************************************/
883         static unsigned long long statcount = 0;
884         static time_t t = 0;
885
886         if (t == 0)
887             t = time(NULL);
888
889         statcount++;
890         if ((statcount % 10000) == 0) {
891             if (dbd_flags & DBD_FLAGS_STATS)            
892                 dbd_log(LOGSTD, "Scanned: %10llu, time: %10llu s",
893                         statcount, (unsigned long long)(time(NULL) - t));
894         }
895
896         /**************************************************************************
897            Tests
898         **************************************************************************/
899
900         /* Check encoding */
901         if ( -1 == (encoding_ok = check_name_encoding(ep->d_name)) ) {
902             /* If its a file: skipp all other tests now ! */
903             /* For dirs we could try to get a CNID for it and recurse, but currently I prefer not to */
904             continue;
905         }
906
907         /* Check for appledouble file, create if missing, but only if we have addir */
908         adfile_ok = -1;
909         if (ADDIR_OK)
910             adfile_ok = check_adfile(ep->d_name, &st);
911
912         if ( ! nocniddb) {
913             /* Check CNIDs */
914             cnid = check_cnid(ep->d_name, did, &st, adfile_ok);
915
916             /* Now add this object to our rebuild dbd */
917             if (cnid && dbd_rebuild) {
918                 static uint count = 0;
919                 rqst.cnid = rply.cnid;
920                 ret = dbd_rebuild_add(dbd_rebuild, &rqst, &rply);
921                 if (dbif_txn_close(dbd_rebuild, ret) != 0)
922                     return -1;
923                 if (rply.result != CNID_DBD_RES_OK) {
924                     dbd_log( LOGSTD, "Fatal error adding CNID: %u for '%s/%s' to in-memory rebuild-db",
925                              cnid, cwdbuf, ep->d_name);
926                     return -1;
927                 }
928                 count++;
929                 if (count == 10000) {
930                     if (dbif_txn_checkpoint(dbd_rebuild, 0, 0, 0) < 0) {
931                         dbd_log(LOGSTD, "Error checkpointing!");
932                         return -1;
933                     }
934                     count = 0;
935                 }
936             }
937         }
938
939         /* Check EA files */
940         if (myvol->v_vfs_ea == AFPVOL_EA_AD)
941             check_eafiles(ep->d_name);
942
943         /**************************************************************************
944           Recursion
945         **************************************************************************/
946         if (S_ISDIR(st.st_mode) && (cnid || nocniddb)) { /* If we have no cnid for it we cant recur */
947             strcat(cwdbuf, "/");
948             strcat(cwdbuf, ep->d_name);
949             dbd_log( LOGDEBUG, "Entering directory: %s", cwdbuf);
950             if (-1 == (cwd = open(".", O_RDONLY))) {
951                 dbd_log( LOGSTD, "Cant open directory '%s': %s", cwdbuf, strerror(errno));
952                 continue;
953             }
954             if (0 != chdir(ep->d_name)) {
955                 dbd_log( LOGSTD, "Cant chdir to directory '%s': %s", cwdbuf, strerror(errno));
956                 close(cwd);
957                 continue;
958             }
959
960             ret = dbd_readdir(0, cnid);
961
962             fchdir(cwd);
963             close(cwd);
964             *(strrchr(cwdbuf, '/')) = 0;
965             if (ret < 0)
966                 return -1;
967         }
968     }
969
970     /*
971       Use results of previous checks
972     */
973     if ((myvol->v_adouble == AD_VERSION_EA) && (dbd_flags & DBD_FLAGS_V2TOEA)) {
974         if (rmdir(ADv2_DIRNAME) != 0) {
975             switch (errno) {
976             case ENOENT:
977                 break;
978             default:
979                 dbd_log(LOGSTD, "Error removing adouble dir \"%s/%s\": %s", cwdbuf, ADv2_DIRNAME, strerror(errno));
980                 break;
981             }
982         }
983     }
984     closedir(dp);
985     return ret;
986 }
987
988 static int scanvol(struct vol *vol, dbd_flags_t flags)
989 {
990     struct stat st;
991
992     /* Make this stuff accessible from all funcs easily */
993     myvol = vol;
994     dbd_flags = flags;
995
996     /* Run with umask 0 */
997     umask(0);
998
999     strcpy(cwdbuf, myvol->v_path);
1000     chdir(myvol->v_path);
1001
1002     if ((myvol->v_adouble == AD_VERSION_EA) && (dbd_flags & DBD_FLAGS_V2TOEA)) {
1003         if (lstat(".", &st) != 0)
1004             return -1;
1005         if (ad_convert(".", &st, vol) != 0) {
1006             switch (errno) {
1007             case ENOENT:
1008                 break;
1009             default:
1010                 dbd_log(LOGSTD, "Conversion error for \"%s\": %s", myvol->v_path, strerror(errno));
1011                 break;
1012             }
1013         }
1014     }
1015
1016     /* Start recursion */
1017     if (dbd_readdir(1, htonl(2)) < 0)  /* 2 = volumeroot CNID */
1018         return -1;
1019
1020     return 0;
1021 }
1022
1023 /*
1024   Remove all CNIDs from dbd that are not in dbd_rebuild
1025 */
1026 static void delete_orphaned_cnids(DBD *dbd, DBD *dbd_rebuild, dbd_flags_t flags)
1027 {
1028     int ret = 0, deleted = 0;
1029     cnid_t dbd_cnid = 0, rebuild_cnid = 0;
1030     struct cnid_dbd_rqst rqst;
1031     struct cnid_dbd_rply rply;
1032
1033     /* jump over rootinfo key */
1034     if ( dbif_idwalk(dbd, &dbd_cnid, 0) != 1)
1035         return;
1036     if ( dbif_idwalk(dbd_rebuild, &rebuild_cnid, 0) != 1)
1037         return;
1038
1039     /* Get first id from dbd_rebuild */
1040     if ((dbif_idwalk(dbd_rebuild, &rebuild_cnid, 0)) == -1)
1041         return;
1042
1043     /* Start main loop through dbd: get CNID from dbd */
1044     while ((dbif_idwalk(dbd, &dbd_cnid, 0)) == 1) {
1045         /* Check if we got a termination signal */
1046         if (alarmed)
1047             longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
1048
1049         if (deleted > 1000) {
1050             deleted = 0;
1051             if (dbif_txn_checkpoint(dbd, 0, 0, 0) < 0) {
1052                 dbd_log(LOGSTD, "Error checkpointing!");
1053                 goto cleanup;
1054             }
1055         }
1056
1057         /* This should be the normal case: CNID is in both dbs */
1058         if (dbd_cnid == rebuild_cnid) {
1059             /* Get next CNID from rebuild db */
1060             if ((ret = dbif_idwalk(dbd_rebuild, &rebuild_cnid, 0)) == -1) {
1061                 /* Some error */
1062                 goto cleanup;
1063             } else if (ret == 0) {
1064                 /* end of rebuild_cnid, delete all remaining CNIDs from dbd */
1065                 while ((dbif_idwalk(dbd, &dbd_cnid, 0)) == 1) {
1066                     dbd_log(LOGSTD, "Orphaned CNID in database: %u", dbd_cnid);
1067                     if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
1068                         rqst.cnid = htonl(dbd_cnid);
1069                         if ((ret = dbd_delete(dbd, &rqst, &rply, DBIF_CNID)) == -1) {
1070                             dbd_log(LOGSTD, "Error deleting CNID %u", dbd_cnid);
1071                             (void)dbif_txn_abort(dbd);
1072                             goto cleanup;
1073                         }
1074                         
1075                         if (dbif_txn_close(dbd, ret) != 0)
1076                             return;
1077                         deleted++;
1078                     }
1079                     /* Check if we got a termination signal */
1080                     if (alarmed)
1081                         longjmp(jmp, 1); /* this jumps back to cmd_dbd_scanvol() */
1082                 }
1083                 return;
1084             } else
1085                 /* Normal case (ret=1): continue while loop */
1086                 continue;
1087         }
1088
1089         if (dbd_cnid < rebuild_cnid) {
1090             /* CNID is orphaned -> delete */
1091             dbd_log(LOGSTD, "One orphaned CNID in database: %u.", dbd_cnid);
1092             if ( ! (dbd_flags & DBD_FLAGS_SCAN)) {
1093                 rqst.cnid = htonl(dbd_cnid);
1094                 if ((ret = dbd_delete(dbd, &rqst, &rply, DBIF_CNID)) == -1) {
1095                     dbd_log(LOGSTD, "Error deleting CNID %u", dbd_cnid);
1096                     (void)dbif_txn_abort(dbd);
1097                     goto cleanup;
1098                 }
1099                 if (dbif_txn_close(dbd, ret) != 0)
1100                     return;
1101                 deleted++;
1102             }
1103             continue;
1104         }
1105
1106         if (dbd_cnid > rebuild_cnid) {
1107             dbif_idwalk(dbd, NULL, 1); /* Close cursor */
1108             dbif_idwalk(dbd_rebuild, NULL, 1); /* Close cursor */
1109             (void)dbif_txn_close(dbd, 2);
1110             (void)dbif_txn_close(dbd_rebuild, 2);                
1111             dbd_log(LOGSTD, "Ghost CNID: %u. This is fatal! Dumping rebuild db:\n", rebuild_cnid);
1112             dbif_dump(dbd_rebuild, 0);
1113             dbd_log(LOGSTD, "Send this dump and a `dbd -d ...` dump to the Netatalk Dev team!");
1114             goto cleanup;
1115         }
1116     } /* while ((dbif_idwalk(dbd, &dbd_cnid, 0)) == 1) */
1117
1118 cleanup:
1119     dbif_idwalk(dbd, NULL, 1); /* Close cursor */
1120     dbif_idwalk(dbd_rebuild, NULL, 1); /* Close cursor */
1121     return;
1122 }
1123
1124 static const char *get_tmpdb_path(void)
1125 {
1126     pid_t pid = getpid();
1127     static char path[MAXPATHLEN];
1128     snprintf(path, MAXPATHLEN, "/tmp/tmpdb-dbd.%u", pid);
1129     if (mkdir(path, 0755) != 0)
1130         return NULL;
1131     return path;
1132 }
1133
1134 /*
1135   Main func called from cmd_dbd.c
1136 */
1137 int cmd_dbd_scanvol(DBD *dbd_ref, struct vol *vol, dbd_flags_t flags)
1138 {
1139     int ret = 0;
1140     struct db_param db_param = { 0 };
1141     const char *tmpdb_path = NULL;
1142
1143     /* Set cachesize for in-memory rebuild db */
1144     db_param.cachesize = 64 * 1024;         /* 64 MB */
1145     db_param.maxlocks = DEFAULT_MAXLOCKS;
1146     db_param.maxlockobjs = DEFAULT_MAXLOCKOBJS;
1147     db_param.logfile_autoremove = 1;
1148
1149     /* Make it accessible for all funcs */
1150     dbd = dbd_ref;
1151
1152     /* We only support unicode volumes ! */
1153     if (vol->v_volcharset != CH_UTF8) {
1154         dbd_log( LOGSTD, "Not a Unicode volume: %s, %u != %u", vol->v_volcodepage, vol->v_volcharset, CH_UTF8);
1155         return -1;
1156     }
1157
1158     /* Get volume stamp */
1159     dbd_getstamp(dbd, &rqst, &rply);
1160     if (rply.result != CNID_DBD_RES_OK) {
1161         ret = -1;
1162         goto exit;
1163     }
1164     memcpy(stamp, rply.name, CNID_DEV_LEN);
1165
1166     /* temporary rebuild db, used with -re rebuild to delete unused CNIDs, not used with -f */
1167     if (! nocniddb && (flags & DBD_FLAGS_EXCL) && !(flags & DBD_FLAGS_FORCE)) {
1168         tmpdb_path = get_tmpdb_path();
1169         if (NULL == (dbd_rebuild = dbif_init(tmpdb_path, "cnid2.db"))) {
1170             ret = -1;
1171             goto exit;
1172         }
1173
1174         if (dbif_env_open(dbd_rebuild,
1175                           &db_param,
1176                           DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN) < 0) {
1177             dbd_log(LOGSTD, "error opening tmp database!");
1178             goto exit;
1179         }
1180
1181         if (0 != (dbif_open(dbd_rebuild, NULL, 0))) {
1182             ret = -1;
1183             goto exit;
1184         }
1185
1186         if (0 != (dbif_copy_rootinfokey(dbd, dbd_rebuild))) {
1187             ret = -1;
1188             goto exit;
1189         }
1190     }
1191
1192     if (setjmp(jmp) != 0) {
1193         ret = 0;                /* Got signal, jump from dbd_readdir */
1194         goto exit;
1195     }
1196
1197     /* scanvol */
1198     if ((scanvol(vol, flags)) != 0) {
1199         ret = -1;
1200         goto exit;
1201     }
1202
1203 exit:
1204     if (! nocniddb) {
1205         if (dbif_txn_close(dbd, ret == 0 ? 1 : 0) != 0)
1206             ret = -1;
1207         if (dbd_rebuild)
1208             if (dbif_txn_close(dbd_rebuild, ret == 0 ? 1 : 0) != 0)
1209                 ret = -1;
1210         if ((ret == 0) && dbd_rebuild && (flags & DBD_FLAGS_EXCL) && !(flags & DBD_FLAGS_FORCE))
1211             /* We can only do this in exclusive mode, otherwise we might delete CNIDs added from
1212                other clients in between our pass 1 and 2 */
1213             delete_orphaned_cnids(dbd, dbd_rebuild, flags);
1214     }
1215
1216     if (dbd_rebuild) {
1217         dbd_log(LOGDEBUG, "Closing tmp db");
1218         dbif_close(dbd_rebuild);
1219
1220         if (tmpdb_path) {
1221             char cmd[8 + MAXPATHLEN];
1222             snprintf(cmd, 8 + MAXPATHLEN, "rm -f %s/*", tmpdb_path);
1223             dbd_log( LOGDEBUG, "Removing temp database '%s'", tmpdb_path);
1224             system(cmd);
1225             snprintf(cmd, 8 + MAXPATHLEN, "rmdir %s", tmpdb_path);
1226             system(cmd);
1227         }        
1228     }
1229     return ret;
1230 }