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