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