summaryrefslogtreecommitdiffabout
path: root/src/mtasim.c
blob: 2a12a436725acada33296423f33ff6ef284e4e2e (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
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
/*
   This file is part of Mailfromd.
   Copyright (C) 2003, 2004, 2007 The Anubis Team.

   Mailfromd 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 of the License, or
   (at your option) any later version.

   Mailfromd 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 Mailfromd.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <unistd.h>
#ifdef HAVE_GETOPT_H
# include <getopt.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
#ifdef HAVE_READLINE_READLINE_H
# include <readline/readline.h>
# include <readline/history.h>
#endif

#include <pwd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <mailutils/mailutils.h>
#if MAILUTILS_VERSION_NUMBER > 1290
# include <gettext.h>
# define _(string) gettext(string)
# define N_(string) string
#endif

#include <gacopyz.h>
#define obstack_chunk_alloc malloc
#define obstack_chunk_free free
#include <obstack.h>
#include <argp.h>
#include <xalloc.h>
#include <save-cwd.h>

#if defined(USE_GNUTLS) && defined(HAVE_GNUTLS_GNUTLS_H)
# include <gnutls/gnutls.h>
# define HAVE_TLS
#endif /* USE_GNUTLS and HAVE_GNUTLS_GNUTLS_H */

FILE *trace = NULL;		/* diagnostic output */
int port = 0;			/* Port number (for smtp mode) */

int verbose;
#ifdef HAVE_TLS
char *tls_cert;			/* TLS sertificate */
char *tls_key;			/* TLS key */
char *tls_cafile;

#define DH_BITS 768
#define enable_tls() \
 (tls_cafile != NULL || (tls_cert != NULL && tls_key != NULL))
void tls_init (void);

gnutls_dh_params dh_params;
static gnutls_certificate_server_credentials x509_cred;
#endif /* HAVE_TLS */

int interactive;
char *prompt = "(mtasim) ";

int mta_daemon (void);
int mta_stdio (void);
void error (const char *, ...);
void smtp_reply (int, char *, ...);
void reset_capa (char *);
void shell_help (void);

void shell (int argc, char **argv);
int define_macro (char *arg);

#define R_CONT     0x8000
#define R_CODEMASK 0xfff

/* Milter-related options */
char *milter_port;
size_t max_body_chunk = 65535;
int milter_version_option = 0;
struct timeval milter_timeouts[GACOPYZ_TO_COUNT] = {
  { GACOPYZ_WRITE_TIMEOUT, 0 },
  { GACOPYZ_READ_TIMEOUT, 0 },
  { GACOPYZ_EOM_TIMEOUT, 0 },
  { GACOPYZ_CONNECT_TIMEOUT, 0 }
};

  

gacopyz_srv_t gsrv;

void
update_nrcpts (char *name, unsigned n)
{
  char buf[128];
  snprintf (buf, sizeof buf, "%u", n);
  gacopyz_srv_define_macro (gsrv, name, buf);
}


static mu_list_t defnlist;

int
defer_define_macro (char *arg)
{
  char *p;
  p = strchr (arg, '=');
  if (!p)
    return 1;
  *p++ = 0;
  if (!defnlist)
    mu_list_create (&defnlist);
  mu_list_append (defnlist, arg);
  return 0;
}

static int
do_define (void *item, void *data)
{
  char *name = item;
  char *value = name + strlen (name) + 1;
  gacopyz_srv_t srv = data;
  gacopyz_srv_define_macro (srv, name, value);
  return 0;
}

void
flush_deferred_defns (gacopyz_srv_t srv)
{
  if (srv)
    mu_list_do (defnlist, do_define, srv);
  mu_list_destroy (&defnlist);
}


/* Expect stuff */
static char expected_code[4];

void
free_expected_code ()
{
  expected_code[0] = 0;
}

int
set_expected_code (const char *str)
{
  size_t len = strlen (str);
  if (len == 0 || !strchr ("12345", str[0]))
    return 1;

  if (len > 1)
    {
      if (!isdigit (str[1])
	  || (len > 2 && !isdigit (str[2])))
	return 1;
    }

  if (len > 3)
    len = 3;
  memcpy (expected_code, str, len);
  expected_code[len] = 0;
  return 0;
}

void
check_expected_code (char *str)
{
  int i;
  
  for (i = 0; i < 3 && expected_code[i]; i++)
    if (str[i] != expected_code[i])
      {
	/* fill in the expected code */
	for (i = strlen(expected_code); i < 3; i++)
	  expected_code[i] = '.';
	mu_error (_("Expected %s, but got %3.3s"), expected_code, str);
	
	if (gsrv)
	  {
	    gacopyz_srv_abort (gsrv);
	    gacopyz_srv_quit (gsrv);
	    gacopyz_srv_close (gsrv);
	    gacopyz_srv_destroy (&gsrv);
	  }
	exit (1);
      }
  expected_code[0] = 0;
}


const char *argp_program_version = "mtasim (" PACKAGE_STRING ")";
const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">";
static char doc[] = N_("mtasim -- MTA simulator for mailfromd");


enum {
  OPTION_STDIO = 128,
  OPTION_DAEMON,
  OPTION_TLS_CERT,
  OPTION_TLS_CA,
  OPTION_TLS_KEY,
  OPTION_TRACE_FILE,
  OPTION_BODY_CHUNK,
  OPTION_MILTER_VERSION,
  OPTION_NO_INTERACTIVE,
  OPTION_PROMPT,
  OPTION_STATEDIR
};

#ifndef WITH_READLINE
# define OPT_INTERACTIVE OPTION_HIDDEN
#else
# define OPT_INTERACTIVE 0
#endif

static struct argp_option options[] = {
#define GRP 1
  { NULL, 0, NULL, 0,
    N_("Mode selection"), GRP },
  { NULL, 'b', N_("MODE"), 0,
    N_("Set MTA mode (-bd or -bs)"), GRP+1 },
  { "stdio", OPTION_STDIO, NULL, 0,
    N_("Use the SMTP protocol on standard input and output (same as -bs)"),
    GRP+1 },
  { "daemon", OPTION_DAEMON, NULL, 0,
    N_("Run as daemon (same as -bd)"),
    GRP+1 },
#undef GRP

#define GRP 10
  { NULL, 0, NULL, 0,
    N_("Operation modifiers"), GRP },
  { "define", 'D', N_("MACRO=VALUE"), 0,
    N_("Define Sendmail macro"),
    GRP+1 },
  { "port", 'X', N_("PORT"), 0,
    N_("Communicate with Milter PORT"),
    GRP+1 },
  { "statedir", OPTION_STATEDIR, NULL, 0,
    N_("Pass temporary directory to mailfromd as its state dir (with -Xauto)"),
    GRP+1 },
  { "body-chunk", OPTION_BODY_CHUNK, N_("NUMBER"), 0,
    N_("Set the body chunk for xxfi_body calls"),
    GRP+1 },
  { "milter-version", OPTION_MILTER_VERSION, N_("NUMBER"), 0,
    N_("Force using the given Milter protocol version number"), GRP+1 },
#undef GRP

#define GRP 20
  { "no-interactive", OPTION_NO_INTERACTIVE, NULL, OPT_INTERACTIVE,
    N_("Not-interactive mode (disable readline)"), GRP+1 },
  { "prompt", OPTION_PROMPT, N_("STRING"), OPT_INTERACTIVE,
    N_("Set readline prompt"), GRP+1 },
#undef GRP
  
#define GRP 30
  { NULL, 0, NULL, 0,
    N_("Debugging and tracing"), GRP },
  { "append", 'a', NULL, 0,
    N_("Append to the trace file"), GRP+1 },
  { "trace-file", OPTION_TRACE_FILE, N_("FILE"), 0,
    N_("Set name of the trace file"), GRP+1 },
  { "verbose", 'v', NULL, 0,
    N_("Increase verbosity level"),
    GRP+1 },
#undef GRP
  
#define GRP 40  
#ifdef HAVE_TLS
  { NULL, 0, NULL, 0,
    N_("TLS options"), GRP },
  { "tls-cert", OPTION_TLS_CERT, N_("FILE"), 0,
    N_("Set name of the TLS certificate file"),
    GRP+1 },
  { "tls-ca", OPTION_TLS_CA, N_("FILE"), 0,
    N_("Set name of the TLS CA file"),
    GRP+1 },
  { "tls-key", OPTION_TLS_KEY, N_("FILE"), 0,
    N_("Set name of the TLS key file"),
    GRP+1 },
#endif
#undef GRP
  
  { NULL }
};

int (*mta_mode) (void) = mta_stdio;
char *trace_name = NULL;
int append;
int statedir_option;

static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
  char *p;
  
  switch (key)
    {
    case 'a':
      append = 1;
      break;

    case 'b':
      switch (arg[0])
	{
	case 'd':
	  mta_mode = mta_daemon;
	  break;
	
	case 's':
	  mta_mode = mta_stdio;
	  break;
	  
	default:
	  mu_error (_("unsupported mode"));
	  exit (1);
	}
      break;

    case OPTION_STDIO:
      mta_mode = mta_stdio;
      break;

    case OPTION_DAEMON:
      mta_mode = mta_daemon;
      break;
      
#ifdef HAVE_TLS
    case OPTION_TLS_CERT:
      tls_cert = arg;
      break;

    case OPTION_TLS_CA:
      tls_cafile = arg;
      break;

    case OPTION_TLS_KEY:
      tls_key = arg;
      break;
#endif

    case 'D':
      if (defer_define_macro (arg))
	mu_error (_("wrong assignment format: %s"), arg);
      break;

    case OPTION_TRACE_FILE:
      trace_name = arg;
      break;

    case 'X':
      milter_port = arg;
      break;

    case 'v':
      verbose++;
      break;

    case OPTION_BODY_CHUNK:
      max_body_chunk = strtoul (arg, &p, 0);
      if (*p)
	{
	  mu_error (_("invalid number: %s"), arg);
	  exit (1);
	}
      break;

    case OPTION_MILTER_VERSION:
      milter_version_option = strtoul (arg, &p, 0);
      if (*p)
	{
	  mu_error (_("invalid number: %s"), arg);
	  exit (1);
	}
      break;

#ifdef WITH_READLINE
    case OPTION_NO_INTERACTIVE:
      interactive = 0;
      break;

    case OPTION_PROMPT:
      prompt = arg;
      break;
#endif

    case OPTION_STATEDIR:
      statedir_option = 1;
      break;
      
    default:
      return ARGP_ERR_UNKNOWN;
    }
  return 0;
}
      
