~semi-hallikas/sspamm/3.0-devel

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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
#!/usr/bin/env python2
# -*- coding: UTF-8 -*-

"""Semi's SPAM Milter - Who would like to get trash on email? Not me.
"""

__author__ = "Sami-Pekka Hallikas <semi@hallikas.com>"
__email__ = "semi@hallikas.com"
__date__ = "18 Aug 2010"
__version__ = "3.0-devel"

import sys
import os
import time
import locale
import ConfigParser
import re
import thread
from email import message_from_file
from email.Header import decode_header
from string import maketrans, letters, digits, punctuation, whitespace
from signal import signal, SIGINT, SIGHUP, SIGBUS, SIGTERM

# Debug
from traceback import print_exc
from syslog import \
	LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, \
	LOG_DEBUG, LOG_MAIL, LOG_PID, LOG_CONS

# http://sourceforge.net/projects/pymilter
import Milter

from milter import \
	ACCEPT, CONTINUE, REJECT, DISCARD, TEMPFAIL, \
	ADDHDRS, CHGBODY, ADDRCPT, DELRCPT, CHGHDRS

try: from milter import QUARANTINE
except: pass



##############################################################################
##
## Global variables / Configuration
##
conffile = "sspamm.conf"

confdefaults = {
	"main": {
		"name":			"sspamm",
		"port":			"local:/tmp/sspamm.sock",
		"sspammdir":		None,
		"pid":			"sspamm.pid",
		"logfile":		"sspamm.log",
		"verbose":		0,
		"timeme":		True,
		"tmpdir":		"/dev/shm",
		"savedir":		None,
		"watchmode":		True,
#		"detailed":		False,
	},
#	"stats": {
#		"driver":		None,
#		"user":			"sspamm",
#		"pass":			"sspamm",
#		"host":			"localhost",
#		"database":		"sspamm2",
#		"table":		"stats",
#	},
	"filter": {
		"tests":		["connect", "helo", "ipfromto", "charset", "headers", "wordscan", "rbl", "dyndns", "bayesian"],
		"domains":		[],
		"rules":		[],
	},
	"connect": {
		"action":		"Flag",
		"ignore_ip":		["127.0.0.1"],
#		"ignore_dns":		[],
#		"allow_ip":		[],
#		"allow_dns":		[],
#		"block_ip":		[],
#		"block_dns":		[]
	},
	"helo": {
		"action":		"Flag",
#		"recursive":		False,
#		"rules":		[],
	},
	"samefromto": {
		"action":		"Flag",
	},
	"accept": {
		"rules":		[],
	},
	"block": {
		"rules":		[],
	},
#	"ipfromto": {
#		"action":		"Flag",
#		"maxrcpt":		2,
#		"rules":		[],
#	},
#	"rbl": {
#		"action":		"Flag",
#		"recursive":		False,
#		"ipservers":		["sbl-xbl.spamhaus.org", "dnsbl.sorbs.net", "bl.spamcop.net"],
#		"skip_ip":		[],
#		"skip_dns":		[],
#	},
#	"dyndns": {
#		"action":		"Flag",
#		"recursive":		False,
#		"ignore_authmx":	[],
#		"known_authmx":		[],
#		"skip_dyndns":		[],
#		"rules":		[
#					"^[0-9]{1,3}[\-\.][0-9]{1,3}[\-\.][0-9]{1-3}\..*",
#		],
#	},
#	"bayesian": {
#		"action":		"Flag",
#		"unsure":		"Flag",
#		"spampros":		90,
#		"hampros":		20,
#		"maxbodysize":		200,
#		"commondb":		"sspamm.db",
#		"mimeparts":		False,
#		"usedomaindb":		False,
#		"dbtrain":		False,
#		"savembox":		False,
#		"saveunsure":		True,
#		"maxtrainsize":		512,
#		"msgsneeded":		10,
#		"maxtrain":		10000,
#		"ratio":		"50:50",
#	},
#	"headers": {
#		"action":		"Flag",
#		"rules":		[],
#	},
#	"charset": {
#		"action":		"Flag",
#		"rules":		[],
#	},
#	"wordscan": {
#		"action":		"Flag",
#		"maxbodysize":		200,
#		"links":		[],
#		"blockhtml":		[],
#		"subject":		[],
#		"blockwords":		[],
#	},
}
conf = confdefaults.copy()

conf["runtime"] = {
	"starttime":	0,
	"endtime":	0,
	"conftime":	0,
	"logtime":	0,
	"conffile":	None,
	"offline":	False,
}

##############################################################################
##
## Basic fileoperations (Usualy we don't need to care if it success or not)
##
def rm(file, id=None):
	debug("rm(\"%s\")" % (file), LOG_DEBUG, id=id)
	try:
		if os.path.exists(file): os.remove(file)
	except:
		pass
	return

def rmdir(path, id=None):
	debug("rmdir(\"%s\")" % (path), LOG_DEBUG, id=id)
	try:
		os.rmdir(path)
	except OSError, (errno, strerror):
		if errno != 39: debug("%s" % sys.exc_value, LOG_ERR)
	except:
		debug("%s: %s" % (sys.exc_type, sys.exc_value), LOG_ERR)
	return

def mkdir(path, id=None):
	debug("mkdir(\"%s\")" % (path), LOG_DEBUG, id=id)
	try:
		os.mkdir(path)
	except OSError, (errno, strerror):
		if errno != 17: debug("%s" % sys.exc_value, LOG_ERR)
	except:
		debug("%s: %s" % (sys.exc_type, sys.exc_value), LOG_ERR)
	return

def mv(what, where, id=None):
	debug("mv(\"%s\" \"%s\")" % (what, where), LOG_DEBUG, id=id)
	try:
		os.rename(what, where)
	except:
		try:
			fpin = open(what,"r")
			fpout = open(where,"w+b")
			while 1:
				buf = fpin.read(1024*16)
				if len(buf) == 0: break
				fpout.write(buf)
			fpin.close()
			fpout.close()
			rm(what)
		except:
			debug("move failed: %s -> %s" % (what, where), LOG_DEBUG)
	return

