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