2 * This is a data store backend for the Citadel server which uses Berkeley DB.
4 * Copyright (c) 1987-2011 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 as published
8 * by the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 /*****************************************************************************
23 Tunable configuration parameters for the Berkeley DB back end
24 *****************************************************************************/
26 /* Citadel will checkpoint the db at the end of every session, but only if
27 * the specified number of kilobytes has been written, or if the specified
28 * number of minutes has passed, since the last checkpoint.
30 #define MAX_CHECKPOINT_KBYTES 256
31 #define MAX_CHECKPOINT_MINUTES 15
33 /*****************************************************************************/
42 #include <sys/types.h>
49 #elif defined(HAVE_DB4_DB_H)
52 #error Neither <db.h> nor <db4/db.h> was found by configure. Install db4-devel.
56 #if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 1
57 #error Citadel requires Berkeley DB v4.1 or newer. Please upgrade.
61 #include <libcitadel.h>
64 #include "citserver.h"
67 #include "sysdep_decls.h"
72 #include "ctdl_module.h"
75 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
76 static DB_ENV *dbenv; /* The DB environment (global) */
84 /* Verbose logging callback */
85 void cdb_verbose_log(const DB_ENV *dbenv, const char *msg)
87 if (!IsEmptyStr(msg)) {
88 syslog(LOG_DEBUG, "DB: %s", msg);
93 /* Verbose logging callback */
94 void cdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg)
96 syslog(LOG_ALERT, "DB: %s", msg);
100 /* just a little helper function */
101 static void txabort(DB_TXN * tid)
105 ret = tid->abort(tid);
108 syslog(LOG_EMERG, "bdb(): txn_abort: %s", db_strerror(ret));
113 /* this one is even more helpful than the last. */
114 static void txcommit(DB_TXN * tid)
118 ret = tid->commit(tid, 0);
121 syslog(LOG_EMERG, "bdb(): txn_commit: %s", db_strerror(ret));
126 /* are you sensing a pattern yet? */
127 static void txbegin(DB_TXN ** tid)
131 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
134 syslog(LOG_EMERG, "bdb(): txn_begin: %s", db_strerror(ret));
139 static void dbpanic(DB_ENV * env, int errval)
141 syslog(LOG_EMERG, "bdb(): PANIC: %s", db_strerror(errval));
144 static void cclose(DBC * cursor)
148 if ((ret = cursor->c_close(cursor))) {
149 syslog(LOG_EMERG, "bdb(): c_close: %s", db_strerror(ret));
154 static void bailIfCursor(DBC ** cursors, const char *msg)
158 for (i = 0; i < MAXCDB; i++)
159 if (cursors[i] != NULL) {
160 syslog(LOG_EMERG, "bdb(): cursor still in progress on cdb %02x: %s", i, msg);
166 void cdb_check_handles(void)
168 bailIfCursor(TSD->cursors, "in check_handles");
170 if (TSD->tid != NULL) {
171 syslog(LOG_EMERG, "bdb(): transaction still in progress!");
178 * Cull the database logs
180 static void cdb_cull_logs(void)
189 /* Get the list of names. */
190 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
191 syslog(LOG_ERR, "cdb_cull_logs: %s", db_strerror(ret));
195 /* Print the list of names. */
197 for (file = list; *file != NULL; ++file) {
198 syslog(LOG_DEBUG, "Deleting log: %s", *file);
201 snprintf(errmsg, sizeof(errmsg),
202 " ** ERROR **\n \n \n "
203 "Citadel was unable to delete the "
204 "database log file '%s' because of the "
205 "following error:\n \n %s\n \n"
206 " This log file is no longer in use "
207 "and may be safely deleted.\n",
208 *file, strerror(errno));
209 CtdlAideMessage(errmsg, "Database Warning Message");
217 * Manually initiate log file cull.
219 void cmd_cull(char *argbuf) {
220 if (CtdlAccessCheck(ac_internal)) return;
222 cprintf("%d Database log file cull completed.", CIT_OK);
227 * Request a checkpoint of the database. Called once per minute by the thread manager.
229 void cdb_checkpoint(void)
233 syslog(LOG_DEBUG, "-- db checkpoint --");
234 ret = dbenv->txn_checkpoint(dbenv, MAX_CHECKPOINT_KBYTES, MAX_CHECKPOINT_MINUTES, 0);
237 syslog(LOG_EMERG, "cdb_checkpoint: txn_checkpoint: %s", db_strerror(ret));
241 /* After a successful checkpoint, we can cull the unused logs */
242 if (config.c_auto_cull) {
250 * Open the various databases we'll be using. Any database which
251 * does not exist should be created. Note that we don't need a
252 * critical section here, because there aren't any active threads
253 * manipulating the database yet.
255 void open_databases(void)
261 int dbversion_major, dbversion_minor, dbversion_patch;
262 int current_dbversion = 0;
264 syslog(LOG_DEBUG, "bdb(): open_databases() starting");
265 syslog(LOG_DEBUG, "Compiled db: %s", DB_VERSION_STRING);
266 syslog(LOG_INFO, " Linked db: %s",
267 db_version(&dbversion_major, &dbversion_minor, &dbversion_patch));
269 current_dbversion = (dbversion_major * 1000000) + (dbversion_minor * 1000) + dbversion_patch;
271 syslog(LOG_DEBUG, "Calculated dbversion: %d", current_dbversion);
272 syslog(LOG_DEBUG, " Previous dbversion: %d", CitControl.MMdbversion);
274 if ( (getenv("SUPPRESS_DBVERSION_CHECK") == NULL)
275 && (CitControl.MMdbversion > current_dbversion) ) {
276 syslog(LOG_EMERG, "You are attempting to run the Citadel server using a version");
277 syslog(LOG_EMERG, "of Berkeley DB that is older than that which last created or");
278 syslog(LOG_EMERG, "updated the database. Because this would probably cause data");
279 syslog(LOG_EMERG, "corruption or loss, the server is aborting execution now.");
283 CitControl.MMdbversion = current_dbversion;
287 syslog(LOG_INFO, "Linked zlib: %s\n", zlibVersion());
291 * Silently try to create the database subdirectory. If it's
292 * already there, no problem.
294 if ((mkdir(ctdl_data_dir, 0700) != 0) && (errno != EEXIST)){
296 "unable to create database directory [%s]: %s",
297 ctdl_data_dir, strerror(errno));
299 if (chmod(ctdl_data_dir, 0700) != 0){
301 "unable to set database directory accessrights [%s]: %s",
302 ctdl_data_dir, strerror(errno));
304 if (chown(ctdl_data_dir, CTDLUID, (-1)) != 0){
306 "unable to set the owner for [%s]: %s",
307 ctdl_data_dir, strerror(errno));
309 syslog(LOG_DEBUG, "bdb(): Setting up DB environment\n");
310 /* db_env_set_func_yield((int (*)(u_long, u_long))sched_yield); */
311 ret = db_env_create(&dbenv, 0);
313 syslog(LOG_EMERG, "bdb(): db_env_create: %s\n", db_strerror(ret));
314 syslog(LOG_EMERG, "exit code %d\n", ret);
317 dbenv->set_errpfx(dbenv, "citserver");
318 dbenv->set_paniccall(dbenv, dbpanic);
319 dbenv->set_errcall(dbenv, cdb_verbose_err);
320 dbenv->set_errpfx(dbenv, "ctdl");
321 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 3)
322 dbenv->set_msgcall(dbenv, cdb_verbose_log);
324 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
325 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
328 * We want to specify the shared memory buffer pool cachesize,
329 * but everything else is the default.
331 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
333 syslog(LOG_EMERG, "bdb(): set_cachesize: %s\n", db_strerror(ret));
334 dbenv->close(dbenv, 0);
335 syslog(LOG_EMERG, "exit code %d\n", ret);
339 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
340 syslog(LOG_EMERG, "bdb(): set_lk_detect: %s\n", db_strerror(ret));
341 dbenv->close(dbenv, 0);
342 syslog(LOG_EMERG, "exit code %d\n", ret);
346 flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD | DB_RECOVER;
347 syslog(LOG_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", ctdl_data_dir, flags);
348 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
349 if (ret == DB_RUNRECOVERY) {
350 syslog(LOG_ALERT, "dbenv->open: %s\n", db_strerror(ret));
351 syslog(LOG_ALERT, "Attempting recovery...\n");
353 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
355 if (ret == DB_RUNRECOVERY) {
356 syslog(LOG_ALERT, "dbenv->open: %s\n", db_strerror(ret));
357 syslog(LOG_ALERT, "Attempting catastrophic recovery...\n");
358 flags &= ~DB_RECOVER;
359 flags |= DB_RECOVER_FATAL;
360 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
363 syslog(LOG_EMERG, "dbenv->open: %s\n", db_strerror(ret));
364 dbenv->close(dbenv, 0);
365 syslog(LOG_EMERG, "exit code %d\n", ret);
369 syslog(LOG_INFO, "Starting up DB\n");
371 for (i = 0; i < MAXCDB; ++i) {
373 /* Create a database handle */
374 ret = db_create(&dbp[i], dbenv, 0);
376 syslog(LOG_EMERG, "db_create: %s\n", db_strerror(ret));
377 syslog(LOG_EMERG, "exit code %d\n", ret);
382 /* Arbitrary names for our tables -- we reference them by
383 * number, so we don't have string names for them.
385 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
387 ret = dbp[i]->open(dbp[i],
392 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
396 syslog(LOG_EMERG, "db_open[%02x]: %s\n", i, db_strerror(ret));
398 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");
400 syslog(LOG_EMERG, "exit code %d\n", ret);
408 /* Make sure we own all the files, because in a few milliseconds
409 * we're going to drop root privs.
411 void cdb_chmod_data(void) {
414 char filename[PATH_MAX];
416 dp = opendir(ctdl_data_dir);
418 while (d = readdir(dp), d != NULL) {
419 if (d->d_name[0] != '.') {
420 snprintf(filename, sizeof filename,
421 "%s/%s", ctdl_data_dir, d->d_name);
422 syslog(LOG_DEBUG, "chmod(%s, 0600) returned %d\n",
423 filename, chmod(filename, 0600)
425 syslog(LOG_DEBUG, "chown(%s, CTDLUID, -1) returned %d\n",
426 filename, chown(filename, CTDLUID, (-1))
433 syslog(LOG_DEBUG, "open_databases() finished\n");
434 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
439 * Close all of the db database files we've opened. This can be done
440 * in a loop, since it's just a bunch of closes.
442 void close_databases(void)
447 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
449 "txn_checkpoint: %s\n", db_strerror(ret));
452 /* print some statistics... */
454 dbenv->lock_stat_print(dbenv, DB_STAT_ALL);
457 /* close the tables */
458 for (a = 0; a < MAXCDB; ++a) {
459 syslog(LOG_INFO, "Closing database %02x\n", a);
460 ret = dbp[a]->close(dbp[a], 0);
462 syslog(LOG_EMERG, "db_close: %s\n", db_strerror(ret));
467 /* Close the handle. */
468 ret = dbenv->close(dbenv, 0);
470 syslog(LOG_EMERG, "DBENV->close: %s\n", db_strerror(ret));
476 * Compression functions only used if we have zlib
478 void cdb_decompress_if_necessary(struct cdbdata *cdb)
480 static int magic = COMPRESS_MAGIC;
483 (cdb->ptr == NULL) ||
484 (cdb->len < sizeof(magic)) ||
485 (memcmp(cdb->ptr, &magic, sizeof(magic))))
489 /* At this point we know we're looking at a compressed item. */
491 struct CtdlCompressHeader zheader;
492 char *uncompressed_data;
493 char *compressed_data;
494 uLongf destLen, sourceLen;
497 memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
498 cplen = sizeof(struct CtdlCompressHeader);
499 if (sizeof(struct CtdlCompressHeader) > cdb->len)
501 memcpy(&zheader, cdb->ptr, cplen);
503 compressed_data = cdb->ptr;
504 compressed_data += sizeof(struct CtdlCompressHeader);
506 sourceLen = (uLongf) zheader.compressed_len;
507 destLen = (uLongf) zheader.uncompressed_len;
508 uncompressed_data = malloc(zheader.uncompressed_len);
510 if (uncompress((Bytef *) uncompressed_data,
511 (uLongf *) & destLen,
512 (const Bytef *) compressed_data,
513 (uLong) sourceLen) != Z_OK) {
514 syslog(LOG_EMERG, "uncompress() error\n");
519 cdb->len = (size_t) destLen;
520 cdb->ptr = uncompressed_data;
521 #else /* HAVE_ZLIB */
522 syslog(LOG_EMERG, "Database contains compressed data, but this citserver was built without compression support.");
523 syslog(LOG_EMERG, "Please see http://www.citadel.org/doku.php/faq:installation:zlib for more information.");
525 #endif /* HAVE_ZLIB */
531 * Store a piece of data. Returns 0 if the operation was successful. If a
532 * key already exists it should be overwritten.
534 int cdb_store(int cdb, const void *ckey, int ckeylen, void *cdata, int cdatalen)
542 struct CtdlCompressHeader zheader;
543 char *compressed_data = NULL;
545 size_t buffer_len = 0;
549 memset(&dkey, 0, sizeof(DBT));
550 memset(&ddata, 0, sizeof(DBT));
553 ddata.size = cdatalen;
557 /* Only compress Visit records. Everything else is uncompressed. */
558 if (cdb == CDB_VISIT) {
560 zheader.magic = COMPRESS_MAGIC;
561 zheader.uncompressed_len = cdatalen;
562 buffer_len = ((cdatalen * 101) / 100) + 100
563 + sizeof(struct CtdlCompressHeader);
564 destLen = (uLongf) buffer_len;
565 compressed_data = malloc(buffer_len);
566 if (compress2((Bytef *) (compressed_data + sizeof(struct CtdlCompressHeader)),
567 &destLen, (Bytef *) cdata, (uLongf) cdatalen, 1) != Z_OK)
569 syslog(LOG_EMERG, "compress2() error\n");
572 zheader.compressed_len = (size_t) destLen;
573 memcpy(compressed_data, &zheader, sizeof(struct CtdlCompressHeader));
574 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) + zheader.compressed_len);
575 ddata.data = compressed_data;
579 if (TSD->tid != NULL) {
580 ret = dbp[cdb]->put(dbp[cdb], /* db */
581 TSD->tid, /* transaction ID */
586 syslog(LOG_EMERG, "cdb_store(%d): %s", cdb, db_strerror(ret));
591 free(compressed_data);
596 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
601 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
602 tid, /* transaction ID */
606 if (ret == DB_LOCK_DEADLOCK) {
610 syslog(LOG_EMERG, "cdb_store(%d): %s", cdb, db_strerror(ret));
617 free(compressed_data);
627 * Delete a piece of data. Returns 0 if the operation was successful.
629 int cdb_delete(int cdb, void *key, int keylen)
636 memset(&dkey, 0, sizeof dkey);
640 if (TSD->tid != NULL) {
641 ret = dbp[cdb]->del(dbp[cdb], TSD->tid, &dkey, 0);
643 syslog(LOG_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
644 if (ret != DB_NOTFOUND) {
649 bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
654 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
655 && ret != DB_NOTFOUND) {
656 if (ret == DB_LOCK_DEADLOCK) {
660 syslog(LOG_EMERG, "cdb_delete(%d): %s\n",
661 cdb, db_strerror(ret));
671 static DBC *localcursor(int cdb)
676 if (TSD->cursors[cdb] == NULL)
677 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &curs, 0);
679 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
682 syslog(LOG_EMERG, "localcursor: %s\n", db_strerror(ret));
691 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
692 * a struct cdbdata which it is the caller's responsibility to free later on
693 * using the cdb_free() routine.
695 struct cdbdata *cdb_fetch(int cdb, const void *key, int keylen)
698 struct cdbdata *tempcdb;
702 memset(&dkey, 0, sizeof(DBT));
706 if (TSD->tid != NULL) {
707 memset(&dret, 0, sizeof(DBT));
708 dret.flags = DB_DBT_MALLOC;
709 ret = dbp[cdb]->get(dbp[cdb], TSD->tid, &dkey, &dret, 0);
714 memset(&dret, 0, sizeof(DBT));
715 dret.flags = DB_DBT_MALLOC;
717 curs = localcursor(cdb);
719 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
722 while (ret == DB_LOCK_DEADLOCK);
726 if ((ret != 0) && (ret != DB_NOTFOUND)) {
727 syslog(LOG_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
733 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
735 if (tempcdb == NULL) {
736 syslog(LOG_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
740 tempcdb->len = dret.size;
741 tempcdb->ptr = dret.data;
742 cdb_decompress_if_necessary(tempcdb);
748 * Free a cdbdata item.
750 * Note that we only free the 'ptr' portion if it is not NULL. This allows
751 * other code to assume ownership of that memory simply by storing the
752 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
755 void cdb_free(struct cdbdata *cdb)
763 void cdb_close_cursor(int cdb)
765 if (TSD->cursors[cdb] != NULL) {
766 cclose(TSD->cursors[cdb]);
769 TSD->cursors[cdb] = NULL;
773 * Prepare for a sequential search of an entire database.
774 * (There is guaranteed to be no more than one traversal in
775 * progress per thread at any given time.)
777 void cdb_rewind(int cdb)
781 if (TSD->cursors[cdb] != NULL) {
783 "cdb_rewind: must close cursor on database %d before reopening.\n", cdb);
785 /* cclose(TSD->cursors[cdb]); */
789 * Now initialize the cursor
791 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &TSD->cursors[cdb], 0);
793 syslog(LOG_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
800 * Fetch the next item in a sequential search. Returns a pointer to a
801 * cdbdata structure, or NULL if we've hit the end.
803 struct cdbdata *cdb_next_item(int cdb)
806 struct cdbdata *cdbret;
809 /* Initialize the key/data pair so the flags aren't set. */
810 memset(&key, 0, sizeof(key));
811 memset(&data, 0, sizeof(data));
812 data.flags = DB_DBT_MALLOC;
814 ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &key, &data, DB_NEXT);
817 if (ret != DB_NOTFOUND) {
818 syslog(LOG_EMERG, "cdb_next_item(%d): %s\n", cdb, db_strerror(ret));
821 cdb_close_cursor(cdb);
822 return NULL; /* presumably, end of file */
825 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
826 cdbret->len = data.size;
827 cdbret->ptr = data.data;
828 cdb_decompress_if_necessary(cdbret);
836 * Transaction-based stuff. I'm writing this as I bake cookies...
839 void cdb_begin_transaction(void)
842 bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
844 if (TSD->tid != NULL) {
845 syslog(LOG_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
852 void cdb_end_transaction(void)
856 for (i = 0; i < MAXCDB; i++)
857 if (TSD->cursors[i] != NULL) {
859 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
861 cclose(TSD->cursors[i]);
862 TSD->cursors[i] = NULL;
865 if (TSD->tid == NULL) {
867 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
877 * Truncate (delete every record)
879 void cdb_trunc(int cdb)
885 if (TSD->tid != NULL) {
886 syslog(LOG_EMERG, "cdb_trunc must not be called in a transaction.");
889 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
894 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
895 NULL, /* transaction ID */
896 &count, /* #rows deleted */
898 if (ret == DB_LOCK_DEADLOCK) {
902 syslog(LOG_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));
904 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.");