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