This file is indexed.

/usr/bin/mimedefang.pl is in mimedefang 2.83-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
#!/usr/bin/perl
# -*- Perl -*-
#***********************************************************************
#
# mimedefang.pl
#
# Perl scanner which parses MIME messages and filters or removes
# objectionable attachments.
#
# Copyright (C) 2000-2005 Roaring Penguin Software Inc.
#
# This program may be distributed under the terms of the GNU General
# Public License, Version 2, or (at your option) any later version.
#
# This program was derived from the sample program "mimeexplode"
# in the MIME-Tools Perl module distribution.
#
#***********************************************************************

use warnings;
use strict;

# Move site library directory ahead of default library directory in @INC.
# That's so we can sanely package our own version of MIME::Base64 that
# won't conflict with the built-in one on RPM-based platforms.
use lib '/usr/local/share/perl/5.26.1';

require 5.008;
package main;

# My deepest apologies for this mess of globals...
use vars qw($AddWarningsInline @StatusTags
	    $Action $Administrator $AdminName $AdminAddress $DoStatusTags
	    $Changed $CSSHost $DaemonAddress $DaemonName
	    $DefangCounter $Domain $EntireMessageQuarantined
	    $MessageID $Rebuild $QuarantineCount
	    $QuarantineSubdir $QueueID $MsgID $MIMEDefangID
	    $RelayAddr $WasResent $RelayHostname
	    $RealRelayAddr $RealRelayHostname
	    $ReplacementEntity $Sender $ServerMode $Subject $SubjectCount
	    $ClamdSock $SophieSock $TrophieSock
	    $SuspiciousCharsInHeaders
	    $SuspiciousCharsInBody $Helo @ESMTPArgs
	    @SenderESMTPArgs %RecipientESMTPArgs
	    $TerminateAndDiscard $URL $VirusName
	    $CurrentVirusScannerMessage @AddedParts
	    $VirusScannerMessages $WarningLocation $WasMultiPart
	    $CWD $FprotdHost $Fprotd6Host
	    $NotifySenderSubject $NotifyAdministratorSubject
	    $ValidateIPHeader
	    $QuarantineSubject $SALocalTestsOnly $NotifyNoPreamble
	    %Actions %Stupidity @FlatParts @Recipients @Warnings %Features
	    $SyslogFacility $GraphDefangSyslogFacility
	    $MaxMIMEParts $InMessageContext $InFilterContext $PrivateMyHostName
	    $EnumerateRecipients $InFilterEnd $FilterEndReplacementEntity
	    $AddApparentlyToForSpamAssassin $WarningCounter
	    @VirusScannerMessageRoutines @VirusScannerEntityRoutines
	    $VirusScannerRoutinesInitialized
	    %SendmailMacros %RecipientMailers $CachedTimezone $InFilterWrapUp );

use vars qw($GeneralWarning);
use vars qw($HTMLFoundEndBody $HTMLBoilerplate $SASpamTester);

use Socket;
use IO::Socket;
use IO::Select;
use IO::Handle;
use IO::File;
use MIME::Tools 5.410 ();
use MIME::Words qw(:all);
use Digest::SHA;
use Time::Local;
use MIME::Parser;
use Sys::Hostname;
use File::Spec qw ();

# Detect these Perl modules at run-time.  Can explicitly prevent
# loading of these modules by setting $Features{"xxx"} = 0;
#
# You can turn off ALL auto-detection by setting
# $Features{"AutoDetectPerlModules"} = 0;

sub detect_and_load_perl_modules {
    if (!defined($Features{"AutoDetectPerlModules"}) or
	$Features{"AutoDetectPerlModules"}) {
	if (!defined($Features{"SpamAssassin"})) {
	    (eval 'use Mail::SpamAssassin (); $Features{"SpamAssassin"} = 1;')
		or $Features{"SpamAssassin"} = 0;
	}
	if (!defined($Features{"HTML::Parser"})) {
	    (eval 'use HTML::Parser; $Features{"HTML::Parser"} = 1;')
		or $Features{"HTML::Parser"} = 0;
	}
	if (!defined($Features{"Archive::Zip"})) {
	    (eval 'use Archive::Zip qw(:ERROR_CODES); $Features{"Archive::Zip"} = 1;')
		or $Features{"Archive::Zip"} = 0;
	}
	if (!defined($Features{"Net::DNS"})) {
	    (eval 'use Net::DNS; $Features{"Net::DNS"} = 1;')
		or $Features{"Net::DNS"} = 0;
	}
    }
}

undef $SASpamTester;
undef $PrivateMyHostName;
undef @VirusScannerMessageRoutines;
undef @VirusScannerEntityRoutines;
$VirusScannerRoutinesInitialized = 0;

$SALocalTestsOnly = 1;
$DoStatusTags = 0;

$Features{'Virus:AVP'}      = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:AVP5'}      = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:KAVSCANNER'} = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:CLAMAV'}   = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:CLAMD'}    = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:FPROT'}    = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:FPSCAN'}    = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:FSAV'}     = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:HBEDV'}    = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:VEXIRA'}   = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:NAI'}      = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:BDC'}      = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:NVCC'}     = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:SymantecCSS'} = 0; # Ditto
$Features{'Virus:FPROTD'}   = 0;
$Features{'Virus:FPROTD6'}   = 0;
$Features{'Virus:SOPHIE'}   = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:SOPHOS'}   = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:SAVSCAN'}   = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:TREND'}    = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:TROPHIE'}  = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:CSAV'}     = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);
$Features{'Virus:NOD32'}    = ('/bin/false' ne '/bin/false' ? '/bin/false' : 0);

$Features{'Path:SENDMAIL'}  = '/usr/sbin/sendmail';
$Features{'Path:QUARANTINEDIR'} = '/var/spool/MIMEDefang';
$Features{'Path:SPOOLDIR'}  = '/var/spool/MIMEDefang';
$Features{'Path:CONFDIR'}   = '/etc';

# Not in server mode by default
$ServerMode = 0;

# Don't add Apparently-To: header for SpamAssassin
$AddApparentlyToForSpamAssassin = 0;

# Don't add warnings inline (add a MIME part instead)
$AddWarningsInline = 0;

# M$ Exchange or Outlook cannot display multiple Inline: parts
$Stupidity{"NoMultipleInlines"} = 0;

# Warning goes at beginning
$WarningLocation = 0;

# No limit to complexity of MIME messages
$MaxMIMEParts = -1;

# Cache the timzone calculation
$CachedTimezone = "";

# Syslog facility is "mail"
$SyslogFacility = "mail";
undef $GraphDefangSyslogFacility;

$URL = 'http://www.roaringpenguin.com/mimedefang/enduser.php3';
$CSSHost    = "127.0.0.1:7777:local";
$FprotdHost = "127.0.0.1:10200";
$Fprotd6Host = "127.0.0.1:10200";

$SophieSock = '/var/spool/MIMEDefang/sophie';
$ClamdSock  = '/var/spool/MIMEDefang/clamd.sock';
$TrophieSock = '/var/spool/MIMEDefang/trophie';

require "/etc/mail/mimedefang.pl.conf";

#***********************************************************************
# %PROCEDURE: expand_ipv6_address
# %ARGUMENTS:
#  addr -- an IPv6 address
# %RETURNS:
#  An IPv6 address with all zero fields explicitly expanded, and
#  any field shorter than 4 hex digits padded out with zeros.
#***********************************************************************
sub expand_ipv6_address
{
    my ($addr) = @_;

    return '0000:0000:0000:0000:0000:0000:0000:0000' if ($addr eq '::');
    if ($addr =~ /::/) {
	# Do nothing if more than one pair of colons
	return $addr if ($addr =~ /::.*::/);

	# Make sure we don't begin or end with ::
	$addr = "0000$addr" if $addr =~ /^::/;
	$addr .= '0000' if $addr =~ /::$/;

	# Count number of colons
	my $colons = ($addr =~ tr/:/:/);
	if ($colons < 8) {
	    my $missing = ':' . ('0000:' x (8 - $colons));
	    $addr =~ s/::/$missing/;
	}
    }

    # Pad short fields
    return join(':', map { (length($_) < 4 ? ('0' x (4-length($_)) . $_) : $_) } (split(/:/, $addr)));
}

