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