static struct argp argp = {
  options,
  parse_opt,
  NULL,
  doc,
  NULL,
  NULL,
  NULL
};
    
void
xalloc_die ()
{
  mu_error (_("not enough memory"));
  abort ();
}

static int
portspec_p (const char *str)
{
  size_t len = strlen (str);
  static char *proto[] = { "/", "unix:", "local:", "inet:",  "inet6:", NULL };
  char **p;

  for (p = proto; *p; p++)
    {
      size_t n = strlen (*p);
      if (len > n && memcmp (str, *p, n) == 0)
	return 1;
    }
  return 0;
}


pid_t child_pid;
static char *tmpdir;

static int got_sigchld;

static RETSIGTYPE
sig_child (int sig)
{
  int status;
  
  got_sigchld = 1;
  waitpid((pid_t)-1, &status, 0);
}

static int rmdir_r (const char *name);

static int
recursive_rmdir (const char *name)
{
  int rc;
  DIR *dir;
  struct dirent *ent;

  if (chdir (name))
    {
      mu_error (_("cannot change to directory %s: %s"),
		name, mu_strerror (errno));
      return 1;
    }
  
  dir = opendir (".");
  if (!dir)
    {
      mu_error (_("cannot open directory %s: %s"), name, mu_strerror (errno));
      return 1;
    }

  for (rc = 0; rc == 0 && (ent = readdir (dir));)
    {
      struct stat st;
      
      if (strcmp (ent->d_name, ".") == 0
	  || strcmp (ent->d_name, "..") == 0)
	continue;

      if (stat (ent->d_name, &st) && errno != ENOENT)
	{
	  mu_error (_("cannot stat file `%s': %s"),
		    name, mu_strerror (errno));
	  rc = 1;
	}
      else if (S_ISDIR (st.st_mode))
	rc = rmdir_r (ent->d_name);
      else if ((rc = unlink (ent->d_name)) != 0 && errno != ENOENT)
	mu_error (_("cannot unlink %s: %s"), ent->d_name, mu_strerror (errno));
    }
  closedir (dir);
  return rc;
}

static int
rmdir_r (const char *name)
{
  int rc;
  struct saved_cwd cwd;

  if (save_cwd (&cwd))
    {
      mu_error (_("cannot save current directory: %s"), mu_strerror (errno));
      return 1;
    }
  rc = recursive_rmdir (name);
  if (restore_cwd (&cwd))
    {
      mu_error (_("cannot restore current directory: %s"),
		mu_strerror (errno));
      rc = 1;
    }

  if (rc == 0 && rmdir (name))
    {
      mu_error (_("cannot remove directory %s: %s"),
		name, mu_strerror (errno));
      return 1;
    }

  return rc;
}

void
stop_mailfromd (void)
{
  if (child_pid > 0)
    {
      kill (child_pid, SIGTERM);
    }
  
  rmdir_r (tmpdir);
}

