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