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