aboutsummaryrefslogtreecommitdiff
path: root/src/builtin/db.bi
blob: bf62e8a4d9d97ab6222aa61f6a4c845250345725 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
/* This file is part of Mailfromd.             -*- c -*-
   Copyright (C) 2006-2019 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

MF_BUILTIN_MODULE
#define DEFAULT_DB_MODE 0640
#include <fnmatch.h>

struct db_prop {                /* Database properties */
	char *pat;              /* Database name pattern */
	mode_t mode;            /* File mode */
	int null;               /* Null byte */
	mu_url_t hint;          /* Hint to use instead of the default one */
};

static mu_list_t db_prop_list;

static int
db_prop_compare(const void *item, const void *data)
{
	const struct db_prop *prop = item;
	const char *name = data;
	return strcmp(prop->pat, name);
}

static int
strtomode(char *str, mode_t *pmode)
{
	mode_t mode = 0;
	struct { char c; unsigned mask; } modetab[] = {
		{ 'r', S_IRUSR },
		{ 'w', S_IWUSR },
		{ 'x', S_IXUSR },
		{ 'r', S_IRGRP },
		{ 'w', S_IWGRP },
		{ 'x', S_IXGRP },
		{ 'r', S_IROTH },
		{ 'w', S_IWOTH },
		{ 'x', S_IXOTH },
		{ 0 }
	};
	int i;

	for (i = 0; modetab[i].c; i++) {
		if (!str[i])
			return i + 1;
		if (str[i] == modetab[i].c)
			mode |= modetab[i].mask;
		else if (str[i] != '-')
			return i + 1;
	}
	if (str[i])
		return i + 1;
	*pmode = mode;
	return 0;
}

static int
is_url(const char *p)
{
	for (; *p && mu_isalnum(*p); p++)
		;
	return *p == ':';
}
		
/* #pragma dbprop <name> [null] [mode] [hint]
   At least one of the bracketed parameters must be present.  Two or more
   parameters can be given in arbitrary order.
 */
MF_PRAGMA(dbprop, 3, 5)
{
	int null = 0;
	mode_t mode = DEFAULT_DB_MODE;
	struct db_prop *prop;
	int rc;
	char *pat;
	mu_url_t hint = NULL;

	--argc;
	pat = *++argv;
	
	while (--argc) {
		char *p = *++argv;

		if (strcmp(p, "null") == 0)
			null = 1;
		else if (mu_isdigit(*p)) {
			unsigned long n = strtoul(p, &p, 8);
			if (*p || (mode = n) != n) {
				parse_error(_("bad numeric file mode"));
				return;
			}
		} else if (is_url(p)) {
			rc = mu_url_create(&hint, p);
			if (rc) {
				parse_error(_("not a valid URL: %s"),
					    mu_strerror(rc));
				return;
			}
		} else if (rc = strtomode(p, &mode)) {
			parse_error(_("bad symbolic file mode (near %s)"),
				    p + rc - 1);
			return;
		}
	}

	if (!db_prop_list) {
		rc = mu_list_create(&db_prop_list);
		if (rc) {
			parse_error(_("cannot create list: %s"),
				    mu_strerror(rc));
			return;
		}
		mu_list_set_comparator(db_prop_list, db_prop_compare);
	}

	if (mu_list_locate(db_prop_list, pat, (void**) &prop)) {
		prop = mu_alloc(sizeof(*prop));
		prop->pat = mu_strdup(pat);
		rc = mu_list_append(db_prop_list, prop);
		if (rc) {
			parse_error(_("Cannot create list: %s"),
				    mu_strerror(rc));
			return;
		}
	}
	prop->mode = mode;
	prop->null = null;
	prop->hint = hint;
}

const struct db_prop *
db_prop_lookup(const char *name)
{
	mu_iterator_t itr;
	const struct db_prop *found = NULL;
	
	if (db_prop_list
	    && mu_list_get_iterator(db_prop_list, &itr) == 0) {
		for (mu_iterator_first(itr);
		     !mu_iterator_is_done(itr);
		     mu_iterator_next(itr)) {
			const struct db_prop *p;
			mu_iterator_current(itr, (void**)&p);
			if (strcmp(p->pat, name) == 0) {
				found = p;
				break;
			} else if (fnmatch(p->pat, name, 0) == 0)
				found = p;
		}
		mu_iterator_destroy(&itr);
	}
	return found;	
}