##############################################################################
##
## Debug
##
def debug(args, level=LOG_DEBUG, id=None, trace=None):
	datetime = ""
	msg = ""
	datetime = time.strftime('%Y%m%d %H:%M:%S')+" "
	if id:
		msg += "(%08d) " % (int(id))
	else:
		msg += "%8s " % ("")
	msg = str(msg) + str(args)
	msg = datetime + msg
	print msg
	if trace:
		print_exc(limit=None, file=sys.stderr)
	sys.stdout.flush()
	return

def save_vars(var, fname, id=None):
	if conf["runtime"]["offline"]: return
	debug("save_vars(\"%s\")" % (fname), LOG_DEBUG, id=id)

### DEVELOPER DEBUG
	if var.has_key("raw"): del var["raw"]
	if var.has_key("mime"): del var["mime"]

	fp = open(fname, "w+b")
	if fp: fp.write(show_vars(var))
	fp.close()
	return

def load_vars(fname, id=None):
	debug("load_vars(\"%s\")" % (fname), LOG_DEBUG, id=id)
	fp = open(fname, "r")
	is_raw = False
	do_skip = False
	buf = ""
	while 1:
		line = fp.readline()
		if len(line) < 1: break
		if line[1:10] == "\"mime\": {":
			do_skip = True
		if line[1:13] == "\"raw\": 'From":
			raw = line[9:]
			is_raw = True
		elif is_raw:
			if line == "',\n":
				is_raw = False
			else:
				raw += line
		elif do_skip:
			if line[1:3] == "},":
				do_skip = False
			pass
		else:
			buf += line
	fp.close()
	vars = eval(buf)
	vars["raw"] = raw
	return vars

def show_vars(var, lvl=0):
	if lvl==0: lvl=1
	st=""
	tab = "\t"

	if type(var) is dict:
		st += "{\n"
		for k in var.keys():
			st += tab*lvl
			if(0): # Reserve space for keys
				if type(k) is int:
					st += "%-16s" % ("%d: " % k)
				else:
					st += "%-16s" % ("\"%s\": " % k)
			else:
				if type(k) is int:
					st += "%d: " % k
				else:
					st += "\"%s\": " % k
			st += show_vars(var[k], lvl+1)
			st += ",\n"
		st += tab*(lvl-1)
		st += "}"
	elif type(var) is tuple:
		if len(var) < 1:
			st += str(var)
		else:
			st += "(\n"
			for k in var:
				st += tab*lvl
				st += show_vars(k, lvl+1)
				st += ",\n"
			st += tab*(lvl-1)
			st += ")"
	elif type(var) is list:
		if len(var) < 1:
			st += str(var)
		elif len(var) == 1 and type(var[0]) in [str, int]:
			st += str(var)
		else:
			st += "[\n"
			for k in var:
				st += tab*lvl
				st += show_vars(k, lvl+1)
				st += ",\n"
			st += tab*(lvl-1)
			st += "]"
	elif type(var) is str:
		st += "\'%s\'" % re.sub("\'", "\\\'", var)
	elif type(var) is int:
		st += "%d" % var
	elif var == None:
		st += "None"
	else:
		st += str(var)
	return st

# Timeme:
# Used for trace used time of processing, so one can find how long does
# each part of processing take.
#
def timeme(timer=0, noshow=None, id=None, title="Timer"):
	if timer == 0: return time.time()
	timer = float(time.time())-float(timer)
	if timer < 0: timer = 0
#	if not noshow: debug("\t%s: %.4f" % (title, timer), LOG_DEBUG, id=id)
	return float(timer)

##
## Oneliner
##
def oneliner(value, id=None):
#	debug("*oneliner(\"%s%s\")" % (value[0:160]), LOG_DEBUG, id=id)
	return re.sub(" + ", " ", re.sub("[\r\n\t]", " ", value))

##
## Strip unprintable
##
def stripUnprintable(input_string, id=None):
#	debug("stripUnprintable()", LOG_DEBUG, id=id)
	try: filterUnprintable = stripUnprintable.filter
	except AttributeError: # only the first time it is called
		allchars = maketrans('','')
		delchars = allchars.translate(allchars, letters+digits+punctuation+whitespace)
		filterUnprintable = stripUnprintable.filter = lambda input: input.translate(allchars, delchars)
	return filterUnprintable(input_string)

##
## Unique keys
##
def uniq(seq, idfun=None): 
	# order preserving
	if idfun is None:
		def idfun(x): return x
	seen = {}
	result = []
	for item in seq:
		if item == None: continue
		marker = idfun(item)
		# in old Python versions:
		# if seen.has_key(marker)
		# but in new ones:
		if marker in seen: continue
		seen[marker] = 1
		result.append(item)
	return result

##
## Mime Part
##
def mimepart(part, lvl=0, param=None, id=None):
	if lvl == 0:
		debug("*mimepart()", LOG_DEBUG, id=id)
		if conf["main"]["timeme"] is True: timer = timeme()
	if not part.is_multipart() and part.get_content_type() != None:
		text = None
		if part.get_content_maintype() == "text":
			if part.get_content_subtype() == "plain" or part.get_content_subtype() == "html":
				text = part.get_payload(decode=True)
			else:
				if part.get_content_subtype() == "rfc822-headers":
					return
				debug("Unknown content type text/%s" % part.get_content_subtype(), LOG_NOTICE, id=id)
				return
				#text = part.get_payload(decode=True)
		if lvl>0:
			if text:
				return (part.get_content_maintype(), part.get_content_subtype(), "", param, text.strip())
			else:
				return (part.get_content_maintype(), part.get_content_subtype(), "", param, "")
		else:
			if text:
				return {0: (part.get_content_maintype(), part.get_content_subtype(), "", param, text.strip())}
			else:
				return {0: (part.get_content_maintype(), part.get_content_subtype(), "", param, "")}
		# Nothing to return
		return
	tree = {}
	sublvl=0
	tab="  "
	lvl+=1

	debug("\t%d.%d%s%s" % (lvl,sublvl,tab*lvl,part.get_content_type()), LOG_DEBUG, id=id)
	#tree[lvl*10+sublvl] = (part.get_content_type())
	if not part.get_payload():
		return tree
	for p in part.get_payload():
		ret = None
		if type(p) is str:
			if lvl > 1:
				return (part.get_content_maintype(), part.get_content_subtype(), "", param, part.get_payload().strip())
			return {10: (part.get_content_maintype(), part.get_content_subtype(), "", param, part.get_payload().strip())}
		if p.is_multipart():
			if p.get_param("x-spam-type") == "original":
				param="spam"
				tree = {}
			ret=mimepart(p, lvl, param, id=id)
			if ret:
				for r in ret:
					tree[r] = ret[r]
				continue
		else:
			sublvl += 1
			if p.get_param("x-spam-type") == "original":
				debug("\t%d.%d%s%s ( = original spam)" % (lvl,sublvl,tab*lvl,p.get_content_type()), LOG_DEBUG, id=id)
				msg=email.message_from_string(p.get_payload(decode=True))
				ret=mimepart(msg, lvl, param="spam", id=id)
			else:
				ret = mimepart(p, lvl, param, id=id)
		if ret:
			debug("\t%d.%d%s%s" % (lvl,sublvl,tab*lvl,p.get_content_type()), LOG_DEBUG, id=id)
			
			if p.get_param("x-spam-type"):
				tree = {}
			if type(ret) in [tuple]:
				tree[lvl*10+sublvl] = ret
			else:
				return ret
	if lvl == 0 and conf["main"]["timeme"] is True: mail["timer"]["mimepart"] = str("%.4f") % timeme(timer)
	return tree