void
start_mailfromd (int argc, char **argv)
{
  tmpdir = xstrdup ("/tmp/mtasim-XXXXXX");
  
  if (!mkdtemp (tmpdir))
    {
      mu_error (_("cannot create temprorary directory (%s): %s"),
		tmpdir, mu_strerror (errno));
      exit (1);
    }
  atexit (stop_mailfromd);
  
  milter_port = xstrdup ("unix:/tmp/mtasim-XXXXXX/socket");
  memcpy (milter_port + 5, tmpdir, strlen (tmpdir));

  signal (SIGCHLD, sig_child);
  
  child_pid = fork ();

  if (child_pid == -1)
    {
      mu_error (_("cannot fork: %s"), mu_strerror (errno));
      exit (1);
    }

  if (child_pid == 0)
    {
      int xargc = argc + 5 + (statedir_option ? 2 : 0);
      char **xargv = xmalloc ((xargc + 1) * sizeof xargv[0]);
      int i;

      xargv[0] = "mailfromd";
      for (i = 1; i <= argc; i++)
	xargv[i] = argv[i-1];
      xargv[i++] = "--mtasim";
      xargv[i++] = "--remove";
      xargv[i++] = "--port";
      xargv[i++] = milter_port;
      if (statedir_option)
	{
	  xargv[i++] = "--state-directory";
	  xargv[i++] = tmpdir;
	}
      xargv[i] = 0;

      if (verbose)
	{
	  fprintf (stderr, "executing ");
	  for (i = 0; i < xargc; i++)
	    fprintf (stderr, "%s ", xargv[i]);
	  fprintf (stderr, "\n");
	}
      
      execvp (xargv[0], xargv);

      mu_error (_("cannot execute mailfromd: %s"), mu_strerror (errno));
      exit (127);
    }

  while (access (milter_port + 5, F_OK))
    {
      struct timeval tv;
      
      if (got_sigchld)
	{
	  mu_error (_("child process exited unexpectedly"));
	  exit (1);
	}

      tv.tv_sec = 0;
      tv.tv_usec = 5;
      select (0, NULL, NULL, NULL, &tv);
    }
}


#ifdef WITH_READLINE
static char **mta_command_completion (char *cmd, int start, int end);
static char *get_history_file_name (void);
#endif

extern void mailfromd_version(const char *progname, FILE *stream,
			      struct argp_state *state);

static void
version (FILE *stream, struct argp_state *state)
{
  mailfromd_version("mtasim", stream, state);
}

int
stderr_error_printer (const char *fmt, va_list ap)
{
  fprintf (stderr, "%s: ", program_invocation_short_name);
  vfprintf (stderr, fmt, ap);
  fputc ('\n', stderr);
  return 0;
}

int
main (int argc, char **argv)
{
  int status, index;

#ifdef ENABLE_NLS
  mu_init_nls();
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
#endif

  interactive = isatty(0);
  
  if (!program_invocation_short_name)
    program_invocation_short_name = argv[0];
  mu_error_set_print (stderr_error_printer);
  argp_program_version_hook = version;
  if (argp_parse (&argp, argc, argv, 0, &index, NULL))
    exit (1);
  
#ifdef WITH_READLINE
  if (interactive)
    {
      rl_readline_name = program_invocation_short_name;
      rl_attempted_completion_function = (CPPFunction*) mta_command_completion;
      read_history (get_history_file_name ());
    }
#endif

  if (trace_name)
    {
      char *mode = append ? "a" : "w";
      trace = fopen (trace_name, mode);
      if (!trace)
	{
	  mu_error (_("cannot open trace output: %s"), trace_name);
	  return 1;
	}
    }

  argc -= index;
  argv += index;

  if (!mta_mode)
    {
      mu_error (_("use either --stdio or --daemon"));
      exit (1);
    }

  if (milter_port)
    {
      int rc;
      int mask = SMI_DEFAULT_LOG_MASK;
      
      if (verbose)
	mask |= SMI_LOG_MASK (SMI_LOG_DEBUG);

      gacopyz_set_logger (gacopyz_stderr_log_printer);
      
      if (strcmp (milter_port, "auto") == 0)
	start_mailfromd (argc, argv);

      if (portspec_p (milter_port))
	rc = gacopyz_srv_create (&gsrv, "Test", milter_port, mask);
      else
	rc = gacopyz_srv_create_X (&gsrv, milter_port, mask);

      if (rc != MI_SUCCESS)
	{
	  mu_error (_("cannot create gacopyz server"));
	  exit (1);
	}

      if (milter_version_option)
	gacopyz_srv_set_version (gsrv, milter_version_option);

      gacopyz_srv_set_all_timeouts (gsrv, milter_timeouts);
      
      if (gacopyz_srv_connect (gsrv) != MI_SUCCESS)
	{
	  mu_error (_("cannot connect to the milter using %s"), milter_port);
	  exit (1);
	}
      gacopyz_srv_negotiate (gsrv);
    }
  
  flush_deferred_defns (gsrv);

#ifdef HAVE_TLS
  tls_init ();
#endif
  status = mta_mode ();

  if (trace)
    fclose (trace);

#ifdef WITH_READLINE
  if (interactive)
    write_history (get_history_file_name ());
#endif
  
  return status;
}

static void *in, *out;

static const char *
_def_strerror (int rc)
{
  return rc == -1 ? "end of file reached" : strerror (rc);
}

static int
_def_write (void *sd, char *data, size_t size, size_t * nbytes)
{
  int n = write ((int) sd, data, size);
  if (n != size)
    return errno;
  if (nbytes)
    *nbytes = n;
  return 0;
}

static int
_def_read (void *sd, char *data, size_t size, size_t * nbytes)
{
  int n = read ((int) sd, data, size);
  if (n && n != size)
    return errno;
  if (nbytes)
    *nbytes = n;
  return 0;
}

static int
_def_close (void *sd)
{
  return close ((int) sd);
}

int (*_mta_read) (void *, char *, size_t, size_t *) = _def_read;
int (*_mta_write) (void *, char *, size_t, size_t *) = _def_write;
int (*_mta_close) (void *) = _def_close;
const char *(*_mta_strerror) (int) = _def_strerror;

#ifdef HAVE_TLS

static void
_tls_cleanup_x509 (void)
{
  if (x509_cred)
    gnutls_certificate_free_credentials (x509_cred);
}

static void
generate_dh_params (void)
{
  gnutls_dh_params_init (&dh_params);
  gnutls_dh_params_generate2 (dh_params, DH_BITS);
}