int 
_open_dbm(mu_dbm_file_t *pdb, char *dbname, int access, int mode,
	  mu_url_t hint)
{
	mu_dbm_file_t db;
	int rc;
	mu_url_t url;

	if (!hint)
		hint = mu_dbm_get_hint();
	rc = mu_url_create_hint(&url, dbname, 0, hint);
	if (rc) {
		mu_error(_("cannot create database URL for %s: %s"),
			 dbname, mu_strerror(rc));
		return rc;
	}
	rc = mu_dbm_create_from_url(url, &db,
				    mf_file_mode_to_safety_criteria(mode));
	mu_url_destroy(&url);
	if (rc)
		return rc;

	rc = mu_dbm_safety_check(db);
	if (rc && rc != ENOENT) {
		mu_error(_("%s fails safety check: %s"),
			 dbname, mu_strerror(rc));
		mu_dbm_destroy(&db);
		return rc;
	}

	rc = mu_dbm_open(db, access, mode);
	if (rc) {
		mu_dbm_destroy(&db);
		return rc;
	}
	*pdb = db;
	return rc;
}


#define LOOKUP_NULL_BYTE 0x1
#define LOOKUP_TEST_ONLY 0x2

MF_DSEXP_SUPPRESS([<dbmap_lookup>],[<
static int
dbmap_lookup(eval_environ_t env, char *dbname, const char *keystr,
	     const char *defval, const struct db_prop *prop, int flags)
{
	int rc;
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	struct mu_dbm_datum contents;
	
	if (!defval)
		defval = "";
	rc = _open_dbm(&db, dbname, MU_STREAM_READ,
		       prop ? prop->mode : DEFAULT_DB_MODE,
		       prop ? prop->hint : NULL);
	if (rc)
		MF_THROW(mfe_dbfailure,
			 _("mf_dbm_open(%s) failed: %s"),
			 dbname,
			 mu_strerror(rc));

	memset(&key, 0, sizeof key);
	memset(&contents, 0, sizeof contents);
	key.mu_dptr = (void*) keystr;
	key.mu_dsize = strlen(keystr);
	if (flags & LOOKUP_NULL_BYTE)
		key.mu_dsize++;
	rc = mu_dbm_fetch(db, &key, &contents);
	if (rc && rc != MU_ERR_NOENT) {
		mu_dbm_destroy(&db);
		MF_THROW(mfe_dbfailure,
			 _("cannot fetch data: %s"),
			 mu_dbm_strerror(db));
	}
	MF_DEBUG(MU_DEBUG_TRACE5,
                 ("Looking up %s: %s", keystr, rc ? "false" : "true"));
	if (flags & LOOKUP_TEST_ONLY) 
		push(env, (STKVAL) (rc == 0));
	else {
		if (rc) {
			if (defval)
				pushs(env, defval);
			else
				push(env, (STKVAL) 0L);
		} else if (((char*)contents.mu_dptr)[contents.mu_dsize-1]) {
			size_t off;
			size_t len = contents.mu_dsize;
			char *s = MF_ALLOC_HEAP(off, len + 1);
			memcpy(s, contents.mu_dptr, len);
			s[len] = 0;
			push(env, (STKVAL) off);
		} else
			pushs(env, contents.mu_dptr);
	}
	mu_dbm_datum_free(&contents);
	mu_dbm_destroy(&db);
	return rc;
}
>])

MF_DSEXP
MF_DEFUN(dbmap, NUMBER, STRING dbname, STRING key, OPTIONAL, NUMBER null)
{
	const struct db_prop *prop = db_prop_lookup(dbname);
	dbmap_lookup(env, dbname, key, NULL,
		     prop,
		     LOOKUP_TEST_ONLY | 
		         (MF_OPTVAL(null, prop && prop->null)
			   ? LOOKUP_NULL_BYTE : 0));
}
END

MF_DEFUN(dbget, STRING, STRING dbname, STRING key, OPTIONAL,
	 STRING defval, NUMBER null)
{
	const struct db_prop *prop = db_prop_lookup(dbname);
	dbmap_lookup(env, dbname, key, 
                     MF_OPTVAL(defval),
		     prop,
		     MF_OPTVAL(null, prop && prop->null)
		      ? LOOKUP_NULL_BYTE : 0);
}
END

