2 * This is a data store backend for the Citadel server which uses Berkeley DB.
4 * Copyright (c) 1987-2012 by the citadel.org team
6 * This program is open source software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License version 3.
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.
16 /*****************************************************************************
17 Tunable configuration parameters for the Berkeley DB back end
18 *****************************************************************************/
20 /* Citadel will checkpoint the db at the end of every session, but only if
21 * the specified number of kilobytes has been written, or if the specified
22 * number of minutes has passed, since the last checkpoint.
24 #define MAX_CHECKPOINT_KBYTES 256
25 #define MAX_CHECKPOINT_MINUTES 15
27 /*****************************************************************************/
36 #include <sys/types.h>
44 #elif defined(HAVE_DB4_DB_H)
47 #error Neither <db.h> nor <db4/db.h> was found by configure. Install db4-devel.
51 #if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 1
52 #error Citadel requires Berkeley DB v4.1 or newer. Please upgrade.
56 #include <libcitadel.h>
59 #include "citserver.h"
62 #include "sysdep_decls.h"
67 #include "ctdl_module.h"
70 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
71 static DB_ENV *dbenv; /* The DB environment (global) */
75 /* Verbose logging callback */
76 void cdb_verbose_log(const DB_ENV *dbenv, const char *msg)
78 if (!IsEmptyStr(msg)) {
79 syslog(LOG_DEBUG, "DB: %s", msg);
84 /* Verbose logging callback */
85 void cdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg)
87 syslog(LOG_ALERT, "DB: %s", msg);
91 /* just a little helper function */
92 static void txabort(DB_TXN * tid)
96 ret = tid->abort(tid);
99 syslog(LOG_EMERG, "bdb(): txn_abort: %s", db_strerror(ret));
104 /* this one is even more helpful than the last. */
105 static void txcommit(DB_TXN * tid)
109 ret = tid->commit(tid, 0);
112 syslog(LOG_EMERG, "bdb(): txn_commit: %s", db_strerror(ret));
117 /* are you sensing a pattern yet? */
118 static void txbegin(DB_TXN ** tid)
122 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
125 syslog(LOG_EMERG, "bdb(): txn_begin: %s", db_strerror(ret));
130 static void dbpanic(DB_ENV * env, int errval)
132 syslog(LOG_EMERG, "bdb(): PANIC: %s", db_strerror(errval));
135 static void cclose(DBC * cursor)
139 if ((ret = cursor->c_close(cursor))) {
140 syslog(LOG_EMERG, "bdb(): c_close: %s", db_strerror(ret));
145 static void bailIfCursor(DBC ** cursors, const char *msg)
149 for (i = 0; i < MAXCDB; i++)
150 if (cursors[i] != NULL) {
151 syslog(LOG_EMERG, "bdb(): cursor still in progress on cdb %02x: %s", i, msg);
157 void cdb_check_handles(void)
159 bailIfCursor(TSD->cursors, "in check_handles");
161 if (TSD->tid != NULL) {
162 syslog(LOG_EMERG, "bdb(): transaction still in progress!");
169 * Cull the database logs
171 static void cdb_cull_logs(void)
180 /* Get the list of names. */
181 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
182 syslog(LOG_ERR, "cdb_cull_logs: %s", db_strerror(ret));
186 /* Print the list of names. */
188 for (file = list; *file != NULL; ++file) {
189 syslog(LOG_DEBUG, "Deleting log: %s", *file);
192 snprintf(errmsg, sizeof(errmsg),
193 " ** ERROR **\n \n \n "
194 "Citadel was unable to delete the "
195 "database log file '%s' because of the "
196 "following error:\n \n %s\n \n"
197 " This log file is no longer in use "
198 "and may be safely deleted.\n",
199 *file, strerror(errno));
200 CtdlAideMessage(errmsg, "Database Warning Message");
208 * Manually initiate log file cull.
210 void cmd_cull(char *argbuf) {
211 if (CtdlAccessCheck(ac_internal)) return;
213 cprintf("%d Database log file cull completed.", CIT_OK);
218 * Request a checkpoint of the database. Called once per minute by the thread manager.
220 void cdb_checkpoint(void)
224 syslog(LOG_DEBUG, "-- db checkpoint --");
225 ret = dbenv->txn_checkpoint(dbenv, MAX_CHECKPOINT_KBYTES, MAX_CHECKPOINT_MINUTES, 0);
228 syslog(LOG_EMERG, "cdb_checkpoint: txn_checkpoint: %s", db_strerror(ret));
232 /* After a successful checkpoint, we can cull the unused logs */
233 if (config.c_auto_cull) {
241 * Open the various databases we'll be using. Any database which
242 * does not exist should be created. Note that we don't need a
243 * critical section here, because there aren't any active threads
244 * manipulating the database yet.
246 void open_databases(void)
252 int dbversion_major, dbversion_minor, dbversion_patch;
253 int current_dbversion = 0;
255 syslog(LOG_DEBUG, "bdb(): open_databases() starting");
256 syslog(LOG_DEBUG, "Compiled db: %s", DB_VERSION_STRING);
257 syslog(LOG_INFO, " Linked db: %s",
258 db_version(&dbversion_major, &dbversion_minor, &dbversion_patch));
260 current_dbversion = (dbversion_major * 1000000) + (dbversion_minor * 1000) + dbversion_patch;
262 syslog(LOG_DEBUG, "Calculated dbversion: %d", current_dbversion);
263 syslog(LOG_DEBUG, " Previous dbversion: %d", CitControl.MMdbversion);
265 if ( (getenv("SUPPRESS_DBVERSION_CHECK") == NULL)
266 && (CitControl.MMdbversion > current_dbversion) ) {
267 syslog(LOG_EMERG, "You are attempting to run the Citadel server using a version");
268 syslog(LOG_EMERG, "of Berkeley DB that is older than that which last created or");
269 syslog(LOG_EMERG, "updated the database. Because this would probably cause data");
270 syslog(LOG_EMERG, "corruption or loss, the server is aborting execution now.");
274 CitControl.MMdbversion = current_dbversion;
277 syslog(LOG_INFO, "Linked zlib: %s\n", zlibVersion());
280 * Silently try to create the database subdirectory. If it's
281 * already there, no problem.
283 if ((mkdir(ctdl_data_dir, 0700) != 0) && (errno != EEXIST)){
285 "unable to create database directory [%s]: %s",
286 ctdl_data_dir, strerror(errno));
288 if (chmod(ctdl_data_dir, 0700) != 0){
290 "unable to set database directory accessrights [%s]: %s",
291 ctdl_data_dir, strerror(errno));
293 if (chown(ctdl_data_dir, CTDLUID, (-1)) != 0){
295 "unable to set the owner for [%s]: %s",
296 ctdl_data_dir, strerror(errno));
298 syslog(LOG_DEBUG, "bdb(): Setting up DB environment\n");
299 /* db_env_set_func_yield((int (*)(u_long, u_long))sched_yield); */
300 ret = db_env_create(&dbenv, 0);
302 syslog(LOG_EMERG, "bdb(): db_env_create: %s\n", db_strerror(ret));
303 syslog(LOG_EMERG, "exit code %d\n", ret);
306 dbenv->set_errpfx(dbenv, "citserver");
307 dbenv->set_paniccall(dbenv, dbpanic);
308 dbenv->set_errcall(dbenv, cdb_verbose_err);
309 dbenv->set_errpfx(dbenv, "ctdl");
310 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 3)
311 dbenv->set_msgcall(dbenv, cdb_verbose_log);
313 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
314 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
317 * We want to specify the shared memory buffer pool cachesize,
318 * but everything else is the default.
320 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
322 syslog(LOG_EMERG, "bdb(): set_cachesize: %s\n", db_strerror(ret));
323 dbenv->close(dbenv, 0);
324 syslog(LOG_EMERG, "exit code %d\n", ret);
328 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
329 syslog(LOG_EMERG, "bdb(): set_lk_detect: %s\n", db_strerror(ret));
330 dbenv->close(dbenv, 0);
331 syslog(LOG_EMERG, "exit code %d\n", ret);
335 flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD | DB_RECOVER;
336 syslog(LOG_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", ctdl_data_dir, flags);
337 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
338 if (ret == DB_RUNRECOVERY) {
339 syslog(LOG_ALERT, "dbenv->open: %s\n", db_strerror(ret));
340 syslog(LOG_ALERT, "Attempting recovery...\n");
342 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
344 if (ret == DB_RUNRECOVERY) {
345 syslog(LOG_ALERT, "dbenv->open: %s\n", db_strerror(ret));
346 syslog(LOG_ALERT, "Attempting catastrophic recovery...\n");
347 flags &= ~DB_RECOVER;
348 flags |= DB_RECOVER_FATAL;
349 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
352 syslog(LOG_EMERG, "dbenv->open: %s\n", db_strerror(ret));
353 dbenv->close(dbenv, 0);
354 syslog(LOG_EMERG, "exit code %d\n", ret);
358 syslog(LOG_INFO, "Starting up DB\n");
360 for (i = 0; i < MAXCDB; ++i) {
362 /* Create a database handle */
363 ret = db_create(&dbp[i], dbenv, 0);
365 syslog(LOG_EMERG, "db_create: %s\n", db_strerror(ret));
366 syslog(LOG_EMERG, "exit code %d\n", ret);
371 /* Arbitrary names for our tables -- we reference them by
372 * number, so we don't have string names for them.
374 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
376 ret = dbp[i]->open(dbp[i],
381 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
385 syslog(LOG_EMERG, "db_open[%02x]: %s\n", i, db_strerror(ret));
387 syslog(LOG_EMERG, "You may need to tune your database; please read http://www.citadel.org/doku.php/faq:troubleshooting:out_of_lock_entries for more information.\n");
389 syslog(LOG_EMERG, "exit code %d\n", ret);
397 /* Make sure we own all the files, because in a few milliseconds
398 * we're going to drop root privs.
400 void cdb_chmod_data(void) {
403 char filename[PATH_MAX];
405 dp = opendir(ctdl_data_dir);
407 while (d = readdir(dp), d != NULL) {
408 if (d->d_name[0] != '.') {
409 snprintf(filename, sizeof filename,
410 "%s/%s", ctdl_data_dir, d->d_name);
411 syslog(LOG_DEBUG, "chmod(%s, 0600) returned %d\n",
412 filename, chmod(filename, 0600)
414 syslog(LOG_DEBUG, "chown(%s, CTDLUID, -1) returned %d\n",
415 filename, chown(filename, CTDLUID, (-1))
422 syslog(LOG_DEBUG, "open_databases() finished\n");
423 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
428 * Close all of the db database files we've opened. This can be done
429 * in a loop, since it's just a bunch of closes.
431 void close_databases(void)
436 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
438 "txn_checkpoint: %s\n", db_strerror(ret));
441 /* print some statistics... */
443 dbenv->lock_stat_print(dbenv, DB_STAT_ALL);
446 /* close the tables */
447 for (a = 0; a < MAXCDB; ++a) {
448 syslog(LOG_INFO, "Closing database %02x\n", a);
449 ret = dbp[a]->close(dbp[a], 0);
451 syslog(LOG_EMERG, "db_close: %s\n", db_strerror(ret));
456 /* Close the handle. */
457 ret = dbenv->close(dbenv, 0);
459 syslog(LOG_EMERG, "DBENV->close: %s\n", db_strerror(ret));
465 * Decompress a database item if it was compressed on disk
467 void cdb_decompress_if_necessary(struct cdbdata *cdb)
469 static int magic = COMPRESS_MAGIC;
472 (cdb->ptr == NULL) ||
473 (cdb->len < sizeof(magic)) ||
474 (memcmp(cdb->ptr, &magic, sizeof(magic))))
477 /* At this point we know we're looking at a compressed item. */
479 struct CtdlCompressHeader zheader;
480 char *uncompressed_data;
481 char *compressed_data;
482 uLongf destLen, sourceLen;
485 memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
486 cplen = sizeof(struct CtdlCompressHeader);
487 if (sizeof(struct CtdlCompressHeader) > cdb->len)
489 memcpy(&zheader, cdb->ptr, cplen);
491 compressed_data = cdb->ptr;
492 compressed_data += sizeof(struct CtdlCompressHeader);
494 sourceLen = (uLongf) zheader.compressed_len;
495 destLen = (uLongf) zheader.uncompressed_len;
496 uncompressed_data = malloc(zheader.uncompressed_len);
498 if (uncompress((Bytef *) uncompressed_data,
499 (uLongf *) & destLen,
500 (const Bytef *) compressed_data,
501 (uLong) sourceLen) != Z_OK) {
502 syslog(LOG_EMERG, "uncompress() error\n");
507 cdb->len = (size_t) destLen;
508 cdb->ptr = uncompressed_data;
514 * Store a piece of data. Returns 0 if the operation was successful. If a
515 * key already exists it should be overwritten.
517 int cdb_store(int cdb, const void *ckey, int ckeylen, void *cdata, int cdatalen)
524 struct CtdlCompressHeader zheader;
525 char *compressed_data = NULL;
527 size_t buffer_len = 0;
530 memset(&dkey, 0, sizeof(DBT));
531 memset(&ddata, 0, sizeof(DBT));
534 ddata.size = cdatalen;
537 /* Only compress Visit records. Everything else is uncompressed. */
538 if (cdb == CDB_VISIT) {
540 zheader.magic = COMPRESS_MAGIC;
541 zheader.uncompressed_len = cdatalen;
542 buffer_len = ((cdatalen * 101) / 100) + 100
543 + sizeof(struct CtdlCompressHeader);
544 destLen = (uLongf) buffer_len;
545 compressed_data = malloc(buffer_len);
546 if (compress2((Bytef *) (compressed_data + sizeof(struct CtdlCompressHeader)),
547 &destLen, (Bytef *) cdata, (uLongf) cdatalen, 1) != Z_OK)
549 syslog(LOG_EMERG, "compress2() error\n");
552 zheader.compressed_len = (size_t) destLen;
553 memcpy(compressed_data, &zheader, sizeof(struct CtdlCompressHeader));
554 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) + zheader.compressed_len);
555 ddata.data = compressed_data;
558 if (TSD->tid != NULL) {
559 ret = dbp[cdb]->put(dbp[cdb], /* db */
560 TSD->tid, /* transaction ID */
565 syslog(LOG_EMERG, "cdb_store(%d): %s", cdb, db_strerror(ret));
569 free(compressed_data);
573 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
578 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
579 tid, /* transaction ID */
583 if (ret == DB_LOCK_DEADLOCK) {
587 syslog(LOG_EMERG, "cdb_store(%d): %s", cdb, db_strerror(ret));
593 free(compressed_data);
602 * Delete a piece of data. Returns 0 if the operation was successful.
604 int cdb_delete(int cdb, void *key, int keylen)
611 memset(&dkey, 0, sizeof dkey);
615 if (TSD->tid != NULL) {
616 ret = dbp[cdb]->del(dbp[cdb], TSD->tid, &dkey, 0);
618 syslog(LOG_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
619 if (ret != DB_NOTFOUND) {
624 bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
629 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
630 && ret != DB_NOTFOUND) {
631 if (ret == DB_LOCK_DEADLOCK) {
635 syslog(LOG_EMERG, "cdb_delete(%d): %s\n",
636 cdb, db_strerror(ret));
646 static DBC *localcursor(int cdb)
651 if (TSD->cursors[cdb] == NULL)
652 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &curs, 0);
654 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
657 syslog(LOG_EMERG, "localcursor: %s\n", db_strerror(ret));
666 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
667 * a struct cdbdata which it is the caller's responsibility to free later on
668 * using the cdb_free() routine.
670 struct cdbdata *cdb_fetch(int cdb, const void *key, int keylen)
673 struct cdbdata *tempcdb;
677 memset(&dkey, 0, sizeof(DBT));
681 if (TSD->tid != NULL) {
682 memset(&dret, 0, sizeof(DBT));
683 dret.flags = DB_DBT_MALLOC;
684 ret = dbp[cdb]->get(dbp[cdb], TSD->tid, &dkey, &dret, 0);
689 memset(&dret, 0, sizeof(DBT));
690 dret.flags = DB_DBT_MALLOC;
692 curs = localcursor(cdb);
694 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
697 while (ret == DB_LOCK_DEADLOCK);
701 if ((ret != 0) && (ret != DB_NOTFOUND)) {
702 syslog(LOG_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
708 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
710 if (tempcdb == NULL) {
711 syslog(LOG_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
715 tempcdb->len = dret.size;
716 tempcdb->ptr = dret.data;
717 cdb_decompress_if_necessary(tempcdb);
723 * Free a cdbdata item.
725 * Note that we only free the 'ptr' portion if it is not NULL. This allows
726 * other code to assume ownership of that memory simply by storing the
727 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
730 void cdb_free(struct cdbdata *cdb)
738 void cdb_close_cursor(int cdb)
740 if (TSD->cursors[cdb] != NULL) {
741 cclose(TSD->cursors[cdb]);
744 TSD->cursors[cdb] = NULL;
748 * Prepare for a sequential search of an entire database.
749 * (There is guaranteed to be no more than one traversal in
750 * progress per thread at any given time.)
752 void cdb_rewind(int cdb)
756 if (TSD->cursors[cdb] != NULL) {
758 "cdb_rewind: must close cursor on database %d before reopening.\n", cdb);
760 /* cclose(TSD->cursors[cdb]); */
764 * Now initialize the cursor
766 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &TSD->cursors[cdb], 0);
768 syslog(LOG_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
775 * Fetch the next item in a sequential search. Returns a pointer to a
776 * cdbdata structure, or NULL if we've hit the end.
778 struct cdbdata *cdb_next_item(int cdb)
781 struct cdbdata *cdbret;
784 /* Initialize the key/data pair so the flags aren't set. */
785 memset(&key, 0, sizeof(key));
786 memset(&data, 0, sizeof(data));
787 data.flags = DB_DBT_MALLOC;
789 ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &key, &data, DB_NEXT);
792 if (ret != DB_NOTFOUND) {
793 syslog(LOG_EMERG, "cdb_next_item(%d): %s\n", cdb, db_strerror(ret));
796 cdb_close_cursor(cdb);
797 return NULL; /* presumably, end of file */
800 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
801 cdbret->len = data.size;
802 cdbret->ptr = data.data;
803 cdb_decompress_if_necessary(cdbret);
811 * Transaction-based stuff. I'm writing this as I bake cookies...
814 void cdb_begin_transaction(void)
817 bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
819 if (TSD->tid != NULL) {
820 syslog(LOG_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
827 void cdb_end_transaction(void)
831 for (i = 0; i < MAXCDB; i++)
832 if (TSD->cursors[i] != NULL) {
834 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
836 cclose(TSD->cursors[i]);
837 TSD->cursors[i] = NULL;
840 if (TSD->tid == NULL) {
842 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
852 * Truncate (delete every record)
854 void cdb_trunc(int cdb)
860 if (TSD->tid != NULL) {
861 syslog(LOG_EMERG, "cdb_trunc must not be called in a transaction.");
864 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
869 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
870 NULL, /* transaction ID */
871 &count, /* #rows deleted */
873 if (ret == DB_LOCK_DEADLOCK) {
877 syslog(LOG_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));
879 syslog(LOG_EMERG, "You may need to tune your database; please read http://www.citadel.org/doku.php/faq:troubleshooting:out_of_lock_entries for more information.");