##
## dumbregtest
##
# Test regexp rules for stupid mistakes like || which would match EVERYTHING.
# If this test matches, rule should not be used!
def dumbregtest(regrule):
	try:
		test = re.search(regrule, "The quick brown fox jumps over the lazy dog.\n\t1234567890@${[]}!#&/()=*+-_,;:", re.IGNORECASE+re.MULTILINE)
		if test:
			debug("regexp error: Matched too easily: %s" % (regrule), LOG_ERR)
			return False
	except:
		return False
	return regrule

##
## Is Listed
##
# We could use already defined functions, like domainmatch(ptrs, domainsuffix)
# or cidrmatch(i, ipaddrs, cidr_length=32) ... good ideas, but does not do RegExp ;)
def is_listed(where,what,flags=re.IGNORECASE+re.MULTILINE,id=None,noshow=None):
	noshow=False
	if what == None or where == None or len(what) < 1 or len(where) < 1: return
	if type(where) is str: where = [where]
	if type(what) is str: what = [what]

	if type(what) is dict:
		for a in what:
			tmp = is_listed(where,a,flags=flags,id=id,noshow=noshow)
			if tmp: return what[a]
	elif type(what[0]) is tuple:
		for a in what:
			tmp = is_listed(where,a[0],flags=flags,id=id,noshow=noshow)
			if tmp: return a[1]
	else:
		try:
#			debug("*is_listed(where=\"%s\")" % (where), LOG_DEBUG, id=id)
			for haystack in where:
				for trap in what:
					try:
						if id: globaltmp[id] += 1
					except:
						pass
#					debug("*is_listed(what=\"%s\")" % (trap), LOG_DEBUG, id=id)
					tmp = re.search(trap, haystack, flags)
					if tmp:
#						debug("\t*is_listed matched:", LOG_DEBUG, id=id)
						return (trap, tmp.end()-tmp.start(), haystack[tmp.start():tmp.end()])
		except:
			debug("%s: %s" % (sys.exc_type, sys.exc_value), LOG_DEBUG)
			debug("FAILED: is_listed(%s, %s)" % (haystack, trap), LOG_DEBUG, id=id)
	return

##
## is filtered
##
def is_filtered(mail):
	if conf["main"]["timeme"] is True: timer = timeme()
	debug("is_filtered(%s)" % (mail["to"][0]), LOG_DEBUG, id=mail["id"])
	found = False
	try:
		mail["todomain"] = mail["to"][0].split("@")[1]
		found = is_listed(mail["todomain"], conf["filter"]["domains"], id=mail["id"])
		if found: debug("\tFound: %s" % (found), LOG_DEBUG, id=mail["id"])
	except:
		debug("FAILED: is_filtered %s: %s" % (sys.exc_type, sys.exc_value), LOG_ERR, id=mail["id"], trace=True)
		mail["failed"] = "is_filtered(\"%s\"[0].split(\"@\")[1])" % (mail["to"])
		save_vars(self.mail, "%s/%08d.var" % ("/tmp", mail["id"]), id=mail["id"]);
	if conf["main"]["timeme"] is True: mail["timer"]["is_filtered"] = str("%.4f") % timeme(timer, id=mail["id"])
	return (found, mail)


##
## Makepid
##
def makepid(fname):
	debug("makepid(\"%s\")" % (fname), LOG_DEBUG)

	if os.path.exists(fname):
		fp = open(fname, "r")
		pid=int(fp.readline().strip())
		fp.close

		if os.path.exists("/proc/%d" % pid):
			fp = open("/proc/%d/stat" % pid, "r")
  			pidstat = fp.readline().strip().split(" ")
			fp.close
			if pidstat[2] == "S": pidstat[2] = "Sleeping"
			elif pidstat[2] == "R": pidstat[2] = "Running"
			elif pidstat[2] == "T": pidstat[2] = "Stopped"
			debug("PID file %s found for process %s (%s)." % (conf["main"]["pid"], pidstat[1][1:-1], pidstat[2]), LOG_ERR)
			return False
		else:
			rm(fname)
	try:
		fp = open(fname, "w+b")
		fp.write("%s\n" % os.getpid())
		fp.close()
	except:
		return ("Error", sys.exc_value)
		debug("Couldn't create %s: %s" % (conf["main"]["pid"], tmp[1]), LOG_ERR)
		return False
	return True

##
## parse_addrs - Get only address part of address string. Do lowercase and
## strip blanks. Also return all parsed addresses as array.
##
def parse_addrs(addr, id=None):
#	debug("*parse_addrs(\"%s\")" % (addr), LOG_DEBUG, id=id)
	addr=re.sub(" ", "", re.sub(' ?[("].*?[)"]', "", addr.lower().strip()))
	if addr.startswith("<") or addr.endswith(">"):
		return [addr[addr.find("<")+1:addr.rfind(">")]]
	elif addr.find(","):
		return addr.split(",")
	else:
		return [addr]