MF_DEFUN(dbput, VOID, STRING dbname, STRING keystr, STRING value,
	 OPTIONAL, NUMBER null, NUMBER mode)
{
	int rc;
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	struct mu_dbm_datum contents;
	const struct db_prop *prop = db_prop_lookup(dbname);
	
	rc = _open_dbm(&db, dbname, MU_STREAM_RDWR,
		       MF_OPTVAL(mode,
				 (prop ? prop->mode : DEFAULT_DB_MODE)),
		       prop ? prop->hint : NULL);
	if (rc)
		MF_THROW(mfe_dbfailure,
			 _("mf_dbm_open(%s) failed: %s"),
			 dbname,
			 mu_strerror(rc));
	memset(&key, 0, sizeof key);
	key.mu_dptr = keystr;
	key.mu_dsize = strlen(keystr);
	if (MF_OPTVAL(null, prop && prop->null))
		key.mu_dsize++;

	memset(&contents, 0, sizeof contents);
	contents.mu_dptr = value;
	contents.mu_dsize = strlen(value) + 1;
	
	rc = mu_dbm_store(db, &key, &contents, 1);
	if (rc) {
		const char *errstr = mu_dbm_strerror(db);
		mu_dbm_destroy(&db);
		MF_THROW(mfe_dbfailure,
			 _("failed to insert data to %s: %s %s: %s"),
			 dbname,
			 keystr,
			 value,
			 errstr);
	}
	mu_dbm_destroy(&db);
}
END

MF_DEFUN(dbinsert, VOID, STRING dbname, STRING keystr, STRING value,
	 OPTIONAL, NUMBER replace, NUMBER null, NUMBER mode)
{
	int rc;
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	struct mu_dbm_datum contents;
	const struct db_prop *prop = db_prop_lookup(dbname);
	const char *errstr;
	
	rc = _open_dbm(&db, dbname, MU_STREAM_RDWR,
		       MF_OPTVAL(mode,
				 (prop ? prop->mode : DEFAULT_DB_MODE)),
		       prop ? prop->hint : NULL);
	if (rc)
		MF_THROW(mfe_dbfailure,
			 _("mf_dbm_open(%s) failed: %s"),
			 dbname,
			 mu_strerror(rc));
	memset(&key, 0, sizeof key);
	key.mu_dptr = keystr;
	key.mu_dsize = strlen(keystr);
	if (MF_OPTVAL(null, prop && prop->null))
		key.mu_dsize++;

	memset(&contents, 0, sizeof contents);
	contents.mu_dptr = value;
	contents.mu_dsize = strlen(value) + 1;
	
	rc = mu_dbm_store(db, &key, &contents, MF_OPTVAL(replace));
	if (rc && rc != MU_ERR_EXISTS)
		errstr = mu_dbm_strerror(db);
	mu_dbm_destroy(&db);
	if (rc == MU_ERR_EXISTS)
		MF_THROW(mfe_exists, _("record already exists"));
	
	MF_ASSERT(rc == 0,
		  mfe_dbfailure,
		  _("failed to insert data to %s: %s %s: %s"),
		  dbname,
		  keystr,
		  value,
		  errstr);
}
END

MF_DEFUN(dbdel, VOID, STRING dbname, STRING keystr, OPTIONAL, NUMBER null,
	 NUMBER mode)
{
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	int rc;
	const struct db_prop *prop = db_prop_lookup(dbname);
	
	rc = _open_dbm(&db, dbname, MU_STREAM_RDWR,
		       MF_OPTVAL(mode,
				 (prop ? prop->mode : DEFAULT_DB_MODE)),
		       prop ? prop->hint : NULL);
	MF_ASSERT(rc == 0,
		  mfe_dbfailure,
		  _("mf_dbm_open(%s) failed: %s"),
		  dbname,
		  mu_strerror(rc));
	memset(&key, 0, sizeof key);
	key.mu_dptr = keystr;
	key.mu_dsize = strlen(keystr);
	if (MF_OPTVAL(null, prop && prop->null))
		key.mu_dsize++;
	rc = mu_dbm_delete(db, &key);
	mu_dbm_destroy(&db);
	MF_ASSERT(rc == 0 || rc == MU_ERR_NOENT,
                  mfe_dbfailure,
                  _("failed to delete data `%s' from `%s': %s"),
		  keystr,
                  dbname,
		  mu_strerror(rc));
}
END


#define NUMDB 128

struct db_tab {
	int used;
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
};

static void *
alloc_db_tab()
{
	return mu_calloc(NUMDB, sizeof(struct db_tab));
}