void
tls_init (void)
{
  if (!enable_tls ())
    return;

  gnutls_global_init ();
  atexit (gnutls_global_deinit);
  gnutls_certificate_allocate_credentials (&x509_cred);
  atexit (_tls_cleanup_x509);
  if (tls_cafile)
    {
      int rc = gnutls_certificate_set_x509_trust_file (x509_cred,
						       tls_cafile,
						       GNUTLS_X509_FMT_PEM);
      if (rc < 0)
	{
	  gnutls_perror (rc);
	  return;
	}
    }
  if (tls_cert && tls_key)
    gnutls_certificate_set_x509_key_file (x509_cred,
					  tls_cert, tls_key,
					  GNUTLS_X509_FMT_PEM);

  generate_dh_params ();
  gnutls_certificate_set_dh_params (x509_cred, dh_params);
}

static ssize_t
_tls_fd_pull (gnutls_transport_ptr fd, void *buf, size_t size)
{
  int rc;
  do
    {
      rc = read ((int) fd, buf, size);
    }
  while (rc == -1 && errno == EAGAIN);
  return rc;
}

static ssize_t
_tls_fd_push (gnutls_transport_ptr fd, const void *buf, size_t size)
{
  int rc;
  do
    {
      rc = write ((int) fd, buf, size);
    }
  while (rc == -1 && errno == EAGAIN);
  return rc;
}

static const char *
_tls_strerror (int rc)
{
  return gnutls_strerror (rc);
}

static int
_tls_write (void *sd, char *data, size_t size, size_t * nbytes)
{
  int rc;

  do
    rc = gnutls_record_send (sd, data, size);
  while (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN);
  if (rc >= 0)
    {
      if (nbytes)
	*nbytes = rc;
      return 0;
    }
  return rc;
}

static int
_tls_read (void *sd, char *data, size_t size, size_t * nbytes)
{
  int rc = gnutls_record_recv (sd, data, size);
  if (rc >= 0)
    {
      if (nbytes)
	*nbytes = rc;
      return 0;
    }
  return rc;
}

static int
_tls_close (void *sd)
{
  if (sd)
    {
      gnutls_bye (sd, GNUTLS_SHUT_RDWR);
      gnutls_deinit (sd);
    }
  return 0;
}

static gnutls_session
tls_session_init (void)
{
  gnutls_session session = 0;
  int rc;

  gnutls_init (&session, GNUTLS_SERVER);
  gnutls_set_default_priority (session);
  gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred);
  gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUEST);
  gnutls_dh_set_prime_bits (session, DH_BITS);

  gnutls_transport_set_pull_function (session, _tls_fd_pull);
  gnutls_transport_set_push_function (session, _tls_fd_push);

  gnutls_transport_set_ptr2 (session,
			     (gnutls_transport_ptr) in,
			     (gnutls_transport_ptr) out);
  rc = gnutls_handshake (session);
  if (rc < 0)
    {
      gnutls_deinit (session);
      gnutls_perror (rc);
      return 0;
    }

  return (gnutls_session) session;
}

void
smtp_starttls (void)
{
  gnutls_session session;

  smtp_reply (220, "Ready to start TLS");

  session = tls_session_init ();
  if (session)
    {
      in = out = session;
      _mta_read = _tls_read;
      _mta_write = _tls_write;
      _mta_close = _tls_close;
      _mta_strerror = _tls_strerror;
      reset_capa ("STARTTLS");
    }
  else
    smtp_reply (530, "TLS negotiation failed");
}

#endif /* HAVE_TLS */

void
smtp_send_string (char *str, size_t len)
{
  int rc;
  if (!len)
    len = strlen (str);
  if (trace)
    fprintf (trace, "%s\n", str);
  rc = _mta_write (out, str, len, NULL);
  if (rc == 0 && str[len-1] != '\n')
    rc = _mta_write (out, "\r\n", 2, NULL);
  if (rc)
    {
      mu_error (_("Write failed: %s"), _mta_strerror (rc));
      abort ();
    }
  check_expected_code (str);
}

void
smtp_reply (int code, char *fmt, ...)
{
  va_list ap;
  int cont = code & R_CONT ? '-' : ' ';
  static char obuf[512];
  int n, rc;

  va_start (ap, fmt);
  n = snprintf (obuf, sizeof obuf, "%d%c", code & R_CODEMASK, cont);
  n += vsnprintf (obuf + n, sizeof obuf - n, fmt, ap);
  va_end (ap);
  if (trace)
    fprintf (trace, "%s\n", obuf);
  n += snprintf (obuf + n, sizeof obuf - n, "\r\n");
  rc = _mta_write (out, obuf, n, NULL);
  if (rc)
    {
      mu_error (_("Write failed: %s"), _mta_strerror (rc));
      abort ();
    }
  check_expected_code (obuf);
}

int
get_input_line (char *buf, size_t bufsize)
{
  int i, rc;

#ifdef WITH_READLINE
  if (interactive)
    {
      char *p = readline (prompt);
      if (!p)
	return -1;
      strncpy (buf, p, bufsize);
      buf[bufsize - 1] = 0;
      free (p);
      add_history (buf);
      return strlen (buf);
    }
#endif
  
  for (i = 0; i < bufsize - 1; i++)
    {
      size_t n;
      rc = _mta_read (in, buf + i, 1, &n);
      if (rc)
	{
	  mu_error (_("Read failed: %s"), _mta_strerror (rc));
	  exit (1);
	}
      if (n == 0)
	break;
      if (buf[i] == '\n')
	{
	  if (buf[i-1] == '\r')
	    buf[i-1] = '\n';
          else
            i++;
	  break;
	}
    }
  buf[i] = 0;
  return i;
}
 
#define STATE_INIT    0
#define STATE_EHLO    1
#define STATE_MAIL    2
#define STATE_RCPT    3
#define STATE_HEADERS 4
#define STATE_DATA    5
#define STATE_QUIT    6
#define STATE_DOT     7

#define KW_EHLO      0
#define KW_HELO      1
#define KW_MAIL      2
#define KW_RCPT      3
#define KW_DATA      4
#define KW_HELP      5
#define KW_QUIT      6
#define KW_STARTTLS  7
#define KW_RSET      8

struct keyword
{
  char *name;
  int code;
};

static struct keyword kw[] =
  {
    { "EHLO", KW_EHLO },
    { "HELO", KW_HELO },
    { "MAIL", KW_MAIL },
    { "RCPT", KW_RCPT },
    { "DATA", KW_DATA },
    { "HELP", KW_HELP },
    { "QUIT", KW_QUIT },
    { "HELP", KW_HELP },
#ifdef HAVE_TLS
    { "STARTTLS", KW_STARTTLS },
#endif
    { "RSET", KW_RSET },
    { NULL },
  };

