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.");
524 #endif /* HAVE_ZLIB */
530 * Store a piece of data. Returns 0 if the operation was successful. If a
531 * key already exists it should be overwritten.
533 int cdb_store(int cdb, const void *ckey, int ckeylen, void *cdata, int cdatalen)
541 struct CtdlCompressHeader zheader;
542 char *compressed_data = NULL;
544 size_t buffer_len = 0;
548 memset(&dkey, 0, sizeof(DBT));
549 memset(&ddata, 0, sizeof(DBT));
552 ddata.size = cdatalen;
556 /* Only compress Visit records. Everything else is uncompressed. */
557 if (cdb == CDB_VISIT) {
559 zheader.magic = COMPRESS_MAGIC;
560 zheader.uncompressed_len = cdatalen;
561 buffer_len = ((cdatalen * 101) / 100) + 100
562 + sizeof(struct CtdlCompressHeader);
563 destLen = (uLongf) buffer_len;
564 compressed_data = malloc(buffer_len);
565 if (compress2((Bytef *) (compressed_data + sizeof(struct CtdlCompressHeader)),
566 &destLen, (Bytef *) cdata, (uLongf) cdatalen, 1) != Z_OK)
568 syslog(LOG_EMERG, "compress2() error\n");
571 zheader.compressed_len = (size_t) destLen;
572 memcpy(compressed_data, &zheader, sizeof(struct CtdlCompressHeader));
573 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) + zheader.compressed_len);
574 ddata.data = compressed_data;
578 if (TSD->tid != NULL) {
579 ret = dbp[cdb]->put(dbp[cdb], /* db */
580 TSD->tid, /* transaction ID */
585 syslog(LOG_EMERG, "cdb_store(%d): %s", cdb, db_strerror(ret));
590 free(compressed_data);
595 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
600 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
601 tid, /* transaction ID */
605 if (ret == DB_LOCK_DEADLOCK) {
609 syslog(LOG_EMERG, "cdb_store(%d): %s", cdb, db_strerror(ret));
616 free(compressed_data);
626 * Delete a piece of data. Returns 0 if the operation was successful.
628 int cdb_delete(int cdb, void *key, int keylen)
635 memset(&dkey, 0, sizeof dkey);
639 if (TSD->tid != NULL) {
640 ret = dbp[cdb]->del(dbp[cdb], TSD->tid, &dkey, 0);
642 syslog(LOG_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
643 if (ret != DB_NOTFOUND) {
648 bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
653 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
654 && ret != DB_NOTFOUND) {
655 if (ret == DB_LOCK_DEADLOCK) {
659 syslog(LOG_EMERG, "cdb_delete(%d): %s\n",
660 cdb, db_strerror(ret));
670 static DBC *localcursor(int cdb)
675 if (TSD->cursors[cdb] == NULL)
676 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &curs, 0);
678 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
681 syslog(LOG_EMERG, "localcursor: %s\n", db_strerror(ret));
690 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
691 * a struct cdbdata which it is the caller's responsibility to free later on
692 * using the cdb_free() routine.
694 struct cdbdata *cdb_fetch(int cdb, const void *key, int keylen)
697 struct cdbdata *tempcdb;
701 memset(&dkey, 0, sizeof(DBT));
705 if (TSD->tid != NULL) {
706 memset(&dret, 0, sizeof(DBT));
707 dret.flags = DB_DBT_MALLOC;
708 ret = dbp[cdb]->get(dbp[cdb], TSD->tid, &dkey, &dret, 0);
713 memset(&dret, 0, sizeof(DBT));
714 dret.flags = DB_DBT_MALLOC;
716 curs = localcursor(cdb);
718 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
721 while (ret == DB_LOCK_DEADLOCK);
725 if ((ret != 0) && (ret != DB_NOTFOUND)) {
726 syslog(LOG_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
732 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
734 if (tempcdb == NULL) {
735 syslog(LOG_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
739 tempcdb->len = dret.size;
740 tempcdb->ptr = dret.data;
741 cdb_decompress_if_necessary(tempcdb);
747 * Free a cdbdata item.
749 * Note that we only free the 'ptr' portion if it is not NULL. This allows
750 * other code to assume ownership of that memory simply by storing the
751 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
754 void cdb_free(struct cdbdata *cdb)
762 void cdb_close_cursor(int cdb)
764 if (TSD->cursors[cdb] != NULL) {
765 cclose(TSD->cursors[cdb]);
768 TSD->cursors[cdb] = NULL;
772 * Prepare for a sequential search of an entire database.
773 * (There is guaranteed to be no more than one traversal in
774 * progress per thread at any given time.)
776 void cdb_rewind(int cdb)
780 if (TSD->cursors[cdb] != NULL) {
782 "cdb_rewind: must close cursor on database %d before reopening.\n", cdb);
784 /* cclose(TSD->cursors[cdb]); */
788 * Now initialize the cursor
790 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &TSD->cursors[cdb], 0);
792 syslog(LOG_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
799 * Fetch the next item in a sequential search. Returns a pointer to a
800 * cdbdata structure, or NULL if we've hit the end.
802 struct cdbdata *cdb_next_item(int cdb)
805 struct cdbdata *cdbret;
808 /* Initialize the key/data pair so the flags aren't set. */
809 memset(&key, 0, sizeof(key));
810 memset(&data, 0, sizeof(data));
811 data.flags = DB_DBT_MALLOC;
813 ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &key, &data, DB_NEXT);
816 if (ret != DB_NOTFOUND) {
817 syslog(LOG_EMERG, "cdb_next_item(%d): %s\n", cdb, db_strerror(ret));
820 cdb_close_cursor(cdb);
821 return NULL; /* presumably, end of file */
824 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
825 cdbret->len = data.size;
826 cdbret->ptr = data.data;
827 cdb_decompress_if_necessary(cdbret);
835 * Transaction-based stuff. I'm writing this as I bake cookies...
838 void cdb_begin_transaction(void)
841 bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
843 if (TSD->tid != NULL) {
844 syslog(LOG_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
851 void cdb_end_transaction(void)
855 for (i = 0; i < MAXCDB; i++)
856 if (TSD->cursors[i] != NULL) {
858 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
860 cclose(TSD->cursors[i]);
861 TSD->cursors[i] = NULL;
864 if (TSD->tid == NULL) {
866 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
876 * Truncate (delete every record)
878 void cdb_trunc(int cdb)
884 if (TSD->tid != NULL) {
885 syslog(LOG_EMERG, "cdb_trunc must not be called in a transaction.");
888 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
893 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
894 NULL, /* transaction ID */
895 &count, /* #rows deleted */
897 if (ret == DB_LOCK_DEADLOCK) {
901 syslog(LOG_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));
903 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.");