summaryrefslogtreecommitdiffabout
path: root/src/engine.c
blob: b40e75ed420722be3c27bf0b5a05ac4ca443fef3 (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
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
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
/* This file is part of mailfromd.
   Copyright (C) 2005, 2006, 2007 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/>. */

#define MF_SOURCE_NAME  MF_SOURCE_ENGINE

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#define obstack_chunk_alloc malloc
#define obstack_chunk_free free
#include <obstack.h>
#include <syslog.h>
#include <signal.h>
#include <pwd.h>
#include <grp.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>

#include <mailutils/mailutils.h>
#include <mailutils/daemon.h>

#include "mailfromd.h"


static char *ctx_getsym(void *data, char *str);
static int ctx_setreply(void *data, char *code, char *xcode, char *message);
static void ctx_setheader(void *data, struct old_header_node *hdr);

/* Per-message data */
struct smtp_io_data; /* Declared later on */
struct message_data {
	eval_environ_t env;        /* Evaluation environment */
	struct smtp_io_data *io;   /* I/O data for SMTP transactions */
	mu_list_t hdr;             /* List of header modifications */
	char *helostr;             /* Domain name obtained in HELO phase */   
	char msgid[64];            /* Message ID */  
};

static struct message_data *
priv_get(SMFICTX *ctx)
{
	static struct message_data *test_data;
	struct message_data *md;

	if (mode == MAILFROMD_TEST)
		md = test_data;
	else
		md = (struct message_data*) gacopyz_getpriv(ctx);
		
	if (!md) {
		md = malloc(sizeof(*md));
		if (!md) 
			mu_error(_("Not enough memory"));
		else {
			md->env = create_environment(ctx,
						     ctx_getsym,
						     ctx_setreply,
						     ctx_setheader,
						     ctx);
			clear_rcpt_count(md->env);
			md->hdr = NULL;
			md->io = NULL;
			md->helostr = NULL;
			md->msgid[0] = 0;
			if (mode == MAILFROMD_TEST)
				test_data = md;
			else
				gacopyz_setpriv(ctx, md);
			env_init(md->env);
			xeval(md->env, smtp_state_begin);
		}
	}
	if (!md->msgid[0]) {
		char *p = gacopyz_getsymval(ctx, "i");
		if (p) {
			size_t len = strlen(p);
			if (len > sizeof md->msgid - 3)
				len = sizeof md->msgid - 3;
			memcpy(md->msgid, p, len);
			md->msgid[len++] = ':';
			md->msgid[len++] = ' ';
			md->msgid[len] = 0;
		}
	}
	return md;
}

static int
priv_set_io(SMFICTX *ctx, struct smtp_io_data *io)
{
	struct message_data *md = priv_get(ctx);
	if (!md)
		return 1;
	md->io = io;
	return 0;
}

const char *
mailfromd_msgid(SMFICTX *ctx)
{
	struct message_data *md = priv_get(ctx);
	return md->msgid;
}

char *
mailfromd_timestr(time_t timestamp, char *timebuf, size_t bufsize)
{
	struct tm tm;
	gmtime_r(&timestamp, &tm);
	strftime(timebuf, bufsize, "%c", &tm);
	return timebuf;
}

void
destroy_old_header(void *item)
{
	struct old_header_node *node = item;
	free(node->value);
}
	
int
priv_store_header_command(SMFICTX *ctx, struct old_header_node *node)
{
	struct message_data *md = priv_get(ctx);
	if (!md)
		return 1;
	if (!md->hdr) {
		mu_list_create(&md->hdr);
		mu_list_set_destroy_item(md->hdr, destroy_old_header);
	}
	mu_list_append(md->hdr, node);
	return 0;
}


/* Run-time execution */

static char *
ctx_getsym(void *data, char *str)
{
	char *ret = gacopyz_getsymval(data, str);
	if (!ret) {
		struct message_data *md = priv_get(data);
		if (strcmp (str, "s") == 0)
			ret = md->helostr;
	}
	return ret;
}

static int
ctx_setreply(void *data, char *code, char *xcode, char *message)
{
	if (code) 
		return gacopyz_setreply(data, code, xcode, message);
	return 0;
}

static void
ctx_setheader(void *data, struct old_header_node *hdr)
{
	priv_store_header_command(data, hdr);
}


/* Message capturing functions */
static int capture_enabled;

void
capture_on()
{
	milter_enable_state(smtp_state_helo);
	milter_enable_state(smtp_state_envfrom);
	milter_enable_state(smtp_state_header);
	milter_enable_state(smtp_state_eoh);
	milter_enable_state(smtp_state_body);
	milter_enable_state(smtp_state_eom);
	capture_enabled = 1;
}

static void
capture_from(eval_environ_t env, const char *str)
{
	if (capture_enabled) {
		time_t t;
		struct tm *tm;
		char datebuf[26];

		env_capture_start(env);
		
		t = time(NULL);
		tm = localtime(&t);
		mu_strftime(datebuf, sizeof datebuf,
			    "%a %b %d %H:%M:%S %Y", tm);

		env_capture_write_args(env,
				       "From ", str, " ", datebuf, "\n", NULL);
	}
}

static void
capture_header(eval_environ_t env, const char *hf, const char *hv)
{
	env_capture_write_args(env, hf, ": ", hv, "\n", NULL);
}

static void
capture_eoh(eval_environ_t env)
{
	env_capture_write_args(env, "\n", NULL);
}

static void
capture_body(eval_environ_t env, unsigned char *bodyp, size_t len)
{
	env_capture_write(env, bodyp, len);
}

static void
capture_eom(eval_environ_t env)
{
}
	

/* SMTP I/O functions */

#define SMTP_MAJOR(c) ((c)/100)

struct smtp_io_data {
	SMFICTX *ctx;        /* Milter context */
	mu_stream_t stream;  /* I/O stream */
	size_t send_off;     /* Send offset */
	size_t recv_off;     /* Receive offset */
	struct obstack stk;  /* Obstack for keeping commands/replies */
	char *command;       /* Last issued command */ 
	char *reply;         /* Last received reply */
	char *start;         /* First line of the reply, if it was multiline */
	char buf[128];       /* Input buffer */
	size_t level;        /* Number of bytes in buf */
	int code;            /* Reply code */
};

void
transcript(struct smtp_io_data *io, char *prefix, const char *msg)
{
	if (do_transcript) {
		int len = strlen(msg);
		if (msg[len-1] == '\n') {
			--len;
			if (len > 0 && msg[len-1] == '\r')
				--len;
		}
		if (len) 
			logmsg(LOG_INFO, "%s%s %*.*s",
			       mailfromd_msgid(io->ctx),
			       prefix, len, len, msg);
	}
}

int
smtp_io_data_init(struct smtp_io_data *dat, SMFICTX *ctx, mu_stream_t stream)
{
	obstack_init(&dat->stk);
	dat->send_off = dat->recv_off = 0;
	dat->stream = stream;
	dat->start = dat->command = dat->reply = NULL;
	dat->level = 0;
	dat->ctx = ctx;
	if (ctx && priv_set_io(ctx, dat)) /* save the private data */
		return 1;
	return 0;
}

void
smtp_io_data_destroy(struct smtp_io_data *dat)
{
	if (dat) {
		mu_stream_close (dat->stream);
		mu_stream_destroy(&dat->stream,
				  mu_stream_get_owner(dat->stream));
		obstack_free(&dat->stk, NULL);
		if (dat->ctx)
			priv_set_io(dat->ctx, NULL);
	}
}

struct timeout_ctl {
  time_t start;
  time_t timeout;
};

static void
init_timeout_ctl(struct timeout_ctl *tctl, time_t timeout)
{
  tctl->start = time(NULL);
  tctl->timeout = timeout;
}

#define UPDATE_TTW(t) do {                                           \
        time_t now = time(NULL);                                     \
	time_t delta = now - (t).start;                              \
	if ((t).timeout > delta)                                     \
		(t).timeout -= delta;                                \
	else                                                         \
		(t).timeout = 0;                                     \
        (t).start = now;                                             \
} while (0)