int
smtp_kw (const char *name)
{
  int i;

  for (i = 0; kw[i].name != NULL; i++)
    if (strcasecmp (name, kw[i].name) == 0)
      return kw[i].code;
  return -1;
}

#ifdef WITH_READLINE

#define HISTFILE_SUFFIX "_history"

static char *
get_history_file_name ()
{
  static char *filename = NULL;

  if (!filename)
    {
      size_t size;
      char *home = getenv ("HOME");
      if (!home)
	{
	  struct passwd *pw = getpwuid (getuid ());
	  if (!pw)
	    return NULL;
	  home = pw->pw_dir;
	}
      size = strlen (home) + 2 + strlen (rl_readline_name)
      	     + sizeof HISTFILE_SUFFIX;
      filename = xmalloc (size);
      strcpy (filename, home);
      strcat (filename, "/.");
      strcat (filename, rl_readline_name);
      strcat (filename, HISTFILE_SUFFIX);
  }
  return filename;
}

static char *
mta_command_generator (const char *text, int state)
{
  static int i, len;
  const char *name;
  
  if (!state)
    {
      i = 0;
      len = strlen (text);
    }

  while ((name = kw[i].name))
    {
      i++;
      if (strncasecmp (name, text, len) == 0)
	return strdup (name);
    }

  return NULL;
}

char **
mta_command_completion (char *cmd, int start, int end)
{
  if (start == 0)
    return rl_completion_matches (cmd, mta_command_generator);
  return NULL;
}
#endif

char *
skipws (char *str)
{
  while (*str && isspace (*(u_char *) str))
    str++;
  return str;
}

char *
skipword (char *str)
{
  while (*str && !isspace (*(u_char *) str))
    str++;
  return str;
}

int
argcv_split (char *buf, int *pargc, char ***pargv)
{
  char *t;
  int i, argc = 0;
  char **argv;

  t = buf;
  do
    {
      argc++;
      t = skipws (t);
    }
  while (*t && (t = skipword (t)));

  argv = calloc (argc, sizeof (*argv));
  for (i = 0, t = strtok (buf, " \t"); t; i++, t = strtok (NULL, " \t"))
    argv[i] = strdup (t);
  argv[i] = NULL;
  *pargc = argc - 1;
  *pargv = argv;
  return 0;
}

int
argcv_free (int argc, char **argv)
{
  while (--argc >= 0)
    if (argv[argc])
      free (argv[argc]);
  free (argv);
  return 1;
}

char *mta_capa[] = {
#ifdef HAVE_TLS
  "STARTTLS",
#endif
  NULL
};

void
reset_capa (char *name)
{
  int i;
  for (i = 0; mta_capa[i]; i++)
    if (strcmp (mta_capa[i], name) == 0)
      {
	mta_capa[i] = NULL;
	break;
      }
}

static int tempfail;
static int discard;
static char *nullmailer;
unsigned nrcpt = 0;
unsigned nbadrcpts = 0;

void
smtp_ehlo (int extended, char *domain)
{
  int i;

  if (gsrv)
    {
      gacopyz_srv_define_macro (gsrv, "s", domain);
      switch (gacopyz_srv_helo (gsrv, domain))
	{
	case SMFIR_REPLYCODE:
	  {
	    char *msg;
	    size_t size;
	    gacopyz_srv_reply (gsrv, &msg, &size);
	    nullmailer = strdup (msg);
	    break;
	  }

	case SMFIR_REJECT:
	  nullmailer = strdup ("Command rejected");
	  break;

	case SMFIR_TEMPFAIL:
	  tempfail = 1;
	  break;
	  
	case SMFIR_DISCARD:
	case SMFIR_SHUTDOWN:
	  break;
	}
    }
  
  if (!extended)
    {
      smtp_reply (250, "pleased to meet you");
      return;
    }

  smtp_reply (R_CONT | 250, "pleased to meet you");
  for (i = 0; mta_capa[i]; i++)
    smtp_reply (R_CONT | 250, "%s", mta_capa[i]);
  smtp_reply (250, "HELP");
}

void
smtp_help (void)
{
  int i;
  
  smtp_reply (250|R_CONT, "mtasim (%s); supported SMTP commands:", PACKAGE_STRING);
  for (i = 0; kw[i].name; i++)
    smtp_reply (250|R_CONT, " %s", kw[i].name);
  if (milter_port)
    {
      smtp_reply (250|R_CONT, "Supported administrative commands:");
      shell_help ();
    }
  smtp_reply (250, "End of help output");
}

#define MSG_TEMPFAIL "451 4.3.2 Please try again later"
#define MSG_REJECT "550 5.7.1 Command rejected"
#define MSG_SHUTDOWN "421 4.7.0 bitbucket closing connection"

int
parse_email_addr(char *arg, char **psender, char **addr, char **host)
{
  size_t len;
  char *p = arg, *q;
  if (*p == '<')
    {
      len = strlen (p);
      if (p[len-1] != '>')
	return 1;
      p++;
      *psender = malloc (len - 1);
      if (*psender)
	{
	  memcpy (*psender, p, len - 2);
	  (*psender)[len - 2] = 0;
	}
    }
  else
    *psender = strdup (arg);
  if (!*psender)
    return 1;
  p = *psender;
  q = strchr (p, '@');
  if (q)
    len = q - p;
  else
    len = strlen (p);
  *addr = malloc (len + 1);
  if (!*addr)
    {
      free (*psender);
      return 1;
    }
  memcpy (*addr, p, len);
  (*addr)[len] = 0;
  if (q)
    q++;
  else
    q = "localhost";
  *host = strdup (q);
  if (!*host)
    {
      free (*psender);
      free (*addr);
      return 1;
    }
  return 0;
}

static int
process_gacopyz_reply (char *sname, char *arg, int rc, int *state)
{
  switch (rc)
    {
    case SMFIR_REPLYCODE:
      {
	char *msg;
	size_t size;
	gacopyz_srv_reply (gsrv, &msg, &size);
			
	if (verbose)
	  fprintf (stderr,
		   "Gacopyz: %s=%s, reply=%s",
		   sname, arg, msg);
	smtp_send_string (msg, 0);
	return 1;
      }

    case SMFIR_REJECT:
      if (verbose)
	fprintf (stderr, 
		 "Gacopyz: %s=%s, reply=%s",
		 sname, arg, MSG_REJECT);
      smtp_send_string (MSG_REJECT, 0);
      return 1;

    case SMFIR_DISCARD:
      if (verbose)
	fprintf (stderr, 
		 "Gacopyz: %s=%s, discard",
		 sname, arg);
      discard = 1;
      return 1;

    case SMFIR_TEMPFAIL:
      if (verbose)
	fprintf (stderr, 
		 "Gacopyz: %s=%s, reply=%s",
		 sname, arg, MSG_TEMPFAIL);
      smtp_send_string (MSG_TEMPFAIL, 0);
      return 1;

    case SMFIR_SHUTDOWN:
      if (verbose)
	fprintf (stderr, 
		 "Gacopyz: %s=%s, reply=%s",
		 sname, arg, MSG_SHUTDOWN);
      smtp_send_string (MSG_SHUTDOWN, 0);
      *state = STATE_QUIT;
      return 1;
    }
  return 0;
}

