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