server/database_bdb.c is now server/backends/berkeley_db/berkeley_db.c
[citadel.git] / citadel / server / backends / berkeley_db / berkeley_db.c
1 // This is a data store backend for the Citadel server which uses Berkeley DB.
2 //
3 // Copyright (c) 1987-2023 by the citadel.org team
4 //
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.
7
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
13
14 #include "../../sysdep.h"
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <sys/stat.h>
18 #include <stdio.h>
19 #include <dirent.h>
20 #include <zlib.h>
21 #include <db.h>
22
23 #if DB_VERSION_MAJOR < 18
24 #error Citadel requires Berkeley DB v18.0 or newer.  Please upgrade.
25 #endif
26
27 #include <libcitadel.h>
28 #include "../../ctdl_module.h"
29 #include "../../control.h"
30 #include "../../citserver.h"
31 #include "../../config.h"
32
33 void                    (*cdb_open_databases)(void)                             = NULL;
34 void                    (*cdb_close_databases)(void)                            = NULL;
35 int                     (*cdb_store)(int, const void *, int, void *, int)       = NULL;
36 int                     (*cdb_delete)(int, void *, int)                         = NULL;
37 void                    (*cdb_free)(struct cdbdata *)                           = NULL;
38 struct cdbdata *        (*cdb_next_item)(int)                                   = NULL;
39 void                    (*cdb_close_cursor)(int)                                = NULL;
40 void                    (*cdb_begin_transaction)(void)                          = NULL;
41 void                    (*cdb_end_transaction)(void)                            = NULL;
42 void                    (*cdb_check_handles)(void)                              = NULL;
43 void                    (*cdb_trunc)(int)                                       = NULL;
44 void                    (*cdb_chmod_data)(void)                                 = NULL;
45 void                    (*check_handles)(void *)                                = NULL;
46 void                    (*cdb_compact)(void)                                    = NULL;
47 void                    (*cdb_checkpoint)(void)                                 = NULL;
48 void                    (*cdb_rewind)(int)                                      = NULL;
49 struct cdbdata *        (*cdb_fetch)(int, const void *, int)                    = NULL;
50
51 static DB *dbp[MAXCDB];         // One DB handle for each Citadel database
52 static DB_ENV *dbenv;           // The DB environment (global)
53
54
55 void bdb_abort(void) {
56         syslog(LOG_DEBUG, "bdb: citserver is stopping in order to prevent data loss. uid=%d gid=%d euid=%d egid=%d",
57                 getuid(), getgid(), geteuid(), getegid()
58         );
59         raise(SIGABRT);         // This will exit in a way that can produce a core dump if needed.
60         exit(CTDLEXIT_DB);      // Exit if the signal failed to end the program.
61 }
62
63
64 // Verbose logging callback
65 void bdb_verbose_log(const DB_ENV *dbenv, const char *msg, const char *foo) {
66         if (!IsEmptyStr(msg)) {
67                 syslog(LOG_DEBUG, "bdb: %s %s", msg, foo);
68         }
69 }
70
71
72 // Verbose logging callback
73 void bdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg) {
74         syslog(LOG_ERR, "bdb: %s", msg);
75 }
76
77
78 // wrapper for txn_abort() that logs/aborts on error
79 static void txabort(DB_TXN *tid) {
80         int ret;
81
82         ret = tid->abort(tid);
83
84         if (ret) {
85                 syslog(LOG_ERR, "bdb: txn_abort: %s", db_strerror(ret));
86                 bdb_abort();
87         }
88 }
89
90
91 // wrapper for txn_commit() that logs/aborts on error
92 static void txcommit(DB_TXN *tid) {
93         int ret;
94
95         ret = tid->commit(tid, 0);
96
97         if (ret) {
98                 syslog(LOG_ERR, "bdb: txn_commit: %s", db_strerror(ret));
99                 bdb_abort();
100         }
101 }
102
103
104 // wrapper for txn_begin() that logs/aborts on error
105 static void txbegin(DB_TXN **tid) {
106         int ret;
107
108         ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
109
110         if (ret) {
111                 syslog(LOG_ERR, "bdb: txn_begin: %s", db_strerror(ret));
112                 bdb_abort();
113         }
114 }
115
116
117 // panic callback
118 static void dbpanic(DB_ENV *env, int errval) {
119         syslog(LOG_ERR, "bdb: PANIC: %s", db_strerror(errval));
120         bdb_abort();
121 }
122
123
124 static void cclose(DBC *cursor) {
125         int ret;
126
127         if ((ret = cursor->c_close(cursor))) {
128                 syslog(LOG_ERR, "bdb: c_close: %s", db_strerror(ret));
129                 bdb_abort();
130         }
131 }
132
133
134 static void bailIfCursor(DBC **cursors, const char *msg) {
135         int i;
136
137         for (i = 0; i < MAXCDB; i++)
138                 if (cursors[i] != NULL) {
139                         syslog(LOG_ERR, "bdb: cursor still in progress on cdb %02x: %s", i, msg);
140                         bdb_abort();
141                 }
142 }
143
144
145 void bdb_check_handles(void) {
146         bailIfCursor(TSD->cursors, "in check_handles");
147
148         if (TSD->tid != NULL) {
149                 syslog(LOG_ERR, "bdb: transaction still in progress!");
150                 bdb_abort();
151         }
152 }
153
154
155 // Request a checkpoint of the database.  Called once per minute by the thread manager.
156 void bdb_checkpoint(void) {
157         int ret;
158
159         syslog(LOG_DEBUG, "bdb: -- checkpoint --");
160         ret = dbenv->txn_checkpoint(dbenv, MAX_CHECKPOINT_KBYTES, MAX_CHECKPOINT_MINUTES, 0);
161
162         if (ret != 0) {
163                 syslog(LOG_ERR, "bdb: bdb_checkpoint() txn_checkpoint: %s", db_strerror(ret));
164                 bdb_abort();
165         }
166
167         // After a successful checkpoint, we can cull the unused logs
168         if (CtdlGetConfigInt("c_auto_cull")) {
169                 ret = dbenv->log_set_config(dbenv, DB_LOG_AUTO_REMOVE, 1);
170         }
171         else {
172                 ret = dbenv->log_set_config(dbenv, DB_LOG_AUTO_REMOVE, 0);
173         }
174 }
175
176
177 // Open the various databases we'll be using.  Any database which
178 // does not exist should be created.  Note that we don't need a
179 // critical section here, because there aren't any active threads
180 // manipulating the database yet.
181 void bdb_open_databases(void) {
182         int ret;
183         int i;
184         char dbfilename[32];
185         u_int32_t flags = 0;
186         int dbversion_major, dbversion_minor, dbversion_patch;
187
188         syslog(LOG_DEBUG, "bdb: bdb_open_databases() starting");
189         syslog(LOG_DEBUG, "bdb:    Linked zlib: %s", zlibVersion());
190         syslog(LOG_DEBUG, "bdb: Compiled libdb: %s", DB_VERSION_STRING);
191         syslog(LOG_DEBUG, "bdb:   Linked libdb: %s", db_version(&dbversion_major, &dbversion_minor, &dbversion_patch));
192
193         // Create synthetic integer version numbers and compare them.
194         // Never allow citserver to run with a libdb older then the one with which it was compiled.
195         int compiled_db_version = ( (DB_VERSION_MAJOR * 1000000) + (DB_VERSION_MINOR * 1000) + (DB_VERSION_PATCH) );
196         int linked_db_version = ( (dbversion_major * 1000000) + (dbversion_minor * 1000) + (dbversion_patch) );
197         if (compiled_db_version > linked_db_version) {
198                 syslog(LOG_ERR, "bdb: citserver is running with a version of libdb older than the one with which it was compiled.");
199                 syslog(LOG_ERR, "bdb: This is an invalid configuration.  citserver will now exit to prevent data loss.");
200                 exit(CTDLEXIT_DB);
201         }
202
203         // Silently try to create the database subdirectory.  If it's already there, no problem.
204         if ((mkdir(ctdl_db_dir, 0700) != 0) && (errno != EEXIST)) {
205                 syslog(LOG_ERR, "bdb: database directory [%s] does not exist and could not be created: %m", ctdl_db_dir);
206                 exit(CTDLEXIT_DB);
207         }
208         if (chmod(ctdl_db_dir, 0700) != 0) {
209                 syslog(LOG_ERR, "bdb: unable to set database directory permissions [%s]: %m", ctdl_db_dir);
210                 exit(CTDLEXIT_DB);
211         }
212         if (chown(ctdl_db_dir, CTDLUID, (-1)) != 0) {
213                 syslog(LOG_ERR, "bdb: unable to set the owner for [%s]: %m", ctdl_db_dir);
214                 exit(CTDLEXIT_DB);
215         }
216         syslog(LOG_DEBUG, "bdb: Setting up DB environment");
217         ret = db_env_create(&dbenv, 0);
218         if (ret) {
219                 syslog(LOG_ERR, "bdb: db_env_create: %s", db_strerror(ret));
220                 syslog(LOG_ERR, "bdb: exit code %d", ret);
221                 exit(CTDLEXIT_DB);
222         }
223         dbenv->set_errpfx(dbenv, "citserver");
224         dbenv->set_paniccall(dbenv, dbpanic);
225         dbenv->set_errcall(dbenv, bdb_verbose_err);
226         dbenv->set_msgcall(dbenv, bdb_verbose_log);
227         dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
228         dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
229
230         // We want to specify the shared memory buffer pool cachesize, but everything else is the default.
231         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
232         if (ret) {
233                 syslog(LOG_ERR, "bdb: set_cachesize: %s", db_strerror(ret));
234                 dbenv->close(dbenv, 0);
235                 syslog(LOG_ERR, "bdb: exit code %d", ret);
236                 exit(CTDLEXIT_DB);
237         }
238
239         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
240                 syslog(LOG_ERR, "bdb: set_lk_detect: %s", db_strerror(ret));
241                 dbenv->close(dbenv, 0);
242                 syslog(LOG_ERR, "bdb: exit code %d", ret);
243                 exit(CTDLEXIT_DB);
244         }
245
246         flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD | DB_INIT_LOG;
247         syslog(LOG_DEBUG, "bdb: dbenv->open(dbenv, %s, %d, 0)", ctdl_db_dir, flags);
248         ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0);                                // try opening the database cleanly
249         if (ret == DB_RUNRECOVERY) {
250                 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
251                 syslog(LOG_ERR, "bdb: attempting recovery...");
252                 flags |= DB_RECOVER;
253                 ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0);                        // try recovery
254         }
255         if (ret == DB_RUNRECOVERY) {
256                 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
257                 syslog(LOG_ERR, "bdb: attempting catastrophic recovery...");
258                 flags &= ~DB_RECOVER;
259                 flags |= DB_RECOVER_FATAL;
260                 ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0);                        // try catastrophic recovery
261         }
262         if (ret) {
263                 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
264                 dbenv->close(dbenv, 0);
265                 syslog(LOG_ERR, "bdb: exit code %d", ret);
266                 exit(CTDLEXIT_DB);
267         }
268
269         syslog(LOG_INFO, "bdb: mounting databases");
270         for (i = 0; i < MAXCDB; ++i) {
271                 ret = db_create(&dbp[i], dbenv, 0);                                     // Create a database handle
272                 if (ret) {
273                         syslog(LOG_ERR, "bdb: db_create: %s", db_strerror(ret));
274                         syslog(LOG_ERR, "bdb: exit code %d", ret);
275                         exit(CTDLEXIT_DB);
276                 }
277
278                 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);                 // table names by number
279                 ret = dbp[i]->open(dbp[i], NULL, dbfilename, NULL, DB_BTREE, DB_CREATE | DB_AUTO_COMMIT | DB_THREAD, 0600);
280                 if (ret) {
281                         syslog(LOG_ERR, "bdb: db_open[%02x]: %s", i, db_strerror(ret));
282                         if (ret == ENOMEM) {
283                                 syslog(LOG_ERR, "bdb: You may need to tune your database; please check http://www.citadel.org for more information.");
284                         }
285                         syslog(LOG_ERR, "bdb: exit code %d", ret);
286                         exit(CTDLEXIT_DB);
287                 }
288         }
289 }
290
291
292 // Make sure we own all the files, because in a few milliseconds we're going to drop root privs.
293 void bdb_chmod_data(void) {
294         DIR *dp;
295         struct dirent *d;
296         char filename[PATH_MAX];
297
298         dp = opendir(ctdl_db_dir);
299         if (dp != NULL) {
300                 while (d = readdir(dp), d != NULL) {
301                         if (d->d_name[0] != '.') {
302                                 snprintf(filename, sizeof filename, "%s/%s", ctdl_db_dir, d->d_name);
303                                 syslog(LOG_DEBUG, "bdb: chmod(%s, 0600) returned %d", filename, chmod(filename, 0600));
304                                 syslog(LOG_DEBUG, "bdb: chown(%s, CTDLUID, -1) returned %d", filename, chown(filename, CTDLUID, (-1)));
305                         }
306                 }
307                 closedir(dp);
308         }
309 }
310
311
312 // 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.
313 void bdb_close_databases(void) {
314         int i;
315         int ret;
316
317         static int closing = 0;
318         while (closing == 1) {
319                 syslog(LOG_INFO, "bdb: already closing");
320         }
321         closing = 1;
322
323         syslog(LOG_INFO, "bdb: performing final checkpoint");
324         if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
325                 syslog(LOG_ERR, "bdb: txn_checkpoint: %s", db_strerror(ret));
326         }
327
328         syslog(LOG_INFO, "bdb: flushing the database logs");
329         if ((ret = dbenv->log_flush(dbenv, NULL))) {
330                 syslog(LOG_ERR, "bdb: log_flush: %s", db_strerror(ret));
331         }
332
333         // close the tables
334         syslog(LOG_INFO, "bdb: closing databases");
335         for (i = 0; i < MAXCDB; ++i) {
336                 syslog(LOG_INFO, "bdb: closing database %02x", i);
337                 ret = dbp[i]->close(dbp[i], 0);
338                 if (ret) {
339                         syslog(LOG_ERR, "bdb: db_close: %s", db_strerror(ret));
340                 }
341         }
342
343         // Close the handle.
344         ret = dbenv->close(dbenv, DB_FORCESYNC);
345         if (ret) {
346                 syslog(LOG_ERR, "bdb: DBENV->close: %s", db_strerror(ret));
347         }
348 }
349
350
351 // Decompress a database item if it was compressed on disk
352 void bdb_decompress_if_necessary(struct cdbdata *cdb) {
353         static int magic = COMPRESS_MAGIC;
354
355         if ((cdb == NULL) || (cdb->ptr == NULL) || (cdb->len < sizeof(magic)) || (memcmp(cdb->ptr, &magic, sizeof(magic)))) {
356                 return;
357         }
358
359         // At this point we know we're looking at a compressed item.
360
361         struct CtdlCompressHeader zheader;
362         char *uncompressed_data;
363         char *compressed_data;
364         uLongf destLen, sourceLen;
365         size_t cplen;
366
367         memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
368         cplen = sizeof(struct CtdlCompressHeader);
369         if (sizeof(struct CtdlCompressHeader) > cdb->len) {
370                 cplen = cdb->len;
371         }
372         memcpy(&zheader, cdb->ptr, cplen);
373
374         compressed_data = cdb->ptr;
375         compressed_data += sizeof(struct CtdlCompressHeader);
376
377         sourceLen = (uLongf) zheader.compressed_len;
378         destLen = (uLongf) zheader.uncompressed_len;
379         uncompressed_data = malloc(zheader.uncompressed_len);
380
381         if (uncompress((Bytef *) uncompressed_data,
382                        (uLongf *) &destLen, (const Bytef *) compressed_data, (uLong) sourceLen) != Z_OK) {
383                 syslog(LOG_ERR, "bdb: uncompress() error");
384                 bdb_abort();
385         }
386
387         free(cdb->ptr);
388         cdb->len = (size_t) destLen;
389         cdb->ptr = uncompressed_data;
390 }
391
392
393 // Store a piece of data.  Returns 0 if the operation was successful.  If a
394 // key already exists it should be overwritten.
395 int bdb_store(int cdb, const void *ckey, int ckeylen, void *cdata, int cdatalen) {
396
397         DBT dkey, ddata;
398         DB_TXN *tid = NULL;
399         int ret = 0;
400         struct CtdlCompressHeader zheader;
401         char *compressed_data = NULL;
402         int compressing = 0;
403         size_t buffer_len = 0;
404         uLongf destLen = 0;
405
406         memset(&dkey, 0, sizeof(DBT));
407         memset(&ddata, 0, sizeof(DBT));
408         dkey.size = ckeylen;
409         dkey.data = (void *) ckey;
410         ddata.size = cdatalen;
411         ddata.data = cdata;
412
413         // "visit" records are numerous and have big, mostly-empty string buffers in them.
414         // If we compress these we can get them down to 1% of their size most of the time.
415         if (cdb == CDB_VISIT) {
416                 compressing = 1;
417                 zheader.magic = COMPRESS_MAGIC;
418                 zheader.uncompressed_len = cdatalen;
419                 buffer_len = ((cdatalen * 101) / 100) + 100 + sizeof(struct CtdlCompressHeader);
420                 destLen = (uLongf) buffer_len;
421                 compressed_data = malloc(buffer_len);
422                 if (compress2((Bytef *) (compressed_data + sizeof(struct CtdlCompressHeader)), &destLen, (Bytef *) cdata, (uLongf) cdatalen, 1) != Z_OK) {
423                         syslog(LOG_ERR, "bdb: compress2() error");
424                         bdb_abort();
425                 }
426                 zheader.compressed_len = (size_t) destLen;
427                 memcpy(compressed_data, &zheader, sizeof(struct CtdlCompressHeader));
428                 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) + zheader.compressed_len);
429                 ddata.data = compressed_data;
430         }
431
432         if (TSD->tid != NULL) {
433                 ret = dbp[cdb]->put(dbp[cdb],   // db
434                                     TSD->tid,   // transaction ID
435                                     &dkey,      // key
436                                     &ddata,     // data
437                                     0           // flags
438                 );
439                 if (ret) {
440                         syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
441                         bdb_abort();
442                 }
443                 if (compressing) {
444                         free(compressed_data);
445                 }
446                 return ret;
447         }
448         else {
449                 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
450
451               retry:
452                 txbegin(&tid);
453
454                 if ((ret = dbp[cdb]->put(dbp[cdb],      // db
455                                          tid,           // transaction ID
456                                          &dkey,         // key
457                                          &ddata,        // data
458                                          0))) {         // flags
459                         if (ret == DB_LOCK_DEADLOCK) {
460                                 txabort(tid);
461                                 goto retry;
462                         }
463                         else {
464                                 syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
465                                 bdb_abort();
466                         }
467                 }
468                 else {
469                         txcommit(tid);
470                         if (compressing) {
471                                 free(compressed_data);
472                         }
473                         return ret;
474                 }
475         }
476         return ret;
477 }
478
479
480 // Delete a piece of data.  Returns 0 if the operation was successful.
481 int bdb_delete(int cdb, void *key, int keylen) {
482         DBT dkey;
483         DB_TXN *tid;
484         int ret;
485
486         memset(&dkey, 0, sizeof dkey);
487         dkey.size = keylen;
488         dkey.data = key;
489
490         if (TSD->tid != NULL) {
491                 ret = dbp[cdb]->del(dbp[cdb], TSD->tid, &dkey, 0);
492                 if (ret) {
493                         syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
494                         if (ret != DB_NOTFOUND) {
495                                 bdb_abort();
496                         }
497                 }
498         }
499         else {
500                 bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
501
502               retry:
503                 txbegin(&tid);
504
505                 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0)) && ret != DB_NOTFOUND) {
506                         if (ret == DB_LOCK_DEADLOCK) {
507                                 txabort(tid);
508                                 goto retry;
509                         }
510                         else {
511                                 syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
512                                 bdb_abort();
513                         }
514                 }
515                 else {
516                         txcommit(tid);
517                 }
518         }
519         return ret;
520 }
521
522
523 static DBC *localcursor(int cdb) {
524         int ret;
525         DBC *curs;
526
527         if (TSD->cursors[cdb] == NULL) {
528                 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &curs, 0);
529         }
530         else {
531                 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
532         }
533
534         if (ret) {
535                 syslog(LOG_ERR, "bdb: localcursor: %s", db_strerror(ret));
536                 bdb_abort();
537         }
538
539         return curs;
540 }
541
542
543 // Fetch a piece of data.  If not found, returns NULL.  Otherwise, it returns
544 // a struct cdbdata which it is the caller's responsibility to free later on
545 // using the bdb_free() routine.
546 struct cdbdata *bdb_fetch(int cdb, const void *key, int keylen) {
547
548         if (keylen == 0) {              // key length zero is impossible
549                 return(NULL);
550         }
551
552         struct cdbdata *tempcdb;
553         DBT dkey, dret;
554         int ret;
555
556         memset(&dkey, 0, sizeof(DBT));
557         dkey.size = keylen;
558         dkey.data = (void *) key;
559
560         if (TSD->tid != NULL) {
561                 memset(&dret, 0, sizeof(DBT));
562                 dret.flags = DB_DBT_MALLOC;
563                 ret = dbp[cdb]->get(dbp[cdb], TSD->tid, &dkey, &dret, 0);
564         }
565         else {
566                 DBC *curs;
567
568                 do {
569                         memset(&dret, 0, sizeof(DBT));
570                         dret.flags = DB_DBT_MALLOC;
571                         curs = localcursor(cdb);
572                         ret = curs->c_get(curs, &dkey, &dret, DB_SET);
573                         cclose(curs);
574                 } while (ret == DB_LOCK_DEADLOCK);
575         }
576
577         if ((ret != 0) && (ret != DB_NOTFOUND)) {
578                 syslog(LOG_ERR, "bdb: bdb_fetch(%d): %s", cdb, db_strerror(ret));
579                 bdb_abort();
580         }
581
582         if (ret != 0) {
583                 return NULL;
584         }
585
586         tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
587         if (tempcdb == NULL) {
588                 syslog(LOG_ERR, "bdb: bdb_fetch() cannot allocate memory for tempcdb: %m");
589                 bdb_abort();
590         }
591         else {
592                 tempcdb->len = dret.size;
593                 tempcdb->ptr = dret.data;
594                 bdb_decompress_if_necessary(tempcdb);
595                 return (tempcdb);
596         }
597 }
598
599
600 // Free a cdbdata item.
601 //
602 // Note that we only free the 'ptr' portion if it is not NULL.  This allows
603 // other code to assume ownership of that memory simply by storing the
604 // pointer elsewhere and then setting 'ptr' to NULL.  bdb_free() will then
605 // avoid freeing it.
606 void bdb_free(struct cdbdata *cdb) {
607         if (cdb->ptr) {
608                 free(cdb->ptr);
609         }
610         free(cdb);
611 }
612
613
614 void bdb_close_cursor(int cdb) {
615         if (TSD->cursors[cdb] != NULL) {
616                 cclose(TSD->cursors[cdb]);
617         }
618
619         TSD->cursors[cdb] = NULL;
620 }
621
622
623 // Prepare for a sequential search of an entire database.
624 // (There is guaranteed to be no more than one traversal in
625 // progress per thread at any given time.)
626 void bdb_rewind(int cdb) {
627         int ret = 0;
628
629         if (TSD->cursors[cdb] != NULL) {
630                 syslog(LOG_ERR, "bdb: bdb_rewind: must close cursor on database %d before reopening", cdb);
631                 bdb_abort();
632                 // cclose(TSD->cursors[cdb]);
633         }
634
635         // Now initialize the cursor
636         ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &TSD->cursors[cdb], 0);
637         if (ret) {
638                 syslog(LOG_ERR, "bdb: bdb_rewind: db_cursor: %s", db_strerror(ret));
639                 bdb_abort();
640         }
641 }
642
643
644 // Fetch the next item in a sequential search.  Returns a pointer to a 
645 // cdbdata structure, or NULL if we've hit the end.
646 struct cdbdata *bdb_next_item(int cdb) {
647         DBT key, data;
648         struct cdbdata *cdbret;
649         int ret = 0;
650
651         // Initialize the key/data pair so the flags aren't set.
652         memset(&key, 0, sizeof(key));
653         memset(&data, 0, sizeof(data));
654         data.flags = DB_DBT_MALLOC;
655
656         ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &key, &data, DB_NEXT);
657
658         if (ret) {
659                 if (ret != DB_NOTFOUND) {
660                         syslog(LOG_ERR, "bdb: bdb_next_item(%d): %s", cdb, db_strerror(ret));
661                         bdb_abort();
662                 }
663                 bdb_close_cursor(cdb);
664                 return NULL;    // presumably, end of file
665         }
666
667         cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
668         cdbret->len = data.size;
669         cdbret->ptr = data.data;
670         bdb_decompress_if_necessary(cdbret);
671
672         return (cdbret);
673 }
674
675
676 // Transaction-based stuff.  I'm writing this as I bake cookies...
677 void bdb_begin_transaction(void) {
678         bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
679
680         if (TSD->tid != NULL) {
681                 syslog(LOG_ERR, "bdb: bdb_begin_transaction: ERROR: nested transaction");
682                 bdb_abort();
683         }
684
685         txbegin(&TSD->tid);
686 }
687
688
689 void bdb_end_transaction(void) {
690         int i;
691
692         for (i = 0; i < MAXCDB; i++) {
693                 if (TSD->cursors[i] != NULL) {
694                         syslog(LOG_WARNING, "bdb: bdb_end_transaction: WARNING: cursor %d still open at transaction end", i);
695                         cclose(TSD->cursors[i]);
696                         TSD->cursors[i] = NULL;
697                 }
698         }
699
700         if (TSD->tid == NULL) {
701                 syslog(LOG_ERR, "bdb: bdb_end_transaction: ERROR: txcommit(NULL) !!");
702                 bdb_abort();
703         }
704         else {
705                 txcommit(TSD->tid);
706         }
707
708         TSD->tid = NULL;
709 }
710
711
712 // Truncate (delete every record)
713 void bdb_trunc(int cdb) {
714         int ret;
715         u_int32_t count;
716
717         if (TSD->tid != NULL) {
718                 syslog(LOG_ERR, "bdb: bdb_trunc must not be called in a transaction.");
719                 bdb_abort();
720         }
721         else {
722                 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
723
724               retry:
725
726                 if ((ret = dbp[cdb]->truncate(dbp[cdb], // db
727                                               NULL,     // transaction ID
728                                               &count,   // #rows deleted
729                                               0))) {    // flags
730                         if (ret == DB_LOCK_DEADLOCK) {
731                                 goto retry;
732                         }
733                         else {
734                                 syslog(LOG_ERR, "bdb: bdb_truncate(%d): %s", cdb, db_strerror(ret));
735                                 if (ret == ENOMEM) {
736                                         syslog(LOG_ERR, "bdb: You may need to tune your database; please read http://www.citadel.org for more information.");
737                                 }
738                                 exit(CTDLEXIT_DB);
739                         }
740                 }
741         }
742 }
743
744
745 // compact (defragment) the database, possibly returning space back to the underlying filesystem
746 void bdb_compact(void) {
747         int ret;
748         int i;
749
750         syslog(LOG_DEBUG, "bdb: bdb_compact() started");
751         for (i = 0; i < MAXCDB; i++) {
752                 syslog(LOG_DEBUG, "bdb: compacting database %d", i);
753                 ret = dbp[i]->compact(dbp[i], NULL, NULL, NULL, NULL, DB_FREE_SPACE, NULL);
754                 if (ret) {
755                         syslog(LOG_ERR, "bdb: compact: %s", db_strerror(ret));
756                 }
757         }
758         syslog(LOG_DEBUG, "bdb: bdb_compact() finished");
759 }
760
761
762 // Calling this function activates the Berkeley DB back end.
763 void bdb_init_backend(void) {
764         cdb_compact = bdb_compact;
765         cdb_checkpoint = bdb_checkpoint;
766         cdb_rewind = bdb_rewind;
767         cdb_fetch = bdb_fetch;
768         cdb_open_databases = bdb_open_databases;
769         cdb_close_databases = bdb_close_databases;
770         cdb_store = bdb_store;
771         cdb_delete = bdb_delete;
772         cdb_free = bdb_free;
773         cdb_next_item = bdb_next_item;
774         cdb_close_cursor = bdb_close_cursor;
775         cdb_begin_transaction = bdb_begin_transaction;
776         cdb_end_transaction = bdb_end_transaction;
777         cdb_check_handles = bdb_check_handles;
778         cdb_trunc = bdb_trunc;
779         cdb_chmod_data = bdb_chmod_data;
780
781         syslog(LOG_INFO, "db: initialized Berkeley DB backend");
782 }
783
784
785 // This will get split out into a separate file.  It will act as a marshal for multiple database backends.
786 void cdb_init_backends(void) {
787         bdb_init_backend();             // For now, Berkeley DB is the only backend, so we always initialize it.
788 }