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