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