static void
close_db_tab(struct db_tab *dbt)
{
	if (dbt->used) {
		mu_dbm_datum_free(&dbt->key);
		mu_dbm_destroy(&dbt->db);
		dbt->used = 0;
	}
}

static void
destroy_db_tab(void *data)
{
	int i;
	struct db_tab *db = data;
	for (i = 0; i < NUMDB; i++) 
		close_db_tab(db + i);
	free(db);
}

MF_DECLARE_DATA(DBTAB, alloc_db_tab, destroy_db_tab);

static int
new_db_tab(struct db_tab *dbt)
{
	int i;
	for (i = 0; i < NUMDB; i++)
		if (!dbt[i].used) {
			dbt[i].used = 1;
			return i;
		}
	return -1;
}
			


MF_DEFUN(dbfirst, NUMBER, STRING dbname)
{
	int rc;
	int n;
	struct db_tab *dbt = MF_GET_DATA;
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	const struct db_prop *prop = db_prop_lookup(dbname);

	rc = _open_dbm(&db, dbname, MU_STREAM_READ,
		       prop ? prop->mode : DEFAULT_DB_MODE,
		       prop ? prop->hint : NULL);
	MF_ASSERT(rc == 0,
		  mfe_dbfailure,
		  _("mf_dbm_open(%s) failed: %s"),
		  dbname,
		  mu_strerror(rc));
	memset(&key, 0, sizeof key);
	rc = mu_dbm_firstkey(db, &key);
	if (rc) {
		if (rc == MU_ERR_NOENT) {
			mu_dbm_destroy(&db);
			MF_RETURN(0);
		} else if (rc) {
			mu_dbm_destroy(&db);
			MF_THROW(mfe_dbfailure,
				 _("mf_dbm_firstkey failed: %s"),
				 mu_strerror(rc));
		}
	}
	n = new_db_tab(dbt);
	MF_ASSERT(n >= 0,
		  mfe_failure,
		 _("no more database entries available"));
	dbt += n;
	dbt->db = db;
	dbt->key = key;
	MF_RETURN(n);
}
END

MF_DEFUN(dbnext, NUMBER, NUMBER dn)
{
	struct db_tab *dbt = MF_GET_DATA + dn;
	struct mu_dbm_datum nextkey;
	int rc;
	
	MF_ASSERT(dn >= 0 && dn < NUMDB && dbt->used,
		  mfe_range,
		  _("invalid database descriptor"));

	memset (&nextkey, 0, sizeof nextkey);
	rc = mu_dbm_nextkey(dbt->db, &nextkey);
	if (rc) {
		if (rc == MU_ERR_FAILURE)
			mu_error(_("mu_dbm_nextkey: %s"),
				 mu_dbm_strerror(dbt->db));
		close_db_tab(dbt);
		MF_RETURN(0);
	}
	mu_dbm_datum_free(&nextkey);
	dbt->key = nextkey;
	MF_RETURN(1);
}
END

MF_DEFUN(dbkey, STRING, NUMBER dn)
{
	size_t off, len;
	char *s;
	struct db_tab *dbt = MF_GET_DATA + dn;
	
	MF_ASSERT(dn >= 0 && dn < NUMDB && dbt->used,
		  mfe_range,
		  _("invalid database descriptor"));
	
	len = dbt->key.mu_dsize;
	s = MF_ALLOC_HEAP(off, len + 1);
	memcpy(s, dbt->key.mu_dptr, len);
	s[len] = 0;
	MF_RETURN(off, size);
}
END

MF_DEFUN(dbvalue, STRING, NUMBER dn)
{
	int rc;
	size_t off, len;
	char *s;
	struct db_tab *dbt = MF_GET_DATA + dn;
	struct mu_dbm_datum contents;
	
	MF_ASSERT(dn >= 0 && dn < NUMDB && dbt->used,
		  mfe_range,
		  _("invalid database descriptor"));

	memset(&contents, 0, sizeof contents);
	rc = mu_dbm_fetch(dbt->db, &dbt->key, &contents);
	MF_ASSERT(rc == 0,
		  mfe_dbfailure,
		  _("cannot fetch key: %s"),
		  rc == MU_ERR_FAILURE ?
		   mu_dbm_strerror(dbt->db) : mu_strerror (rc));
	
	len = contents.mu_dsize;
	s = MF_ALLOC_HEAP(off, len + 1);
	memcpy(s, contents.mu_dptr, len);
	s[len] = 0;
	mu_dbm_datum_free(&contents);
	MF_RETURN(off, size);
}
END