int
smtp_stream_wait(mu_stream_t stream, int flags, struct timeout_ctl *tctl)
{
	int rc;
	int oflags = flags;
	struct timeval tv;
	
	while (tctl->timeout) {
		tv.tv_sec = tctl->timeout;
		tv.tv_usec = 0;
		rc = mu_stream_wait(stream, &oflags, &tv);

		/* Correct the timeout */
		UPDATE_TTW(*tctl);
		
		switch (rc) {
		case 0:
			if (flags & oflags)
				return 0;
			/* FALLTHROUGH */
		case EAGAIN:
		case EINPROGRESS:
			continue;

		default:
			return rc;
		}
	}
			
	return ETIMEDOUT;
}

int
smtp_wait(struct smtp_io_data *dat, int flags, struct timeout_ctl *tctl)
{
	return smtp_stream_wait(dat->stream, flags, tctl);
}

int
smtp_send(struct smtp_io_data *dat, char *command)
{
	size_t len = strlen(command);
	struct timeout_ctl tctl;

	init_timeout_ctl (&tctl, io_timeout);
	
	dat->reply = NULL; /* Clear reply for logging purposes */
	transcript(dat, "SEND:", command);
	do {
		size_t nb;
		int rc;
		
		UPDATE_TTW(tctl);
		
		rc = mu_stream_write(dat->stream, command, len,
					 dat->send_off, &nb);
		if (rc == 0) {
			if (nb == 0) {
				mu_error(_("stream_write: wrote 0 bytes"));
				return -1;
			}
			dat->send_off += nb;
			len -= nb;
			command += nb;
		} else if (rc == EAGAIN) {
			rc = smtp_wait(dat, MU_STREAM_READY_WR, &tctl);
			if (rc) {
				mu_error(_("smtp_wait failed: %s"),
					  mu_strerror(rc));
				return -1;
			}
			continue;
		} else {
			mu_error("mu_stream_write: %s",
				  mu_strerror (rc));
			return -1;
		}
	} while (len > 0);
	return 0;
}

