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