enum greylist_semantics
{
	greylist_traditional,
	greylist_ct
};

static enum greylist_semantics greylist_semantics = greylist_traditional;

/* #pragma greylist {traditional|gray|ct|con-tassios}*/
MF_PRAGMA(greylist, 2, 2)
{
	if (strcmp(argv[1], "traditional") == 0
	    || strcmp(argv[1], "gray") == 0)
		greylist_semantics = greylist_traditional;
	else if (strcmp(argv[1], "ct") == 0
		 || strcmp(argv[1], "con-tassios") == 0)
		greylist_semantics = greylist_ct;
	else
		/* TRANSLATORS: Do not translate keywords:
		   traditional, gray, ct, con-tassios */
		parse_error(_("unknown semantics; allowed values are: "
			      "traditional (or gray) and "
			      "ct (or con-tassios)"));
}

/* FIXME: Duplicated in lib/cache.c */
static char *
format_timestr(time_t timestamp, char *timebuf, size_t bufsize)
{
	struct tm tm;
	gmtime_r(&timestamp, &tm);
	strftime(timebuf, bufsize, "%c", &tm);
	return timebuf;
}

MF_VAR(greylist_seconds_left, NUMBER);

/* The traditional (aka gray's) greylist implementation: the greylist
   database keeps the time the greylisting was activated.
 */
static int
do_greylist_traditional(eval_environ_t env, char *email, long interval)
{
	int rc;
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	struct mu_dbm_datum contents;
	int readonly = 0;
	time_t now;

	rc = _open_dbm(&db, greylist_format->dbname, MU_STREAM_RDWR, 0600,
		       NULL);
	if (rc) {
		rc = _open_dbm(&db, greylist_format->dbname,
			       MU_STREAM_READ, 0600, NULL);
		readonly = 1;
	}
        MF_ASSERT(rc == 0, mfe_dbfailure, _("mf_dbm_open(%s) failed: %s"),
		  greylist_format->dbname, mu_strerror(rc));
	
	memset(&key, 0, sizeof key);
	memset(&contents, 0, sizeof contents);
	key.mu_dptr = email;
	key.mu_dsize = strlen(email)+1;

	time(&now);
	rc = mu_dbm_fetch(db, &key, &contents);
	if (rc == 0) {
		time_t timestamp, diff;

		MF_ASSERT(contents.mu_dsize == sizeof timestamp,
			 mfe_dbfailure,
			  _("greylist database %s has wrong data size"),
			  greylist_format->dbname);
		
		timestamp = *(time_t*) contents.mu_dptr;
		diff = now - timestamp;

		if (mu_debug_level_p(debug_handle, MU_DEBUG_TRACE5)) {
			char timebuf[32];
			mu_debug_log("%s entered greylist database on %s, "
				     "%ld seconds ago",
				     email,
				     format_timestr(timestamp, timebuf,
						    sizeof timebuf),
				     (long) diff);
		}
		
		if (diff < interval) {
			diff = interval - diff;
			
			MF_VAR_REF(greylist_seconds_left, ulong, diff);//FIXME
			
			MF_DEBUG(MU_DEBUG_TRACE6, 
                                 ("%s still greylisted (for %lu sec.)",
			          email,
			          (unsigned long) diff));
			rc = 1;
		} else if (diff > greylist_format->expire_interval) {
			MF_DEBUG(MU_DEBUG_TRACE6, 
                                 ("greylist record for %s expired", email));
			MF_VAR_REF(greylist_seconds_left, long, interval);
			if (!readonly) {
				memcpy(contents.mu_dptr, &now, sizeof now);
				rc = mu_dbm_store(db, &key, &contents, 1);
				if (rc)
					mu_error(_("cannot insert datum `%-.*s' in "
						   "greylist database %s: %s"),
			                         (int)key.mu_dsize,
						 (char*)key.mu_dptr,
						 greylist_format->dbname,
						 rc == MU_ERR_FAILURE ?
						  mu_dbm_strerror(db) :
						  mu_strerror(rc));
			} else
				MF_DEBUG(MU_DEBUG_TRACE6, 
                                         ("database opened in readonly mode: "
			  	          "not updating"));
			rc = 1;
		} else {
			MF_DEBUG(MU_DEBUG_TRACE6, 
                                 ("%s finished greylisting period", email));
			rc = 0;
		}
		mu_dbm_datum_free(&contents);
	} else if (!readonly) {
		MF_DEBUG(MU_DEBUG_TRACE6, ("greylisting %s", email));
		MF_VAR_REF(greylist_seconds_left, long, interval);
		contents.mu_dptr = (void*)&now;
		contents.mu_dsize = sizeof now;
		rc = mu_dbm_store(db, &key, &contents, 1);
		if (rc)
			mu_error(_("Cannot insert datum `%-.*s' in greylist "
				   "database %s: %s"),
		                 (int)key.mu_dsize, (char*)key.mu_dptr,
				 greylist_format->dbname,
				 rc == MU_ERR_FAILURE ?
				  mu_dbm_strerror(db) : mu_strerror(rc));
		rc = 1;
	} else
		rc = 0;

	mu_dbm_destroy(&db);

	return rc;
}

