master_cleanup() is now the global shutdown/exit function
[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         // This appears to do nothing over and above the default
240         //if ((ret = bdb_env->set_lk_detect(bdb_env, DB_LOCK_DEFAULT))) {
241                 //syslog(LOG_ERR, "bdb: set_lk_detect: %s", db_strerror(ret));
242                 //bdb_env->close(bdb_env, 0);
243                 //syslog(LOG_ERR, "bdb: exit code %d", ret);
244                 //exit(CTDLEXIT_DB);
245         //}
246
247         flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | /*DB_INIT_LOCK |*/ DB_THREAD | DB_INIT_LOG;
248         syslog(LOG_DEBUG, "bdb: bdb_env->open(bdb_env, %s, %d, 0)", ctdl_db_dir, flags);
249         ret = bdb_env->open(bdb_env, ctdl_db_dir, flags, 0);                            // try opening the database cleanly
250         if (ret == DB_RUNRECOVERY) {
251                 syslog(LOG_ERR, "bdb: bdb_env->open: %s", db_strerror(ret));
252                 syslog(LOG_ERR, "bdb: attempting recovery...");
253                 flags |= DB_RECOVER;
254                 ret = bdb_env->open(bdb_env, ctdl_db_dir, flags, 0);                    // try recovery
255         }
256         if (ret == DB_RUNRECOVERY) {
257                 syslog(LOG_ERR, "bdb: bdb_env->open: %s", db_strerror(ret));
258                 syslog(LOG_ERR, "bdb: attempting catastrophic recovery...");
259                 flags &= ~DB_RECOVER;
260                 flags |= DB_RECOVER_FATAL;
261                 ret = bdb_env->open(bdb_env, ctdl_db_dir, flags, 0);                    // try catastrophic recovery
262         }
263         if (ret) {
264                 syslog(LOG_ERR, "bdb: bdb_env->open: %s", db_strerror(ret));
265                 bdb_env->close(bdb_env, 0);
266                 syslog(LOG_ERR, "bdb: exit code %d", ret);
267                 exit(CTDLEXIT_DB);
268         }
269
270         for (i = 0; i < MAXCDB; ++i) {
271                 syslog(LOG_INFO, "bdb: mounting database %02x", i);
272                 ret = db_create(&bdb_table[i], bdb_env, 0);                             // Create a database handle
273                 if (ret) {
274                         syslog(LOG_ERR, "bdb: db_create: %s", db_strerror(ret));
275                         syslog(LOG_ERR, "bdb: exit code %d", ret);
276                         exit(CTDLEXIT_DB);
277                 }
278
279                 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);                 // table names by number
280                 ret = bdb_table[i]->open(bdb_table[i], NULL, dbfilename, NULL, DB_BTREE, DB_CREATE | DB_AUTO_COMMIT, 0600);
281                 if (ret) {
282                         syslog(LOG_ERR, "bdb: db_open[%02x]: %s", i, db_strerror(ret));
283                         if (ret == ENOMEM) {
284                                 syslog(LOG_ERR, "bdb: You may need to tune your database; please check http://www.citadel.org for more information.");
285                         }
286                         syslog(LOG_ERR, "bdb: exit code %d", ret);
287                         exit(CTDLEXIT_DB);
288                 }
289         }
290 }
291
292
293 // 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.
294 void bdb_close_databases(void) {
295         int i;
296         int ret;
297
298         static int closing = 0;
299         while (closing == 1) {
300                 syslog(LOG_INFO, "bdb: already closing");
301         }
302         closing = 1;
303
304         syslog(LOG_INFO, "bdb: performing final checkpoint");
305         if ((ret = bdb_env->txn_checkpoint(bdb_env, 0, 0, 0))) {
306                 syslog(LOG_ERR, "bdb: txn_checkpoint: %s", db_strerror(ret));
307         }
308
309         syslog(LOG_INFO, "bdb: flushing the database logs");
310         if ((ret = bdb_env->log_flush(bdb_env, NULL))) {
311                 syslog(LOG_ERR, "bdb: log_flush: %s", db_strerror(ret));
312         }
313
314         // close the tables
315         syslog(LOG_INFO, "bdb: closing databases");
316         for (i = 0; i < MAXCDB; ++i) {
317                 syslog(LOG_INFO, "bdb: closing database %02x", i);
318                 ret = bdb_table[i]->close(bdb_table[i], 0);
319                 if (ret) {
320                         syslog(LOG_ERR, "bdb: db_close: %s", db_strerror(ret));
321                 }
322         }
323
324         // Close the handle.
325         syslog(LOG_INFO, "bdb: closing environment");
326         ret = bdb_env->close(bdb_env, DB_FORCESYNC);
327         if (ret) {
328                 syslog(LOG_ERR, "bdb: DBENV->close: %s", db_strerror(ret));
329         }
330
331         syslog(LOG_INFO, "bdb: shutdown completed");
332 }
333
334
335 // Decompress a DBT data block if it was compressed on disk.
336 void bdb_decompress_if_necessary(DBT *d) {
337         static int magic = COMPRESS_MAGIC;
338
339         if ((d == NULL) || (d->data == NULL) || (d->size < sizeof(magic)) || (memcmp(d->data, &magic, sizeof(magic)))) {
340                 return;
341         }
342
343         // At this point we know we're looking at a compressed item.
344
345         struct CtdlCompressHeader zheader;
346         char *uncompressed_data;
347         char *compressed_data;
348         uLongf destLen, sourceLen;
349         size_t cplen;
350
351         memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
352         cplen = sizeof(struct CtdlCompressHeader);
353         if (sizeof(struct CtdlCompressHeader) > d->size) {
354                 cplen = d->size;
355         }
356         memcpy(&zheader, d->data, cplen);
357
358         compressed_data = d->data;
359         compressed_data += sizeof(struct CtdlCompressHeader);
360
361         sourceLen = (uLongf) zheader.compressed_len;
362         destLen = (uLongf) zheader.uncompressed_len;
363         uncompressed_data = malloc(zheader.uncompressed_len);
364
365         if (uncompress((Bytef *) uncompressed_data,
366                        (uLongf *) &destLen, (const Bytef *) compressed_data, (uLong) sourceLen) != Z_OK) {
367                 syslog(LOG_ERR, "bdb: uncompress() error");
368                 bdb_abort();
369         }
370
371         free(d->data);
372         d->size = (size_t) destLen;
373         d->data = uncompressed_data;
374 }
375
376
377 // Store a piece of data.  Returns 0 if the operation was successful.  If a
378 // key already exists it should be overwritten.
379 int bdb_store(int cdb, const void *ckey, int ckeylen, void *cdata, int cdatalen) {
380
381         DBT dkey, ddata;
382         DB_TXN *tid = NULL;
383         int ret = 0;
384         struct CtdlCompressHeader zheader;
385         char *compressed_data = NULL;
386         int compressing = 0;
387         size_t buffer_len = 0;
388         uLongf destLen = 0;
389
390         memset(&dkey, 0, sizeof(DBT));
391         memset(&ddata, 0, sizeof(DBT));
392         dkey.size = ckeylen;
393         dkey.data = (void *) ckey;
394         ddata.size = cdatalen;
395         ddata.data = cdata;
396
397         // "visit" records are numerous and have big, mostly-empty string buffers in them.
398         // If we compress these we can get them down to 1% of their size most of the time.
399         if (cdb == CDB_VISIT) {
400                 compressing = 1;
401                 zheader.magic = COMPRESS_MAGIC;
402                 zheader.uncompressed_len = cdatalen;
403                 buffer_len = ((cdatalen * 101) / 100) + 100 + sizeof(struct CtdlCompressHeader);
404                 destLen = (uLongf) buffer_len;
405                 compressed_data = malloc(buffer_len);
406                 if (compress2((Bytef *) (compressed_data + sizeof(struct CtdlCompressHeader)), &destLen, (Bytef *) cdata, (uLongf) cdatalen, 1) != Z_OK) {
407                         syslog(LOG_ERR, "bdb: compress2() error");
408                         bdb_abort();
409                 }
410                 zheader.compressed_len = (size_t) destLen;
411                 memcpy(compressed_data, &zheader, sizeof(struct CtdlCompressHeader));
412                 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) + zheader.compressed_len);
413                 ddata.data = compressed_data;
414         }
415
416         if (TSD->tid != NULL) {
417                 ret = bdb_table[cdb]->put(bdb_table[cdb],       // db
418                                     TSD->tid,                   // transaction ID
419                                     &dkey,                      // key
420                                     &ddata,                     // data
421                                     0                           // flags
422                 );
423                 if (ret) {
424                         syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
425                         bdb_abort();
426                 }
427                 if (compressing) {
428                         free(compressed_data);
429                 }
430                 return ret;
431         }
432         else {
433                 bdb_bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
434
435               retry:
436                 bdb_txbegin(&tid);
437
438                 if ((ret = bdb_table[cdb]->put(bdb_table[cdb],  // db
439                                          tid,                   // transaction ID
440                                          &dkey,                 // key
441                                          &ddata,                // data
442                                          0))) {                 // flags
443                         if (ret == DB_LOCK_DEADLOCK) {
444                                 bdb_txabort(tid);
445                                 goto retry;
446                         }
447                         else {
448                                 syslog(LOG_ERR, "bdb: bdb_store(%d): %s", cdb, db_strerror(ret));
449                                 bdb_abort();
450                         }
451                 }
452                 else {
453                         bdb_txcommit(tid);
454                         if (compressing) {
455                                 free(compressed_data);
456                         }
457                         return ret;
458                 }
459         }
460         return ret;
461 }
462
463
464 // Delete a piece of data.  Returns 0 if the operation was successful.
465 int bdb_delete(int cdb, void *key, int keylen) {
466         DBT dkey;
467         DB_TXN *tid;
468         int ret;
469
470         memset(&dkey, 0, sizeof dkey);
471         dkey.size = keylen;
472         dkey.data = key;
473
474         if (TSD->tid != NULL) {
475                 ret = bdb_table[cdb]->del(bdb_table[cdb], TSD->tid, &dkey, 0);
476                 if (ret) {
477                         syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
478                         if (ret != DB_NOTFOUND) {
479                                 bdb_abort();
480                         }
481                 }
482         }
483         else {
484                 bdb_bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
485
486               retry:
487                 bdb_txbegin(&tid);
488
489                 if ((ret = bdb_table[cdb]->del(bdb_table[cdb], tid, &dkey, 0)) && ret != DB_NOTFOUND) {
490                         if (ret == DB_LOCK_DEADLOCK) {
491                                 bdb_txabort(tid);
492                                 goto retry;
493                         }
494                         else {
495                                 syslog(LOG_ERR, "bdb: bdb_delete(%d): %s", cdb, db_strerror(ret));
496                                 bdb_abort();
497                         }
498                 }
499                 else {
500                         bdb_txcommit(tid);
501                 }
502         }
503         return ret;
504 }
505
506
507 static DBC *bdb_localcursor(int cdb) {
508         int ret;
509         DBC *curs;
510
511         if (TSD->cursors[cdb] == NULL) {
512                 ret = bdb_table[cdb]->cursor(bdb_table[cdb], TSD->tid, &curs, 0);
513         }
514         else {
515                 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
516         }
517
518         if (ret) {
519                 syslog(LOG_ERR, "bdb: bdb_localcursor: %s", db_strerror(ret));
520                 bdb_abort();
521         }
522
523         return curs;
524 }
525
526
527 // Fetch a piece of data.  Returns a "struct cdbdata"
528 // cdbdata.len will be 0 if the item is not found.
529 struct cdbdata bdb_fetch(int cdb, const void *key, int keylen) {
530
531         struct cdbdata returned_data;
532         memset(&returned_data, 0, sizeof(struct cdbdata));
533
534         if (keylen == 0) {              // key length zero is impossible
535                 return(returned_data);
536         }
537
538         DBT dkey;
539         int ret;
540
541         memset(&dkey, 0, sizeof(DBT));
542         dkey.size = keylen;
543         dkey.data = (void *) key;
544
545         if (TSD->tid != NULL) {
546                 TSD->dbdata[cdb].flags = DB_DBT_REALLOC;
547                 ret = bdb_table[cdb]->get(bdb_table[cdb], TSD->tid, &dkey, &TSD->dbdata[cdb], 0);
548         }
549         else {
550                 DBC *curs;
551
552                 do {
553                         TSD->dbdata[cdb].flags = DB_DBT_REALLOC;
554                         curs = bdb_localcursor(cdb);
555                         ret = curs->c_get(curs, &dkey, &TSD->dbdata[cdb], 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                 bdb_decompress_if_necessary(&TSD->dbdata[cdb]);
567                 returned_data.len = TSD->dbdata[cdb].size;
568                 returned_data.ptr = TSD->dbdata[cdb].data;
569         }
570
571         return(returned_data);
572 }
573
574
575 void bdb_close_cursor(int cdb) {
576         if (TSD->cursors[cdb] != NULL) {
577                 bdb_cclose(TSD->cursors[cdb]);
578         }
579
580         TSD->cursors[cdb] = NULL;
581 }
582
583
584 // Prepare for a sequential search of an entire database.
585 // (There is guaranteed to be no more than one traversal in progress per thread at any given time.)
586 void bdb_rewind(int cdb) {
587         int ret = 0;
588
589         if (TSD->cursors[cdb] != NULL) {
590                 syslog(LOG_ERR, "bdb: bdb_rewind: must close cursor on database %d before reopening", cdb);
591                 bdb_abort();
592                 // bdb_cclose(TSD->cursors[cdb]);
593         }
594
595         // Now initialize the cursor
596         ret = bdb_table[cdb]->cursor(bdb_table[cdb], TSD->tid, &TSD->cursors[cdb], 0);
597         if (ret) {
598                 syslog(LOG_ERR, "bdb: bdb_rewind: db_cursor: %s", db_strerror(ret));
599                 bdb_abort();
600         }
601 }
602
603
604 // Fetch the next item in a sequential search.  Returns a pointer to a 
605 // cdbdata structure, or NULL if we've hit the end.
606 struct cdbkeyval bdb_next_item(int cdb) {
607         struct cdbkeyval kv;
608         int ret = 0;
609
610         memset(&kv, 0, sizeof(struct cdbkeyval));
611
612         // reuse memory from the previous call.
613         TSD->dbkey[cdb].flags = DB_DBT_MALLOC;
614         TSD->dbdata[cdb].flags = DB_DBT_MALLOC;
615
616         assert(TSD->cursors[cdb] != NULL);
617         ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &TSD->dbkey[cdb], &TSD->dbdata[cdb], DB_NEXT);
618
619         if (ret) {
620                 if (ret != DB_NOTFOUND) {
621                         syslog(LOG_ERR, "bdb: bdb_next_item(%d): %s", cdb, db_strerror(ret));
622                         bdb_abort();
623                 }
624                 bdb_close_cursor(cdb);
625                 return(kv);             // presumably, we are at the end
626         }
627
628         bdb_decompress_if_necessary(&TSD->dbdata[cdb]);
629
630         kv.key.len = TSD->dbkey[cdb].size;
631         kv.key.ptr = TSD->dbkey[cdb].data;
632         kv.val.len = TSD->dbdata[cdb].size;
633         kv.val.ptr = TSD->dbdata[cdb].data;
634         return (kv);
635 }
636
637
638 // Transaction-based stuff.  I'm writing this as I bake cookies...
639 void bdb_begin_transaction(void) {
640         bdb_bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
641
642         if (TSD->tid != NULL) {
643                 syslog(LOG_ERR, "bdb: bdb_begin_transaction: ERROR: nested transaction");
644                 bdb_abort();
645         }
646
647         bdb_txbegin(&TSD->tid);
648 }
649
650
651 void bdb_end_transaction(void) {
652         int i;
653
654         for (i = 0; i < MAXCDB; i++) {
655                 if (TSD->cursors[i] != NULL) {
656                         syslog(LOG_WARNING, "bdb: bdb_end_transaction: WARNING: cursor %d still open at transaction end", i);
657                         bdb_cclose(TSD->cursors[i]);
658                         TSD->cursors[i] = NULL;
659                 }
660         }
661
662         if (TSD->tid == NULL) {
663                 syslog(LOG_ERR, "bdb: bdb_end_transaction: ERROR: bdb_txcommit(NULL) !!");
664                 bdb_abort();
665         }
666         else {
667                 bdb_txcommit(TSD->tid);
668         }
669
670         TSD->tid = NULL;
671 }
672
673
674 // Truncate (delete every record)
675 void bdb_trunc(int cdb) {
676         int ret;
677         u_int32_t count;
678
679         if (TSD->tid != NULL) {
680                 syslog(LOG_ERR, "bdb: bdb_trunc must not be called in a transaction.");
681                 bdb_abort();
682         }
683         else {
684                 bdb_bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
685
686               retry:
687
688                 if ((ret = bdb_table[cdb]->truncate(bdb_table[cdb],     // db
689                                               NULL,                     // transaction ID
690                                               &count,                   // #rows deleted
691                                               0))) {                    // flags
692                         if (ret == DB_LOCK_DEADLOCK) {
693                                 goto retry;
694                         }
695                         else {
696                                 syslog(LOG_ERR, "bdb: bdb_truncate(%d): %s", cdb, db_strerror(ret));
697                                 if (ret == ENOMEM) {
698                                         syslog(LOG_ERR, "bdb: You may need to tune your database; please read http://www.citadel.org for more information.");
699                                 }
700                                 exit(CTDLEXIT_DB);
701                         }
702                 }
703         }
704 }
705
706
707 // compact (defragment) the database, possibly returning space back to the underlying filesystem
708 void bdb_compact(void) {
709         int ret;
710         int i;
711
712         syslog(LOG_DEBUG, "bdb: bdb_compact() started");
713         for (i = 0; i < MAXCDB; i++) {
714                 syslog(LOG_DEBUG, "bdb: compacting database %d", i);
715                 ret = bdb_table[i]->compact(bdb_table[i], NULL, NULL, NULL, NULL, DB_FREE_SPACE, NULL);
716                 if (ret) {
717                         syslog(LOG_ERR, "bdb: compact: %s", db_strerror(ret));
718                 }
719         }
720         syslog(LOG_DEBUG, "bdb: bdb_compact() finished");
721 }
722
723
724 // Calling this function activates the Berkeley DB back end.
725 void bdb_init_backend(void) {
726
727         // Assign the backend API stubs to the functions in this module.
728         cdb_compact = bdb_compact;
729         cdb_checkpoint = bdb_checkpoint;
730         cdb_rewind = bdb_rewind;
731         cdb_fetch = bdb_fetch;
732         cdb_open_databases = bdb_open_databases;
733         cdb_close_databases = bdb_close_databases;
734         cdb_store = bdb_store;
735         cdb_delete = bdb_delete;
736         cdb_next_item = bdb_next_item;
737         cdb_close_cursor = bdb_close_cursor;
738         cdb_begin_transaction = bdb_begin_transaction;
739         cdb_end_transaction = bdb_end_transaction;
740         cdb_check_handles = bdb_check_handles;
741         cdb_trunc = bdb_trunc;
742
743         // Some functions in this backend need to store some per-thread data.
744         // We crerate the key here, during module initialization.
745         if (pthread_key_create(&bdb_thread_key, NULL) != 0) {
746                 syslog(LOG_ERR, "pthread_key_create() : %m");
747                 exit(CTDLEXIT_THREAD);
748         }
749
750         syslog(LOG_INFO, "db: initialized Berkeley DB backend");
751 }