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