int
smtp_send2(struct smtp_io_data *dat, char *command, char *arg)
{
	obstack_grow(&dat->stk, command, strlen(command));
	if (arg)
		obstack_grow(&dat->stk, arg, strlen(arg));
	obstack_grow(&dat->stk, "\r\n", 2);
	obstack_1grow(&dat->stk, 0);
	dat->command = obstack_finish(&dat->stk);
	
	return smtp_send(dat, dat->command);
}

int
smtp_send3(struct smtp_io_data *dat, char *command, char *arg1, char *arg2)
{
	obstack_grow(&dat->stk, command, strlen(command));
	obstack_grow(&dat->stk, arg1, strlen(arg1));
	obstack_grow(&dat->stk, arg2, strlen(arg2));
	obstack_grow(&dat->stk, "\r\n", 2);
	obstack_1grow(&dat->stk, 0);
	dat->command = obstack_finish(&dat->stk);
	
	return smtp_send(dat, dat->command);
}

int
smtp_recvline(struct smtp_io_data *dat, time_t timeout)
{
	struct timeout_ctl tctl;
	init_timeout_ctl(&tctl, timeout);
	for (;;) {
		char *p;
		
		UPDATE_TTW(tctl);
		
		if (dat->level == 0) {
			int rc = mu_stream_read(dat->stream,
						dat->buf, sizeof dat->buf,
						dat->recv_off, &dat->level);
			if (rc == 0) {
				if (dat->level == 0) {
					mu_error(_("stream_read: read 0 bytes"));
					return -1;
				}
				dat->recv_off += dat->level;
			} else if (rc == EAGAIN) {
				rc = smtp_wait(dat, 
					       MU_STREAM_READY_RD, &tctl);
				if (rc) {
					mu_error(_("smtp_wait failed: %s"),
						  mu_strerror(rc));
					return -1;
				}
				continue;
			} else {
				mu_error("mu_stream_read: %s",
					  mu_strerror (rc));
				return -1;
			}
		}


		p = memchr(dat->buf, '\n', dat->level);
		if (!p) {
			obstack_grow(&dat->stk, dat->buf, dat->level);
			dat->level = 0;
			continue;
		} else {
			size_t len = p - dat->buf + 1;
			obstack_grow(&dat->stk, dat->buf, len);
			obstack_1grow(&dat->stk, 0);
			dat->reply = obstack_finish(&dat->stk);
			dat->level -= len;
			memmove(dat->buf, dat->buf + len, dat->level);
			break;
		}
	}
	return 0;
}

int
smtp_recv_tm(struct smtp_io_data *dat, time_t timeout)
{
	char *p;
	dat->start = NULL;
	do {
		int code;
		int rc = smtp_recvline(dat, timeout);
		if (rc)
			return -1;
		transcript(dat, "RECV:", dat->reply);
		code = strtoul(dat->reply, &p, 0);
		if (p - dat->reply != 3 || (*p != '-' && *p != ' ')) {
			mu_error(_("Unexpected reply from server: %s"),
				 dat->reply);
			return -1;
		} else if (!dat->start) {
			dat->start = dat->reply;
			dat->code = code;
		} else if (dat->code != code) {
			mu_error(_("Unexpected reply code from server: %d"),
				 code);
			return -1;
		}
	} while (*p == '-');
	obstack_1grow (&dat->stk, 0);
	obstack_finish (&dat->stk);
	return 0;
}

int
smtp_recv(struct smtp_io_data *dat)
{
	return smtp_recv_tm(dat, io_timeout);
}


const char *
smtp_last_sent(struct smtp_io_data *dat)
{
	if (dat->command) {
		size_t len = strcspn(dat->command, "\r\n");
		dat->command[len] = 0;
		return dat->command;
	}
	return "nothing";
}

const char *
smtp_last_received(struct smtp_io_data *dat)
{
	if (dat->reply) {
		size_t len = strcspn(dat->reply, "\r\n");
		dat->reply[len] = 0;
		return dat->reply;
	}
	return "nothing";
}



/* Milter-specific functions */

static mf_status
reset(struct smtp_io_data *io)
{
	smtp_send(io, "RSET");
	if (smtp_recv(io)) 
		return mf_temp_failure;
	else if (SMTP_MAJOR(io->code) != 2) 
		return SMTP_MAJOR(io->code) == 4 ?
			mf_temp_failure : mf_failure;
	return mf_success;
}

