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