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