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