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