/* Implementation of the is_greylisted predicate has no sense for 
   traditional greylist databases, because greylisting interval is
   not known beforehand.
   FIXME: keep the reference below up to date.
 */
static int
is_greylisted_traditional(eval_environ_t env, char *email)
{
	MF_THROW(mfe_failure,
		 _("is_greylisted is not implemented for traditional greylist databases; "
		   "see documentation, chapter %s %s for more info"),
		 "4.12.1.23", "Greylisting functions");
	return 0;
}

/* New greylist implementation (by Con Tassios): the database keeps
   the time the greylisting period is set to expire (`interval' seconds
   from now)
*/
static int
do_greylist_ct(eval_environ_t env, char *email, long interval)
{
	int rc;
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	struct mu_dbm_datum contents;
	int readonly = 0;
	time_t now;

	rc = _open_dbm(&db, greylist_format->dbname, MU_STREAM_RDWR, 0600,
		       NULL);
	if (rc) {
		rc = _open_dbm(&db, greylist_format->dbname,
			       MU_STREAM_READ, 0600, NULL);
		readonly = 1;
	}
        MF_ASSERT(rc == 0, mfe_dbfailure, _("mf_dbm_open(%s) failed: %s"),
		  greylist_format->dbname, mu_strerror(rc));
	
	memset(&key, 0, sizeof key);
	memset(&contents, 0, sizeof contents);
	key.mu_dptr = email;
	key.mu_dsize = strlen(email) + 1;

	time(&now);
	rc = mu_dbm_fetch(db, &key, &contents);
	if (rc == 0) {
		time_t timestamp;

		MF_ASSERT(contents.mu_dsize == sizeof timestamp,
			 mfe_dbfailure,
			  _("greylist database %s has wrong data size"),
			 greylist_format->dbname);
		
		timestamp = *(time_t*) contents.mu_dptr;

		if (now < timestamp) {
			time_t diff = timestamp - now;
			MF_VAR_REF(greylist_seconds_left, long, diff);
			
			MF_DEBUG(MU_DEBUG_TRACE6, 
                                 ("%s still greylisted (for %lu sec.)",
			          email,
                                  (unsigned long) diff));
			rc = 1;
		} else if (now - timestamp >
			   greylist_format->expire_interval) {
			MF_DEBUG(MU_DEBUG_TRACE6, 
                                 ("greylist record for %s expired", email));
			MF_VAR_REF(greylist_seconds_left, long, interval);
			if (!readonly) {
				now += interval;
				memcpy(contents.mu_dptr, &now, sizeof now);
				rc = mu_dbm_store(db, &key, &contents, 1);
				if (rc)
					mu_error(_("Cannot insert datum "
						   "`%-.*s' in greylist "
						   "database %s: %s"),
			                         (int)key.mu_dsize,
						 (char*)key.mu_dptr,
						 greylist_format->dbname,
						 rc == MU_ERR_FAILURE ?
						   mu_dbm_strerror(db) :
						   mu_strerror(rc));
			} else
				MF_DEBUG(MU_DEBUG_TRACE6, 
                                         ("database opened in readonly mode: "
				          "not updating"));
			rc = 1;
		} else {
			MF_DEBUG(MU_DEBUG_TRACE6,
				 ("%s finished greylisting period", email));
			rc = 0;
		}
		mu_dbm_datum_free(&contents);
	} else if (!readonly) {
		MF_DEBUG(MU_DEBUG_TRACE6, ("greylisting %s", email));
		MF_VAR_REF(greylist_seconds_left, long, interval);
		now += interval;
		contents.mu_dptr = (void*)&now;
		contents.mu_dsize = sizeof now;
		rc = mu_dbm_store(db, &key, &contents, 1);
		if (rc)
			mu_error(_("Cannot insert datum `%-.*s' in greylist "
				   "database %s: %s"),
		                 (int)key.mu_dsize, (char*)key.mu_dptr,
				 greylist_format->dbname,
				 rc == MU_ERR_FAILURE ?
				  mu_dbm_strerror(db) : mu_strerror(rc));
		rc = 1;
	} else
		rc = 0;
	
	mu_dbm_destroy(&db);
	
	return rc;
}

