berkeley_db.c: prefixed all module-local functions with bdb_ to avoid namespace colli...
[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 <stdlib.h>
16 #include <unistd.h>
17 #include <sys/stat.h>
18 #include <stdio.h>
19 #include <dirent.h>
20 #include <zlib.h>
21 #include <db.h>
22 #include <libcitadel.h>
23 #include "../../ctdl_module.h"
24 #include "../../control.h"
25 #include "../../citserver.h"
26 #include "../../config.h"
27 #include "berkeley_db.h"
28
29 #if DB_VERSION_MAJOR < 18
30 #error Citadel requires Berkeley DB v18.0 or newer.  Please upgrade.
31 #endif
32
33
34 static DB *dbp[MAXCDB];         // One DB handle for each Citadel database
35 static DB_ENV *dbenv;           // The DB environment (global)
36
37
38 // Called by other functions in this module to GTFO quickly if we need to.  Not part of the backend API.
39 void bdb_abort(void) {
40         syslog(LOG_DEBUG, "bdb: citserver is stopping in order to prevent data loss. uid=%d gid=%d euid=%d egid=%d",
41                 getuid(), getgid(), geteuid(), getegid()
42         );
43         raise(SIGABRT);         // This will exit in a way that can produce a core dump if needed.
44         exit(CTDLEXIT_DB);      // Exit if the signal failed to end the program.
45 }
46
47
48 // Verbose logging callback for Berkeley DB.  Not part of the backend API.
49 void bdb_verbose_log(const DB_ENV *dbenv, const char *msg, const char *foo) {
50         if (!IsEmptyStr(msg)) {
51                 syslog(LOG_DEBUG, "bdb: %s %s", msg, foo);
52         }
53 }
54
55
56 // Verbose error logging callback for Berkeley DB.  Not part of the backend API.
57 void bdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg) {
58         syslog(LOG_ERR, "bdb: %s", msg);
59 }
60
61
62 // wrapper for txn_abort() that logs/aborts on error
63 static void bdb_txabort(DB_TXN *tid) {
64         int ret;
65
66         ret = tid->abort(tid);
67
68         if (ret) {
69                 syslog(LOG_ERR, "bdb: txn_abort: %s", db_strerror(ret));
70                 bdb_abort();
71         }
72 }
73
74
75 // wrapper for txn_commit() that logs/aborts on error
76 static void bdb_txcommit(DB_TXN *tid) {
77         int ret;
78
79         ret = tid->commit(tid, 0);
80
81         if (ret) {
82                 syslog(LOG_ERR, "bdb: txn_commit: %s", db_strerror(ret));
83                 bdb_abort();
84         }
85 }
86
87
88 // wrapper for txn_begin() that logs/aborts on error
89 static void bdb_txbegin(DB_TXN **tid) {
90         int ret;
91
92         ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
93
94         if (ret) {
95                 syslog(LOG_ERR, "bdb: txn_begin: %s", db_strerror(ret));
96                 bdb_abort();
97         }
98 }
99
100
101 // panic callback
102 static void bdb_dbpanic(DB_ENV *env, int errval) {
103         syslog(LOG_ERR, "bdb: PANIC: %s", db_strerror(errval));
104         bdb_abort();
105 }
106
107
108 static void bdb_cclose(DBC *cursor) {
109         int ret;
110
111         if ((ret = cursor->c_close(cursor))) {
112                 syslog(LOG_ERR, "bdb: c_close: %s", db_strerror(ret));
113                 bdb_abort();
114         }
115 }
116
117
118 static void bdb_bailIfCursor(DBC **cursors, const char *msg) {
119         int i;
120
121         for (i = 0; i < MAXCDB; i++)
122                 if (cursors[i] != NULL) {
123                         syslog(LOG_ERR, "bdb: cursor still in progress on cdb %02x: %s", i, msg);
124                         bdb_abort();
125                 }
126 }
127
128
129 void bdb_check_handles(void) {
130         bdb_bailIfCursor(TSD->cursors, "in check_handles");
131
132         if (TSD->tid != NULL) {
133                 syslog(LOG_ERR, "bdb: transaction still in progress!");
134                 bdb_abort();
135         }
136 }
137
138
139 // Request a checkpoint of the database.  Called once per minute by the thread manager.
140 void bdb_checkpoint(void) {
141         int ret;
142
143         syslog(LOG_DEBUG, "bdb: -- checkpoint --");
144         ret = dbenv->txn_checkpoint(dbenv, MAX_CHECKPOINT_KBYTES, MAX_CHECKPOINT_MINUTES, 0);
145
146         if (ret != 0) {
147                 syslog(LOG_ERR, "bdb: bdb_checkpoint() txn_checkpoint: %s", db_strerror(ret));
148                 bdb_abort();
149         }
150
151         // After a successful checkpoint, we can cull the unused logs
152         if (CtdlGetConfigInt("c_auto_cull")) {
153                 ret = dbenv->log_set_config(dbenv, DB_LOG_AUTO_REMOVE, 1);
154         }
155         else {
156                 ret = dbenv->log_set_config(dbenv, DB_LOG_AUTO_REMOVE, 0);
157         }
158 }
159
160
161 // Open the various databases we'll be using.  Any database which
162 // does not exist should be created.  Note that we don't need a
163 // critical section here, because there aren't any active threads
164 // manipulating the database yet.
165 void bdb_open_databases(void) {
166         int ret;
167         int i;
168         char dbfilename[32];
169         u_int32_t flags = 0;
170         int dbversion_major, dbversion_minor, dbversion_patch;
171
172         syslog(LOG_DEBUG, "bdb: bdb_open_databases() starting");
173         syslog(LOG_DEBUG, "bdb:    Linked zlib: %s", zlibVersion());
174         syslog(LOG_DEBUG, "bdb: Compiled libdb: %s", DB_VERSION_STRING);
175         syslog(LOG_DEBUG, "bdb:   Linked libdb: %s", db_version(&dbversion_major, &dbversion_minor, &dbversion_patch));
176
177         // Create synthetic integer version numbers and compare them.
178         // Never allow citserver to run with a libdb older then the one with which it was compiled.
179         int compiled_db_version = ( (DB_VERSION_MAJOR * 1000000) + (DB_VERSION_MINOR * 1000) + (DB_VERSION_PATCH) );
180         int linked_db_version = ( (dbversion_major * 1000000) + (dbversion_minor * 1000) + (dbversion_patch) );
181         if (compiled_db_version > linked_db_version) {
182                 syslog(LOG_ERR, "bdb: citserver is running with a version of libdb older than the one with which it was compiled.");
183                 syslog(LOG_ERR, "bdb: This is an invalid configuration.  citserver will now exit to prevent data loss.");
184                 exit(CTDLEXIT_DB);
185         }
186
187         // Silently try to create the database subdirectory.  If it's already there, no problem.
188         if ((mkdir(ctdl_db_dir, 0700) != 0) && (errno != EEXIST)) {
189                 syslog(LOG_ERR, "bdb: database directory [%s] does not exist and could not be created: %m", ctdl_db_dir);
190                 exit(CTDLEXIT_DB);
191         }
192         if (chmod(ctdl_db_dir, 0700) != 0) {
193                 syslog(LOG_ERR, "bdb: unable to set database directory permissions [%s]: %m", ctdl_db_dir);
194                 exit(CTDLEXIT_DB);
195         }
196         if (chown(ctdl_db_dir, CTDLUID, (-1)) != 0) {
197                 syslog(LOG_ERR, "bdb: unable to set the owner for [%s]: %m", ctdl_db_dir);
198                 exit(CTDLEXIT_DB);
199         }
200         syslog(LOG_DEBUG, "bdb: Setting up DB environment");
201         ret = db_env_create(&dbenv, 0);
202         if (ret) {
203                 syslog(LOG_ERR, "bdb: db_env_create: %s", db_strerror(ret));
204                 syslog(LOG_ERR, "bdb: exit code %d", ret);
205                 exit(CTDLEXIT_DB);
206         }
207         dbenv->set_errpfx(dbenv, "citserver");
208         dbenv->set_paniccall(dbenv, bdb_dbpanic);
209         dbenv->set_errcall(dbenv, bdb_verbose_err);
210         dbenv->set_msgcall(dbenv, bdb_verbose_log);
211         dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
212         dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
213
214         // We want to specify the shared memory buffer pool cachesize, but everything else is the default.
215         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
216         if (ret) {
217                 syslog(LOG_ERR, "bdb: set_cachesize: %s", db_strerror(ret));
218                 dbenv->close(dbenv, 0);
219                 syslog(LOG_ERR, "bdb: exit code %d", ret);
220                 exit(CTDLEXIT_DB);
221         }
222
223         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
224                 syslog(LOG_ERR, "bdb: set_lk_detect: %s", db_strerror(ret));
225                 dbenv->close(dbenv, 0);
226                 syslog(LOG_ERR, "bdb: exit code %d", ret);
227                 exit(CTDLEXIT_DB);
228         }
229
230         flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD | DB_INIT_LOG;
231         syslog(LOG_DEBUG, "bdb: dbenv->open(dbenv, %s, %d, 0)", ctdl_db_dir, flags);
232         ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0);                                // try opening the database cleanly
233         if (ret == DB_RUNRECOVERY) {
234                 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
235                 syslog(LOG_ERR, "bdb: attempting recovery...");
236                 flags |= DB_RECOVER;
237                 ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0);                        // try recovery
238         }
239         if (ret == DB_RUNRECOVERY) {
240                 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
241                 syslog(LOG_ERR, "bdb: attempting catastrophic recovery...");
242                 flags &= ~DB_RECOVER;
243                 flags |= DB_RECOVER_FATAL;
244                 ret = dbenv->open(dbenv, ctdl_db_dir, flags, 0);                        // try catastrophic recovery
245         }
246         if (ret) {
247                 syslog(LOG_ERR, "bdb: dbenv->open: %s", db_strerror(ret));
248                 dbenv->close(dbenv, 0);
249                 syslog(LOG_ERR, "bdb: exit code %d", ret);
250                 exit(CTDLEXIT_DB);
251         }
252
253         syslog(LOG_INFO, "bdb: mounting databases");
254         for (i = 0; i < MAXCDB; ++i) {
255                 ret = db_create(&dbp[i], dbenv, 0);                                     // Create a database handle
256                 if (ret) {
257                         syslog(LOG_ERR, "bdb: db_create: %s", db_strerror(ret));
258                         syslog(LOG_ERR, "bdb: exit code %d", ret);
259                         exit(CTDLEXIT_DB);
260                 }
261
262                 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);                 // table names by number
263                 ret = dbp[i]->open(dbp[i], NULL, dbfilename, NULL, DB_BTREE, DB_CREATE | DB_AUTO_COMMIT | DB_THREAD, 0600);
264                 if (ret) {
265                         syslog(LOG_ERR, "bdb: db_open[%02x]: %s", i, db_strerror(ret));
266                         if (ret == ENOMEM) {
267                                 syslog(LOG_ERR, "bdb: You may need to tune your database; please check http://www.citadel.org for more information.");
268                         }
269                         syslog(LOG_ERR, "bdb: exit code %d", ret);
270                         exit(CTDLEXIT_DB);
271                 }
272         }
273 }
274
275
276 // Make sure we own all the files, because in a few milliseconds we're going to drop root privs.
277 void bdb_chmod_data(void) {
278         DIR *dp;
279         struct dirent *d;
280         char filename[PATH_MAX];
281
282         dp = opendir(ctdl_db_dir);
283         if (dp != NULL) {
284                 while (d = readdir(dp), d != NULL) {
285                         if (d->d_name[0] != '.') {
286                                 snprintf(filename, sizeof filename, "%s/%s", ctdl_db_dir, d->d_name);
287                                 syslog(LOG_DEBUG, "bdb: chmod(%s, 0600) returned %d", filename, chmod(filename, 0600));
288                                 syslog(LOG_DEBUG, "bdb: chown(%s, CTDLUID, -1) returned %d", filename, chown(filename, CTDLUID, (-1)));
289                         }
290                 }
291                 closedir(dp);
292         }
293 }
294
295
296 // 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.
297 void bdb_close_databases(void) {
298         int i;
299         int ret;
300
301         static int closing = 0;
302         while (closing == 1) {
303                 syslog(LOG_INFO, "bdb: already closing");
304         }
305         closing = 1;
306
307         syslog(LOG_INFO, "bdb: performing final checkpoint");
308         if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
309                 syslog(LOG_ERR, "bdb: txn_checkpoint: %s", db_strerror(ret));
310         }
311
312         syslog(LOG_INFO, "bdb: flushing the database logs");
313         if ((ret = dbenv->log_flush(dbenv, NULL))) {
314                 syslog(LOG_ERR, "bdb: log_flush: %s", db_strerror(ret));
315         }
316
317         // close the tables
318         syslog(LOG_INFO, "bdb: closing databases");
319         for (i = 0; i < MAXCDB; ++i) {
320                 syslog(LOG_INFO, "bdb: closing database %02x", i);
321                 ret = dbp[i]->close(dbp[i], 0);
322                 if (ret) {
323                         syslog(LOG_ERR, "bdb: db_close: %s", db_strerror(ret));
324                 }
325         }
326
327         // Close the handle.
328         ret = dbenv->close(dbenv, DB_FORCESYNC);
329         if (ret) {
330                 syslog(LOG_ERR, "bdb: DBENV->close: %s", db_strerror(ret));
331         }
332 }
333
334
335 // Decompress a database item if it was compressed on disk
336 void bdb_decompress_if_necessary(struct cdbdata *cdb) {
337         static int magic = COMPRESS_MAGIC;
338
339         if ((cdb == NULL) || (cdb->ptr == NULL) || (cdb->len < sizeof(magic)) || (memcmp(cdb->ptr, &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) > cdb->len) {
354                 cplen = cdb->len;
355         }
356         memcpy(&zheader, cdb->ptr, cplen);
357
358         compressed_data = cdb->ptr;
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(cdb->ptr);
372         cdb->len = (size_t) destLen;
373         cdb->ptr = 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 = dbp[cdb]->put(dbp[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 = dbp[cdb]->put(dbp[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 = dbp[cdb]->del(dbp[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 = dbp[cdb]->del(dbp[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 = dbp[cdb]->cursor(dbp[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.  If not found, returns NULL.  Otherwise, it returns
528 // a struct cdbdata which it is the caller's responsibility to free later on
529 // using the bdb_free() routine.
530 struct cdbdata *bdb_fetch(int cdb, const void *key, int keylen) {
531
532         if (keylen == 0) {              // key length zero is impossible
533                 return(NULL);
534         }
535
536         struct cdbdata *tempcdb;
537         DBT dkey, dret;
538         int ret;
539
540         memset(&dkey, 0, sizeof(DBT));
541         dkey.size = keylen;
542         dkey.data = (void *) key;
543
544         if (TSD->tid != NULL) {
545                 memset(&dret, 0, sizeof(DBT));
546                 dret.flags = DB_DBT_MALLOC;
547                 ret = dbp[cdb]->get(dbp[cdb], TSD->tid, &dkey, &dret, 0);
548         }
549         else {
550                 DBC *curs;
551
552                 do {
553                         memset(&dret, 0, sizeof(DBT));
554                         dret.flags = DB_DBT_MALLOC;
555                         curs = bdb_localcursor(cdb);
556                         ret = curs->c_get(curs, &dkey, &dret, DB_SET);
557                         bdb_cclose(curs);
558                 } while (ret == DB_LOCK_DEADLOCK);
559         }
560
561         if ((ret != 0) && (ret != DB_NOTFOUND)) {
562                 syslog(LOG_ERR, "bdb: bdb_fetch(%d): %s", cdb, db_strerror(ret));
563                 bdb_abort();
564         }
565
566         if (ret != 0) {
567                 return NULL;
568         }
569
570         tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
571         if (tempcdb == NULL) {
572                 syslog(LOG_ERR, "bdb: bdb_fetch() cannot allocate memory for tempcdb: %m");
573                 bdb_abort();
574         }
575         else {
576                 tempcdb->len = dret.size;
577                 tempcdb->ptr = dret.data;
578                 bdb_decompress_if_necessary(tempcdb);
579                 return (tempcdb);
580         }
581 }
582
583
584 // Free a cdbdata item.
585 //
586 // Note that we only free the 'ptr' portion if it is not NULL.  This allows
587 // other code to assume ownership of that memory simply by storing the
588 // pointer elsewhere and then setting 'ptr' to NULL.  bdb_free() will then
589 // avoid freeing it.
590 void bdb_free(struct cdbdata *cdb) {
591         if (cdb->ptr) {
592                 free(cdb->ptr);
593         }
594         free(cdb);
595 }
596
597
598 void bdb_close_cursor(int cdb) {
599         if (TSD->cursors[cdb] != NULL) {
600                 bdb_cclose(TSD->cursors[cdb]);
601         }
602
603         TSD->cursors[cdb] = NULL;
604 }
605
606
607 // Prepare for a sequential search of an entire database.
608 // (There is guaranteed to be no more than one traversal in
609 // progress per thread at any given time.)
610 void bdb_rewind(int cdb) {
611         int ret = 0;
612
613         if (TSD->cursors[cdb] != NULL) {
614                 syslog(LOG_ERR, "bdb: bdb_rewind: must close cursor on database %d before reopening", cdb);
615                 bdb_abort();
616                 // bdb_cclose(TSD->cursors[cdb]);
617         }
618
619         // Now initialize the cursor
620         ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &TSD->cursors[cdb], 0);
621         if (ret) {
622                 syslog(LOG_ERR, "bdb: bdb_rewind: db_cursor: %s", db_strerror(ret));
623                 bdb_abort();
624         }
625 }
626
627
628 // Fetch the next item in a sequential search.  Returns a pointer to a 
629 // cdbdata structure, or NULL if we've hit the end.
630 struct cdbdata *bdb_next_item(int cdb) {
631         DBT key, data;
632         struct cdbdata *cdbret;
633         int ret = 0;
634
635         // Initialize the key/data pair so the flags aren't set.
636         memset(&key, 0, sizeof(key));
637         memset(&data, 0, sizeof(data));
638         data.flags = DB_DBT_MALLOC;
639
640         ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &key, &data, DB_NEXT);
641
642         if (ret) {
643                 if (ret != DB_NOTFOUND) {
644                         syslog(LOG_ERR, "bdb: bdb_next_item(%d): %s", cdb, db_strerror(ret));
645                         bdb_abort();
646                 }
647                 bdb_close_cursor(cdb);
648                 return NULL;    // presumably, end of file
649         }
650
651         cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
652         cdbret->len = data.size;
653         cdbret->ptr = data.data;
654         bdb_decompress_if_necessary(cdbret);
655
656         return (cdbret);
657 }
658
659
660 // Transaction-based stuff.  I'm writing this as I bake cookies...
661 void bdb_begin_transaction(void) {
662         bdb_bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
663
664         if (TSD->tid != NULL) {
665                 syslog(LOG_ERR, "bdb: bdb_begin_transaction: ERROR: nested transaction");
666                 bdb_abort();
667         }
668
669         bdb_txbegin(&TSD->tid);
670 }
671
672
673 void bdb_end_transaction(void) {
674         int i;
675
676         for (i = 0; i < MAXCDB; i++) {
677                 if (TSD->cursors[i] != NULL) {
678                         syslog(LOG_WARNING, "bdb: bdb_end_transaction: WARNING: cursor %d still open at transaction end", i);
679                         bdb_cclose(TSD->cursors[i]);
680                         TSD->cursors[i] = NULL;
681                 }
682         }
683
684         if (TSD->tid == NULL) {
685                 syslog(LOG_ERR, "bdb: bdb_end_transaction: ERROR: bdb_txcommit(NULL) !!");
686                 bdb_abort();
687         }
688         else {
689                 bdb_txcommit(TSD->tid);
690         }
691
692         TSD->tid = NULL;
693 }
694
695
696 // Truncate (delete every record)
697 void bdb_trunc(int cdb) {
698         int ret;
699         u_int32_t count;
700
701         if (TSD->tid != NULL) {
702                 syslog(LOG_ERR, "bdb: bdb_trunc must not be called in a transaction.");
703                 bdb_abort();
704         }
705         else {
706                 bdb_bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
707
708               retry:
709
710                 if ((ret = dbp[cdb]->truncate(dbp[cdb], // db
711                                               NULL,     // transaction ID
712                                               &count,   // #rows deleted
713                                               0))) {    // flags
714                         if (ret == DB_LOCK_DEADLOCK) {
715                                 goto retry;
716                         }
717                         else {
718                                 syslog(LOG_ERR, "bdb: bdb_truncate(%d): %s", cdb, db_strerror(ret));
719                                 if (ret == ENOMEM) {
720                                         syslog(LOG_ERR, "bdb: You may need to tune your database; please read http://www.citadel.org for more information.");
721                                 }
722                                 exit(CTDLEXIT_DB);
723                         }
724                 }
725         }
726 }
727
728
729 // compact (defragment) the database, possibly returning space back to the underlying filesystem
730 void bdb_compact(void) {
731         int ret;
732         int i;
733
734         syslog(LOG_DEBUG, "bdb: bdb_compact() started");
735         for (i = 0; i < MAXCDB; i++) {
736                 syslog(LOG_DEBUG, "bdb: compacting database %d", i);
737                 ret = dbp[i]->compact(dbp[i], NULL, NULL, NULL, NULL, DB_FREE_SPACE, NULL);
738                 if (ret) {
739                         syslog(LOG_ERR, "bdb: compact: %s", db_strerror(ret));
740                 }
741         }
742         syslog(LOG_DEBUG, "bdb: bdb_compact() finished");
743 }
744
745
746 // Calling this function activates the Berkeley DB back end.
747 void bdb_init_backend(void) {
748         cdb_compact = bdb_compact;
749         cdb_checkpoint = bdb_checkpoint;
750         cdb_rewind = bdb_rewind;
751         cdb_fetch = bdb_fetch;
752         cdb_open_databases = bdb_open_databases;
753         cdb_close_databases = bdb_close_databases;
754         cdb_store = bdb_store;
755         cdb_delete = bdb_delete;
756         cdb_free = bdb_free;
757         cdb_next_item = bdb_next_item;
758         cdb_close_cursor = bdb_close_cursor;
759         cdb_begin_transaction = bdb_begin_transaction;
760         cdb_end_transaction = bdb_end_transaction;
761         cdb_check_handles = bdb_check_handles;
762         cdb_trunc = bdb_trunc;
763         cdb_chmod_data = bdb_chmod_data;
764
765         syslog(LOG_INFO, "db: initialized Berkeley DB backend");
766 }
767
768