##############################################################################
##
## Configuration
##
class MyParser(ConfigParser.ConfigParser):
	def getvalue(self,section,option,default=None,warn=False):
		value = default
		try:
			value = self.getboolean(section, option)
		except ConfigParser.NoOptionError, (err):
			if warn:
				print err
			pass
		except:
			try:
				value = self.getint(section, option)
			except:
				err = "Warning: No value for %s: %s" % (section, option)
				if warn:
					print err
				pass
			pass
		return value

	def getlines(self,section,option,default=None,warn=False):
		try:
			value = self.get(section, option)
			t = value.split('\n')
			try:
				if t[0] == "": t.remove('')
			except IndexError:
				t = []
			return t
		except ConfigParser.NoOptionError, (err):
			if warn:
				print err
			pass
		except:
			err = "Warning: No lines for %s: %s" % (section, option)
			if warn:
				print err
			return None
		return default

	def getlist(self,section,option,default=None,warn=False):
		try:
			value = self.get(section, option)
			(value, count) = re.compile(",|;|\n").subn(' ', value)
			t = value.split()
			try:
				if t[0] == "": t.remove('')
			except IndexError:
				t = []
			return t
		except ConfigParser.NoOptionError, (err):
			if warn:
				print err
			pass
		except:
			err = "Warning: No list for %s: %s" % (section, option)
			if warn:
				print err
			return None
		return default


def config_read(cfgfile = conffile):
	tmpconf = conf.copy()
	cp = MyParser()
	if not os.access(cfgfile, os.R_OK):
		print "FATAL: Can't access %s." % (cfgfile)
		return
	cp.read(cfgfile)

	if not (cp.has_section("main")):
		print "FATAL: Main section is missing!"

	conf["main"]["verbose"] = cp.getvalue("main", "verbose")

	for s in confdefaults.keys():
		if cp.has_section(s):
			for k in confdefaults[s].keys():
				try:
					if "%s/%s" % (s,k) in ["filter/domains"]:
						t = []

						for i in cp.getlines(s, k, []):
							i=re.sub("\t| ", "", i).split(":")
							if '' in i: i.remove('')
							if len(i) == 1: i.append("all")
							t.append((i[0].split(","), i[1].split(",")))
						tmpconf[s][k] = t

					elif "%s/%s" % (s,k) in ["filter/rules"]:
						t = []

						for i in cp.getlines(s, k, []):
							i=re.sub("\t| ", "", i).split(":")
							if '' in i: i.remove('')
							if len(i) > 1:
								t.append((i[0].split(","), ":".join(i[1:]).split(",")))
						tmpconf[s][k] = t

					# Parameters that can be bolean value
					elif k in ["enabled", "verbose", "detailed", "watchmode", "timeme", "recursive", "usedomaindb", "dbtrain", "savembox", "saveunsure", "mimeparts", "learning"]:
						tmpconf[s][k] = cp.getvalue(s, k)
					# RegExp lines
					elif k in ["links", "blockhtml", "blockwords", "subject"]:
						testconf = []
						tmpconf[s][k] = cp.getlines(s, k, tmpconf[s][k])
						for t in tmpconf[s][k]:
							if dumbregtest(t): testconf.append(t)
						tmpconf[s][k] = testconf
					elif "%s/%s" % (s,k) in [ "headers/rules", "helo/rules" ]:
						testconf = []
						tmpconf[s][k] = cp.getlines(s, k, tmpconf[s][k])
						for t in tmpconf[s][k]:
							if dumbregtest(t): testconf.append(t)
						tmpconf[s][k] = testconf
					elif type(tmpconf[s][k]) is int:
						try:
							tmpconf[s][k] = cp.getint(s, k)
						except ValueError:
							debug("%s/%s should be numerical! Using default value %s" % (s, k, tmpconf[s][k]), LOG_DEBUG)
					elif type(tmpconf[s][k]) is list:
						tmpconf[s][k] = cp.getlist(s, k, tmpconf[s][k])
					else:
						tmpconf[s][k] = cp.get(s, k)
				except ConfigParser.NoOptionError, (err):
					if "%s/%s" % (s,k) in [ "main/pid" ]:
						tmpconf[s][k] = confdefaults[s][k]
					elif "%s/%s" % (s,k) in [ "main/sspammdir", "main/timeme", "stats/driver", "main/logfile", "main/savedir", "bayesian/commondb", "wordscan/blockhtml" ]:
						tmpconf[s][k] = None
					else:
						debug("%s" % err, LOG_DEBUG)
				if tmpconf[s][k] == "None":
					tmpconf[s][k] = None
				else:
					# Write 'our special regexp' (_ip and _dns) to real regexp
					# Notice, even SPACE is rule separator!
					if "%s/%s" % (s,k) in [ "accept/rules", "block/rules", "ipfromto/rules" ]:
						testconf = []
						for t in tmpconf[s][k]:
							if dumbregtest(t): testconf.append(t)
						tmpconf[s][k] = testconf
					elif "%s/%s" % (s,k) in [ "connect/allow_ip", "connect/allow_dns", "connect/block_ip", "connect/block_dns", "rbl/skip_ip", "rbl/skip_dns", "dyndns/skip_ip", "dyndns/skip_dns" ]:
						testconf = []
						for t in tmpconf[s][k]:
							if "%s/%s" % (s,k) in [] or ("%s/%s" % (s,k))[-3:] == "_ip":
								t = re.sub("^", "^", re.sub("\?", ".", re.sub("\.", "\.", t)))
							elif "%s/%s" % (s,k) in ["dyndns/rules"] or ("%s/%s" % (s,k))[-4:] == "_dns":
								t = re.sub("$", "$", re.sub("\*", ".*", re.sub("\?", ".", re.sub("\.", "\.", t))))
							if dumbregtest(t): testconf.append(t)
						tmpconf[s][k] = testconf
		else:
			if s != "runtime":
				debug("Section %s not found" % s, LOG_DEBUG)
				del tmpconf[s]