/* The `is_greylisted' predicate for new databases */
static int
is_greylisted_ct(eval_environ_t env, char *email)
{
	int rc;
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	struct mu_dbm_datum contents;
	time_t now;

	rc = _open_dbm(&db, greylist_format->dbname, MU_STREAM_RDWR, 0600,
		       NULL);
	if (rc)
		rc = _open_dbm(&db, greylist_format->dbname,
			       MU_STREAM_READ, 0600, NULL);
	MF_ASSERT(rc == 0, mfe_dbfailure, _("mf_dbm_open(%s) failed: %s"),
		  greylist_format->dbname, mu_strerror(rc));

	memset(&key, 0, sizeof key);
	memset(&contents, 0, sizeof contents);
	key.mu_dptr = email;
	key.mu_dsize = strlen(email) + 1;

	time(&now);
	rc = mu_dbm_fetch(db, &key, &contents);
	if (rc == 0) {
		time_t timestamp;

		MF_ASSERT(contents.mu_dsize == sizeof timestamp,
			mfe_dbfailure,
			  _("greylist database %s has wrong data size"),
			greylist_format->dbname);
                
		timestamp = *(time_t*) contents.mu_dptr;
                
		rc = timestamp > now;
                if (rc)
			MF_VAR_REF(greylist_seconds_left, long, timestamp - now);

		mu_dbm_datum_free(&contents);
	} else  
		rc = 0;

	mu_dbm_destroy(&db);

	return rc;
}

struct greylist_class {
	int (*gl_fun)(eval_environ_t, char *, long);
	int (*gl_pred)(eval_environ_t, char *);
};

struct greylist_class greylist_class[] = {
	{ do_greylist_traditional, is_greylisted_traditional },
	{ do_greylist_ct, is_greylisted_ct }
};

/* greylist(key, interval)

   Returns true if the key is greylisted, false if it's OK to
   deliver mail.
 */
MF_DEFUN(greylist, NUMBER, STRING email, NUMBER interval)
{
	MF_RETURN(greylist_class[greylist_semantics].gl_fun(env, email,
							    interval));
}
END

/* is_greylisted(key)
   
   Returns true if the key is greylisted, otherwise false
   
*/
MF_DEFUN(is_greylisted, NUMBER, STRING email)
{
	MF_RETURN(greylist_class[greylist_semantics].gl_pred(env, email));
}
END

MF_DEFUN(db_name, STRING, STRING fmtid)
{
	struct db_format *fmt = db_format_lookup(fmtid);
	MF_ASSERT(fmt != NULL,
		  mfe_not_found,
		  _("no such db format: %s"), fmtid);
	MF_RETURN(fmt->dbname);
}
END

MF_DEFUN(db_get_active, NUMBER, STRING fmtid)
{
	struct db_format *fmt = db_format_lookup(fmtid);
	MF_ASSERT(fmt != NULL,
		  mfe_not_found,
		  _("no such db format: %s"), fmtid);
	MF_RETURN(fmt->enabled);
}
END

MF_DEFUN(db_set_active, VOID, STRING fmtid, NUMBER active)
{
	struct db_format *fmt = db_format_lookup(fmtid);
	MF_ASSERT(fmt != NULL,
		  mfe_not_found,
		  _("no such db format: %s"), fmtid);
	fmt->enabled = active;
}
END

MF_DEFUN(db_expire_interval, NUMBER, STRING fmtid)
{
	struct db_format *fmt = db_format_lookup(fmtid);
	MF_ASSERT(fmt != NULL,
		  mfe_not_found,
		  _("no such db format: %s"), fmtid);
	MF_RETURN(fmt->expire_interval);
}
END

Return to:

Send suggestions and report system problems to the System administrator.