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