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