#***********************************************************************
# %PROCEDURE: reverse_ip_address_for_rbl
# %ARGUMENTS:
#  addr -- an IPv4 or IPv6 address
# %RETURNS:
#  The appropriately-reversed address for RBL lookups.
#***********************************************************************
sub reverse_ip_address_for_rbl
{
    my ($addr) = @_;
    if ($addr =~ /:/) {
	$addr = expand_ipv6_address($addr);
	$addr =~ s/://g;
	return join('.', reverse(split(//, $addr)));
    }

    return join('.', reverse(split(/\./, $addr)));
}


#***********************************************************************
# %PROCEDURE: in_message_context
# %ARGUMENTS:
#  name -- a string to syslog if we are not in a message context
# %RETURNS:
#  1 if we are processing a message; 0 otherwise.  Returns 0 if
#  we're in filter_relay, filter_sender or filter_recipient
#***********************************************************************
sub in_message_context {
    my($name) = @_;
    return 1 if ($InMessageContext);
    md_syslog('warning', "$name called outside of message context");
    return 0;
}

#***********************************************************************
# %PROCEDURE: in_filter_wrapup
# %ARGUMENTS:
#  name -- a string to syslog if we are in filter wrapup
# %RETURNS:
#  1 if we are not in filter wrapup; 0 otherwise. 
#***********************************************************************
sub in_filter_wrapup {
    my($name) = @_;
    if ($InFilterWrapUp) {
	    md_syslog('warning', "$name called inside filter_wrapup context");
	    return 1;
    }
    return 0;
}

#***********************************************************************
# %PROCEDURE: in_filter_context
# %ARGUMENTS:
#  name -- a string to syslog if we are not in a filter context
# %RETURNS:
#  1 if we are inside filter or filter_multipart, 0 otherwise.
#***********************************************************************
sub in_filter_context {
    my($name) = @_;
    return 1 if ($InFilterContext);
    md_syslog('warning', "$name called outside of filter context");
    return 0;
}

#***********************************************************************
# %PROCEDURE: in_filter_end
# %ARGUMENTS:
#  name -- a string to syslog if we are not in filter_end
# %RETURNS:
#  1 if we are inside filter_end 0 otherwise.
#***********************************************************************
sub in_filter_end {
    my($name) = @_;
    return 1 if ($InFilterEnd);
    md_syslog('warning', "$name called outside of filter_end");
    return 0;
}

#***********************************************************************
# %PROCEDURE: copy_or_link
# %ARGUMENTS:
#  src -- source filename
#  dest -- destination filename
# %RETURNS:
#  1 on success; 0 on failure.
# %DESCRIPTION:
#  Copies a file: First, attempts to make a hard link.  If that fails,
#  reads the file and copies the data.
#***********************************************************************
sub copy_or_link {
    my($src, $dst) = @_;
    return 1 if link($src, $dst);

    # Link failed; do it the hard way
    open(IN, "<$src") or return 0;
    if (!open(OUT, ">$dst")) {
	close(IN);
	return 0;
    }
    my($n, $string);
    while (($n = read(IN, $string, 4096)) > 0) {
	print OUT $string;
    }
    close(IN);
    close(OUT);
    return 1;
}

#***********************************************************************
# %PROCEDURE: md_copy_orig_msg_to_work_dir
# %ARGUMENTS:
#  None
# %DESCRIPTION:
#  Copies original INPUTMSG file into work directory for virus-scanning
# %RETURNS:
#  1 on success, 0 on failure.
#***********************************************************************
sub md_copy_orig_msg_to_work_dir {
    return if (!in_message_context("md_copy_orig_msg_to_work_dir"));
    return copy_or_link("INPUTMSG", "Work/INPUTMSG");
}

#***********************************************************************
# %PROCEDURE: md_copy_orig_msg_to_work_dir_as_mbox_file
# %ARGUMENTS:
#  None
# %DESCRIPTION:
#  Copies original INPUTMSG file into work directory for virus-scanning
#  as a valid mbox file (adds the "From $Sender mumble..." stuff.)
# %RETURNS:
#  1 on success, 0 on failure.
#***********************************************************************
sub md_copy_orig_msg_to_work_dir_as_mbox_file {
    return if (!in_message_context("md_copy_orig_msg_to_work_dir_as_mbox_file"));
    open(IN, "<INPUTMSG") or return 0;
    unless (open(OUT, ">Work/INPUTMBOX")) {
	close(IN);
	return 0;
    }

    # Remove angle-brackets for From_ line
    my $s = $Sender;
    $s =~ s/^<//;
    $s =~ s/>$//;

    print OUT "From $s " . rfc2822_date() . "\n";
    my($n, $string);
    while (($n = read(IN, $string, 4096)) > 0) {
	print OUT $string;
    }
    close(IN);
    close(OUT);
    return 1;
}

#***********************************************************************
# %PROCEDURE: percent_encode
# %ARGUMENTS:
#  str -- a string, possibly with newlines and control characters
# %RETURNS:
#  A string with unsafe chars encoded as "%XY" where X and Y are hex
#  digits.  For example:
#  "foo\r\nbar\tbl%t" ==> "foo%0D%0Abar%09bl%25t"
#***********************************************************************
sub percent_encode {
    my($str) = @_;
    $str =~ s/([^\x21-\x7e]|[%\\'"])/sprintf("%%%02X", unpack("C", $1))/ge;
    #" Fix emacs highlighting...
    return $str;
}

#***********************************************************************
# %PROCEDURE: percent_encode_for_graphdefang
# %ARGUMENTS:
#  str -- a string, possibly with newlines and control characters
# %RETURNS:
#  A string with unsafe chars encoded as "%XY" where X and Y are hex
#  digits.  For example:
#  "foo\r\nbar\tbl%t" ==> "foo%0D%0Abar%09bl%25t"
# This differs slightly from percent_encode because we don't encode
# quotes or spaces, but we do encode commas.
#***********************************************************************
sub percent_encode_for_graphdefang {
    my($str) = @_;
    $str =~ s/([^\x20-\x7e]|[%\\,])/sprintf("%%%02X", unpack("C", $1))/ge;
    #" Fix emacs highlighting...
    return $str;
}

#***********************************************************************
# %PROCEDURE: push_status_tag
# %ARGUMENTS:
#  tag -- tag describing current status
# %DESCRIPTION:
#  Updates status tag inside multiplexor and pushes onto stack.
# %RETURNS:
#  Nothing
#***********************************************************************
sub push_status_tag
{
	return unless $DoStatusTags;

	my ($tag) = @_;
	push(@StatusTags, $tag);
	if($tag ne '') {
		$tag = "> $tag";
	}
	set_status_tag(scalar(@StatusTags), $tag);
}

#***********************************************************************
# %PROCEDURE: pop_status_tag
# %ARGUMENTS:
#  None
# %DESCRIPTION:
#  Pops previous status of stack and sets tag in multiplexor.
# %RETURNS:
#  Nothing
#***********************************************************************
sub pop_status_tag
{
	return unless $DoStatusTags;

	pop @StatusTags;

	my $tag = $StatusTags[0] || 'no_tag';

	set_status_tag(scalar(@StatusTags), "< $tag");
}

#***********************************************************************
# %PROCEDURE: set_status_tag
# %ARGUMENTS:
#  nest_depth -- nesting depth
#  tag -- status tag
# %DESCRIPTION:
#  Sets the status tag for this worker inside the multiplexor.
# %RETURNS:
#  Nothing
#***********************************************************************
sub set_status_tag
{
	return unless $DoStatusTags;

	my ($depth, $tag) = @_;
	$tag ||= '';

	if($tag eq '') {
		print STATUS_HANDLE "\n";
		return;
	}
	$tag =~ s/[^[:graph:]]/ /g;

	if(defined($MsgID) and ($MsgID ne "NOQUEUE")) {
		print STATUS_HANDLE percent_encode("$depth: $tag $MsgID") . "\n";
	} else {
		print STATUS_HANDLE percent_encode("$depth: $tag") . "\n";
	}
}

# Try to open the status descriptor
sub init_status_tag
{
	return unless $DoStatusTags;

	if(open(STATUS_HANDLE, ">&=3")) {
		STATUS_HANDLE->autoflush(1);
	} else {
		$DoStatusTags = 0;
	}
}

#***********************************************************************
# %PROCEDURE: percent_decode
# %ARGUMENTS:
#  str -- a string encoded by percent_encode
# %RETURNS:
#  The decoded string.  For example:
#  "foo%0D%0Abar%09bl%25t" ==> "foo\r\nbar\tbl%t"
#***********************************************************************
sub percent_decode {
    my($str) = @_;
    $str =~ s/%([0-9A-Fa-f]{2})/pack("C", hex($1))/ge;
    return $str;
}

my $results_fh;

=pod

=head2 write_result_line ( $cmd, @args )

Writes a result line to the RESULTS file.

$cmd should be a one-letter command for the RESULTS file

@args are the arguments for $cmd, if any.  They will be percent_encode()'ed
before being written to the file.

Returns nothing.

=cut

sub write_result_line
{
	my $cmd = shift;

	# Do nothing if we don't yet have a dedicated working directory
	if ($CWD eq $Features{'Path:SPOOLDIR'}) {
		md_syslog('warning', "write_result_line called before working directory established");
		return;
	}

	my $line = $cmd . join ' ', map { percent_encode($_) } @_;

	if (!$results_fh) {
		$results_fh = IO::File->new('>>RESULTS');
		if (!$results_fh) {
			die("Could not open RESULTS file: $!");
		}
	}

	# We have an 8kb limit on the length of lines in RESULTS, including
	# trailing newline and null used in the milter.  So, we limit $cmd +
	# $args to 8190 bytes.
	if( length $line > 8190 ) {
		md_syslog( 'warning',  "Cannot write line over 8190 bytes long to RESULTS file; truncating.  Original line began with: " . substr $line, 0, 40);
		$line = substr $line, 0, 8190;
	}

	print $results_fh "$line\n" or die "Could not write RESULTS line: $!";

	return;
}

#***********************************************************************
# %PROCEDURE: time_str
# %ARGUMENTS:
#  None
# %RETURNS:
#  The current time in the form: "YYYY-MM-DD-HH:mm:ss"
# %DESCRIPTION:
#  Returns a string representing the current time.
#***********************************************************************
sub time_str {
    my($sec, $min, $hour, $mday, $mon, $year, $junk);
    ($sec, $min, $hour, $mday, $mon, $year, $junk) = localtime(time());
    return sprintf("%04d-%02d-%02d-%02d.%02d.%02d",
		   $year + 1900, $mon+1, $mday, $hour, $min, $sec);
}

sub hour_str {
    my($sec, $min, $hour, $mday, $mon, $year, $junk);
    ($sec, $min, $hour, $mday, $mon, $year, $junk) = localtime(time());
    return sprintf('%04d-%02d-%02d-%02d', $year+1900, $min+1, $mday, $hour);
}

{
	# Reworked detection/usage of Sys::Syslog or Unix::Syslog as
	# appropriate is mostly borrowed from Log::Syslog::Abstract, to which
	# I'd love to convert at some point.
	my $_syslogsub = undef;
	my $_openlogsub = undef;
	my $_fac_map   = undef;

	#***********************************************************************
	# %PROCEDURE: md_openlog
	# %ARGUMENTS:
	#  tag -- syslog tag ("mimedefang.pl")
	#  facility -- Syslog facility as a string
	# %RETURNS:
	#  Nothing
	# %DESCRIPTION:
	#  Opens a log using either Unix::Syslog or Sys::Syslog
	#***********************************************************************
	sub md_openlog
	{
		my ($tag, $facility) = @_;

		if( ! defined $_openlogsub ) {
			# Try Unix::Syslog first, then Sys::Syslog
			eval qq{use Unix::Syslog qw( :macros ); };
			if(!$@) {
				($_openlogsub, $_syslogsub) = _wrap_for_unix_syslog();
			} else {
				eval qq{use Sys::Syslog ();};
				if(!$@) {
					($_openlogsub, $_syslogsub) = _wrap_for_sys_syslog();
				} else {
					die q{Unable to detect either Unix::Syslog or Sys::Syslog};
				}
			}
		}

		return $_openlogsub->($tag, 'pid,ndelay', $facility);
	}

	#***********************************************************************
	# %PROCEDURE: md_syslog
	# %ARGUMENTS:
	#  facility -- Syslog facility as a string
	#  msg -- message to log
	# %RETURNS:
	#  Nothing
	# %DESCRIPTION:
	#  Calls syslog, either in Sys::Syslog or Unix::Syslog package
	#***********************************************************************
	sub md_syslog
	{
		my ($facility, $msg) = @_;

		if(!$_syslogsub) {
			md_openlog('mimedefang.pl', $SyslogFacility);
		}

		if (defined $MsgID && $MsgID ne 'NOQUEUE') {
			return $_syslogsub->($facility, '%s', $MsgID . ': ' . $msg);
		} else {
			return $_syslogsub->($facility, '%s', $msg);
		}
	}

	sub _wrap_for_unix_syslog
	{

		my $openlog = sub {
			my ($id, $flags, $facility) = @_;

			die q{first argument must be an identifier string} unless defined $id;
			die q{second argument must be flag string} unless defined $flags;
			die q{third argument must be a facility string} unless defined $facility;

			return Unix::Syslog::openlog( $id, _convert_flags( $flags ), _convert_facility( $facility ) );
		};

		my $syslog = sub {
			my $facility = shift;
			return Unix::Syslog::syslog( _convert_facility( $facility ), @_);
		};

		return ($openlog, $syslog);
	}

	sub _wrap_for_sys_syslog
	{

		my $openlog  = sub {
			# Debian Stretch version is 0.33_01...dammit!
			my $ver = $Sys::Syslog::VERSION;
			$ver =~ s/_.*//;
			if( $ver < 0.16 ) {
				# Older Sys::Syslog versions still need
				# setlogsock().  RHEL5 still ships with 0.13 :(
				Sys::Syslog::setlogsock([ 'unix', 'tcp', 'udp' ]);
			}
			return Sys::Syslog::openlog(@_);
		};
		my $syslog   = sub {
			return Sys::Syslog::syslog(@_);
		};

		return ($openlog, $syslog);
	}

	sub _convert_flags
	{
		my($flags) = @_;

		my $flag_map = {
			pid     => Unix::Syslog::LOG_PID(),
			ndelay  => Unix::Syslog::LOG_NDELAY(),
		};

		my $num = 0;
		foreach my $thing (split(/,/, $flags)) {
			next unless exists $flag_map->{$thing};
			$num |= $flag_map->{$thing};
		}
		return $num;
	}


	sub _convert_facility
	{
		my($facility) = @_;

		my $num = 0;
		foreach my $thing (split(/\|/, $facility)) {
			if (!defined($_fac_map) ||
			    !exists($_fac_map->{$thing})) {
				$_fac_map->{$thing} = _fac_to_num($thing);
			}
			next unless defined $_fac_map->{$thing};
			$num |= $_fac_map->{$thing};
		}
		return $num;
	}

	my %special = (
		error => 'err',
		panic => 'emerg',
	);

	# Some of the Unix::Syslog 'macros' tag exports aren't
	# constants, so we need to ignore them if found.
	my %blacklisted = map { $_ => 1 } qw(mask upto pri makepri fac);

        sub _fac_to_num
	{
		my ($thing) = @_;
		return undef if exists $blacklisted{$thing};
		$thing = $special{$thing} if exists $special{$thing};
		$thing = 'LOG_' . uc($thing);
		return undef unless grep { $_ eq $thing } @ {$Unix::Syslog::EXPORT_TAGS{macros} };
		return eval "Unix::Syslog::$thing()";
	}
}

#***********************************************************************
# %PROCEDURE: fatal
# %ARGUMENTS:
#  msg -- message
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Logs an error and (if we are not in server mode) exits.
#***********************************************************************
sub fatal {
    my($msg) = @_;
    md_syslog('err', "$msg");
    if (!$ServerMode) {
	die($msg);
    } else {
	print_and_flush("error: $msg");
    }
}

#***********************************************************************
# %PROCEDURE: synthesize_received_header
# %ARGUMENTS:
#  None
# %RETURNS:
#  A "Received:" header for current message
# %DESCRIPTION:
#  Synthesizes a valid Received: header to reflect re-mailing.
#***********************************************************************
sub synthesize_received_header {
    my($hdr);
    
    my($hn) = $SendmailMacros{"if_name"};

    my $strdate = rfc2822_date();

    $hn = get_host_name() unless (defined($hn) and ($hn ne ""));
    if ($RealRelayHostname ne "[$RealRelayAddr]") {
	$hdr = "Received: from $Helo ($RealRelayHostname [$RealRelayAddr])\n";
    } else {
	$hdr = "Received: from $Helo ([$RealRelayAddr])\n";
    }
    $hdr .= "\tby $hn (envelope-sender $Sender) (MIMEDefang) with ESMTP id $MsgID";
    if ($#Recipients != 0) {
	$hdr .= "; ";
    } else {
	$hdr .= "\n\tfor " . $Recipients[0] . "; ";
    }

    $hdr .= $strdate . "\n";
    return $hdr;
}

#***********************************************************************
# %PROCEDURE: rebuild_entity
# %ARGUMENTS:
#  out -- output entity to hold rebuilt message
#  in -- input message
# %RETURNS:
#  Nothing useful
# %DESCRIPTION:
#  Descends through input entity and rebuilds an output entity.  The
#  various parts of the input entity may be modified (or even deleted)
#***********************************************************************
sub rebuild_entity {
    my($out, $in) = @_;
    my @parts = $in->parts;
    my($type) = $in->mime_type;
    $type =~ tr/A-Z/a-z/;
    my($body) = $in->bodyhandle;
    my($fname) = takeStabAtFilename($in);
    $fname = "" unless defined($fname);
    my $extension = "";
    $extension = $1 if $fname =~ /(\.[^.]*)$/;

    # If no Content-Type: header, add one
    if (!$in->head->mime_attr('content-type')) {
	$in->head->mime_attr('Content-Type', $type);
    }

    if (!defined($body)) {
	$Action = "accept";
	if (defined(&filter_multipart)) {
	    push_status_tag("In filter_multipart routine");
	    filter_multipart($in, $fname, $extension, $type);
	    pop_status_tag();
	}
	if ($Action eq "drop") {
	    $Changed = 1;
	    return 0;
	}

	if ($Action eq "replace") {
	    $Changed = 1;
	    $out->add_part($ReplacementEntity);
	    return 0;
	}

	my($subentity);
	$subentity = $in->dup;
	$subentity->parts([]);
	$out->add_part($subentity);
	map { rebuild_entity($subentity, $_) } @parts;
    } else {
	# This is where we call out to the user filter.  Get some useful
	# info to pass to the filter

	# Default action is to accept the part
	$Action = "accept";

	if (defined(&filter)) {
	    push_status_tag("In filter routine");
	    filter($in, $fname, $extension, $type);
	    pop_status_tag();
	}

	# If action is "drop", just drop it silently;
	if ($Action eq "drop") {
	    $Changed = 1;
	    return 0;
	}

	# If action is "replace", replace it with $ReplacementEntity;
	if ($Action eq "replace") {
	    $Changed = 1;
	    $out->add_part($ReplacementEntity);
	    return 0;
	}

	# Otherwise, accept it
	$out->add_part($in);
    }
}

#***********************************************************************
# %PROCEDURE: collect_parts
# %ARGUMENTS:
#  entity -- root entity to rebuild
#  skip_pgp_mime -- If true, skip multipart/signed and multipart/encrypted
#                   parts
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Adds parts to the array @FlatParts for flattening.
#***********************************************************************
sub collect_parts {
    my($entity, $skip_pgp_mime) = @_;
    my(@parts) = $entity->parts;
    my($part);
    if ($#parts >= 0) {
	if (! $skip_pgp_mime ||
	    (lc($entity->head->mime_type) ne "multipart/signed" and
	     lc($entity->head->mime_type) ne "multipart/encrypted")) {
	    foreach $part (@parts) {
		collect_parts($part, $skip_pgp_mime);
	    }
	}
    } else {
	push(@FlatParts, $entity);
    }
}

#***********************************************************************
# %PROCEDURE: make_defanged_name
# %ARGUMENTS:
#  None
# %RETURNS:
#  A unique name of the form "defang-$n.binary"
#***********************************************************************
sub make_defanged_name {
    $DefangCounter++;
    return "defang-$DefangCounter.binary";
}

#***********************************************************************
# %PROCEDURE: action_rebuild
# %ARGUMENTS:
#  None
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Sets a flag telling MIMEDefang to rebuild message even if it is
#  unchanged.
#***********************************************************************
sub action_rebuild {
    return undef unless (in_message_context("action_rebuild") && !in_filter_wrapup("action_rebuild"));
    $Rebuild = 1;
}

#***********************************************************************
# %PROCEDURE: action_add_entity
# %ARGUMENTS:
#  entity -- the mime entity to add (must be pre-built)
#  location -- (optional) location at which to add part (default -1 = end)
# %RETURNS:
#  The entity object for the new part
# %DESCRIPTION:
#  Makes a note to add a part to the message.  Parts are *actually* added
#  at the end, which lets us correctly handle non-multipart messages or
#  multipart/foo where "foo" != "mixed".  Sets the rebuild flag.
#***********************************************************************
sub action_add_entity
{
	my($entity, $offset) = @_;

	return undef unless (in_message_context("action_add_part") && !in_filter_wrapup("action_add_part"));
	$offset = -1 unless defined($offset);
	push(@AddedParts, [$entity, $offset]);
	action_rebuild();
	return $entity;
}

#***********************************************************************
# %PROCEDURE: action_add_part
# %ARGUMENTS:
#  entity -- the mime entity
#  type -- the mime type
#  encoding -- see MIME::Entity(8)
#  data -- the data for the part
#  fname -- file name
#  disposition -- content-disposition header
#  location -- (optional) location at which to add part (default -1 = end)
# %RETURNS:
#  The entity object for the new part
# %DESCRIPTION:
#  Makes a note to add a part to the message.  Parts are *actually* added
#  at the end, which lets us correctly handle non-multipart messages or
#  multipart/foo where "foo" != "mixed".  Sets the rebuild flag.
#***********************************************************************
sub action_add_part {
    my ($entity)      = shift;
    my ($type)        = shift;
    my ($encoding)    = shift;
    my ($data)        = shift;
    my ($fname)       = shift;
    my ($disposition) = shift;
    my ($offset)      = shift;

    return undef unless (in_message_context("action_add_part") && !in_filter_wrapup("action_add_part"));

    $offset = -1 unless defined($offset);

    my ($part);

    $part = MIME::Entity->build(Type => $type,
				Top => 0,
				'X-Mailer' => undef,
				Encoding => $encoding,
				Data => ["$data"]);
    defined ($fname) && $part->head->mime_attr("Content-Type.name" => $fname);
    defined ($disposition) && $part->head->mime_attr("Content-Disposition" => $disposition);
    defined ($fname) && $part->head->mime_attr("Content-Disposition.filename" => $fname);

    return action_add_entity($part, $offset);
}

#***********************************************************************
# %PROCEDURE: process_added_parts
# %ARGUMENTS:
#  rebuilt -- rebuilt entity
# %RETURNS:
#  A new entity with parts added
# %DESCRIPTION:
#  Actually adds requested parts to entity.  Ensures that entity is
#  of type multipart/mixed
#***********************************************************************
sub process_added_parts {
    my($rebuilt) = @_;
    my($entity);

    # If no parts to add, do nothing
    return $rebuilt if ($#AddedParts < 0);

    # Make sure we have a multipart/mixed container
    if (lc($rebuilt->head->mime_type) ne "multipart/mixed") {
	$entity = MIME::Entity->build(Type => "multipart/mixed",
				      'X-Mailer' => undef);
	$entity->add_part($rebuilt);
    } else {
	$entity = $rebuilt;
    }
    my $thing;
    foreach $thing (@AddedParts) {
	$entity->add_part($thing->[0], $thing->[1]);
    }
    return $entity;
}

#***********************************************************************
# %PROCEDURE: action_insert_header
# %ARGUMENTS:
#  header -- header name (eg: X-My-Header)
#  value -- header value (eg: any text goes here)
#  position -- where to place it (eg: 0 [default] to make it first)
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note for milter to insert a header in the message in the
#  specified position.  May not be supported on all versions of Sendmail;
#  on unsupported versions, the C milter falls back to action_add_header.
#***********************************************************************
sub action_insert_header {
    my($header, $value, $pos) = @_;
    $pos = 0 unless defined($pos);
    write_result_line('N', $header, $pos, $value);
}

#***********************************************************************
# %PROCEDURE: action_add_header
# %ARGUMENTS:
#  header -- header name (eg: X-My-Header)
#  value -- header value (eg: any text goes here)
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note for milter to add a header to the message.
#***********************************************************************
sub action_add_header {
    my($header, $value) = @_;
    write_result_line('H', $header, $value);
}


#***********************************************************************
# %PROCEDURE: action_change_header
# %ARGUMENTS:
#  header -- header name (eg: X-My-Header)
#  value -- header value (eg: any text goes here)
#  index -- index of header to change (default 1)
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note for milter to change a header in the message.
#***********************************************************************
sub action_change_header {
    my($header, $value, $idx) = @_;
    return if (!in_message_context("action_change_header"));
    $idx = 1 unless defined($idx);

    write_result_line('I', $header, $idx, $value);
}

#***********************************************************************
# %PROCEDURE: action_delete_header
# %ARGUMENTS:
#  header -- header name (eg: X-My-Header)
#  index -- index of header to delete (default 1)
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note for milter to delete a header in the message.
#***********************************************************************
sub action_delete_header {
    my($header, $idx) = @_;
    return if (!in_message_context("action_delete_header"));
    $idx = 1 unless defined($idx);

    write_result_line('J', $header, $idx);
}

#***********************************************************************
# %PROCEDURE: action_delete_all_headers
# %ARGUMENTS:
#  header -- header name (eg: X-My-Header)
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note for milter to delete all instances of header.
#***********************************************************************
sub action_delete_all_headers {
    my($header) = @_;
    return 0 if (!in_message_context("action_delete_all_headers"));
    my($count, $len, $orig_header);

    $orig_header = $header;
    $len = length($header) + 1;
    $header .= ":";
    $header = lc($header);

    return undef unless(open(HDRS, "<HEADERS"));

    $count = 0;
    while(<HDRS>) {
	if (lc(substr($_, 0, $len)) eq $header) {
	    $count++;
	}
    }
    close(HDRS);

    # Delete in REVERSE order, in case Sendmail updates
    # its count as headers are deleted... paranoid but safe.
    while ($count > 0) {
	action_delete_header($orig_header, $count);
	$count--;
    }
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_accept
# %ARGUMENTS:
#  Ignored
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note to accept the current part.
#***********************************************************************
sub action_accept {
    return 0 if (!in_filter_context("action_accept"));
    $Action = "accept";
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_accept_with_warning
# %ARGUMENTS:
#  msg -- warning message
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note to accept the current part, but add a warning to the
#  message.
#***********************************************************************
sub action_accept_with_warning {
    my($msg) = @_;
    return 0 if (!in_filter_context("action_accept_with_warning"));
    $Actions{'accept_with_warning'}++;
    $Action = "accept";
    push(@Warnings, "$msg\n");
    return 1;
}

#***********************************************************************
# %PROCEDURE: message_rejected
# %ARGUMENTS:
#  None
# %RETURNS:
#  True if message has been rejected (with action_bounce or action_tempfail);
#  false otherwise.
#***********************************************************************
sub message_rejected {
    return 0 if (!in_message_context("message_rejected"));
    return (defined($Actions{'tempfail'}) ||
	    defined($Actions{'bounce'})   ||
	    defined($Actions{'discard'}));
}

#***********************************************************************
# %PROCEDURE: action_drop
# %ARGUMENTS:
#  Ignored
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note to drop the current part without any warning.
#***********************************************************************
sub action_drop {
    return 0 if (!in_filter_context("action_drop"));
    $Actions{'drop'}++;
    $Action = "drop";
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_drop_with_warning
# %ARGUMENTS:
#  msg -- warning message
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note to drop the current part and add a warning to the message
#***********************************************************************
sub action_drop_with_warning {
    my($msg) = @_;
    return 0 if (!in_filter_context("action_drop_with_warning"));
    $Actions{'drop_with_warning'}++;
    $Action = "drop";
    push(@Warnings, "$msg\n");
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_replace_with_warning
# %ARGUMENTS:
#  msg -- warning message
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note to drop the current part and replace it with a warning
#***********************************************************************
sub action_replace_with_warning {
    my($msg) = @_;
    return 0 if (!in_filter_context("action_replace_with_warning"));
    $Actions{'replace_with_warning'}++;
    $Action = "replace";
    $WarningCounter++;
    $ReplacementEntity = MIME::Entity->build(Top => 0,
					     Type => "text/plain",
 					     Encoding => "-suggest",
					     Disposition => "inline",
					     Filename => "warning$WarningCounter.txt",
					     'X-Mailer' => undef,
 					     Data => [ "$msg\n" ]);
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_defang
# %ARGUMENTS:
#  entity -- current part
#  name -- suggested name for defanged part
#  fname -- suggested filename for defanged part
#  type -- suggested MIME type for defanged part
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Makes a note to defang the current part by changing its name, filename
#  and possibly MIME type.
#***********************************************************************
sub action_defang {
    $Changed = 1;
    my($entity, $name, $fname, $type) = @_;
    return 0 if (!in_filter_context("action_defang"));

    $name = "" unless defined($name);
    $fname = "" unless defined($fname);
    $type = "application/octet-stream" unless defined($type);

    $Actions{'defang'}++;
    my($head) = $entity->head;
    my($oldfname) = takeStabAtFilename($entity);

    my($defang);
    if ($name eq "" || $fname eq "") {
	$defang = make_defanged_name();
    }
    $name = $defang if ($name eq "");
    $fname = $defang if ($fname eq "");

    my($warning);
    if (defined(&defang_warning)) {
	$warning = defang_warning($oldfname, $fname);
    } else {
	$warning = "An attachment named '$oldfname'";
	$warning .= " was converted to '$fname'.\n";
	$warning .= "To recover the file, click on the attachment and Save As\n'$oldfname' in order to access it.\n";
    }

    $entity->effective_type($type);
    $head->replace("Content-Type", $type);
    $head->mime_attr("Content-Type.name" => $name);
    $head->mime_attr("Content-Disposition.filename" => $fname);
    $head->mime_attr("Content-Description" => $fname);

    action_accept_with_warning("$warning");
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_external_filter
# %ARGUMENTS:
#  entity -- current part
#  cmd -- UNIX command to run
# %RETURNS:
#  1 on success, 0 otherwise.
# %DESCRIPTION:
#  Pipes the part through the UNIX command $cmd, and replaces the
#  part with the result of running the filter.
#***********************************************************************
sub action_external_filter {
    my($entity, $cmd) = @_;

    return 0 if (!in_filter_context("action_external_filter"));
    # Copy the file
    my($body) = $entity->bodyhandle;
    if (!defined($body)) {
	return 0;
    }

    if (!defined($body->path)) {
	return 0;
    }

    unless(copy_or_link($body->path, "FILTERINPUT")) {
	md_syslog('err', "Could not open FILTERINPUT: $!");
	return(0);
    }

    # Run the filter
    my($status) = system($cmd);

    # Filter failed if non-zero exit
    if ($status % 255) {
	md_syslog('err', "External filter exited with non-zero status $status");
	return 0;
    }

    # If filter didn't produce FILTEROUTPUT, do nothing
    return 1 if (! -r "FILTEROUTPUT");

    # Rename FILTEROUTPUT over original path
    unless (rename("FILTEROUTPUT", $body->path)) {
	md_syslog('err', "Could not rename FILTEROUTPUT to path: $!");
	return(0);
    }
    $Changed = 1;
    $Actions{'external_filter'}++;
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_quarantine
# %ARGUMENTS:
#  entity -- current part
#  msg -- warning message
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Similar to action_drop_with_warning, but e-mails the MIMEDefang
#  administrator a notification, and quarantines the part in the
#  quarantine directory.
#***********************************************************************
sub action_quarantine {
    my($entity, $msg) = @_;

    return 0 if (!in_filter_context("action_quarantine"));
    $Action = "drop";
    push(@Warnings, "$msg\n");

    # Can't handle path-less bodies
    my($body) = $entity->bodyhandle;
    if (!defined($body)) {
	return 0;
    }

    if (!defined($body->path)) {
	return 0;
    }

    get_quarantine_dir();
    if ($QuarantineSubdir eq "") {
	# Could not create quarantine directory
	return 0;
    }

    $Actions{'quarantine'}++;
    $QuarantineCount++;

    # Save the part
    copy_or_link($body->path, "$QuarantineSubdir/PART.$QuarantineCount.BODY");

    # Save the part's headers
    if (open(OUT, ">$QuarantineSubdir/PART.$QuarantineCount.HEADERS")) {
	$entity->head->print(\*OUT);
	close(OUT);
    }

    # Save the messages
    if (open(OUT, ">$QuarantineSubdir/MSG.$QuarantineCount")) {
	print OUT "$msg\n";
	close(OUT);
    }
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_sm_quarantine
# %ARGUMENTS:
#  reason -- reason for quarantine
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Asks Sendmail to quarantine message in mqueue using Sendmail's
#  smfi_quarantine facility.
#***********************************************************************
sub action_sm_quarantine {
    my($reason) = @_;
    return if (!in_message_context("action_sm_quarantine"));

    $Actions{'sm_quarantine'} = 1;
    write_result_line("Q", $reason);
}

sub get_quarantine_dir {

    # If quarantine dir has already been made, return it.
    if ($QuarantineSubdir ne "") {
	return $QuarantineSubdir;
    }

    my($counter) = 0;
    my($tries);
    my($success) = 0;
    my($tm);
    $tm = time_str();
    my $hour = hour_str();
    my $hour_dir = sprintf("%s/%s", $Features{'Path:QUARANTINEDIR'}, $hour);
    mkdir($hour_dir, 0750);
    if (! -d $hour_dir) {
	    return "";
    }
    do {
	$counter++;
	$QuarantineSubdir = sprintf("%s/%s/qdir-%s-%03d",
				    $Features{'Path:QUARANTINEDIR'}, $hour, $tm, $counter);
	if (mkdir($QuarantineSubdir, 0750)) {
	    $success = 1;
	}
    } while(!$success && ($tries++ < 1000));
    if (!$success) {
	$QuarantineSubdir = "";
	return "";
    }

    # Write the sender and recipient info
    if (open(OUT, ">$QuarantineSubdir/SENDER")) {
	print OUT "$Sender\n";
	close(OUT);
    }
    if (open(OUT, ">$QuarantineSubdir/SENDMAIL-QID")) {
	print OUT "$QueueID\n";
	close(OUT);
    }

    if (open(OUT, ">$QuarantineSubdir/RECIPIENTS")) {
	my($s);
	foreach $s (@Recipients) {
	    print OUT "$s\n";
	}
	close(OUT);
    }

    # Copy message headers
    if (open(OUT, ">$QuarantineSubdir/HEADERS")) {
	if (open(IN, "<HEADERS")) {
	    while(<IN>) {
		print OUT;
	    }
	    close(IN);
	}
	close(OUT);
    }

    return $QuarantineSubdir;
}

#***********************************************************************
# %PROCEDURE: action_quarantine_entire_message
# %ARGUMENTS:
#  msg -- quarantine message (optional)
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Puts a copy of the entire message in the quarantine directory.
#***********************************************************************
sub action_quarantine_entire_message {
    my($msg) = @_;
    return 0 if (!in_message_context("action_quarantine_entire_message"));
    # If no parts have yet been quarantined, create the quarantine subdirectory
    # and write useful info there
    get_quarantine_dir();
    if ($QuarantineSubdir eq "") {
	# Could not create quarantine directory
	return 0;
    }

    # Don't copy message twice
    if ($EntireMessageQuarantined) {
	return 1;
    }

    $Actions{'quarantine_entire_message'}++;
    if (defined($msg) && ($msg ne "")) {
	if (open(OUT, ">$QuarantineSubdir/MSG.0")) {
	    print OUT "$msg\n";
	    close(OUT);
	}
    }

    $EntireMessageQuarantined = 1;

    copy_or_link("INPUTMSG", "$QuarantineSubdir/ENTIRE_MESSAGE");

    return 1;
}

#***********************************************************************
# %PROCEDURE: action_bounce
# %ARGUMENTS:
#  reply -- SMTP reply text (eg: "Not allowed, sorry")
#  code -- SMTP reply code (eg: 554)
#  DSN -- DSN code (eg: 5.7.1)
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Causes the SMTP transaction to fail with an SMTP 554 failure code and the
#  specified reply text.  If code or DSN are omitted or invalid,
#  use 554 and 5.7.1.
#***********************************************************************
sub action_bounce {
    my($reply, $code, $dsn) = @_;
    return 0 if (!in_message_context("action_bounce"));

    $reply = "Forbidden for policy reasons" unless (defined($reply) and ($reply ne ""));
    $code = 554 unless (defined($code) and $code =~ /^5\d\d$/);
    $dsn = "5.7.1" unless (defined($dsn) and $dsn =~ /^5\.\d{1,3}\.\d{1,3}$/);

    write_result_line('B', $code, $dsn, $reply);
    $Actions{'bounce'}++;
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_discard
# %ARGUMENTS:
#  None
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Causes the entire message to be silently discarded without without
#  notifying anyone.
#***********************************************************************
sub action_discard {
    return 0 if (!in_message_context("action_discard"));
    write_result_line("D", "");
    $Actions{'discard'}++;
    return 1;
}

#***********************************************************************
# %PROCEDURE: action_notify_sender
# %ARGUMENTS:
#  msg -- a message to send
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Causes an e-mail to be sent to the sender containing $msg
#***********************************************************************
sub action_notify_sender {
    my($msg) = @_;
    return 0 if (!in_message_context("action_notify_sender"));
    if ($Sender eq '<>') {
	md_syslog('err', "Skipped action_notify_sender: Sender = <>");
	return 0;
    }

    if ($VirusName ne "") {
	md_syslog('err', "action_notify_sender disabled when virus is detected");
	return 0;
    }

    if (open(FILE, ">>NOTIFICATION")) {
	print FILE $msg;
	close(FILE);
	$Actions{'notify_sender'}++;
	return 1;
    }
    md_syslog('err', "Could not create NOTIFICATION file: $!");
    return 0;
}

#***********************************************************************
# %PROCEDURE: action_notify_administrator
# %ARGUMENTS:
#  msg -- a message to send
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Causes an e-mail to be sent to the MIMEDefang administrator
#  containing $msg
#***********************************************************************
sub action_notify_administrator {
    my($msg) = @_;
    if (!$InMessageContext) {
	send_admin_mail($NotifyAdministratorSubject, $msg);
	return 1;
    }
    if (open(FILE, ">>ADMIN_NOTIFICATION")) {
	print FILE $msg;
	close(FILE);
	$Actions{'notify_administrator'}++;
	return 1;
    }
    md_syslog('err', "Could not create ADMIN_NOTIFICATION file: $!");
    return 0;
}

#***********************************************************************
# %PROCEDURE: relay_is_blacklisted
# %ARGUMENTS:
#  addr -- IP address of relay host.
#  domain -- domain of blacklist server (eg: inputs.orbz.org)
# %RETURNS:
#  The result of the lookup (eg 127.0.0.2)
#***********************************************************************
sub relay_is_blacklisted {
    my($addr, $domain) = @_;
    $addr = reverse_ip_address_for_rbl($addr) . ".$domain";

    my $hn;
    $hn = gethostbyname($addr);
    return 0 unless defined($hn);
    return $hn if ($hn);

    # Hostname is defined, but false -- return 1 instead.
    return 1;
}

#***********************************************************************
# %PROCEDURE: relay_is_blacklisted_multi
# %ARGUMENTS:
#  addr -- IP address of relay host.
#  timeout -- number of seconds after which to time out
#  answers_wanted -- if positive, return as soon as this many positive answers
#                    have been received.
#  domains -- an array of domains to check
#  res (optional) -- A Net::DNS::Resolver object.  If you don't pass
#                    one in, we'll generate one and use it.
# %RETURNS:
#  A hash table with one entry per original domain.  Entries in hash
#  will be:
#  { $domain => $return }, where $return is one of SERVFAIL, NXDOMAIN or
#  a list of IP addresses as a dotted-quad.
#***********************************************************************
sub relay_is_blacklisted_multi {
    my($addr, $timeout, $answers_wanted, $domains, $res) = @_;
    my($domain, $sock);

    my $ans = {};
    my $positive_answers = 0;

    foreach $domain (@{$domains}) {
	$ans->{$domain} = 'SERVFAIL';
    }
    unless ($Features{"Net::DNS"}) {
	md_syslog('err', "Attempted to call relay_is_blacklisted_multi, but Perl module Net::DNS is not installed");
	return $ans;
    }

    push_status_tag("Doing RBL Lookup");
    my %sock_to_domain;

    # Reverse the address
    $addr = reverse_ip_address_for_rbl($addr);

    # If user did not pass in a Net::DNS::Resolver object, generate one.
    unless (defined($res and (UNIVERSAL::isa($res, "Net::DNS::Resolver")))) {
	$res = Net::DNS::Resolver->new;
	$res->defnames(0);
    }

    my $sel = IO::Select->new();

    # Send out the queries
    foreach $domain (@{$domains}) {
	$sock = $res->bgsend("$addr.$domain", 'A');
	$sock_to_domain{$sock} = $domain;
	$sel->add($sock);
    }

    # Now wait for them to come back.
    my $terminate = time() + $timeout;
    while (time() <= $terminate) {
	my $expire = $terminate - time();
	# Avoid fractional wait for select which gets truncated.
	# So we may end up timing out after 1 extra second... no big deal
	$expire = 1 if ($expire < 1);
	my @ready;
	@ready = $sel->can_read($expire);
	foreach $sock (@ready) {
	    my $pack = $res->bgread($sock);
	    $sel->remove($sock);
	    $domain = $sock_to_domain{$sock};
	    undef($sock);
	    my($rr, $rcode);
	    $rcode = $pack->header->rcode;
	    if ($rcode eq "SERVFAIL" or $rcode eq "NXDOMAIN") {
		$ans->{$domain} = $rcode;
		next;
	    }
	    my $got_one = 0;
	    foreach $rr ($pack->answer) {
		if ($rr->type eq 'A') {
		    $got_one = 1;
		    if ($ans->{$domain} eq "SERVFAIL") {
			$ans->{$domain} = ();
		    }
		    push(@{$ans->{$domain}}, $rr->address);
		}
	    }
	    $positive_answers++ if ($got_one);
	}
	last if ($sel->count() == 0 or
		 ($answers_wanted > 0 and $positive_answers >= $answers_wanted));
    }
    pop_status_tag();
    return $ans;
}

#***********************************************************************
# %PROCEDURE: relay_is_blacklisted_multi_count
# %ARGUMENTS:
#  addr -- IP address of relay host.
#  timeout -- number of seconds after which to time out
#  answers_wanted -- if positive, return as soon as this many positive answers
#                    have been received.
#  domains -- an array of domains to check
#  res (optional) -- A Net::DNS::Resolver object.  If you don't pass
#                    one in, we'll generate one and use it.
# %RETURNS:
#  A number indicating how many RBLs the host was blacklisted in.
#***********************************************************************
sub relay_is_blacklisted_multi_count {
    my($addr, $timeout, $answers_wanted, $domains, $res) = @_;
    my $ans = relay_is_blacklisted_multi($addr,
					 $timeout,
					 $answers_wanted,
					 $domains,
					 $res);
    my $count = 0;
    my $domain;
    foreach $domain (keys(%$ans)) {
	my $r = $ans->{$domain};
	if (ref($r) eq "ARRAY" and $#{$r} >= 0) {
	    $count++;
	}
    }
    return $count;
}

#***********************************************************************
# %PROCEDURE: relay_is_blacklisted_multi_list
# %ARGUMENTS:
#  addr -- IP address of relay host.
#  timeout -- number of seconds after which to time out
#  answers_wanted -- if positive, return as soon as this many positive answers
#                    have been received.
#  domains -- an array of domains to check
#  res (optional) -- A Net::DNS::Resolver object.  If you don't pass
#                    one in, we'll generate one and use it.
# %RETURNS:
#  An array indicating the domains in which the relay is blacklisted.
#***********************************************************************
sub relay_is_blacklisted_multi_list {
    my($addr, $timeout, $answers_wanted, $domains, $res) = @_;
    my $ans = relay_is_blacklisted_multi($addr,
					 $timeout,
					 $answers_wanted,
					 $domains,
					 $res);
    my $result = [];
    my $domain;
    foreach $domain (keys(%$ans)) {
	my $r = $ans->{$domain};
	if (ref($r) eq "ARRAY" and $#{$r} >= 0) {
	    push @$result, $domain;
	}
    }

    # If in list context, return the array.  Otherwise, return
    # array reference.
    return (wantarray ? @$result : $result);
}

#***********************************************************************
# %PROCEDURE: signal_unchanged
# %ARGUMENTS:
#  None
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Tells mimedefang C program message has not been altered (does nothing...)
#***********************************************************************
sub signal_unchanged {
}

#***********************************************************************
# %PROCEDURE: signal_changed
# %ARGUMENTS:
#  None
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Tells mimedefang C program message has been altered.
#***********************************************************************
sub signal_changed {
    write_result_line("C", "");
}

#***********************************************************************
# %PROCEDURE: get_host_name
# %ARGUMENTS:
#  None
# %RETURNS:
#  Local host name, if it could be determined.
#***********************************************************************
sub get_host_name {
    # Use cached value if we have it
    return $PrivateMyHostName if defined($PrivateMyHostName);

    # Otherwise execute "hostname"
    $PrivateMyHostName = hostname;

    $PrivateMyHostName = "localhost" unless defined($PrivateMyHostName);

    # Now make it FQDN
    my($fqdn) = gethostbyname($PrivateMyHostName);
    $PrivateMyHostName = $fqdn if (defined $fqdn) and length($fqdn) > length($PrivateMyHostName);

    return $PrivateMyHostName;
}

#***********************************************************************
# %PROCEDURE: gen_date_msgid_headers
# %ARGUMENTS:
#  None
# %RETURNS:
#  A string like this: "Date: <rfc2822-date>\nMessage-ID: <message@id.com>\n"
# %DESCRIPTION:
#  Generates RFC2822-compliant Date and Message-ID headers.
#***********************************************************************
sub gen_date_msgid_headers {
    return "Date: " . rfc2822_date() . "\n" . gen_msgid_header();
}

sub rfc2822_date
{
	my $now = time();
	my ($ss, $mm, $hh, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($now);
	return sprintf("%s, %02d %s %04d %02d:%02d:%02d %s",
		(qw( Sun Mon Tue Wed Thu Fri Sat ))[$wday],
		$mday,
		(qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ))[$mon],
		$year + 1900,
		$hh,
		$mm,
		$ss,
		header_timezone($now)
	);
}

sub header_timezone
{
    return $CachedTimezone if ($CachedTimezone ne "");

    my($now) = @_;

    my($sec, $min, $hr, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($now);
    my $a = timelocal($sec, $min, $hr, $mday, $mon, $year);
    my $b = timegm($sec, $min, $hr, $mday, $mon, $year);
    my $c = ($b - $a) / 60;
    $hr = int(abs($c) / 60);
    $min = abs($c) - 60 * $hr;

    if ($c >= 0) {
	$CachedTimezone = sprintf("+%02d%02d", $hr, $min);
    } else {
	$CachedTimezone = sprintf("-%02d%02d", $hr, $min);
    }
    return $CachedTimezone;
}

#***********************************************************************
# %PROCEDURE: gen_msgid_header
# %ARGUMENTS:
#  None
# %RETURNS:
#  A string like this: "Message-ID: <message@id.com>\n"
# %DESCRIPTION:
#  Generates RFC2822-compliant Message-ID headers.
#***********************************************************************
sub gen_msgid_header {
	my ($ss, $mm, $hh, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);

	# Generate a "random" message ID that looks
	# similiar to sendmail's for SpamAssassin comparing
	# Received / MessageID QueueID
	return sprintf("Message-ID: <%04d%02d%02d%02d%02d.%s\@%s>\n",
		$year + 1900,
		$mon  + 1,
		$mday,
		$hh,
		$mm,
		($QueueID eq 'NOQUEUE' ? rand() : $QueueID),
		get_host_name()
	);
}

#***********************************************************************
# %PROCEDURE: send_quarantine_notifications
# %ARGUMENTS:
#  None
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Sends quarantine notification message, if anything was quarantined
#***********************************************************************
sub send_quarantine_notifications {
    # If there are quarantined parts, e-mail a report
    if ($QuarantineCount > 0 || $EntireMessageQuarantined) {
	my($body);
	$body = "From: $DaemonName <$DaemonAddress>\n";
	$body .= "To: \"$AdminName\" <$AdminAddress>\n";
	$body .= gen_date_msgid_headers();
	$body .= "Auto-Submitted: auto-generated\n";
	$body .= "MIME-Version: 1.0\nContent-Type: text/plain\n";
	$body .= "Precedence: bulk\n";
	$body .= "Subject: $QuarantineSubject\n\n";
	if ($QuarantineCount >= 1) {
	    $body .= "An e-mail had $QuarantineCount part";
	    $body .= "s" if ($QuarantineCount != 1);
	} else {
	    $body .= "An e-mail message was";
	}

	$body .= " quarantined in the directory\n";
	$body .= "$QuarantineSubdir on " . get_host_name() . ".\n\n";
	$body .= "The sender was '$Sender'.\n\n" if defined($Sender);
	$body .= "The Sendmail queue identifier was $QueueID.\n\n" if ($QueueID ne "NOQUEUE");
	$body .= "The relay machine was $RelayHostname ($RelayAddr).\n\n";
	if ($EntireMessageQuarantined) {
	    $body .= "The entire message was quarantined in $QuarantineSubdir/ENTIRE_MESSAGE\n\n";
	}

	my($recip);
	foreach $recip (@Recipients) {
	    $body .= "Recipient: $recip\n";
	}
	my $donemsg = 0;
	my $i;
	for ($i=0; $i<=$QuarantineCount; $i++) {
	    if (open(IN, "<$QuarantineSubdir/MSG.$i")) {
		if (!$donemsg) {
		    $body .= "Quarantine Messages:\n";
		    $donemsg = 1;
		}
		while(<IN>) {
		    $body .= $_;
		}
		close(IN);
	    }
	}
	if ($donemsg) {
	    $body .= "\n";
	}

	if (open(IN, "<$QuarantineSubdir/HEADERS")) {
	    $body .= "\n----------\nHere are the message headers:\n";
	    while(<IN>) {
		$body .= $_;
	    }
	    close(IN);
	}
	for ($i=1; $i<=$QuarantineCount; $i++) {
	    if (open(IN, "<$QuarantineSubdir/PART.$i.HEADERS")) {
		$body .= "\n----------\nHere are the headers for quarantined part $i:\n";
		while(<IN>) {
		    $body .= $_;
		}
		close(IN);
	    }
	}
	if ($#Warnings >= 0) {
	    $body .= "\n----------\nHere are the warning details:\n\n";
	    $body .= "@Warnings";
	}
	send_mail($DaemonAddress, $DaemonName, $AdminAddress, $body);
    }
}


#***********************************************************************
# %PROCEDURE: signal_complete
# %ARGUMENTS:
#  None
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Tells mimedefang C program Perl filter has finished successfully.
#  Also mails any quarantine notifications and sender notifications.
#***********************************************************************
sub signal_complete {
    # Send notification to sender, if required
    if ($Sender ne '<>' && -r "NOTIFICATION") {
	my($body);
	$body = "From: $DaemonName <$DaemonAddress>\n";
	$body .= "To: $Sender\n";
	$body .= gen_date_msgid_headers();
	$body .= "Auto-Submitted: auto-generated\n";
	$body .= "MIME-Version: 1.0\nContent-Type: text/plain\n";
	$body .= "Precedence: bulk\n";
	$body .= "Subject: $NotifySenderSubject\n\n";
	unless($NotifyNoPreamble) {
	    $body .= "An e-mail you sent with message-id $MessageID\n";
	    $body .= "was modified by our mail scanning software.\n\n";
	    $body .= "The recipients were:";
	    my($recip);
	    foreach $recip (@Recipients) {
		$body .= " $recip";
	    }
	    $body .= "\n\n";
	}
	if (open(FILE, "<NOTIFICATION")) {
	    unless($NotifyNoPreamble) {
		$body .= "Here are the details of the modification:\n\n";
	    }
	    while(<FILE>) {
		$body .= $_;
	    }
	    close(FILE);
	}
	send_mail($DaemonAddress, $DaemonName, $Sender, $body);
    }

    # Send notification to administrator, if required
    if (-r "ADMIN_NOTIFICATION") {
	my $body = "";
	if (open(FILE, "<ADMIN_NOTIFICATION")) {
	    $body .= join('', <FILE>);
	    close(FILE);
	    send_admin_mail($NotifyAdministratorSubject, $body);
	}
    }

    # Syslog some info if any actions were taken
    my($msg) = "";
    my($key, $num);
    foreach $key (sort keys(%Actions)) {
	$num = $Actions{$key};
	$msg .= " $key=$num";
    }
    if ($msg ne "") {
	md_syslog('debug', "filter: $msg");
    }
    write_result_line("F", "");
    if ($results_fh) {
	    $results_fh->close() or die("Could not close RESULTS file: $!");
	    undef $results_fh;
    }

    if ($ServerMode) {
	print_and_flush('ok');
    }
}

#***********************************************************************
# %PROCEDURE: send_mail
# %ARGUMENTS:
#  fromAddr -- address of sender
#  fromFull -- full name of sender
#  recipient -- address of recipient
#  body -- mail message (including headers) newline-terminated
#  deliverymode -- optional sendmail delivery mode arg (default "-odd")
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Sends a mail message using Sendmail.  Invokes Sendmail without involving
#  the shell, so that shell metacharacters won't cause security problems.
#***********************************************************************
sub send_mail {
    my($fromAddr, $fromFull, $recipient, $body, $deliverymode) = @_;

    $deliverymode = "-odd" unless defined($deliverymode);
    if ($deliverymode ne "-odb" &&
	$deliverymode ne "-odq" &&
	$deliverymode ne "-odd" &&
	$deliverymode ne "-odi") {
	$deliverymode = "-odd";
    }

    my($pid);

    # Fork and exec for safety instead of involving shell
    $pid = open(CHILD, "|-");
    if (!defined($pid)) {
	md_syslog('err', "Cannot fork to run sendmail");
	return;
    }

    if ($pid) {   # In the parent -- pipe mail message to the child
	print CHILD $body;
	close(CHILD);
	return;
    }

    # In the child -- invoke Sendmail

    # Direct stdout to stderr, or we will screw up communication with
    # the multiplexor..
    open(STDOUT, ">&STDERR");

    my(@cmd);
    if ($fromAddr ne "") {
	push(@cmd, "-f$fromAddr");
    } else {
	push(@cmd, "-f<>");
    }
    if ($fromFull ne "") {
	push(@cmd, "-F$fromFull");
    }
    push(@cmd, $deliverymode);
    push(@cmd, "-Ac");
    push(@cmd, "-oi");
    push(@cmd, "--");
    push(@cmd, $recipient);

    # In curlies to silence Perl warning...
    my $sm;
    $sm = $Features{'Path:SENDMAIL'};
    { exec($sm, @cmd); }

    # exec failed!
    md_syslog('err', "Could not exec $sm: $!");
    exit(1);
    # NOTREACHED
}

#***********************************************************************
# %PROCEDURE: resend_message_one_recipient
# %ARGUMENTS:
#  recip -- a single recipient
#  deliverymode -- optional sendmail delivery mode arg (default "-odd")
# %RETURNS:
#  True on success; false on failure.
# %DESCRIPTION:
#  Re-sends the message (as if it came from original sender) to
#  a single recipient.
#***********************************************************************
sub resend_message_one_recipient {
	my($recip, $deliverymode) = @_;
	return resend_message_specifying_mode($deliverymode, [ $recip ]);
}

#***********************************************************************
# %PROCEDURE: send_admin_mail
# %ARGUMENTS:
#  subject -- mail subject
#  body -- mail message (without headers) newline-terminated
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Sends a mail message to the administrator
#***********************************************************************
sub send_admin_mail {

    my ($subject, $body) = @_;

    my $mail;
    $mail = "From: $DaemonName <$DaemonAddress>\n";
    $mail .= "To: \"$AdminName\" <$AdminAddress>\n";
    $mail .= gen_date_msgid_headers();
    $mail .= "Auto-Submitted: auto-generated\n";
    $mail .= "MIME-Version: 1.0\nContent-Type: text/plain\n";
    $mail .= "Precedence: bulk\n";
    $mail .= "Subject: $subject\n\n";
    $mail .= $body;

    send_mail($DaemonAddress, $DaemonName, $AdminAddress, $mail);
}

#***********************************************************************
# %PROCEDURE: resend_message_specifying_mode
# %ARGUMENTS:
#  deliverymode -- delivery mode
#  recipients -- reference to list of recipients to resend message to.
# %RETURNS:
#  True on success; false on failure.
# %DESCRIPTION:
#  Re-sends the message (as if it came from original sender) to
#  a list of recipients.
#***********************************************************************
sub resend_message_specifying_mode {
    my($deliverymode, $recips) = @_;
    return 0 if (!in_message_context("resend_message_specifying_mode"));

    $deliverymode = "-odd" unless defined($deliverymode);
    if ($deliverymode ne "-odb" &&
	$deliverymode ne "-odq" &&
	$deliverymode ne "-odd" &&
	$deliverymode ne "-odi") {
	$deliverymode = "-odd";
    }

    # Fork and exec for safety instead of involving shell
    my $pid = open(CHILD, "|-");
    if (!defined($pid)) {
	md_syslog('err', "Cannot fork to resend message");
	return 0;
    }

    if ($pid) {   # In the parent -- pipe mail message to the child
	unless (open(IN, "<INPUTMSG")) {
	    md_syslog('err', "Could not open INPUTMSG in resend_message: $!");
	    return 0;
	}

	# Preserve relay's IP address if possible...
	if ($ValidateIPHeader =~ /^X-MIMEDefang-Relay/) {
	    print CHILD "$ValidateIPHeader: $RelayAddr\n"
	}

	# Synthesize a Received: header
	print CHILD synthesize_received_header();

	# Copy message over
	while(<IN>) {
	    print CHILD;
	}
	close(IN);
	if (!close(CHILD)) {
	    if ($!) {
		md_syslog('err', "sendmail failure in resend_message: $!");
	    } else {
		md_syslog('err', "sendmail non-zero exit status in resend_message: $?");
	    }
	    return 0;
	}
	return 1;
    }

    # In the child -- invoke Sendmail

    # Direct stdout to stderr, or we will screw up communication with
    # the multiplexor..
    open(STDOUT, ">&STDERR");

    my(@cmd);
    if ($Sender eq "") {
	push(@cmd, "-f<>");
    } else {
	push(@cmd, "-f$Sender");
    }
    push(@cmd, $deliverymode);
    push(@cmd, "-Ac");
    push(@cmd, "-oi");
    push(@cmd, "--");
    push @cmd, @$recips;

    # In curlies to silence Perl warning...
    my $sm;
    $sm = $Features{'Path:SENDMAIL'};
    { exec($sm, @cmd); }

    # exec failed!
    md_syslog('err', "Could not exec $sm: $!");
    exit(1);
    # NOTREACHED
}

#***********************************************************************
# %PROCEDURE: resend_message
# %ARGUMENTS:
#  recipients -- list of recipients to resend message to.
# %RETURNS:
#  True on success; false on failure.
# %DESCRIPTION:
#  Re-sends the message (as if it came from original sender) to
#  a list of recipients.
#***********************************************************************
sub resend_message {
    return 0 if (!in_message_context("resend_message"));
    my(@recips);
    @recips = @_;
    return resend_message_specifying_mode("-odd", \@recips);
}

#***********************************************************************
# %PROCEDURE: stream_by_recipient
# %ARGUMENTS:
#  None
# %RETURNS:
#  True if message was resent; false if it was for only a single user
# %DESCRIPTION:
#  If there is more than one recipient, re-send the message once per
#  recipient.
#  MAKE SURE your sendmail is set up to use
#  /etc/mail/submit.cf.
#
#  Use this
#  ONLY from filter_begin() and ONLY if you have Sendmail 8.12 or newer,
#  and ONLY if locally-submitted mail goes via SMTP.
#***********************************************************************
sub stream_by_recipient {
    return 0 if (!in_message_context("stream_by_recipient"));
    if ($#Recipients <= 0) {
	# Only one recipient (or none??)
	return 0;
    }

    my($recip);

    foreach $recip (@Recipients) {
	if (!resend_message_one_recipient($recip)) {
	    md_syslog('crit', 'stream_by_recipient: COULD NOT RESEND MESSAGE - PLEASE INVESTIGATE');
	    action_bounce("Unable to stream message");

	    # We return 1 to avoid rest of filter
	    return 1;
	}
    }
    $TerminateAndDiscard = 1;
    return 1;
}

#***********************************************************************
# %PROCEDURE: stream_by_domain
# %ARGUMENTS:
#  None
# %RETURNS:
#  True if message was resent; false if it was for only a single domain.
# %DESCRIPTION:
#  Checks each recipient.  If recipients are in more than one domain
#  (foo@abc.com, foo@xyz.com), the message is re-sent (once per domain),
#  action_discard() is called, and scanning terminates.  Use this
#  ONLY from filter_begin() and ONLY if you have Sendmail 8.12 or newer,
#  and ONLY if locally-submitted mail goes via SMTP.
#***********************************************************************
sub stream_by_domain {
    my(%Domains, $recip, $dom, $nkeys, $key);
    return 0 if (!in_message_context("stream_by_domain"));

    # Grab list of domains of recipients
    foreach $recip (@Recipients) {
	$dom = $recip;
	# Remove angle brackets
	$dom =~ s/[<>]//g;
	# Get domain
	$dom =~ s/.*\@//;
	if (!defined($Domains{$dom})) {
	    $Domains{$dom} = [ $recip ];
	} else {
	    push( @{ $Domains{$dom} }, $recip);
	}
	$Domain = $dom;
    }

    $nkeys = keys(%Domains);
    if ($nkeys > 1) {
	# More than one domain.  Cancel and resend
	foreach $key (keys %Domains) {
	    if (!resend_message(@{$Domains{$key}})) {
		md_syslog('crit', 'stream_by_domain: COULD NOT RESEND MESSAGE - PLEASE INVESTIGATE');
		action_bounce("Unable to stream message");

		# We return 1 to avoid rest of filter
		return 1;
	    }
	}
	$TerminateAndDiscard = 1;
	return 1;
    }

    return 0;
}

=pod 

=head2  takeStabAtFilename ( $entity )

Makes a guess at a filename for the attachment.  Calls MIME::Head's
recommended_filename() method, which tries 'Content-Disposition.filename'and if
not found, 'Content-Type.name'.

Returns a MIME-decoded filename, or a blank string if none found.

=cut

sub takeStabAtFilename
{
	my ($entity) = @_;

	my $guess = $entity->head->recommended_filename();

	if( defined $guess ) {
		return scalar( decode_mimewords( $guess ) );
	}

	return '';
}

#***********************************************************************
# %PROCEDURE: re_match
# %ARGUMENTS:
#  entity -- a MIME entity
#  regexp -- a regular expression
# %RETURNS:
#  1 if either of Content-Disposition.filename or Content-Type.name
#  matches regexp; 0 otherwise.  Matching is
#  case-insensitive
# %DESCRIPTION:
#  A helper function for filter.
#***********************************************************************
sub re_match {
    my($entity, $regexp) = @_;
    my($head) = $entity->head;

    my($guess) = $head->mime_attr("Content-Disposition.filename");
    if (defined($guess)) {
	$guess = decode_mimewords($guess);
	return 1 if $guess =~ /$regexp/i;
    }

    $guess = $head->mime_attr("Content-Type.name");
    if (defined($guess)) {
	$guess = decode_mimewords($guess);
	return 1 if $guess =~ /$regexp/i;
    }

    return 0;
}

#***********************************************************************
# %PROCEDURE: re_match_ext
# %ARGUMENTS:
#  entity -- a MIME entity
#  regexp -- a regular expression
# %RETURNS:
#  1 if the EXTENSION part of either of Content-Disposition.filename or
#  Content-Type.name matches regexp; 0 otherwise.
#  Matching is case-insensitive.
# %DESCRIPTION:
#  A helper function for filter.
#***********************************************************************
sub re_match_ext {
    my($entity, $regexp) = @_;
    my($ext);
    my($head) = $entity->head;

    my($guess) = $head->mime_attr("Content-Disposition.filename");
    if (defined($guess)) {
	$guess = decode_mimewords($guess);
	return 1 if (($guess =~ /(\.[^.]*)$/) && ($1 =~ /$regexp/i));
    }

    $guess = $head->mime_attr("Content-Type.name");
    if (defined($guess)) {
	$guess = decode_mimewords($guess);
	return 1 if (($guess =~ /(\.[^.]*)$/) && ($1 =~ /$regexp/i));
    }

    return 0;
}

#***********************************************************************
# %PROCEDURE: re_match_in_zip_directory
# %ARGUMENTS:
#  fname -- name of ZIP file
#  regexp -- a regular expression
# %RETURNS:
#  1 if the EXTENSION part of any file in the zip archive matches regexp
#  Matching is case-insensitive.
# %DESCRIPTION:
#  A helper function for filter.
#***********************************************************************
no strict 'subs';
sub dummy_zip_error_handler {} ;

sub re_match_in_zip_directory {
    my($zipname, $regexp) = @_;
    unless ($Features{"Archive::Zip"}) {
	md_syslog('err', "Attempted to use re_match_in_zip_directory, but Perl module Archive::Zip is not installed.");
	return 0;
    }
    my $zip = Archive::Zip->new();

    # Prevent carping about errors
    Archive::Zip::setErrorHandler(\&dummy_zip_error_handler);
    if ($zip->read($zipname) == AZ_OK()) {
	foreach my $member ($zip->members()) {
	    my $file = $member->fileName();
	    return 1 if ($file =~ /$regexp/i);
	}
    }

    return 0;
}
use strict 'subs';

#***********************************************************************
# %PROCEDURE: entity_contains_virus_nai
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by NAI uvscan; 0 otherwise.
# %DESCRIPTION:
#  Runs the NAI Virus Scan program on the entity. (http://www.nai.com)
#***********************************************************************
sub entity_contains_virus_nai {

    unless ($Features{'Virus:NAI'}) {
	md_syslog('err', "NAI Virus Scan not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run uvscan
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:NAI'} . " --mime --noboot --secure --allole $path 2>&1", "Found");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }

    # UVScan return codes
    return (wantarray ? interpret_nai_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_nai
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the NAI Virus Scan program on the working directory
#***********************************************************************
sub message_contains_virus_nai {

    unless ($Features{'Virus:NAI'}) {
	md_syslog('err', "NAI Virus Scan not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run uvscan
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:NAI'} . " --noboot --secure --mime --allole ./Work 2>&1", "Found");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    # UVScan return codes
    return (wantarray ? interpret_nai_code($code) : $code);
}

sub interpret_nai_code {
    # Info from Anthony Giggins
    my($code) = @_;
    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # Driver integrity check failed
    return ($code, 'swerr', 'tempfail') if ($code == 2);

    # "A general problem occurred" -- idiot Windoze programmers...
    return ($code, 'swerr', 'tempfail') if ($code == 6);

    # Could not find a driver
    return ($code, 'swerr', 'tempfail') if ($code == 8);

    # Scanner tried to clean a file, but it failed
    return ($code, 'swerr', 'tempfail') if ($code == 12);

    # Virus found
    if ($code == 13) {
	# Sigh... stupid NAI can't have a standard message.  Go through
	# hoops to get virus name.
	my $cm = $CurrentVirusScannerMessage;
	$cm =~ s/ !+//;
	$cm =~ s/!+//;
	if ($VirusName eq "") {
	    $VirusName = "EICAR-Test"
		if ($cm =~ m/Found: EICAR test file/i);
	}
	if ($VirusName eq "") {
	    $VirusName = $1
		if ($cm =~ m/^\s+Found the (\S+) .*virus/i);
	}
	if ($VirusName eq "") {
	    $VirusName = $1
		if ($cm =~ m/Found the (.*) trojan/i);
	}
	if ($VirusName eq "") {
	    $VirusName = $1
		if ($cm =~ m/Found .* or variant (.*)/i);
	}
	$VirusName = "unknown-NAI-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # Self-check failed
    return ($code, 'swerr', 'tempfail') if ($code == 19);

    # User quit using --exit-on-error
    return ($code, 'interrupted', 'tempfail') if ($code == 102);

    # Unknown exit code
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_bdc
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Bitdefender; 0 otherwise.
# %DESCRIPTION:
#  Runs the Bitdefender program on the entity. (http://www.bitdefender.com)
#***********************************************************************
sub entity_contains_virus_bdc {

    unless($Features{'Virus:BDC'}) {
	md_syslog('err', "Bitdefender not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;
    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    if (! ($path =~ m+^/+)) {
	$path = $CWD . "/" . $path;
    }

    # Run bdc
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:BDC'} . " $path --mail 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_bdc_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_bdc
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the Bitdefender program on the working directory
#***********************************************************************
sub message_contains_virus_bdc {

    unless($Features{'Virus:BDC'}) {
	md_syslog('err', "Bitdefender not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run bdc
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:BDC'} . " $CWD/Work --mail --arc 2>&1");
    return (wantarray ? interpret_bdc_code($code) : $code);
}

sub interpret_bdc_code {
    my($code) = @_;

    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # If code is not 0 or 1, it's an internal error
    return ($code, 'swerr', 'tempfail') if ($code != 1);

    # Code is 1 -- virus found.
    $VirusName = $1 if ($CurrentVirusScannerMessage =~ m/(?:suspected|infected)\: (\S+)/);
    $VirusName = "unknown-BDC-virus" if $VirusName eq "";

    return ($code, 'virus', 'quarantine');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_csav
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Command Anti-Virus
# %DESCRIPTION:
#  Runs the Command Anti-Virus program. (http://www.commandsoftware.com)
#***********************************************************************
sub entity_contains_virus_csav {

    unless($Features{'Virus:CSAV'}) {
	md_syslog('err', "Command Anti-Virus not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run csav
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:CSAV'} . " $path 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }

    # csav return codes
    return (wantarray ? interpret_csav_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_csav
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the Command Anti-Virus program on the working directory
#***********************************************************************
sub message_contains_virus_csav {

    unless($Features{'Virus:CSAV'}) {
	md_syslog('err', "Command Anti-Virus not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run csav
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:CSAV'} . " ./Work 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    # csav return codes
    return (wantarray ? interpret_csav_code($code) : $code);
}

sub interpret_csav_code {
    my($code) = @_;
    # OK
    return ($code, 'ok', 'ok') if ($code == 50);

    # Interrupted
    return ($code, 'interrupted', 'tempfail') if ($code == 5);

    # Out of memory
    return ($code, 'swerr', 'tempfail') if ($code == 101);

    # Suspicious files found
    if ($code == 52) {
	$VirusName = 'suspicious';
	return ($code, 'suspicious', 'quarantine');
    }

    # Found a virus
    if ($code == 51) {
	$VirusName = $1 if ($CurrentVirusScannerMessage =~ m/infec.*\: (\S+)/i);
	$VirusName = "unknown-CSAV-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # Found a virus and disinfected
    if ($code == 53) {
	$VirusName = "unknown-CSAV-virus disinfected";
	return ($code, 'virus', 'quarantine');
    }

    # Unknown exit code
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_fsav
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by F-Secure Anti-Virus
# %DESCRIPTION:
#  Runs the F-Secure Anti-Virus program. (http://www.f-secure.com)
#***********************************************************************
sub entity_contains_virus_fsav {

    unless($Features{'Virus:FSAV'}) {
	md_syslog('err', "F-Secure Anti-Virus not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run fsav
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:FSAV'} . " --dumb --mime $path 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }

    # fsav return codes
    return (wantarray ? interpret_fsav_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_fsav
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the F-Secure Anti-Virus program on the working directory
#***********************************************************************
sub message_contains_virus_fsav {

    unless($Features{'Virus:FSAV'}) {
	md_syslog('err', "F-Secure Anti-Virus not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run fsav
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:FSAV'} . " --dumb --mime ./Work 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    # fsav return codes
    return (wantarray ? interpret_fsav_code($code) : $code);
}

sub interpret_fsav_code {
    # Info from David Green
    my($code) = @_;
    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # Abnormal termination
    return ($code, 'swerr', 'tempfail') if ($code == 1);

    # Self-test failed
    return ($code, 'swerr', 'tempfail') if ($code == 2);

    # Found a virus
    if ($code == 3 or $code == 6) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/infec.*\: (\S+)/i);
	$VirusName = "unknown-FSAV-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # Interrupted
    return ($code, 'interrupted', 'tempfail') if ($code == 5);

    # Out of memory
    return ($code, 'swerr', 'tempfail') if ($code == 7);

    # Suspicious files found
    if ($code == 8) {
	$VirusName = 'suspicious';
	return ($code, 'suspicious', 'quarantine');
    }

    # Unknown exit code
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: scan_file_using_fprotd_v6
# %ARGUMENTS:
#  fname -- name of file to scan
#  host -- host and port on which FPROTD version 6 is listening,
#          eg 127.0.0.1:7777
# %RETURNS:
#  A (code, category, action) triplet.  Sets VirusName if virus found.
# %DESCRIPTION:
#  Asks FPROTD version 6 to scan a file.
#***********************************************************************
sub scan_file_using_fprotd_v6
{
    my($fname, $hname) = @_;

    $hname ||= $Fprotd6Host;
    my($host, $port) = split(/:/, $hname);
    $host ||= '127.0.0.1';
    $port ||= 10200;

    my $connect_timeout = 10;
    my $read_timeout = 60;

    # Convert path to absolute
    if (! ($fname =~ m+^/+)) {
	my($cwd);
	chomp($cwd = `pwd`);
	$fname = $cwd . "/" . $fname;
    }

    my $sock = IO::Socket::INET->new(
	PeerAddr => $host,
	PeerPort => $port,
	Timeout => $connect_timeout);

    unless (defined $sock) {
	md_syslog('warning', "Could not connect to FPROTD6 on $host: $!");
	return (999, 'cannot-execute', 'tempfail');
    }

    if (!$sock->print("SCAN --scanlevel=2 --archive=2 --heurlevel=2 --adware --applications FILE $fname\n") || !$sock->flush()) {
	md_syslog('warning', "Error writing to FPROTD6 on $host: $!");
	$sock->close();
	return (999, 'cannot-execute', 'tempfail');
    }

    my $s = IO::Select->new($sock);
    if (!$s->can_read($read_timeout)) {
	$sock->close();
	md_syslog('warning', "Timeout reading from FPROTD6 daemon on $host");
	return (999, 'cannot-execute', 'tempfail');
    }

    my $resp = $sock->getline();
    $sock->close();
    if (!$resp) {
	md_syslog('warning', "Did not get response from FPROTD6 on $host while scanning $fname");
	return (999, 'cannot-execute', 'tempfail');
    }

    my ($code, $desc, $name);
    unless (($code, $desc, $name) = $resp =~ /\A(\d+)\s<(.*?)>\s(.*)\Z/) {
	md_syslog('warning', "Failed to parse response from FPROTD6 for $fname: $resp");
	return (999, 'cannot-execute', 'tempfail');

    }

    # Clean up $desc
    $desc =~ s/\A(?:contains infected objects|infected):\s//i;

    # Our output should contain:
    # 1) A code.  The code is a bitmask of:
    # bit num Meaning
    #  0   1  At least one virus-infected object was found (and remains).
    #  1   2  At least one suspicious (heuristic match) object was found (and remains).
    #  2   4  Interrupted by user. (SIGINT, SIGBREAK).
    #  3   8  Scan restriction caused scan to skip files (maxdepth directories, maxdepth archives, exclusion list, etc).
    #  4  16  Platform error (out of memory, real I/O errors, insufficient file permission etc.).
    #  5  32  Internal engine error (whatever the engine fails at)
    #  6  64  At least one object was not scanned (encrypted file, unsupported/unknown compression method, corrupted or invalid file).
    #  7 128  At least one object was disinfected (clean now) (treat same as virus for File::VirusScan)
    #
    # 2) The description, including virus name
    #
    # 3) The item name, incl. member of archive etc.  We ignore
    # this for now.

    if($code & (1 | 2 | 128)) {
	$VirusName = $desc;
	$VirusName ||= 'unknown-FPROTD6-virus';
	return ($code, 'virus', 'quarantine');
    } elsif($code & 4) {
	md_syslog('warning', 'FPROTD6 scanning interrupted by user');
	return ($code, 'interrupted', 'tempfail');
    } elsif($code & 16) {
	md_syslog('warning', 'FPROTD6 platform error');
	return ($code, 'swerr', 'tempfail');
    } elsif($code & 32) {
	md_syslog('warning', 'FPROTD6 internal engine error');
	return ($code, 'swerr', 'tempfail');
    }

    return(0, 'ok', 'ok');
}

#***********************************************************************
# %PROCEDURE: scan_file_using_carrier_scan
# %ARGUMENTS:
#  fname -- name of file to scan
#  host -- host and port on which Carrier Scan is listening, eg 127.0.0.1:7777
#          Can optionally have :local or :nonlocal appended to force
#          AVSCANLOCAL or AVSCAN
# %RETURNS:
#  A (code, category, action) triplet.  Sets VirusName if virus found.
# %DESCRIPTION:
#  Asks Symantec CarrierScan Server to scan a file.
#***********************************************************************
sub scan_file_using_carrier_scan {
    my($fname, $hname) = @_;

    my($host, $port, $local) = split(/:/, $hname);
    # If not specified, use local scanning for 127.0.0.1, remote for
    # any other.
    unless(defined($local)) {
	if ($host =~ /^127\.0\.0\.1/) {
	    $local = 1;
	} else {
	    $local = 0;
	}
    }

    # Convert from strings
    if ($local eq "local") {
	$local = 1;
    }
    if ($local eq "nonlocal") {
	$local = 0;
    }

    $port = 7777 unless defined($port);

    # Convert path to absolute
    if (! ($fname =~ m+^/+)) {
	my($cwd);
	chomp($cwd = `pwd`);
	$fname = $cwd . "/" . $fname;
    }
    my $sock = IO::Socket::INET->new("$host:$port");
    my ($line);
    unless (defined $sock) {
	md_syslog('warning', "Could not connect to CarrierScan Server on $host: $!");
	return (999, 'cannot-execute', 'tempfail');
    }

    # Read first line of reply from socket
    chomp($line = $sock->getline);
    $line =~ s/\r//g;
    unless ($line =~ /^220/) {
	md_syslog('warning', "Unexpected reply $line from CarrierScan Server");
	$sock->close;
	return (999, 'swerr', 'tempfail');
    }

    # Next line must be version
    chomp($line = $sock->getline);
    $line =~ s/\r//g;
    unless ($line eq "2") {
	md_syslog('warning', "Unexpected version $line from CarrierScan Server");
	$sock->close;
	return(999, 'swerr', 'tempfail');
    }

    # Cool; send our stuff!
    if ($local) {
	if (!$sock->print("Version 2\nAVSCANLOCAL\n$fname\n")) {
	    $sock->close;
	    return (999, 'swerr', 'tempfail');
	}
    } else {
	my ($size);
	my ($chunk);
	my ($chunksize, $nread);
	$size = (stat($fname))[7];
	unless(defined($size)) {
	    md_syslog('warning', "Cannot stat $fname: $!");
	    $sock->close;
	    return(999, 'swerr', 'tempfail');
	}
	if (!$sock->print("Version 2\nAVSCAN\n$fname\n$size\n")) {
	    $sock->close;
	    return (999, 'swerr', 'tempfail');
	}
	unless(open(IN, "<$fname")) {
	    md_syslog('warning', "Cannot open $fname: $!");
	    $sock->close;
	    return(999, 'swerr', 'tempfail');
	}
	while ($size > 0) {
	    if ($size < 8192) {
		$chunksize = $size;
	    } else {
		$chunksize = 8192;
	    }
	    $nread = read(IN, $chunk, $chunksize);
	    unless(defined($nread)) {
		md_syslog('warning', "Error reading $fname: $!");
		$sock->close;
		return(999, 'swerr', 'tempfail');
	    }
	    last if ($nread == 0);
	    if (!$sock->print($chunk)) {
		$sock->close;
		return (999, 'swerr', 'tempfail');
	    }
	    $size -= $nread;
	}
	if ($size > 0) {
	    md_syslog('warning', "Error reading $fname: $!");
	    $sock->close;
	    return(999, 'swerr', 'tempfail');
	}
    }
    if (!$sock->flush) {
	$sock->close;
	return (999, 'swerr', 'tempfail');
    }

    # Get reply from server
    chomp($line = $sock->getline);
    $line =~ s/\r//g;
    unless ($line =~ /^230/) {
	md_syslog('warning', "Unexpected response to AVSCAN or AVSCANLOCAL command: $line");
	$sock->close;
	return(999, 'swerr', 'tempfail');
    }
    # Get infection status
    chomp($line = $sock->getline);
    $line =~ s/\r//g;
    if ($line == 0) {
	$sock->close;
	return (0, 'ok', 'ok');
    }

    # Skip definition date and version, infection count and filename
    chomp($line = $sock->getline); # Definition date
    chomp($line = $sock->getline); # Definition version
    chomp($line = $sock->getline); # Infection count (==1)
    chomp($line = $sock->getline); # Filename

    # Get virus name
    chomp($line = $sock->getline);
    $line =~ s/\r//g;
    $sock->close;

    $VirusName = $line;
    return (1, 'virus', 'quarantine');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_carrier_scan
# %ARGUMENTS:
#  entity -- a MIME entity
#  host (optional) -- Symantec CarrierScan host:port
# %RETURNS:
#  Usual virus status
# %DESCRIPTION:
#  Scans the entity using Symantec CarrierScan
#***********************************************************************
sub entity_contains_virus_carrier_scan {
    my($entity) = shift;
    my($host) = $CSSHost;
    $host = shift if (@_ > 0);
    $host = '127.0.0.1:7777:local' if (!defined($host));
    if (!defined($entity->bodyhandle)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    if (!defined($entity->bodyhandle->path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }
    return scan_file_using_carrier_scan($entity->bodyhandle->path,
					$host);
}

sub entity_contains_virus_fprotd_v6
{
    my($entity, $host) = @_;
    $host ||= $Fprotd6Host;
    if (!defined($entity->bodyhandle)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    if (!defined($entity->bodyhandle->path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }
    return scan_file_using_fprotd_v6($entity->bodyhandle->path,
				     $host);
}

sub message_contains_virus_fprotd_v6
{
    my($host) = @_;
    $host ||= $Fprotd6Host;

    if (!opendir(DIR, "./Work")) {
	md_syslog('err', "message_contains_virus_fprotd_v6: Could not open ./Work directory: $!");
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Scan all files in Work
    my(@files);
    @files = grep { -f "./Work/$_" } readdir(DIR);
    closedir(DIR);

    my($file, $code, $category, $action);
    foreach $file (@files) {
	($code, $category, $action) =
	    scan_file_using_fprotd_v6("Work/$file", $host);
	if ($code != 0) {
	    return (wantarray ? ($code, $category, $action) : $code);
	}
    }
    return (0, 'ok', 'ok');
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_carrier_scan
# %ARGUMENTS:
#  host (optional) -- Symantec CarrierScan host:port
# %RETURNS:
#  Usual virus status
# %DESCRIPTION:
#  Scans the entity using Symantec CarrierScan
#***********************************************************************
sub message_contains_virus_carrier_scan {
    my($host) = $CSSHost;
    $host = shift if (@_ > 0);
    $host = '127.0.0.1:7777:local' if (!defined($host));

    if (!opendir(DIR, "./Work")) {
	md_syslog('err', "message_contains_virus_carrier_scan: Could not open ./Work directory: $!");
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Scan all files in Work
    my(@files);
    @files = grep { -f "./Work/$_" } readdir(DIR);
    closedir(DIR);

    my($file, $code, $category, $action);
    foreach $file (@files) {
	($code, $category, $action) =
	    scan_file_using_carrier_scan("Work/$file", $host);
	if ($code != 0) {
	    return (wantarray ? ($code, $category, $action) : $code);
	}
    }
    return (0, 'ok', 'ok');
}

#***********************************************************************
# %PROCEDURE: item_contains_virus_fprotd
# %ARGUMENTS:
#  item -- a file or directory
#  host (optional) -- Fprotd host and base port.
# %RETURNS:
#  Usual virus status
# %DESCRIPTION:
#  Scans the entity using Fprotd scanning daemon
#***********************************************************************
sub item_contains_virus_fprotd {
    my $item = shift;
    my ($host) = $FprotdHost;
    $host = shift if (@_ > 0);
    $host = '127.0.0.1' if (!defined($host));
    my $baseport = 10200;
    if($host =~ /(.*):(.*)/ ) {
	$host = $1;
	$baseport = $2;
    }

    md_syslog('info', "Scan '$item' via F-Protd \@$host:$baseport");
    # The F-Prot demon cannot scan directories, but files only
    # hence, we recurse any directories manually
    if(-d $item) {
	my @result;
	$host .= ":$baseport";
	foreach my $entry (glob("$item/*")) {
	    @result = &item_contains_virus_fprotd($entry, $host);
	    last if $result[0] != 0;
	}
	return (wantarray ? @result : $result[0]);
    }

    # Default error message when reaching end of function
    my $errmsg = "Could not connect to F-Prot Daemon at $host:$baseport";

    # Try 5 ports in order to find an active scanner; they may change the port
    # when they find and spawn an updated demon executable
SEARCH_DEMON: foreach my $port ($baseport..($baseport+4)) {
    my $sock = IO::Socket::INET->new(PeerAddr => $host, PeerPort => $port);
    if (defined $sock) {

	# The arguments (following the '?' sign in the HTTP request)
	# are the same as for the command line F-Prot, the additional
	# -remote-dtd suppresses the unuseful XML DTD prefix
	if (!$sock->print("GET $item?-dumb%20-archive%20-packed%20-remote-dtd HTTP/1.0\n\n")) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
	if (!$sock->flush) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}

	# Fetch HTTP Header
	## Maybe dropped, if no validation checks are to be made
	while(my $output = $sock->getline) {
	    if($output =~ /^\s*$/) {
		last;	# break line for XML content
		#### Below here: Validating the protocol
		#### If the protocol is not recognized, it's assumed that the
		#### endpoint is not an F-Prot demon, hence,
		#### the next port is probed.
	    } elsif($output =~ /^HTTP(.*)/) {
		my $h = $1;
		next SEARCH_DEMON unless $h =~ m!/1\.0\s+200\s!;
	    } elsif($output =~ /^Server:\s*(\S*)/) {
		next SEARCH_DEMON if $1 !~ /^fprotd/;
	    }
	}

	# Parsing XML results
	my $xml = HTML::TokeParser->new($sock);
	my $t = $xml->get_tag('fprot-results');
	unless($t) {	# This is an essential tag --> assume a broken demon
	    $errmsg = 'Demon did not return <fprot-results> tag';
	    last SEARCH_DEMON;
	}

	if($t->[1]{'version'} ne '1.0') {
	    $errmsg = "Incompatible F-Protd results version: "
		. $t->[1]{'version'};
	    last SEARCH_DEMON;
	}

	my $curText;	# temporarily accumulated information
	my $virii = '';	# name(s) of virus(es) found
	my $code;	# overall exit code
	my $msg = '';	# accumulated message of virus scanner
	while( $t = $xml->get_token ) {
	    my $tag = $t->[1];
	    if($t->[0] eq 'S') {	# Start tag
		# Accumulate the information temporarily
		# into $curText until the </detected> tag is found
		my $text = $xml->get_trimmed_text;
		# $tag 'filename' of no use in MIMEDefang
		if($tag eq 'name') {
		    $virii .= (length $virii ? " " : "" ) . $text;
		    $curText .= "Found the virus: '$text'\n";
		} elsif($tag eq 'accuracy' || $tag eq 'disinfectable' ||
		        $tag eq 'message') {
		    $curText .= "\t$tag: $text\n";
		} elsif($tag eq 'error') {
		    $msg .= "\nError: $text\n";
		} elsif($tag eq 'summary') {
		    $code = $t->[2]{'code'}
		    if defined $t->[2]{'code'};
		}
	    } elsif($t->[0] eq 'E') {	# End tag
		if($tag eq 'detected') {
		    # move the cached information to the
		    # accumulated message
		    $msg .= "\n$curText" if $curText;
		    undef $curText;
		} elsif($tag eq 'fprot-results') {
		    last;	# security check
		}
	    }
	}
	$sock->close;

## Check the exit code (man f-protd)
## NOTE: These codes are different from the ones of the command line version!
#  0      Not scanned, unable to handle the object.
#  1      Not scanned due to an I/O error.
#  2      Not scanned, as the scanner ran out of memory.
#  3  X   The object is not of a type the scanner knows. This
#         may  either mean it was misidentified or that it is
#         corrupted.
#  4  X   The object was valid, but encrypted and  could  not
#         be scanned.
#  5      Scanning of the object was interrupted.
#  7  X   The  object was identified as an "innocent" object.
#  9  X   The object was successfully scanned and nothing was
#         found.
#  11     The object is infected.
#  13     The object was disinfected.
	unless(defined $code) {
	    $errmsg = "No summary code found";
	    last SEARCH_DEMON;
	}
	if($code < 3 # I/O error, unable to handle, out of mem
	   # any filesystem error less than zero
	   || $code == 5) { # interrupted
	    ## assume this a temporary failure
	    $errmsg = "Scan error #$code: $msg";
		last SEARCH_DEMON;
	}

	if($code > 10) { # infected; (disinfected: Should never happen!)
	    # Add the accumulated information
	    $VirusScannerMessages .= $msg;
	    if ( length $virii ) {
		$VirusName = $virii;
	    } elsif ( $msg =~ /^\tmessage:\s+(\S.*)/m ) {
		$VirusName = $1;
	    } else {
                # no virus name found, log message returned by fprot
                $msg =~ s/\s+/ /g;
                md_syslog('info',
                    qq[$MsgID: cannot extract virus name from f-prot: "$msg"]);
                $VirusName = "unknown";
            }
	    return (wantarray ? (1, 'virus', 'quarantine') : 1);
	}
###### These codes are left to be handled:
#  3  X   The object is not of a type the scanner knows. This
#         may  either mean it was misidentified or that it is
#         corrupted.
#  4  X   The object was valid, but encrypted and  could  not
#         be scanned.
#  7  X   The  object was identified as an "innocent" object.
#  9  X   The object was successfully scanned and nothing was

#	9 is trival; 7 is probably trival
#	4 & 3 we can't do anything really, because if the attachement
#	is some unknown archive format, the scanner wouldn't had known
#	this issue anyway, hence, I consider it "clean"

	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
}

    # Could not connect to daemon or some error occured during the
    # communication with it
    $errmsg =~ s/\s*\.*\s*\n+\s*/\. /g;
    md_syslog('err', "$errmsg");
    return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_fprotd
# %ARGUMENTS:
#  entity -- a MIME entity
#  host (optional) -- F-Prot Demon host:port
# %RETURNS:
#  1 if entity contains a virus as reported by F-Prot Demon
# %DESCRIPTION:
#  Invokes the F-Prot daemon (http://www.frisk.org/) on
#  the entity.
#***********************************************************************
sub entity_contains_virus_fprotd {
    my ($entity) = shift;

    if (!defined($entity->bodyhandle)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    if (!defined($entity->bodyhandle->path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    my $path = $entity->bodyhandle->path;
    # If path is not absolute, add cwd
    if (! ($path =~ m+^/+)) {
	$path = $CWD . "/" . $path;
    }
    return item_contains_virus_fprotd($path, $_[0]);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_fprotd
# %ARGUMENTS:
#  host (optional) -- F-Prot Demon host:port
# %RETURNS:
#  1 if entity contains a virus as reported by F-Prot Demon
# %DESCRIPTION:
#  Invokes the F-Prot daemon (http://www.frisk.org/) on
#  the entire message.
#***********************************************************************
sub message_contains_virus_fprotd {
    return item_contains_virus_fprotd ("$CWD/Work", $_[0]);
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_hbedv
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by H+BEDV Antivir; 0 otherwise.
# %DESCRIPTION:
#  Runs the H+BEDV Antivir program on the entity. (http://www.hbedv.com)
#***********************************************************************
sub entity_contains_virus_hbedv {

    unless($Features{'Virus:HBEDV'}) {
	md_syslog('err', "H+BEDV not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;
    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run antivir
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:HBEDV'} . " --allfiles -z -rs $path 2>&1", "!Virus!|>>>|VIRUS:|ALERT:");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_hbedv_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_hbedv
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the H+BEDV Antivir program on the working directory
#***********************************************************************
sub message_contains_virus_hbedv {

    unless($Features{'Virus:HBEDV'}) {
	md_syslog('err', "H+BEDV not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run antivir
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:HBEDV'} . " --allfiles -z -rs ./Work 2>&1", "!Virus!|>>>|VIRUS:|ALERT:");
    return (wantarray ? interpret_hbedv_code($code) : $code);
}

sub interpret_hbedv_code {
    # Based on info from Nels Lindquist, updated by
    # Thorsten Schlichting
    my($code) = @_;

    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # Virus or virus in memory
    if ($code == 1 || $code == 2 || $code == 3) {
	$VirusName = $1 if ($CurrentVirusScannerMessage =~ m/ALERT: \[(\S+)/ or
			    $CurrentVirusScannerMessage =~ /!Virus! \S+ (\S+)/ or
			    $CurrentVirusScannerMessage =~ m/VIRUS: file contains code of the virus '(\S+)'/);
	$VirusName = "unknown-HBEDV-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # All other codes should not happen
    md_syslog('err', "Unknown HBEDV Virus scanner return code: $code");
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_vexira
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Vexira; 0 otherwise.
# %DESCRIPTION:
#  Runs the Vexira program on the entity. (http://www.centralcommand.com)
#***********************************************************************
sub entity_contains_virus_vexira {

    unless($Features{'Virus:VEXIRA'}) {
	md_syslog('err', "Vexira not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;
    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run vexira
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:VEXIRA'} . " -qqq --log=/dev/null --all-files -as $path 2>&1", ": (virus|iworm|macro|mutant|sequence|trojan) ");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_vexira_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_vexira
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the Vexira program on the working directory
#***********************************************************************
sub message_contains_virus_vexira {

    unless($Features{'Virus:VEXIRA'}) {
	md_syslog('err', "Vexira not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run vexira
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:VEXIRA'} . " -qqq --log=/dev/null --all-files -as ./Work 2>&1", ": (virus|iworm|macro|mutant|sequence|trojan) ");
    return (wantarray ? interpret_vexira_code($code) : $code);
}

sub interpret_vexira_code {
    # http://www.centralcommand.com/ts/dl/pdf/scanner_en_vexira.pdf
    my($code) = @_;

    # OK or new file type we don't understand
    return ($code, 'ok', 'ok') if ($code == 0 or $code == 9);

    # Password-protected ZIP or corrupted file
    if ($code == 3 or $code == 5) {
	$VirusName = 'vexira-password-protected-zip';
	return ($code, 'suspicious', 'quarantine');
    }

    # Virus
    if ($code == 1 or $code == 2) {
	$VirusName = $2 if ($CurrentVirusScannerMessage =~ m/: (virus|iworm|macro|mutant|sequence|trojan) (\S+)/);
	$VirusName = "unknown-Vexira-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # All other codes should not happen
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_sophos
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Sophos Sweep
# %DESCRIPTION:
#  Runs the Sophos Sweep program on the entity.
#***********************************************************************
sub entity_contains_virus_sophos {

    unless($Features{'Virus:SOPHOS'}) {
	md_syslog('err', "Sophos Sweep not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;
    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run antivir
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:SOPHOS'} . " -f -mime -all -archive -ss $path 2>&1", "(>>> Virus)|(Password)|(Could not check)");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_sweep_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_savscan
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Sophos Savscan
# %DESCRIPTION:
#  Runs the Sophos Savscan program on the entity.
#***********************************************************************
sub entity_contains_virus_savscan {

    unless($Features{'Virus:SAVSCAN'}) {
	md_syslog('err', "Sophos Savscan not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;
    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run antivir
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:SAVSCAN'} . " -f -mime -all -cab -oe -tnef -archive -ss $path 2>&1", "(>>> Virus)|(Password)|(Could not check)");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_savscan_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_sophos
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the Sophos Sweep program on the working directory
#***********************************************************************
sub message_contains_virus_sophos {

    unless($Features{'Virus:SOPHOS'}) {
	md_syslog('err', "Sophos Sweep not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run antivir
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:SOPHOS'} . " -f -mime -all -archive -ss ./Work 2>&1", "(>>> Virus)|(Password)|(Could not check)");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_sweep_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_savscan
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the Sophos Savscan program on the working directory
#***********************************************************************
sub message_contains_virus_savscan {

    unless($Features{'Virus:SAVSCAN'}) {
	md_syslog('err', "Sophos Savscan not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run antivir
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:SAVSCAN'} . " -f -mime -all -cab -oe -tnef -archive -ss ./Work 2>&1", "(>>> Virus)|(Password)|(Could not check)");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_savscan_code($code) : $code);
}

sub interpret_sweep_code {
    # Based on info from Nicholas Brealey
    my($code) = @_;

    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # Interrupted
    return ($code, 'interrupted', 'tempfail') if ($code == 1);

    # This is technically an error code, but Sophos chokes
    # on a lot of M$ docs with this code, so we let it through...
    return (0, 'ok', 'ok') if ($code == 2);

    # Virus
    if ($code == 3) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/^\s*>>> Virus '(\S+)'/);
	$VirusName = "unknown-Sweep-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # Unknown code
    return ($code, 'swerr', 'tempfail');
}

sub interpret_savscan_code {
    # Based on info from Nicholas Brealey
    my($code) = @_;

    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # Interrupted
    return ($code, 'interrupted', 'tempfail') if ($code == 1);

    # This is technically an error code, but Sophos chokes
    # on a lot of M$ docs with this code, so we let it through...
    return (0, 'ok', 'ok') if ($code == 2);

    # Virus
    if ($code == 3) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/^\s*>>> Virus '(\S+)'/);
	$VirusName = "unknown-Savscan-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # Unknown code
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_clamav
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by clamav
# %DESCRIPTION:
#  Runs the clamav program on the entity.
#***********************************************************************
sub entity_contains_virus_clamav {
    unless ($Features{'Virus:CLAMAV'}) {
	md_syslog('err', "clamav not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run clamscan
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:CLAMAV'} . " --stdout --no-summary --infected $path 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_clamav_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_clamav
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the clamscan program on the working directory
#***********************************************************************
sub message_contains_virus_clamav {
    unless ($Features{'Virus:CLAMAV'}) {
	md_syslog('err', "clamav not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run clamscan
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:CLAMAV'} . " -r --stdout --no-summary --infected ./Work 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_clamav_code($code) : $code);
}

sub interpret_clamav_code {
    my($code) = @_;
    # From info obtained from:
    # clamscan(1)

    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # virus found
    if ($code == 1) {
	$VirusName = $1 if ($CurrentVirusScannerMessage =~ m/: (.+) FOUND/);
	$VirusName = "unknown-Clamav-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # other codes
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_avp5
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Kaspersky 5.x
# %DESCRIPTION:
#  Runs the Kaspersky 5.x aveclient program on the entity.
#***********************************************************************
sub entity_contains_virus_avp5 {
    unless ($Features{'Virus:AVP5'}) {
	md_syslog('err', "Kaspersky aveclient not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run aveclient
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:AVP5'} . " -s -p /var/run/aveserver $path 2>&1","INFECTED");

    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_avp5_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_avp5
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the Kaspersky 5.x aveclient program on the working directory
#***********************************************************************
sub message_contains_virus_avp5 {
    unless ($Features{'Virus:AVP5'}) {
	md_syslog('err', "Kaspersky aveclient not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run aveclient
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:AVP5'} . " -s -p /var/run/aveserver $CWD/Work/* 2>&1","INFECTED");

    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_avp5_code($code) : $code);
}

sub interpret_avp5_code {
    my($code) = @_;
    # From info obtained from:
    # man aveclient (/opt/kav/man/aveclient.8)

    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # Scan incomplete
    return ($code, 'interrupted', 'tempfail') if ($code == 1);

    # "modified or damaged virus" = 2; virus = 4
    if ($code == 2 or $code == 4) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/INFECTED (\S+)/);
	$VirusName = "unknown-AVP5-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # "suspicious" object found
    if ($code == 3) {
	$VirusName = 'suspicious';
	return ($code, 'suspicious', 'quarantine');
    }

    # Disinfected ??
    return ($code, 'ok', 'ok') if ($code == 5);

    # Viruses deleted ??
    return ($code, 'ok', 'ok') if ($code == 6);

    # AVPLinux corrupt or infected
    return ($code, 'swerr', 'tempfail') if ($code == 7);

    # Corrupt objects found -- treat as suspicious
    if ($code == 8) {
	$VirusName = 'suspicious';
	return ($code, 'suspicious', 'quarantine');
    }

    # Anything else shouldn't happen
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_kavscanner
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Kaspersky kavscanner
# %DESCRIPTION:
#  Runs the Kaspersky kavscanner program on the entity.
#***********************************************************************
sub entity_contains_virus_kavscanner {
    unless ($Features{'Virus:KAVSCANNER'}) {
	md_syslog('err', "Kaspersky kavscanner not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run kavscanner
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:KAVSCANNER'} . " -e PASBME -o syslog -i0 $path 2>&1",
						      "INFECTED");

    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_kavscanner_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_kavscanner
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the Kaspersky 5.x aveclient program on the working directory
#***********************************************************************
sub message_contains_virus_kavscanner {
    unless ($Features{'Virus:KAVSCANNER'}) {
	md_syslog('err', "Kaspersky aveclient not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run kavscanner
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:KAVSCANNER'} . " -e PASBME -o syslog -i0 $CWD/Work/* 2>&1",
						      "INFECTED");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_kavscanner_code($code) : $code);
}

sub interpret_kavscanner_code {
    my($code) = @_;
    # From info obtained from:
    # man kavscanner (/opt/kav/man/kavscanner.8)

    # OK
    return ($code, 'ok', 'ok') if ($code == 0 or $code == 5 or $code == 10);

    # Password-protected ZIP
    if ($code == 9) {
	    $VirusName = 'kavscanner-password-protected-zip';
	    return ($code, 'suspicious', 'quarantine');
    }

    # Virus or suspicious TODO: Set virus name
    if ($code == 20 or $code == 21 or $code == 25) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/INFECTED (\S+)/);
	$VirusName = 'unknown-kavscanner-virus' if $VirusName eq "";
	if ($code == 20) {
	    return ($code, 'suspicious', 'quarantine');
	} else {
	    return ($code, 'virus', 'quarantine');
	}
    }

    # Something else
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_avp
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by AVP AvpLinux
# %DESCRIPTION:
#  Runs the AvpLinux program on the entity.
#***********************************************************************
sub entity_contains_virus_avp {

    unless ($Features{'Virus:AVP'}) {
	md_syslog('err', "AVP AvpLinux not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($is_daemon);
    $is_daemon = ($Features{'Virus:AVP'} =~ /kavdaemon$/);
    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run antivir
    my($code, $category, $action);
    if ($is_daemon) {
	# If path is not absolute, add cwd
	if (! ($path =~ m+^/+)) {
	    $path = $CWD . "/" . $path;
	}
	($code, $category, $action) =
	    run_virus_scanner($Features{'Virus:AVP'} . " $CWD -o{$path} -dl -Y -O- -K -I0 -WU=$CWD/DAEMON.RPT 2>&1", "infected");
    } else {
	($code, $category, $action) =
	    run_virus_scanner($Features{'Virus:AVP'} . " -Y -O- -K -I0 $path 2>&1", "infected");
    }
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_avp_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_avp
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the AVP AvpLinux program on the working directory
#***********************************************************************
sub message_contains_virus_avp {

    unless ($Features{'Virus:AVP'}) {
	md_syslog('err', "AVP AvpLinux not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($is_daemon);
    $is_daemon = ($Features{'Virus:AVP'} =~ /kavdaemon$/);

    # Run antivir
    my($code, $category, $action);
    if ($is_daemon) {
	($code, $category, $action) =
	    run_virus_scanner($Features{'Virus:AVP'} . " $CWD -o{$CWD/Work} -dl -Y -O- -K -I0 -WU=$CWD/DAEMON.RPT 2>&1", "infected");
    } else {
	($code, $category, $action) =
	    run_virus_scanner($Features{'Virus:AVP'} . " -Y -O- -K -I0 ./Work 2>&1", "infected");
    }
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_avp_code($code) : $code);
}

sub interpret_avp_code {
    my($code) = @_;
    # From info obtained from:
    # http://sm.msk.ru/patches/violet-avp-sendmail-11.4.patch
    # and from Steve Ladendorf

    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # Scan incomplete
    return ($code, 'interrupted', 'tempfail') if ($code == 1);

    # "modified or damaged virus" = 2; virus = 4
    if ($code == 2 or $code == 4) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/infected\: (\S+)/);
	$VirusName = "unknown-AVP-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # "suspicious" object found
    if ($code == 3) {
	$VirusName = 'suspicious';
	return ($code, 'suspicious', 'quarantine');
    }

    # Disinfected ??
    return ($code, 'ok', 'ok') if ($code == 5);

    # Viruses deleted ??
    return ($code, 'ok', 'ok') if ($code == 6);

    # AVPLinux corrupt or infected
    return ($code, 'swerr', 'tempfail') if ($code == 7);

    # Corrupt objects found -- treat as suspicious
    if ($code == 8) {
	$VirusName = 'suspicious';
	return ($code, 'suspicious', 'quarantine');
    }

    # Anything else shouldn't happen
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_fprot
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by FRISK F-Prot; 0 otherwise.
# %DESCRIPTION:
#  Runs the F-PROT program on the entity. (http://www.f-prot.com)
#***********************************************************************
sub entity_contains_virus_fprot {
    unless ($Features{'Virus:FPROT'}) {
	md_syslog('err', "F-RISK FPROT not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run f-prot
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:FPROT'} . " -DUMB -ARCHIVE -PACKED $path 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }

    # f-prot return codes
    return (wantarray ? interpret_fprot_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_fprot
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the F-RISK f-prot program on the working directory
#***********************************************************************
sub message_contains_virus_fprot {
    unless ($Features{'Virus:FPROT'}) {
	md_syslog('err', "F-RISK f-prot not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run f-prot
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:FPROT'} . " -DUMB -ARCHIVE -PACKED ./Work 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    # f-prot return codes
    return (wantarray ? interpret_fprot_code($code) : $code);
}

sub interpret_fprot_code {
    # Info from
    my($code) = @_;
    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # Unrecoverable error (Missing DAT, etc)
    return ($code, 'swerr', 'tempfail') if ($code == 1);

    # Driver integrity check failed
    return ($code, 'swerr', 'tempfail') if ($code == 2);

    # Virus found
    if ($code == 3) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/Infection\: (\S+)/);
	$VirusName = "unknown-FPROT-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # Reserved for now. Treat as an error
    return ($code, 'swerr', 'tempfail') if ($code == 4);

    # Abnormal termination (scan didn't finish)
    return ($code, 'swerr', 'tempfail') if ($code == 5);

    # At least one virus removed - Should not happen as we aren't
    # requesting disinfection ( at least in this version).
    return ($code, 'swerr', 'tempfail') if ($code == 6);

    # Memory error
    return ($code, 'swerr', 'tempfail') if ($code == 7);

    # Something suspicious was found, but not recognized virus
    # ( uncomment the one your paranoia dictates :) ).
#    return ($code, 'virus', 'quarantine') if ($code == 8);
    return ($code, 'ok', 'ok') if ($code == 8);

    # Unknown exit code
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_fpscan
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by FRISK F-Prot; 0 otherwise.
# %DESCRIPTION:
#  Runs the F-PROT program on the entity. (http://www.f-prot.com)
#***********************************************************************
sub entity_contains_virus_fpscan {
    unless ($Features{'Virus:FPSCAN'}) {
        md_syslog('err', "F-RISK fpscan not installed on this system");
        return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
        return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
        return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run f-prot
    my($code, $category, $action) =
        run_virus_scanner($Features{'Virus:FPSCAN'} . " --report --archive=5  --scanlevel=4 --heurlevel=3 $path 2>&1");
    if ($action ne 'proceed') {
        return (wantarray ? ($code, $category, $action) : $code);
    }

    # f-prot return codes
    return (wantarray ? interpret_fpscan_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_fpscan
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the F-RISK f-prot program on the working directory
#***********************************************************************
sub message_contains_virus_fpscan {
    unless ($Features{'Virus:FPSCAN'}) {
        md_syslog('err', "F-RISK fpscan not installed on this system");
        return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run f-prot
    my($code, $category, $action) =
        run_virus_scanner($Features{'Virus:FPSCAN'} . " --report --archive=5  --scanlevel=4 --heurlevel=3 ./Work 2>&1");
    if ($action ne 'proceed') {
        return (wantarray ? ($code, $category, $action) : $code);
    }
    # f-prot return codes
    return (wantarray ? interpret_fpscan_code($code) : $code);
}

sub interpret_fpscan_code {
    # Info from
    my($code) = @_;

    # Set to 1 to mark heuristic matches as a virus
    my $heuristic_virus = 0;
    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # bit 1 (1)   ==> At least one virus-infected object was found (and
    #                 remains).
    if ($code & 0b1) {
        $VirusName = $1
            if ($CurrentVirusScannerMessage =~ m/^\[Found\s+[^\]]*\]\s+<([^ \t\(>]*)/m);
        $VirusName = "unknown-FPSCAN-virus" if $VirusName eq "";
        return ($code, 'virus', 'quarantine');
    }

    if ($heuristic_virus and $code & 0b10) {
        return ($code, 'virus', 'quarantine');
    }

    # bit 3 (4)   ==> Interrupted by user (SIGINT, SIGBREAK).
    if ($code & 0b100) {
        return ($code, 'swerr', 'tempfail');
    }

    # bit 4 (8)   ==> Scan restriction caused scan to skip files
    #                 (maxdepth directories, maxdepth archives,
    #                 exclusion list, etc).

    if ($code & 0b1000) {
        return ($code, 'swerr', 'tempfail');
    }
    # bit 5 (16)  ==> Platform error (out of memory, real I/O errors,
    #                 insufficient file permission etc.)

    if ($code & 0b10000) {
        return ($code, 'swerr', 'tempfail');
    }

    # bit 6 (32)  ==> Internal engine error (whatever the engine fails
    #                 at)
    if ($code & 0b100000) {
        return ($code, 'swerr', 'tempfail');
    }

    # bit 7 (64)  ==> At least one object was not scanned (encrypted
    #                 file, unsupported/unknown compression method,
    #                 corrupted or invalid file).
    if ($code & 0b1000000) {
        return ($code, 'swerr', 'tempfail');
    }

    # bit 8 (128) ==> At least one object was disinfected (clean now).
    # Should not happen as we aren't requesting disinfection ( at least
    # in this version).
    if ($code & 0b10000000) {
        return ($code, 'swerr', 'tempfail');
    }

    # bit 2 (2)   ==> At least one suspicious (heuristic match) object
    #                 was found (and remains).
    if ($code & 0b10) {
    # ( uncomment the one your paranoia dictates :) ).
        return ($code, 'ok', 'ok');
    }

    # Unknown exit code, this should never happen
    return ($code, 'swerr', 'tempfail');
}


#***********************************************************************
# %PROCEDURE: entity_contains_virus_trend
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Trend Micro vscan
# %DESCRIPTION:
#  Runs the vscan program on the entity.
#***********************************************************************
sub entity_contains_virus_trend {
    unless ($Features{'Virus:TREND'}) {
	md_syslog('err', "TREND vscan not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = @_;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run antivir
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:TREND'} . " -za -a $path 2>&1", "Found ");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_trend_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_trend
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the Trend vscan program on the working directory
#***********************************************************************
sub message_contains_virus_trend {
    unless ($Features{'Virus:TREND'}) {
	md_syslog('err', "TREND Filescanner or Interscan  not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run vscan
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:TREND'} . " -za -a ./Work/* 2>&1", "Found ");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_trend_code($code) : $code);
}

sub interpret_trend_code {
    my($code) = @_;
    # From info obtained from:
    # http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/amavis/amavis/README.scanners

    # OK
    return ($code, 'ok', 'ok') if ($code == 0);

    # virus found
    if ($code >= 1 and $code < 10) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/^\*+ Found virus (\S+)/);
	$VirusName = "unknown-Trend-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # Anything else shouldn't happen
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_nvcc
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by Norman Virus Control(NVCC)
# %DESCRIPTION:
#  Runs the NVCC Anti-Virus program. (http://www.norman.no/)
#***********************************************************************
sub entity_contains_virus_nvcc {

    unless($Features{'Virus:NVCC'}) {
	md_syslog('err', "Norman Virus Control (NVCC) not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    my($entity) = shift;
    my($body) = $entity->bodyhandle;

    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }

    # Run nvcc
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:NVCC'} . " -u -c $path 2>&1");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }

    # nvcc return codes
    return (wantarray ? interpret_nvcc_code($code) : ($code==1 || $code==2));
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_nvcc
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs the NVCC Anti-Virus program on the working directory.
#  (http://www.norman.no/)
#***********************************************************************
sub message_contains_virus_nvcc {

    unless($Features{'Virus:NVCC'}) {
	md_syslog('err', "Norman Virus Control (NVCC) not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }

    # Run nvcc
    my($code, $category, $action) =
	run_virus_scanner($Features{'Virus:NVCC'} . " -u -c -s ./Work 2>&1");

    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    # nvcc return codes
    return (wantarray ? interpret_nvcc_code($code) : ($code==1 || $code==2));
}

sub interpret_nvcc_code {

    my($code) = shift;

    # OK
    return (0, 'ok', 'ok') if ($code == 0);

    # Found a virus
    if ($code == 1 or $code == 2 or $code == 14) {
	$VirusName = $1
	    if ($CurrentVirusScannerMessage =~ m/Possible virus[^']*'(\S+)'$/);
        #' Emacs highlighting goes nuts with unbalanced single-quote...
	$VirusName = "unknown-NVCC-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }

    # Corrupt files/archives found -- treat as suspicious
    if ($code == 11) {
	$VirusName = 'NVCC-suspicious-code-11';
        return ($code, 'suspicious', 'quarantine');
    }

    # No scan area given or something went wrong
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_sophie
# %ARGUMENTS:
#  entity -- a MIME entity
#  sophie_sock (optional) -- Sophie socket path
# %RETURNS:
#  1 if entity contains a virus as reported by Sophie
# %DESCRIPTION:
#  Invokes the Sophie daemon (http://www.vanja.com/tools/sophie/)
#  on the entity.
#***********************************************************************
sub entity_contains_virus_sophie {
    my ($entity) = shift;
    my ($sophie_sock) = $SophieSock;
    $sophie_sock = shift if (@_ > 0);
    $sophie_sock = '/var/spool/MIMEDefang/sophie' if (!defined($sophie_sock));
    if (!defined($entity->bodyhandle)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    if (!defined($entity->bodyhandle->path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }
    my $sock = IO::Socket::UNIX->new(Peer => $sophie_sock);
    if (defined $sock) {
	my $path = $entity->bodyhandle->path;
	# If path is not absolute, add cwd
	if (! ($path =~ m+^/+)) {
	    $path = $CWD . "/" . $path;
	}
	if (!$sock->print("$path\n")) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	if (!$sock->flush) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	my($output);
	if (!$sock->sysread($output,256)) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	if (!$sock->close) {
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	if ($output =~ /^0/) { return (wantarray ? (0, 'ok', 'ok') : 0); }
	elsif ($output =~ /^1/) {
	    $VirusName = "Unknown-sophie-virus";
	    $VirusName = $1 if $output =~ /^1:(.*)$/;
	    $VirusScannerMessages .= "Sophie found the $VirusName virus.\n";
	    return (wantarray ? (1, 'virus', 'quarantine') : 1);
	}
	elsif ($output =~ /^-1/) {
	    my $errmsg = "unknown status";
	    $errmsg = "$1" if $output =~ /^-1:(.*)$/;
	    md_syslog('err', "entity_contains_virus_sophie: $errmsg ($path)");
	    $VirusScannerMessages .= "Sophie error: $errmsg\n";
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	else {
	    md_syslog('err', "entity_contains_virus_sophie: unknown response - $output ($path)");
	    $VirusScannerMessages .= "Sophie error: unknown response - $output\n";
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
    }
    # Could not connect to daemon
    md_syslog('err', "Could not connect to Sophie Daemon at $sophie_sock");
    return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_sophie
# %ARGUMENTS:
#  sophie_sock (optional) -- Sophie socket path
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Invokes the Sophie daemon (http://www.vanja.com/tools/sophie/)
#  on the entire message.
#***********************************************************************
sub message_contains_virus_sophie {
    my ($sophie_sock) = $SophieSock;
    $sophie_sock = shift if (@_ > 0);
    $sophie_sock = '/var/spool/MIMEDefang/sophie' if (!defined($sophie_sock));
    my $sock = IO::Socket::UNIX->new(Peer => $sophie_sock);
    if (defined $sock) {
	if (!$sock->print("$CWD/Work\n")) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	if (!$sock->flush) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	my($output, $ans);
	$ans = $sock->sysread($output, 256);
	if (!defined($ans)) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	if (!$sock->close) {
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	if ($output =~ /^0/) { return (wantarray ? (0, 'ok', 'ok') : 0); }
	elsif ($output =~ /^1/) {
	    $VirusName = "Unknown-sophie-virus";
	    $VirusName = $1 if $output =~ /^1:(.*)$/;
	    $VirusScannerMessages .= "Sophie found the $VirusName virus.\n";
	    return (wantarray ? (1, 'virus', 'quarantine') : 1);
	}
	elsif ($output =~ /^-1/) {
	    my $errmsg = "unknown status";
	    $errmsg = "$1" if $output =~ /^-1:(.*)$/;
	    md_syslog('err', "message_contains_virus_sophie: $errmsg ($CWD/Work)");
	    $VirusScannerMessages .= "Sophie error: $errmsg\n";
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	else {
	    md_syslog('err', "message_contains_virus_sophie: unknown response - $output ($CWD/Work)");
	    $VirusScannerMessages .= "Sophie error: unknown response - $output\n";
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
    }
    # Could not connect to daemon
    md_syslog('err', "Could not connect to Sophie Daemon at $sophie_sock");
    return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_clamd
# %ARGUMENTS:
#  entity -- a MIME entity
#  clamd_sock (optional) -- clamd socket path
# %RETURNS:
#  1 if entity contains a virus as reported by clamd
# %DESCRIPTION:
#  Invokes the clamd daemon (http://www.clamav.net/)
#  on the entity.
#***********************************************************************
sub entity_contains_virus_clamd {
    my ($entity) = shift;
    my ($clamd_sock) = $ClamdSock;
    $clamd_sock = shift if (@_ > 0);
    $clamd_sock = '/var/spool/MIMEDefang/clamd.sock' if (!defined($clamd_sock));
    if (!defined($entity->bodyhandle)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    if (!defined($entity->bodyhandle->path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }
    my $sock = IO::Socket::UNIX->new(Peer => $clamd_sock);
    if (defined $sock) {
	my $path = $entity->bodyhandle->path;
	# If path is not absolute, add cwd
	if (! ($path =~ m+^/+)) {
	    $path = $CWD . "/" . $path;
	}
	if (!$sock->print("SCAN $path\n")) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	if (!$sock->flush) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	my($output, $ans);
	$ans = $sock->sysread($output,256);
	$sock->close;
	if (!defined($ans) || !$ans) {
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	if ($output =~ /: (.+) FOUND/) {
	    $VirusScannerMessages .= "clamd found the $1 virus.\n";
	    $VirusName = $1;
	    return (wantarray ? (1, 'virus', 'quarantine') : 1);
	} elsif ($output =~ /: (.+) ERROR/) {
	    my $err_detail = $1;
	    md_syslog('err', "Clamd returned error: $err_detail");
	    # If it's a zip module failure, try falling back on clamscan.
	    # This is despicable, but it might work
	    if ($err_detail =~ /(?:zip module failure|not supported data format)/i &&
		$Features{'Virus:CLAMAV'}) {
		my ($code, $category, $action) =
		run_virus_scanner($Features{'Virus:CLAMAV'} . " -r --unzip --unrar --stdout --no-summary --infected $CWD/Work 2>&1");
		if ($action ne 'proceed') {
			return (wantarray ? ($code, $category, $action) : $code);
		}
		md_syslog('info', "Falling back on clamscan --unzip --unrar because of Zip module failure in clamd");
		return (wantarray ? interpret_clamav_code($code) : $code);
	    }
	    return (wantarray ? (999, 'swerr', 'tempfail') : 1);
	}
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    # Could not connect to daemon
    md_syslog('err', "Could not connect to clamd Daemon at $clamd_sock");
    return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_clamd
# %ARGUMENTS:
#  clamd_sock (optional) -- clamd socket path
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Invokes the clamd daemon (http://www.clamav.net/)
#  on the entire message.
#***********************************************************************
sub message_contains_virus_clamd {
    my ($clamd_sock) = $ClamdSock;
    $clamd_sock = shift if (@_ > 0);
    $clamd_sock = '/var/spool/MIMEDefang/clamd.sock' if (!defined($clamd_sock));
    my ($output,$sock);

    # PING/PONG test to make sure clamd is alive
    $sock = IO::Socket::UNIX->new(Peer => $clamd_sock);

    if (!defined($sock)) {
	md_syslog('err', "Could not connect to clamd daemon at $clamd_sock");
	return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
    }

    my $s = IO::Select->new();
    $s->add($sock);
    if (!$s->can_write(30)) {
	$sock->close;
	md_syslog('err', "Timeout writing to clamd daemon at $clamd_sock");
	return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
    }

    $sock->print("PING");
    $sock->flush;

    if (!$s->can_read(60)) {
	$sock->close;
	md_syslog('err', "Timeout reading from clamd daemon at $clamd_sock");
	return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
    }

    # Free up memory used by IO::Select object
    undef $s;

    $sock->sysread($output,256);
    $sock->close;
    chomp($output);
    if (! defined($output) || $output ne "PONG") {
	md_syslog('err', "clamd is not responding");
	return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
    }

    # open up a socket and scan each file in ./Work
    $sock = IO::Socket::UNIX->new(Peer => $clamd_sock);
    if (defined $sock) {
	if (!$sock->print("SCAN $CWD/Work\n")) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
	if (!$sock->flush) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
	my $ans;
	$ans = $sock->sysread($output,256);
	$sock->close;
	if (!defined($ans) || !$ans) {
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
	if ($output =~ /: (.+) FOUND/) {
	    $VirusScannerMessages .= "clamd found the $1 virus.\n";
	    $VirusName = $1;
	    return (wantarray ? (1, 'virus', 'quarantine') : 1);
	} elsif ($output =~ /: (.+) ERROR/) {
	    my $err_detail = $1;
	    md_syslog('err', "Clamd returned error: $err_detail");
	    # If it's a zip module failure, try falling back on clamscan.
	    # This is despicable, but it might work
	    if ($err_detail =~ /(?:zip module failure|not supported data format)/i &&
		$Features{'Virus:CLAMAV'}) {
		my ($code, $category, $action) =
		    run_virus_scanner($Features{'Virus:CLAMAV'} . " -r --unzip --unrar --stdout --no-summary --infected $CWD/Work 2>&1");
		if ($action ne 'proceed') {
			return (wantarray ? ($code, $category, $action) : $code);
		}
		md_syslog('info', "Falling back on clamscan --unzip --unrar because of Zip module failure in clamd");
		return (wantarray ? interpret_clamav_code($code) : $code);
	    }
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
    }
    else {
	# Could not connect to daemon
	md_syslog('err', "Could not connect to clamd daemon at $clamd_sock");
	return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
    }
    # No errors, no infected files were found
    return (wantarray ? (0, 'ok', 'ok') : 0);
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_trophie
# %ARGUMENTS:
#  entity -- a MIME entity
#  trophie_sock (optional) -- Trophie socket path
# %RETURNS:
#  1 if entity contains a virus as reported by Trophie
# %DESCRIPTION:
#  Invokes the Trophie daemon (http://www.vanja.com/tools/trophie/)
#  on the entity.
#***********************************************************************
sub entity_contains_virus_trophie {
    my ($entity) = shift;
    my ($trophie_sock) = $TrophieSock;
    $trophie_sock = shift if (@_ > 0);
    $trophie_sock = '/var/spool/MIMEDefang/trophie' if (!defined($trophie_sock));
    if (!defined($entity->bodyhandle)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    if (!defined($entity->bodyhandle->path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }
    my $sock = IO::Socket::UNIX->new(Peer => $trophie_sock);
    if (defined $sock) {
	my $path = $entity->bodyhandle->path;
	# If path is not absolute, add cwd
	if (! ($path =~ m+^/+)) {
	    $path = $CWD . "/" . $path;
	}
	if (!$sock->print("$path\n")) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
	if (!$sock->flush) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
	my($output);
	$sock->sysread($output, 256);
	$sock->close;
	if ($output =~ /^1:(.*)$/) {
	    $VirusScannerMessages .= "Trophie found the $1 virus.\n";
	    $VirusName = $1;
	    return (wantarray ? (1, 'virus', 'quarantine') : 1);
	}
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    # Could not connect to daemon
    md_syslog('err', "Could not connect to Trophie Daemon at $trophie_sock");
    return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_trophie
# %ARGUMENTS:
#  trophie_sock (optional) -- Trophie socket path
# %RETURNS:
#  1 if any file in the working directory contains a virus
# %DESCRIPTION:
#  Invokes the Trophie daemon (http://www.vanja.com/tools/trophie/)
#  on the entire message.
#***********************************************************************
sub message_contains_virus_trophie {
    my ($trophie_sock) = $TrophieSock;
    $trophie_sock = shift if (@_ > 0);
    $trophie_sock = '/var/spool/MIMEDefang/trophie' if (!defined($trophie_sock));
    my $sock = IO::Socket::UNIX->new(Peer => $trophie_sock);
    if (defined $sock) {
	if (!$sock->print("$CWD/Work\n")) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
	if (!$sock->flush) {
	    $sock->close;
	    return (wantarray ? (999, 'swerr', 'tempfail') : 999);
	}
	my($output);
	$sock->sysread($output, 256);
	$sock->close;
	if ($output =~ /^1:(.*)$/) {
	    $VirusScannerMessages .= "Trophie found the $1 virus.\n";
	    $VirusName = $1;
	    return (wantarray ? (1, 'virus', 'quarantine') : 1);
	}
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    # Could not connect to daemon
    md_syslog('err', "Could not connect to Trophie Daemon at $trophie_sock");
    return (wantarray ? (999, 'cannot-execute', 'tempfail') : 999);
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus_nod32
# %ARGUMENTS:
#  entity -- a MIME entity
# %RETURNS:
#  1 if entity contains a virus as reported by NOD32; 0 otherwise.
# %DESCRIPTION:
#  Runs Eset NOD32 program on the entity. (http://www.eset.com)
#***********************************************************************
sub entity_contains_virus_nod32 {
    unless($Features{'Virus:NOD32'}) {
	md_syslog('err', "NOD32 not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }
    my($entity) = @_;
    my($body) = $entity->bodyhandle;
    if (!defined($body)) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }
    # Get filename
    my($path) = $body->path;
    if (!defined($path)) {
	return (wantarray ? (999, 'swerr', 'tempfail') : 1);
    }
    # Run NOD32
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:NOD32'} . " --subdir $path 2>&1", "virus=\"([^\"]+)\"");
    if ($action ne 'proceed') {
	return (wantarray ? ($code, $category, $action) : $code);
    }
    return (wantarray ? interpret_nod32_code($code) : $code);
}

#***********************************************************************
# %PROCEDURE: message_contains_virus_nod32
# %ARGUMENTS:
#  Nothing
# %RETURNS:
#  1 or 2  if any file in the working directory contains a virus
# %DESCRIPTION:
#  Runs Eset NOD32 program on the working directory
#***********************************************************************
sub message_contains_virus_nod32 {
    unless($Features{'Virus:NOD32'}) {
	md_syslog('err', "NOD32 not installed on this system");
	return (wantarray ? (1, 'not-installed', 'tempfail') : 1);
    }
    # Run NOD32
    my($code, $category, $action) = run_virus_scanner($Features{'Virus:NOD32'} . " --subdir ./Work 2>&1", "virus=\"([^\"]+)\"");
    return (wantarray ? interpret_nod32_code($code) : $code);
}

sub interpret_nod32_code {
    my($code) = @_;
    # OK
    return ($code, 'ok', 'ok') if ($code == 0);
    # 1 or 2 -- virus found
    if ($code == 1 || $code == 2) {
	$VirusName = $1 if ($CurrentVirusScannerMessage =~ m/virus=\"([^"]*)/);
	$VirusName = "unknown-NOD32-virus" if $VirusName eq "";
	return ($code, 'virus', 'quarantine');
    }
    # error
    return ($code, 'swerr', 'tempfail');
}

#***********************************************************************
# %PROCEDURE: run_virus_scanner
# %ARGUMENTS:
#  cmdline -- command to run
#  match -- regular expression to match (default ".*")
# %RETURNS:
#  A three-element list: (exitcode, category, recommended_action)
#  exitcode is actual exit code from scanner
#  category is either "cannot-execute" or "ok"
#  recommended_action is either "tempfail" or "proceed"
# %DESCRIPTION:
#  Runs a virus scanner, collecting output in $VirusScannerMessages
#***********************************************************************
sub run_virus_scanner {
    my($cmd, $match) = @_;
    return (999, 'wrong-context', 'tempfail')
	if (!in_message_context("run_virus_scanner"));
    my($retcode);
    my($msg) = "";
    $CurrentVirusScannerMessage = "";

    $match = ".*" unless defined($match);
    unless (open(SCANNER, "$cmd |")) {
	$msg = "Unable to execute $cmd: $!";
	md_syslog('err', "run_virus_scanner: $msg");
	$VirusScannerMessages .= "$msg\n";
	$CurrentVirusScannerMessage = $msg;
	return (999, 'cannot-execute', 'tempfail');
    }
    while(<SCANNER>) {
	$msg .= $_ if /$match/i;
    }
    close(SCANNER);
    $retcode = $? / 256;

    # Some daemons are instructed to save output in a file
    if (open(REPORT, "DAEMON.RPT")) {
	while(<REPORT>) {
	    $msg .= $_ if /$match/i;
	}
	close(REPORT);
	unlink("DAEMON.RPT");
    }

    $VirusScannerMessages .= $msg;
    $CurrentVirusScannerMessage = $msg;
    return ($retcode, 'ok', 'proceed');
}

#***********************************************************************
# %PROCEDURE: action_tempfail
# %ARGUMENTS:
#  reply -- the text reply
#  code -- SMTP reply code (eg: 451)
#  DSN -- DSN code (eg: 4.3.0)
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Tempfails the message with a 4.x.x SMTP code.  If code or DSN are
#  omitted or invalid, use 451 and 4.3.0.
#***********************************************************************
sub action_tempfail {
    my($reply, $code, $dsn) = @_;
    return 0 if (!in_message_context("action_tempfail"));
    $reply = "Try again later" unless (defined($reply) and ($reply ne ""));
    $code = 451 unless (defined($code) and $code =~ /^4\d\d$/);
    $dsn = "4.3.0" unless (defined($dsn) and $dsn =~ /^4\.\d{1,3}\.\d{1,3}$/);

    write_result_line('T', $code, $dsn, $reply);
    $Actions{'tempfail'}++;
    return 1;
}

#***********************************************************************
# %PROCEDURE: pretty_print_mail
# %ARGUMENTS:
#  e -- a MIME::Entity object
#  size -- maximum size of value to return in characters
#  chunk -- optional; used in recursive calls only.  Do not supply as arg.
#  depth -- used in recursive calls only.  Do not supply as arg.
# %RETURNS:
#  A "pretty-printed" version of the e-mail body
# %DESCRIPTION:
#  Makes a pretty-printed version of the e-mail body no longer than size
#  characters.  This odd-looking function is used by CanIt...
#***********************************************************************

sub pretty_print_mail {
    my($e, $size, $chunk, $depth) = @_;
    $chunk = "" unless defined($chunk);
    $depth = 0 unless defined($depth);

    my(@parts) = $e->parts;
    my($type) = $e->mime_type;
    my($fname) = takeStabAtFilename($e);
    $fname = "; filename=$fname" if ($fname ne "");
    my($spaces) = "  " x $depth;
    $chunk .= "\n$spaces" . "[Part: ${type}${fname}]\n\n";
    if ($#parts >= 0) {
	my($part);
	foreach $part (@parts) {
	    $chunk = pretty_print_mail($part, $size, $chunk, $depth+1);
	    last if (length($chunk) >= $size);
	}
    } else {
	return $chunk unless ($type =~ m+^text/+);
	my($body) = $e->bodyhandle;
	return $chunk unless (defined($body));
	my($path) = $body->path;
	return $chunk unless (defined($path));
	return $chunk unless (open(IN, "<$path"));
	while (<IN>) {
	    $chunk .= $_;
	    last if (length($chunk) >= $size);
	}
	close(IN);
    }
    return $chunk;
}

#***********************************************************************
# %PROCEDURE: md_version
# %ARGUMENTS:
#  None
# %RETURNS:
#  MIMEDefang version
#***********************************************************************
sub md_version {
    return '2.83';
}

#***********************************************************************
# %PROCEDURE: main
# %ARGUMENTS:
#  workdir -- directory to "chdir" to and do all work in.
#  msg -- file containing MIME message
# %RETURNS:
#  0 if parse went well; non-zero otherwise.
# %DESCRIPTION:
#  Main program.  Splits the MIME message up and then reconstructs it.
#***********************************************************************
sub main {
    my($Filter);
    my($workdir);
    $Filter = '/etc/mail/mimedefang-filter';

    $DoStatusTags = 0;

    my($ip, $name, $sender, $recip, $firstRecip, $helo, $map, $key);
    # Check for "-f filter-file" option
    if ($#ARGV >= 2) {
	if ($ARGV[0] eq "-f") {
	    $Filter = $ARGV[1];
	    shift @ARGV;
	    shift @ARGV;
	}
    }
    if ($#ARGV != 0) {
	md_syslog('warning', "Usage: mimedefang.pl [-f filter] workdir | -server | -test | -features | -validate");
	print STDERR "Usage: mimedefang.pl [-f filter] workdir | -server | -test | -features | -validate\n";
	return 1;
    }

    $ValidateIPHeader = "";
    if (open(IN, '</etc/mimedefang-ip-key')) {
	$ValidateIPHeader = <IN>;
	chomp($ValidateIPHeader);
	close(IN);
    }

    # These are set unconditionally; filter() can change them.
    $NotifySenderSubject = "MIMEDefang Notification";
    $NotifyAdministratorSubject = "MIMEDefang Notification";
    $QuarantineSubject = "MIMEDefang Quarantine Report";
    $NotifyNoPreamble = 0;

    # Load the filter
    init_globals();
    if ($ValidateIPHeader ne "" and
	$ValidateIPHeader !~ /^X-MIMEDefang-Relay/) {
	md_syslog('err', "Invalid value for mimedefang-ip-key: $ValidateIPHeader");
	$ValidateIPHeader = "";
    }

    if (! -r $Filter) {
	md_syslog('err', "Cannot read filter $Filter: Check permissions.  mimedefang.pl will not work.");
    }

    # Special-case /dev/null so we can invoke without
    # a filter for test purposes.
    unless ($Filter eq '/dev/null') {
	    require $Filter;
    }

    # In case it wasn't done in filter... won't hurt to do it again
    detect_and_load_perl_modules();

    # Backward-compatibility
    if (defined($Administrator)) {
	$AdminAddress = $Administrator;
	md_syslog('warning', 'Variable $Administrator is deprecated.  Use $AdminAddress instead');
    }

    # Defaults
    $AdminName = 'MIMEDefang Administrator' unless defined($AdminName);
    $AdminAddress = 'postmaster@localhost' unless defined($AdminAddress);
    $DaemonName = 'MIMEDefang' unless defined($DaemonName);
    $DaemonAddress = 'mailer-daemon@localhost' unless defined($DaemonAddress);
    $SALocalTestsOnly = 1 unless defined($SALocalTestsOnly);

    if (!defined($GeneralWarning)) {
	$GeneralWarning =
	    "WARNING: This e-mail has been altered by MIMEDefang.  Following this\n" .
	    "paragraph are indications of the actual changes made.  For more\n" .
	    "information about your site's MIMEDefang policy, contact\n" .
	    "$AdminName <$AdminAddress>.  For more information about MIMEDefang, see:\n\n" .
	    "            $URL\n\n";
    }

    # check dir
    $workdir = $ARGV[0];
    if ($workdir eq "-test") {
	printf("Filter $Filter seems syntactically correct.\n");
	exit(0);
    }
    if ($workdir eq "-validate") {
	if (defined(&filter_validate)) {
	    exit(filter_validate());
	}
	print STDERR "ERROR: You must define a function called filter_validate in your filter\nto use the -validate argument.\n";
	exit(1);
    }

    if ($workdir eq "-features") {
	# Print available features
	my($thing, $ans);

	# Print MIMEDefang version
	my $ver = md_version();
	print("MIMEDefang version $ver\n\n");
	# Print the features we have first
	foreach $thing (sort keys %Features) {
	    my($feat);
	    $feat = $Features{$thing};
	    $ans = $feat ? "yes" : "no";
	    if ($ans eq "yes") {
		if ($feat ne "1") {
		    printf("%-30s: %s\n", $thing,  "yes ($feat)");
		} else {
		    printf("%-30s: %s\n", $thing,  "yes");
		}
	    }
	}

	# And now print the ones we don't have
	foreach $thing (sort keys %Features) {
	    my($feat);
	    $feat = $Features{$thing};
	    $ans = $feat ? "yes" : "no";
	    if ($ans eq "no") {
		printf("%-30s: %s\n", $thing,  "no");
	    }
	}

	# And print Perl module versions
	print("\n");
	my($version);
	foreach $thing (qw(Archive::Zip Digest::SHA HTML::Parser IO::Socket IO::Stringy MIME::Base64 MIME::Tools MIME::Words Mail::Mailer Mail::SpamAssassin Net::DNS Unix::Syslog )) {
	    unless (eval "require $thing") {
		printf("%-30s: missing\n", $thing);
		next;
	    }
	    $version = $thing->VERSION();
	    $version = "UNKNOWN" unless defined($version);
	    printf("%-30s: Version %s\n", $thing, $version);
	}
	exit(0);
    }

    my $enter_main_loop;
    if ($workdir eq "-server") {
	$ServerMode = 1;
	$enter_main_loop = 1;
    } elsif ($workdir eq "-serveru") {
	$ServerMode = 1;
	$enter_main_loop = 1;
	$DoStatusTags = 1;
    } elsif ($workdir eq "-embserver") {
	$ServerMode = 1;
	$enter_main_loop = 0;
    } elsif ($workdir eq "-embserveru") {
	$ServerMode = 1;
	$DoStatusTags = 1;
	$enter_main_loop = 0;
    } else {
	$ServerMode = 0;
    }

    if (!$ServerMode) {
	chdir($Features{'Path:SPOOLDIR'});
	if (defined(&filter_initialize)) {
	    filter_initialize();
	}

	init_globals();
	do_scan($workdir);
	exit(0);
    }

    do_main_loop() if $enter_main_loop;
}

=item is_public_ip4_address $ip_addr

Returns true if $ip_addr is a publicly-routable IPv4 address, false otherwise

=cut
sub is_public_ip4_address {
	my ($addr) = @_;
	my @octets = split(/\./, $addr);

	# Sanity check: Return false if it's not an IPv4 address
	return 0 unless (scalar(@octets) == 4);
	foreach my $octet (@octets) {
		return 0 if ($octet !~ /^\d+$/);
		return 0 if ($octet > 255);
	}

	# 10.0.0.0 to 10.255.255.255
	return 0 if ($octets[0] == 10);

	# 172.16.0.0 to 172.31.255.255
	return 0 if ($octets[0] == 172 && $octets[1] >= 16 && $octets[1] <= 31);

	# 192.168.0.0 to 192.168.255.255
	return 0 if ($octets[0] == 192 && $octets[1] == 168);

	# Loopback
	return 0 if ($octets[0] == 127);

	# Local-link for auto-DHCP
	return 0 if ($octets[0] == 169 && $octets[1] == 254);

	# IPv4 multicast
	return 0 if ($octets[0] >= 224 && $octets[0] <= 239);

	# Class E ("Don't Use")
	return 0 if ($octets[0] >= 240 && $octets[0] <= 247);

	# 0.0.0.0 and 255.255.255.255 are bogus
	return 0 if ($octets[0] == 0 &&
		     $octets[1] == 0 &&
		     $octets[2] == 0 &&
		     $octets[3] == 0);

	return 0 if ($octets[0] == 255 &&
		     $octets[1] == 255 &&
		     $octets[2] == 255 &&
		     $octets[3] == 255);
	return 1;
}

=item get_mx_ip_addresses $domain [$resolver_object]

Get IP addresses of all MX hosts for given domain.  If there are
no MX hosts, then return A records.

=cut
sub get_mx_ip_addresses {
	my($domain, $res) = @_;
	my @results;
	unless ($Features{"Net::DNS"}) {
		md_syslog('err', "Attempted to call get_mx_ip_addresses, but Perl module Net::DNS is not installed");
		return @results;
	}
	if (!defined($res)) {
		$res = Net::DNS::Resolver->new;
		$res->defnames(0);
	}

	my $packet = $res->query($domain, 'MX');
	if (!defined($packet) ||
	    $packet->header->rcode eq 'SERVFAIL' ||
	    $packet->header->rcode eq 'NXDOMAIN' ||
	    !defined($packet->answer)) {
		# No MX records; try A records
		$packet = $res->query($domain, 'A');
		if (!defined($packet) ||
		    $packet->header->rcode eq 'SERVFAIL' ||
		    $packet->header->rcode eq 'NXDOMAIN' ||
		    !defined($packet->answer)) {
			return @results;
		}
	}
	foreach my $item ($packet->answer) {
		if ($item->type eq 'MX') {

			# Weird MX record of "." or ""
			# host -t mx yahoo.com.pk for example
			if ($item->exchange eq '' ||
			    $item->exchange eq '.' ||
			    $item->exchange eq '0' ||
			    $item->exchange eq '0 ' ||
			    $item->exchange eq '0 .' ||
			    $item->exchange eq '0.') {
				push(@results, '0.0.0.0');
				next;
			}

			# If it LOOKS like an IPv4 address, don't do
			# an A lookup
			if ($item->exchange =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.?$/) {
				my ($a, $b, $c, $d) = ($1, $2, $3, $4);
				if ($a <= 255 && $b <= 255 && $c <= 255 && $d <= 255) {
					push(@results, "$a.$b.$c.$d");
					next;
				}
			}

			my $packet2 = $res->query($item->exchange, 'A');
			next unless defined($packet2);
			next if $packet2->header->rcode eq 'SERVFAIL';
			next if $packet2->header->rcode eq 'NXDOMAIN';
			next unless defined($packet2->answer);
			foreach my $item2 ($packet2->answer) {
				if ($item2->type eq 'A') {
					push(@results, $item2->address);
				}
			}
		} elsif ($item->type eq 'A') {
			push(@results, $item->address);
		}
	}
	return @results;
}

=item md_get_bogus_mx_hosts $domain

Returns a list of "bogus" IP addresses that are in $domain's list of MX
records.  A "bogus" IP address is loopback/private/multicast/etc.

=cut
#'
sub md_get_bogus_mx_hosts {
	my ($domain) = @_;
	my @bogus_hosts = ();
	my @mx = get_mx_ip_addresses($domain);
	foreach my $mx (@mx) {
		if (!is_public_ip4_address($mx)) {
			push(@bogus_hosts, $mx);
		}
	}
	return @bogus_hosts;
}

sub do_main_loop
{
	init_status_tag();

	chdir($Features{'Path:SPOOLDIR'});
	if(defined(&filter_initialize)) {
		filter_initialize();
	}

	# Infinite server loop... well, not quite infinite; we stop on EOF
	# from STDIN.
	while (my $line = <STDIN>) {
		chomp $line;

		# Clear out vars so they aren't used by filter_begin, etc.
		init_globals();

		# Change to spool dir -- ignore error
		chdir($Features{'Path:SPOOLDIR'});

		my ($cmd, @args) = map { percent_decode($_) } split(/\s+/, $line);
		$cmd = lc $cmd;

		no strict 'refs';
		my $cmd_handler = *{"handle_${cmd}"};
		use strict 'refs';
		if (defined(&{'handle_' . $cmd})) {
			no strict 'refs';
			&{'handle_' . $cmd}(@args);
			use strict 'refs';
		} else {
			unknown_command_handler( $cmd, @args );
		}
	}

	# EOF on STDIN... time to bye-bye...
	if(defined(&filter_cleanup)) {
		exit(filter_cleanup());
	}
	exit(0);
}

# This is the only command handler not named handle_XXXXX for two reasons:
#  1) We don't want someone to pass in a command named 'unknown_command' and
#     get this handler.
#  2) This handler takes $cmd as first argument, whereas the others do not get
#     their own name passed down as the first arg.
sub unknown_command_handler
{
	my ($cmd, @args) = @_;

	if(!defined(&filter_unknown_cmd)) {
		print_and_flush('error: Unknown command');
		return;
	}

	my ($code, @list) = filter_unknown_cmd($cmd, @args);
	$code = "error:" if($code ne "ok" and $code ne "error:");

	my $reply = join(' ', map { percent_encode($_) } ($code, @list) );
	print_and_flush($reply);
}

sub handle_ping
{
	print_and_flush('PONG');
}

sub handle_scan
{
	my ($dummyqid, $workdir) = @_;
	# EVIL FOLLOWS.  AVERT YOUR EYES.
	# File::Spec::Unix caches $ENV{'TMPDIR'}.
	# We want to force it to cache it BEFORE
	# we muck about with the env. variable,
	# otherwise code that uses File::Spec->tmpfile
	# will fail when our transient $workdir/tmp is
	# deleted.  Horrible.

	# FORCE File::Spec to cache a reasonable tmpfile
	File::Spec->tmpdir();

	my $old_tmpdir;
	mkdir("$workdir/tmp");
	if(-d "$workdir/tmp") {
		$old_tmpdir = $ENV{'TMPDIR'};
		$ENV{'TMPDIR'} = "$workdir/tmp";
	} else {
		$old_tmpdir = undef;
	}

	do_scan($workdir);

	# If we set TMPDIR to $workdir/tmp, reset it
	# here.
	if(exists($ENV{'TMPDIR'}) && $ENV{'TMPDIR'} eq "$workdir/tmp")
	{
		if($old_tmpdir) {
			$ENV{'TMPDIR'} = $old_tmpdir;
		} else {
			delete($ENV{'TMPDIR'});
		}
	}

	chdir($Features{'Path:SPOOLDIR'});
}

sub handle_map
{
	my ($map, $key) = @_;

	if(!defined(&filter_map)) {
		md_syslog('err', "No filter_map function defined");
		print_and_flush('PERM No filter_map function defined');
		return;
	}

	my ($code, $val) = filter_map($map, $key);
	if(         $code ne "OK"
		and $code ne "NOTFOUND"
		and $code ne "TEMP"
		and $code ne "TIMEOUT"
		and $code ne "PERM")
	{
		md_syslog('err', "Invalid code from filter_map: $code");
		print_and_flush('PERM Invalid code from filter_map: ' . percent_encode($code));
		return;
	}
	print_and_flush("$code " . percent_encode($val));
}

#***********************************************************************
# %PROCEDURE: handle_tick
# %ARGUMENTS:
#  Tick value (integer)
# %DESCRIPTION:
#  May be called periodically by multiplexor; runs filter_tick routine
#  if it exists.
# %RETURNS:
#  Nothing
#***********************************************************************
sub handle_tick
{
	my ($tick_no) = @_;
	$tick_no ||= 0;
	if(defined(&filter_tick)) {
		filter_tick($tick_no);
		print_and_flush("tock $tick_no");
	} else {
		print_and_flush("error: tick $tick_no: filter_tick undefined");
	}
}

#***********************************************************************
# %PROCEDURE: handle_relayok
# %ARGUMENTS:
#  hostip -- IP address of relay host
#  hostname -- name of relay host
#  port -- client port
#  myip -- my IP address
#  myport -- my listening port
# %RETURNS:
#  Nothing, but prints "ok 1" if we accept connection, "ok 0" if not.
#***********************************************************************
sub handle_relayok
{
	my ($hostip, $hostname, $port, $myip, $myport) = @_;
	if(!defined(&filter_relay)) {
		send_filter_answer('CONTINUE', "ok", "filter_relay", "host $hostip ($hostname)");
		return;
	}

	# Set up globals
	$RelayAddr     = $hostip;
	$RelayHostname = $hostname;
	my ($ok, $msg, $code, $dsn, $delay) = filter_relay($hostip, $hostname, $port, $myip, $myport);
	send_filter_answer($ok, $msg, "filter_relay", "host $hostip ($hostname)", $code, $dsn, $delay);
}

#***********************************************************************
# %PROCEDURE: handle_helook
# %ARGUMENTS:
#  ip -- IP address of relay host
#  name -- name of relay host
#  helo -- arg to SMTP HELO command
#  port -- client port
#  myip -- my IP address
#  myport -- my listening port
# %RETURNS:
#  Nothing, but prints "ok 1" if we accept connections from this host.
# "ok 0" if not.
#***********************************************************************
sub handle_helook
{
	my ($ip, $name, $helo, $port, $myip, $myport) = @_;
	if(!defined(&filter_helo)) {
		send_filter_answer('CONTINUE', "ok", "filter_helo", "helo $helo");
		return;
	}

	# Set up globals
	$RelayAddr     = $ip;
	$RelayHostname = $name;
	$Helo          = $helo;

	my ($ok, $msg, $code, $dsn, $delay) = filter_helo($ip, $name, $helo, $port, $myip, $myport);
	send_filter_answer($ok, $msg, "filter_helo", "helo $helo", $code, $dsn, $delay);
}

#***********************************************************************
# %PROCEDURE: handle_senderok
# %ARGUMENTS:
#  sender -- e-mail address of sender
#  ip -- IP address of relay host
#  name -- name of relay host
#  helo -- arg to SMTP HELO command
# %RETURNS:
#  Nothing, but prints "ok 1" if we accept message from this sender,
# "ok 0" if not.
#***********************************************************************
sub handle_senderok
{
	my ($sender, $ip, $name, $helo);

	($sender, $ip, $name, $helo, $CWD, $QueueID, @ESMTPArgs) = @_;

	if(!defined(&filter_sender)) {
		send_filter_answer('CONTINUE', "ok", "filter_sender", "sender $sender");
		return;
	}

	if (!chdir($CWD)) {
		send_filter_answer('TEMPFAIL', "could not chdir($CWD): $!", "filter_sender", "sender $sender");
	}

	# Set up additional globals
	$MsgID         = $QueueID;
	$Sender        = $sender;
	$RelayAddr     = $ip;
	$RelayHostname = $name;
	$Helo          = $helo;

	my ($ok, $msg, $code, $dsn, $delay) = filter_sender($sender, $ip, $name, $helo);
	send_filter_answer($ok, $msg, "filter_sender", "sender $sender", $code, $dsn, $delay);

	chdir($Features{'Path:SPOOLDIR'});
}

#***********************************************************************
# %PROCEDURE: handle_recipok
# %ARGUMENTS:
#  recipient -- e-mail address of recipient
#  sender -- e-mail address of sender
#  ip -- IP address of relay host
#  name -- name of relay host
#  firstRecip -- first recipient of message
#  helo -- arg to SMTP HELO command
# %RETURNS:
#  Nothing, but prints "ok 1" if we accept message to this recipient,
# "ok 0" if not.
#***********************************************************************
sub handle_recipok
{
	my ($recipient, $sender, $ip, $name, $firstRecip, $helo, $rcpt_mailer, $rcpt_host, $rcpt_addr);

	($recipient, $sender, $ip, $name, $firstRecip, $helo, $CWD, $QueueID, $rcpt_mailer, $rcpt_host, $rcpt_addr, @ESMTPArgs) = @_;
	$MsgID = $QueueID;

	if(!defined(&filter_recipient)) {
		send_filter_answer('CONTINUE', "ok", "filter_recipient", "recipient $recipient");
		return;
	}

	if (!chdir($CWD)) {
		send_filter_answer('TEMPFAIL', "could not chdir($CWD): $!", "filter_recipient", "recipient $recipient");
	}

	# Set up additional globals
	@Recipients    = ($recipient);
	$Sender        = $sender;
	$RelayAddr     = $ip;
	$RelayHostname = $name;
	$Helo          = $helo;
	$RecipientMailers{$recipient} = [ $rcpt_mailer, $rcpt_host, $rcpt_addr ];

	my ($ok, $msg, $code, $dsn, $delay) = filter_recipient($recipient, $sender, $ip, $name, $firstRecip, $helo, $rcpt_mailer, $rcpt_host, $rcpt_addr);
	send_filter_answer($ok, $msg, "filter_recipient", "recipient $recipient", $code, $dsn, $delay);

	chdir($Features{'Path:SPOOLDIR'});
}

sub print_and_flush
{
	local $| = 1;
	print($_[0], "\n");
}

sub init_globals {
    $CWD = $Features{'Path:SPOOLDIR'};
    $InMessageContext = 0;
    $InFilterEnd = 0;
    $InFilterContext = 0;
    $InFilterWrapUp = 0;
    undef $FilterEndReplacementEntity;
    $Action = "";
    $Changed = 0;
    $DefangCounter = 0;
    $Domain = "";
    $MIMEDefangID = "";
    $MsgID = "NOQUEUE";
    $MessageID = "NOQUEUE";
    $Helo = "";
    $QueueID = "NOQUEUE";
    $QuarantineCount = 0;
    $Rebuild = 0;
    $EntireMessageQuarantined = 0;
    $QuarantineSubdir = "";
    $RelayAddr = "";
    $RealRelayAddr = "";
    $WasResent = 0;
    $RelayHostname = "";
    $RealRelayHostname = "";
    $Sender = "";
    $Subject = "";
    $SubjectCount = 0;
    $SuspiciousCharsInHeaders = 0;
    $SuspiciousCharsInBody = 0;
    $TerminateAndDiscard = 0;
    $VirusScannerMessages = "";
    $VirusName = "";
    $WasMultiPart = 0;
    $WarningCounter = 0;
    undef %Actions;
    undef %SendmailMacros;
    undef %RecipientMailers;
    undef %RecipientESMTPArgs;
    undef @FlatParts;
    undef @Recipients;
    undef @Warnings;
    undef @AddedParts;
    undef @StatusTags;
    undef @ESMTPArgs;
    undef @SenderESMTPArgs;
    undef $results_fh;
}

sub builtin_create_parser {
    my $parser = MIME::Parser->new();
    $parser->extract_nested_messages(1);
    $parser->extract_uuencode(1);
    $parser->output_to_core(0);
    $parser->tmp_to_core(0);
    return $parser;
}

#***********************************************************************
# %PROCEDURE: do_scan
# %ARGUMENTS:
#  workdir -- working directory to scan
# %RETURNS:
#  0 if parse went well; non-zero otherwise.
# %DESCRIPTION:
#  Scan a message in working directory.
#***********************************************************************
sub do_scan {
    my($workdir) = @_;

    if (!chdir($workdir)) {
	fatal("Cannot chdir($workdir): $!");
	return -1;
    }

    $CWD = $workdir;

    # Read command file
    push_status_tag("Reading COMMANDS");
    read_commands_file('need_F') or return -1;
    pop_status_tag();

    # We're processing a message
    $InMessageContext = 1;

    # Set message ID
    if ($QueueID ne "") {
	$MsgID = $QueueID;
    } elsif ($MessageID ne "") {
	$MsgID = $MessageID;
    } else {
	$MsgID = "NOQUEUE";
    }

    if ($QueueID eq "") {
	$QueueID = "NOQUEUE";
    }
    if ($MessageID eq "") {
	$MessageID = "NOQUEUE";
    }

    my($file) = "INPUTMSG";

    # Create a subdirectory for storing all the actual message data
    my($msgdir) = "Work";
    if (!mkdir($msgdir, 0750)) {
	fatal("Cannot mkdir($msgdir): $!");
	return -1;
    }

    my $entity;
    my $parser;
    if (defined(&filter_create_parser)) {
	$parser = filter_create_parser();
	if (!defined($parser) ||
	    !$parser->isa('MIME::Parser')) {
	    $parser = builtin_create_parser();
	}
    } else {
	$parser = builtin_create_parser();
    }

    my $filer = MIME::Parser::FileInto->new($msgdir);
    # Don't trust any filenames from the message.
    $filer->ignore_filename(1);
    $parser->filer($filer);

    # Parse the input stream:
    if (!open(FILE, $file)) {
	fatal("couldn't open $file: $!");
	signal_complete();
	return -1;
    }

    if ($MaxMIMEParts > 0) {
	$parser->max_parts($MaxMIMEParts);
    }
    push_status_tag("Parsing Message");
    $entity = $parser->parse(\*FILE);
    pop_status_tag();
    close FILE;

    if (!defined($entity) && $MaxMIMEParts > 0) {
	# Message is too complex; bounce it
	action_bounce("Message contained too many MIME parts.  We do not accept such complicated messages.");
	signal_unchanged();
	signal_complete();
	return;
    }

    if (!$entity) {
	fatal("Couldn't parse MIME in $file: $!");
	signal_complete();
	return -1;
    }

    # Make entity multipart
    my ($code);
    $code = $entity->make_multipart();
    $WasMultiPart = ($code eq 'ALREADY');


    # If there are multiple Subject: lines, delete all but the first
    if ($SubjectCount > 1) {
	md_syslog('warning', "Message contains $SubjectCount Subject: headers.  Deleting all but the first");
	for (my $i=$SubjectCount; $i > 1; $i--) {
	    action_delete_header("Subject", $i);
	}
    }

    # Call pre-scan filter if defined
    if (defined(&filter_begin)) {
	push_status_tag("In filter_begin");
	filter_begin($entity);
	pop_status_tag();
	# If stream_by_domain tells us to discard, do so...
	if ($TerminateAndDiscard) {
	    write_result_line("D", "");
	    signal_unchanged();
	    md_syslog('debug', "filter_begin set TerminateAndDiscard flag.  Don't panic; it's most likely a message being streamed.");
	    signal_complete();
	    return;
	}
    }


    # Now rebuild the message!
    my($boundary);
    my($rebuilt);
    my($rebuilt_flat);

    # Prepare rebuilt container.
    # We don't want a deep copy here, so do some trickery...
    my @parts;

    # Save parts
    @parts = $entity->parts;

    # Clear them out prior to deep copy
    $entity->parts([]);

    # "Deep" copy (ha ha...)
    $rebuilt = $entity->dup;

    # And restore parts to original
    $entity->parts(\@parts);

    # Rebuild
    $InFilterContext = 1;
    push_status_tag("In rebuild loop");
    map { rebuild_entity($rebuilt, $_) } $entity->parts;
    pop_status_tag();

    if ($#Warnings >= 0) {
	my $didSomething = 0;
	my $html_warning;
	$Changed = 1;
	if ($AddWarningsInline) {
	    my $warning = $GeneralWarning . join("\n", @Warnings);
	    my $ruler = "=" x 75;
	    $html_warning = $warning;
	    $html_warning =~ s/&/&amp;/g;
	    $html_warning =~ s/</&lt;/g;
	    $html_warning =~ s/>/&gt;/g;
	    $didSomething = 1
		if append_text_boilerplate($rebuilt, "$ruler\n$warning", 0);
	    $didSomething = 1
		if append_html_boilerplate($rebuilt, "<hr>\n<pre>\n$html_warning</pre>", 0);
	}

	if (!$didSomething) {
	    # HACK for Micro$oft "LookOut!"
	    if ($WasMultiPart &&
		$Stupidity{"NoMultipleInlines"} &&
		$WarningLocation == 0) {
		# Descend into first leaf
		my($msg) = $rebuilt;
		my(@parts) = $msg->parts;
		while($#parts >= 0) {
		    $msg = $parts[0];
		    @parts = $msg->parts;
		}
		my($head) = $msg->head;
		my($type) = $msg->mime_type;
		if (lc($head->mime_type) eq "text/plain") {
		    $head->mime_attr("Content-Type.name" => "MESSAGE.TXT");
		    $head->mime_attr("Content-Disposition" => "inline");
		    $head->mime_attr("Content-Disposition.filename" => "MESSAGE.TXT");
		    $head->mime_attr("Content-Description" => "MESSAGE.TXT");
		}
	    }
	    my $warns = $GeneralWarning . join("\n", @Warnings);
	    $WarningCounter++;
	    action_add_part($rebuilt, "text/plain", "-suggest",
			    $warns, "warning$WarningCounter.txt", "inline", $WarningLocation);
	}
    }

    $InFilterContext = 0;

    # Call post-scan filter if defined
    if (defined(&filter_end)) {
	$InFilterEnd = 1;
	push_status_tag("In filter_end");
	filter_end($rebuilt);
	pop_status_tag();
	$InFilterEnd = 0;
    }

    if ($Rebuild && defined($FilterEndReplacementEntity)) {
	$rebuilt = $FilterEndReplacementEntity;
	undef $FilterEndReplacementEntity;
    }

    if ($Changed || $Rebuild) {
	if (!open(OUT, ">NEWBODY")) {
	    fatal("Can't open NEWBODY: $!");
	    signal_complete();
	    return -1;
	}

	# Add any parts inserted by action_add_part
	$rebuilt = process_added_parts($rebuilt);

	# Trim out useless multiparts.  FIXME: Make this optional?
	while ((lc($rebuilt->head->mime_type) eq "multipart/mixed" ||
		lc($rebuilt->head->mime_type) eq "multipart/alternative") &&
	       $rebuilt->parts == 1 && defined($rebuilt->parts(0))) {
		$rebuilt->make_singlepart();
	}
	push_status_tag("Writing new body");
	$rebuilt->print_body(\*OUT);
	pop_status_tag();
	close(OUT);


	# Write new content-type header in case we've changed the type.
	my $ct = $rebuilt->head->get('Content-Type');
	if (!defined($ct)) {
	    my $type;
	    $type = $rebuilt->mime_type;
	    $boundary = $rebuilt->head->multipart_boundary;
	    if (defined($boundary)) {
		$ct = "$type; boundary=\"$boundary\"";
	    } else {
		$ct = "$type";
	    }
	}
	if (defined($ct)) {
	    chomp($ct);
	    write_result_line("M", $ct);
	}
	# Write out all the other MIME headers associated with the rebuilt
	# entity.
	my($tag, $hdr);
	foreach $tag (grep {/^content-/i} $rebuilt->head->tags) {
	    # Already done content-type
	    next if ($tag =~ /^content-type$/i);
	    if ($tag =~ /^content-transfer-encoding$/i) {
		# If it is now multipart, but wasn't before, we will
		# delete any content-transfer-encoding header.
		if ($rebuilt->head->mime_type =~ m+^multipart/+i &&
		    !$WasMultiPart) {
		    next;
		}
	    }
	    $hdr = $rebuilt->head->get($tag);
	    if (defined($hdr) && $hdr ne "") {
		chomp($hdr);
		action_change_header($tag, $hdr);
	    }
	}
	# If it is now multipart, but wasn't before, delete
	# content-transfer-encoding header.
	if ($rebuilt->head->mime_type =~ m+^multipart/+i &&
	    !$WasMultiPart) {
	    action_delete_header("Content-Transfer-Encoding");
	}
	signal_changed();
    } else {
	signal_unchanged();
    }

    # Call filter_wrapup if defined
    if (defined(&filter_wrapup)) {
	$InFilterWrapUp = 1;
	push_status_tag("In filter_wrapup");
	filter_wrapup($rebuilt);
	pop_status_tag();
	$InFilterWrapUp = 0;
    }

    signal_complete();

    return 0;
}

#***********************************************************************
# %PROCEDURE: read_commands_file
# %ARGUMENTS:
#  needf - if true, will return an error when no closing "F" was found.
#          (optional, default is false). needf should not be set when
#          called from within filter_relay, filter_sender, filter_recipient.
# %RETURNS:
#  true if parse went well,
#  false otherwise
# %DESCRIPTION:
#  Parses the COMMANDS file, and sets these global variables based
#  upon the contents of that file:
#    $Sender
#    @Recipients
#    %RecipientMailers
#    $SuspiciousCharsInHeaders
#    $SuspiciousCharsInBody
#    $RelayAddr
#    $RealRelayAddr
#    $WasResent
#    $RelayHostname
#    $RealRelayHostname
#    $QueueID
#    $Subject
#    $MessageID
#    $Helo
#    %SendmailMacros
#
#***********************************************************************
sub read_commands_file {
    my $needF = shift;
    $needF = 0 unless defined($needF);

    if (!open(IN, "<COMMANDS")) {
	fatal("Cannot open COMMANDS file from mimedefang: $!");
	return 0;
    }

    my($cmd, $arg, $rawcmd, $rawarg, $seenF);

    # Save current recipient if called from filter_recipient
    my @tmp_recipients = @Recipients;
    @Recipients = ();
    $seenF = 0;
    my $recent_recip = "";

    while(<IN>) {
	chomp;
	$rawcmd = $_;
	$cmd = percent_decode($rawcmd);
	$arg = substr($cmd, 1);
	$cmd = substr($cmd, 0, 1);
	$rawarg = substr($rawcmd, 1);

	if ($cmd eq "S") {
	    $Sender = $arg;
	} elsif ($cmd eq "s") {
	    push(@SenderESMTPArgs, $arg);
	} elsif ($cmd eq "F") {
	    $seenF = 1;
	    last;
	} elsif ($cmd eq "R") {
	    my($recip, $rcpt_mailer, $rcpt_host, $rcpt_addr);
	    ($recip, $rcpt_mailer, $rcpt_host, $rcpt_addr) = split(' ', $rawarg);
	    $rcpt_mailer = "?" unless (defined($rcpt_mailer) and ($rcpt_mailer ne ""));
	    $rcpt_host = "?" unless (defined($rcpt_host) and ($rcpt_host ne ""));
	    $rcpt_addr = "?" unless (defined($rcpt_addr) and ($rcpt_addr ne ""));
	    $recip = percent_decode($recip);
	    $rcpt_mailer = percent_decode($rcpt_mailer);
	    $rcpt_host = percent_decode($rcpt_host);
	    $rcpt_addr = percent_decode($rcpt_addr);
	    push(@Recipients, $recip);
	    $RecipientMailers{$recip} = [$rcpt_mailer, $rcpt_host, $rcpt_addr];
	    $recent_recip = $recip;
	} elsif ($cmd eq "r") {
	    push (@{$RecipientESMTPArgs{$recent_recip}}, $arg);
	} elsif ($cmd eq "!") {
	    $SuspiciousCharsInHeaders = 1;
	} elsif ($cmd eq "?") {
	    $SuspiciousCharsInBody    = 1;
	} elsif ($cmd eq "I") {
	    $RelayAddr = $arg;
	    $RealRelayAddr = $arg;
	} elsif ($cmd eq "J") {
	    $WasResent = 1;
	    $RelayAddr = $arg;
	    my($iaddr, $iname);
	    $iaddr = inet_aton($RelayAddr);
	    $iname = gethostbyaddr($iaddr, AF_INET);
	    if (defined($iname)) {
		$RelayHostname = $iname;
	    } else {
		$RelayHostname = "[$RelayAddr]";
	    }
	} elsif ($cmd eq "H") {
	    $RelayHostname = $arg;
	    $RealRelayHostname = $arg;
	} elsif ($cmd eq "Q") {
	    $QueueID = $arg;
	} elsif ($cmd eq "U") {
	    $SubjectCount++;
	    if ($SubjectCount > 1) {
		md_syslog('warning', "Message contains more than one Subject: header: $Subject --> $arg");
  	    } else {
		$Subject = $arg;
	    }
	} elsif ($cmd eq "X") {
	    $MessageID = $arg;
	} elsif ($cmd eq "E") {
	    $Helo = $arg;
	} elsif ($cmd eq "=") {
	    my($macro, $value);
	    ($macro, $value) = split(' ', $rawarg);
	    $value = "" unless defined($value);
	    $macro = "" unless defined($macro);
	    if ($macro ne "") {
		$macro = percent_decode($macro);
		$value = percent_decode($value);
		$SendmailMacros{$macro} = $value;
	    }
	} elsif ($cmd eq "i") {
		$MIMEDefangID = $arg;
	} else {
	    md_syslog('warning', "Unknown command $cmd from mimedefang");
	}
    }
    close(IN);

    if ( $needF && !$seenF ) {
	md_syslog('err', "COMMANDS file from mimedefang did not terminate with 'F' -- check disk space in spool directory");
	fatal("COMMANDS file did not end with F");
        return 0;
    }

    push @Recipients, @tmp_recipients;
    return 1;
}


#***********************************************************************
# %PROCEDURE: replace_entire_message
# %ARGUMENTS:
#  e -- a MIME::Entity
# %RETURNS:
#  1 on success; 0 on failure.
# %DESCRIPTION:
#  Replaces entire message with $e
# %PRECONDITIONS:
#  Can only be called from filter_end
#***********************************************************************
sub replace_entire_message {
    my($e) = @_;
    return 0 unless in_filter_end("replace_entire_message");

    if (!defined($e)) {
	md_syslog('err', "Call to replace_entire_message with undefined argument");
	return 0;
    }
    if (ref($e) ne "MIME::Entity") {
	md_syslog('err', "Call to replace_entire_message with agument that is not of type MIME::Entity");
	return 0;
    }
    $FilterEndReplacementEntity = $e;
    $Rebuild = 1;
    return 1;
}

#***********************************************************************
# %PROCEDURE: remove_redundant_html_parts
# %ARGUMENTS:
#  e -- entity
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Rebuilds $e without redundant HTML parts.  That is, if
#  a multipart/alternative entity contains text/plain and text/html
#  parts, we nuke the text/html part.
#***********************************************************************
sub remove_redundant_html_parts {
    my($e) = @_;
    return 0 unless in_filter_end("remove_redundant_html_parts");

    my(@parts) = $e->parts;
    my($type) = lc($e->mime_type);

    # Don't recurse into multipart/signed or multipart/encrypted
    return 0 if ($type eq "multipart/signed" or
		 $type eq "multipart/encrypted");
    my(@keep, $part);
    my($didsomething);
    $didsomething = 0;
    my($have_text_plain);
    if ($type eq "multipart/alternative" && $#parts >= 0) {
	# First look for a text/plain part
	$have_text_plain = 0;
	foreach $part (@parts) {
	    $type = lc($part->mime_type);
	    if ($type eq "text/plain") {
		$have_text_plain = 1;
		last;
	    }
	}

	# If we have a text/plain part, delete any text/html part
	if ($have_text_plain) {
	    foreach $part (@parts) {
		$type = lc($part->mime_type);
		if ($type ne "text/html") {
		    push(@keep, $part);
		} else {
		    $didsomething = 1;
		}
	    }
	    if ($didsomething) {
		$e->parts(\@keep);
		@parts = @keep;
		$Changed = 1;
	    }
	}
    }
    if ($#parts >= 0) {
	foreach $part (@parts) {
	    $didsomething = 1 if (remove_redundant_html_parts($part));
	}
    }
    return $didsomething;
}

#***********************************************************************
# %PROCEDURE: find_part
# %ARGUMENTS:
#  entity -- root MIME part
#  content_type -- desired MIME content type
#  skip_pgp_mime -- If true, do not descend into multipart/signed or
#                   multipart/encrypted parts
# %RETURNS:
#  First MIME entity of type "$content_type"; undef if none exists.
#***********************************************************************
sub find_part {
    my($entity, $content_type, $skip_pgp_mime) = @_;
    my(@parts);
    my($part);
    my($ans);
    if (!($entity->is_multipart)) {
	if (lc($entity->head->mime_type) eq lc($content_type)) {
	    return $entity;
	} else {
	    return undef;
	}
    }

    if ($skip_pgp_mime &&
	(lc($entity->head->mime_type) eq "multipart/signed" or
	 lc($entity->head->mime_type) eq "multipart/encrypted")) {
	return undef;
    }

    @parts = $entity->parts;
    foreach $part (@parts) {
	$ans = find_part($part, $content_type, $skip_pgp_mime);
	return $ans if defined($ans);
    }
    return undef;
}

#***********************************************************************
# %PROCEDURE: append_to_part
# %ARGUMENTS:
#  part -- a mime entity
#  msg -- text to append to the entity
# %RETURNS:
#  1 on success; 0 on failure.
# %DESCRIPTION:
#  Appends text to $part
#***********************************************************************
sub append_to_part {
    my($part, $boilerplate) = @_;
    return 0 unless defined($part->bodyhandle);
    my($path) = $part->bodyhandle->path;
    return 0 unless (defined($path));
    return 0 unless (open(OUT, ">>$path"));
    print OUT "\n$boilerplate\n";
    close(OUT);
    $Changed = 1;
    return 1;
}

# HTML parser callbacks
sub html_echo {
    my($text) = @_;
    print OUT $text;
}

sub html_end {
    my($text) = @_;
    if (!$HTMLFoundEndBody) {
	if ($text =~ m+<\s*/body+i) {
	    print OUT "$HTMLBoilerplate\n";
	    $HTMLFoundEndBody = 1;
	}
    }
    if (!$HTMLFoundEndBody) {
	if ($text =~ m+<\s*/html+i) {
	    print OUT "$HTMLBoilerplate\n";
	    $HTMLFoundEndBody = 1;
	}
    }

    print OUT $text;
}

#***********************************************************************
# %PROCEDURE: append_to_html_part
# %ARGUMENTS:
#  part -- a mime entity (of type text/html)
#  msg -- text to append to the entity
# %RETURNS:
#  1 on success; 0 on failure.
# %DESCRIPTION:
#  Appends text to $part, but does so by parsing HTML and adding the
#  text before </body> or </html>
#***********************************************************************
sub append_to_html_part {
    my($part, $boilerplate) = @_;

    if (!$Features{"HTML::Parser"}) {
	md_syslog('warning', "Attempt to call append_to_html_part, but HTML::Parser Perl module not installed");
	return 0;
    }
    return 0 unless defined($part->bodyhandle);
    my($path) = $part->bodyhandle->path;
    return 0 unless (defined($path));
    return 0 unless (open(IN, "<$path"));
    if (!open(OUT, ">$path.tmp")) {
	close(IN);
	return(0);
    }

    $HTMLFoundEndBody = 0;
    $HTMLBoilerplate = $boilerplate;
    my($p);
    $p = HTML::Parser->new(api_version => 3,
			   default_h   => [\&html_echo, "text"],
			   end_h       => [\&html_end,  "text"]);
    $p->unbroken_text(1);
    $p->parse_file(*IN);
    if (!$HTMLFoundEndBody) {
	print OUT "\n$boilerplate\n";
    }
    close(IN);
    close(OUT);

    # Rename the path
    return 0 unless rename($path, "$path.old");
    unless (rename("$path.tmp", $path)) {
	rename ("$path.old", $path);
	return 0;
    }
    unlink "$path.old";
    $Changed = 1;
    return 1;
}

#***********************************************************************
# %PROCEDURE: append_text_boilerplate
# %ARGUMENTS:
#  msg -- root MIME entity.
#  boilerplate -- boilerplate text to append
#  all -- if 1, append to ALL text/plain parts.  If 0, append only to
#         FIRST text/plain part.
# %RETURNS:
#  1 if text was appended to at least one part; 0 otherwise.
# %DESCRIPTION:
#  Appends text to text/plain part or parts.
#***********************************************************************
sub append_text_boilerplate {
    my($msg, $boilerplate, $all) = @_;
    my($part);
    if (!$all) {
	$part = find_part($msg, "text/plain", 1);
	if (defined($part)) {
	    if (append_to_part($part, $boilerplate)) {
		$Actions{'append_text_boilerplate'}++;
		return 1;
	    }
	}
	return 0;
    }
    @FlatParts = ();
    my($ok) = 0;
    collect_parts($msg, 1);
    foreach $part (@FlatParts) {
	if (lc($part->head->mime_type) eq "text/plain") {
	    if (append_to_part($part, $boilerplate)) {
		$ok = 1;
		$Actions{'append_text_boilerplate'}++;
	    }
	}
    }
    return $ok;
}

#***********************************************************************
# %PROCEDURE: append_html_boilerplate
# %ARGUMENTS:
#  msg -- root MIME entity.
#  boilerplate -- boilerplate text to append
#  all -- if 1, append to ALL text/html parts.  If 0, append only to
#         FIRST text/html part.
# %RETURNS:
#  1 if text was appended to at least one part; 0 otherwise.
# %DESCRIPTION:
#  Appends text to text/html part or parts.  Tries to be clever and
#  insert the text before the </body> tag so it has a hope in hell of
#  being seen.
#***********************************************************************
sub append_html_boilerplate {
    my($msg, $boilerplate, $all) = @_;
    my($part);
    if (!$all) {
	$part = find_part($msg, "text/html", 1);
	if (defined($part)) {
	    if (append_to_html_part($part, $boilerplate)) {
		$Actions{'append_html_boilerplate'}++;
		return 1;
	    }
	}
	return 0;
    }
    @FlatParts = ();
    my($ok) = 0;
    collect_parts($msg, 1);
    foreach $part (@FlatParts) {
	if (lc($part->head->mime_type) eq "text/html") {
	    if (append_to_html_part($part, $boilerplate)) {
		$ok = 1;
		$Actions{'append_html_boilerplate'}++;
	    }
	}
    }
    return $ok;
}

#***********************************************************************
# %PROCEDURE: action_replace_with_url
# %ARGUMENTS:
#  entity -- part to replace
#  doc_root -- document root in which to place file
#  base_url -- base URL for retrieving document
#  msg -- message to replace document with.  The string "_URL_" is
#         replaced with the actual URL of the part.
#  cd_data -- optional Content-Disposition filename data to save
#  salt    -- optional salt to add to SHA1 hash.
# %RETURNS:
#  1 on success, 0 on failure
# %DESCRIPTION:
#  Places the part in doc_root/{sha1_of_part}.ext and replaces it with
#  a text/plain part giving the URL for pickup.
#***********************************************************************
sub action_replace_with_url {
    my($entity, $doc_root, $base_url, $msg, $cd_data, $salt) = @_;
    my($ctx);
    my($path);
    my($fname, $ext, $name, $url);
    my $extension = "";

    return 0 unless in_filter_context("action_replace_with_url");
    return 0 unless defined($entity->bodyhandle);
    $path = $entity->bodyhandle->path;
    return 0 unless defined($path);
    open(IN, "<$path") or return 0;

    $ctx = Digest::SHA->new;
    $ctx->addfile(*IN);
    $ctx->add($salt) if defined($salt);
    close(IN);

    $fname = takeStabAtFilename($entity);
    $fname = "" unless defined($fname);
    $extension = $1 if ($fname =~ /(\.[^.]*)$/);

    # Use extension if it is .[alpha,digit,underscore]
    $extension = "" unless ($extension =~ /^\.[A-Za-z0-9_]*$/);

    # Filename to save
    $name = $ctx->hexdigest . $extension;
    $fname = $doc_root . "/" . $name;
    $url = $base_url . "/" . $name;

    if (-r $fname) {
	# If file exists, then this is either a duplicate or someone
	# has defeated SHA1.  Just update the mtime on the file.
	my($now);
	$now = time;
	utime($now, $now, $fname);
    } else {
	copy_or_link($path, $fname) or return 0;
	# In case umask is whacked...
	chmod 0644, $fname;
    }

    # save optional Content-Disposition data
    if (defined($cd_data) and ($cd_data ne "")) {
	if (open CDF, ">$doc_root/.$name") {
	    print CDF $cd_data;
	    close CDF;
	    chmod 0644, "$doc_root/.$name";
	}
    }

    $msg =~ s/_URL_/$url/g;
    action_replace_with_warning($msg);
    return 1;
}

#***********************************************************************
# %PROCEDURE: add_recipient
# %ARGUMENTS:
#  recip -- recipient to add
# %RETURNS:
#  0 on failure, 1 on success.
# %DESCRIPTION:
#  Signals to MIMEDefang to add a recipient to the envelope.
#***********************************************************************
sub add_recipient {
    my($recip) = @_;
    write_result_line("R", $recip);
    return 1;
}

#***********************************************************************
# %PROCEDURE: change_sender
# %ARGUMENTS:
#  sender -- new envelope sender
# %RETURNS:
#  0 on failure, 1 on success.
# %DESCRIPTION:
#  Signals to MIMEDefang to change the envelope sender.  Only works on
#  Sendmail 8.14.0 and higher, but no feedback is given to Perl caller!
#***********************************************************************
sub change_sender {
    my($sender) = @_;
    write_result_line("f", $sender);
    return 1;
}

#***********************************************************************
# %PROCEDURE: delete_recipient
# %ARGUMENTS:
#  recip -- recipient to delete
# %RETURNS:
#  0 on failure, 1 on success.
# %DESCRIPTION:
#  Signals to MIMEDefang to delete a recipient from the envelope.
#***********************************************************************
sub delete_recipient {
    my($recip) = @_;
    write_result_line("S", $recip);
    return 1;
}

#***********************************************************************
# %PROCEDURE: spam_assassin_is_spam
# %ARGUMENTS:
#  config -- optional configuration file
# %RETURNS:
#  1 if SpamAssassin thinks current message is SPAM; 0 otherwise
#  or if message could not be opened.
# %DESCRIPTION:
#  Scans message using SpamAssassin (http://www.spamassassin.org)
#***********************************************************************
sub spam_assassin_is_spam {

    my($hits, $req, $tests, $report) = spam_assassin_check(@_);
    return undef if (!defined($hits));

    return ($hits >= $req);
}

#***********************************************************************
# %PROCEDURE: spam_assassin_check
# %ARGUMENTS:
#  config -- optional spamassassin config file
# %RETURNS:
#  An array of four elements,
#       Weight of message ('hits')
#       Number of hits required before SA conciders a message spam
#       Comma separated list of symbolic test names that were triggered
#       A 'report' string, detailing tests that failed and their weights
# %DESCRIPTION:
#  Scans message using SpamAssassin (http://www.spamassassin.org)
#***********************************************************************
sub spam_assassin_check {

    my($status) = spam_assassin_status(@_);
    return undef if (!defined($status));

    my $hits = $status->get_hits;
    my $req = $status->get_required_hits();
    my $tests = $status->get_names_of_tests_hit();
    my $report = $status->get_report();

    $status->finish();

    return ($hits, $req, $tests, $report);
}

#***********************************************************************
# %PROCEDURE: spam_assassin_status
# %ARGUMENTS:
#  config -- optional spamassassin config file
# %RETURNS:
#  A Mail::SpamAssassin:PerMsgStatus object.
#  CALLER IS RESPONSIBLE FOR CALLING finish()
# %DESCRIPTION:
#  Scans message using SpamAssassin (http://www.spamassassin.org)
#***********************************************************************
sub spam_assassin_status {

    my $object = spam_assassin_init(@_);
    return undef unless $object;

    my $mail = spam_assassin_mail();
    return undef unless $mail;

    my $status;
    push_status_tag("Running SpamAssassin");
    $status = $object->check($mail);
    $mail->finish();
    pop_status_tag();
    return $status;
}

#***********************************************************************
# %PROCEDURE: spam_assassin_init
# %ARGUMENTS:
#  config -- optional spamassassin config file
# %RETURNS:
#  A Mail::SpamAssassin object.
# %DESCRIPTION:
#  Scans message using SpamAssassin (http://www.spamassassin.org)
#***********************************************************************
sub spam_assassin_init {
    my($config) = @_;
    my $LOCAL_RULES_DIR = '/etc/spamassassin';
    my $LOCAL_STATE_DIR = '/var/lib';

    unless ($Features{"SpamAssassin"}) {
	md_syslog('err', "Attempt to call SpamAssassin function, but SpamAssassin is not installed.");
	return undef;
    }

    if (!defined($SASpamTester)) {
	if (!defined($config)) {
	    if (-r '/etc/sa-mimedefang.cf') {
		$config = '/etc/sa-mimedefang.cf';
	    } elsif (-r '/etc/mail/sa-mimedefang.cf') {
		$config = '/etc/mail/sa-mimedefang.cf';
	    } elsif (-r '/etc/spamassassin/local.cf') {
		$config = '/etc/spamassassin/local.cf';
	    } else {
		$config = '/etc/spamassassin.cf';
	    }
	}

	push_status_tag("Creating SpamAssasin Object");

	my $sa_args = {
		local_tests_only   => $SALocalTestsOnly,
		dont_copy_prefs    => 1,
		userprefs_filename => $config,
		user_dir           => $Features{'Path:QUARANTINEDIR'},
	};

	# If SpamAssassin version is older than 3.1.5, we must set
	# LOCAL_STATE_DIR or LOCAL_RULES_DIR, because Mail::SpamAssassin
	# doesn't provide a default value.
	if ($Mail::SpamAssassin::VERSION < 3.001005) {
		$sa_args->{LOCAL_STATE_DIR} = $LOCAL_STATE_DIR;
		$sa_args->{LOCAL_RULES_DIR} = $LOCAL_RULES_DIR;
	}
	$SASpamTester = Mail::SpamAssassin->new( $sa_args );
	pop_status_tag();
    }

    return $SASpamTester;
}

#***********************************************************************
# %PROCEDURE: spam_assassin_mail
# %ARGUMENTS:
#  none
# %RETURNS:
#  A Mail::SpamAssassin::Message object
#***********************************************************************
sub spam_assassin_mail {

    unless ($Features{"SpamAssassin"}) {
	md_syslog('err', "Attempt to call SpamAssassin function, but SpamAssassin is not installed.");
	return undef;
    }

    open(IN, "<./INPUTMSG") or return undef;
    my @msg = <IN>;
    close(IN);

    # Synthesize a "Return-Path" and "Received:" header
    my @sahdrs;
    push (@sahdrs, "Return-Path: $Sender\n");
    push (@sahdrs, split(/^/m, synthesize_received_header()));

    if ($AddApparentlyToForSpamAssassin and
	($#Recipients >= 0)) {
	push(@sahdrs, "Apparently-To: " .
	     join(", ", @Recipients) . "\n");
    }
    unshift (@msg, @sahdrs);
    if (!defined($SASpamTester)) {
	spam_assassin_init(@_);
	return undef unless $SASpamTester;
    }
    return $SASpamTester->parse(\@msg);
}

#***********************************************************************
# %PROCEDURE: send_filter_answer
# %ARGUMENTS:
#  ok -- 1 = accept, 0 = reject, -1 = tmpfail
#  msg -- if non-blank, additional message
#  who -- one of "filter_sender", "filter_relay" or "filter_recipient"
#  what -- the address or host being adjusted
#  code -- SMTP reply code
#  dsn -- DSN code
#  delay -- number of seconds C code should delay before returning
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Sends an answer back for filter_relay, filter_sender and filter_recipient
#***********************************************************************
sub send_filter_answer {
    my($ok, $msg, $who, $what, $code, $dsn, $delay) = @_;

    my($num_ok);
    $num_ok = 0;
    # Did we get an integer?

    $delay = 0 unless (defined($delay) and $delay =~ /^\d+$/);

    if ($ok =~ /^-?\d+$/) {
	$num_ok = $ok;
    }

    $msg = "?" if (!defined($msg) or ($msg eq ""));

    if ($ok eq 'ACCEPT_AND_NO_MORE_FILTERING') {
	md_syslog('debug', "$who said ACCEPT_AND_NO_MORE_FILTERING: No further filtering for this message");
	$code = 250 unless (defined($code) and $code =~ /^2\d\d$/);
	$dsn = "2.1.0" unless (defined($dsn) and $dsn =~ /^2\.\d{1,3}\.\d{1,3}$/);
	$msg = percent_encode($msg);
	$code = percent_encode($code);
	$dsn = percent_encode($dsn);
	print_and_flush("ok 2 $msg $code $dsn $delay");
    } elsif ($ok eq 'DISCARD') {
	$code = 250 unless (defined($code) and $code =~ /^2\d\d$/);
	$dsn = "2.1.0" unless (defined($dsn) and $dsn =~ /^2\.\d{1,3}\.\d{1,3}$/);
	$msg = percent_encode($msg);
	$code = percent_encode($code);
	$dsn = percent_encode($dsn);
	md_syslog('info', "$who said DISCARD: Discarding this message");
	print_and_flush("ok 3 $msg $code $dsn $delay");
    } elsif (($ok eq 'CONTINUE') or ($num_ok > 0)) {
	$code = 250 unless (defined($code) and $code =~ /^2\d\d$/);
	$dsn = "2.1.0" unless (defined($dsn) and $dsn =~ /^2\.\d{1,3}\.\d{1,3}$/);
	$msg = percent_encode($msg);
	$code = percent_encode($code);
	$dsn = percent_encode($dsn);
	print_and_flush("ok 1 $msg $code $dsn $delay");
    } elsif (($ok eq 'TEMPFAIL') or ($num_ok < 0)) {
	md_syslog('debug', "$who tempfailed $what");
	$code = 451 unless (defined($code) and $code =~ /^4\d\d$/);
	$dsn = "4.3.0" unless (defined($dsn) and $dsn =~ /^4\.\d{1,3}\.\d{1,3}$/);
	$msg = percent_encode($msg);
	$code = percent_encode($code);
	$dsn = percent_encode($dsn);
	print_and_flush("ok -1 $msg $code $dsn $delay");
    } else {
	$code = 554 unless (defined($code) and $code =~ /^5\d\d$/);
	$dsn = "5.7.1" unless (defined($dsn) and $dsn =~ /^5\.\d{1,3}\.\d{1,3}$/);
	md_syslog('debug', "$who rejected $what");
	$msg = percent_encode($msg);
	$code = percent_encode($code);
	$dsn = percent_encode($dsn);
	print_and_flush("ok 0 $msg $code $dsn $delay");
    }
}

#***********************************************************************
# %PROCEDURE: md_graphdefang_log_enable
# %ARGUMENTS:
#  SyslogFacility -- (optional) The Syslog facility to which mimedefang
#                    should log messages when md_graphdefang_log() is called.  If
#                    this variable is not passed in, a default value
#                    of 'mail' will be used.
#  EnumerateRecipients -- (optional) Whether or not to output a syslog
#                    line for each recipient of a spam message or only
#                    once per incoming message.  Disabling this will
#                    reduce the entries to syslog but will reduce
#                    statistical granularity on a per user basis.
#
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  This is called to enable Mimedefang logging when the md_graphdefang_log()
#  subroutine is called.  The $SyslogFacility name should be known
#  to syslog on the machine on which Mimedefang is running.
#***********************************************************************
sub md_graphdefang_log_enable
{
    $GraphDefangSyslogFacility = shift;
    $EnumerateRecipients = shift;

    # If we don't have a SyslogFacility from the user,
    # use the system default

    $GraphDefangSyslogFacility = $SyslogFacility
	unless defined($GraphDefangSyslogFacility);

    # By default, we want md_graphdefang_log to output a syslog line for each
    # recipient.  This is useful for per user spam statistics.
    # i.e. How many spam messages were received by foo@bar.com?

    $EnumerateRecipients = 1 unless defined($EnumerateRecipients);
}

#***********************************************************************
# %PROCEDURE: add_ip_validation_header
# %ARGUMENTS:
#  None
# %RETURNS:
#  1 if header was added; 0 otherwise
# %DESCRIPTION:
#  Adds an IP address validation header to preserve relay info.
#***********************************************************************
sub add_ip_validation_header {
    if ($ValidateIPHeader eq "") {
	md_syslog('warning', 'add_ip_validation_header called, but no validation header available.  Check permissions on /etc/mimedefang-ip-key');
	return 0;
    }
    action_add_header($ValidateIPHeader, $RelayAddr);
    return 1;
}

#***********************************************************************
# %PROCEDURE: delete_ip_validation_header
# %ARGUMENTS:
#  None
# %RETURNS:
#  1 if header was deleted; 0 otherwise
# %DESCRIPTION:
#  Deletes IP address validation header.
#***********************************************************************
sub delete_ip_validation_header {
    if ($ValidateIPHeader eq "") {
	md_syslog('warning', 'delete_ip_validation_header called, but no validation header available.  Check permissions on /etc/mimedefang-ip-key');
	return 0;
    }
    action_delete_all_headers($ValidateIPHeader);
    return 1;
}

#***********************************************************************
# %PROCEDURE: md_graphdefang_log
# %ARGUMENTS:
#  event -- The name of the event that is being logged.  Examples
#           include virus, spam, mail, etc.
#  value1 -- (optional) A value associated with the event being logged.
#  value2 -- (optional) A value associated with the event being logged.
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  This is called to log events that occur during mimedefang processing.
#  It should be called from mimedefang-filter with appropriate
#  event names and values.  Possible examples:
#      md_graphdefang_log('virus',$VirusName,$filename);
#      md_graphdefang_log('spam',$hits);
#      md_graphdefang_log('bad_filename',$filename,$extension);
#***********************************************************************
sub md_graphdefang_log
{
    return unless defined($GraphDefangSyslogFacility);
    return if (!in_message_context("md_graphdefang_log"));

    my $event = shift;
    my $value1 = shift;
    my $value2 = shift;

    $value1 = "" unless defined($value1);
    $value2 = "" unless defined($value2);

    my $lcsender = percent_encode_for_graphdefang(lc($Sender));

    # Make values safe for graphdefang
    my $id = percent_encode_for_graphdefang($MsgID);
    my $subj = percent_encode_for_graphdefang($Subject);
    $event = percent_encode_for_graphdefang($event);
    $value1 = percent_encode_for_graphdefang($value1);
    $value2 = percent_encode_for_graphdefang($value2);
    if ($EnumerateRecipients || scalar(@Recipients) == 1) {
	foreach my $recipient (@Recipients) {
	    my $lcrecipient = percent_encode_for_graphdefang(lc($recipient));
	    md_syslog("$GraphDefangSyslogFacility|info","MDLOG,$id," .
		      "$event,$value1,$value2,$lcsender," .
		      "$lcrecipient,$subj");
	}
    } else {
	my $lcrecipient = "rcpts=" . scalar(@Recipients);
	$lcrecipient = percent_encode_for_graphdefang($lcrecipient);
	md_syslog("$GraphDefangSyslogFacility|info","MDLOG,$id," .
		  "$event,$value1,$value2,$lcsender," .
		  "$lcrecipient,$subj");
    }
}

#***********************************************************************
# %PROCEDURE: message_contains_virus
# %ARGUMENTS:
#  None
# %RETURNS:
#  ($code, $category, $action) -- standard virus-scanner return values.
# %DESCRIPTION:
#  Scans message using *every single* installed virus scanner.
#***********************************************************************
sub message_contains_virus {
    my($code, $category, $action);
    $code = 0;
    $category = 'ok';
    $action = 'ok';
    initialize_virus_scanner_routines();

    if (!@VirusScannerMessageRoutines) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    my ($scanner, $scode, $scat, $sact);
    push_status_tag("Running virus scanner");
    foreach $scanner (@VirusScannerMessageRoutines) {
	($scode, $scat, $sact) = &$scanner();
	if ($scat eq "virus") {
	    return (wantarray ? ($scode, $scat, $sact) : $scode);
	}
	if ($scat ne "ok") {
	    $code = $scode;
	    $category = $scat;
	    $action = $sact;
	}
    }
    pop_status_tag();
    return (wantarray ? ($code, $category, $action) : $code);
}

#***********************************************************************
# %PROCEDURE: entity_contains_virus
# %ARGUMENTS:
#  e -- a MIME::Entity
# %RETURNS:
#  ($code, $category, $action) -- standard virus-scanner return values.
# %DESCRIPTION:
#  Scans entity using *every single* installed virus scanner.
#***********************************************************************
sub entity_contains_virus {
    my($e) = @_;
    my($code, $category, $action);
    $code = 0;
    $category = 'ok';
    $action = 'ok';

    initialize_virus_scanner_routines();
    if (!@VirusScannerEntityRoutines) {
	return (wantarray ? (0, 'ok', 'ok') : 0);
    }

    my ($scanner, $scode, $scat, $sact);
    push_status_tag("Running virus scanner");
    foreach $scanner (@VirusScannerEntityRoutines) {
	($scode, $scat, $sact) = &$scanner($e);
	if ($scat eq "virus") {
	    return (wantarray ? ($scode, $scat, $sact) : $scode);
	}
	if ($scat ne "ok") {
	    $code = $scode;
	    $category = $scat;
	    $action = $sact;
	}
    }
    pop_status_tag();
    return (wantarray ? ($code, $category, $action) : $code);
}

#***********************************************************************
# %PROCEDURE: initialize_virus_scanner_routines
# %ARGUMENTS:
#  None
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Sets @VirusScannerMessageRoutines and @VirusScannerEntityRoutines
#  to arrays of virus-scanner routines to call, based on installed
#  scanners.
#***********************************************************************
sub initialize_virus_scanner_routines {
    if ($VirusScannerRoutinesInitialized) {
	return;
    }
    $VirusScannerRoutinesInitialized = 1;

    # The daemonized scanners first
    if ($Features{'Virus:CLAMD'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_clamd;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_clamd;
    }

    if ($Features{'Virus:SOPHIE'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_sophie;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_sophie;
    }

    if ($Features{'Virus:TROPHIE'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_trophie;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_trophie;
    }

    if ($Features{'Virus:SymantecCSS'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_carrier_scan;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_carrier_scan;
    }

    if ($Features{'Virus:FPROTD'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_fprotd;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_fprotd;
    }

    if ($Features{'Virus:FPROTD6'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_fprotd_v6;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_fprotd_v6;
    }

    if ($Features{'Virus:AVP5'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_avp5;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_avp5;
    }

    if ($Features{'Virus:KAVSCANNER'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_kavscanner;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_kavscanner;
    }

    # Finally the command-line scanners
    if ($Features{'Virus:CLAMAV'} && ! $Features{'Virus:CLAMD'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_clamav;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_clamav;
    }

    if ($Features{'Virus:AVP'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_avp;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_avp;
    }

    if ($Features{'Virus:NAI'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_nai;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_nai;
    }

    if ($Features{'Virus:FPROT'} && !$Features{'Virus:FPROTD'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_fprot;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_fprot;
    }

    if ($Features{'Virus:FPSCAN'} && !$Features{'Virus:FPROTD6'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_fpscan;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_fpscan;
    }

    if ($Features{'Virus:CSAV'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_csav;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_csav;
    }

    if ($Features{'Virus:FSAV'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_fsav;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_fsav;
    }

    if ($Features{'Virus:HBEDV'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_hbedv;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_hbedv;
    }

    if ($Features{'Virus:BDC'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_bdc;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_bdc;
    }

    if ($Features{'Virus:NVCC'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_nvcc;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_nvcc;
    }

    if ($Features{'Virus:VEXIRA'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_vexira;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_vexira;
    }

    if ($Features{'Virus:SOPHOS'} && ! $Features{'Virus:SOPHIE'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_sophos;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_sophos;
    }

    if ($Features{'Virus:SAVSCAN'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_savscan;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_savscan;
    }

    if ($Features{'Virus:TREND'} && ! $Features{'Virus:TROPHIE'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_trend;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_trend;
    }

    if ($Features{'Virus:NOD32'}) {
	push @VirusScannerMessageRoutines, \&message_contains_virus_nod32;
	push @VirusScannerEntityRoutines, \&entity_contains_virus_nod32;
    }
}

#***********************************************************************
# %PROCEDURE: get_smtp_return_code
# %ARGUMENTS:
#  sock -- a socket connected to an SMTP server
#  recip -- the recipient we're inquring about
#  server -- the server we're querying
# %RETURNS:
#  A four-element list:(retval, code, dsn, text),
#  where code is a 3-digit SMTP code.
#  Retval is 'CONTINUE', 'TEMPFAIL' or 'REJECT'.
# %DESCRIPTION:
#  Reads return codes from SMTP server
#***********************************************************************
sub get_smtp_return_code {
    my($sock, $recip, $server) = @_;
    my($line, $code, $text, $retval, $dsn);
    while (defined ($line = $sock->getline())) {
	# Chew up all white space, including CR
	$line =~ s/\s+$//;
	if (($line =~ /^\d\d\d$/) or ($line =~ /^\d\d\d\s/)) {
	    $line =~ /^(\d\d\d)\s*(.*)$/;
	    $code = $1;
	    $text = $2;
	    # Check for DSN
	    if ($text =~ /^(\d\.\d{1,3}\.\d{1,3})\s+(.*)$/) {
		$dsn = $1;
		$text = $2;
	    } else {
		$dsn = "";
	    }
	    if ($code =~ /^[123]/) {
		$retval = 'CONTINUE';
	    } elsif ($code =~ /^4/) {
		md_syslog('info', "md_check_against_smtp_server for $recip on $server returned $code $dsn $text");
		$retval = 'TEMPFAIL';
	    } elsif ($code =~ /^5/) {
		md_syslog('info', "md_check_against_smtp_server for $recip on $server returned $code $dsn $text");
		$retval = 'REJECT';
	    } else {
		md_syslog('warning', "Invalid SMTP reply code $code from server $server for $recip");
		$retval = 'TEMPFAIL';
	    }
	    return ($retval, $code, $dsn, $text);
	}
    }

    my $msg;
    if( defined $line ) {
        $msg = "Invalid response [$line] from SMTP server";
        md_syslog('info', "md_check_against_smtp_server for $recip on $server returned invalid response [$line]");
    } else {
        $msg = "Empty response from SMTP server";
        md_syslog('info', "md_check_against_smtp_server for $recip on $server returned an empty response");
    }

    return ('TEMPFAIL', "451", "4.3.0", $msg );
}

#***********************************************************************
# %PROCEDURE: md_check_against_smtp_server
# %ARGUMENTS:
#  sender -- sender e-mail address
#  recip -- recipient e-mail address
#  helo -- string to put in "HELO" command
#  server -- SMTP server to try.
#  port   -- optional: Port to connect on (defaults to 25)
# %RETURNS:
#  ('CONTINUE', "OK") if recipient is OK
#  ('TEMPFAIL', "err") if temporary failure
#  ('REJECT', "err") if recipient is not OK.
# %DESCRIPTION:
#  Verifies a recipient against another SMTP server by issuing a
#  HELO / MAIL FROM: / RCPT TO: / QUIT sequence
#***********************************************************************
sub md_check_against_smtp_server {
    my($sender, $recip, $helo, $server, $port) = @_;
    my($code, $text, $dsn, $retval);

    $port = 'smtp(25)' unless defined($port);

    # Add angle-brackets if needed
    if (!($sender =~ /^<.*>$/)) {
	$sender = "<$sender>";
    }

    if (!($recip =~ /^<.*>$/)) {
	$recip = "<$recip>";
    }

    my $sock = IO::Socket::INET->new(PeerAddr => $server,
				     PeerPort => $port,
				     Proto    => 'tcp',
				     Timeout  => 15);
    if (!defined($sock)) {
	return ('TEMPFAIL', "Could not connect to other SMTP server $server: $!");
    }

    ($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
    if ($retval ne 'CONTINUE') {
	$sock->print("QUIT\r\n");
	$sock->flush();
	# Swallow return value
	get_smtp_return_code($sock, $recip, $server);
	$sock->close();
	return ($retval, $text, $code, $dsn);
    }

    # If the banner contains our host name, there's a loop!
    # However, don't check if $server is explicitly 127.0.0.1
    # because presumably that indicates the caller knows
    # what he or she is doing.
    if ($server ne '127.0.0.1' && $server ne '::1') {
	    my $host_expr = quotemeta(get_host_name());
	    if ($text =~ /^$host_expr\b/) {
		    $sock->print("QUIT\r\n");
		    $sock->flush();
		    # Swallow return value
		    get_smtp_return_code($sock, $recip, $server);
		    $sock->close();
		    return('REJECT', "Verification server loop!  Trying to verify $recip against myself!",
			   554, '5.4.6');
	    }
    }

    $sock->print("HELO $helo\r\n");
    $sock->flush();

    ($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
    if ($retval ne 'CONTINUE') {
	$sock->print("QUIT\r\n");
	$sock->flush();
	# Swallow return value
	get_smtp_return_code($sock, $recip, $server);
	$sock->close();
	return ($retval, $text, $code, $dsn);
    }

    $sock->print("MAIL FROM:$sender\r\n");
    $sock->flush();

    ($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
    if ($retval ne 'CONTINUE') {
	$sock->print("QUIT\r\n");
	$sock->flush();
	# Swallow return value
	get_smtp_return_code($sock, $recip, $server);
	$sock->close();
	return ($retval, $text, $code, $dsn);
    }

    $sock->print("RCPT TO:$recip\r\n");
    $sock->flush();

    ($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
    $sock->print("QUIT\r\n");
    $sock->flush();
    # Swallow return value
    get_smtp_return_code($sock, $recip, $server);
    $sock->close();
    return ($retval, $text, $code, $dsn);
}

exit(&main) unless caller;
#------------------------------------------------------------
1;