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