/* Verify whether EMAIL address is served by host CLIENT_ADDR. */
mf_status
check_on_host(eval_environ_t env, char *email, char *client_addr,
	      char *ehlo, char *mailfrom)
{
	int rc;
	mu_stream_t stream;
	struct smtp_io_data io;
	mf_status status = mf_success;
	int count = 0;
	SMFICTX *ctx = env_get_context(env);
	struct timeout_ctl tctl;
	
	debug2(10, "email = %s, client_addr = %s", email, client_addr);
	
	set_last_poll_result(env, client_addr, "", "");
	
	rc = mu_tcp_stream_create_with_source_ip (&stream, client_addr, 25,
						  source_address,
						  MU_STREAM_NONBLOCK);
	if (rc) {
		mu_error(_("%sCannot connect to `%s': %s"),
			 mailfromd_msgid(ctx), client_addr,
			 mu_strerror (rc));
		return mf_temp_failure;
	}
	
	init_timeout_ctl(&tctl, connect_timeout);
	while ((rc = mu_stream_open(stream))) {
		if ((rc == EAGAIN || rc == EINPROGRESS)
		    && tctl.timeout) {
			rc = smtp_stream_wait(stream, MU_STREAM_READY_WR,
					      &tctl);
			if (rc == 0) {
				UPDATE_TTW(tctl);
				continue;
			}
		}
		mu_error("%sstream_open: %s, %d",
			  mailfromd_msgid(ctx), mu_strerror(rc), count);
		mu_stream_destroy(&stream, mu_stream_get_owner(stream));
		return mf_temp_failure;
	}
	debug(100,"stream opened");
	
	if (smtp_io_data_init(&io, ctx, stream))
		status = mf_temp_failure;
	else {
		mu_address_t addr;
		size_t mailcount;

		/* FIXME-MU: compensate for mailutils deficiency */
		if (mailfrom[0] == 0)
			mailfrom = "<>"; 
		rc = mu_address_create(&addr, mailfrom);
		if (rc) {
			mu_error(_("Cannot create address `%s': %s"),
				 mailfrom, mu_strerror(rc));
			return mf_temp_failure;
		}
		mu_address_get_count(addr, &mailcount);
		
		do {
			int i;
			
			if (smtp_recv_tm(&io, response_timeout)) {
				status = mf_temp_failure;
				break;
			} else if (SMTP_MAJOR(io.code) != 2) {
				status = SMTP_MAJOR(io.code) == 4 ?
					mf_temp_failure : mf_not_found;
				break;
			}
			
			smtp_send2(&io, "HELO ", ehlo);
			if (smtp_recv(&io)) {
				status = mf_temp_failure;
				break;
			} else if (SMTP_MAJOR(io.code) == 5) {
				/* Let's try EHLO, then */
				smtp_send2(&io, "EHLO ", ehlo);
				if (smtp_recv(&io)) {
					status = mf_not_found;
					break;
				}
			}
			if (SMTP_MAJOR(io.code) != 2) {
				status = SMTP_MAJOR(io.code) == 4 ?
					mf_temp_failure : mf_not_found;
				break;
			}

			for (i = 1; i <= mailcount; i++) {
				char *fromaddr;
				
				mu_address_aget_email(addr, i, &fromaddr);
			
				smtp_send3(&io, "MAIL FROM:<", fromaddr, ">");
				free(fromaddr);
				if (smtp_recv(&io)) {
					status = mf_temp_failure;
					break;
				} else if (SMTP_MAJOR(io.code) != 2) {
					if (SMTP_MAJOR(io.code) == 4) {
						if (reset(&io) != mf_success) {
						/* RSET must always return 250
						   If it does not, there's no
						   use talking with this host
						   any more */
							status = mf_failure;
							break;
						} else
							status = mf_temp_failure;
					} else
						status = mf_not_found;
				} else {
					status = mf_success;
					break;
				}
			}
			if (status != mf_success)
				break;
			
			smtp_send3(&io, "RCPT TO:<", email, ">");
			if (smtp_recv(&io)) {
				status = mf_temp_failure;
				break;
			} else if (SMTP_MAJOR(io.code) != 2) {
				status = SMTP_MAJOR(io.code) == 4 ?
					mf_temp_failure : mf_not_found;
				break;
			}
		} while (0);
		
		mu_address_destroy(&addr); 

		set_last_poll_result(env,
				     client_addr,
				     smtp_last_sent(&io),
				     smtp_last_received(&io));
		
		debug4(1,
	             "%spoll exited with status: %s; sent \"%s\", got \"%s\"",
		       mailfromd_msgid(ctx), 
		       mf_status_str(status),
		       smtp_last_sent(&io),
		       smtp_last_received(&io));
		
		smtp_send2(&io, "QUIT", NULL);
	        smtp_recv(&io);
		smtp_io_data_destroy(&io);
	}
	
	return status;
}

mf_status
check_mx_records(eval_environ_t env, char *email, char *client_addr,
		 char *ehlo, char *mailfrom, int *pcount)
{
	int i;
	mxbuf_t mxbuf;
	mf_status rc, mxstat = getmx(client_addr, mxbuf);

	if (pcount)
		*pcount = 0;
	switch (mxstat) {
	case mf_temp_failure:
		rc = mf_temp_failure;
		break;

	case mf_failure:
	case mf_not_found:
		rc = mf_not_found;
		break;

	case mf_success:
		debug1(2,"Checking MX servers for %s", email);
		rc = mf_not_found;
		for (i = 0; i < MAXMXCOUNT && mxbuf[i]; i++) {
			rc = check_on_host(env, email, mxbuf[i],
					   ehlo, mailfrom);
			if (mf_resolved(rc))
				break;
		}
		if (pcount) {
			for (; i < MAXMXCOUNT && mxbuf[i]; i++)
				;
			*pcount = i;
		}
		dns_freemx(mxbuf);
		break;
		
	default:
		abort();
	}
	return rc;
}

