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