5117bb59002db8fbd726aa9efa0127f3872935ac
[citadel.git] / citadel / database_sleepycat.c
1 /*
2  * $Id$
3  *
4  * Sleepycat (Berkeley) DB driver for Citadel/UX
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 an S_DATABASE
277  * critical section here, because there aren't any active threads manipulating
278  * the database yet -- and besides, it causes problems on BSDI.
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_THREAD
370                                 |DB_AUTO_COMMIT
371                                 ,
372                                 0600);
373                 if (ret) {
374                         lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
375                         exit(ret);
376                 }
377         }
378
379         if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
380                 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n", strerror(ret));
381                 exit(1);
382         }
383
384         cdb_allocate_tsd();
385         CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
386
387         /* Now make sure we own all the files, because in a few milliseconds
388          * we're going to drop root privs.
389          */
390         dp = opendir(dbdirname);
391         if (dp != NULL) {
392                 while (d = readdir(dp), d != NULL) {
393                         if (d->d_name[0] != '.') {
394                                 snprintf(filename, sizeof filename, "%s/%s",
395                                         dbdirname, d->d_name);
396                                 chmod(filename, 0600);
397                                 chown(filename, BBSUID, (-1) );
398                         }
399                 }
400                 closedir(dp);
401         }
402
403         lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
404 }
405
406
407 /*
408  * Close all of the db database files we've opened.  This can be done
409  * in a loop, since it's just a bunch of closes.
410  */
411 void close_databases(void)
412 {
413         int a;
414         int ret;
415
416         cdb_free_tsd();
417
418         if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
419                 lprintf(CTDL_EMERG, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
420                 abort();
421         }
422
423         for (a = 0; a < MAXCDB; ++a) {
424                 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
425                 ret = dbp[a]->close(dbp[a], 0);
426                 if (ret) {
427                         lprintf(CTDL_EMERG, "cdb_*: db_close: %s\n", db_strerror(ret));
428                         abort();
429                 }
430                 
431         }
432
433         /* Close the handle. */
434         ret = dbenv->close(dbenv, 0);
435         if (ret) {
436                 lprintf(CTDL_EMERG, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
437                 abort();
438         }
439 }
440
441
442 /*
443  * Compression functions only used if we have zlib
444  */
445 #ifdef HAVE_ZLIB
446
447 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
448         static int magic = COMPRESS_MAGIC;
449         struct CtdlCompressHeader zheader;
450         char *uncompressed_data;
451         char *compressed_data;
452         uLongf destLen, sourceLen;
453
454         if (cdb == NULL) return;
455         if (cdb->ptr == NULL) return;
456         if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
457
458         /* At this point we know we're looking at a compressed item. */
459         memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
460
461         compressed_data = cdb->ptr;
462         compressed_data += sizeof(struct CtdlCompressHeader);
463
464         sourceLen = (uLongf) zheader.compressed_len;
465         destLen = (uLongf) zheader.uncompressed_len;
466         uncompressed_data = malloc(zheader.uncompressed_len);
467
468         if (uncompress( (Bytef *) uncompressed_data,
469                         &destLen,
470                         compressed_data,
471                         sourceLen
472         ) != Z_OK) {
473                 lprintf(CTDL_EMERG, "uncompress() error\n");
474                 abort();
475         }
476
477         free(cdb->ptr);
478         cdb->len = (size_t) destLen;
479         cdb->ptr = uncompressed_data;
480 }
481
482 #endif  /* HAVE_ZLIB */
483         
484
485 /*
486  * Store a piece of data.  Returns 0 if the operation was successful.  If a
487  * key already exists it should be overwritten.
488  */
489 int cdb_store(int cdb,
490               void *ckey, int ckeylen,
491               void *cdata, int cdatalen)
492 {
493
494   DBT dkey, ddata;
495   DB_TXN *tid;
496   int ret;
497
498 #ifdef HAVE_ZLIB
499         struct CtdlCompressHeader zheader;
500         char *compressed_data = NULL;
501         int compressing = 0;
502         size_t buffer_len;
503         uLongf destLen;
504 #endif
505   
506   memset(&dkey, 0, sizeof(DBT));
507   memset(&ddata, 0, sizeof(DBT));
508   dkey.size = ckeylen;
509   dkey.data = ckey;
510   ddata.size = cdatalen;
511   ddata.data = cdata;
512
513 #ifdef HAVE_ZLIB
514         /* Only compress Visit records.  Everything else is uncompressed. */
515         if (cdb == CDB_VISIT) {
516                 compressing = 1;
517                 zheader.magic = COMPRESS_MAGIC;
518                 zheader.uncompressed_len = cdatalen;
519                 buffer_len = ( (cdatalen * 101) / 100 ) + 100
520                                 + sizeof(struct CtdlCompressHeader) ;
521                 destLen = (uLongf) buffer_len;
522                 compressed_data = malloc(buffer_len);
523                 if (compress2(
524                         (Bytef *) (compressed_data +
525                                         sizeof(struct CtdlCompressHeader)),
526                         &destLen,
527                         (Bytef *) cdata,
528                         (uLongf) cdatalen,
529                         1
530                 ) != Z_OK) {
531                         lprintf(CTDL_EMERG, "compress2() error\n");
532                         abort();
533                 }
534                 zheader.compressed_len = (size_t) destLen;
535                 memcpy(compressed_data, &zheader,
536                         sizeof(struct CtdlCompressHeader));
537                 ddata.size = (size_t)  (sizeof(struct CtdlCompressHeader) +
538                                                 zheader.compressed_len);
539                 ddata.data = compressed_data;
540         }
541 #endif
542   
543   if (MYTID != NULL)
544     {
545       ret = dbp[cdb]->put(dbp[cdb],             /* db */
546                           MYTID,                /* transaction ID */
547                           &dkey,                /* key */
548                           &ddata,               /* data */
549                           0);           /* flags */
550       if (ret)
551         {
552           lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
553           abort();
554         }
555 #ifdef HAVE_ZLIB
556       if (compressing) free(compressed_data);
557 #endif
558       return ret;
559       
560     }
561   else
562     {
563       bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
564       
565     retry:
566       txbegin(&tid);
567       
568       if ((ret = dbp[cdb]->put(dbp[cdb],    /* db */
569                                tid,         /* transaction ID */
570                                &dkey,       /* key */
571                                &ddata,      /* data */
572                                0)))         /* flags */
573         {
574           if (ret == DB_LOCK_DEADLOCK)
575             {
576               txabort(tid);
577               goto retry;
578             }
579           else
580             {
581               lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
582               abort();
583             }
584         }
585       else
586         {
587           txcommit(tid);
588 #ifdef HAVE_ZLIB
589           if (compressing) free(compressed_data);
590 #endif
591           return ret;
592         }
593     }
594 }
595
596
597 /*
598  * Delete a piece of data.  Returns 0 if the operation was successful.
599  */
600 int cdb_delete(int cdb, void *key, int keylen)
601 {
602
603   DBT dkey;
604   DB_TXN *tid;
605   int ret;
606
607   memset(&dkey, 0, sizeof dkey);
608   dkey.size = keylen;
609   dkey.data = key;
610
611   if (MYTID != NULL)
612     {
613       ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
614       if (ret)
615         {
616           lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
617           if (ret != DB_NOTFOUND)
618             abort();
619         }
620     }
621   else
622     {
623       bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
624     
625     retry:
626       txbegin(&tid);
627     
628       if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
629           && ret != DB_NOTFOUND)
630         {
631           if (ret == DB_LOCK_DEADLOCK)
632             {
633               txabort(tid);
634               goto retry;
635             }
636           else
637             {
638               lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
639               abort();
640             }
641         }
642       else
643         {
644           txcommit(tid);
645         }
646     }
647   return ret;
648 }
649
650 static DBC *localcursor(int cdb)
651 {
652   int ret;
653   DBC *curs;
654
655   if (MYCURSORS[cdb] == NULL)
656     ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
657   else
658     ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
659
660   if (ret)
661     {
662       lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
663       abort();
664     }
665
666   return curs;
667 }
668
669
670 /*
671  * Fetch a piece of data.  If not found, returns NULL.  Otherwise, it returns
672  * a struct cdbdata which it is the caller's responsibility to free later on
673  * using the cdb_free() routine.
674  */
675 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
676 {
677
678   struct cdbdata *tempcdb;
679   DBT dkey, dret;
680   int ret;
681
682   memset(&dkey, 0, sizeof(DBT));
683   dkey.size = keylen;
684   dkey.data = key;
685
686   if (MYTID != NULL)
687     {
688       memset(&dret, 0, sizeof(DBT));
689       dret.flags = DB_DBT_MALLOC;
690       ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
691     }
692   else
693     {
694       DBC *curs;
695
696       do
697         {
698           memset(&dret, 0, sizeof(DBT));
699           dret.flags = DB_DBT_MALLOC;
700
701           curs = localcursor(cdb);
702
703           ret = curs->c_get(curs, &dkey, &dret, DB_SET);
704           cclose(curs);
705         }
706       while (ret == DB_LOCK_DEADLOCK);
707
708     }
709
710   if ((ret != 0) && (ret != DB_NOTFOUND))
711     {
712       lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
713       abort();
714     }
715
716   if (ret != 0) return NULL;
717   tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
718
719   if (tempcdb == NULL)
720     {
721       lprintf(CTDL_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
722       abort();
723     }
724
725   tempcdb->len = dret.size;
726   tempcdb->ptr = dret.data;
727 #ifdef HAVE_ZLIB
728   cdb_decompress_if_necessary(tempcdb);
729 #endif
730   return (tempcdb);
731 }
732
733
734 /*
735  * Free a cdbdata item (ok, this is really no big deal, but we might need to do
736  * more complex stuff with other database managers in the future).
737  */
738 void cdb_free(struct cdbdata *cdb)
739 {
740         free(cdb->ptr);
741         free(cdb);
742 }
743
744 void cdb_close_cursor(int cdb)
745 {
746         if (MYCURSORS[cdb] != NULL)
747                 cclose(MYCURSORS[cdb]);
748
749         MYCURSORS[cdb] = NULL;
750 }
751
752 /* 
753  * Prepare for a sequential search of an entire database.
754  * (There is guaranteed to be no more than one traversal in
755  * progress per thread at any given time.)
756  */
757 void cdb_rewind(int cdb)
758 {
759         int ret = 0;
760
761         if (MYCURSORS[cdb] != NULL)
762                 cclose(MYCURSORS[cdb]);
763
764         /*
765          * Now initialize the cursor
766          */
767         ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
768         if (ret) {
769                 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
770                 abort();
771         }
772 }
773
774
775 /*
776  * Fetch the next item in a sequential search.  Returns a pointer to a 
777  * cdbdata structure, or NULL if we've hit the end.
778  */
779 struct cdbdata *cdb_next_item(int cdb)
780 {
781         DBT key, data;
782         struct cdbdata *cdbret;
783         int ret = 0;
784
785         /* Initialize the key/data pair so the flags aren't set. */
786         memset(&key, 0, sizeof(key));
787         memset(&data, 0, sizeof(data));
788         data.flags = DB_DBT_MALLOC;
789
790         ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
791                 &key, &data, DB_NEXT);
792         
793         if (ret) {
794                 if (ret != DB_NOTFOUND) {
795                         lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
796                                 cdb, db_strerror(ret));
797                         abort();
798                 }
799                 cclose(MYCURSORS[cdb]);
800                 MYCURSORS[cdb] = NULL;
801                 return NULL;            /* presumably, end of file */
802         }
803
804         cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
805         cdbret->len = data.size;
806         cdbret->ptr = data.data;
807 #ifdef HAVE_ZLIB
808         cdb_decompress_if_necessary(cdbret);
809 #endif
810
811         return (cdbret);
812 }
813
814
815
816 /*
817  * Transaction-based stuff.  I'm writing this as I bake cookies...
818  */
819
820 void cdb_begin_transaction(void) {
821
822   bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
823
824   if (MYTID != NULL)
825     {
826       lprintf(CTDL_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
827       abort();
828     }
829
830   txbegin(&MYTID);
831 }
832
833 void cdb_end_transaction(void) {
834   int i;
835
836   for (i = 0; i < MAXCDB; i++)
837     if (MYCURSORS[i] != NULL) {
838       lprintf(CTDL_WARNING, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
839       cclose(MYCURSORS[i]);
840       MYCURSORS[i] = NULL;
841     }
842
843   if (MYTID == NULL)
844     {
845       lprintf(CTDL_EMERG, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
846       abort();
847     }
848   else
849     txcommit(MYTID);
850
851   MYTID = NULL;
852 }
853
854 /*
855  * Truncate (delete every record)
856  */
857 void cdb_trunc(int cdb)
858 {
859   DB_TXN *tid;
860   int ret;
861   u_int32_t count;
862   
863   if (MYTID != NULL)
864     {
865       lprintf(CTDL_EMERG, "cdb_trunc must not be called in a transaction.\n");
866       abort();
867     }
868   else
869     {
870       bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
871       
872     retry:
873       txbegin(&tid);
874       
875       if ((ret = dbp[cdb]->truncate(dbp[cdb],    /* db */
876                                     tid,         /* transaction ID */
877                                     &count,      /* #rows deleted */
878                                     0)))         /* flags */
879         {
880           if (ret == DB_LOCK_DEADLOCK)
881             {
882               txabort(tid);
883               goto retry;
884             }
885           else
886             {
887               lprintf(CTDL_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));
888               abort();
889             }
890         }
891       else
892         {
893           txcommit(tid);
894         }
895     }
896 }