static int
process_data_reply (char *sname, char *arg, int rc, int *state, char **reply)
{
  switch (rc)
    {
    case SMFIR_REPLYCODE:
      {
	char *msg;
	size_t size;
	gacopyz_srv_reply (gsrv, &msg, &size);
			
	if (verbose)
	  fprintf (stderr,
		   "Gacopyz: %s=%s, reply=%s",
		   sname, arg, msg);
	*reply = strdup (msg);
	return 1;
      }

    case SMFIR_REJECT:
      if (verbose)
	fprintf (stderr, 
		 "Gacopyz: %s=%s, reply=%s",
		 sname, arg, MSG_REJECT);
      *reply = strdup (MSG_REJECT);
      return 1;

    case SMFIR_DISCARD:
      if (verbose)
	fprintf (stderr, 
		 "Gacopyz: %s=%s, discard",
		 sname, arg);
      discard = 1;
      return 1;

    case SMFIR_TEMPFAIL:
      if (verbose)
	fprintf (stderr, 
		 "Gacopyz: %s=%s, reply=%s",
		 sname, arg, MSG_TEMPFAIL);
      *reply = strdup (MSG_TEMPFAIL);
      return 1;

    case SMFIR_SHUTDOWN:
      if (verbose)
	fprintf (stderr, 
		 "Gacopyz: %s=%s, reply=%s",
		 sname, arg, MSG_SHUTDOWN);
      smtp_send_string (MSG_SHUTDOWN, 0);
      *state = STATE_QUIT;
      return 1;
    }
  return 0;
}

/* Check if (*PARGV)[1] begins with the string PFX, followed by ':'.
   Return 0 if so, 1 otherwise.
   If any characters follow the semicolon, reformat *PARGV so that
   [1] contains only PFX:, [2] contains the characters in question,
   and the rest of entries after [2] is properly reindexed.
*/
int
check_address_command(const char *pfx, int *pargc, char ***pargv)
{
  int argc = *pargc;
  char **argv = *pargv;
  int pfxlen = strlen (pfx);
  int arglen = strlen (argv[1]);
  
  if (argc >= 2 && arglen > pfxlen
      && strncasecmp (argv[1], pfx, pfxlen) == 0
      && argv[1][pfxlen] == ':') {

    if (arglen > pfxlen + 1)
      {
	argc++;
	argv = xrealloc (argv, (argc + 1) * sizeof (argv[0]));
	memmove (&argv[2], &argv[1], (argc - 1) * sizeof argv[1]);
	argv[2] = xstrdup (argv[1] + pfxlen + 1);
	argv[1][pfxlen + 1] = 0;

	*pargc = argc;
	*pargv = argv;
      }
    
    return 0;
  }
  return 1;
}

static void
smtp_rcpt (int *pargc, char ***pargv, int *state)
{
  nrcpt++;
  if (check_address_command("to", pargc, pargv) == 0)
    {
      char **argv = *pargv;
      int rc;
      char *sender;
      char *addr;
      char *host;
	      
      if (parse_email_addr (argv[2], &sender, &addr, &host))
	{
	  smtp_reply (553, "5.0.0 recipient address syntactically incorrect");
	  nbadrcpts++;
	  return;
	}
	      
      if (gsrv)
	{
	  update_nrcpts ("nrcpts", nrcpt);
	  update_nrcpts ("nbadrcpts", nbadrcpts);
	  gacopyz_srv_define_macro (gsrv, "rcpt_host", host);
	  gacopyz_srv_define_macro (gsrv, "rcpt_addr", addr);
	  
	  rc = gacopyz_srv_envrcpt (gsrv, argv + 2);
	  free (sender);
	  free (addr);
	  free (host);
	  if (process_gacopyz_reply ("to", argv[2], rc, state))
	    return;
	}
      else
	{
	  free (sender);
	  free (addr);
	  free (host);
	}
      
      smtp_reply (250, "Recipient OK");
      *state = STATE_RCPT;
    }
  else
    smtp_reply (501, "Syntax error");
}

int
process_header (struct obstack *stk, size_t header_size,
		int *state, char **reply)
{
  int status = 0;
  char *hn, *hv;
  
  obstack_1grow (stk, 0);
  hn = obstack_finish (stk);
  hv = strchr (hn, ':');
  if (hv)
    {
      int rc, len;
      
      *hv++ = 0;
      while (*hv && isascii (*hv) && isspace (*hv))
	hv++;
      len = strlen (hv);
      if (len > 0 && hv[len-1] == '\n')
	hv[len - 1] = 0;
      rc = gacopyz_srv_header(gsrv, hn, hv);
      status = process_data_reply ("cmd", "header", rc, state, reply);
    }
  obstack_free (stk, hn);
  return status;
}

