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