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