]> arthur.barton.de Git - netatalk.git/blob - libatalk/cnid/cnid_open.c
Implement a round of CNID DB fixes per suggestions by
[netatalk.git] / libatalk / cnid / cnid_open.c
1 /*
2  * $Id: cnid_open.c,v 1.31 2002-01-17 16:19:07 jmarcus Exp $
3  *
4  * Copyright (c) 1999. Adrian Sun (asun@zoology.washington.edu)
5  * All Rights Reserved. See COPYRIGHT.
6  *
7  * CNID database support. 
8  *
9  * here's the deal:
10  *  1) afpd already caches did's. 
11  *  2) the database stores cnid's as both did/name and dev/ino pairs. 
12  *  3) RootInfo holds the value of the NextID.
13  *  4) the cnid database gets called in the following manner --
14  *     start a database:
15  *     cnid = cnid_open(root_dir);
16  *
17  *     allocate a new id: 
18  *     newid = cnid_add(cnid, dev, ino, parent did,
19  *     name, id); id is a hint for a specific id. pass 0 if you don't
20  *     care. if the id is already assigned, you won't get what you
21  *     requested.
22  *
23  *     given an id, get a did/name and dev/ino pair.
24  *     name = cnid_get(cnid, &id); given an id, return the corresponding
25  *     info.
26  *     return code = cnid_delete(cnid, id); delete an entry. 
27  *
28  * with AFP, CNIDs 0-2 have special meanings. here they are:
29  * 0 -- invalid cnid
30  * 1 -- parent of root directory (handled by afpd) 
31  * 2 -- root directory (handled by afpd)
32  *
33  * so, CNID_START begins at 3.
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif /* HAVE_CONFIG_H */
39
40 #ifdef CNID_DB
41 #include <errno.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif /* HAVE_UNISTD_H */
47 #ifdef HAVE_FCNTL_H
48 #include <fcntl.h>
49 #endif /* HAVE_FCNTL_H */
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <atalk/logger.h>
53 #ifdef HAVE_SYS_TIME_H
54 #include <sys/time.h>
55 #endif /* HAVE_SYS_TIME_H */
56
57 #include <db.h>
58
59 #include <atalk/adouble.h>
60 #include <atalk/cnid.h>
61 #include <atalk/util.h>
62
63 #include "cnid_private.h"
64
65 #ifndef MIN
66 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
67 #endif /* ! MIN */
68
69 #define DBHOME        ".AppleDB"
70 #define DBCNID        "cnid.db"
71 #define DBDEVINO      "devino.db"
72 #define DBDIDNAME     "didname.db"   /* did/full name mapping */
73 #define DBSHORTNAME   "shortname.db" /* did/8+3 mapping */
74 #define DBMACNAME     "macname.db"   /* did/31 mapping */
75 #define DBLONGNAME    "longname.db"  /* did/unicode mapping */
76 #define DBLOCKFILE    "cnid.lock"
77 #define DBRECOVERFILE "cnid.dbrecover"
78 #define DBCLOSEFILE   "cnid.close"
79
80 #define DBHOMELEN    8
81 #define DBLEN        10
82
83 /* we version the did/name database so that we can change the format
84  * if necessary. the key is in the form of a did/name pair. in this case,
85  * we use 0/0. */
86 #define DBVERSION_KEY    "\0\0\0\0\0"
87 #define DBVERSION_KEYLEN 5
88 #define DBVERSION1       0x00000001U
89 #define DBVERSION        DBVERSION1
90
91 #if DB_VERSION_MINOR > 1
92 #define DBOPTIONS    (DB_CREATE | DB_INIT_MPOOL | DB_INIT_LOCK | \
93 DB_INIT_LOG | DB_INIT_TXN)
94 #else /* DB_VERSION_MINOR < 1 */
95 #define DBOPTIONS    (DB_CREATE | DB_INIT_MPOOL | DB_INIT_LOCK | \
96 DB_INIT_LOG | DB_INIT_TXN | DB_TXN_NOSYNC)
97 /*#define DBOPTIONS    (DB_CREATE | DB_INIT_MPOOL | DB_INIT_LOCK | \
98 DB_INIT_LOG | DB_INIT_TXN)*/
99 #endif /* DB_VERSION_MINOR */
100
101 /* Let's try and use the youngest lock detector if present.
102  * If we can't do that, then let DB3 use its default deadlock detector. */
103 #if defined DB_LOCK_YOUNGEST
104 #define DEAD_LOCK_DETECT DB_LOCK_YOUNGEST
105 #else /* DB_LOCK_YOUNGEST */
106 #define DEAD_LOCK_DETECT DB_LOCK_DEFAULT
107 #endif /* DB_LOCK_YOUNGEST */
108
109 #define MAXITER     0xFFFF /* maximum number of simultaneously open CNID
110 * databases. */
111
112 /* the first compare that's always done. */
113 static __inline__ int compare_did(const DBT *a, const DBT *b)
114 {
115     u_int32_t dida, didb;
116
117     memcpy(&dida, a->data, sizeof(dida));
118     memcpy(&didb, b->data, sizeof(didb));
119     return dida - didb;
120 }
121
122 /* sort did's and then names. this is for unix paths.
123  * i.e., did/unixname lookups. */
124 #if DB_VERSION_MINOR > 1
125 static int compare_unix(DB *db, const DBT *a, const DBT *b)
126 #else /* DB_VERSION_MINOR < 1 */
127 static int compare_unix(const DBT *a, const DBT *b)
128 #endif /* DB_VERSION_MINOR */
129 {
130     u_int8_t *sa, *sb;
131     int len, ret;
132
133     /* sort by did */
134     if ((ret = compare_did(a, b)))
135         return ret;
136
137     sa = (u_int8_t *) a->data + 4; /* shift past did */
138     sb = (u_int8_t *) b->data + 4;
139     for (len = MIN(a->size, b->size); len-- > 4; sa++, sb++)
140         if ((ret = (*sa - *sb)))
141             return ret; /* sort by lexical ordering */
142
143     return a->size - b->size; /* sort by length */
144 }
145
146 /* sort did's and then names. this is for macified paths (i.e.,
147  * did/macname, and did/shortname. i think did/longname needs a
148  * unicode table to work. also, we can't use strdiacasecmp as that
149  * returns a match if a < b. */
150 #if DB_VERSION_MINOR > 1
151 static int compare_mac(DB *db, const DBT *a, const DBT *b)
152 #else /* DB_VERSION_MINOR < 1 */
153 static int compare_mac(const DBT *a, const DBT *b)
154 #endif /* DB_VERSION_MINOR */
155 {
156     u_int8_t *sa, *sb;
157     int len, ret;
158
159     /* sort by did */
160     if ((ret = compare_did(a, b)))
161         return ret;
162
163     sa = (u_int8_t *) a->data + 4;
164     sb = (u_int8_t *) b->data + 4;
165     for (len = MIN(a->size, b->size); len-- > 4; sa++, sb++)
166         if ((ret = (_diacasemap[*sa] - _diacasemap[*sb])))
167             return ret; /* sort by lexical ordering */
168
169     return a->size - b->size; /* sort by length */
170 }
171
172
173 /* for unicode names -- right now it's the same as compare_mac. */
174 #if DB_VERSION_MINOR > 1
175 static int compare_unicode(DB *db, const DBT *a, const DBT *b)
176 #else /* DB_VERSION_MINOR < 1 */
177 static int compare_unicode(const DBT *a, const DBT *b)
178 #endif /* DB_VERSION_MINOR */
179 {
180 #if DB_VERSION_MINOR > 1
181     return compare_mac(db,a,b);
182 #else /* DB_VERSION_MINOR < 1 */
183     return compare_mac(a,b);
184 #endif /* DB_VERSION_MINOR */
185 }
186
187 static int have_lock = 0;
188
189 void *cnid_open(const char *dir) {
190     struct stat st, rsb, csb;
191     struct flock lock;
192     char path[MAXPATHLEN + 1];
193     char recover_file[MAXPATHLEN + 1];
194     CNID_private *db;
195     DBT key, data;
196     DB_TXN *tid;
197     u_int32_t DBEXTRAS = 0;
198     int open_flag, len;
199     int rc, rfd = -1;
200
201     if (!dir) {
202         return NULL;
203     }
204
205     /* this checks .AppleDB */
206     if ((len = strlen(dir)) > (MAXPATHLEN - DBLEN - 1)) {
207         LOG(log_error, logtype_default, "cnid_open: Pathname too large: %s", dir);
208         return NULL;
209     }
210
211     if ((db = (CNID_private *)calloc(1, sizeof(CNID_private))) == NULL) {
212         LOG(log_error, logtype_default, "cnid_open: Unable to allocate memory for database");
213         return NULL;
214     }
215
216     db->magic = CNID_DB_MAGIC;
217
218     strcpy(path, dir);
219     if (path[len - 1] != '/') {
220         strcat(path, "/");
221         len++;
222     }
223
224     lock.l_type = F_WRLCK;
225     lock.l_whence = SEEK_SET;
226
227     strcpy(path + len, DBHOME);
228     if ((stat(path, &st) < 0) && (ad_mkdir(path, 0777) < 0)) {
229         LOG(log_error, logtype_default, "cnid_open: DBHOME mkdir failed for %s", path);
230         goto fail_adouble;
231     }
232
233     /* Make sure cnid.lock goes in .AppleDB. */
234     strcat(path, "/");
235     len++;
236
237     strcpy(db->close_file, path);
238     strcat(db->close_file, DBCLOSEFILE);
239
240     /* Check to make sure that a client isn't in the process of closing
241      * the database environment.  To do this, select on the close file. */
242     while(stat(db->close_file, &csb) == 0) {
243         struct timeval ct;
244         ct.tv_sec = 1;
245         ct.tv_usec = 0;
246         (void)select(0, NULL, NULL, NULL, &ct);
247     }
248
249     strcpy(recover_file, path);
250     strcat(recover_file, DBRECOVERFILE);
251
252     /* Search for a byte lock.  This allows us to cleanup the log files
253      * at cnid_close() in a clean fashion.
254      *
255      * NOTE: This won't work if multiple volumes for the same user refer
256      * to the sahe directory. */
257     strcat(path, DBLOCKFILE);
258     if ((db->lockfd = open(path, O_RDWR | O_CREAT, 0666)) > -1) {
259         lock.l_start = 0;
260         lock.l_len = 1;
261         while (fcntl(db->lockfd, F_SETLK, &lock) < 0) {
262             if (++lock.l_start > MAXITER) {
263                 LOG(log_error, logtype_default, "cnid_open: Cannot establish logfile cleanup for database environment %s lock (lock failed)", path);
264                 close(db->lockfd);
265                 db->lockfd = -1;
266                 break;
267             }
268         }
269     }
270     else {
271         LOG(log_error, logtype_default, "cnid_open: Cannot establish logfile cleanup lock for database environment %s (open() failed)", path);
272     }
273
274     /* Create a file to represent database recovery.  While this file
275      * exists, the database is being recovered, and all other clients will
276      * select until recovery is complete, and this file goes away. */
277     if (!have_lock && db->lockfd > -1 && lock.l_start == 0) {
278         if (stat(recover_file, &rsb) == 0) {
279             (void)remove(recover_file);
280         }
281         if ((rfd = open(recover_file, O_RDWR | O_CREAT, 0666)) > -1) {
282             DBEXTRAS |= DB_RECOVER;
283             have_lock = 1;
284         }
285     }
286     else if (!have_lock) {
287         while (stat(recover_file, &rsb) == 0) {
288             struct timeval rt;
289             rt.tv_sec = 1;
290             rt.tv_usec = 0;
291             (void)select(0, NULL, NULL, NULL, &rt);
292         }
293     }
294
295     path[len + DBHOMELEN] = '\0';
296     open_flag = DB_CREATE;
297
298     /* We need to be able to open the database environment with full
299      * transaction, logging, and locking support if we ever hope to 
300      * be a true multi-acess file server. */
301     if ((rc = db_env_create(&db->dbenv, 0)) != 0) {
302         LOG(log_error, logtype_default, "cnid_open: db_env_create: %s", db_strerror(rc));
303         goto fail_lock;
304     }
305
306     /* Setup internal deadlock detection. */
307     if ((rc = db->dbenv->set_lk_detect(db->dbenv, DEAD_LOCK_DETECT)) != 0) {
308         LOG(log_error, logtype_default, "cnid_open: set_lk_detect: %s", db_strerror(rc));
309         goto fail_lock;
310     }
311
312 #if DB_VERSION_MINOR > 1
313     /* Take care of setting the DB_TXN_NOSYNC flag in db3 > 3.1.x. */
314     if ((rc = db->dbenv->set_flags(db->dbenv, DB_TXN_NOSYNC, 1)) != 0) {
315         LOG(log_error, logtype_default, "cnid_open: set_flags: %s", db_strerror(rc));
316         goto fail_lock;
317     }
318 #endif /* DB_VERSION_MINOR > 1 */
319
320     /* Open the database environment. */
321     if ((rc = db->dbenv->open(db->dbenv, path, DBOPTIONS | DBEXTRAS, 0666)) != 0) {
322         if (rc == DB_RUNRECOVERY) {
323             /* This is the mother of all errors.  We _must_ fail here. */
324             LOG(log_error, logtype_default, "cnid_open: CATASTROPHIC ERROR opening database environment %s.  Run db_recovery -c immediately", path);
325             goto fail_lock;
326         }
327
328         /* We can't get a full transactional environment, so multi-access
329          * is out of the question.  Let's assume a read-only environment,
330          * and try to at least get a shared memory pool. */
331         if ((rc = db->dbenv->open(db->dbenv, path, DB_INIT_MPOOL, 0666)) != 0) {
332             /* Nope, not a MPOOL, either.  Last-ditch effort: we'll try to
333              * open the environment with no flags. */
334             if ((rc = db->dbenv->open(db->dbenv, path, 0, 0666)) != 0) {
335                 LOG(log_error, logtype_default, "cnid_open: dbenv->open of %s failed: %s",
336                     path, db_strerror(rc));
337                 goto fail_lock;
338             }
339         }
340         db->flags |= CNIDFLAG_DB_RO;
341         open_flag = DB_RDONLY;
342         LOG(log_info, logtype_default, "cnid_open: Obtained read-only database environment %s", path);
343     }
344
345     /* If we have the recovery lock, close the file, remove it, so other
346      * clients can proceed opening the DB environment. */
347     if (rfd > -1) {
348         (void)remove(recover_file);
349         switch(errno) {
350         case 0:
351         case ENOENT:
352             break;
353         default:
354             LOG(log_error, logtype_default, "cnid_open: Unable to remove %s: %s",
355                 recover_file, strerror(errno));
356         }
357         close(rfd);
358         rfd = -1;
359     }
360
361     /* did/name reverse mapping.  We use a BTree for this one. */
362     if ((rc = db_create(&db->db_didname, db->dbenv, 0)) != 0) {
363         LOG(log_error, logtype_default, "cnid_open: Failed to create did/name database: %s",
364             db_strerror(rc));
365         goto fail_appinit;
366     }
367
368     db->db_didname->set_bt_compare(db->db_didname, &compare_unix);
369     if ((rc = db->db_didname->open(db->db_didname, DBDIDNAME, NULL,
370                                    DB_BTREE, open_flag, 0666))) {
371         LOG(log_error, logtype_default, "cnid_open: Failed to open did/name database: %s",
372             db_strerror(rc));
373         goto fail_appinit;
374     }
375
376     /* Check for version.  This way we can update the database if we need
377      * to change the format in any way. */
378     memset(&key, 0, sizeof(key));
379     memset(&data, 0, sizeof(data));
380     key.data = DBVERSION_KEY;
381     key.size = DBVERSION_KEYLEN;
382
383 dbversion_retry:
384     if ((rc = txn_begin(db->dbenv, NULL, &tid, 0)) != 0) {
385         LOG(log_error, logtype_default, "cnid_open: txn_begin: failed to check db version: %s",
386             db_strerror(rc));
387         db->db_didname->close(db->db_didname, 0);
388         goto fail_appinit;
389     }
390
391     while ((rc = db->db_didname->get(db->db_didname, tid, &key, &data, DB_RMW))) {
392         int ret;
393         switch (rc) {
394         case DB_LOCK_DEADLOCK:
395             if ((ret = txn_abort(tid)) != 0) {
396                 LOG(log_error, logtype_default, "cnid_open: txn_abort: %s", db_strerror(ret));
397                 db->db_didname->close(db->db_didname, 0);
398                 goto fail_appinit;
399             }
400             goto dbversion_retry;
401         case DB_NOTFOUND:
402             {
403                 u_int32_t version = htonl(DBVERSION);
404
405                 data.data = &version;
406                 data.size = sizeof(version);
407             }
408
409             if ((ret = db->db_didname->put(db->db_didname, tid, &key, &data,
410                                            DB_NOOVERWRITE))) {
411                 if (ret == DB_LOCK_DEADLOCK) {
412                     if ((ret = txn_abort(tid)) != 0) {
413                         LOG(log_error, logtype_default, "cnid_open: txn_abort: %s",
414                             db_strerror(ret));
415                         db->db_didname->close(db->db_didname, 0);
416                         goto fail_appinit;
417                     }
418                     goto dbversion_retry;
419                 }
420                 else if (ret == DB_RUNRECOVERY) {
421                     /* At this point, we don't care if the transaction aborts
422                      * successfully or not. */
423                     txn_abort(tid);
424                     LOG(log_error, logtype_default, "cnid_open: Error putting new version: %s",
425                         db_strerror(ret));
426                     db->db_didname->close(db->db_didname, 0);
427                     goto fail_appinit;
428                 }
429             }
430             break; /* while loop */
431         default:
432             txn_abort(tid);
433             LOG(log_error, logtype_default, "cnid_open: Failed to check db version: %s",
434                 db_strerror(rc));
435             db->db_didname->close(db->db_didname, 0);
436             goto fail_appinit;
437         }
438     }
439
440     if ((rc = txn_commit(tid, 0)) != 0) {
441         LOG(log_error, logtype_default, "cnid_open: Failed to commit db version: %s",
442             db_strerror(rc));
443         db->db_didname->close(db->db_didname, 0);
444         goto fail_appinit;
445     }
446
447     /* TODO In the future we might check for version number here. */
448 #if 0
449     memcpy(&version, data.data, sizeof(version));
450     if (version != ntohl(DBVERSION)) {
451         /* Do stuff here. */
452     }
453 #endif /* 0 */
454
455 #ifdef EXTENDED_DB
456     /* did/macname (31 character) mapping.  Use a BTree for this one. */
457     if ((rc = db_create(&db->db_macname, db->dbenv, 0)) != 0) {
458         LOG(log_error, logtype_default, "cnid_open: Failed to create did/macname database: %s",
459             db_strerror(rc));
460         db->db_didname->close(db->db_didname, 0);
461         goto fail_appinit;
462     }
463
464     db->db_macname->set_bt_compare(db->db_macname, &compare_mac);
465     if ((rc = db->db_macname->open(db->db_macname, DBMACNAME, NULL, DB_BTREE, open_flag, 0666)) != 0) {
466         LOG(log_error, logtype_default, "cnid_open: Failed to open did/macname database: %s",
467             db_strerror(rc));
468         db->db_didname->close(db->db_didname, 0);
469         goto fail_appinit;
470     }
471
472     /* did/shortname (DOS 8.3) mapping.  Use a BTree for this one. */
473     if ((rc = db_create(&db->db_shortname, db->dbenv, 0)) != 0) {
474         LOG(log_error, logtype_default, "cnid_open: Failed to create did/shortname database: %s",
475             db_strerror(rc));
476         db->db_didname->close(db->db_didname, 0);
477         db->db_macname->close(db->db_macname, 0);
478         goto fail_appinit;
479     }
480
481     db->db_shortname->set_bt_compare(db->db_shortname, &compare_mac);
482     if ((rc = db->db_shortname->open(db->db_shortname, DBSHORTNAME, NULL, DB_BTREE, open_flag, 0666)) != 0) {
483         LOG(log_error, logtype_default, "cnid_open: Failed to open did/shortname database: %s",
484             db_strerror(rc));
485         db->db_didname->close(db->db_didname, 0);
486         db->db_macname->close(db->db_macname, 0);
487         goto fail_appinit;
488     }
489
490     /* did/longname (Unicode) mapping.  Use a BTree for this one. */
491     if ((rc = db_create(&db->db_longname, db->dbenv, 0)) != 0) {
492         LOG(log_error, logtype_default, "cnid_open: Failed to create did/longname database: %s",
493             db_strerror(rc));
494         db->db_didname->close(db->db_didname, 0);
495         db->db_macname->close(db->db_macname, 0);
496         db->db_shortname->close(db->db_shortname, 0);
497         goto fail_appinit;
498     }
499
500     db->db_longname->set_bt_compare(db->db_longname, &compare_unicode);
501     if ((rc = db->db_longname->open(db->db_longname, DBLONGNAME, NULL, DB_BTREE, open_flag, 0666)) != 0) {
502         LOG(log_error, logtype_default, "cnid_open: Failed to open did/longname database: %s",
503             db_strerror(rc));
504         db->db_didname->close(db->db_didname, 0);
505         db->db_macname->close(db->db_macname, 0);
506         db->db_shortname->close(db->db_shortname, 0);
507         goto fail_appinit;
508     }
509 #endif /* EXTENDED_DB */
510
511     /* dev/ino reverse mapping.  Use a hash for this one. */
512     if ((rc = db_create(&db->db_devino, db->dbenv, 0)) != 0) {
513         LOG(log_error, logtype_default, "cnid_open: Failed to create dev/ino database: %s",
514             db_strerror(rc));
515         db->db_didname->close(db->db_didname, 0);
516 #ifdef EXTENDED_DB
517         db->db_macname->close(db->db_macname, 0);
518         db->db_shortname->close(db->db_shortname, 0);
519         db->db_longname->close(db->db_longname, 0);
520 #endif /* EXTENDED_DB */
521         goto fail_appinit;
522     }
523
524     if ((rc = db->db_devino->open(db->db_devino, DBDEVINO, NULL, DB_HASH, open_flag, 0666)) != 0) {
525         LOG(log_error, logtype_default, "cnid_open: Failed to open devino database: %s",
526             db_strerror(rc));
527         db->db_didname->close(db->db_didname, 0);
528 #ifdef EXTENDED_DB
529         db->db_macname->close(db->db_macname, 0);
530         db->db_shortname->close(db->db_shortname, 0);
531         db->db_longname->close(db->db_longname, 0);
532 #endif /* EXTENDED_DB */
533         goto fail_appinit;
534     }
535
536     /* Main CNID database.  Use a hash for this one. */
537     if ((rc = db_create(&db->db_cnid, db->dbenv, 0)) != 0) {
538         LOG(log_error, logtype_default, "cnid_open: Failed to create cnid database: %s",
539             db_strerror(rc));
540         db->db_didname->close(db->db_didname, 0);
541 #ifdef EXTENDED_DB
542         db->db_macname->close(db->db_macname, 0);
543         db->db_shortname->close(db->db_shortname, 0);
544         db->db_longname->close(db->db_longname, 0);
545 #endif /* EXTENDED_DB */
546         db->db_devino->close(db->db_devino, 0);
547         goto fail_appinit;
548     }
549
550
551     if ((rc = db->db_cnid->open(db->db_cnid, DBCNID, NULL, DB_HASH, open_flag, 0666)) != 0) {
552         LOG(log_error, logtype_default, "cnid_open: Failed to open dev/ino database: %s",
553             db_strerror(rc));
554         db->db_didname->close(db->db_didname, 0);
555 #ifdef EXTENDED_DB
556         db->db_macname->close(db->db_macname, 0);
557         db->db_shortname->close(db->db_shortname, 0);
558         db->db_longname->close(db->db_longname, 0);
559 #endif /* EXTENDED_DB */
560         goto fail_appinit;
561     }
562
563     return db;
564
565 fail_appinit:
566     LOG(log_error, logtype_default, "cnid_open: Failed to setup CNID DB environment");
567     db->dbenv->close(db->dbenv, 0);
568
569 fail_lock:
570     if (db->lockfd > -1) {
571         close(db->lockfd);
572     }
573     if (rfd > -1) {
574         (void)remove(recover_file);
575         close(rfd);
576     }
577
578 fail_adouble:
579
580 fail_db:
581     free(db);
582     return NULL;
583 }
584 #endif /* CNID_DB */
585
586