1 // This is a data store backend for the Citadel server which uses Berkeley DB.
3 // Copyright (c) 1987-2023 by the citadel.org team
5 // This program is open source software. Use, duplication, or disclosure
6 // is subject to the terms of the GNU General Public License, version 3.
8 // Citadel will checkpoint the db at the end of every session, but only if
9 // the specified number of kilobytes has been written, or if the specified
10 // number of minutes has passed, since the last checkpoint.
11 #define MAX_CHECKPOINT_KBYTES 256
12 #define MAX_CHECKPOINT_MINUTES 15
14 #include "../../sysdep.h"
22 #include <libcitadel.h>
23 #include "../../ctdl_module.h"
24 #include "../../control.h"
25 #include "../../citserver.h"
26 #include "../../config.h"
27 #include "berkeley_db.h"
29 #if DB_VERSION_MAJOR < 18
30 #error Citadel requires Berkeley DB v18.0 or newer. Please upgrade.
34 static DB *dbp[MAXCDB]; // One DB handle for each Citadel database
35 static DB_ENV *dbenv; // The DB environment (global)
38 void bdb_abort(void) {
39 syslog(LOG_DEBUG, "bdb: citserver is stopping in order to prevent data loss. uid=%d gid=%d euid=%d egid=%d",
40 getuid(), getgid(), geteuid(), getegid()
42 raise(SIGABRT); // This will exit in a way that can produce a core dump if needed.
43 exit(CTDLEXIT_DB); // Exit if the signal failed to end the program.
47 // Verbose logging callback
48 void bdb_verbose_log(const DB_ENV *dbenv, const char *msg, const char *foo) {
49 if (!IsEmptyStr(msg)) {
50 syslog(LOG_DEBUG, "bdb: %s %s", msg, foo);
55 // Verbose logging callback
56 void bdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg) {
57 syslog(LOG_ERR, "bdb: %s", msg);
61 // wrapper for txn_abort() that logs/aborts on error
62 static void txabort(DB_TXN *tid) {
65 ret = tid->abort(tid);
68 syslog(LOG_ERR, "bdb: txn_abort: %s", db_strerror(ret));
74 // wrapper for txn_commit() that logs/aborts on error
75 static void txcommit(DB_TXN *tid) {
78 ret = tid->commit(tid, 0);
81 syslog(LOG_ERR, "bdb: txn_commit: %s", db_strerror(ret));
87 // wrapper for txn_begin() that logs/aborts on error
88 static void txbegin(DB_TXN **tid) {
91 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
94 syslog(LOG_ERR, "bdb: txn_begin: %s", db_strerror(ret));
101 static void dbpanic(DB_ENV *env, int errval) {
102 syslog(LOG_ERR, "bdb: PANIC: %s", db_strerror(errval));
107 static void cclose(DBC *cursor) {
110 if ((ret = cursor->c_close(cursor))) {
111 syslog(LOG_ERR, "bdb: c_close: %s", db_strerror(ret));
117 static void bailIfCursor(DBC **cursors, const char *msg) {
120 for (i = 0; i < MAXCDB; i++)
121 if (cursors[i] != NULL) {
122 syslog(LOG_ERR, "bdb: cursor still in progress on cdb %02x: %s", i, msg);
128 void bdb_check_handles(void) {
129 bailIfCursor(TSD->cursors, "in check_handles");
131 if (TSD->tid != NULL) {
132 syslog(LOG_ERR, "bdb: transaction still in progress!");
138 // Request a checkpoint of the database. Called once per minute by the thread manager.
139 void bdb_checkpoint(void) {
142 syslog(LOG_DEBUG, "bdb: -- checkpoint --");
143 ret = dbenv->txn_checkpoint(dbenv, MAX_CHECKPOINT_KBYTES, MAX_CHECKPOINT_MINUTES, 0);
146 syslog(LOG_ERR, "bdb: bdb_checkpoint() txn_checkpoint: %s", db_strerror(ret));
150 // After a successful checkpoint, we can cull the unused logs
151 if (CtdlGetConfigInt("c_auto_cull")) {
152 ret = dbenv->log_set_config(dbenv, DB_LOG_AUTO_REMOVE, 1);
155 ret = dbenv->log_set_config(dbenv, DB_LOG_AUTO_REMOVE, 0);
160 // Open the various databases we'll be using. Any database which
161 // does not exist should be created. Note that we don't need a
162 // critical section here, because there aren't any active threads
163 // manipulating the database yet.
164 void bdb_open_databases(void) {
169 int dbversion_major, dbversion_minor, dbversion_patch;
171 syslog(LOG_DEBUG, "bdb: bdb_open_databases() starting");
172 syslog(LOG_DEBUG, "bdb: Linked zlib: %s", zlibVersion());
173 syslog(LOG_DEBUG, "bdb: Compiled libdb: %s", DB_VERSION_STRING);
174 syslog(LOG_DEBUG, "bdb: Linked libdb: %s", db_version(&dbversion_major, &dbversion_minor, &dbversion_patch));
176 // Create synthetic integer version numbers and compare them.
177 // Never allow citserver to run with a libdb older then the one with which it was compiled.
178 int compiled_db_version = ( (DB_VERSION_MAJOR * 1000000) + (DB_VERSION_MINOR * 1000) + (DB_VERSION_PATCH) );
179 int linked_db_version = ( (dbversion_major * 1000000) + (dbversion_minor * 1000) + (dbversion_patch) );
180 if (compiled_db_version > linked_db_version) {
181 syslog(LOG_ERR, "bdb: citserver is running with a version of libdb older than the one with which it was compiled.");
182 syslog(LOG_ERR, "bdb: This is an invalid configuration. citserver will now exit to prevent data loss.");
186 // Silently try to create the database subdirectory. If it's already there, no problem.
187 if ((mkdir(ctdl_db_dir, 0700) != 0) && (errno != EEXIST)) {
188 syslog(LOG_ERR, "bdb: database directory [%s] does not exist and could not be created: %m", ctdl_db_dir);
191 if (chmod(ctdl_db_dir, 0700) != 0) {
192 syslog(LOG_ERR, "bdb: unable to set database directory permissions [%s]: %m", ctdl_db_dir);
195 if (chown(ctdl_db_dir, CTDLUID, (-1)) != 0) {
196 syslog(LOG_ERR, "bdb: unable to set the owner for [%s]: %m", ctdl_db_dir);
199 syslog(LOG_DEBUG, "bdb: Setting up DB environment");
200 ret = db_env_create(&dbenv, 0);
202 syslog(LOG_ERR, "bdb: db_env_create: %s", db_strerror(ret));
203 syslog(LOG_ERR, "bdb: exit code %d", ret);
206 dbenv->set_errpfx(dbenv, "citserver");
207 dbenv->set_paniccall(dbenv, dbpanic);
208 dbenv->set_errcall(dbenv, bdb_verbose_err);
209 dbenv->set_msgcall(dbenv, bdb_verbose_log);
210 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
211 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
213 // We want to specify the shared memory buffer pool cachesize, but everything else is the default.
214 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
216 syslog(LOG_ERR, "bdb: set_cachesize: %s", db_strerror(ret));
217 dbenv->close(dbenv, 0);
218 syslog(LOG_ERR, "bdb: exit code %d", ret);
222 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
223 syslog(LOG_ERR, "bdb: set_lk_detect: %s", db_strerror(ret));
224 dbenv->close(dbenv, 0);
225 syslog(LOG_ERR, "bdb: exit code %d", ret);
229 flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD | DB_INIT_LOG;
230 syslog(LOG_DEBUG, "bdb: dbenv->open(dbenv, %s, %d, 0)", ctdl_db_dir, flags);
231 ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0); // try opening the database cleanly
232 if (ret == DB_RUNRECOVERY) {
233 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
234 syslog(LOG_ERR, "bdb: attempting recovery...");
236 ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0); // try recovery
238 if (ret == DB_RUNRECOVERY) {
239 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
240 syslog(LOG_ERR, "bdb: attempting catastrophic recovery...");
241 flags &= ~DB_RECOVER;
242 flags |= DB_RECOVER_FATAL;
243 ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0); // try catastrophic recovery
246 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
247 dbenv->close(dbenv, 0);
248 syslog(LOG_ERR, "bdb: exit code %d", ret);
252 syslog(LOG_INFO, "bdb: mounting databases");
253 for (i = 0; i < MAXCDB; ++i) {
254 ret = db_create(&dbp[i], dbenv, 0); // Create a database handle
256 syslog(LOG_ERR, "bdb: db_create: %s", db_strerror(ret));
257 syslog(LOG_ERR, "bdb: exit code %d", ret);
261 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i); // table names by number
262 ret = dbp[i]->open(dbp[i], NULL, dbfilename, NULL, DB_BTREE, DB_CREATE | DB_AUTO_COMMIT | DB_THREAD, 0600);
264 syslog(LOG_ERR, "bdb: db_open[%02x]: %s", i, db_strerror(ret));
266 syslog(LOG_ERR, "bdb: You may need to tune your database; please check http://www.citadel.org for more information.");
268 syslog(LOG_ERR, "bdb: exit code %d", ret);
275 // Make sure we own all the files, because in a few milliseconds we're going to drop root privs.
276 void bdb_chmod_data(void) {
279 char filename[PATH_MAX];
281 dp = opendir(ctdl_db_dir);
283 while (d = readdir(dp), d != NULL) {
284 if (d->d_name[0] != '.') {
285 snprintf(filename, sizeof filename, "%s/%s", ctdl_db_dir, d->d_name);
286 syslog(LOG_DEBUG, "bdb: chmod(%s, 0600) returned %d", filename, chmod(filename, 0600));
287 syslog(LOG_DEBUG, "bdb: chown(%s, CTDLUID, -1) returned %d", filename, chown(filename, CTDLUID, (-1)));
295 // Close all of the db database files we've opened. This can be done in a loop, since it's just a bunch of closes.
296 void bdb_close_databases(void) {
300 static int closing = 0;
301 while (closing == 1) {
302 syslog(LOG_INFO, "bdb: already closing");
306 syslog(LOG_INFO, "bdb: performing final checkpoint");
307 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
308 syslog(LOG_ERR, "bdb: txn_checkpoint: %s", db_strerror(ret));
311 syslog(LOG_INFO, "bdb: flushing the database logs");
312 if ((ret = dbenv->log_flush(dbenv, NULL))) {
313 syslog(LOG_ERR, "bdb: log_flush: %s", db_strerror(ret));
317 syslog(LOG_INFO, "bdb: closing databases");
318 for (i = 0; i < MAXCDB; ++i) {
319 syslog(LOG_INFO, "bdb: closing database %02x", i);
320 ret = dbp[i]->close(dbp[i], 0);
322 syslog(LOG_ERR, "bdb: db_close: %s", db_strerror(ret));
327 ret = dbenv->close(dbenv, DB_FORCESYNC);
329 syslog(LOG_ERR, "bdb: DBENV->close: %s", db_strerror(ret));
334 // Decompress a database item if it was compressed on disk
335 void bdb_decompress_if_necessary(struct cdbdata *cdb) {
336 static int magic = COMPRESS_MAGIC;
338 if ((cdb == NULL) || (cdb->ptr == NULL) || (cdb->len < sizeof(magic)) || (memcmp(cdb->ptr, &magic, sizeof(magic)))) {
342 // At this point we know we're looking at a compressed item.
344 struct CtdlCompressHeader zheader;
345 char *uncompressed_data;
346 char *compressed_data;
347 uLongf destLen, sourceLen;
350 memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
351 cplen = sizeof(struct CtdlCompressHeader);
352 if (sizeof(struct CtdlCompressHeader) > cdb->len) {
355 memcpy(&zheader, cdb->ptr, cplen);
357 compressed_data = cdb->ptr;
358 compressed_data += sizeof(struct CtdlCompressHeader);
360 sourceLen = (uLongf) zheader.compressed_len;
361 destLen = (uLongf) zheader.uncompressed_len;
362 uncompressed_data = malloc(zheader.uncompressed_len);
364 if (uncompress((Bytef *) uncompressed_data,
365 (uLongf *) &destLen, (const Bytef *) compressed_data, (uLong) sourceLen) != Z_OK) {
366 syslog(LOG_ERR, "bdb: uncompress() error");
371 cdb->len = (size_t) destLen;
372 cdb->ptr = uncompressed_data;
376 // Store a piece of data. Returns 0 if the operation was successful. If a
377 // key already exists it should be overwritten.
378 int bdb_store(int cdb, const void *ckey, int ckeylen, void *cdata, int cdatalen) {
383 struct CtdlCompressHeader zheader;
384 char *compressed_data = NULL;
386 size_t buffer_len = 0;
389 memset(&dkey, 0, sizeof(DBT));
390 memset(&ddata, 0, sizeof(DBT));
392 dkey.data = (void *) ckey;
393 ddata.size = cdatalen;
396 // "visit" records are numerous and have big, mostly-empty string buffers in them.
397 // If we compress these we can get them down to 1% of their size most of the time.
398 if (cdb == CDB_VISIT) {
400 zheader.magic = COMPRESS_MAGIC;
401 zheader.uncompressed_len = cdatalen;
402 buffer_len = ((cdatalen * 101) / 100) + 100 + sizeof(struct CtdlCompressHeader);
403 destLen = (uLongf) buffer_len;
404 compressed_data = malloc(buffer_len);
405 if (compress2((Bytef *) (compressed_data + sizeof(struct CtdlCompressHeader)), &destLen, (Bytef *) cdata, (uLongf) cdatalen, 1) != Z_OK) {
406 syslog(LOG_ERR, "bdb: compress2() error");
409 zheader.compressed_len = (size_t) destLen;
410 memcpy(compressed_data, &zheader, sizeof(struct CtdlCompressHeader));
411 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) + zheader.compressed_len);
412 ddata.data = compressed_data;
415 if (TSD->tid != NULL) {
416 ret = dbp[cdb]->put(dbp[cdb], // db
417 TSD->tid, // transaction ID
423 syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
427 free(compressed_data);
432 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
437 if ((ret = dbp[cdb]->put(dbp[cdb], // db
438 tid, // transaction ID
442 if (ret == DB_LOCK_DEADLOCK) {
447 syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
454 free(compressed_data);
463 // Delete a piece of data. Returns 0 if the operation was successful.
464 int bdb_delete(int cdb, void *key, int keylen) {
469 memset(&dkey, 0, sizeof dkey);
473 if (TSD->tid != NULL) {
474 ret = dbp[cdb]->del(dbp[cdb], TSD->tid, &dkey, 0);
476 syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
477 if (ret != DB_NOTFOUND) {
483 bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
488 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0)) && ret != DB_NOTFOUND) {
489 if (ret == DB_LOCK_DEADLOCK) {
494 syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
506 static DBC *localcursor(int cdb) {
510 if (TSD->cursors[cdb] == NULL) {
511 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &curs, 0);
514 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
518 syslog(LOG_ERR, "bdb: localcursor: %s", db_strerror(ret));
526 // Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
527 // a struct cdbdata which it is the caller's responsibility to free later on
528 // using the bdb_free() routine.
529 struct cdbdata *bdb_fetch(int cdb, const void *key, int keylen) {
531 if (keylen == 0) { // key length zero is impossible
535 struct cdbdata *tempcdb;
539 memset(&dkey, 0, sizeof(DBT));
541 dkey.data = (void *) key;
543 if (TSD->tid != NULL) {
544 memset(&dret, 0, sizeof(DBT));
545 dret.flags = DB_DBT_MALLOC;
546 ret = dbp[cdb]->get(dbp[cdb], TSD->tid, &dkey, &dret, 0);
552 memset(&dret, 0, sizeof(DBT));
553 dret.flags = DB_DBT_MALLOC;
554 curs = localcursor(cdb);
555 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
557 } while (ret == DB_LOCK_DEADLOCK);
560 if ((ret != 0) && (ret != DB_NOTFOUND)) {
561 syslog(LOG_ERR, "bdb: bdb_fetch(%d): %s", cdb, db_strerror(ret));
569 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
570 if (tempcdb == NULL) {
571 syslog(LOG_ERR, "bdb: bdb_fetch() cannot allocate memory for tempcdb: %m");
575 tempcdb->len = dret.size;
576 tempcdb->ptr = dret.data;
577 bdb_decompress_if_necessary(tempcdb);
583 // Free a cdbdata item.
585 // Note that we only free the 'ptr' portion if it is not NULL. This allows
586 // other code to assume ownership of that memory simply by storing the
587 // pointer elsewhere and then setting 'ptr' to NULL. bdb_free() will then
589 void bdb_free(struct cdbdata *cdb) {
597 void bdb_close_cursor(int cdb) {
598 if (TSD->cursors[cdb] != NULL) {
599 cclose(TSD->cursors[cdb]);
602 TSD->cursors[cdb] = NULL;
606 // Prepare for a sequential search of an entire database.
607 // (There is guaranteed to be no more than one traversal in
608 // progress per thread at any given time.)
609 void bdb_rewind(int cdb) {
612 if (TSD->cursors[cdb] != NULL) {
613 syslog(LOG_ERR, "bdb: bdb_rewind: must close cursor on database %d before reopening", cdb);
615 // cclose(TSD->cursors[cdb]);
618 // Now initialize the cursor
619 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &TSD->cursors[cdb], 0);
621 syslog(LOG_ERR, "bdb: bdb_rewind: db_cursor: %s", db_strerror(ret));
627 // Fetch the next item in a sequential search. Returns a pointer to a
628 // cdbdata structure, or NULL if we've hit the end.
629 struct cdbdata *bdb_next_item(int cdb) {
631 struct cdbdata *cdbret;
634 // Initialize the key/data pair so the flags aren't set.
635 memset(&key, 0, sizeof(key));
636 memset(&data, 0, sizeof(data));
637 data.flags = DB_DBT_MALLOC;
639 ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &key, &data, DB_NEXT);
642 if (ret != DB_NOTFOUND) {
643 syslog(LOG_ERR, "bdb: bdb_next_item(%d): %s", cdb, db_strerror(ret));
646 bdb_close_cursor(cdb);
647 return NULL; // presumably, end of file
650 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
651 cdbret->len = data.size;
652 cdbret->ptr = data.data;
653 bdb_decompress_if_necessary(cdbret);
659 // Transaction-based stuff. I'm writing this as I bake cookies...
660 void bdb_begin_transaction(void) {
661 bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
663 if (TSD->tid != NULL) {
664 syslog(LOG_ERR, "bdb: bdb_begin_transaction: ERROR: nested transaction");
672 void bdb_end_transaction(void) {
675 for (i = 0; i < MAXCDB; i++) {
676 if (TSD->cursors[i] != NULL) {
677 syslog(LOG_WARNING, "bdb: bdb_end_transaction: WARNING: cursor %d still open at transaction end", i);
678 cclose(TSD->cursors[i]);
679 TSD->cursors[i] = NULL;
683 if (TSD->tid == NULL) {
684 syslog(LOG_ERR, "bdb: bdb_end_transaction: ERROR: txcommit(NULL) !!");
695 // Truncate (delete every record)
696 void bdb_trunc(int cdb) {
700 if (TSD->tid != NULL) {
701 syslog(LOG_ERR, "bdb: bdb_trunc must not be called in a transaction.");
705 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
709 if ((ret = dbp[cdb]->truncate(dbp[cdb], // db
710 NULL, // transaction ID
711 &count, // #rows deleted
713 if (ret == DB_LOCK_DEADLOCK) {
717 syslog(LOG_ERR, "bdb: bdb_truncate(%d): %s", cdb, db_strerror(ret));
719 syslog(LOG_ERR, "bdb: You may need to tune your database; please read http://www.citadel.org for more information.");
728 // compact (defragment) the database, possibly returning space back to the underlying filesystem
729 void bdb_compact(void) {
733 syslog(LOG_DEBUG, "bdb: bdb_compact() started");
734 for (i = 0; i < MAXCDB; i++) {
735 syslog(LOG_DEBUG, "bdb: compacting database %d", i);
736 ret = dbp[i]->compact(dbp[i], NULL, NULL, NULL, NULL, DB_FREE_SPACE, NULL);
738 syslog(LOG_ERR, "bdb: compact: %s", db_strerror(ret));
741 syslog(LOG_DEBUG, "bdb: bdb_compact() finished");
745 // Calling this function activates the Berkeley DB back end.
746 void bdb_init_backend(void) {
747 cdb_compact = bdb_compact;
748 cdb_checkpoint = bdb_checkpoint;
749 cdb_rewind = bdb_rewind;
750 cdb_fetch = bdb_fetch;
751 cdb_open_databases = bdb_open_databases;
752 cdb_close_databases = bdb_close_databases;
753 cdb_store = bdb_store;
754 cdb_delete = bdb_delete;
756 cdb_next_item = bdb_next_item;
757 cdb_close_cursor = bdb_close_cursor;
758 cdb_begin_transaction = bdb_begin_transaction;
759 cdb_end_transaction = bdb_end_transaction;
760 cdb_check_handles = bdb_check_handles;
761 cdb_trunc = bdb_trunc;
762 cdb_chmod_data = bdb_chmod_data;
764 syslog(LOG_INFO, "db: initialized Berkeley DB backend");