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