Switched back to the old style thread architecture in preparation for eventual migrat...
[citadel.git] / citadel / database.c
1 /*
2  * This is a data store backend for the Citadel server which uses Berkeley DB.
3  *
4  * Copyright (c) 1987-2011 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as published
8  * by the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  */
21
22 /*****************************************************************************
23        Tunable configuration parameters for the Berkeley DB back end
24  *****************************************************************************/
25
26 /* Citadel will checkpoint the db at the end of every session, but only if
27  * the specified number of kilobytes has been written, or if the specified
28  * number of minutes has passed, since the last checkpoint.
29  */
30 #define MAX_CHECKPOINT_KBYTES   256
31 #define MAX_CHECKPOINT_MINUTES  15
32
33 /*****************************************************************************/
34
35 #include "sysdep.h"
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <stdio.h>
39 #include <ctype.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <dirent.h>
45 #include <syslog.h>
46
47 #ifdef HAVE_DB_H
48 #include <db.h>
49 #elif defined(HAVE_DB4_DB_H)
50 #include <db4/db.h>
51 #else
52 #error Neither <db.h> nor <db4/db.h> was found by configure. Install db4-devel.
53 #endif
54
55
56 #if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 1
57 #error Citadel requires Berkeley DB v4.1 or newer.  Please upgrade.
58 #endif
59
60
61 #include <libcitadel.h>
62 #include "citadel.h"
63 #include "server.h"
64 #include "citserver.h"
65 #include "database.h"
66 #include "msgbase.h"
67 #include "sysdep_decls.h"
68 #include "threads.h"
69 #include "config.h"
70 #include "control.h"
71
72 #include "ctdl_module.h"
73
74
75 static DB *dbp[MAXCDB];         /* One DB handle for each Citadel database */
76 static DB_ENV *dbenv;           /* The DB environment (global) */
77
78
79 #ifdef HAVE_ZLIB
80 #include <zlib.h>
81 #endif
82
83
84 /* Verbose logging callback */
85 void cdb_verbose_log(const DB_ENV *dbenv, const char *msg)
86 {
87         if (!IsEmptyStr(msg)) {
88                 syslog(LOG_DEBUG, "DB: %s", msg);
89         }
90 }
91
92
93 /* Verbose logging callback */
94 void cdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg)
95 {
96         syslog(LOG_ALERT, "DB: %s", msg);
97 }
98
99
100 /* just a little helper function */
101 static void txabort(DB_TXN * tid)
102 {
103         int ret;
104
105         ret = tid->abort(tid);
106
107         if (ret) {
108                 syslog(LOG_EMERG, "bdb(): txn_abort: %s", db_strerror(ret));
109                 abort();
110         }
111 }
112
113 /* this one is even more helpful than the last. */
114 static void txcommit(DB_TXN * tid)
115 {
116         int ret;
117
118         ret = tid->commit(tid, 0);
119
120         if (ret) {
121                 syslog(LOG_EMERG, "bdb(): txn_commit: %s", db_strerror(ret));
122                 abort();
123         }
124 }
125
126 /* are you sensing a pattern yet? */
127 static void txbegin(DB_TXN ** tid)
128 {
129         int ret;
130
131         ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
132
133         if (ret) {
134                 syslog(LOG_EMERG, "bdb(): txn_begin: %s", db_strerror(ret));
135                 abort();
136         }
137 }
138
139 static void dbpanic(DB_ENV * env, int errval)
140 {
141         syslog(LOG_EMERG, "bdb(): PANIC: %s", db_strerror(errval));
142 }
143
144 static void cclose(DBC * cursor)
145 {
146         int ret;
147
148         if ((ret = cursor->c_close(cursor))) {
149                 syslog(LOG_EMERG, "bdb(): c_close: %s", db_strerror(ret));
150                 abort();
151         }
152 }
153
154 static void bailIfCursor(DBC ** cursors, const char *msg)
155 {
156         int i;
157
158         for (i = 0; i < MAXCDB; i++)
159                 if (cursors[i] != NULL) {
160                         syslog(LOG_EMERG, "bdb(): cursor still in progress on cdb %02x: %s", i, msg);
161                         abort();
162                 }
163 }
164
165
166 void cdb_check_handles(void)
167 {
168         bailIfCursor(TSD->cursors, "in check_handles");
169
170         if (TSD->tid != NULL) {
171                 syslog(LOG_EMERG, "bdb(): transaction still in progress!");
172                 abort();
173         }
174 }
175
176
177 /*
178  * Cull the database logs
179  */
180 static void cdb_cull_logs(void)
181 {
182         u_int32_t flags;
183         int ret;
184         char **file, **list;
185         char errmsg[SIZ];
186
187         flags = DB_ARCH_ABS;
188
189         /* Get the list of names. */
190         if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
191                 syslog(LOG_ERR, "cdb_cull_logs: %s", db_strerror(ret));
192                 return;
193         }
194
195         /* Print the list of names. */
196         if (list != NULL) {
197                 for (file = list; *file != NULL; ++file) {
198                         syslog(LOG_DEBUG, "Deleting log: %s", *file);
199                         ret = unlink(*file);
200                         if (ret != 0) {
201                                 snprintf(errmsg, sizeof(errmsg),
202                                          " ** ERROR **\n \n \n "
203                                          "Citadel was unable to delete the "
204                                          "database log file '%s' because of the "
205                                          "following error:\n \n %s\n \n"
206                                          " This log file is no longer in use "
207                                          "and may be safely deleted.\n",
208                                          *file, strerror(errno));
209                                 CtdlAideMessage(errmsg, "Database Warning Message");
210                         }
211                 }
212                 free(list);
213         }
214 }
215
216 /*
217  * Manually initiate log file cull.
218  */
219 void cmd_cull(char *argbuf) {
220         if (CtdlAccessCheck(ac_internal)) return;
221         cdb_cull_logs();
222         cprintf("%d Database log file cull completed.", CIT_OK);
223 }
224
225
226 /*
227  * Request a checkpoint of the database.  Called once per minute by the thread manager.
228  */
229 void cdb_checkpoint(void)
230 {
231         int ret;
232
233         syslog(LOG_DEBUG, "-- db checkpoint --");
234         ret = dbenv->txn_checkpoint(dbenv, MAX_CHECKPOINT_KBYTES, MAX_CHECKPOINT_MINUTES, 0);
235
236         if (ret != 0) {
237                 syslog(LOG_EMERG, "cdb_checkpoint: txn_checkpoint: %s", db_strerror(ret));
238                 abort();
239         }
240
241         /* After a successful checkpoint, we can cull the unused logs */
242         if (config.c_auto_cull) {
243                 cdb_cull_logs();
244         }
245 }
246
247
248
249 /*
250  * Open the various databases we'll be using.  Any database which
251  * does not exist should be created.  Note that we don't need a
252  * critical section here, because there aren't any active threads
253  * manipulating the database yet.
254  */
255 void open_databases(void)
256 {
257         int ret;
258         int i;
259         char dbfilename[32];
260         u_int32_t flags = 0;
261         int dbversion_major, dbversion_minor, dbversion_patch;
262         int current_dbversion = 0;
263
264         syslog(LOG_DEBUG, "bdb(): open_databases() starting");
265         syslog(LOG_DEBUG, "Compiled db: %s", DB_VERSION_STRING);
266         syslog(LOG_INFO, "  Linked db: %s",
267                 db_version(&dbversion_major, &dbversion_minor, &dbversion_patch));
268
269         current_dbversion = (dbversion_major * 1000000) + (dbversion_minor * 1000) + dbversion_patch;
270
271         syslog(LOG_DEBUG, "Calculated dbversion: %d", current_dbversion);
272         syslog(LOG_DEBUG, "  Previous dbversion: %d", CitControl.MMdbversion);
273
274         if ( (getenv("SUPPRESS_DBVERSION_CHECK") == NULL)
275            && (CitControl.MMdbversion > current_dbversion) ) {
276                 syslog(LOG_EMERG, "You are attempting to run the Citadel server using a version");
277                 syslog(LOG_EMERG, "of Berkeley DB that is older than that which last created or");
278                 syslog(LOG_EMERG, "updated the database.  Because this would probably cause data");
279                 syslog(LOG_EMERG, "corruption or loss, the server is aborting execution now.");
280                 exit(CTDLEXIT_DB);
281         }
282
283         CitControl.MMdbversion = current_dbversion;
284         put_control();
285
286 #ifdef HAVE_ZLIB
287         syslog(LOG_INFO, "Linked zlib: %s\n", zlibVersion());
288 #endif
289
290         /*
291          * Silently try to create the database subdirectory.  If it's
292          * already there, no problem.
293          */
294         if ((mkdir(ctdl_data_dir, 0700) != 0) && (errno != EEXIST)){
295                 syslog(LOG_EMERG, 
296                               "unable to create database directory [%s]: %s", 
297                               ctdl_data_dir, strerror(errno));
298         }
299         if (chmod(ctdl_data_dir, 0700) != 0){
300                 syslog(LOG_EMERG, 
301                               "unable to set database directory accessrights [%s]: %s", 
302                               ctdl_data_dir, strerror(errno));
303         }
304         if (chown(ctdl_data_dir, CTDLUID, (-1)) != 0){
305                 syslog(LOG_EMERG, 
306                               "unable to set the owner for [%s]: %s", 
307                               ctdl_data_dir, strerror(errno));
308         }
309         syslog(LOG_DEBUG, "bdb(): Setting up DB environment\n");
310         /* db_env_set_func_yield((int (*)(u_long,  u_long))sched_yield); */
311         ret = db_env_create(&dbenv, 0);
312         if (ret) {
313                 syslog(LOG_EMERG, "bdb(): db_env_create: %s\n", db_strerror(ret));
314                 syslog(LOG_EMERG, "exit code %d\n", ret);
315                 exit(CTDLEXIT_DB);
316         }
317         dbenv->set_errpfx(dbenv, "citserver");
318         dbenv->set_paniccall(dbenv, dbpanic);
319         dbenv->set_errcall(dbenv, cdb_verbose_err);
320         dbenv->set_errpfx(dbenv, "ctdl");
321 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 3)
322         dbenv->set_msgcall(dbenv, cdb_verbose_log);
323 #endif
324         dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
325         dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
326
327         /*
328          * We want to specify the shared memory buffer pool cachesize,
329          * but everything else is the default.
330          */
331         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
332         if (ret) {
333                 syslog(LOG_EMERG, "bdb(): set_cachesize: %s\n", db_strerror(ret));
334                 dbenv->close(dbenv, 0);
335                 syslog(LOG_EMERG, "exit code %d\n", ret);
336                 exit(CTDLEXIT_DB);
337         }
338
339         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
340                 syslog(LOG_EMERG, "bdb(): set_lk_detect: %s\n", db_strerror(ret));
341                 dbenv->close(dbenv, 0);
342                 syslog(LOG_EMERG, "exit code %d\n", ret);
343                 exit(CTDLEXIT_DB);
344         }
345
346         flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD | DB_RECOVER;
347         syslog(LOG_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", ctdl_data_dir, flags);
348         ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
349         if (ret == DB_RUNRECOVERY) {
350                 syslog(LOG_ALERT, "dbenv->open: %s\n", db_strerror(ret));
351                 syslog(LOG_ALERT, "Attempting recovery...\n");
352                 flags |= DB_RECOVER;
353                 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
354         }
355         if (ret == DB_RUNRECOVERY) {
356                 syslog(LOG_ALERT, "dbenv->open: %s\n", db_strerror(ret));
357                 syslog(LOG_ALERT, "Attempting catastrophic recovery...\n");
358                 flags &= ~DB_RECOVER;
359                 flags |= DB_RECOVER_FATAL;
360                 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
361         }
362         if (ret) {
363                 syslog(LOG_EMERG, "dbenv->open: %s\n", db_strerror(ret));
364                 dbenv->close(dbenv, 0);
365                 syslog(LOG_EMERG, "exit code %d\n", ret);
366                 exit(CTDLEXIT_DB);
367         }
368
369         syslog(LOG_INFO, "Starting up DB\n");
370
371         for (i = 0; i < MAXCDB; ++i) {
372
373                 /* Create a database handle */
374                 ret = db_create(&dbp[i], dbenv, 0);
375                 if (ret) {
376                         syslog(LOG_EMERG, "db_create: %s\n", db_strerror(ret));
377                         syslog(LOG_EMERG, "exit code %d\n", ret);
378                         exit(CTDLEXIT_DB);
379                 }
380
381
382                 /* Arbitrary names for our tables -- we reference them by
383                  * number, so we don't have string names for them.
384                  */
385                 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
386
387                 ret = dbp[i]->open(dbp[i],
388                                    NULL,
389                                    dbfilename,
390                                    NULL,
391                                    DB_BTREE,
392                                    DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
393                                    0600
394                 );
395                 if (ret) {
396                         syslog(LOG_EMERG, "db_open[%02x]: %s\n", i, db_strerror(ret));
397                         if (ret == ENOMEM) {
398                                 syslog(LOG_EMERG, "You may need to tune your database; please read http://www.citadel.org/doku.php/faq:troubleshooting:out_of_lock_entries for more information.\n");
399                         }
400                         syslog(LOG_EMERG, "exit code %d\n", ret);
401                         exit(CTDLEXIT_DB);
402                 }
403         }
404
405 }
406
407
408 /* Make sure we own all the files, because in a few milliseconds
409  * we're going to drop root privs.
410  */
411 void cdb_chmod_data(void) {
412         DIR *dp;
413         struct dirent *d;
414         char filename[PATH_MAX];
415
416         dp = opendir(ctdl_data_dir);
417         if (dp != NULL) {
418                 while (d = readdir(dp), d != NULL) {
419                         if (d->d_name[0] != '.') {
420                                 snprintf(filename, sizeof filename,
421                                          "%s/%s", ctdl_data_dir, d->d_name);
422                                 syslog(LOG_DEBUG, "chmod(%s, 0600) returned %d\n",
423                                         filename, chmod(filename, 0600)
424                                 );
425                                 syslog(LOG_DEBUG, "chown(%s, CTDLUID, -1) returned %d\n",
426                                         filename, chown(filename, CTDLUID, (-1))
427                                 );
428                         }
429                 }
430                 closedir(dp);
431         }
432
433         syslog(LOG_DEBUG, "open_databases() finished\n");
434         CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
435 }
436
437
438 /*
439  * Close all of the db database files we've opened.  This can be done
440  * in a loop, since it's just a bunch of closes.
441  */
442 void close_databases(void)
443 {
444         int a;
445         int ret;
446
447         if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
448                 syslog(LOG_EMERG,
449                         "txn_checkpoint: %s\n", db_strerror(ret));
450         }
451
452         /* print some statistics... */
453 #ifdef DB_STAT_ALL
454         dbenv->lock_stat_print(dbenv, DB_STAT_ALL);
455 #endif
456
457         /* close the tables */
458         for (a = 0; a < MAXCDB; ++a) {
459                 syslog(LOG_INFO, "Closing database %02x\n", a);
460                 ret = dbp[a]->close(dbp[a], 0);
461                 if (ret) {
462                         syslog(LOG_EMERG, "db_close: %s\n", db_strerror(ret));
463                 }
464
465         }
466
467         /* Close the handle. */
468         ret = dbenv->close(dbenv, 0);
469         if (ret) {
470                 syslog(LOG_EMERG, "DBENV->close: %s\n", db_strerror(ret));
471         }
472 }
473
474
475 /*
476  * Compression functions only used if we have zlib
477  */
478 void cdb_decompress_if_necessary(struct cdbdata *cdb)
479 {
480         static int magic = COMPRESS_MAGIC;
481
482         if ((cdb == NULL) || 
483             (cdb->ptr == NULL) || 
484             (cdb->len < sizeof(magic)) ||
485             (memcmp(cdb->ptr, &magic, sizeof(magic))))
486             return;
487
488 #ifdef HAVE_ZLIB
489         /* At this point we know we're looking at a compressed item. */
490
491         struct CtdlCompressHeader zheader;
492         char *uncompressed_data;
493         char *compressed_data;
494         uLongf destLen, sourceLen;
495         size_t cplen;
496
497         memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
498         cplen = sizeof(struct CtdlCompressHeader);
499         if (sizeof(struct CtdlCompressHeader) > cdb->len)
500                 cplen = cdb->len;
501         memcpy(&zheader, cdb->ptr, cplen);
502
503         compressed_data = cdb->ptr;
504         compressed_data += sizeof(struct CtdlCompressHeader);
505
506         sourceLen = (uLongf) zheader.compressed_len;
507         destLen = (uLongf) zheader.uncompressed_len;
508         uncompressed_data = malloc(zheader.uncompressed_len);
509
510         if (uncompress((Bytef *) uncompressed_data,
511                        (uLongf *) & destLen,
512                        (const Bytef *) compressed_data,
513                        (uLong) sourceLen) != Z_OK) {
514                 syslog(LOG_EMERG, "uncompress() error\n");
515                 abort();
516         }
517
518         free(cdb->ptr);
519         cdb->len = (size_t) destLen;
520         cdb->ptr = uncompressed_data;
521 #else                           /* HAVE_ZLIB */
522         syslog(LOG_EMERG, "Database contains compressed data, but this citserver was built without compression support.");
523         exit(CTDLEXIT_DB);
524 #endif                          /* HAVE_ZLIB */
525 }
526
527
528
529 /*
530  * Store a piece of data.  Returns 0 if the operation was successful.  If a
531  * key already exists it should be overwritten.
532  */
533 int cdb_store(int cdb, const void *ckey, int ckeylen, void *cdata, int cdatalen)
534 {
535
536         DBT dkey, ddata;
537         DB_TXN *tid;
538         int ret = 0;
539
540 #ifdef HAVE_ZLIB
541         struct CtdlCompressHeader zheader;
542         char *compressed_data = NULL;
543         int compressing = 0;
544         size_t buffer_len = 0;
545         uLongf destLen = 0;
546 #endif
547
548         memset(&dkey, 0, sizeof(DBT));
549         memset(&ddata, 0, sizeof(DBT));
550         dkey.size = ckeylen;
551         dkey.data = ckey;
552         ddata.size = cdatalen;
553         ddata.data = cdata;
554
555 #ifdef HAVE_ZLIB
556         /* Only compress Visit records.  Everything else is uncompressed. */
557         if (cdb == CDB_VISIT) {
558                 compressing = 1;
559                 zheader.magic = COMPRESS_MAGIC;
560                 zheader.uncompressed_len = cdatalen;
561                 buffer_len = ((cdatalen * 101) / 100) + 100
562                     + sizeof(struct CtdlCompressHeader);
563                 destLen = (uLongf) buffer_len;
564                 compressed_data = malloc(buffer_len);
565                 if (compress2((Bytef *) (compressed_data + sizeof(struct CtdlCompressHeader)),
566                         &destLen, (Bytef *) cdata, (uLongf) cdatalen, 1) != Z_OK)
567                 {
568                         syslog(LOG_EMERG, "compress2() error\n");
569                         abort();
570                 }
571                 zheader.compressed_len = (size_t) destLen;
572                 memcpy(compressed_data, &zheader, sizeof(struct CtdlCompressHeader));
573                 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) + zheader.compressed_len);
574                 ddata.data = compressed_data;
575         }
576 #endif
577
578         if (TSD->tid != NULL) {
579                 ret = dbp[cdb]->put(dbp[cdb],   /* db */
580                                     TSD->tid,   /* transaction ID */
581                                     &dkey,      /* key */
582                                     &ddata,     /* data */
583                                     0); /* flags */
584                 if (ret) {
585                         syslog(LOG_EMERG, "cdb_store(%d): %s", cdb, db_strerror(ret));
586                         abort();
587                 }
588 #ifdef HAVE_ZLIB
589                 if (compressing)
590                         free(compressed_data);
591 #endif
592                 return ret;
593
594         } else {
595                 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
596
597               retry:
598                 txbegin(&tid);
599
600                 if ((ret = dbp[cdb]->put(dbp[cdb],      /* db */
601                                          tid,   /* transaction ID */
602                                          &dkey, /* key */
603                                          &ddata,        /* data */
604                                          0))) { /* flags */
605                         if (ret == DB_LOCK_DEADLOCK) {
606                                 txabort(tid);
607                                 goto retry;
608                         } else {
609                                 syslog(LOG_EMERG, "cdb_store(%d): %s", cdb, db_strerror(ret));
610                                 abort();
611                         }
612                 } else {
613                         txcommit(tid);
614 #ifdef HAVE_ZLIB
615                         if (compressing) {
616                                 free(compressed_data);
617                         }
618 #endif
619                         return ret;
620                 }
621         }
622 }
623
624
625 /*
626  * Delete a piece of data.  Returns 0 if the operation was successful.
627  */
628 int cdb_delete(int cdb, void *key, int keylen)
629 {
630
631         DBT dkey;
632         DB_TXN *tid;
633         int ret;
634
635         memset(&dkey, 0, sizeof dkey);
636         dkey.size = keylen;
637         dkey.data = key;
638
639         if (TSD->tid != NULL) {
640                 ret = dbp[cdb]->del(dbp[cdb], TSD->tid, &dkey, 0);
641                 if (ret) {
642                         syslog(LOG_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
643                         if (ret != DB_NOTFOUND) {
644                                 abort();
645                         }
646                 }
647         } else {
648                 bailIfCursor(TSD->cursors, "attempt to delete during r/o cursor");
649
650               retry:
651                 txbegin(&tid);
652
653                 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
654                     && ret != DB_NOTFOUND) {
655                         if (ret == DB_LOCK_DEADLOCK) {
656                                 txabort(tid);
657                                 goto retry;
658                         } else {
659                                 syslog(LOG_EMERG, "cdb_delete(%d): %s\n",
660                                         cdb, db_strerror(ret));
661                                 abort();
662                         }
663                 } else {
664                         txcommit(tid);
665                 }
666         }
667         return ret;
668 }
669
670 static DBC *localcursor(int cdb)
671 {
672         int ret;
673         DBC *curs;
674
675         if (TSD->cursors[cdb] == NULL)
676                 ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &curs, 0);
677         else
678                 ret = TSD->cursors[cdb]->c_dup(TSD->cursors[cdb], &curs, DB_POSITION);
679
680         if (ret) {
681                 syslog(LOG_EMERG, "localcursor: %s\n", db_strerror(ret));
682                 abort();
683         }
684
685         return curs;
686 }
687
688
689 /*
690  * Fetch a piece of data.  If not found, returns NULL.  Otherwise, it returns
691  * a struct cdbdata which it is the caller's responsibility to free later on
692  * using the cdb_free() routine.
693  */
694 struct cdbdata *cdb_fetch(int cdb, const void *key, int keylen)
695 {
696
697         struct cdbdata *tempcdb;
698         DBT dkey, dret;
699         int ret;
700
701         memset(&dkey, 0, sizeof(DBT));
702         dkey.size = keylen;
703         dkey.data = key;
704
705         if (TSD->tid != NULL) {
706                 memset(&dret, 0, sizeof(DBT));
707                 dret.flags = DB_DBT_MALLOC;
708                 ret = dbp[cdb]->get(dbp[cdb], TSD->tid, &dkey, &dret, 0);
709         } else {
710                 DBC *curs;
711
712                 do {
713                         memset(&dret, 0, sizeof(DBT));
714                         dret.flags = DB_DBT_MALLOC;
715
716                         curs = localcursor(cdb);
717
718                         ret = curs->c_get(curs, &dkey, &dret, DB_SET);
719                         cclose(curs);
720                 }
721                 while (ret == DB_LOCK_DEADLOCK);
722
723         }
724
725         if ((ret != 0) && (ret != DB_NOTFOUND)) {
726                 syslog(LOG_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
727                 abort();
728         }
729
730         if (ret != 0)
731                 return NULL;
732         tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
733
734         if (tempcdb == NULL) {
735                 syslog(LOG_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
736                 abort();
737         }
738
739         tempcdb->len = dret.size;
740         tempcdb->ptr = dret.data;
741         cdb_decompress_if_necessary(tempcdb);
742         return (tempcdb);
743 }
744
745
746 /*
747  * Free a cdbdata item.
748  *
749  * Note that we only free the 'ptr' portion if it is not NULL.  This allows
750  * other code to assume ownership of that memory simply by storing the
751  * pointer elsewhere and then setting 'ptr' to NULL.  cdb_free() will then
752  * avoid freeing it.
753  */
754 void cdb_free(struct cdbdata *cdb)
755 {
756         if (cdb->ptr) {
757                 free(cdb->ptr);
758         }
759         free(cdb);
760 }
761
762 void cdb_close_cursor(int cdb)
763 {
764         if (TSD->cursors[cdb] != NULL) {
765                 cclose(TSD->cursors[cdb]);
766         }
767
768         TSD->cursors[cdb] = NULL;
769 }
770
771 /* 
772  * Prepare for a sequential search of an entire database.
773  * (There is guaranteed to be no more than one traversal in
774  * progress per thread at any given time.)
775  */
776 void cdb_rewind(int cdb)
777 {
778         int ret = 0;
779
780         if (TSD->cursors[cdb] != NULL) {
781                 syslog(LOG_EMERG,
782                         "cdb_rewind: must close cursor on database %d before reopening.\n", cdb);
783                 abort();
784                 /* cclose(TSD->cursors[cdb]); */
785         }
786
787         /*
788          * Now initialize the cursor
789          */
790         ret = dbp[cdb]->cursor(dbp[cdb], TSD->tid, &TSD->cursors[cdb], 0);
791         if (ret) {
792                 syslog(LOG_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
793                 abort();
794         }
795 }
796
797
798 /*
799  * Fetch the next item in a sequential search.  Returns a pointer to a 
800  * cdbdata structure, or NULL if we've hit the end.
801  */
802 struct cdbdata *cdb_next_item(int cdb)
803 {
804         DBT key, data;
805         struct cdbdata *cdbret;
806         int ret = 0;
807
808         /* Initialize the key/data pair so the flags aren't set. */
809         memset(&key, 0, sizeof(key));
810         memset(&data, 0, sizeof(data));
811         data.flags = DB_DBT_MALLOC;
812
813         ret = TSD->cursors[cdb]->c_get(TSD->cursors[cdb], &key, &data, DB_NEXT);
814
815         if (ret) {
816                 if (ret != DB_NOTFOUND) {
817                         syslog(LOG_EMERG, "cdb_next_item(%d): %s\n", cdb, db_strerror(ret));
818                         abort();
819                 }
820                 cdb_close_cursor(cdb);
821                 return NULL;    /* presumably, end of file */
822         }
823
824         cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
825         cdbret->len = data.size;
826         cdbret->ptr = data.data;
827         cdb_decompress_if_necessary(cdbret);
828
829         return (cdbret);
830 }
831
832
833
834 /*
835  * Transaction-based stuff.  I'm writing this as I bake cookies...
836  */
837
838 void cdb_begin_transaction(void)
839 {
840
841         bailIfCursor(TSD->cursors, "can't begin transaction during r/o cursor");
842
843         if (TSD->tid != NULL) {
844                 syslog(LOG_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
845                 abort();
846         }
847
848         txbegin(&TSD->tid);
849 }
850
851 void cdb_end_transaction(void)
852 {
853         int i;
854
855         for (i = 0; i < MAXCDB; i++)
856                 if (TSD->cursors[i] != NULL) {
857                         syslog(LOG_WARNING,
858                                 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
859                                 i);
860                         cclose(TSD->cursors[i]);
861                         TSD->cursors[i] = NULL;
862                 }
863
864         if (TSD->tid == NULL) {
865                 syslog(LOG_EMERG,
866                         "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
867                 abort();
868         } else {
869                 txcommit(TSD->tid);
870         }
871
872         TSD->tid = NULL;
873 }
874
875 /*
876  * Truncate (delete every record)
877  */
878 void cdb_trunc(int cdb)
879 {
880         /* DB_TXN *tid; */
881         int ret;
882         u_int32_t count;
883
884         if (TSD->tid != NULL) {
885                 syslog(LOG_EMERG, "cdb_trunc must not be called in a transaction.");
886                 abort();
887         } else {
888                 bailIfCursor(TSD->cursors, "attempt to write during r/o cursor");
889
890               retry:
891                 /* txbegin(&tid); */
892
893                 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
894                                               NULL,     /* transaction ID */
895                                               &count,   /* #rows deleted */
896                                               0))) {    /* flags */
897                         if (ret == DB_LOCK_DEADLOCK) {
898                                 /* txabort(tid); */
899                                 goto retry;
900                         } else {
901                                 syslog(LOG_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));
902                                 if (ret == ENOMEM) {
903                                         syslog(LOG_EMERG, "You may need to tune your database; please read http://www.citadel.org/doku.php/faq:troubleshooting:out_of_lock_entries for more information.");
904                                 }
905                                 exit(CTDLEXIT_DB);
906                         }
907                 } else {
908                         /* txcommit(tid); */
909                 }
910         }
911 }