]> code.citadel.org Git - citadel.git/blob - citadel/database_sleepycat.c
Activate verbose logging in Berkeley DB
[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(ret);
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         dbenv->set_verbose(dbenv, DB_VERB_REGISTER, 1);
373
374         /*
375          * We want to specify the shared memory buffer pool cachesize,
376          * but everything else is the default.
377          */
378         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
379         if (ret) {
380                 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
381                         db_strerror(ret));
382                 dbenv->close(dbenv, 0);
383                 exit(ret);
384         }
385
386         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
387                 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
388                         db_strerror(ret));
389                 dbenv->close(dbenv, 0);
390                 exit(ret);
391         }
392
393         flags =
394             DB_CREATE | DB_RECOVER | DB_INIT_MPOOL |
395             DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
396         lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n",
397                 ctdl_data_dir, flags);
398         ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
399         if (ret) {
400                 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
401                         db_strerror(ret));
402                 dbenv->close(dbenv, 0);
403                 exit(ret);
404         }
405
406         lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
407
408         for (i = 0; i < MAXCDB; ++i) {
409
410                 /* Create a database handle */
411                 ret = db_create(&dbp[i], dbenv, 0);
412                 if (ret) {
413                         lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
414                                 db_strerror(ret));
415                         exit(ret);
416                 }
417
418
419                 /* Arbitrary names for our tables -- we reference them by
420                  * number, so we don't have string names for them.
421                  */
422                 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
423
424                 ret = dbp[i]->open(dbp[i],
425                                    NULL,
426                                    dbfilename,
427                                    NULL,
428                                    DB_BTREE,
429                                    DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
430                                    0600);
431                 if (ret) {
432                         lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
433                                 db_strerror(ret));
434                         exit(ret);
435                 }
436         }
437
438         if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
439                 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
440                         strerror(ret));
441                 exit(1);
442         }
443
444         cdb_allocate_tsd();
445
446         /* Now make sure we own all the files, because in a few milliseconds
447          * we're going to drop root privs.
448          */
449         dp = opendir(ctdl_data_dir);
450         if (dp != NULL) {
451                 while (d = readdir(dp), d != NULL) {
452                         if (d->d_name[0] != '.') {
453                                 snprintf(filename, sizeof filename,
454                                          "%s/%s", ctdl_data_dir, d->d_name);
455                                 chmod(filename, 0600);
456                                 chown(filename, CTDLUID, (-1));
457                         }
458                 }
459                 closedir(dp);
460         }
461
462         lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
463
464         CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
465 }
466
467
468 /*
469  * Close all of the db database files we've opened.  This can be done
470  * in a loop, since it's just a bunch of closes.
471  */
472 void close_databases(void)
473 {
474         int a;
475         int ret;
476
477         cdb_free_tsd();
478
479         if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
480                 lprintf(CTDL_EMERG,
481                         "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
482         }
483
484         for (a = 0; a < MAXCDB; ++a) {
485                 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
486                 ret = dbp[a]->close(dbp[a], 0);
487                 if (ret) {
488                         lprintf(CTDL_EMERG,
489                                 "cdb_*: db_close: %s\n", db_strerror(ret));
490                 }
491
492         }
493
494         /* Close the handle. */
495         ret = dbenv->close(dbenv, 0);
496         if (ret) {
497                 lprintf(CTDL_EMERG,
498                         "cdb_*: DBENV->close: %s\n", db_strerror(ret));
499         }
500 }
501
502
503 /*
504  * Compression functions only used if we have zlib
505  */
506 #ifdef HAVE_ZLIB
507
508 void cdb_decompress_if_necessary(struct cdbdata *cdb)
509 {
510         static int magic = COMPRESS_MAGIC;
511         struct CtdlCompressHeader zheader;
512         char *uncompressed_data;
513         char *compressed_data;
514         uLongf destLen, sourceLen;
515
516         if (cdb == NULL)
517                 return;
518         if (cdb->ptr == NULL)
519                 return;
520         if (memcmp(cdb->ptr, &magic, sizeof(magic)))
521                 return;
522
523         /* At this point we know we're looking at a compressed item. */
524         memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
525
526         compressed_data = cdb->ptr;
527         compressed_data += sizeof(struct CtdlCompressHeader);
528
529         sourceLen = (uLongf) zheader.compressed_len;
530         destLen = (uLongf) zheader.uncompressed_len;
531         uncompressed_data = malloc(zheader.uncompressed_len);
532
533         if (uncompress((Bytef *) uncompressed_data,
534                        (uLongf *) & destLen,
535                        (const Bytef *) compressed_data,
536                        (uLong) sourceLen) != Z_OK) {
537                 lprintf(CTDL_EMERG, "uncompress() error\n");
538                 abort();
539         }
540
541         free(cdb->ptr);
542         cdb->len = (size_t) destLen;
543         cdb->ptr = uncompressed_data;
544 }
545
546 #endif                          /* HAVE_ZLIB */
547
548
549 /*
550  * Store a piece of data.  Returns 0 if the operation was successful.  If a
551  * key already exists it should be overwritten.
552  */
553 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
554 {
555
556         DBT dkey, ddata;
557         DB_TXN *tid;
558         int ret;
559
560 #ifdef HAVE_ZLIB
561         struct CtdlCompressHeader zheader;
562         char *compressed_data = NULL;
563         int compressing = 0;
564         size_t buffer_len;
565         uLongf destLen;
566 #endif
567
568         memset(&dkey, 0, sizeof(DBT));
569         memset(&ddata, 0, sizeof(DBT));
570         dkey.size = ckeylen;
571         dkey.data = ckey;
572         ddata.size = cdatalen;
573         ddata.data = cdata;
574
575 #ifdef HAVE_ZLIB
576         /* Only compress Visit records.  Everything else is uncompressed. */
577         if (cdb == CDB_VISIT) {
578                 compressing = 1;
579                 zheader.magic = COMPRESS_MAGIC;
580                 zheader.uncompressed_len = cdatalen;
581                 buffer_len = ((cdatalen * 101) / 100) + 100
582                     + sizeof(struct CtdlCompressHeader);
583                 destLen = (uLongf) buffer_len;
584                 compressed_data = malloc(buffer_len);
585                 if (compress2((Bytef *) (compressed_data +
586                                          sizeof(struct
587                                                 CtdlCompressHeader)),
588                               &destLen, (Bytef *) cdata, (uLongf) cdatalen,
589                               1) != Z_OK) {
590                         lprintf(CTDL_EMERG, "compress2() error\n");
591                         abort();
592                 }
593                 zheader.compressed_len = (size_t) destLen;
594                 memcpy(compressed_data, &zheader,
595                        sizeof(struct CtdlCompressHeader));
596                 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
597                                        zheader.compressed_len);
598                 ddata.data = compressed_data;
599         }
600 #endif
601
602         if (MYTID != NULL) {
603                 ret = dbp[cdb]->put(dbp[cdb],   /* db */
604                                     MYTID,      /* transaction ID */
605                                     &dkey,      /* key */
606                                     &ddata,     /* data */
607                                     0); /* flags */
608                 if (ret) {
609                         lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
610                                 db_strerror(ret));
611                         abort();
612                 }
613 #ifdef HAVE_ZLIB
614                 if (compressing)
615                         free(compressed_data);
616 #endif
617                 return ret;
618
619         } else {
620                 bailIfCursor(MYCURSORS,
621                              "attempt to write during r/o cursor");
622
623               retry:
624                 txbegin(&tid);
625
626                 if ((ret = dbp[cdb]->put(dbp[cdb],      /* db */
627                                          tid,   /* transaction ID */
628                                          &dkey, /* key */
629                                          &ddata,        /* data */
630                                          0))) { /* flags */
631                         if (ret == DB_LOCK_DEADLOCK) {
632                                 txabort(tid);
633                                 goto retry;
634                         } else {
635                                 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
636                                         cdb, db_strerror(ret));
637                                 abort();
638                         }
639                 } else {
640                         txcommit(tid);
641 #ifdef HAVE_ZLIB
642                         if (compressing)
643                                 free(compressed_data);
644 #endif
645                         return ret;
646                 }
647         }
648 }
649
650
651 /*
652  * Delete a piece of data.  Returns 0 if the operation was successful.
653  */
654 int cdb_delete(int cdb, void *key, int keylen)
655 {
656
657         DBT dkey;
658         DB_TXN *tid;
659         int ret;
660
661         memset(&dkey, 0, sizeof dkey);
662         dkey.size = keylen;
663         dkey.data = key;
664
665         if (MYTID != NULL) {
666                 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
667                 if (ret) {
668                         lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
669                                 db_strerror(ret));
670                         if (ret != DB_NOTFOUND)
671                                 abort();
672                 }
673         } else {
674                 bailIfCursor(MYCURSORS,
675                              "attempt to delete during r/o cursor");
676
677               retry:
678                 txbegin(&tid);
679
680                 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
681                     && ret != DB_NOTFOUND) {
682                         if (ret == DB_LOCK_DEADLOCK) {
683                                 txabort(tid);
684                                 goto retry;
685                         } else {
686                                 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
687                                         cdb, db_strerror(ret));
688                                 abort();
689                         }
690                 } else {
691                         txcommit(tid);
692                 }
693         }
694         return ret;
695 }
696
697 static DBC *localcursor(int cdb)
698 {
699         int ret;
700         DBC *curs;
701
702         if (MYCURSORS[cdb] == NULL)
703                 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
704         else
705                 ret =
706                     MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
707                                           DB_POSITION);
708
709         if (ret) {
710                 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
711                 abort();
712         }
713
714         return curs;
715 }
716
717
718 /*
719  * Fetch a piece of data.  If not found, returns NULL.  Otherwise, it returns
720  * a struct cdbdata which it is the caller's responsibility to free later on
721  * using the cdb_free() routine.
722  */
723 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
724 {
725
726         struct cdbdata *tempcdb;
727         DBT dkey, dret;
728         int ret;
729
730         memset(&dkey, 0, sizeof(DBT));
731         dkey.size = keylen;
732         dkey.data = key;
733
734         if (MYTID != NULL) {
735                 memset(&dret, 0, sizeof(DBT));
736                 dret.flags = DB_DBT_MALLOC;
737                 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
738         } else {
739                 DBC *curs;
740
741                 do {
742                         memset(&dret, 0, sizeof(DBT));
743                         dret.flags = DB_DBT_MALLOC;
744
745                         curs = localcursor(cdb);
746
747                         ret = curs->c_get(curs, &dkey, &dret, DB_SET);
748                         cclose(curs);
749                 }
750                 while (ret == DB_LOCK_DEADLOCK);
751
752         }
753
754         if ((ret != 0) && (ret != DB_NOTFOUND)) {
755                 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
756                         db_strerror(ret));
757                 abort();
758         }
759
760         if (ret != 0)
761                 return NULL;
762         tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
763
764         if (tempcdb == NULL) {
765                 lprintf(CTDL_EMERG,
766                         "cdb_fetch: Cannot allocate memory for tempcdb\n");
767                 abort();
768         }
769
770         tempcdb->len = dret.size;
771         tempcdb->ptr = dret.data;
772 #ifdef HAVE_ZLIB
773         cdb_decompress_if_necessary(tempcdb);
774 #endif
775         return (tempcdb);
776 }
777
778
779 /*
780  * Free a cdbdata item.
781  *
782  * Note that we only free the 'ptr' portion if it is not NULL.  This allows
783  * other code to assume ownership of that memory simply by storing the
784  * pointer elsewhere and then setting 'ptr' to NULL.  cdb_free() will then
785  * avoid freeing it.
786  */
787 void cdb_free(struct cdbdata *cdb)
788 {
789         if (cdb->ptr) {
790                 free(cdb->ptr);
791         }
792         free(cdb);
793 }
794
795 void cdb_close_cursor(int cdb)
796 {
797         if (MYCURSORS[cdb] != NULL)
798                 cclose(MYCURSORS[cdb]);
799
800         MYCURSORS[cdb] = NULL;
801 }
802
803 /* 
804  * Prepare for a sequential search of an entire database.
805  * (There is guaranteed to be no more than one traversal in
806  * progress per thread at any given time.)
807  */
808 void cdb_rewind(int cdb)
809 {
810         int ret = 0;
811
812         if (MYCURSORS[cdb] != NULL) {
813                 lprintf(CTDL_EMERG,
814                         "cdb_rewind: must close cursor on database %d before reopening.\n",
815                         cdb);
816                 abort();
817                 /* cclose(MYCURSORS[cdb]); */
818         }
819
820         /*
821          * Now initialize the cursor
822          */
823         ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
824         if (ret) {
825                 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
826                         db_strerror(ret));
827                 abort();
828         }
829 }
830
831
832 /*
833  * Fetch the next item in a sequential search.  Returns a pointer to a 
834  * cdbdata structure, or NULL if we've hit the end.
835  */
836 struct cdbdata *cdb_next_item(int cdb)
837 {
838         DBT key, data;
839         struct cdbdata *cdbret;
840         int ret = 0;
841
842         /* Initialize the key/data pair so the flags aren't set. */
843         memset(&key, 0, sizeof(key));
844         memset(&data, 0, sizeof(data));
845         data.flags = DB_DBT_MALLOC;
846
847         ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
848
849         if (ret) {
850                 if (ret != DB_NOTFOUND) {
851                         lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
852                                 cdb, db_strerror(ret));
853                         abort();
854                 }
855                 cclose(MYCURSORS[cdb]);
856                 MYCURSORS[cdb] = NULL;
857                 return NULL;    /* presumably, end of file */
858         }
859
860         cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
861         cdbret->len = data.size;
862         cdbret->ptr = data.data;
863 #ifdef HAVE_ZLIB
864         cdb_decompress_if_necessary(cdbret);
865 #endif
866
867         return (cdbret);
868 }
869
870
871
872 /*
873  * Transaction-based stuff.  I'm writing this as I bake cookies...
874  */
875
876 void cdb_begin_transaction(void)
877 {
878
879         bailIfCursor(MYCURSORS,
880                      "can't begin transaction during r/o cursor");
881
882         if (MYTID != NULL) {
883                 lprintf(CTDL_EMERG,
884                         "cdb_begin_transaction: ERROR: nested transaction\n");
885                 abort();
886         }
887
888         txbegin(&MYTID);
889 }
890
891 void cdb_end_transaction(void)
892 {
893         int i;
894
895         for (i = 0; i < MAXCDB; i++)
896                 if (MYCURSORS[i] != NULL) {
897                         lprintf(CTDL_WARNING,
898                                 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
899                                 i);
900                         cclose(MYCURSORS[i]);
901                         MYCURSORS[i] = NULL;
902                 }
903
904         if (MYTID == NULL) {
905                 lprintf(CTDL_EMERG,
906                         "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
907                 abort();
908         } else
909                 txcommit(MYTID);
910
911         MYTID = NULL;
912 }
913
914 /*
915  * Truncate (delete every record)
916  */
917 void cdb_trunc(int cdb)
918 {
919         /* DB_TXN *tid; */
920         int ret;
921         u_int32_t count;
922
923         if (MYTID != NULL) {
924                 lprintf(CTDL_EMERG,
925                         "cdb_trunc must not be called in a transaction.\n");
926                 abort();
927         } else {
928                 bailIfCursor(MYCURSORS,
929                              "attempt to write during r/o cursor");
930
931               retry:
932                 /* txbegin(&tid); */
933
934                 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
935                                               NULL,     /* transaction ID */
936                                               &count,   /* #rows deleted */
937                                               0))) {    /* flags */
938                         if (ret == DB_LOCK_DEADLOCK) {
939                                 /* txabort(tid); */
940                                 goto retry;
941                         } else {
942                                 lprintf(CTDL_EMERG,
943                                         "cdb_truncate(%d): %s\n", cdb,
944                                         db_strerror(ret));
945                                 abort();
946                         }
947                 } else {
948                         /* txcommit(tid); */
949                 }
950         }
951 }