# Now config is fully loaded, do some special parsing.
	tmp = []
	for val in tmpconf["filter"]["domains"]:
		retests = val[1]
		if 'all' in val[1]:
			retests += tmpconf["filter"]["tests"]
			retests.remove('all')
		else:
			retests = val[1]
		if '' in retests: retests.remove('')

		tests = []
		rules = 0
		action = {}
		for test in retests:
			if test in tests: continue
			tests.append(test)
			if test[0] >= 'a' and test[0] <= 'z':
				rules += 1

		if rules == 0:
			tests += tmpconf["filter"]["tests"]
		if 'all' in tests: tests.remove('all')
		t = list(tests)
		for test in tests:
			if test[0] == "-" or test[0] == "!":
				if test[1:] in t: t.remove(test[1:])
				t.remove(test)
			if test[0] == "+":
				if test[1:] in t: t.remove(test[1:])
				t.remove(test)
				t.append(test[1:])
			
		tmp.append((val[0], t))
	tmpconf["filter"]["domains"] = tmp

	tmp = {}
	for val in tmpconf["filter"]["rules"]:
		for domain in val[0]:
			if not tmp.has_key(domain): tmp[domain] = {}
			for rule in val[1]:
				r = rule.split('=')
				if len(r) > 2:
					test=r[0].lower()
					param="=".join(r[1:])
				elif len(r) == 2:
					test=r[0].lower()
					param=r[1]
				else:
					test="rules"
					param=r[0]
				if test == "rules":
					if not tmp[domain].has_key(test): tmp[domain][test] = []
					tmp[domain][test].append(param)
				else:
					tmp[domain][test] = param
	tmpconf["filter"]["rules"] = tmp

	return tmpconf

def config_load(file):
	global conf

	try:
		conf = config_read(file);
	except:
		debug("CONFIG LOAD ERROR. %s: %s" % (sys.exc_type, sys.exc_value), LOG_ERR)
		print_exc(limit=None, file=sys.stderr)

def config_save():
	global conf, conffile

	try:
		fp = open("%s.bak" % (conffile), "w+b")
		tmpconf = conf.copy()
		del tmpconf["runtime"]
		fp.write(show_vars(tmpconf))
		fp.close()
	except:
		pass

##############################################################################
##
## SpamMilter Class 
##
class SpamMilter(Milter.Milter):
	def maildef(self):
		return {
			"smtpcmds": [ ],
			"timer": {},
			"my": {
				"ip": "",
				"dns": "",
			},
			"received": {
				1: {
					"ip": None,
					"dns": None,
					"helo": None,
				}
			},
			"from": [],
			"to": [],
			"todomain": "",
			"size": 0,
			"subject": "",
			"charset": "",
			"header": { },
			"tests": [],
			"type": "",
		}

	def __init__(self):
		self.id = Milter.uniqueID()
		debug("SpamMilter.__init__()", LOG_DEBUG, id=self.id)
		self.mail = self.maildef()
		self.mail["id"] = self.id
		self.tmpname = "%08d.tmp" % (self.id)
#		self.dns = spf.query("", "", "")
		try:
		## Temp file in DISK
			if not os.path.exists(conf["main"]["tmpdir"]): mkdir(conf["main"]["tmpdir"])
			self.tmp = open("%s/%s" % (conf["main"]["tmpdir"], self.tmpname),"w+b")
		except IOError, (errno, strerror):
			debug("Temp file failure (%s: %s)" % (errno, strerror), LOG_DEBUG, id=self.id)
		except:
			debug("Temp file (%s) failure" % "%s/%s" % (conf["main"]["tmpdir"], self.tmpname), LOG_DEBUG, id=self.id)
		self.mail["tmpfile"]=self.tmpname

## This is runned for every SMTP Connection, and ONLY when Sendmail
## connects.
	def _cleanup(self):
		debug("SpamMilter._cleanup()", LOG_DEBUG, id=self.id)
		if self.tmp:
			self.tmp.close()
			rm(self.tmp.name, id=self.id)
		if self.mail:
			if conf["main"]["timeme"] and self.mail["timer"].has_key("timepass"): self.mail["timer"]["timepass"] = str("%.4f") % timeme(self.mail["timer"]["timepass"], id=self.id, title="TTimer")
			if not conf["runtime"]["offline"]:
				if conf["main"]["savedir"]:
					save_vars(self.mail, "%s/%08d.var" % (conf["main"]["savedir"], self.id), id=self.id)
