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