Revert "Changed the API for cdb_rewind() / cdb_next_item() to make the caller hold...
[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 <sys/stat.h>
16 #include <stdio.h>
17 #include <dirent.h>
18 #include <zlib.h>
19 #include <db.h>
20 #include <libcitadel.h>
21 #include "../../citserver.h"
22 #include "../../config.h"
23 #include "berkeley_db.h"
24
25 #if DB_VERSION_MAJOR < 18
26 #error Citadel requires Berkeley DB v18.0 or newer.  Please upgrade.
27 #endif
28
29
30 static DB *dbp[MAXCDB];         // One DB handle for each Citadel database
31 static DB_ENV *dbenv;           // The DB environment (global)
32
33
34 // Called by other functions in this module to GTFO quickly if we need to.  Not part of the backend API.
35 void bdb_abort(void) {
36         syslog(LOG_DEBUG, "bdb: citserver is stopping in order to prevent data loss. uid=%d gid=%d euid=%d egid=%d",
37                 getuid(), getgid(), geteuid(), getegid()
38         );
39         raise(SIGABRT);         // This will exit in a way that can produce a core dump if needed.
40         exit(CTDLEXIT_DB);      // Exit if the signal failed to end the program.
41 }
42
43
44 // Verbose logging callback for Berkeley DB.  Not part of the backend API.
45 void bdb_verbose_log(const DB_ENV *dbenv, const char *msg, const char *foo) {
46         if (!IsEmptyStr(msg)) {
47                 syslog(LOG_DEBUG, "bdb: %s %s", msg, foo);
48         }
49 }
50
51
52 // Verbose error logging callback for Berkeley DB.  Not part of the backend API.
53 void bdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg) {
54         syslog(LOG_ERR, "bdb: %s", msg);
55 }
56
57
58 // Wrapper for txn_abort() that logs/aborts on error.  Not part of the backend API.
59 static void bdb_txabort(DB_TXN *tid) {
60         int ret;
61
62         ret = tid->abort(tid);
63
64         if (ret) {
65                 syslog(LOG_ERR, "bdb: txn_abort: %s", db_strerror(ret));
66                 bdb_abort();
67         }
68 }
69
70
71 // Wrapper for txn_commit() that logs/aborts on error.  Not part of the backend API.
72 static void bdb_txcommit(DB_TXN *tid) {
73         int ret;
74
75         ret = tid->commit(tid, 0);
76
77         if (ret) {
78                 syslog(LOG_ERR, "bdb: txn_commit: %s", db_strerror(ret));
79                 bdb_abort();
80         }
81 }
82
83
84 // Wrapper for txn_begin() that logs/aborts on error.  Not part of the backend API.
85 static void bdb_txbegin(DB_TXN **tid) {
86         int ret;
87
88         ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
89
90         if (ret) {
91                 syslog(LOG_ERR, "bdb: txn_begin: %s", db_strerror(ret));
92                 bdb_abort();
93         }
94 }
95
96
97 // Panic callback for Berkeley DB.  Not part of the backend API.
98 static void bdb_dbpanic(DB_ENV *env, int errval) {
99         syslog(LOG_ERR, "bdb: PANIC: %s", db_strerror(errval));
100         bdb_abort();
101 }
102
103
104 // Close a cursor -- not part of the backend API.
105 static void bdb_cclose(DBC *cursor) {
106         int ret;
107
108         if ((ret = cursor->c_close(cursor))) {
109                 syslog(LOG_ERR, "bdb: c_close: %s", db_strerror(ret));
110                 bdb_abort();
111         }
112 }
113
114
115 // Convenience function to abort if a cursor is still open when we didn't expect it to be.
116 // This is not part of the backend API.
117 static void bdb_bailIfCursor(DBC **cursors, const char *msg) {
118         int i;
119
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);
123                         bdb_abort();
124                 }
125 }
126
127
128 void bdb_check_handles(void) {
129         bdb_bailIfCursor(TSD->cursors, "in check_handles");
130
131         if (TSD->tid != NULL) {
132                 syslog(LOG_ERR, "bdb: transaction still in progress!");
133                 bdb_abort();
134         }
135 }
136
137
138 // Request a checkpoint of the database.  Called once per minute by the thread manager.
139 void bdb_checkpoint(void) {
140         int ret;
141
142         syslog(LOG_DEBUG, "bdb: -- checkpoint --");
143         ret = dbenv->txn_checkpoint(dbenv, MAX_CHECKPOINT_KBYTES, MAX_CHECKPOINT_MINUTES, 0);
144
145         if (ret != 0) {
146                 syslog(LOG_ERR, "bdb: bdb_checkpoint() txn_checkpoint: %s", db_strerror(ret));
147                 bdb_abort();
148         }
149
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);
153         }
154         else {
155                 ret = dbenv->log_set_config(dbenv, DB_LOG_AUTO_REMOVE, 0);
156         }
157 }
158
159
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) {
165         int ret;
166         int i;
167         char dbfilename[32];
168         u_int32_t flags = 0;
169         int dbversion_major, dbversion_minor, dbversion_patch;
170
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));
175
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.");
183                 exit(CTDLEXIT_DB);
184         }
185
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);
189                 exit(CTDLEXIT_DB);
190         }
191         if (chmod(ctdl_db_dir, 0700) != 0) {
192                 syslog(LOG_ERR, "bdb: unable to set database directory permissions [%s]: %m", ctdl_db_dir);
193                 exit(CTDLEXIT_DB);
194         }
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);
197                 exit(CTDLEXIT_DB);
198         }
199         syslog(LOG_DEBUG, "bdb: Setting up DB environment");
200         ret = db_env_create(&dbenv, 0);
201         if (ret) {
202                 syslog(LOG_ERR, "bdb: db_env_create: %s", db_strerror(ret));
203                 syslog(LOG_ERR, "bdb: exit code %d", ret);
204                 exit(CTDLEXIT_DB);
205         }
206         dbenv->set_errpfx(dbenv, "citserver");
207         dbenv->set_paniccall(dbenv, bdb_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);
212
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);
215         if (ret) {
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);
219                 exit(CTDLEXIT_DB);
220         }
221
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);
226                 exit(CTDLEXIT_DB);
227         }
228
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...");
235                 flags |= DB_RECOVER;
236                 ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0);                        // try recovery
237         }
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
244         }
245         if (ret) {
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);
249                 exit(CTDLEXIT_DB);
250         }
251
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
255                 if (ret) {
256                         syslog(LOG_ERR, "bdb: db_create: %s", db_strerror(ret));
257                         syslog(LOG_ERR, "bdb: exit code %d", ret);
258                         exit(CTDLEXIT_DB);
259                 }
260
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);
263                 if (ret) {
264                         syslog(LOG_ERR, "bdb: db_open[%02x]: %s", i, db_strerror(ret));
265                         if (ret == ENOMEM) {
266                                 syslog(LOG_ERR, "bdb: You may need to tune your database; please check http://www.citadel.org for more information.");
267                         }
268                         syslog(LOG_ERR, "bdb: exit code %d", ret);
269                         exit(CTDLEXIT_DB);
270                 }
271         }
272 }
273
274
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) {
277         DIR *dp;
278         struct dirent *d;
279         char filename[PATH_MAX];
280
281         dp = opendir(ctdl_db_dir);
282         if (dp != NULL) {
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)));
288                         }
289                 }
290                 closedir(dp);
291         }
292 }
293
294
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) {
297         int i;
298         int ret;
299
300         static int closing = 0;
301         while (closing == 1) {
302                 syslog(LOG_INFO, "bdb: already closing");
303         }
304         closing = 1;
305
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));
309         }
310
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));
314         }
315
316         // close the tables
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);
321                 if (ret) {
322                         syslog(LOG_ERR, "bdb: db_close: %s", db_strerror(ret));
323                 }
324         }
325
326         // Close the handle.
327         ret = dbenv->close(dbenv, DB_FORCESYNC);
328         if (ret) {
329                 syslog(LOG_ERR, "bdb: DBENV->close: %s", db_strerror(ret));
330         }
331 }
332
333
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;
337
338         if ((cdb == NULL) || (cdb->ptr == NULL) || (cdb->len < sizeof(magic)) || (memcmp(cdb->ptr, &magic, sizeof(magic)))) {
339                 return;
340         }
341
342         // At this point we know we're looking at a compressed item.
343
344         struct CtdlCompressHeader zheader;
345         char *uncompressed_data;
346         char *compressed_data;
347         uLongf destLen, sourceLen;
348         size_t cplen;
349
350         memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
351         cplen = sizeof(struct CtdlCompressHeader);
352         if (sizeof(struct CtdlCompressHeader) > cdb->len) {
353                 cplen = cdb->len;
354         }
355         memcpy(&zheader, cdb->ptr, cplen);
356
357         compressed_data = cdb->ptr;
358         compressed_data += sizeof(struct CtdlCompressHeader);
359
360         sourceLen = (uLongf) zheader.compressed_len;
361         destLen = (uLongf) zheader.uncompressed_len;
362         uncompressed_data = malloc(zheader.uncompressed_len);
363
364         if (uncompress((Bytef *) uncompressed_data,
365                        (uLongf *) &destLen, (const Bytef *) compressed_data, (uLong) sourceLen) != Z_OK) {
366                 syslog(LOG_ERR, "bdb: uncompress() error");
367                 bdb_abort();
368         }
369
370         free(cdb->ptr);
371         cdb->len = (size_t) destLen;
372         cdb->ptr = uncompressed_data;
373 }
374
375
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) {
379
380         DBT dkey, ddata;
381         DB_TXN *tid = NULL;
382         int ret = 0;
383         struct CtdlCompressHeader zheader;
384         char *compressed_data = NULL;
385         int compressing = 0;
386         size_t buffer_len = 0;
387         uLongf destLen = 0;
388
389         memset(&dkey, 0, sizeof(DBT));
390         memset(&ddata, 0, sizeof(DBT));
391         dkey.size = ckeylen;
392         dkey.data = (void *) ckey;
393         ddata.size = cdatalen;
394         ddata.data = cdata;
395
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) {
399                 compressing = 1;
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");
407                         bdb_abort();
408                 }
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;
413         }
414
415         if (TSD->tid != NULL) {
416                 ret = dbp[cdb]->put(dbp[cdb],   // db
417                                     TSD->tid,   // transaction ID
418                                     &dkey,      // key
419                                     &ddata,     // data
420                                     0           // flags
421                 );
422                 if (ret) {
423                         syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
424                         bdb_abort();
425                 }
426                 if (compressing) {
427                         free(compressed_data);
428                 }
429                 return ret;
430         }
431         else {
432                 bdb_bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
433
434               retry:
435                 bdb_txbegin(&tid);
436
437                 if ((ret = dbp[cdb]->put(dbp[cdb],      // db
438                                          tid,           // transaction ID
439                                          &dkey,         // key
440                                          &ddata,        // data
441                                          0))) {         // flags
442                         if (ret == DB_LOCK_DEADLOCK) {
443                                 bdb_txabort(tid);
444                                 goto retry;
445                         }
446                         else {
447                                 syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
448                                 bdb_abort();
449                         }
450                 }
451                 else {
452                         bdb_txcommit(tid);
453                         if (compressing) {
454                                 free(compressed_data);
455                         }
456                         return ret;
457                 }
458         }
459         return ret;
460 }
461
462
463 // Delete a piece of data.  Returns 0 if the operation was successful.
464 int bdb_delete(int cdb, void *key, int keylen) {
465         DBT dkey;
466         DB_TXN *tid;
467         int ret;
468
469         memset(&dkey, 0, sizeof dkey);
470         dkey.size = keylen;
471         dkey.data = key;
472
473         if (TSD->tid != NULL) {
474                 ret = dbp[cdb]->del(dbp[cdb], TSD->tid, &dkey, 0);
475                 if (ret) {
476                         syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
477                         if (ret != DB_NOTFOUND) {
478                                 bdb_abort();
479                         }
480                 }
481         }
482         else {
483                 bdb_bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
484
485               retry:
486                 bdb_txbegin(&tid);
487
488                 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0)) && ret != DB_NOTFOUND) {
489                         if (ret == DB_LOCK_DEADLOCK) {
490                                 bdb_txabort(tid);
491                                 goto retry;
492                         }
493                         else {
494                                 syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
495                                 bdb_abort();
496                         }
497                 }
498                 else {
499                         bdb_txcommit(tid);
500                 }
501         }
502         return ret;
503 }
504
505
506 static DBC *bdb_localcursor(int cdb) {
507         int ret;
508         DBC *curs;
509
510         if (TSD->cursors[cdb] == NULL) {
511                 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &curs, 0);
512         }
513         else {
514                 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
515         }
516
517         if (ret) {
518                 syslog(LOG_ERR, "bdb: bdb_localcursor: %s", db_strerror(ret));
519                 bdb_abort();
520         }
521
522         return curs;
523 }
524
525
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) {
530
531         if (keylen == 0) {              // key length zero is impossible
532                 return(NULL);
533         }
534
535         struct cdbdata *tempcdb;
536         DBT dkey, dret;
537         int ret;
538
539         memset(&dkey, 0, sizeof(DBT));
540         dkey.size = keylen;
541         dkey.data = (void *) key;
542
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);
547         }
548         else {
549                 DBC *curs;
550
551                 do {
552                         memset(&dret, 0, sizeof(DBT));
553                         dret.flags = DB_DBT_MALLOC;
554                         curs = bdb_localcursor(cdb);
555                         ret = curs->c_get(curs, &dkey, &dret, DB_SET);
556                         bdb_cclose(curs);
557                 } while (ret == DB_LOCK_DEADLOCK);
558         }
559
560         if ((ret != 0) && (ret != DB_NOTFOUND)) {
561                 syslog(LOG_ERR, "bdb: bdb_fetch(%d): %s", cdb, db_strerror(ret));
562                 bdb_abort();
563         }
564
565         if (ret != 0) {
566                 return NULL;
567         }
568
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");
572                 bdb_abort();
573         }
574         else {
575                 tempcdb->len = dret.size;
576                 tempcdb->ptr = dret.data;
577                 bdb_decompress_if_necessary(tempcdb);
578                 return (tempcdb);
579         }
580 }
581
582
583 // Free a cdbdata item.
584 //
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
588 // avoid freeing it.
589 void bdb_free(struct cdbdata *cdb) {
590         if (cdb->ptr) {
591                 free(cdb->ptr);
592         }
593         free(cdb);
594 }
595
596
597 void bdb_close_cursor(int cdb) {
598         if (TSD->cursors[cdb] != NULL) {
599                 bdb_cclose(TSD->cursors[cdb]);
600         }
601
602         TSD->cursors[cdb] = NULL;
603 }
604
605
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) {
610         int ret = 0;
611
612         if (TSD->cursors[cdb] != NULL) {
613                 syslog(LOG_ERR, "bdb: bdb_rewind: must close cursor on database %d before reopening", cdb);
614                 bdb_abort();
615                 // bdb_cclose(TSD->cursors[cdb]);
616         }
617
618         // Now initialize the cursor
619         ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &TSD->cursors[cdb], 0);
620         if (ret) {
621                 syslog(LOG_ERR, "bdb: bdb_rewind: db_cursor: %s", db_strerror(ret));
622                 bdb_abort();
623         }
624 }
625
626
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) {
630         DBT key, data;
631         struct cdbdata *cdbret;
632         int ret = 0;
633
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;
638
639         ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &key, &data, DB_NEXT);
640
641         if (ret) {
642                 if (ret != DB_NOTFOUND) {
643                         syslog(LOG_ERR, "bdb: bdb_next_item(%d): %s", cdb, db_strerror(ret));
644                         bdb_abort();
645                 }
646                 bdb_close_cursor(cdb);
647                 return NULL;    // presumably, end of file
648         }
649
650         cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
651         cdbret->len = data.size;
652         cdbret->ptr = data.data;
653         bdb_decompress_if_necessary(cdbret);
654
655         return (cdbret);
656 }
657
658
659 // Transaction-based stuff.  I'm writing this as I bake cookies...
660 void bdb_begin_transaction(void) {
661         bdb_bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
662
663         if (TSD->tid != NULL) {
664                 syslog(LOG_ERR, "bdb: bdb_begin_transaction: ERROR: nested transaction");
665                 bdb_abort();
666         }
667
668         bdb_txbegin(&TSD->tid);
669 }
670
671
672 void bdb_end_transaction(void) {
673         int i;
674
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                         bdb_cclose(TSD->cursors[i]);
679                         TSD->cursors[i] = NULL;
680                 }
681         }
682
683         if (TSD->tid == NULL) {
684                 syslog(LOG_ERR, "bdb: bdb_end_transaction: ERROR: bdb_txcommit(NULL) !!");
685                 bdb_abort();
686         }
687         else {
688                 bdb_txcommit(TSD->tid);
689         }
690
691         TSD->tid = NULL;
692 }
693
694
695 // Truncate (delete every record)
696 void bdb_trunc(int cdb) {
697         int ret;
698         u_int32_t count;
699
700         if (TSD->tid != NULL) {
701                 syslog(LOG_ERR, "bdb: bdb_trunc must not be called in a transaction.");
702                 bdb_abort();
703         }
704         else {
705                 bdb_bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
706
707               retry:
708
709                 if ((ret = dbp[cdb]->truncate(dbp[cdb], // db
710                                               NULL,     // transaction ID
711                                               &count,   // #rows deleted
712                                               0))) {    // flags
713                         if (ret == DB_LOCK_DEADLOCK) {
714                                 goto retry;
715                         }
716                         else {
717                                 syslog(LOG_ERR, "bdb: bdb_truncate(%d): %s", cdb, db_strerror(ret));
718                                 if (ret == ENOMEM) {
719                                         syslog(LOG_ERR, "bdb: You may need to tune your database; please read http://www.citadel.org for more information.");
720                                 }
721                                 exit(CTDLEXIT_DB);
722                         }
723                 }
724         }
725 }
726
727
728 // compact (defragment) the database, possibly returning space back to the underlying filesystem
729 void bdb_compact(void) {
730         int ret;
731         int i;
732
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);
737                 if (ret) {
738                         syslog(LOG_ERR, "bdb: compact: %s", db_strerror(ret));
739                 }
740         }
741         syslog(LOG_DEBUG, "bdb: bdb_compact() finished");
742 }
743
744
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;
755         cdb_free = bdb_free;
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;
763
764         syslog(LOG_INFO, "db: initialized Berkeley DB backend");
765 }
766
767