/* Method "strict". Verifies whether EMAIL is understood either by
   host CLIENT_ADDR or one of MX servers of its domain */
mf_status
method_strict(eval_environ_t env, char *email, char *client_addr,
	      char *ehlo, char *mailfrom)
{
	mf_status rc;

        if (email[0] == 0)
                return mf_success;
	
	rc = cache_get2(email, client_addr);
	if (!mf_resolved(rc)) {
		set_cache_used(env, 0);
		rc = check_on_host(env, email, client_addr, ehlo, mailfrom);
		if (!mf_resolved(rc)) {
			mf_status mx_stat;
			mx_stat = check_mx_records(env, email, client_addr,
						   ehlo, mailfrom, NULL);
			if (mf_resolved(mx_stat)
			    || mx_stat == mf_temp_failure)
				rc = mx_stat;
		}
		if (mf_resolved(rc))
			cache_insert2(email, client_addr, rc);
	} else {
		set_last_poll_result(env, client_addr, "", "");
		set_cache_used(env, 1);
	}
	return rc;
}

/* Method "standard". Verifies whether EMAIL is understood by
   any of its MXs, or, if there are none, by the domain part host itself.  */
mf_status
method_standard(eval_environ_t env, char *email, char *ehlo, char *mailfrom)
{
	mf_status rc;

        if (email[0] == 0)
                return mf_success;
	
	rc = cache_get(email);
	if (!mf_resolved(rc)) {	
		char *p = strchr(email, '@');
		set_cache_used(env, 0);
		if (p == NULL) {
			mu_error(_("Invalid address: %s"), email);
			rc = mf_not_found;
		} else {
			int mxcount;
			rc = check_mx_records(env, email, p+1, ehlo, mailfrom,
					      &mxcount);
			if (rc != mf_success && mxcount == 0) {
				mf_status host_stat;
				host_stat = check_on_host(env, email, p+1, 
							  ehlo, mailfrom);
				if (mf_resolved(host_stat)
				    || host_stat == mf_temp_failure)
					rc = host_stat;
			}
		}
		if (mf_resolved(rc))
			cache_insert(email, rc);
	} else {
		set_last_poll_result(env, "", "", "");
		set_cache_used(env, 1);
	}
	return rc;
}

mf_status
listens_on (const char *client_addr, int port)
{
	unsigned count = 0;
	mu_stream_t stream;
	int rc;
	struct timeout_ctl tctl;
	
	if (port == 0)
		port = 25;

	debug2(10, "client_addr = %s, port = %d", client_addr, port);
	rc = mu_tcp_stream_create_with_source_ip (&stream, client_addr, port,
						  source_address,
						  MU_STREAM_NONBLOCK);
	if (rc) {
		debug1 (10, "mu_tcp_stream_create_with_source_ip: %s",
			mu_strerror (rc));
		return mf_failure;
	}

	init_timeout_ctl(&tctl, connect_timeout);
	while ((rc = mu_stream_open(stream))) {
		if ((rc == EAGAIN || rc == EINPROGRESS) && tctl.timeout) {
			rc = smtp_stream_wait(stream, MU_STREAM_READY_WR,
                                              &tctl);
			if (rc == 0) {
				UPDATE_TTW(tctl);
				continue;
			}
		}
		break;
	}
	mu_stream_destroy(&stream, mu_stream_get_owner(stream));

	debug3 (10, "mu_stream_open(%s): %s, %u", client_addr, mu_strerror(rc),
		count);

	return rc == 0 ? mf_success :
		(rc == EAGAIN || rc == EINPROGRESS) ?
		mf_temp_failure : mf_failure;
}

/* Cleanup functions */
void
filter_cleanup(SMFICTX *ctx)
{
	struct message_data *md = priv_get(ctx);
	debug(100,"cleaning up");
	if (md) {
		env_init(md->env);
		xeval(md->env, smtp_state_end);
		free(md->helostr);
		destroy_environment(md->env);
		smtp_io_data_destroy(md->io);
		mu_list_destroy(&md->hdr);
		free(md);
		gacopyz_setpriv(ctx, NULL);
	}
}


/* Milter interface functions */

int
xeval(eval_environ_t env, enum smtp_state tag)
{
	int rc;
	
	rc = eval_environment(env, entry_point[tag]);
	if (rc) 
		mu_error(_("Execution of the filter program was not finished"));
	if (tag == smtp_state_begin)
		env_save_catches(env);

	return rc;
}

sfsistat
mlfi_eval(SMFICTX *ctx, enum smtp_state tag)
{
	int rc;
	sfsistat status;
	struct message_data *md = priv_get(ctx);

	rc = xeval(md->env, tag);
	if (rc == 0)
		status = environment_get_status(md->env);
	else {
		gacopyz_setreply(ctx, "410", NULL,
			      "Local configuration error; please try again later");
		status = SMFIS_TEMPFAIL;
	}
	log_status(status, ctx);
	return status;
}

