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