#			else:
#				if self.mail.has_key("raw"): del self.mail["raw"]
#				if self.mail.has_key("mime"): del self.mail["mime"]
#				if self.mail.has_key("header"): del self.mail["header"]
#			print show_vars(self.mail)
		sys.stdout.flush()
		if not conf["runtime"]["offline"]: del self.mail
		return

	def log(self,*msg):
		debug(msg, LOG_DEBUG, id=self.id)

	def abort(self):
		debug("SpamMilter.abort()", LOG_DEBUG, id=self.id)
		self.mail = None
		self._cleanup()
		return CONTINUE

	def close(self):
		debug("SpamMilter.close()", LOG_DEBUG, id=self.id)
		if self.mail: self.mail["smtpcmds"].append("close")
		self._cleanup()
		return CONTINUE

	def connect(self,hostname,family,hostaddr):
		if conf["main"]["timeme"]: timer = timeme()
		debug("SpamMilter.connect(%s, %s)" % (hostname,hostaddr), LOG_DEBUG, id=self.id)
		if self.mail: self.mail["smtpcmds"].append("connect")
		self.mail["received"][1]["ip"] = hostaddr[0]
		self.mail["received"][1]["dns"] = hostname
		if conf["main"]["timeme"]: self.mail["timer"]["smtp_connect"] = str("%.4f") % timeme(timer, id=self.id, noshow=True)
		return CONTINUE

	def hello(self,hostname):
		if conf["main"]["timeme"]: timer = timeme()
		debug("SpamMilter.hello(%s)" % (hostname), LOG_DEBUG, id=self.id)
		if self.mail: self.mail["smtpcmds"].append("hello")
		self.mail["received"][1]["helo"] = hostname
		self.reuse = self.mail["received"][1]
		if conf["main"]["timeme"]: self.mail["timer"]["smtp_hello"] = str("%.4f") % timeme(timer, id=self.id, noshow=True)
		return CONTINUE

	def envfrom(self,mailfrom,*vars):
		if not self.mail or "eom" in self.mail["smtpcmds"]:
			self._cleanup()
			debug("Connection reused", LOG_DEBUG, id=self.id)
			self.__init__()
			self.mail["received"][1] = self.reuse
			self.mail["smtpcmds"].append("reused")

		if conf["main"]["timeme"]: timer = timeme()
		debug("SpamMilter.envfrom(\"%s\", %s)" % (mailfrom,vars), LOG_DEBUG, id=self.id)
		if conf["main"]["timeme"]: self.mail["timer"]["timepass"] = timeme()
		if self.mail: self.mail["smtpcmds"].append("envfrom")

		if mailfrom == "<>":
			if self.mail["received"][1].has_key("dns"):
				mailfrom = "<MAILER-DAEMON@%s>" % (self.mail["received"][1]["dns"])
			else:
				mailfrom = "<MAILER-DAEMON@[%s]>" % (self.mail["received"][1]["ip"])
		self.mail["from"] = parse_addrs(mailfrom, id=self.id)

		if not conf["runtime"]["offline"]:
			self.mail["my"]["ip"] = self.getsymval('{if_addr}')
			self.mail["my"]["dns"] = self.getsymval('{if_name}')
			if self.getsymval('{auth_type}'):
				self.mail["smtp_auth"] = self.getsymval('{auth_authen}')

		if conf["main"]["timeme"]: self.mail["timer"]["smtp_envfrom"] = str("%.4f") % (timeme(timer, id=self.id, noshow=True))

		return CONTINUE

	def envrcpt(self,rcpt,*vars):
		if conf["main"]["timeme"]: timer = timeme()
		debug("SpamMilter.envrcpt(\"%s\")" % (rcpt), LOG_DEBUG, id=self.id)
		if self.mail: self.mail["smtpcmds"].append("envrcpt")

		if rcpt.startswith('<MAILER-DAEMON@'): debug("?To MAILER-DAEMON ?", LOG_DEBUG, id=self.id)

		if len(self.mail["to"]) > 0 and rcpt not in self.mail["to"]:
			self.mail["to"].append(parse_addrs(rcpt, id=self.id)[0])
		else:
			self.mail["to"] = parse_addrs(rcpt, id=self.id)

		if conf["main"]["timeme"]:
			if self.mail["timer"].has_key("smtp_envrcpt"):
				self.mail["timer"]["smtp_envrcpt"] = str("%.4f") % (float(self.mail["timer"]["smtp_envrcpt"]) + timeme(timer, id=self.id, noshow=True))
			else:
				self.mail["timer"]["smtp_envrcpt"] = str("%.4f") % (timeme(timer, id=self.id, noshow=True))
		return CONTINUE

	def header(self,field,value):
		if conf["main"]["timeme"]: timer = timeme()
		if self.mail and "header" not in self.mail["smtpcmds"]: self.mail["smtpcmds"].append("header")

		debug("SpamMilter.header(%s, %s)" % (field,value), LOG_DEBUG, id=self.id)

		if self.tmp and len(self.mail["header"]) == 0:
			self.tmp.write("From %s %s\n" % (self.mail["from"][0], time.ctime()))
			self.mail["size"] = 0
			self.mail["subject"] = ""
		if self.tmp: self.tmp.write("%s: %s\n" % (field, value))

# Note, this is NOT endless loop, it is just used like switch-case
# statement. We break out when perferred line has been processed.
# Save header line as is, before prosessing

		while 1:
# Headers to drop ... just proof-of-concept
			lfield = field.lower()
			if lfield in [ "x-spambayes-classification", "x-spam-level" ]:
				break

			onelinerh = oneliner(value, id=self.id).strip()
			if self.mail["header"].has_key(field) and lfield not in [ "subject" ]:
				if type(self.mail["header"][field]) is not list:
					tmp = self.mail["header"][field]
					del self.mail["header"][field]
					self.mail["header"][field] = [ tmp ]
				self.mail["header"][field].append(onelinerh)
			else:
				self.mail["header"][field] = onelinerh

			if lfield == "subject":
				self.mail["subject"] = self.mail["header"][field][:]
				break

			if lfield == "received":
				a = re.compile("(?:from ((?P<ip3>[\d\.]+)|(?P<helo>\S+)) (?:\(helo (?P<helo2>[\w\d\.]+?)\) )?((?:\(?(?:\w+@)?(?:\S+(?: )?)?)?(?:(?:\[)(?P<ip>[\d.]+?)(?:\](?:[: ].+?)?))\)? )?|(\((?P<ip2>[\d\.]+?)\) )?)(?:\(using .*?\))?by (?P<by>.+?)(?: \(.+?\))? (with|id) ").match(onelinerh.lower())
				if a == None:
					break
				reclen = len(self.mail["received"])+1
				self.mail["received"][reclen]=a.groupdict()
				if self.mail["received"][reclen]["ip"] == None and self.mail["received"][reclen]["ip3"] != None: self.mail["received"][reclen]["ip"] = self.mail["received"][reclen]["ip3"]
				del self.mail["received"][reclen]["ip3"]
				if self.mail["received"][reclen]["ip"] == None and self.mail["received"][reclen]["ip2"] != None: self.mail["received"][reclen]["ip"] = self.mail["received"][reclen]["ip2"]
				del self.mail["received"][reclen]["ip2"]
				if self.mail["received"][reclen]["ip"] == None:
					del self.mail["received"][reclen]
					break
				if self.mail["received"][reclen]["helo"] == None and self.mail["received"][reclen]["helo2"] != None: self.mail["received"][reclen]["helo"] = self.mail["received"][reclen]["helo2"]
				del self.mail["received"][reclen]["helo2"]

