ctdldump: use the backend API instead of BDB calls
[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 <zlib.h>
18 #include <db.h>
19 #include <assert.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 // Globals (these are used across multiple functions in *this* module, but not elsewhere)
30 static DB *bdb_table[MAXCDB];   // One DB handle for each Citadel database
31 static DB_ENV *bdb_env;         // The DB environment (global)
32
33
34 // These are items that we need to store "per thread" rather than "per session".
35 struct bdb_tsd {
36         DB_TXN *tid;            // Transaction handle
37         DBC *cursors[MAXCDB];   // Cursors, for traversals...
38         DBT dbkey[MAXCDB];
39         DBT dbdata[MAXCDB];
40 };
41
42
43 pthread_key_t bdb_thread_key;
44 #define TSD bdb_get_tsd()
45
46
47 // Some functions in this backend need to store some per-thread data.
48 // This returns the pointer to the current thread's per-thread data block, creating it if necessary.
49 // (This will also work in a non-threaded program; it will return the same pointer every time.)
50 struct bdb_tsd *bdb_get_tsd(void) {
51
52         struct bdb_tsd *c = (struct bdb_tsd *) pthread_getspecific(bdb_thread_key) ;
53         if (c != NULL) {
54                 return(c);              // Got it.
55         }
56
57         // If there's no TSD for this thread, it must be a new thread.  Create our TSD region.
58         c = (struct bdb_tsd *) malloc(sizeof(struct bdb_tsd));
59         memset(c, 0, sizeof(struct bdb_tsd));
60         pthread_setspecific(bdb_thread_key, (const void *) c);
61         return(c);
62 }
63
64
65 // Called by other functions in this module to GTFO quickly if we need to.  Not part of the backend API.
66 void bdb_abort(void) {
67         syslog(LOG_DEBUG, "bdb: citserver is stopping in order to prevent data loss. uid=%d gid=%d euid=%d egid=%d",
68                 getuid(), getgid(), geteuid(), getegid()
69         );
70         raise(SIGABRT);         // This will exit in a way that can produce a core dump if needed.
71         exit(CTDLEXIT_DB);      // Exit if the signal failed to end the program.
72 }
73
74
75 // Verbose logging callback for Berkeley DB.  Not part of the backend API.
76 void bdb_verbose_log(const DB_ENV *bdb_env, const char *msg, const char *foo) {
77         if (!IsEmptyStr(msg)) {
78                 syslog(LOG_DEBUG, "bdb: %s %s", msg, foo);
79         }
80 }
81
82
83 // Verbose error logging callback for Berkeley DB.  Not part of the backend API.
84 void bdb_verbose_err(const DB_ENV *bdb_env, const char *errpfx, const char *msg) {
85         syslog(LOG_ERR, "bdb: %s", msg);
86 }
87
88
89 // Wrapper for txn_abort() that logs/aborts on error.  Not part of the backend API.
90 static void bdb_txabort(DB_TXN *tid) {
91         int ret;
92
93         ret = tid->abort(tid);
94
95         if (ret) {
96                 syslog(LOG_ERR, "bdb: txn_abort: %s", db_strerror(ret));
97                 bdb_abort();
98         }
99 }
100
101
102 // Wrapper for txn_commit() that logs/aborts on error.  Not part of the backend API.
103 static void bdb_txcommit(DB_TXN *tid) {
104         int ret;
105
106         ret = tid->commit(tid, 0);
107
108         if (ret) {
109                 syslog(LOG_ERR, "bdb: txn_commit: %s", db_strerror(ret));
110                 bdb_abort();
111         }
112 }
113
114
115 // Wrapper for txn_begin() that logs/aborts on error.  Not part of the backend API.
116 static void bdb_txbegin(DB_TXN **tid) {
117         int ret;
118
119         ret = bdb_env->txn_begin(bdb_env, NULL, tid, 0);
120
121         if (ret) {
122                 syslog(LOG_ERR, "bdb: txn_begin: %s", db_strerror(ret));
123                 bdb_abort();
124         }
125 }
126
127
128 // Panic callback for Berkeley DB.  Not part of the backend API.
129 static void bdb_dbpanic(DB_ENV *env, int errval) {
130         syslog(LOG_ERR, "bdb: PANIC: %s", db_strerror(errval));
131         bdb_abort();
132 }
133
134
135 // Close a cursor -- not part of the backend API.
136 static void bdb_cclose(DBC *cursor) {
137         int ret;
138
139         if ((ret = cursor->c_close(cursor))) {
140                 syslog(LOG_ERR, "bdb: c_close: %s", db_strerror(ret));
141                 bdb_abort();
142         }
143 }
144
145
146 // Convenience function to abort if a cursor is still open when we didn't expect it to be.
147 // This is not part of the backend API.
148 static void bdb_bailIfCursor(DBC **cursors, const char *msg) {
149         int i;
150
151         for (i = 0; i < MAXCDB; i++)
152                 if (cursors[i] != NULL) {
153                         syslog(LOG_ERR, "bdb: cursor still in progress on cdb %02x: %s", i, msg);
154                         bdb_abort();
155                 }
156 }
157
158
159 void bdb_check_handles(void) {
160         bdb_bailIfCursor(TSD->cursors, "in check_handles");
161
162         if (TSD->tid != NULL) {
163                 syslog(LOG_ERR, "bdb: transaction still in progress!");
164                 bdb_abort();
165         }
166 }
167
168
169 // Request a checkpoint of the database.  Called once per minute by the thread manager.
170 void bdb_checkpoint(void) {
171         int ret;
172
173         syslog(LOG_DEBUG, "bdb: -- checkpoint --");
174         ret = bdb_env->txn_checkpoint(bdb_env, MAX_CHECKPOINT_KBYTES, MAX_CHECKPOINT_MINUTES, 0);
175
176         if (ret != 0) {
177                 syslog(LOG_ERR, "bdb: bdb_checkpoint() txn_checkpoint: %s", db_strerror(ret));
178                 bdb_abort();
179         }
180
181         // After a successful checkpoint, we can cull the unused logs
182         ret = bdb_env->log_set_config(bdb_env, DB_LOG_AUTO_REMOVE, 1);
183         if (ret != 0) {
184                 syslog(LOG_ERR, "bdb: bdb_checkpoint() auto coll logs: %s", db_strerror(ret));
185         }
186 }
187
188
189 // Open the various tables we'll be using.  Any table which
190 // does not exist should be created.  Note that we don't need a
191 // critical section here, because there aren't any active threads
192 // manipulating the database yet.
193 void bdb_open_databases(void) {
194         int ret;
195         int i;
196         char dbfilename[32];
197         u_int32_t flags = 0;
198         int dbversion_major, dbversion_minor, dbversion_patch;
199
200         syslog(LOG_DEBUG, "bdb: bdb_open_databases() starting");
201         syslog(LOG_DEBUG, "bdb:    Linked zlib: %s", zlibVersion());
202         syslog(LOG_DEBUG, "bdb: Compiled libdb: %s", DB_VERSION_STRING);
203         syslog(LOG_DEBUG, "bdb:   Linked libdb: %s", db_version(&dbversion_major, &dbversion_minor, &dbversion_patch));
204
205         // Create synthetic integer version numbers and compare them.
206         // Never allow citserver to run with a libdb older then the one with which it was compiled.
207         int compiled_db_version = ( (DB_VERSION_MAJOR * 1000000) + (DB_VERSION_MINOR * 1000) + (DB_VERSION_PATCH) );
208         int linked_db_version = ( (dbversion_major * 1000000) + (dbversion_minor * 1000) + (dbversion_patch) );
209         if (compiled_db_version > linked_db_version) {
210                 syslog(LOG_ERR, "bdb: citserver is running with a version of libdb older than the one with which it was compiled.");
211                 syslog(LOG_ERR, "bdb: This is an invalid configuration.  citserver will now exit to prevent data loss.");
212                 exit(CTDLEXIT_DB);
213         }
214
215         syslog(LOG_DEBUG, "bdb: Setting up DB environment");
216         ret = db_env_create(&bdb_env, 0);
217         if (ret) {
218                 syslog(LOG_ERR, "bdb: db_env_create: %s", db_strerror(ret));
219                 syslog(LOG_ERR, "bdb: exit code %d", ret);
220                 exit(CTDLEXIT_DB);
221         }
222         bdb_env->set_errpfx(bdb_env, "citserver");
223         bdb_env->set_paniccall(bdb_env, bdb_dbpanic);
224         bdb_env->set_errcall(bdb_env, bdb_verbose_err);
225         bdb_env->set_msgcall(bdb_env, bdb_verbose_log);
226         bdb_env->set_verbose(bdb_env, DB_VERB_DEADLOCK, 1);
227         bdb_env->set_verbose(bdb_env, DB_VERB_RECOVERY, 1);
228
229         // We want to specify the shared memory buffer pool cachesize, but everything else is the default.
230         // 2023aug21 ajc: the third argument is zero, so this never did anything
231         // ret = bdb_env->set_cachesize(bdb_env, 0, 64 * 1024, 0);
232         // if (ret) {
233                 // syslog(LOG_ERR, "bdb: set_cachesize: %s", db_strerror(ret));
234                 // bdb_env->close(bdb_env, 0);
235                 // syslog(LOG_ERR, "bdb: exit code %d", ret);
236                 // exit(CTDLEXIT_DB);
237         // }
238
239         if ((ret = bdb_env->set_lk_detect(bdb_env, DB_LOCK_DEFAULT))) {
240                 syslog(LOG_ERR, "bdb: set_lk_detect: %s", db_strerror(ret));
241                 bdb_env->close(bdb_env, 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: bdb_env->open(bdb_env, %s, %d, 0)", ctdl_db_dir, flags);
248         ret = bdb_env->open(bdb_env, ctdl_db_dir, flags, 0);                            // try opening the database cleanly
249         if (ret == DB_RUNRECOVERY) {
250                 syslog(LOG_ERR, "bdb: bdb_env->open: %s", db_strerror(ret));
251                 syslog(LOG_ERR, "bdb: attempting recovery...");
252                 flags |= DB_RECOVER;
253                 ret = bdb_env->open(bdb_env, ctdl_db_dir, flags, 0);                    // try recovery
254         }
255         if (ret == DB_RUNRECOVERY) {
256                 syslog(LOG_ERR, "bdb: bdb_env->open: %s", db_strerror(ret));
257                 syslog(LOG_ERR, "bdb: attempting catastrophic recovery...");
258                 flags &= ~DB_RECOVER;
259                 flags |= DB_RECOVER_FATAL;
260                 ret = bdb_env->open(bdb_env, ctdl_db_dir, flags, 0);                    // try catastrophic recovery
261         }
262         if (ret) {
263                 syslog(LOG_ERR, "bdb: bdb_env->open: %s", db_strerror(ret));
264                 bdb_env->close(bdb_env, 0);
265                 syslog(LOG_ERR, "bdb: exit code %d", ret);
266                 exit(CTDLEXIT_DB);
267         }
268
269         for (i = 0; i < MAXCDB; ++i) {
270                 syslog(LOG_INFO, "bdb: mounting database %02x", i);
271                 ret = db_create(&bdb_table[i], bdb_env, 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 = bdb_table[i]->open(bdb_table[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 // 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.
293 void bdb_close_databases(void) {
294         int i;
295         int ret;
296
297         static int closing = 0;
298         while (closing == 1) {
299                 syslog(LOG_INFO, "bdb: already closing");
300         }
301         closing = 1;
302
303         syslog(LOG_INFO, "bdb: performing final checkpoint");
304         if ((ret = bdb_env->txn_checkpoint(bdb_env, 0, 0, 0))) {
305                 syslog(LOG_ERR, "bdb: txn_checkpoint: %s", db_strerror(ret));
306         }
307
308         syslog(LOG_INFO, "bdb: flushing the database logs");
309         if ((ret = bdb_env->log_flush(bdb_env, NULL))) {
310                 syslog(LOG_ERR, "bdb: log_flush: %s", db_strerror(ret));
311         }
312
313         // close the tables
314         syslog(LOG_INFO, "bdb: closing databases");
315         for (i = 0; i < MAXCDB; ++i) {
316                 syslog(LOG_INFO, "bdb: closing database %02x", i);
317                 ret = bdb_table[i]->close(bdb_table[i], 0);
318                 if (ret) {
319                         syslog(LOG_ERR, "bdb: db_close: %s", db_strerror(ret));
320                 }
321         }
322
323         // Close the handle.
324         ret = bdb_env->close(bdb_env, DB_FORCESYNC);
325         if (ret) {
326                 syslog(LOG_ERR, "bdb: DBENV->close: %s", db_strerror(ret));
327         }
328 }
329
330
331 // Decompress a DBT data block if it was compressed on disk.
332 void bdb_decompress_if_necessary(DBT *d) {
333         static int magic = COMPRESS_MAGIC;
334
335         if ((d == NULL) || (d->data == NULL) || (d->size < sizeof(magic)) || (memcmp(d->data, &magic, sizeof(magic)))) {
336                 return;
337         }
338
339         // At this point we know we're looking at a compressed item.
340
341         struct CtdlCompressHeader zheader;
342         char *uncompressed_data;
343         char *compressed_data;
344         uLongf destLen, sourceLen;
345         size_t cplen;
346
347         memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
348         cplen = sizeof(struct CtdlCompressHeader);
349         if (sizeof(struct CtdlCompressHeader) > d->size) {
350                 cplen = d->size;
351         }
352         memcpy(&zheader, d->data, cplen);
353
354         compressed_data = d->data;
355         compressed_data += sizeof(struct CtdlCompressHeader);
356
357         sourceLen = (uLongf) zheader.compressed_len;
358         destLen = (uLongf) zheader.uncompressed_len;
359         uncompressed_data = malloc(zheader.uncompressed_len);
360
361         if (uncompress((Bytef *) uncompressed_data,
362                        (uLongf *) &destLen, (const Bytef *) compressed_data, (uLong) sourceLen) != Z_OK) {
363                 syslog(LOG_ERR, "bdb: uncompress() error");
364                 bdb_abort();
365         }
366
367         free(d->data);
368         d->size = (size_t) destLen;
369         d->data = uncompressed_data;
370 }
371
372
373 // Store a piece of data.  Returns 0 if the operation was successful.  If a
374 // key already exists it should be overwritten.
375 int bdb_store(int cdb, const void *ckey, int ckeylen, void *cdata, int cdatalen) {
376
377         DBT dkey, ddata;
378         DB_TXN *tid = NULL;
379         int ret = 0;
380         struct CtdlCompressHeader zheader;
381         char *compressed_data = NULL;
382         int compressing = 0;
383         size_t buffer_len = 0;
384         uLongf destLen = 0;
385
386         memset(&dkey, 0, sizeof(DBT));
387         memset(&ddata, 0, sizeof(DBT));
388         dkey.size = ckeylen;
389         dkey.data = (void *) ckey;
390         ddata.size = cdatalen;
391         ddata.data = cdata;
392
393         // "visit" records are numerous and have big, mostly-empty string buffers in them.
394         // If we compress these we can get them down to 1% of their size most of the time.
395         if (cdb == CDB_VISIT) {
396                 compressing = 1;
397                 zheader.magic = COMPRESS_MAGIC;
398                 zheader.uncompressed_len = cdatalen;
399                 buffer_len = ((cdatalen * 101) / 100) + 100 + sizeof(struct CtdlCompressHeader);
400                 destLen = (uLongf) buffer_len;
401                 compressed_data = malloc(buffer_len);
402                 if (compress2((Bytef *) (compressed_data + sizeof(struct CtdlCompressHeader)), &destLen, (Bytef *) cdata, (uLongf) cdatalen, 1) != Z_OK) {
403                         syslog(LOG_ERR, "bdb: compress2() error");
404                         bdb_abort();
405                 }
406                 zheader.compressed_len = (size_t) destLen;
407                 memcpy(compressed_data, &zheader, sizeof(struct CtdlCompressHeader));
408                 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) + zheader.compressed_len);
409                 ddata.data = compressed_data;
410         }
411
412         if (TSD->tid != NULL) {
413                 ret = bdb_table[cdb]->put(bdb_table[cdb],       // db
414                                     TSD->tid,                   // transaction ID
415                                     &dkey,                      // key
416                                     &ddata,                     // data
417                                     0                           // flags
418                 );
419                 if (ret) {
420                         syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
421                         bdb_abort();
422                 }
423                 if (compressing) {
424                         free(compressed_data);
425                 }
426                 return ret;
427         }
428         else {
429                 bdb_bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
430
431               retry:
432                 bdb_txbegin(&tid);
433
434                 if ((ret = bdb_table[cdb]->put(bdb_table[cdb],  // db
435                                          tid,                   // transaction ID
436                                          &dkey,                 // key
437                                          &ddata,                // data
438                                          0))) {                 // flags
439                         if (ret == DB_LOCK_DEADLOCK) {
440                                 bdb_txabort(tid);
441                                 goto retry;
442                         }
443                         else {
444                                 syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
445                                 bdb_abort();
446                         }
447                 }
448                 else {
449                         bdb_txcommit(tid);
450                         if (compressing) {
451                                 free(compressed_data);
452                         }
453                         return ret;
454                 }
455         }
456         return ret;
457 }
458
459
460 // Delete a piece of data.  Returns 0 if the operation was successful.
461 int bdb_delete(int cdb, void *key, int keylen) {
462         DBT dkey;
463         DB_TXN *tid;
464         int ret;
465
466         memset(&dkey, 0, sizeof dkey);
467         dkey.size = keylen;
468         dkey.data = key;
469
470         if (TSD->tid != NULL) {
471                 ret = bdb_table[cdb]->del(bdb_table[cdb], TSD->tid, &dkey, 0);
472                 if (ret) {
473                         syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
474                         if (ret != DB_NOTFOUND) {
475                                 bdb_abort();
476                         }
477                 }
478         }
479         else {
480                 bdb_bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
481
482               retry:
483                 bdb_txbegin(&tid);
484
485                 if ((ret = bdb_table[cdb]->del(bdb_table[cdb], tid, &dkey, 0)) && ret != DB_NOTFOUND) {
486                         if (ret == DB_LOCK_DEADLOCK) {
487                                 bdb_txabort(tid);
488                                 goto retry;
489                         }
490                         else {
491                                 syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
492                                 bdb_abort();
493                         }
494                 }
495                 else {
496                         bdb_txcommit(tid);
497                 }
498         }
499         return ret;
500 }
501
502
503 static DBC *bdb_localcursor(int cdb) {
504         int ret;
505         DBC *curs;
506
507         if (TSD->cursors[cdb] == NULL) {
508                 ret = bdb_table[cdb]->cursor(bdb_table[cdb], TSD->tid, &curs, 0);
509         }
510         else {
511                 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
512         }
513
514         if (ret) {
515                 syslog(LOG_ERR, "bdb: bdb_localcursor: %s", db_strerror(ret));
516                 bdb_abort();
517         }
518
519         return curs;
520 }
521
522
523 // Fetch a piece of data.  Returns a "struct cdbdata"
524 // cdbdata.len will be 0 if the item is not found.
525 struct cdbdata bdb_fetch(int cdb, const void *key, int keylen) {
526
527         struct cdbdata returned_data;
528         memset(&returned_data, 0, sizeof(struct cdbdata));
529
530         if (keylen == 0) {              // key length zero is impossible
531                 return(returned_data);
532         }
533
534         DBT dkey;
535         int ret;
536
537         memset(&dkey, 0, sizeof(DBT));
538         dkey.size = keylen;
539         dkey.data = (void *) key;
540
541         if (TSD->tid != NULL) {
542                 TSD->dbdata[cdb].flags = DB_DBT_REALLOC;
543                 ret = bdb_table[cdb]->get(bdb_table[cdb], TSD->tid, &dkey, &TSD->dbdata[cdb], 0);
544         }
545         else {
546                 DBC *curs;
547
548                 do {
549                         TSD->dbdata[cdb].flags = DB_DBT_REALLOC;
550                         curs = bdb_localcursor(cdb);
551                         ret = curs->c_get(curs, &dkey, &TSD->dbdata[cdb], DB_SET);
552                         bdb_cclose(curs);
553                 } while (ret == DB_LOCK_DEADLOCK);
554         }
555
556         if ((ret != 0) && (ret != DB_NOTFOUND)) {
557                 syslog(LOG_ERR, "bdb: bdb_fetch(%d): %s", cdb, db_strerror(ret));
558                 bdb_abort();
559         }
560
561         if (ret == 0) {
562                 bdb_decompress_if_necessary(&TSD->dbdata[cdb]);
563                 returned_data.len = TSD->dbdata[cdb].size;
564                 returned_data.ptr = TSD->dbdata[cdb].data;
565         }
566
567         return(returned_data);
568 }
569
570
571 void bdb_close_cursor(int cdb) {
572         if (TSD->cursors[cdb] != NULL) {
573                 bdb_cclose(TSD->cursors[cdb]);
574         }
575
576         TSD->cursors[cdb] = NULL;
577 }
578
579
580 // Prepare for a sequential search of an entire database.
581 // (There is guaranteed to be no more than one traversal in progress per thread at any given time.)
582 void bdb_rewind(int cdb) {
583         int ret = 0;
584
585         if (TSD->cursors[cdb] != NULL) {
586                 syslog(LOG_ERR, "bdb: bdb_rewind: must close cursor on database %d before reopening", cdb);
587                 bdb_abort();
588                 // bdb_cclose(TSD->cursors[cdb]);
589         }
590
591         // Now initialize the cursor
592         ret = bdb_table[cdb]->cursor(bdb_table[cdb], TSD->tid, &TSD->cursors[cdb], 0);
593         if (ret) {
594                 syslog(LOG_ERR, "bdb: bdb_rewind: db_cursor: %s", db_strerror(ret));
595                 bdb_abort();
596         }
597 }
598
599
600 // Fetch the next item in a sequential search.  Returns a pointer to a 
601 // cdbdata structure, or NULL if we've hit the end.
602 struct cdbkeyval bdb_next_item(int cdb) {
603         struct cdbkeyval kv;
604         int ret = 0;
605
606         memset(&kv, 0, sizeof(struct cdbkeyval));
607
608         // reuse memory from the previous call.
609         TSD->dbkey[cdb].flags = DB_DBT_MALLOC;
610         TSD->dbdata[cdb].flags = DB_DBT_MALLOC;
611
612         assert(TSD->cursors[cdb] != NULL);
613         ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &TSD->dbkey[cdb], &TSD->dbdata[cdb], DB_NEXT);
614
615         if (ret) {
616                 if (ret != DB_NOTFOUND) {
617                         syslog(LOG_ERR, "bdb: bdb_next_item(%d): %s", cdb, db_strerror(ret));
618                         bdb_abort();
619                 }
620                 bdb_close_cursor(cdb);
621                 return(kv);             // presumably, we are at the end
622         }
623
624         bdb_decompress_if_necessary(&TSD->dbdata[cdb]);
625
626         kv.key.len = TSD->dbkey[cdb].size;
627         kv.key.ptr = TSD->dbkey[cdb].data;
628         kv.val.len = TSD->dbdata[cdb].size;
629         kv.val.ptr = TSD->dbdata[cdb].data;
630         return (kv);
631 }
632
633
634 // Transaction-based stuff.  I'm writing this as I bake cookies...
635 void bdb_begin_transaction(void) {
636         bdb_bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
637
638         if (TSD->tid != NULL) {
639                 syslog(LOG_ERR, "bdb: bdb_begin_transaction: ERROR: nested transaction");
640                 bdb_abort();
641         }
642
643         bdb_txbegin(&TSD->tid);
644 }
645
646
647 void bdb_end_transaction(void) {
648         int i;
649
650         for (i = 0; i < MAXCDB; i++) {
651                 if (TSD->cursors[i] != NULL) {
652                         syslog(LOG_WARNING, "bdb: bdb_end_transaction: WARNING: cursor %d still open at transaction end", i);
653                         bdb_cclose(TSD->cursors[i]);
654                         TSD->cursors[i] = NULL;
655                 }
656         }
657
658         if (TSD->tid == NULL) {
659                 syslog(LOG_ERR, "bdb: bdb_end_transaction: ERROR: bdb_txcommit(NULL) !!");
660                 bdb_abort();
661         }
662         else {
663                 bdb_txcommit(TSD->tid);
664         }
665
666         TSD->tid = NULL;
667 }
668
669
670 // Truncate (delete every record)
671 void bdb_trunc(int cdb) {
672         int ret;
673         u_int32_t count;
674
675         if (TSD->tid != NULL) {
676                 syslog(LOG_ERR, "bdb: bdb_trunc must not be called in a transaction.");
677                 bdb_abort();
678         }
679         else {
680                 bdb_bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
681
682               retry:
683
684                 if ((ret = bdb_table[cdb]->truncate(bdb_table[cdb],     // db
685                                               NULL,                     // transaction ID
686                                               &count,                   // #rows deleted
687                                               0))) {                    // flags
688                         if (ret == DB_LOCK_DEADLOCK) {
689                                 goto retry;
690                         }
691                         else {
692                                 syslog(LOG_ERR, "bdb: bdb_truncate(%d): %s", cdb, db_strerror(ret));
693                                 if (ret == ENOMEM) {
694                                         syslog(LOG_ERR, "bdb: You may need to tune your database; please read http://www.citadel.org for more information.");
695                                 }
696                                 exit(CTDLEXIT_DB);
697                         }
698                 }
699         }
700 }
701
702
703 // compact (defragment) the database, possibly returning space back to the underlying filesystem
704 void bdb_compact(void) {
705         int ret;
706         int i;
707
708         syslog(LOG_DEBUG, "bdb: bdb_compact() started");
709         for (i = 0; i < MAXCDB; i++) {
710                 syslog(LOG_DEBUG, "bdb: compacting database %d", i);
711                 ret = bdb_table[i]->compact(bdb_table[i], NULL, NULL, NULL, NULL, DB_FREE_SPACE, NULL);
712                 if (ret) {
713                         syslog(LOG_ERR, "bdb: compact: %s", db_strerror(ret));
714                 }
715         }
716         syslog(LOG_DEBUG, "bdb: bdb_compact() finished");
717 }
718
719
720 // Calling this function activates the Berkeley DB back end.
721 void bdb_init_backend(void) {
722
723         // Assign the backend API stubs to the functions in this module.
724         cdb_compact = bdb_compact;
725         cdb_checkpoint = bdb_checkpoint;
726         cdb_rewind = bdb_rewind;
727         cdb_fetch = bdb_fetch;
728         cdb_open_databases = bdb_open_databases;
729         cdb_close_databases = bdb_close_databases;
730         cdb_store = bdb_store;
731         cdb_delete = bdb_delete;
732         cdb_next_item = bdb_next_item;
733         cdb_close_cursor = bdb_close_cursor;
734         cdb_begin_transaction = bdb_begin_transaction;
735         cdb_end_transaction = bdb_end_transaction;
736         cdb_check_handles = bdb_check_handles;
737         cdb_trunc = bdb_trunc;
738
739         // Some functions in this backend need to store some per-thread data.
740         // We crerate the key here, during module initialization.
741         if (pthread_key_create(&bdb_thread_key, NULL) != 0) {
742                 syslog(LOG_ERR, "pthread_key_create() : %m");
743                 exit(CTDLEXIT_THREAD);
744         }
745
746         syslog(LOG_INFO, "db: initialized Berkeley DB backend");
747 }