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