#				try:
#					dns = self.dns.dns("%s.in-addr.arpa" % spf.reverse_dots(self.mail["received"][reclen]["ip"]), "PTR")
#					if len(dns) > 0 and type(dns) is list:
#						self.mail["received"][reclen]["dns"] = dns[0]
#				except DNS.DNSError, (errmsg):
#					if errmsg in ["Timeout"]:
#						debug("TIMEOUT SEEN")
#					debug("DNS Error: %s (in header, received PTR)" % errmsg, LOG_DEBUG, id=self.id)
#					pass
				break
			break

		if conf["main"]["timeme"]:
			if self.mail["timer"].has_key("smtp_header"):
				self.mail["timer"]["smtp_header"] = str("%.4f") % (float(self.mail["timer"]["smtp_header"]) + timeme(timer, id=self.id, noshow=True))
			else:
				self.mail["timer"]["smtp_header"] = str("%.4f") % (timeme(timer, id=self.id, noshow=True))
		return CONTINUE

	def eoh(self):
		if conf["main"]["timeme"]: timer = timeme()
		debug("SpamMilter.eoh()", LOG_DEBUG, id=self.id)
		if self.mail: self.mail["smtpcmds"].append("eoh")

		toremove = []
		for r in self.mail["received"]:
			# Now we have received lines, make readable and remove stupid entries
			if self.mail["received"][r].has_key("by"):
				del self.mail["received"][r]["by"]
			for f in self.mail["received"][r].keys():
				if self.mail["received"][r][f] == None:
					del self.mail["received"][r][f]

			if not self.mail["received"][r].has_key("ip"):
				toremove.append(r)
				continue
			if r>1 and is_listed(self.mail["received"][r]["ip"], ["^127\.", "^192\.168\.", "^10\."], noshow=True):
				toremove.append(r)
				continue

			try:
				if self.mail["received"][r].has_key("dns"):
					if self.mail["received"][r]["dns"][0] == "[" or is_listed(self.mail["received"][r]["dns"], ["^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"], noshow=True):
						del self.mail["received"][r]["dns"]
				if self.mail["received"][r].has_key("helo"):
					if self.mail["received"][r]["helo"][0] == "[":
						self.mail["received"][r]["helo"] = self.mail["received"][r]["helo"][1:-1]
### I had this commented out, dunno why :)
					if self.mail["received"][r].has_key("dns") and self.mail["received"][r]["dns"] == self.mail["received"][r]["helo"]:
						del self.mail["received"][r]["helo"]
					elif is_listed(self.mail["received"][r]["helo"], ["^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"], noshow=True):
						if self.mail["received"][r]["helo"] == self.mail["received"][r]["ip"]:
							del self.mail["received"][r]["helo"]
						elif is_listed(self.mail["received"][r]["helo"], ["^127\.", "^192\.168\.", "^10\."], noshow=True):
							del self.mail["received"][r]["helo"]
###
			except:
				debug("%s: %s (eoh -> received fix)" % (sys.exc_type, sys.exc_value), LOG_ERR, id=self.id, trace=False)

		for r in toremove:
			del self.mail["received"][r]

		if conf["main"]["timeme"]: self.mail["timer"]["smtp_eoh"] = str("%.4f") % (timeme(timer, id=self.id, noshow=True))
		return CONTINUE

	def body(self,chunk):
		if conf["main"]["timeme"]: timer = timeme()
		debug("SpamMilter.body() (chunk size: %d)" % len(chunk), LOG_DEBUG, id=self.id)

		if self.mail: self.mail["smtpcmds"].append("body")
		if self.tmp and self.mail["size"] == 0:
			self.tmp.write("\n")
		self.mail["size"] += len(chunk)
		if self.tmp: self.tmp.write(chunk)

		if conf["main"]["timeme"]: self.mail["timer"]["smtp_body"] = str("%.4f") % (timeme(timer, id=self.id, noshow=True))
		return CONTINUE

	def eom(self):
		if conf["main"]["timeme"]: timer = timeme()
		debug("SpamMilter.eom()", LOG_DEBUG, id=self.id)
		if self.mail: self.mail["smtpcmds"].append("eom")

###
### Sample how filter can 'answer' mail messages
###
		if self.mail["to"][0][0:11] == "spamfilter@":
			debug("Test request from %s" % self.mail["from"][0], LOG_ERR, id=self.id)
			if conf["runtime"]["offline"]: return
			self.delrcpt(self.mail["to"][0])
			self.addrcpt(self.mail["from"][0])
			self.chgheader("MIME-Version", 1, "")
			self.chgheader("Reply-To", 0, "")
			self.chgheader("From", 0, "Spam Filter <abuse@%s>" % (self.mail["my"]["dns"]))
			self.chgheader("Content-Type", 1, "text/plain")
			self.chgheader("Subject", 1, "Test message from %s" % (self.mail["from"][0]))
			self.replacebody("""

Your test message was received

""")
			return Milter.ACCEPT

		# Authenticated sender, accept without logging
		if not conf["runtime"]["offline"] and self.mail.has_key("smtp_auth"):
			debug("\tskip, authenticated", LOG_DEBUG, id=self.id)
			return Milter.ACCEPT
		# Domain (not) found from filtered list
#
#
# TODO: root@smtp-dev1.sspamm.com should match with "filter sspamm.com"
#
#

		(tests, self.mail) = is_filtered(self.mail)

		if not tests:
			debug("\tskip, not filtered domain", LOG_DEBUG, id=self.id)
			return Milter.CONTINUE
		else:
			self.mail["rules"] = is_listed(self.mail["todomain"], conf["filter"]["rules"], id=self.id)

		if self.mail["size"] == 0 and self.mail["subject"] == "":
			self.mail["type"] = "empty"
			return Milter.DISCARD

		subchar = []
		try:
			if self.tmp:
				self.tmp.seek(0)
				msg = message_from_file(self.tmp)
				(subj, subchar) = decode_header(msg["subject"])[0]
				self.mail["subject"] = oneliner(stripUnprintable(subj), id=self.id)
				self.mail["rawsubject"] = oneliner(stripUnprintable(msg["subject"]), id=self.id)
				self.mail["raw"] = """%s""" % msg
				self.mail["mime"] = mimepart(msg, id=self.id)
				charset = msg.get_charsets()
				charset.append(subchar)
				self.mail["charset"]=uniq(charset)
		except:
# WORKME? If 'crashes' on email.message_from_file, save that tmp file into
# /tmp so we can take look of it later. Now we just need to pass mail
# without checking.
			debug("eom(): %s: %s" % (sys.exc_type, sys.exc_value), LOG_ERR, id=self.id, trace=False)
			if self.tmp:
				self.tmp.close()
				mv(self.tmp.name, "/tmp/%s" % (self.tmpname))
				save_vars(self.mail, "/tmp/%s.var" % (self.tmpname), id=mail["id"]);
				debug("saved as /tmp/%s" % (self.tmpname), LOG_ERR, id=self.id, trace=False)
			return Milter.CONTINUE