void
smtp (void)
{
  int state;
  char buf[128];
  struct obstack stk;
  int stk_init = 0;
  size_t header_size = 0;
  char *datareply = NULL;
  char *body_buf;
  size_t body_level = 0;

  body_buf = xmalloc (max_body_chunk);

  if (milter_port)
    {
      smtp_reply (220|R_CONT, "mtasim (%s) ready", PACKAGE_STRING);
      smtp_reply (220, "Connected to milter %s", milter_port);
    }
  else
    smtp_reply (220, "mtasim (%s) ready", PACKAGE_STRING);


  for (state = STATE_INIT; state != STATE_QUIT;)
    {
      int argc;
      char **argv;
      int kw, len;

      if (get_input_line (buf, sizeof buf) <= 0)
	{
	  state = STATE_QUIT;
	  continue;
	}

      len = strlen (buf);

      if (trace)
	fprintf (trace, "%s", buf);

      if (state != STATE_HEADERS && state != STATE_DATA)
	{
	  while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r'))
	    len--;
	  buf[len] = 0;
	  
	  argcv_split (buf, &argc, &argv);
	  if (argc == 0)
	    continue;
      
	  if (argv[0][0] == '\\' && milter_port)
	    {
	      shell (argc, argv);
	      argcv_free (argc, argv);
	      continue;
	    }
      
	  kw = smtp_kw (argv[0]);
	  switch (kw)
	    {
	    case KW_QUIT:
	      state = STATE_QUIT;
	      smtp_reply (221, "Done");
	      argcv_free (argc, argv);
	      continue;
	      
	    case KW_HELP:
	      smtp_help ();
	      continue;
	      
	    case KW_RSET:
	      state = STATE_INIT;
	      free (nullmailer);
	      nullmailer = NULL;
	      tempfail = 0;
	      nrcpt = 0;
	      nbadrcpts = 0;
	      discard = 0;
	      header_size = 0;
	      free (datareply);
	      datareply = NULL;
	      if (stk_init)
		obstack_free (&stk, NULL);
	      stk_init = 0;
	      smtp_reply(250, "2.0.0 Reset state");
	      continue;
	    }
	}
      else if (len > 0 && buf[len - 1] == '\n' && buf[len - 2] == '\r')
	{
	  buf[len - 2] = '\n';
	  len--;
	}
      
      buf[len] = 0;
      if (state != STATE_INIT)
	{
	  if (nullmailer)
	    {
	      smtp_send_string (nullmailer, 0);
	      continue;
	    }
	  if (tempfail)
	    {
	      smtp_send_string (MSG_TEMPFAIL, 0);
	      continue;
	    }
	}
	    
      switch (state) {
      case STATE_INIT:
	switch (kw) {
	case KW_EHLO:
	case KW_HELO:
	  if (argc == 2)
	    {
	      smtp_ehlo (kw == KW_EHLO, argv[1]);
	      state = STATE_EHLO;
	    }
	  else
	    smtp_reply (501, "%s requires domain address", argv[0]);
	  break;
	  
	default:
	  smtp_reply (503, "Polite people say HELO first");
	  break;
	}
	break;
	
      case STATE_EHLO:
	switch (kw) {
	case KW_EHLO:
	  if (argc == 2)
	    {
	      smtp_ehlo (1, argv[1]);
	    }
	  else
	    smtp_reply (501, "%s requires domain address", argv[0]);
	  break;

	case KW_MAIL:
	  if (check_address_command("from", &argc, &argv) == 0)
	    {
	      int rc;
	      char *sender;
	      char *addr;
	      char *host;
	      
	      if (parse_email_addr (argv[2], &sender, &addr, &host))
		{
		  smtp_reply (553, "5.0.0 sender address syntactically incorrect");
		  break;
		}
	      
	      if (gsrv)
		{
		  gacopyz_srv_define_macro (gsrv, "f", sender);
		  gacopyz_srv_define_macro0 (gsrv, "r", "SMTP", 0);
 		  /* FIXME: 
		     gacopyz_srv_define_macro (gsrv, "s", host);
		  */
		  gacopyz_srv_define_macro (gsrv, "ntries", "0");
		  gacopyz_srv_define_macro (gsrv, "nrcpts", "0");
		  gacopyz_srv_define_macro (gsrv, "nbadrcpts", "0");

		  /* FIXME */
		  gacopyz_srv_define_macro (gsrv, "mail_mailer", "local");
		  gacopyz_srv_define_macro (gsrv, "mail_host", host);
		  gacopyz_srv_define_macro (gsrv, "mail_addr", addr);
		  gacopyz_srv_define_macro (gsrv, "mail_from", sender);

		  rc = gacopyz_srv_envfrom (gsrv, argv + 2);
		  free (sender);
		  free (addr);
		  free (host);
		  if (process_gacopyz_reply ("from", argv[2], rc, &state))
		    continue;
		}
	      else
		{
		  free (sender);
		  free (addr);
		  free (host);
		}
	      smtp_reply (250, "Sender OK");
	      state = STATE_MAIL;
	    }
	  else
	    smtp_reply (501, "Syntax error");
	  break;

#ifdef HAVE_TLS
	case KW_STARTTLS:
	  smtp_starttls ();
	  break;
#endif
	default:
	  smtp_reply (503, "Need MAIL command");
	}
	break;
	
      case STATE_MAIL:
	switch (kw) {
	case KW_MAIL:
	  smtp_reply (503, "5.5.0 Sender already specified");
	  break;
	  
	case KW_RCPT:
	  smtp_rcpt (&argc, &argv, &state);
	  break;
	  
	default:
	  smtp_reply (503, "Need RCPT command");
	}
	break;
	
      case STATE_RCPT:
	switch (kw) {
	case KW_RCPT:
	  smtp_rcpt (&argc, &argv, &state);
	  break;
	  
	case KW_DATA:
	  if (gsrv)
	    {
	      int rc = gacopyz_srv_data (gsrv);
	      if (process_gacopyz_reply ("cmd", "data", rc, &state))
		continue;
	    }

	  smtp_reply (354,
		      "Enter mail, end with \".\" on a line by itself");
	  if (!stk_init)
	    {
	      obstack_init (&stk);
	      stk_init = 1;
	      header_size = 0;
	    }
	  state = STATE_HEADERS;
	  break;
	  
	default:
	  smtp_reply (501, "Syntax error");
	}
	break;
	
      case STATE_HEADERS:
	if (strcmp (buf, "\n") == 0)
	  {
	    if (gsrv)
	      {
		int rc;
		
		if (header_size)
		  {
		    rc = process_header (&stk, header_size, &state,
					     &datareply);
		    header_size = 0;
		    if (rc)
		      continue;
		  }
		rc = gacopyz_srv_eoh (gsrv);
		if (process_data_reply ("cmd", "eoh", rc, &state, &datareply))
		  continue;
	      }
	    body_level = 0;
	    state = STATE_DATA;
	  }
	else if (buf[0] == ' ' || buf[1] == '\t')
	  {
	    if (gsrv)
	      {
		obstack_1grow (&stk, '\n');	
		obstack_grow (&stk, buf, len);
		header_size += len + 1;
	      }
	  }
	else if (strcmp (buf, ".") == 0)
	  {
	    if (gsrv)
	      {
		int rc = gacopyz_srv_eom (gsrv, NULL, 0);
		process_data_reply ("cmd", "eom", rc, &state, &datareply);
		/* FIXME: Clear macro table, except for the entries from
		   command line */
		gacopyz_srv_clear_macros (gsrv);
	      }
	    if (datareply)
	      {
		smtp_send_string (datareply, 0);
		free (datareply);
		datareply = 0;
	      }
	    else
	      smtp_reply (250, "Mail accepted for delivery");
	    state = STATE_EHLO;
 	  }
	else if (gsrv)
	  {
	    if (header_size)
	      {
		int rc = process_header (&stk, header_size, &state,
					 &datareply);
		header_size = 0;
		if (rc)
		  continue;
	      }
	    obstack_grow (&stk, buf, len);
	    header_size += len;
	  }
	break;
	
      case STATE_DATA:
	if (strcmp (buf, ".\n") == 0)
	  {
	    if (gsrv)
	      {
		int rc;

		rc = gacopyz_srv_eom (gsrv, body_buf, body_level);
		process_data_reply ("cmd", "eom", rc, &state, &datareply);
		/* FIXME: Clear macro table, except for the entries from
		   command line */
		gacopyz_srv_clear_macros (gsrv);
	      }
	    if (datareply)
	      {
		smtp_send_string (datareply, 0);
		free (datareply);
		datareply = 0;
	      }
	    else
	      smtp_reply (250, "Mail accepted for delivery");
	    state = STATE_EHLO;
	  }
	else if (gsrv)
	  {
	    char *ptr = buf;
	    
	    while (len > 0)
	      {
		size_t s = max_body_chunk - body_level;
		if (s > len)
		  s = len;
		memcpy (body_buf + body_level, ptr, s);
		ptr += s;
		len -= s;
		body_level += s;
		if (body_level == max_body_chunk)
		  {
		    int rc = gacopyz_srv_body (gsrv, body_buf, body_level);
		    body_level = 0;
		    if (process_data_reply ("cmd", "data", rc,
					    &state, &datareply))
		      {
			if (datareply)
			  {
			    smtp_send_string (datareply, 0);
			    free (datareply);
			    datareply = 0;
			  }
		      }
		    break;
		  }
	      }
	  }
	break;
      }
    }
  if (gsrv)
    {
      gacopyz_srv_quit (gsrv);
      gacopyz_srv_close (gsrv);
      gacopyz_srv_destroy (&gsrv);
    }
}