#define MFAM_STDIO 0
#define MFAM_UNIX  1
#define MFAM_INET  2

sfsistat
mlfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr)
{
	sfsistat status;
	struct message_data *md = priv_get(ctx);
	int port;
	char *addrstr;
	int family;
	
	if (!hostaddr) {
		family = MFAM_STDIO;
		port = 0;
		addrstr = "";
	} else switch (hostaddr->sa.sa_family) {
	case PF_INET:
		family = MFAM_INET;
		port = ntohs(hostaddr->sin.sin_port);
		addrstr = inet_ntoa(hostaddr->sin.sin_addr);
		break;
		
	case PF_UNIX:
		family = MFAM_UNIX;
		port = 0;
		addrstr = hostaddr->sunix.sun_path;
		break;

	default:
		mu_error(_("mlfi_connect: unsupported address family: %d"),
			 hostaddr->sa.sa_family);
		gacopyz_setreply(ctx, "410", NULL,
				 "Local configuration error; please try again later");
		return SMFIS_TEMPFAIL;
	}
	debug4(70, "Processing xxfi_connect: %s, %d, %u, %s",
	       hostname, family, port, addrstr);

	env_init(md->env);
	env_push_string(md->env, addrstr);
	env_push_number(md->env, port);
	env_push_number(md->env, family);
	env_push_string(md->env, hostname);
	env_make_frame(md->env);
	status = mlfi_eval(ctx, smtp_state_connect);
	env_leave_frame(md->env, 4);
	return status;
}

sfsistat
mlfi_helo(SMFICTX *ctx, char *helohost)
{
	sfsistat status;
	struct message_data *md = priv_get(ctx);

	debug1(70, "Processing xxfi_helo: %s", helohost);
	md->helostr = strdup(helohost);
	env_init(md->env);
	env_push_string(md->env, md->helostr);
	env_make_frame(md->env);
	status = mlfi_eval(ctx, smtp_state_helo);
	env_leave_frame(md->env, 1);
	return status;
}

static char *
concat_args(const char *fname, char **argv)
{
	size_t argc;
	char *p = NULL;

	for (argc = 0; argv[argc]; argc++)
		;
	if (mu_argcv_string(argc, argv, &p))
		debug3(70, "Processing %s: %s%s",
		       fname, argv[0], argv[1] ? " (more)" : "");
	else 
		debug2(70, "Processing %s: %s", fname, p);
	return p;
}

sfsistat
mlfi_envfrom(SMFICTX *ctx, char **argv)
{
	sfsistat status;
	struct message_data *md = priv_get(ctx);
	char *p = concat_args("xxfi_envfrom", argv);

	env_init(md->env);
	capture_from(md->env, argv[0]);
	env_push_string(md->env, p);
	free(p);
	env_push_string(md->env, argv[0]);
	env_make_frame(md->env);
	status = mlfi_eval(ctx, smtp_state_envfrom);
	env_leave_frame(md->env, 2);
	return status;
}

sfsistat
mlfi_envrcpt(SMFICTX *ctx, char ** argv)
{
	sfsistat status;
        struct message_data *md = priv_get(ctx);
	char *p = concat_args("xxfi_envrcpt", argv);

	env_init(md->env);
	env_push_string(md->env, p);
	free(p);
	env_push_string(md->env, argv[0]);
	env_make_frame(md->env);
	incr_rcpt_count(md->env);
	status = mlfi_eval(ctx, smtp_state_envrcpt);
	env_leave_frame(md->env, 2);
	return status;
}

sfsistat
mlfi_data(SMFICTX *ctx)
{
	sfsistat status;
	struct message_data *md = priv_get(ctx);

	debug(70, "Processing xxfi_data:");
	env_init(md->env);
	env_make_frame(md->env);
	status = mlfi_eval(ctx, smtp_state_data);
	env_leave_frame(md->env, 1);
	return status;
}

sfsistat
mlfi_header(SMFICTX *ctx, char *headerf, char *headerv)
{
	sfsistat status;
	struct message_data *md = priv_get(ctx);

	debug(70, "Processing xxfi_header:");
	env_init(md->env);
	capture_header(md->env, headerf, headerv);
	env_push_string(md->env, headerv);
	env_push_string(md->env, headerf);
	env_make_frame(md->env);
	status = mlfi_eval(ctx, smtp_state_header);
	env_leave_frame(md->env, 2);
	return status;
}

sfsistat
mlfi_eoh(SMFICTX *ctx)
{
	sfsistat status;
        struct message_data *md = priv_get(ctx);
	debug(70, "Processing xxfi_eoh");
	env_init(md->env);
	capture_eoh(md->env);
	env_make_frame(md->env);
	status = mlfi_eval(ctx, smtp_state_eoh);
	env_leave_frame(md->env, 0);
	return status;
}

