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