##
## Now message is received and processed. Fun part begins now, testing.
##
		for test in tests:
			if test in ['disable']: continue
			try:
				debug("*call test_%s()" % (test), LOG_DEBUG, id=self.mail["id"])
#				(ret, self.mail) = eval("test_"+test)(self.mail)
#				if conf["runtime"]["offline"]:
#					if ret:
#						matches[test] = "%s: %s%s" % (self.mail["action"], self.mail["reason"], self.mail["detail"])
#					else:
#						matches[test] = "pass"
#				if ret:
#					if not conf["runtime"]["offline"]:
#						debug("TEST MATCHES: %s" % (test), LOG_NOTICE, id=self.mail["id"])
#					break
#				else:
#					if test == "bayesian": self.mail["bayesiantype"] = self.mail["type"]
#				continue
			except:
				debug("Test: %s" % (test), LOG_DEBUG)
				debug("%s: %s (do tests)" % (sys.exc_type, sys.exc_value), LOG_DEBUG, id=self.id, trace=False)
				save_vars(self.mail, "/tmp/%s.var" % (self.tmpname), id=mail["id"]);
				traceback.print_exc(limit=None, file=sys.stderr)

			continue









		if conf["main"]["timeme"]: self.mail["timer"]["smtp_eom"] = str("%.4f") % (timeme(timer, id=self.id, noshow=True))

		return CONTINUE

## List of Milter commands:
#	def setreply(self,rcode,xcode=None,msg=None,*ml):
#	def addheader(self,field,value,idx=-1):
#	def chgheader(self,field,idx,value):
#	def addrcpt(self,rcpt,params=None):
#	def delrcpt(self,rcpt):
#	def replacebody(self,body):
#	def chgfrom(self,sender,params=None):
#	def quarantine(self,reason):
#	def progress(self):


##############################################################################
##
## CHILD THREADS
##
def Tconfig(childname=None):
	global conffile, conf
	
	debug("Tconfig")
	if conf["runtime"]["conffile"] == None:
		debug("Scan for config file location")

		files = [ ]
		if conffile[0] != "/":
			files.append("%s/%s" % (startdir, conffile))
			files.append("/etc/%s" % conffile)
			files.append("/etc/sspamm/%s" % conffile)
			files.append(None)

		cf = conffile
		for conffile in files:
			if conffile != None and os.access(conffile, os.R_OK):
				break

		if conffile == None:
			debug("FATAL: Can't find or read %s." % (cf), LOG_ERR)
			return

		debug("Config file %s found." % conffile)

	debug("Tconfig loop started")
	while conf["runtime"]["endtime"] == 0:
		if not os.access(conffile, os.R_OK):
			debug("FATAL: Can't access %s." % (conffile), LOG_ERR)
			time.sleep(60)
			continue

		debug("Configuration file %s tested for update" % (conffile), LOG_DEBUG)
		if conf["runtime"]["conftime"] < os.stat(conffile)[8]:
			if conf["runtime"]["conftime"] > 0:
				config_save()
			config_load(conffile)
			debug("Configuration %s reloaded" % (conffile), LOG_DEBUG)
			conf["runtime"]["conftime"] = os.stat(conffile)[8]
			conf["runtime"]["conffile"] = conffile
			if conf["main"]["sspammdir"]:
				conf["runtime"]["confpath"] = conf["main"]["sspammdir"]
			else:
				conf["runtime"]["confpath"] = conf["runtime"]["conffile"][0:conf["runtime"]["conffile"].rfind("/")+1]

			if conf["main"]["savedir"]:
				mkdir(conf["main"]["savedir"])
		else:
			time.sleep(5)
		if childname != "Configuration Loader":
			break
		time.sleep(1)
	return
	

##
## Main Function
##
def cleanquit():
	global conf

	debug("cleanquit()")
	rm(conf["main"]["pid"])
	conf["runtime"]["endtime"] = "%.0f" % time.time()
	debug("Spam Filter runtime was %.0f seconds" % (int(conf["runtime"]["endtime"])-int(conf["runtime"]["starttime"])), LOG_ERR)
#	print show_vars(conf["main"])
	print show_vars(conf["runtime"])
	sys.stdout.flush()
	sys.exit(0)

def main():
	global conf

#	if conf["main"]["tmpdir"]:
#		mkdir(conf["main"]["tmpdir"])
#		os.chdir(conf["main"]["tmpdir"])

	if 0:
		thread.start_new_thread(Tconfig,("Configuration Loader",))
	else:
		Tconfig()
		signal(SIGHUP , Tconfig) # 1
		signal(SIGINT , cleanquit) # ^C
		signal(SIGBUS , cleanquit) # 7
		signal(SIGTERM, cleanquit) # 15


	wtime = 0
	maxwtime = 5
	while conf["runtime"]["conftime"] == 0 and wtime < maxwtime:
		sys.stdout.flush()
		time.sleep(1)
		wtime += 1
	if conf["runtime"]["conftime"] == 0:
		debug("Couldn't load configuration file in %d seconds." % (maxwtime), LOG_ERR)
		sys.stdout.flush()
		return

	Milter.factory = SpamMilter
	Milter.set_flags(ADDRCPT + DELRCPT + ADDHDRS + CHGHDRS + CHGBODY)

	debug("Spam Filter started", LOG_ERR)
	try:
		Milter.runmilter(conf["main"]["name"],conf["main"]["port"],300)
	except SystemExit:
		pass
	except:
		debug("%s: %s" % (sys.exc_type, sys.exc_value), LOG_ERR)
	cleanquit()

##
## Start
##
if __name__ == "__main__":
	tmp = None
	conf["runtime"]["starttime"] = "%.0f" % time.time()
	startdir = os.getcwd()

	os.nice(5)
	locale.setlocale(locale.LC_CTYPE, 'fi_FI.UTF-8')

	if not sys.argv[1:]:
		if(makepid(conf["main"]["pid"])): main()
	else:
		""" Usage """
		sys.exit(1)
sys.exit(0)