sfsistat
mlfi_body(SMFICTX *ctx, unsigned char *bodyp, size_t len)
{
	sfsistat status;
	struct message_data *md = priv_get(ctx);
	debug1(70, "Processing xxfi_body: %lu", (unsigned long) len);
	env_init(md->env);
	capture_body(md->env, bodyp, len);
	env_push_number(md->env, len);
	/* FIXME: Push bodyp as number to avoid unnecessary stack allocation.
	   This, however, makes it impossible to pass $2 between invocations of
	   mlfi_body
	 */
	env_push_number(md->env, bodyp);
	env_make_frame(md->env);
	status = mlfi_eval(ctx, smtp_state_body);
	env_leave_frame(md->env, 2);
	return status;
}

static int
run_header_command(void *item, void *data)
{
	struct old_header_node *hdr = item;
	SMFICTX *ctx = data;

	debug3(50,
	       "%s %s: %s",
	       header_command_str(hdr->opcode),
	       hdr->name, hdr->value);
	switch (hdr->opcode) {
	case header_add:
		gacopyz_add_header(ctx, hdr->name, hdr->value);
		break;
		
	case header_replace:
		gacopyz_change_header(ctx, 1, hdr->name, hdr->value);
		break;

	case header_delete:
		gacopyz_change_header(ctx, 1, hdr->name, NULL);
		break;
	}
	return 0;
}

	
sfsistat
mlfi_eom(SMFICTX *ctx)
{
        sfsistat status;
	struct message_data *md = priv_get(ctx);

	debug(70, "Processing xxfi_eom");

	env_init(md->env);
	capture_eom(md->env);
	env_make_frame(md->env);
	status = mlfi_eval(ctx, smtp_state_eom);
	env_leave_frame(md->env, 0);
	if ((status == SMFIS_ACCEPT || status == SMFIS_CONTINUE) && md->hdr) {
		debug(50,"executing header commands");
		mu_list_do(md->hdr, run_header_command, ctx);
	}
	
	clear_rcpt_count(md->env);

	return status;
}

sfsistat
mlfi_abort(SMFICTX *ctx)
{
	struct message_data *md = priv_get(ctx);

	debug(70, "Abort");
        mu_list_destroy(&md->hdr);
        md->hdr = NULL;
        md->msgid[0] = 0;
	return SMFIS_CONTINUE;
}		

sfsistat
mlfi_close(SMFICTX *ctx)
{
	debug(70, "Close");
	filter_cleanup(ctx);
	return SMFIS_CONTINUE; 
}

static int
child_start()
{
	signal(SIGPIPE, SIG_IGN);
	signal(SIGALRM, SIG_IGN);
	return 0;
}

struct smfiDesc smfilter =
{
	"MailfromFilter",	
	SMFI_VERSION,	
	SMFIF_ADDHDRS|SMFIF_CHGHDRS,
	NULL,	        /* connection info filter */
	NULL,	        /* SMTP HELO command filter */
	NULL,	        /* envelope sender filter */
	NULL,	        /* envelope recipient filter */
	NULL,	        /* header filter */
	NULL,           /* end of header */
	NULL,	        /* body block filter */
	mlfi_eom,	/* end of message */
	mlfi_abort,	/* message aborted */
	mlfi_close,	/* connection cleanup */
#ifdef GACOPYZ_VERSION_MAJOR
	NULL,   /* unknown command handler */
	NULL,   /* data handler */
	child_start,   /* child start */
	NULL,   /* child finish */
	NULL /* idle callback */
#endif
};

void
milter_enable_state(enum smtp_state state)
{
	switch (state) {
	case smtp_state_connect:
		smfilter.xxfi_connect = mlfi_connect;
		break;
		
	case smtp_state_helo:
		smfilter.xxfi_helo = mlfi_helo;
		break;

	case smtp_state_envfrom:
		smfilter.xxfi_envfrom = mlfi_envfrom;
		break;
		
	case smtp_state_envrcpt:
		smfilter.xxfi_envrcpt = mlfi_envrcpt;
		break;

	case smtp_state_data:
		smfilter.xxfi_data = mlfi_data;
		break;
		
	case smtp_state_header:
		smfilter.xxfi_header = mlfi_header;
		break;

	case smtp_state_eoh:
		smfilter.xxfi_eoh = mlfi_eoh;
		break;
		
	case smtp_state_body:
		smfilter.xxfi_body = mlfi_body;
		break;

	default:
		break;
	}
}

/* Check whether pidfile NAME exists and if so, whether its PID is still
   active. Exit if it is. */
void
check_pidfile(char *name)
{
	unsigned long pid;
	FILE *fp = fopen(name, "r");
	if (!fp) {
		if (errno == ENOENT)
			return;
		mu_error(_("Cannot open pidfile `%s': %s"),
			 name, mu_strerror(errno));
		exit(EX_TEMPFAIL);
	}
	if (fscanf(fp, "%lu", &pid) != 1) {
		mu_error(_("Cannot get pid from pidfile `%s'"), name);
	} else {
		if (kill(pid, 0) == 0) {
			mu_error(_("%s appears to run with pid %lu. If it does not, remove `%s' and retry."),
				 program_invocation_short_name,
				 pid,
				 name);
			exit(EX_USAGE);
		}
	}
	fclose(fp);
	if (unlink(pidfile)) {
		mu_error(_("Cannot unlink pidfile `%s': %s"),
			 name, mu_strerror(errno));
		exit(EX_USAGE);
	}
}

