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