int
mta_daemon ()
{
  int on = 1;
  struct sockaddr_in address;
  int fd;

  fd = socket (PF_INET, SOCK_STREAM, 0);
  if (fd < 0)
    {
      perror ("socket");
      return 1;
    }

  setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on));

  memset (&address, 0, sizeof (address));
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = INADDR_ANY;

  if (port)
    {
      address.sin_port = htons (port);
      if (bind (fd, (struct sockaddr *) &address, sizeof (address)) < 0)
	{
	  close (fd);
	  perror ("bind");
	  return 1;
	}
    }
  else
    {
      int status;

      port = 1023;
      do
	{
	  if (++port >= 65535)
	    {
	      mu_error (_("can't bind socket: all ports in use?"));
	      return 1;
	    }
	  address.sin_port = htons (port);
	  status = bind (fd, (struct sockaddr *) &address, sizeof (address));
	}
      while (status < 0);
      printf ("%d\n", port);
      fclose (stdout);
    }

  listen (fd, 5);
  while (1)
    {
      fd_set rfds;
      struct sockaddr_in his_addr;
      int sfd, len, status;

      FD_ZERO (&rfds);
      FD_SET (fd, &rfds);

      status = select (fd + 1, &rfds, NULL, NULL, NULL);
      if (status == -1)
	{
	  if (errno == EINTR)
	    continue;
	  perror ("select");
	  return 1;
	}

      len = sizeof (his_addr);
      if ((sfd = accept (fd, (struct sockaddr *) &his_addr, &len)) < 0)
	{
	  perror ("accept");
	  return 1;
	}

      in = out = (void *) fd;
      smtp ();
      break;
    }

  return 0;
}

int
mta_stdio ()
{
  in = (void *) fileno (stdin);
  out = (void *) fileno (stdout);
  smtp ();
  return 0;
}



int
define_macro (char *arg)
{
  char *p;
  p = strchr (arg, '=');
  if (!p)
    return 1;
  *p++ = 0;
  gacopyz_srv_define_macro (gsrv, arg, p);
  return 0;
}

void
undefine_macro (char *arg)
{
  gacopyz_srv_del_macro (gsrv, arg);
}

void
undefine_all_macros ()
{
  gacopyz_srv_clear_macros (gsrv);
}

void
list_macro (char *name)
{
  const char *val;
  if (gacopyz_srv_find_macro (gsrv, name, &val) == MI_SUCCESS)
    smtp_reply (220, "%s=%s", name, val);
  else
    smtp_reply (220, "%s undefined", name);
}

struct macro_itr
{
  size_t num;
  size_t count;
};

int
macprint (const char *name, const char *value, void *data)
{
  struct macro_itr *itr = data;
  int code = 220;
  
  itr->num++;
  if (itr->num < itr->count)
    code |= R_CONT;
  smtp_reply (code, "%s=%s", name, value);
  return 0;
}

void
list_all_macros ()
{
  struct macro_itr itr;

  itr.num = itr.count = 0;
  gacopyz_srv_count_macros (gsrv, &itr.count);
  
  if (itr.count == 0)
    smtp_reply (220, "No macros defined");
  else
    gacopyz_srv_iterate_macros (gsrv, macprint, &itr);
}

void
shell_help ()
{
  static char *hstr[] = {
    " \\Dname=value [name=value...]       Define Sendmail macros",
    " \\Ecode                             Expect given SMTP reply code",
    " \\L[name] [name...]                 List macros",
    " \\Uname [name...]                   Undefine Sendmail macros",
  };
  #define hcount (sizeof (hstr) / sizeof (hstr[0]))
  int i;

  for (i = 0; i < hcount; i++)
    smtp_reply (((i < hcount-1) ? R_CONT : 0) | 250, "%s", hstr[i]);
}

void
shell (int argc, char **argv)
{
  switch (argv[0][1])
    {
    case 'd':
    case 'D':
      {
	int rc = 0;
	if (argv[0][2])
	  rc = define_macro (&argv[0][2]);
	while (rc == 0 && --argc)
	  rc = define_macro (*++argv);

	if (rc)
	  smtp_reply (502, "Malformed administrative command");
      }
      break;

    case 'u':
    case 'U':
      if (argv[0][2])
	{
	  undefine_macro (&argv[0][2]);
	  while (--argc)
	    undefine_macro (*++argv);
	}
      else if (argc > 1)
	while (--argc)
	  undefine_macro (*++argv);
      else
	undefine_all_macros ();
      break;

    case 'l':
    case 'L':
      if (argv[0][2])
	{
	  list_macro (&argv[0][2]);
	  while (--argc)
	    list_macro (*++argv);
	}
      else if (argc > 1)
	while (--argc)
	  list_macro (*++argv);
      else
	list_all_macros ();
      break;

    case 'e':
    case 'E':
      if (set_expected_code (argv[0] + 2))
	smtp_reply (502, "Invalid SMPT code: %s", argv[0] + 2);
      break;
      
    case '?':
      shell_help ();
      break;
      
    default:
      smtp_reply (502, "Unknown administrative command");
      break;
    }
}

/*
 Local Variables:
 c-file-style: "gnu"
 End:
*/
/* EOF */

Return to:

Send suggestions and report system problems to the System administrator.