/* Check whether local socket P exists. Act in accordance with the settings
   of --remove command line option. */
static void
check_local_portspec(char *p)
{
	struct stat st;

	if (stat(p, &st)) {
		if (errno == ENOENT)
			return; /* That's OK. The socket must not exist */
		mu_error(_("Cannot stat file `%s': %s"),
			 p, mu_strerror(errno));
		exit(EX_SOFTWARE);
	} else if (!force_remove) {
		mu_error(_("File `%s' already exists. Remove it or use --remove option."), p);
		exit(EX_SOFTWARE);
	}

	if (unlink (p)) {
		mu_error(_("Cannot unlink file `%s': %s"), p, mu_strerror(errno));
		exit(EX_SOFTWARE);
	}
}

void
check_portspec(char *portspec)
{
	static struct spectab {
		char *proto;
		int skip;
		void (*check)(char *);
	} spectab[] = {
		{ "/",      0, check_local_portspec },
		{ "unix:",  1, check_local_portspec }, 
		{ "local:", 1, check_local_portspec },
		{ "inet:",  1, NULL },
		{ "inet6:", 1, NULL },
 	};
	struct spectab *sp;
	
	for (sp = spectab; sp < spectab + sizeof(spectab)/sizeof(spectab[0]);
	     sp++) {
		int len = strlen(sp->proto);
		if (strlen(portspec) > len + 1
		    && strncasecmp(portspec, sp->proto, len) == 0) {
			if (sp->check) 
				sp->check(portspec + (sp->skip ? len : 0));
			return;
		}
	}
	mu_error(_("Unknown port specification: %s"), portspec);
}

static int x_argc;          /* A copy of argc and ... */
static char **x_argv;       /* ... argv */ 
static int restart;         /* Set to 1 if restart is requested */

void
save_cmdline(int argc, char **argv)
{
	int i;

	if (argc == 0) {
		/* Clear saved command line */
		for (i = 0; i < x_argc; i++)
			free(x_argv[i]);
		free(x_argv);
		x_argc = 0;
		x_argv = NULL;
	} else if (argv[0][0] != '/') {
		/* Do not save if argv[0] is not a full file name.
		   An appropriate error message will be issued later,
		   if necessary. */
		return;
	}
	x_argc = argc;
	x_argv = xcalloc (x_argc + 1, sizeof x_argv[0]);
	for (i = 0; i < x_argc; i++)
		x_argv[i] = xstrdup (argv[i]);
	x_argv[i] = NULL;
}


static RETSIGTYPE
sig_stop(int sig)
{
	smfi_stop();
}

static RETSIGTYPE
sig_restart(int sig)
{
	restart = 1;
	smfi_stop();
}

void
mailfromd_daemon()
{
	int rc;

	mu_error(_("mailfromd version %s starting"), PACKAGE_VERSION);
	
	priv_setup();

	if (!foreground)
		check_pidfile(pidfile);

	check_portspec(portspec);
	
	if (smfi_setconn(portspec) == MI_FAILURE) {
		mu_error("smfi_setconn: %s", mu_strerror(errno));
		exit(EX_SOFTWARE);
	}
	
	if (smfi_register(smfilter) == MI_FAILURE) {
		mu_error(_("smfi_register failed"));
		exit(EX_UNAVAILABLE);
	}

	smfi_set_foreground(single_process_option);
	
	signal(SIGTERM, sig_stop);
	signal(SIGQUIT, sig_stop);
	if (x_argc == 0) {
		if (!mtasim_option) {
			if (script_file[0] != '/')
				mu_error(_("Warning: script file is given "
					 "without full file name"));
			else
				mu_error(_("Warning: mailfromd started "
					   "without full file name"));
			mu_error(_("Warning: restart (SIGHUP) will not work"));
		}
		signal(SIGHUP, sig_stop);
	} else
		signal(SIGHUP, sig_restart);
	signal(SIGINT, sig_stop);

 	if (!foreground) {
		if (daemon(0, 0) == -1) {
			mu_error(_("Cannot become a daemon: %s"),
				 mu_strerror(errno));
			exit(EX_OSERR);
		}
		umask(0117);
		mu_daemon_create_pidfile(pidfile);
		rc = smfi_main();
	} else {
		umask(0117);
		rc = smfi_main();
	}

	if (rc) 
		mu_error(_("Exit code = %d, last error status: %s"),
			 rc, strerror (errno));
	if (restart) {
		char *s;
		int i;
		
		mu_error(_("mailfromd restarting"));
		mu_daemon_remove_pidfile();
		for (i = getmaxfd(); i > 2; i--)
			close(i);
		execv(x_argv[0], x_argv);
		log_setup(0);
		mu_error(_("Cannot restart: %s"), mu_strerror(errno));
		if (mu_argcv_string(x_argc, x_argv, &s) == 0)
			mu_error(_("Command line was: %s"), s);
	} else 
		mu_error(_("mailfromd terminating"));
	exit(rc);
}

Return to:

Send suggestions and report system problems to the System administrator.