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