summaryrefslogtreecommitdiff
path: root/src/deliver.c
blob: 957551590fcde949845d235f7426ff534e7273fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
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
/*
 * Copyright (c) 1983, 1995-1997 Eric P. Allman
 * Copyright (c) 1988, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef lint
static char sccsid[] = "@(#)deliver.c	8.296 (Berkeley) 10/22/97";
#endif /* not lint */

#include "sendmail.h"
#include <errno.h>
#if NAMED_BIND
#include <resolv.h>

extern int	h_errno;
#endif

#if HASSETUSERCONTEXT
# include <login_cap.h>
#endif

#if SMTP
extern char	SmtpError[];
#endif

/*
**  SENDALL -- actually send all the messages.
**
**	Parameters:
**		e -- the envelope to send.
**		mode -- the delivery mode to use.  If SM_DEFAULT, use
**			the current e->e_sendmode.
**
**	Returns:
**		none.
**
**	Side Effects:
**		Scans the send lists and sends everything it finds.
**		Delivers any appropriate error messages.
**		If we are running in a non-interactive mode, takes the
**			appropriate action.
*/

void
sendall(e, mode)
	ENVELOPE *e;
	int mode;
{
	register ADDRESS *q;
	char *owner;
	int otherowners;
	register ENVELOPE *ee;
	ENVELOPE *splitenv = NULL;
	int oldverbose = Verbose;
	bool somedeliveries = FALSE, expensive = FALSE;
	pid_t pid;
	extern void sendenvelope();

	/*
	**  If we have had global, fatal errors, don't bother sending
	**  the message at all if we are in SMTP mode.  Local errors
	**  (e.g., a single address failing) will still cause the other
	**  addresses to be sent.
	*/

	if (bitset(EF_FATALERRS, e->e_flags) &&
	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
	{
		e->e_flags |= EF_CLRQUEUE;
		return;
	}

	/* determine actual delivery mode */
	if (mode == SM_DEFAULT)
	{
		mode = e->e_sendmode;
		if (mode != SM_VERIFY && mode != SM_DEFER &&
		    shouldqueue(e->e_msgpriority, e->e_ctime))
			mode = SM_QUEUE;
	}

	if (tTd(13, 1))
	{
		extern void printenvflags();

		printf("\n===== SENDALL: mode %c, id %s, e_from ",
			mode, e->e_id);
		printaddr(&e->e_from, FALSE);
		printf("\te_flags = ");
		printenvflags(e);
		printf("sendqueue:\n");
		printaddr(e->e_sendqueue, TRUE);
	}

	/*
	**  Do any preprocessing necessary for the mode we are running.
	**	Check to make sure the hop count is reasonable.
	**	Delete sends to the sender in mailing lists.
	*/

	CurEnv = e;
	if (tTd(62, 1))
		checkfds(NULL);

	if (e->e_hopcount > MaxHopCount)
	{
		errno = 0;
#if QUEUE
		queueup(e, mode == SM_QUEUE || mode == SM_DEFER);
#endif
		e->e_flags |= EF_FATALERRS|EF_PM_NOTIFY|EF_CLRQUEUE;
		syserr("554 Too many hops %d (%d max): from %s via %s, to %s",
			e->e_hopcount, MaxHopCount, e->e_from.q_paddr,
			RealHostName == NULL ? "localhost" : RealHostName,
			e->e_sendqueue->q_paddr);
		e->e_sendqueue->q_status = "5.4.6";
		return;
	}

	/*
	**  Do sender deletion.
	**
	**	If the sender has the QQUEUEUP flag set, skip this.
	**	This can happen if the name server is hosed when you
	**	are trying to send mail.  The result is that the sender
	**	is instantiated in the queue as a recipient.
	*/

	if (!bitset(EF_METOO, e->e_flags) &&
	    !bitset(QQUEUEUP, e->e_from.q_flags))
	{
		if (tTd(13, 5))
		{
			printf("sendall: QDONTSEND ");
			printaddr(&e->e_from, FALSE);
		}
		e->e_from.q_flags |= QDONTSEND;
		(void) recipient(&e->e_from, &e->e_sendqueue, 0, e);
	}

	/*
	**  Handle alias owners.
	**
	**	We scan up the q_alias chain looking for owners.
	**	We discard owners that are the same as the return path.
	*/

	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
	{
		register struct address *a;

		for (a = q; a != NULL && a->q_owner == NULL; a = a->q_alias)
			continue;
		if (a != NULL)
			q->q_owner = a->q_owner;

		if (q->q_owner != NULL &&
		    !bitset(QDONTSEND, q->q_flags) &&
		    strcmp(q->q_owner, e->e_from.q_paddr) == 0)
			q->q_owner = NULL;
	}

	if (tTd(13, 25))
	{
		printf("\nAfter first owner pass, sendq =\n");
		printaddr(e->e_sendqueue, TRUE);
	}

	owner = "";
	otherowners = 1;
	while (owner != NULL && otherowners > 0)
	{
		if (tTd(13, 28))
			printf("owner = \"%s\", otherowners = %d\n",
				owner, otherowners);
		owner = NULL;
		otherowners = bitset(EF_SENDRECEIPT, e->e_flags) ? 1 : 0;

		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
		{
			if (tTd(13, 30))
			{
				printf("Checking ");
				printaddr(q, FALSE);
			}
			if (bitset(QDONTSEND, q->q_flags))
			{
				if (tTd(13, 30))
					printf("    ... QDONTSEND\n");
				continue;
			}
			if (tTd(13, 29) && !tTd(13, 30))
			{
				printf("Checking ");
				printaddr(q, FALSE);
			}

			if (q->q_owner != NULL)
			{
				if (owner == NULL)
				{
					if (tTd(13, 40))
						printf("    ... First owner = \"%s\"\n",
							q->q_owner);
					owner = q->q_owner;
				}
				else if (owner != q->q_owner)
				{
					if (strcmp(owner, q->q_owner) == 0)
					{
						if (tTd(13, 40))
							printf("    ... Same owner = \"%s\"\n",
								owner);

						/* make future comparisons cheap */
						q->q_owner = owner;
					}
					else
					{
						if (tTd(13, 40))
							printf("    ... Another owner \"%s\"\n",
								q->q_owner);
						otherowners++;
					}
					owner = q->q_owner;
				}
				else if (tTd(13, 40))
					printf("    ... Same owner = \"%s\"\n",
						owner);
			}
			else
			{
				if (tTd(13, 40))
					printf("    ... Null owner\n");
				otherowners++;
			}

			/*
			**  If this mailer is expensive, and if we don't
			**  want to make connections now, just mark these
			**  addresses and return.  This is useful if we
			**  want to batch connections to reduce load.  This
			**  will cause the messages to be queued up, and a
			**  daemon will come along to send the messages later.
			*/

			if (bitset(QBADADDR|QQUEUEUP, q->q_flags))
			{
				if (tTd(13, 30))
					printf("    ... QBADADDR|QQUEUEUP\n");
				continue;
			}
			if (NoConnect && !Verbose &&
			    bitnset(M_EXPENSIVE, q->q_mailer->m_flags))
			{
				if (tTd(13, 30))
					printf("    ... expensive\n");
				q->q_flags |= QQUEUEUP;
				expensive = TRUE;
			}
			else
			{
				if (tTd(13, 30))
					printf("    ... deliverable\n");
				somedeliveries = TRUE;
			}
		}

		if (owner != NULL && otherowners > 0)
		{
			extern HDR *copyheader();
			extern ADDRESS *copyqueue();
			extern void dup_queue_file __P((ENVELOPE *, ENVELOPE *, int));

			/*
			**  Split this envelope into two.
			*/

			ee = (ENVELOPE *) xalloc(sizeof(ENVELOPE));
			*ee = *e;
			ee->e_id = NULL;
			(void) queuename(ee, '\0');

			if (tTd(13, 1))
				printf("sendall: split %s into %s, owner = \"%s\", otherowners = %d\n",
					e->e_id, ee->e_id, owner, otherowners);

			ee->e_header = copyheader(e->e_header);
			ee->e_sendqueue = copyqueue(e->e_sendqueue);
			ee->e_errorqueue = copyqueue(e->e_errorqueue);
			ee->e_flags = e->e_flags & ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS|EF_SENDRECEIPT|EF_RET_PARAM);
			ee->e_flags |= EF_NORECEIPT;
			setsender(owner, ee, NULL, '\0', TRUE);
			if (tTd(13, 5))
			{
				printf("sendall(split): QDONTSEND ");
				printaddr(&ee->e_from, FALSE);
			}
			ee->e_from.q_flags |= QDONTSEND;
			ee->e_dfp = NULL;
			ee->e_xfp = NULL;
			ee->e_errormode = EM_MAIL;
			ee->e_sibling = splitenv;
			splitenv = ee;

			for (q = e->e_sendqueue; q != NULL; q = q->q_next)
			{
				if (q->q_owner == owner)
				{
					q->q_flags |= QDONTSEND;
					q->q_flags &= ~(QQUEUEUP|QBADADDR);
					if (tTd(13, 6))
						printf("\t... stripping %s from original envelope\n",
							q->q_paddr);
				}
			}
			for (q = ee->e_sendqueue; q != NULL; q = q->q_next)
			{
				if (q->q_owner != owner)
				{
					q->q_flags |= QDONTSEND;
					q->q_flags &= ~(QQUEUEUP|QBADADDR);
					if (tTd(13, 6))
						printf("\t... dropping %s from cloned envelope\n",
							q->q_paddr);
				}
				else
				{
					/* clear DSN parameters */
					q->q_flags &= ~(QHASNOTIFY|Q_PINGFLAGS);
					q->q_flags |= DefaultNotify & ~QPINGONSUCCESS;
					if (tTd(13, 6))
						printf("\t... moving %s to cloned envelope\n",
							q->q_paddr);
				}
			}

			if (mode != SM_VERIFY && bitset(EF_HAS_DF, e->e_flags))
				dup_queue_file(e, ee, 'd');
			openxscript(ee);
			if (LogLevel > 4)
				sm_syslog(LOG_INFO, ee->e_id,
					"clone %s, owner=%s",
					e->e_id, owner);
		}
	}

	if (owner != NULL)
	{
		setsender(owner, e, NULL, '\0', TRUE);
		if (tTd(13, 5))
		{
			printf("sendall(owner): QDONTSEND ");
			printaddr(&e->e_from, FALSE);
		}
		e->e_from.q_flags |= QDONTSEND;
		e->e_errormode = EM_MAIL;
		e->e_flags |= EF_NORECEIPT;
		e->e_flags &= ~EF_FATALERRS;
	}

	/* if nothing to be delivered, just queue up everything */
	if (!somedeliveries && mode != SM_QUEUE && mode != SM_DEFER &&
	    mode != SM_VERIFY)
	{
		if (tTd(13, 29))
			printf("No deliveries: auto-queuing\n");
		mode = SM_QUEUE;

		/* treat this as a delivery in terms of counting tries */
		e->e_dtime = curtime();
		if (!expensive)
			e->e_ntries++;
		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
		{
			ee->e_dtime = curtime();
			if (!expensive)
				ee->e_ntries++;
		}
	}

# if QUEUE
	if ((mode == SM_QUEUE || mode == SM_DEFER || mode == SM_FORK ||
	     (mode != SM_VERIFY && SuperSafe)) &&
	    (!bitset(EF_INQUEUE, e->e_flags) || splitenv != NULL))
	{
		/* be sure everything is instantiated in the queue */
		queueup(e, mode == SM_QUEUE || mode == SM_DEFER);
		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
			queueup(ee, mode == SM_QUEUE || mode == SM_DEFER);
	}
#endif /* QUEUE */

	if (tTd(62, 10))
		checkfds("after envelope splitting");

	/*
	**  If we belong in background, fork now.
	*/

	if (tTd(13, 20))
	{
		printf("sendall: final mode = %c\n", mode);
		if (tTd(13, 21))
		{
			printf("\n================ Final Send Queue(s) =====================\n");
			printf("\n  *** Envelope %s, e_from=%s ***\n",
				e->e_id, e->e_from.q_paddr);
			printaddr(e->e_sendqueue, TRUE);
			for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
			{
				printf("\n  *** Envelope %s, e_from=%s ***\n",
					ee->e_id, ee->e_from.q_paddr);
				printaddr(ee->e_sendqueue, TRUE);
			}
			printf("==========================================================\n\n");
		}
	}
	switch (mode)
	{
	  case SM_VERIFY:
		Verbose = 2;
		break;

	  case SM_QUEUE:
	  case SM_DEFER:
  queueonly:
		if (e->e_nrcpts > 0)
			e->e_flags |= EF_INQUEUE;
		dropenvelope(e, FALSE);
		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
		{
			if (ee->e_nrcpts > 0)
				ee->e_flags |= EF_INQUEUE;
			dropenvelope(ee, FALSE);
		}
		return;

	  case SM_FORK:
		if (e->e_xfp != NULL)
			(void) fflush(e->e_xfp);

# if !HASFLOCK
		/*
		**  Since fcntl locking has the interesting semantic that
		**  the lock is owned by a process, not by an open file
		**  descriptor, we have to unlock this envelope, and
		**  then restart from scratch in the child.
		*/

		unlockqueue(e);
		for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
			unlockqueue(ee);

# endif /* !HASFLOCK */

		pid = fork();
		if (pid < 0)
		{
			goto queueonly;
		}
		else if (pid > 0)
		{
# if HASFLOCK
			/* be sure we leave the temp files to our child */
			/* can't call unlockqueue to avoid unlink of xfp */
			if (e->e_lockfp != NULL)
				(void) xfclose(e->e_lockfp, "sendenvelope lockfp", e->e_id);
			e->e_lockfp = NULL;

			/* close any random open files in the envelope */
			closexscript(e);
			if (e->e_dfp != NULL)
				(void) xfclose(e->e_dfp, "sendenvelope dfp", e->e_id);
			e->e_dfp = NULL;
			e->e_flags &= ~EF_HAS_DF;
# endif

			/* make sure the parent doesn't own the envelope */
			e->e_id = NULL;

			/* catch intermediate zombie */
			(void) waitfor(pid);
			return;
		}

		/* double fork to avoid zombies */
		pid = fork();
		if (pid > 0)
			exit(EX_OK);

		/* be sure we are immune from the terminal */
		disconnect(2, e);

		/* prevent parent from waiting if there was an error */
		if (pid < 0)
		{
			e->e_flags |= EF_INQUEUE;
			finis();
		}

		/* be sure to give error messages in child */
		QuickAbort = FALSE;

		/*
		**  Close any cached connections.
		**
		**	We don't send the QUIT protocol because the parent
		**	still knows about the connection.
		**
		**	This should only happen when delivering an error
		**	message.
		*/

		mci_flush(FALSE, NULL);

# if HASFLOCK
		break;
# else

		/*
		**  Now reacquire and run the various queue files.
		*/

		for (ee = splitenv; ee != NULL; ee = e->e_sibling)
			(void) dowork(ee->e_id, FALSE, FALSE, ee);
		(void) dowork(e->e_id, FALSE, FALSE, e);
		finis();
# endif /* !HASFLOCK */
	}

	sendenvelope(e, mode);
	dropenvelope(e, TRUE);
	for (ee = splitenv; ee != NULL; ee = ee->e_sibling)
	{
		CurEnv = ee;
		if (mode != SM_VERIFY)
			openxscript(ee);
		sendenvelope(ee, mode);
		dropenvelope(ee, TRUE);
	}
	CurEnv = e;

	Verbose = oldverbose;
	if (mode == SM_FORK)
		finis();
}

void
sendenvelope(e, mode)
	register ENVELOPE *e;
	char mode;
{
	register ADDRESS *q;
	bool didany;

	if (tTd(13, 10))
		printf("sendenvelope(%s) e_flags=0x%lx\n",
			e->e_id == NULL ? "[NOQUEUE]" : e->e_id,
			e->e_flags);
	if (LogLevel > 80)
		sm_syslog(LOG_DEBUG, e->e_id,
			"sendenvelope, flags=0x%x",
			e->e_flags);

	/*
	**  If we have had global, fatal errors, don't bother sending
	**  the message at all if we are in SMTP mode.  Local errors
	**  (e.g., a single address failing) will still cause the other
	**  addresses to be sent.
	*/

	if (bitset(EF_FATALERRS, e->e_flags) &&
	    (OpMode == MD_SMTP || OpMode == MD_DAEMON))
	{
		e->e_flags |= EF_CLRQUEUE;
		return;
	}

	/*
	**  Run through the list and send everything.
	**
	**	Set EF_GLOBALERRS so that error messages during delivery
	**	result in returned mail.
	*/

	e->e_nsent = 0;
	e->e_flags |= EF_GLOBALERRS;
	define(macid("{envid}", NULL), e->e_envid, e);
	define(macid("{bodytype}", NULL), e->e_bodytype, e);
	didany = FALSE;

	/* now run through the queue */
	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
	{
#if XDEBUG
		char wbuf[MAXNAME + 20];

		(void) snprintf(wbuf, sizeof wbuf, "sendall(%.*s)",
			MAXNAME, q->q_paddr);
		checkfd012(wbuf);
#endif
		if (mode == SM_VERIFY)
		{
			e->e_to = q->q_paddr;
			if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
			{
				if (q->q_host != NULL && q->q_host[0] != '\0')
					message("deliverable: mailer %s, host %s, user %s",
						q->q_mailer->m_name,
						q->q_host,
						q->q_user);
				else
					message("deliverable: mailer %s, user %s",
						q->q_mailer->m_name,
						q->q_user);
			}
		}
		else if (!bitset(QDONTSEND|QBADADDR, q->q_flags))
		{
			extern int deliver __P((ENVELOPE *, ADDRESS *));

# if QUEUE
			/*
			**  Checkpoint the send list every few addresses
			*/

			if (e->e_nsent >= CheckpointInterval)
			{
				queueup(e, FALSE);
				e->e_nsent = 0;
			}
# endif /* QUEUE */
			(void) deliver(e, q);
			didany = TRUE;
		}
	}
	if (didany)
	{
		e->e_dtime = curtime();
		e->e_ntries++;
	}

#if XDEBUG
	checkfd012("end of sendenvelope");
#endif
}
/*
**  DUP_QUEUE_FILE -- duplicate a queue file into a split queue
**
**	Parameters:
**		e -- the existing envelope
**		ee -- the new envelope
**		type -- the queue file type (e.g., 'd')
**
**	Returns:
**		none
*/

void
dup_queue_file(e, ee, type)
	struct envelope *e, *ee;
	int type;
{
	char f1buf[MAXQFNAME], f2buf[MAXQFNAME];

	ee->e_dfp = NULL;
	ee->e_xfp = NULL;
	snprintf(f1buf, sizeof f1buf, "%s", queuename(e, type));
	snprintf(f2buf, sizeof f2buf, "%s", queuename(ee, type));
	if (link(f1buf, f2buf) < 0)
	{
		int saverrno = errno;

		syserr("sendall: link(%s, %s)", f1buf, f2buf);
		if (saverrno == EEXIST)
		{
			if (unlink(f2buf) < 0)
			{
				syserr("!sendall: unlink(%s): permanent",
					f2buf);
				/*NOTREACHED*/
			}
			if (link(f1buf, f2buf) < 0)
			{
				syserr("!sendall: link(%s, %s): permanent",
					f1buf, f2buf);
				/*NOTREACHED*/
			}
		}
	}
}
/*
**  DOFORK -- do a fork, retrying a couple of times on failure.
**
**	This MUST be a macro, since after a vfork we are running
**	two processes on the same stack!!!
**
**	Parameters:
**		none.
**
**	Returns:
**		From a macro???  You've got to be kidding!
**
**	Side Effects:
**		Modifies the ==> LOCAL <== variable 'pid', leaving:
**			pid of child in parent, zero in child.
**			-1 on unrecoverable error.
**
**	Notes:
**		I'm awfully sorry this looks so awful.  That's
**		vfork for you.....
*/

# define NFORKTRIES	5

# ifndef FORK
# define FORK	fork
# endif

# define DOFORK(fORKfN) \
{\
	register int i;\
\
	for (i = NFORKTRIES; --i >= 0; )\
	{\
		pid = fORKfN();\
		if (pid >= 0)\
			break;\
		if (i > 0)\
			sleep((unsigned) NFORKTRIES - i);\
	}\
}
/*
**  DOFORK -- simple fork interface to DOFORK.
**
**	Parameters:
**		none.
**
**	Returns:
**		pid of child in parent.
**		zero in child.
**		-1 on error.
**
**	Side Effects:
**		returns twice, once in parent and once in child.
*/

int
dofork()
{
	register pid_t pid = -1;

	DOFORK(fork);
	return (pid);
}
/*
**  DELIVER -- Deliver a message to a list of addresses.
**
**	This routine delivers to everyone on the same host as the
**	user on the head of the list.  It is clever about mailers
**	that don't handle multiple users.  It is NOT guaranteed
**	that it will deliver to all these addresses however -- so
**	deliver should be called once for each address on the
**	list.
**
**	Parameters:
**		e -- the envelope to deliver.
**		firstto -- head of the address list to deliver to.
**
**	Returns:
**		zero -- successfully delivered.
**		else -- some failure, see ExitStat for more info.
**
**	Side Effects:
**		The standard input is passed off to someone.
*/

#ifndef NO_UID
# define NO_UID		-1
#endif
#ifndef NO_GID
# define NO_GID		-1
#endif

int
deliver(e, firstto)
	register ENVELOPE *e;
	ADDRESS *firstto;
{
	char *host;			/* host being sent to */
	char *user;			/* user being sent to */
	char **pvp;
	register char **mvp;
	register char *p;
	register MAILER *m;		/* mailer for this recipient */
	ADDRESS *volatile ctladdr;
	ADDRESS *volatile contextaddr = NULL;
	register MCI *volatile mci;
	register ADDRESS *to = firstto;
	volatile bool clever = FALSE;	/* running user smtp to this mailer */
	ADDRESS *volatile tochain = NULL; /* users chain in this mailer call */
	int rcode;			/* response code */
	char *firstsig;			/* signature of firstto */
	pid_t pid = -1;
	char *volatile curhost;
	register volatile u_short port = 0;
	time_t xstart;
	bool suidwarn;
	bool anyok;			/* at least one address was OK */
	bool goodmxfound = FALSE;	/* at least one MX was OK */
	int mpvect[2];
	int rpvect[2];
	char *pv[MAXPV+1];
	char tobuf[TOBUFSIZE];		/* text line of to people */
	char buf[MAXNAME + 1];
	char rpathbuf[MAXNAME + 1];	/* translated return path */
	extern int checkcompat();
	extern void markfailure __P((ENVELOPE *, ADDRESS *, MCI *, int));

	errno = 0;
	if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags))
		return (0);

	suidwarn = geteuid() == 0;

#if NAMED_BIND
	/* unless interactive, try twice, over a minute */
	if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
	{
		_res.retrans = 30;
		_res.retry = 2;
	}
#endif

	m = to->q_mailer;
	host = to->q_host;
	CurEnv = e;			/* just in case */
	e->e_statmsg = NULL;
#if SMTP
	SmtpError[0] = '\0';
#endif
	xstart = curtime();

	if (tTd(10, 1))
		printf("\n--deliver, id=%s, mailer=%s, host=`%s', first user=`%s'\n",
			e->e_id, m->m_name, host, to->q_user);
	if (tTd(10, 100))
		printopenfds(FALSE);

	/*
	**  Do initial argv setup.
	**	Insert the mailer name.  Notice that $x expansion is
	**	NOT done on the mailer name.  Then, if the mailer has
	**	a picky -f flag, we insert it as appropriate.  This
	**	code does not check for 'pv' overflow; this places a
	**	manifest lower limit of 4 for MAXPV.
	**		The from address rewrite is expected to make
	**		the address relative to the other end.
	*/

	/* rewrite from address, using rewriting rules */
	rcode = EX_OK;
	if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags))
		p = e->e_sender;
	else
		p = e->e_from.q_paddr;
	p = remotename(p, m, RF_SENDERADDR|RF_CANONICAL, &rcode, e);
	if (strlen(p) >= (SIZE_T) sizeof rpathbuf)
	{
		p = shortenstring(p, 203);
		syserr("remotename: huge return %s", p);
	}
	snprintf(rpathbuf, sizeof rpathbuf, "%s", p);
	define('g', rpathbuf, e);		/* translated return path */
	define('h', host, e);			/* to host */
	Errors = 0;
	pvp = pv;
	*pvp++ = m->m_argv[0];

	/* insert -f or -r flag as appropriate */
	if (FromFlag && (bitnset(M_FOPT, m->m_flags) || bitnset(M_ROPT, m->m_flags)))
	{
		if (bitnset(M_FOPT, m->m_flags))
			*pvp++ = "-f";
		else
			*pvp++ = "-r";
		*pvp++ = newstr(rpathbuf);
	}

	/*
	**  Append the other fixed parts of the argv.  These run
	**  up to the first entry containing "$u".  There can only
	**  be one of these, and there are only a few more slots
	**  in the pv after it.
	*/

	for (mvp = m->m_argv; (p = *++mvp) != NULL; )
	{
		/* can't use strchr here because of sign extension problems */
		while (*p != '\0')
		{
			if ((*p++ & 0377) == MACROEXPAND)
			{
				if (*p == 'u')
					break;
			}
		}

		if (*p != '\0')
			break;

		/* this entry is safe -- go ahead and process it */
		expand(*mvp, buf, sizeof buf, e);
		*pvp++ = newstr(buf);
		if (pvp >= &pv[MAXPV - 3])
		{
			syserr("554 Too many parameters to %s before $u", pv[0]);
			return (-1);
		}
	}

	/*
	**  If we have no substitution for the user name in the argument
	**  list, we know that we must supply the names otherwise -- and
	**  SMTP is the answer!!
	*/

	if (*mvp == NULL)
	{
		/* running SMTP */
# if SMTP
		clever = TRUE;
		*pvp = NULL;
# else /* SMTP */
		/* oops!  we don't implement SMTP */
		syserr("554 SMTP style mailer not implemented");
		return (EX_SOFTWARE);
# endif /* SMTP */
	}

	/*
	**  At this point *mvp points to the argument with $u.  We
	**  run through our address list and append all the addresses
	**  we can.  If we run out of space, do not fret!  We can
	**  always send another copy later.
	*/

	tobuf[0] = '\0';
	e->e_to = tobuf;
	ctladdr = NULL;
	firstsig = hostsignature(firstto->q_mailer, firstto->q_host, e);
	for (; to != NULL; to = to->q_next)
	{
		/* avoid sending multiple recipients to dumb mailers */
		if (tobuf[0] != '\0' && !bitnset(M_MUSER, m->m_flags))
			break;

		/* if already sent or not for this host, don't send */
		if (bitset(QDONTSEND|QBADADDR|QQUEUEUP, to->q_flags) ||
		    to->q_mailer != firstto->q_mailer ||
		    strcmp(hostsignature(to->q_mailer, to->q_host, e), firstsig) != 0)
			continue;

		/* avoid overflowing tobuf */
		if (sizeof tobuf < (strlen(to->q_paddr) + strlen(tobuf) + 2))
			break;

		if (tTd(10, 1))
		{
			printf("\nsend to ");
			printaddr(to, FALSE);
		}

		/* compute effective uid/gid when sending */
		if (bitnset(M_RUNASRCPT, to->q_mailer->m_flags))
			contextaddr = ctladdr = getctladdr(to);

		if (tTd(10, 2))
		{
			printf("ctladdr=");
			printaddr(ctladdr, FALSE);
		}

		user = to->q_user;
		e->e_to = to->q_paddr;
		if (tTd(10, 5))
		{
			printf("deliver: QDONTSEND ");
			printaddr(to, FALSE);
		}
		to->q_flags |= QDONTSEND;

		/*
		**  Check to see that these people are allowed to
		**  talk to each other.
		*/

		if (m->m_maxsize != 0 && e->e_msgsize > m->m_maxsize)
		{
			e->e_flags |= EF_NO_BODY_RETN;
			to->q_status = "5.2.3";
			usrerr("552 Message is too large; %ld bytes max", m->m_maxsize);
			markfailure(e, to, NULL, EX_UNAVAILABLE);
			giveresponse(EX_UNAVAILABLE, m, NULL, ctladdr, xstart, e);
			continue;
		}
#if NAMED_BIND
		h_errno = 0;
#endif

		/* do config file checking of compatibility */
		rcode = rscheck("check_compat",
				e->e_from.q_paddr, to->q_paddr, e);
		if (rcode == EX_OK)
		{
			/* do in-code checking */
			rcode = checkcompat(to, e);
		}
		if (rcode != EX_OK)
		{
			markfailure(e, to, NULL, rcode);
			giveresponse(rcode, m, NULL, ctladdr, xstart, e);
			continue;
		}

		/*
		**  Strip quote bits from names if the mailer is dumb
		**	about them.
		*/

		if (bitnset(M_STRIPQ, m->m_flags))
		{
			stripquotes(user);
			stripquotes(host);
		}

		/* hack attack -- delivermail compatibility */
		if (m == ProgMailer && *user == '|')
			user++;

		/*
		**  If an error message has already been given, don't
		**	bother to send to this address.
		**
		**	>>>>>>>>>> This clause assumes that the local mailer
		**	>> NOTE >> cannot do any further aliasing; that
		**	>>>>>>>>>> function is subsumed by sendmail.
		*/

		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
			continue;

		/*
		**  See if this user name is "special".
		**	If the user name has a slash in it, assume that this
		**	is a file -- send it off without further ado.  Note
		**	that this type of addresses is not processed along
		**	with the others, so we fudge on the To person.
		*/

		if (strcmp(m->m_mailer, "[FILE]") == 0)
		{
			rcode = mailfile(user, ctladdr, SFF_CREAT, e);
			giveresponse(rcode, m, NULL, ctladdr, xstart, e);
			e->e_nsent++;
			if (rcode == EX_OK)
			{
				to->q_flags |= QSENT;
				markstats(e, to);
				if (bitnset(M_LOCALMAILER, m->m_flags) &&
				    bitset(QPINGONSUCCESS, to->q_flags))
				{
					to->q_flags |= QDELIVERED;
					to->q_status = "2.1.5";
					fprintf(e->e_xfp, "%s... Successfully delivered\n",
						to->q_paddr);
				}
			}
			to->q_statdate = curtime();
			continue;
		}

		/*
		**  Address is verified -- add this user to mailer
		**  argv, and add it to the print list of recipients.
		*/

		/* link together the chain of recipients */
		to->q_tchain = tochain;
		tochain = to;

		/* create list of users for error messages */
		(void) strcat(tobuf, ",");
		(void) strcat(tobuf, to->q_paddr);
		define('u', user, e);		/* to user */
		p = to->q_home;
		if (p == NULL && ctladdr != NULL)
			p = ctladdr->q_home;
		define('z', p, e);	/* user's home */

		/*
		**  Expand out this user into argument list.
		*/

		if (!clever)
		{
			expand(*mvp, buf, sizeof buf, e);
			*pvp++ = newstr(buf);
			if (pvp >= &pv[MAXPV - 2])
			{
				/* allow some space for trailing parms */
				break;
			}
		}
	}

	/* see if any addresses still exist */
	if (tobuf[0] == '\0')
	{
		define('g', (char *) NULL, e);
		return (0);
	}

	/* print out messages as full list */
	e->e_to = tobuf + 1;

	/*
	**  Fill out any parameters after the $u parameter.
	*/

	while (!clever && *++mvp != NULL)
	{
		expand(*mvp, buf, sizeof buf, e);
		*pvp++ = newstr(buf);
		if (pvp >= &pv[MAXPV])
			syserr("554 deliver: pv overflow after $u for %s", pv[0]);
	}
	*pvp++ = NULL;

	/*
	**  Call the mailer.
	**	The argument vector gets built, pipes
	**	are created as necessary, and we fork & exec as
	**	appropriate.
	**	If we are running SMTP, we just need to clean up.
	*/

	/*XXX this seems a bit wierd */
	if (ctladdr == NULL && m != ProgMailer && m != FileMailer &&
	    bitset(QGOODUID, e->e_from.q_flags))
		ctladdr = &e->e_from;

#if NAMED_BIND
	if (ConfigLevel < 2)
		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */
#endif

	if (tTd(11, 1))
	{
		printf("openmailer:");
		printav(pv);
	}
	errno = 0;
#if NAMED_BIND
	h_errno = 0;
#endif

	CurHostName = NULL;

	/*
	**  Deal with the special case of mail handled through an IPC
	**  connection.
	**	In this case we don't actually fork.  We must be
	**	running SMTP for this to work.  We will return a
	**	zero pid to indicate that we are running IPC.
	**  We also handle a debug version that just talks to stdin/out.
	*/

	curhost = NULL;
	SmtpPhase = NULL;
	mci = NULL;

#if XDEBUG
	{
		char wbuf[MAXLINE];

		/* make absolutely certain 0, 1, and 2 are in use */
		snprintf(wbuf, sizeof wbuf, "%s... openmailer(%s)",
			shortenstring(e->e_to, 203), m->m_name);
		checkfd012(wbuf);
	}
#endif

	/* check for 8-bit available */
	if (bitset(EF_HAS8BIT, e->e_flags) &&
	    bitnset(M_7BITS, m->m_flags) &&
	    (bitset(EF_DONT_MIME, e->e_flags) ||
	     !(bitset(MM_MIME8BIT, MimeMode) ||
	       (bitset(EF_IS_MIME, e->e_flags) &&
	        bitset(MM_CVTMIME, MimeMode)))))
	{
		usrerr("554 Cannot send 8-bit data to 7-bit destination");
		rcode = EX_DATAERR;
		e->e_status = "5.6.3";
		goto give_up;
	}

	if (tTd(62, 8))
		checkfds("before delivery");

	/* check for Local Person Communication -- not for mortals!!! */
	if (strcmp(m->m_mailer, "[LPC]") == 0)
	{
		mci = (MCI *) xalloc(sizeof *mci);
		bzero((char *) mci, sizeof *mci);
		mci->mci_in = stdin;
		mci->mci_out = stdout;
		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
		mci->mci_mailer = m;
	}
	else if (strcmp(m->m_mailer, "[IPC]") == 0 ||
		 strcmp(m->m_mailer, "[TCP]") == 0)
	{
#if DAEMON
		register int i;

		if (pv[0] == NULL || pv[1] == NULL || pv[1][0] == '\0')
		{
			syserr("null host name for %s mailer", m->m_mailer);
			rcode = EX_CONFIG;
			goto give_up;
		}

		CurHostName = pv[1];
		curhost = hostsignature(m, pv[1], e);

		if (curhost == NULL || curhost[0] == '\0')
		{
			syserr("null host signature for %s", pv[1]);
			rcode = EX_CONFIG;
			goto give_up;
		}

		if (!clever)
		{
			syserr("554 non-clever IPC");
			rcode = EX_CONFIG;
			goto give_up;
		}
		if (pv[2] != NULL)
		{
			port = htons(atoi(pv[2]));
			if (port == 0)
			{
				struct servent *sp = getservbyname(pv[2], "tcp");

				if (sp == NULL)
					syserr("Service %s unknown", pv[2]);
				else
					port = sp->s_port;
			}
		}
tryhost:
		while (*curhost != '\0')
		{
			register char *p;
			static char hostbuf[MAXNAME + 1];
			extern int makeconnection __P((char *, u_short, MCI *, ENVELOPE *));

			/* pull the next host from the signature */
			p = strchr(curhost, ':');
			if (p == NULL)
				p = (char *) &curhost[strlen(curhost)];
			if (p == curhost)
			{
				syserr("deliver: null host name in signature");
				curhost++;
				continue;
			}
			i = p - curhost;
			if (i >= sizeof hostbuf)
				i = sizeof hostbuf - 1;
			strncpy(hostbuf, curhost, i);
			hostbuf[i] = '\0';
			if (*p != '\0')
				p++;
			curhost = p;

			/* see if we already know that this host is fried */
			CurHostName = hostbuf;
			mci = mci_get(hostbuf, m);
			if (mci->mci_state != MCIS_CLOSED)
			{
				if (tTd(11, 1))
				{
					printf("openmailer: ");
					mci_dump(mci, FALSE);
				}
				CurHostName = mci->mci_host;
				message("Using cached %sSMTP connection to %s via %s...",
					bitset(MCIF_ESMTP, mci->mci_flags) ? "E" : "",
					hostbuf, m->m_name);
				break;
			}
			mci->mci_mailer = m;
			if (mci->mci_exitstat != EX_OK)
			{
				if (mci->mci_exitstat == EX_TEMPFAIL)
					goodmxfound = TRUE;
				continue;
			}

			if (mci_lock_host(mci) != EX_OK)
			{
				mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
				goodmxfound = TRUE;
				continue;
			}

			/* try the connection */
			setproctitle("%s %s: %s", e->e_id, hostbuf, "user open");
			if (port == 0)
				message("Connecting to %s via %s...",
					hostbuf, m->m_name);
			else
				message("Connecting to %s port %d via %s...",
					hostbuf, ntohs(port), m->m_name);
			i = makeconnection(hostbuf, port, mci, e);
			mci->mci_lastuse = curtime();
			mci->mci_exitstat = i;
			mci->mci_errno = errno;
#if NAMED_BIND
			mci->mci_herrno = h_errno;
#endif
			if (i == EX_OK)
			{
				goodmxfound = TRUE;
				mci->mci_state = MCIS_OPENING;
				mci_cache(mci);
				if (TrafficLogFile != NULL)
					fprintf(TrafficLogFile, "%05d === CONNECT %s\n",
						(int) getpid(), hostbuf);
				break;
			}
			else
			{
			    	if (tTd(11, 1))
					printf("openmailer: makeconnection => stat=%d, errno=%d\n",
						i, errno);
				if (i == EX_TEMPFAIL)
					goodmxfound = TRUE;
				mci_unlock_host(mci);
			}

			/* enter status of this host */
			setstat(i);

			/* should print some message here for -v mode */
		}
		if (mci == NULL)
		{
			syserr("deliver: no host name");
			rcode = EX_SOFTWARE;
			goto give_up;
		}
		mci->mci_pid = 0;
#else /* no DAEMON */
		syserr("554 openmailer: no IPC");
		if (tTd(11, 1))
			printf("openmailer: NULL\n");
		rcode = EX_UNAVAILABLE;
		goto give_up;
#endif /* DAEMON */
	}
	else
	{
		/* flush any expired connections */
		(void) mci_scan(NULL);

		/* announce the connection to verbose listeners */
		if (host == NULL || host[0] == '\0')
			message("Connecting to %s...", m->m_name);
		else
			message("Connecting to %s via %s...", host, m->m_name);
		if (TrafficLogFile != NULL)
		{
			char **av;

			fprintf(TrafficLogFile, "%05d === EXEC", (int) getpid());
			for (av = pv; *av != NULL; av++)
				fprintf(TrafficLogFile, " %s", *av);
			fprintf(TrafficLogFile, "\n");
		}

#if XDEBUG
		checkfd012("before creating mail pipe");
#endif

		/* create a pipe to shove the mail through */
		if (pipe(mpvect) < 0)
		{
			syserr("%s... openmailer(%s): pipe (to mailer)",
				shortenstring(e->e_to, 203), m->m_name);
			if (tTd(11, 1))
				printf("openmailer: NULL\n");
			rcode = EX_OSERR;
			goto give_up;
		}

#if XDEBUG
		/* make sure we didn't get one of the standard I/O files */
		if (mpvect[0] < 3 || mpvect[1] < 3)
		{
			syserr("%s... openmailer(%s): bogus mpvect %d %d",
				shortenstring(e->e_to, 203), m->m_name,
				mpvect[0], mpvect[1]);
			printopenfds(TRUE);
			if (tTd(11, 1))
				printf("openmailer: NULL\n");
			rcode = EX_OSERR;
			goto give_up;
		}

		/* make sure system call isn't dead meat */
		checkfdopen(mpvect[0], "mpvect[0]");
		checkfdopen(mpvect[1], "mpvect[1]");
		if (mpvect[0] == mpvect[1] ||
		    (e->e_lockfp != NULL &&
		     (mpvect[0] == fileno(e->e_lockfp) ||
		      mpvect[1] == fileno(e->e_lockfp))))
		{
			if (e->e_lockfp == NULL)
				syserr("%s... openmailer(%s): overlapping mpvect %d %d",
					shortenstring(e->e_to, 203), m->m_name,
					mpvect[0], mpvect[1]);
			else
				syserr("%s... openmailer(%s): overlapping mpvect %d %d, lockfp = %d",
					shortenstring(e->e_to, 203), m->m_name,
					mpvect[0], mpvect[1], fileno(e->e_lockfp));
		}
#endif

		/* if this mailer speaks smtp, create a return pipe */
#if SMTP
		if (clever)
		{
			if (pipe(rpvect) < 0)
			{
				syserr("%s... openmailer(%s): pipe (from mailer)",
					shortenstring(e->e_to, 203), m->m_name);
				(void) close(mpvect[0]);
				(void) close(mpvect[1]);
				if (tTd(11, 1))
					printf("openmailer: NULL\n");
				rcode = EX_OSERR;
				goto give_up;
			}
# if XDEBUG
			checkfdopen(rpvect[0], "rpvect[0]");
			checkfdopen(rpvect[1], "rpvect[1]");
# endif
		}
#endif

		/*
		**  Actually fork the mailer process.
		**	DOFORK is clever about retrying.
		**
		**	Dispose of SIGCHLD signal catchers that may be laying
		**	around so that endmail will get it.
		*/

		if (e->e_xfp != NULL)
			(void) fflush(e->e_xfp);		/* for debugging */
		(void) fflush(stdout);
# ifdef SIGCHLD
		(void) setsignal(SIGCHLD, SIG_DFL);
# endif /* SIGCHLD */
		DOFORK(FORK);
		/* pid is set by DOFORK */
		if (pid < 0)
		{
			/* failure */
			syserr("%s... openmailer(%s): cannot fork",
				shortenstring(e->e_to, 203), m->m_name);
			(void) close(mpvect[0]);
			(void) close(mpvect[1]);
#if SMTP
			if (clever)
			{
				(void) close(rpvect[0]);
				(void) close(rpvect[1]);
			}
#endif
			if (tTd(11, 1))
				printf("openmailer: NULL\n");
			rcode = EX_OSERR;
			goto give_up;
		}
		else if (pid == 0)
		{
			int i;
			int saveerrno;
			int new_euid = NO_UID;
			int new_ruid = NO_UID;
			int new_gid = NO_GID;
			struct stat stb;
			extern int DtableSize;

			if (e->e_lockfp != NULL)
				(void) close(fileno(e->e_lockfp));

			/* child -- set up input & exec mailer */
			(void) setsignal(SIGINT, SIG_IGN);
			(void) setsignal(SIGHUP, SIG_IGN);
			(void) setsignal(SIGTERM, SIG_DFL);

			if (m != FileMailer || stat(tochain->q_user, &stb) < 0)
				stb.st_mode = 0;

#if HASSETUSERCONTEXT
			/*
			**  Set user resources.
			*/

			if (contextaddr != NULL)
			{
				struct passwd *pwd;

				if (contextaddr->q_ruser != NULL)
					pwd = sm_getpwnam(contextaddr->q_ruser);
				else
					pwd = sm_getpwnam(contextaddr->q_user);
				if (pwd != NULL)
					(void) setusercontext(NULL,
						pwd, pwd->pw_uid,
						LOGIN_SETRESOURCES|LOGIN_SETPRIORITY);
			}
#endif

			/* tweak niceness */
			if (m->m_nice != 0)
				nice(m->m_nice);

			/* reset group id */
			if (bitnset(M_SPECIFIC_UID, m->m_flags))
				new_gid = m->m_gid;
			else if (bitset(S_ISGID, stb.st_mode))
				new_gid = stb.st_gid;
			else if (ctladdr != NULL && ctladdr->q_gid != 0)
			{
				if (!DontInitGroups)
					(void) initgroups(ctladdr->q_ruser != NULL ?
						ctladdr->q_ruser : ctladdr->q_user,
						ctladdr->q_gid);
				new_gid = ctladdr->q_gid;
			}
			else
			{
				if (!DontInitGroups)
					(void) initgroups(DefUser, DefGid);
				if (m->m_gid == 0)
					new_gid = DefGid;
				else
					new_gid = m->m_gid;
			}
			if (new_gid != NO_GID && setgid(new_gid) < 0 && suidwarn)
				syserr("openmailer: setgid(%ld) failed",
					(long) new_gid);

			/* reset user id */
			endpwent();
			if (bitnset(M_SPECIFIC_UID, m->m_flags))
				new_euid = m->m_uid;
			if (bitset(S_ISUID, stb.st_mode))
				new_ruid = stb.st_uid;
			else if (ctladdr != NULL && ctladdr->q_uid != 0)
				new_ruid = ctladdr->q_uid;
			else if (m->m_uid != 0)
				new_ruid = m->m_uid;
			else if (!bitnset(M_SPECIFIC_UID, m->m_flags))
				new_ruid = DefUid;
			if (new_euid != NO_UID)
			{
				vendor_set_uid(new_euid);
#if USESETEUID
				if (seteuid(new_euid) < 0 && suidwarn)
					syserr("openmailer: seteuid(%ld) failed",
						(long) new_euid);
#else
# if HASSETREUID
				if (setreuid(new_ruid, new_euid) < 0 && suidwarn)
					syserr("openmailer: setreuid(%ld, %ld) failed",
						(long) new_ruid, (long) new_euid);
# else
				if (new_euid != geteuid() && setuid(new_euid) < 0 && suidwarn)
					syserr("openmailer: setuid(%ld) failed",
						(long) new_euid);
# endif
#endif
			}
			else if (new_ruid != NO_UID)
			{
				vendor_set_uid(new_ruid);
				if (setuid(new_ruid) < 0 && suidwarn)
					syserr("openmailer: setuid(%ld) failed",
						(long) new_ruid);
			}

			if (tTd(11, 2))
				printf("openmailer: running as r/euid=%d/%d\n",
					(int) getuid(), (int) geteuid());

			/* move into some "safe" directory */
			if (m->m_execdir != NULL)
			{
				char *p, *q;
				char buf[MAXLINE + 1];

				for (p = m->m_execdir; p != NULL; p = q)
				{
					q = strchr(p, ':');
					if (q != NULL)
						*q = '\0';
					expand(p, buf, sizeof buf, e);
					if (q != NULL)
						*q++ = ':';
					if (tTd(11, 20))
						printf("openmailer: trydir %s\n",
							buf);
					if (buf[0] != '\0' && chdir(buf) >= 0)
						break;
				}
			}

			/* arrange to filter std & diag output of command */
#if SMTP
			if (clever)
			{
				(void) close(rpvect[0]);
				if (dup2(rpvect[1], STDOUT_FILENO) < 0)
				{
					syserr("%s... openmailer(%s): cannot dup pipe %d for stdout",
						shortenstring(e->e_to, 203),
						m->m_name, rpvect[1]);
					_exit(EX_OSERR);
				}
				(void) close(rpvect[1]);
			}
			else if (OpMode == MD_SMTP || OpMode == MD_DAEMON ||
				  HoldErrs || DisConnected)
			{
				/* put mailer output in transcript */
				if (dup2(fileno(e->e_xfp), STDOUT_FILENO) < 0)
				{
					syserr("%s... openmailer(%s): cannot dup xscript %d for stdout",
						shortenstring(e->e_to, 203),
						m->m_name, fileno(e->e_xfp));
					_exit(EX_OSERR);
				}
			}
#endif
			if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
			{
				syserr("%s... openmailer(%s): cannot dup stdout for stderr",
					shortenstring(e->e_to, 203), m->m_name);
				_exit(EX_OSERR);
			}

			/* arrange to get standard input */
			(void) close(mpvect[1]);
			if (dup2(mpvect[0], STDIN_FILENO) < 0)
			{
				syserr("%s... openmailer(%s): cannot dup pipe %d for stdin",
					shortenstring(e->e_to, 203),
					m->m_name, mpvect[0]);
				_exit(EX_OSERR);
			}
			(void) close(mpvect[0]);

			/* arrange for all the files to be closed */
			for (i = 3; i < DtableSize; i++)
			{
				register int j;

				if ((j = fcntl(i, F_GETFD, 0)) != -1)
					(void) fcntl(i, F_SETFD, j | 1);
			}

			/* run disconnected from terminal */
			(void) setsid();

			/* try to execute the mailer */
			execve(m->m_mailer, (ARGV_T) pv, (ARGV_T) UserEnviron);
			saveerrno = errno;
			syserr("Cannot exec %s", m->m_mailer);
			if (bitnset(M_LOCALMAILER, m->m_flags) ||
			    transienterror(saveerrno))
				_exit(EX_OSERR);
			_exit(EX_UNAVAILABLE);
		}

		/*
		**  Set up return value.
		*/

		mci = (MCI *) xalloc(sizeof *mci);
		bzero((char *) mci, sizeof *mci);
		mci->mci_mailer = m;
		mci->mci_state = clever ? MCIS_OPENING : MCIS_OPEN;
		mci->mci_pid = pid;
		(void) close(mpvect[0]);
		mci->mci_out = fdopen(mpvect[1], "w");
		if (mci->mci_out == NULL)
		{
			syserr("deliver: cannot create mailer output channel, fd=%d",
				mpvect[1]);
			(void) close(mpvect[1]);
#if SMTP
			if (clever)
			{
				(void) close(rpvect[0]);
				(void) close(rpvect[1]);
			}
#endif
			rcode = EX_OSERR;
			goto give_up;
		}
#if SMTP
		if (clever)
		{
			(void) close(rpvect[1]);
			mci->mci_in = fdopen(rpvect[0], "r");
			if (mci->mci_in == NULL)
			{
				syserr("deliver: cannot create mailer input channel, fd=%d",
					mpvect[1]);
				(void) close(rpvect[0]);
				fclose(mci->mci_out);
				mci->mci_out = NULL;
				rcode = EX_OSERR;
				goto give_up;
			}
		}
		else
#endif
		{
			mci->mci_flags |= MCIF_TEMP;
			mci->mci_in = NULL;
		}
	}

	/*
	**  If we are in SMTP opening state, send initial protocol.
	*/

	if (bitnset(M_7BITS, m->m_flags) &&
	    (!clever || mci->mci_state == MCIS_OPENING))
		mci->mci_flags |= MCIF_7BIT;
#if SMTP
	if (clever && mci->mci_state != MCIS_CLOSED)
	{
		extern void smtpinit __P((MAILER *, MCI *, ENVELOPE *));

		smtpinit(m, mci, e);
	}
#endif

	/* clear out per-message flags from connection structure */
	mci->mci_flags &= ~(MCIF_CVT7TO8|MCIF_CVT8TO7);

	if (bitset(EF_HAS8BIT, e->e_flags) &&
	    !bitset(EF_DONT_MIME, e->e_flags) &&
	    bitnset(M_7BITS, m->m_flags))
		mci->mci_flags |= MCIF_CVT8TO7;

#if MIME7TO8
	if (bitnset(M_MAKE8BIT, m->m_flags) &&
	    !bitset(MCIF_7BIT, mci->mci_flags) &&
	    (p = hvalue("Content-Transfer-Encoding", e->e_header)) != NULL &&
	     (strcasecmp(p, "quoted-printable") == 0 ||
	      strcasecmp(p, "base64") == 0) &&
	    (p = hvalue("Content-Type", e->e_header)) != NULL)
	{
		/* may want to convert 7 -> 8 */
		/* XXX should really parse it here -- and use a class XXX */
		if (strncasecmp(p, "text/plain", 10) == 0 &&
		    (p[10] == '\0' || p[10] == ' ' || p[10] == ';'))
			mci->mci_flags |= MCIF_CVT7TO8;
	}
#endif

	if (tTd(11, 1))
	{
		printf("openmailer: ");
		mci_dump(mci, FALSE);
	}

	if (mci->mci_state != MCIS_OPEN)
	{
		/* couldn't open the mailer */
		rcode = mci->mci_exitstat;
		errno = mci->mci_errno;
#if NAMED_BIND
		h_errno = mci->mci_herrno;
#endif
		if (rcode == EX_OK)
		{
			/* shouldn't happen */
			syserr("554 deliver: mci=%lx rcode=%d errno=%d state=%d sig=%s",
				(long) mci, rcode, errno, mci->mci_state,
				firstsig);
			mci_dump_all(TRUE);
			rcode = EX_SOFTWARE;
		}
#if DAEMON
		else if (curhost != NULL && *curhost != '\0')
		{
			/* try next MX site */
			goto tryhost;
		}
#endif
	}
	else if (!clever)
	{
		/*
		**  Format and send message.
		*/

		putfromline(mci, e);
		(*e->e_puthdr)(mci, e->e_header, e);
		(*e->e_putbody)(mci, e, NULL);

		/* get the exit status */
		rcode = endmailer(mci, e, pv);
	}
	else
#if SMTP
	{
		extern int smtpmailfrom __P((MAILER *, MCI *, ENVELOPE *));
		extern int smtprcpt __P((ADDRESS *, MAILER *, MCI *, ENVELOPE *));
		extern int smtpdata __P((MAILER *, MCI *, ENVELOPE *));
		extern int smtpgetstat __P((MAILER *, MCI *, ENVELOPE *));

		/*
		**  Send the MAIL FROM: protocol
		*/

		rcode = smtpmailfrom(m, mci, e);
		if (rcode == EX_OK)
		{
			register char *t = tobuf;
			register int i;

			/* send the recipient list */
			tobuf[0] = '\0';
			for (to = tochain; to != NULL; to = to->q_tchain)
			{
				e->e_to = to->q_paddr;
				if (strlen(to->q_paddr) + (t - tobuf) + 2 > sizeof tobuf)
				{
					/* not enough room */
					continue;
				}
				else if ((i = smtprcpt(to, m, mci, e)) != EX_OK)
				{
					markfailure(e, to, mci, i);
					giveresponse(i, m, mci, ctladdr, xstart, e);
				}
				else
				{
					*t++ = ',';
					for (p = to->q_paddr; *p; *t++ = *p++)
						continue;
					*t = '\0';
				}
			}

			/* now send the data */
			if (tobuf[0] == '\0')
			{
				rcode = EX_OK;
				e->e_to = NULL;
				if (bitset(MCIF_CACHED, mci->mci_flags))
					smtprset(m, mci, e);
			}
			else
			{
				e->e_to = tobuf + 1;
				rcode = smtpdata(m, mci, e);
			}
		}
# if DAEMON
		if (rcode == EX_TEMPFAIL && curhost != NULL && *curhost != '\0')
		{
			/* try next MX site */
			goto tryhost;
		}
# endif
	}
#else /* not SMTP */
	{
		syserr("554 deliver: need SMTP compiled to use clever mailer");
		rcode = EX_CONFIG;
		goto give_up;
	}
#endif /* SMTP */
#if NAMED_BIND
	if (ConfigLevel < 2)
		_res.options |= RES_DEFNAMES | RES_DNSRCH;	/* XXX */
#endif

	if (tTd(62, 1))
		checkfds("after delivery");

	/*
	**  Do final status disposal.
	**	We check for something in tobuf for the SMTP case.
	**	If we got a temporary failure, arrange to queue the
	**		addressees.
	*/

  give_up:
#if SMTP
# if _FFR_LMTP
	if (bitnset(M_LMTP, m->m_flags))
	{
		tobuf[0] = '\0';
		anyok = FALSE;
	}
	else
# endif
#endif
		anyok = rcode == EX_OK;

	for (to = tochain; to != NULL; to = to->q_tchain)
	{
		/* see if address already marked */
		if (bitset(QBADADDR|QQUEUEUP, to->q_flags))
			continue;

#if SMTP
# if _FFR_LMTP
		/* if running LMTP, get the status for each address */
		if (bitnset(M_LMTP, m->m_flags))
		{
			rcode = smtpgetstat(m, mci, e);
			if (rcode == EX_OK)
			{
				if (strlen(to->q_paddr) + strlen(tobuf) + 2 >= sizeof tobuf)
				{
					syserr("LMTP tobuf overflow");
				}
				else
				{
					strcat(tobuf, ",");
					strcat(tobuf, to->q_paddr);
				}
				anyok = TRUE;
			}
			else
			{
				e->e_to = to->q_paddr;
				markfailure(e, to, mci, rcode);
				giveresponse(rcode, m, mci, ctladdr, xstart, e);
				e->e_to = tobuf + 1;
				continue;
			}
		}
		else
# endif
#endif
		{
			/* mark bad addresses */
			if (rcode != EX_OK)
			{
				if (goodmxfound && rcode == EX_NOHOST)
					rcode = EX_TEMPFAIL;
				markfailure(e, to, mci, rcode);
				continue;
			}
		}

		/* successful delivery */
		to->q_flags |= QSENT;
		to->q_statdate = curtime();
		e->e_nsent++;
		if (bitnset(M_LOCALMAILER, m->m_flags) &&
		    bitset(QPINGONSUCCESS, to->q_flags))
		{
			to->q_flags |= QDELIVERED;
			to->q_status = "2.1.5";
			fprintf(e->e_xfp, "%s... Successfully delivered\n",
				to->q_paddr);
		}
		else if (bitset(QPINGONSUCCESS, to->q_flags) &&
			 bitset(QPRIMARY, to->q_flags) &&
			 !bitset(MCIF_DSN, mci->mci_flags))
		{
			to->q_flags |= QRELAYED;
			fprintf(e->e_xfp, "%s... relayed; expect no further notifications\n",
				to->q_paddr);
		}
	}

#if SMTP
# if _FFR_LMTP
	if (bitnset(M_LMTP, m->m_flags))
	{
		/*
		**  Global information applies to the last recipient only;
		**  clear it out to avoid bogus errors.
		*/

		rcode = EX_OK;
		e->e_statmsg = NULL;

		/* reset the mci state for the next transaction */
		if (mci != NULL && mci->mci_state == MCIS_ACTIVE)
			mci->mci_state = MCIS_OPEN;
	}
# endif
#endif

	if (tobuf[0] != '\0')
		giveresponse(rcode, m, mci, ctladdr, xstart, e);
	if (anyok)
		markstats(e, tochain);
	mci_store_persistent(mci);

#if SMTP
	/* now close the connection */
	if (clever && mci != NULL && mci->mci_state != MCIS_CLOSED &&
	    !bitset(MCIF_CACHED, mci->mci_flags))
		smtpquit(m, mci, e);
#endif

	/*
	**  Restore state and return.
	*/

#if XDEBUG
	{
		char wbuf[MAXLINE];

		/* make absolutely certain 0, 1, and 2 are in use */
		snprintf(wbuf, sizeof wbuf, "%s... end of deliver(%s)",
			e->e_to == NULL ? "NO-TO-LIST"
					: shortenstring(e->e_to, 203),
			m->m_name);
		checkfd012(wbuf);
	}
#endif

	errno = 0;
	define('g', (char *) NULL, e);
	return (rcode);
}
/*
**  MARKFAILURE -- mark a failure on a specific address.
**
**	Parameters:
**		e -- the envelope we are sending.
**		q -- the address to mark.
**		mci -- mailer connection information.
**		rcode -- the code signifying the particular failure.
**
**	Returns:
**		none.
**
**	Side Effects:
**		marks the address (and possibly the envelope) with the
**			failure so that an error will be returned or
**			the message will be queued, as appropriate.
*/

void
markfailure(e, q, mci, rcode)
	register ENVELOPE *e;
	register ADDRESS *q;
	register MCI *mci;
	int rcode;
{
	char *stat = NULL;

	switch (rcode)
	{
	  case EX_OK:
		break;

	  case EX_TEMPFAIL:
	  case EX_IOERR:
	  case EX_OSERR:
		q->q_flags |= QQUEUEUP;
		q->q_flags &= ~QDONTSEND;
		break;

	  default:
		q->q_flags |= QBADADDR;
		break;
	}

	/* find most specific error code possible */
	if (mci != NULL && mci->mci_status != NULL)
	{
		q->q_status = mci->mci_status;
		q->q_rstatus = mci->mci_rstatus;
	}
	else if (e->e_status != NULL)
	{
		q->q_status = e->e_status;
		q->q_rstatus = NULL;
	}
	else
	{
		switch (rcode)
		{
		  case EX_USAGE:
			stat = "5.5.4";
			break;

		  case EX_DATAERR:
			stat = "5.5.2";
			break;

		  case EX_NOUSER:
			stat = "5.1.1";
			break;

		  case EX_NOHOST:
			stat = "5.1.2";
			break;

		  case EX_NOINPUT:
		  case EX_CANTCREAT:
		  case EX_NOPERM:
			stat = "5.3.0";
			break;

		  case EX_UNAVAILABLE:
		  case EX_SOFTWARE:
		  case EX_OSFILE:
		  case EX_PROTOCOL:
		  case EX_CONFIG:
			stat = "5.5.0";
			break;

		  case EX_OSERR:
		  case EX_IOERR:
			stat = "4.5.0";
			break;

		  case EX_TEMPFAIL:
			stat = "4.2.0";
			break;
		}
		if (stat != NULL)
			q->q_status = stat;
	}

	q->q_statdate = curtime();
	if (CurHostName != NULL && CurHostName[0] != '\0')
		q->q_statmta = newstr(CurHostName);
	if (rcode != EX_OK && q->q_rstatus == NULL &&
	    q->q_mailer != NULL && q->q_mailer->m_diagtype != NULL &&
	    strcasecmp(q->q_mailer->m_diagtype, "UNIX") == 0)
	{
		char buf[30];

		(void) snprintf(buf, sizeof buf, "%d", rcode);
		q->q_rstatus = newstr(buf);
	}
}
/*
**  ENDMAILER -- Wait for mailer to terminate.
**
**	We should never get fatal errors (e.g., segmentation
**	violation), so we report those specially.  For other
**	errors, we choose a status message (into statmsg),
**	and if it represents an error, we print it.
**
**	Parameters:
**		pid -- pid of mailer.
**		e -- the current envelope.
**		pv -- the parameter vector that invoked the mailer
**			(for error messages).
**
**	Returns:
**		exit code of mailer.
**
**	Side Effects:
**		none.
*/

int
endmailer(mci, e, pv)
	register MCI *mci;
	register ENVELOPE *e;
	char **pv;
{
	int st;

	mci_unlock_host(mci);

	/* close any connections */
	if (mci->mci_in != NULL)
		(void) xfclose(mci->mci_in, mci->mci_mailer->m_name, "mci_in");
	if (mci->mci_out != NULL)
		(void) xfclose(mci->mci_out, mci->mci_mailer->m_name, "mci_out");
	mci->mci_in = mci->mci_out = NULL;
	mci->mci_state = MCIS_CLOSED;

	/* in the IPC case there is nothing to wait for */
	if (mci->mci_pid == 0)
		return (EX_OK);

#if _FFR_TIMEOUT_WAIT
	put a timeout around the wait
#endif

	/* wait for the mailer process to die and collect status */
	st = waitfor(mci->mci_pid);
	if (st == -1)
	{
		syserr("endmailer %s: wait", mci->mci_mailer->m_name);
		return (EX_SOFTWARE);
	}

	if (WIFEXITED(st))
	{
		/* normal death -- return status */
		return (WEXITSTATUS(st));
	}

	/* it died a horrid death */
	syserr("451 mailer %s died with signal %o",
		mci->mci_mailer->m_name, st);

	/* log the arguments */
	if (pv != NULL && e->e_xfp != NULL)
	{
		register char **av;

		fprintf(e->e_xfp, "Arguments:");
		for (av = pv; *av != NULL; av++)
			fprintf(e->e_xfp, " %s", *av);
		fprintf(e->e_xfp, "\n");
	}

	ExitStat = EX_TEMPFAIL;
	return (EX_TEMPFAIL);
}
/*
**  GIVERESPONSE -- Interpret an error response from a mailer
**
**	Parameters:
**		stat -- the status code from the mailer (high byte
**			only; core dumps must have been taken care of
**			already).
**		m -- the mailer info for this mailer.
**		mci -- the mailer connection info -- can be NULL if the
**			response is given before the connection is made.
**		ctladdr -- the controlling address for the recipient
**			address(es).
**		xstart -- the transaction start time, for computing
**			transaction delays.
**		e -- the current envelope.
**
**	Returns:
**		none.
**
**	Side Effects:
**		Errors may be incremented.
**		ExitStat may be set.
*/

void
giveresponse(stat, m, mci, ctladdr, xstart, e)
	int stat;
	register MAILER *m;
	register MCI *mci;
	ADDRESS *ctladdr;
	time_t xstart;
	ENVELOPE *e;
{
	register const char *statmsg;
	extern char *SysExMsg[];
	register int i;
	extern int N_SysEx;
	char buf[MAXLINE];

	if (e == NULL)
		syserr("giveresponse: null envelope");

	/*
	**  Compute status message from code.
	*/

	i = stat - EX__BASE;
	if (stat == 0)
	{
		statmsg = "250 Sent";
		if (e->e_statmsg != NULL)
		{
			(void) snprintf(buf, sizeof buf, "%s (%s)",
				statmsg, shortenstring(e->e_statmsg, 403));
			statmsg = buf;
		}
	}
	else if (i < 0 || i > N_SysEx)
	{
		(void) snprintf(buf, sizeof buf, "554 unknown mailer error %d",
			stat);
		stat = EX_UNAVAILABLE;
		statmsg = buf;
	}
	else if (stat == EX_TEMPFAIL)
	{
		char *bp = buf;

		snprintf(bp, SPACELEFT(buf, bp), "%s", SysExMsg[i] + 1);
		bp += strlen(bp);
#if NAMED_BIND
		if (h_errno == TRY_AGAIN)
			statmsg = errstring(h_errno+E_DNSBASE);
		else
#endif
		{
			if (errno != 0)
				statmsg = errstring(errno);
			else
			{
#if SMTP
				statmsg = SmtpError;
#else /* SMTP */
				statmsg = NULL;
#endif /* SMTP */
			}
		}
		if (statmsg != NULL && statmsg[0] != '\0')
			snprintf(bp, SPACELEFT(buf, bp), ": %s", statmsg);
		statmsg = buf;
	}
#if NAMED_BIND
	else if (stat == EX_NOHOST && h_errno != 0)
	{
		statmsg = errstring(h_errno + E_DNSBASE);
		(void) snprintf(buf, sizeof buf, "%s (%s)",
			SysExMsg[i] + 1, statmsg);
		statmsg = buf;
	}
#endif
	else
	{
		statmsg = SysExMsg[i];
		if (*statmsg++ == ':')
		{
			(void) snprintf(buf, sizeof buf, "%s: %s",
				statmsg, errstring(errno));
			statmsg = buf;
		}
	}

	/*
	**  Print the message as appropriate
	*/

	if (stat == EX_OK || stat == EX_TEMPFAIL)
	{
		extern char MsgBuf[];

		message("%s", &statmsg[4]);
		if (stat == EX_TEMPFAIL && e->e_xfp != NULL)
			fprintf(e->e_xfp, "%s\n", &MsgBuf[4]);
	}
	else
	{
		char mbuf[8];

		Errors++;
		snprintf(mbuf, sizeof mbuf, "%.3s %%s", statmsg);
		usrerr(mbuf, &statmsg[4]);
	}

	/*
	**  Final cleanup.
	**	Log a record of the transaction.  Compute the new
	**	ExitStat -- if we already had an error, stick with
	**	that.
	*/

	if (OpMode != MD_VERIFY && !bitset(EF_VRFYONLY, e->e_flags) &&
	    LogLevel > ((stat == EX_TEMPFAIL) ? 8 : (stat == EX_OK) ? 7 : 6))
		logdelivery(m, mci, &statmsg[4], ctladdr, xstart, e);

	if (tTd(11, 2))
		printf("giveresponse: stat=%d, e->e_message=%s\n",
			stat, e->e_message == NULL ? "<NULL>" : e->e_message);

	if (stat != EX_TEMPFAIL)
		setstat(stat);
	if (stat != EX_OK && (stat != EX_TEMPFAIL || e->e_message == NULL))
	{
		if (e->e_message != NULL)
			free(e->e_message);
		e->e_message = newstr(&statmsg[4]);
	}
	errno = 0;
#if NAMED_BIND
	h_errno = 0;
#endif
}
/*
**  LOGDELIVERY -- log the delivery in the system log
**
**	Care is taken to avoid logging lines that are too long, because
**	some versions of syslog have an unfortunate proclivity for core
**	dumping.  This is a hack, to be sure, that is at best empirical.
**
**	Parameters:
**		m -- the mailer info.  Can be NULL for initial queue.
**		mci -- the mailer connection info -- can be NULL if the
**			log is occuring when no connection is active.
**		stat -- the message to print for the status.
**		ctladdr -- the controlling address for the to list.
**		xstart -- the transaction start time, used for
**			computing transaction delay.
**		e -- the current envelope.
**
**	Returns:
**		none
**
**	Side Effects:
**		none
*/

void
logdelivery(m, mci, stat, ctladdr, xstart, e)
	MAILER *m;
	register MCI *mci;
	const char *stat;
	ADDRESS *ctladdr;
	time_t xstart;
	register ENVELOPE *e;
{
	register char *bp;
	register char *p;
	int l;
	char buf[1024];

#  if (SYSLOG_BUFSIZE) >= 256
	/* ctladdr: max 106 bytes */
	bp = buf;
	if (ctladdr != NULL)
	{
		snprintf(bp, SPACELEFT(buf, bp), ", ctladdr=%s",
			shortenstring(ctladdr->q_paddr, 83));
		bp += strlen(bp);
		if (bitset(QGOODUID, ctladdr->q_flags))
		{
			(void) snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
					ctladdr->q_uid, ctladdr->q_gid);
			bp += strlen(bp);
		}
	}

	/* delay & xdelay: max 41 bytes */
	snprintf(bp, SPACELEFT(buf, bp), ", delay=%s",
		pintvl(curtime() - e->e_ctime, TRUE));
	bp += strlen(bp);

	if (xstart != (time_t) 0)
	{
		snprintf(bp, SPACELEFT(buf, bp), ", xdelay=%s",
			pintvl(curtime() - xstart, TRUE));
		bp += strlen(bp);
	}

	/* mailer: assume about 19 bytes (max 10 byte mailer name) */
	if (m != NULL)
	{
		snprintf(bp, SPACELEFT(buf, bp), ", mailer=%s", m->m_name);
		bp += strlen(bp);
	}

	/* relay: max 66 bytes for IPv4 addresses */
	if (mci != NULL && mci->mci_host != NULL)
	{
# if DAEMON
		extern SOCKADDR CurHostAddr;
# endif

		snprintf(bp, SPACELEFT(buf, bp), ", relay=%s",
			shortenstring(mci->mci_host, 40));
		bp += strlen(bp);

# if DAEMON
		if (CurHostAddr.sa.sa_family != 0)
		{
			snprintf(bp, SPACELEFT(buf, bp), " [%s]",
				anynet_ntoa(&CurHostAddr));
		}
# endif
	}
	else if (strcmp(stat, "queued") != 0)
	{
		char *p = macvalue('h', e);

		if (p != NULL && p[0] != '\0')
		{
			snprintf(bp, SPACELEFT(buf, bp), ", relay=%s",
				shortenstring(p, 40));
		}
	}
	bp += strlen(bp);

#define STATLEN		(((SYSLOG_BUFSIZE) - 100) / 4)
#if (STATLEN) < 63
# undef STATLEN
# define STATLEN	63
#endif
#if (STATLEN) > 203
# undef STATLEN
# define STATLEN	203
#endif

	/* stat: max 210 bytes */
	if ((bp - buf) > (sizeof buf - ((STATLEN) + 20)))
	{
		/* desperation move -- truncate data */
		bp = buf + sizeof buf - ((STATLEN) + 17);
		strcpy(bp, "...");
		bp += 3;
	}

	(void) strcpy(bp, ", stat=");
	bp += strlen(bp);

	(void) strcpy(bp, shortenstring(stat, (STATLEN)));

	/* id, to: max 13 + TOBUFSIZE bytes */
	l = SYSLOG_BUFSIZE - 100 - strlen(buf);
	p = e->e_to;
	while (strlen(p) >= (SIZE_T) l)
	{
		register char *q = strchr(p + l, ',');

		if (q == NULL)
			break;
		sm_syslog(LOG_INFO, e->e_id,
			"to=%.*s [more]%s",
			++q - p, p, buf);
		p = q;
	}
	sm_syslog(LOG_INFO, e->e_id, "to=%s%s", p, buf);

#  else		/* we have a very short log buffer size */

	l = SYSLOG_BUFSIZE - 85;
	p = e->e_to;
	while (strlen(p) >= (SIZE_T) l)
	{
		register char *q = strchr(p + l, ',');

		if (q == NULL)
			break;
		sm_syslog(LOG_INFO, e->e_id,
			"to=%.*s [more]",
			++q - p, p);
		p = q;
	}
	sm_syslog(LOG_INFO, e->e_id, "to=%s", p);

	if (ctladdr != NULL)
	{
		bp = buf;
		snprintf(bp, SPACELEFT(buf, bp), "ctladdr=%s",
			shortenstring(ctladdr->q_paddr, 83));
		bp += strlen(bp);
		if (bitset(QGOODUID, ctladdr->q_flags))
		{
			(void) snprintf(bp, SPACELEFT(buf, bp), " (%d/%d)",
					ctladdr->q_uid, ctladdr->q_gid);
			bp += strlen(bp);
		}
		sm_syslog(LOG_INFO, e->e_id, "%s", buf);
	}
	bp = buf;
	snprintf(bp, SPACELEFT(buf, bp), "delay=%s",
		pintvl(curtime() - e->e_ctime, TRUE));
	bp += strlen(bp);
	if (xstart != (time_t) 0)
	{
		snprintf(bp, SPACELEFT(buf, bp), ", xdelay=%s",
			pintvl(curtime() - xstart, TRUE));
		bp += strlen(bp);
	}

	if (m != NULL)
	{
		snprintf(bp, SPACELEFT(buf, bp), ", mailer=%s", m->m_name);
		bp += strlen(bp);
	}
	sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);

	buf[0] = '\0';
	bp = buf;
	if (mci != NULL && mci->mci_host != NULL)
	{
# if DAEMON
		extern SOCKADDR CurHostAddr;
# endif

		snprintf(bp, SPACELEFT(buf, bp), "relay=%.100s", mci->mci_host);
		bp += strlen(bp);

# if DAEMON
		if (CurHostAddr.sa.sa_family != 0)
			snprintf(bp, SPACELEFT(buf, bp), " [%.100s]",
				anynet_ntoa(&CurHostAddr));
# endif
	}
	else if (strcmp(stat, "queued") != 0)
	{
		char *p = macvalue('h', e);

		if (p != NULL && p[0] != '\0')
			snprintf(buf, sizeof buf, "relay=%.100s", p);
	}
	if (buf[0] != '\0')
		sm_syslog(LOG_INFO, e->e_id, "%.1000s", buf);

	sm_syslog(LOG_INFO, e->e_id, "stat=%s", shortenstring(stat, 63));
#  endif /* short log buffer */
}
/*
**  PUTFROMLINE -- output a UNIX-style from line (or whatever)
**
**	This can be made an arbitrary message separator by changing $l
**
**	One of the ugliest hacks seen by human eyes is contained herein:
**	UUCP wants those stupid "remote from <host>" lines.  Why oh why
**	does a well-meaning programmer such as myself have to deal with
**	this kind of antique garbage????
**
**	Parameters:
**		mci -- the connection information.
**		e -- the envelope.
**
**	Returns:
**		none
**
**	Side Effects:
**		outputs some text to fp.
*/

void
putfromline(mci, e)
	register MCI *mci;
	ENVELOPE *e;
{
	char *template = UnixFromLine;
	char buf[MAXLINE];
	char xbuf[MAXLINE];

	if (bitnset(M_NHDR, mci->mci_mailer->m_flags))
		return;

	if (bitnset(M_UGLYUUCP, mci->mci_mailer->m_flags))
	{
		char *bang;

		expand("\201g", buf, sizeof buf, e);
		bang = strchr(buf, '!');
		if (bang == NULL)
		{
			char *at;
			char hname[MAXNAME];

		    	/*
			** If we can construct a UUCP path, do so
			*/

			at = strrchr(buf, '@');
			if (at == NULL)
			{
				expand( "\201k", hname, sizeof hname, e);
				at = hname;
			}
			else
				*at++ = '\0';
			(void) snprintf(xbuf, sizeof xbuf,
				"From %.800s  \201d remote from %.100s\n",
				buf, at);
		}
		else
		{
			*bang++ = '\0';
			(void) snprintf(xbuf, sizeof xbuf,
				"From %.800s  \201d remote from %.100s\n",
				bang, buf);
			template = xbuf;
		}
	}
	expand(template, buf, sizeof buf, e);
	putxline(buf, strlen(buf), mci, PXLF_HEADER);
}
/*
**  PUTBODY -- put the body of a message.
**
**	Parameters:
**		mci -- the connection information.
**		e -- the envelope to put out.
**		separator -- if non-NULL, a message separator that must
**			not be permitted in the resulting message.
**
**	Returns:
**		none.
**
**	Side Effects:
**		The message is written onto fp.
*/

/* values for output state variable */
#define OS_HEAD		0	/* at beginning of line */
#define OS_CR		1	/* read a carriage return */
#define OS_INLINE	2	/* putting rest of line */

void
putbody(mci, e, separator)
	register MCI *mci;
	register ENVELOPE *e;
	char *separator;
{
	char buf[MAXLINE];

	/*
	**  Output the body of the message
	*/

	if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
	{
		char *df = queuename(e, 'd');

		e->e_dfp = fopen(df, "r");
		if (e->e_dfp == NULL)
			syserr("putbody: Cannot open %s for %s from %s",
				df, e->e_to, e->e_from.q_paddr);
	}
	if (e->e_dfp == NULL)
	{
		if (bitset(MCIF_INHEADER, mci->mci_flags))
		{
			putline("", mci);
			mci->mci_flags &= ~MCIF_INHEADER;
		}
		putline("<<< No Message Collected >>>", mci);
		goto endofmessage;
	}
	if (e->e_dfino == (ino_t) 0)
	{
		struct stat stbuf;

		if (fstat(fileno(e->e_dfp), &stbuf) < 0)
			e->e_dfino = -1;
		else
		{
			e->e_dfdev = stbuf.st_dev;
			e->e_dfino = stbuf.st_ino;
		}
	}
	rewind(e->e_dfp);

#if MIME8TO7
	if (bitset(MCIF_CVT8TO7, mci->mci_flags))
	{
		char *boundaries[MAXMIMENESTING + 1];

		/*
		**  Do 8 to 7 bit MIME conversion.
		*/

		/* make sure it looks like a MIME message */
		if (hvalue("MIME-Version", e->e_header) == NULL)
			putline("MIME-Version: 1.0", mci);

		if (hvalue("Content-Type", e->e_header) == NULL)
		{
			snprintf(buf, sizeof buf,
				"Content-Type: text/plain; charset=%s",
				defcharset(e));
			putline(buf, mci);
		}

		/* now do the hard work */
		boundaries[0] = NULL;
		mime8to7(mci, e->e_header, e, boundaries, M87F_OUTER);
	}
# if MIME7TO8
	else if (bitset(MCIF_CVT7TO8, mci->mci_flags))
	{
		mime7to8(mci, e->e_header, e);
	}
# endif
	else
#endif
	{
		int ostate;
		register char *bp;
		register char *pbp;
		register int c;
		register char *xp;
		int padc;
		char *buflim;
		int pos = 0;
		char peekbuf[10];

		/* we can pass it through unmodified */
		if (bitset(MCIF_INHEADER, mci->mci_flags))
		{
			putline("", mci);
			mci->mci_flags &= ~MCIF_INHEADER;
		}

		/* determine end of buffer; allow for short mailer lines */
		buflim = &buf[sizeof buf - 1];
		if (mci->mci_mailer->m_linelimit > 0 &&
		    mci->mci_mailer->m_linelimit < sizeof buf - 1)
			buflim = &buf[mci->mci_mailer->m_linelimit - 1];

		/* copy temp file to output with mapping */
		ostate = OS_HEAD;
		bp = buf;
		pbp = peekbuf;
		while (!ferror(mci->mci_out))
		{
			if (pbp > peekbuf)
				c = *--pbp;
			else if ((c = getc(e->e_dfp)) == EOF)
				break;
			if (bitset(MCIF_7BIT, mci->mci_flags))
				c &= 0x7f;
			switch (ostate)
			{
			  case OS_HEAD:
#if _FFR_NONULLS
				if (c == '\0' &&
				    bitnset(M_NONULLS, mci->mci_mailer->m_flags))
					break;
#endif
				if (c != '\r' && c != '\n' && bp < buflim)
				{
					*bp++ = c;
					break;
				}

				/* check beginning of line for special cases */
				*bp = '\0';
				pos = 0;
				padc = EOF;
				if (buf[0] == 'F' &&
				    bitnset(M_ESCFROM, mci->mci_mailer->m_flags) &&
				    strncmp(buf, "From ", 5) == 0)
				{
					padc = '>';
				}
				if (buf[0] == '-' && buf[1] == '-' &&
				    separator != NULL)
				{
					/* possible separator */
					int sl = strlen(separator);

					if (strncmp(&buf[2], separator, sl) == 0)
						padc = ' ';
				}
				if (buf[0] == '.' &&
				    bitnset(M_XDOT, mci->mci_mailer->m_flags))
				{
					padc = '.';
				}

				/* now copy out saved line */
				if (TrafficLogFile != NULL)
				{
					fprintf(TrafficLogFile, "%05d >>> ",
						(int) getpid());
					if (padc != EOF)
						putc(padc, TrafficLogFile);
					for (xp = buf; xp < bp; xp++)
						putc(*xp, TrafficLogFile);
					if (c == '\n')
						fputs(mci->mci_mailer->m_eol,
						      TrafficLogFile);
				}
				if (padc != EOF)
				{
					putc(padc, mci->mci_out);
					pos++;
				}
				for (xp = buf; xp < bp; xp++)
					putc(*xp, mci->mci_out);
				if (c == '\n')
				{
					fputs(mci->mci_mailer->m_eol,
					      mci->mci_out);
					pos = 0;
				}
				else
				{
					pos += bp - buf;
					if (c != '\r')
						*pbp++ = c;
				}
				bp = buf;

				/* determine next state */
				if (c == '\n')
					ostate = OS_HEAD;
				else if (c == '\r')
					ostate = OS_CR;
				else
					ostate = OS_INLINE;
				continue;

			  case OS_CR:
				if (c == '\n')
				{
					/* got CRLF */
					fputs(mci->mci_mailer->m_eol, mci->mci_out);
					if (TrafficLogFile != NULL)
					{
						fputs(mci->mci_mailer->m_eol,
						      TrafficLogFile);
					}
					ostate = OS_HEAD;
					continue;
				}

				/* had a naked carriage return */
				*pbp++ = c;
				c = '\r';
				ostate = OS_INLINE;
				goto putch;

			  case OS_INLINE:
				if (c == '\r')
				{
					ostate = OS_CR;
					continue;
				}
#if _FFR_NONULLS
				if (c == '\0' &&
				    bitnset(M_NONULLS, mci->mci_mailer->m_flags))
					break;
#endif
putch:
				if (mci->mci_mailer->m_linelimit > 0 &&
				    pos > mci->mci_mailer->m_linelimit &&
				    c != '\n')
				{
					putc('!', mci->mci_out);
					fputs(mci->mci_mailer->m_eol, mci->mci_out);
					if (TrafficLogFile != NULL)
					{
						fprintf(TrafficLogFile, "!%s",
							mci->mci_mailer->m_eol);
					}
					ostate = OS_HEAD;
					*pbp++ = c;
					continue;
				}
				if (c == '\n')
				{
					if (TrafficLogFile != NULL)
						fputs(mci->mci_mailer->m_eol,
						      TrafficLogFile);
					fputs(mci->mci_mailer->m_eol, mci->mci_out);
					pos = 0;
					ostate = OS_HEAD;
				}
				else
				{
					if (TrafficLogFile != NULL)
						putc(c, TrafficLogFile);
					putc(c, mci->mci_out);
					pos++;
					ostate = OS_INLINE;
				}
				break;
			}
		}

		/* make sure we are at the beginning of a line */
		if (bp > buf)
		{
			if (TrafficLogFile != NULL)
			{
				for (xp = buf; xp < bp; xp++)
					putc(*xp, TrafficLogFile);
			}
			for (xp = buf; xp < bp; xp++)
				putc(*xp, mci->mci_out);
			pos += bp - buf;
		}
		if (pos > 0)
		{
			if (TrafficLogFile != NULL)
				fputs(mci->mci_mailer->m_eol, TrafficLogFile);
			fputs(mci->mci_mailer->m_eol, mci->mci_out);
		}
	}

	if (ferror(e->e_dfp))
	{
		syserr("putbody: df%s: read error", e->e_id);
		ExitStat = EX_IOERR;
	}

endofmessage:
	/* some mailers want extra blank line at end of message */
	if (bitnset(M_BLANKEND, mci->mci_mailer->m_flags) &&
	    buf[0] != '\0' && buf[0] != '\n')
		putline("", mci);

	(void) fflush(mci->mci_out);
	if (ferror(mci->mci_out) && errno != EPIPE)
	{
		syserr("putbody: write error");
		ExitStat = EX_IOERR;
	}
	errno = 0;
}
/*
**  MAILFILE -- Send a message to a file.
**
**	If the file has the setuid/setgid bits set, but NO execute
**	bits, sendmail will try to become the owner of that file
**	rather than the real user.  Obviously, this only works if
**	sendmail runs as root.
**
**	This could be done as a subordinate mailer, except that it
**	is used implicitly to save messages in ~/dead.letter.  We
**	view this as being sufficiently important as to include it
**	here.  For example, if the system is dying, we shouldn't have
**	to create another process plus some pipes to save the message.
**
**	Parameters:
**		filename -- the name of the file to send to.
**		ctladdr -- the controlling address header -- includes
**			the userid/groupid to be when sending.
**		sfflags -- flags for opening.
**		e -- the current envelope.
**
**	Returns:
**		The exit code associated with the operation.
**
**	Side Effects:
**		none.
*/

static jmp_buf	CtxMailfileTimeout;
static void	mailfiletimeout();

int
mailfile(filename, ctladdr, sfflags, e)
	char *volatile filename;
	ADDRESS *ctladdr;
	volatile int sfflags;
	register ENVELOPE *e;
{
	register FILE *f;
	register pid_t pid = -1;
	volatile int mode = ST_MODE_NOFILE;
	bool suidwarn = geteuid() == 0;
	EVENT *ev;

	if (tTd(11, 1))
	{
		printf("mailfile %s\n  ctladdr=", filename);
		printaddr(ctladdr, FALSE);
	}

	if (e->e_xfp != NULL)
		fflush(e->e_xfp);

	/*
	**  Special case /dev/null.  This allows us to restrict file
	**  delivery to regular files only.
	*/

	if (strcmp(filename, "/dev/null") == 0)
		return EX_OK;

	/*
	**  Fork so we can change permissions here.
	**	Note that we MUST use fork, not vfork, because of
	**	the complications of calling subroutines, etc.
	*/

	DOFORK(fork);

	if (pid < 0)
		return (EX_OSERR);
	else if (pid == 0)
	{
		/* child -- actually write to file */
		struct stat stb;
		MCI mcibuf;
		volatile int oflags = O_WRONLY|O_APPEND;

		if (e->e_lockfp != NULL)
			(void) close(fileno(e->e_lockfp));

		(void) setsignal(SIGINT, SIG_DFL);
		(void) setsignal(SIGHUP, SIG_DFL);
		(void) setsignal(SIGTERM, SIG_DFL);
		(void) umask(OldUmask);
		e->e_to = filename;
		ExitStat = EX_OK;

		if (setjmp(CtxMailfileTimeout) != 0)
		{
			exit(EX_TEMPFAIL);
		}

		if (TimeOuts.to_fileopen > 0)
			ev = setevent(TimeOuts.to_fileopen, mailfiletimeout, 0);
		else
			ev = NULL;

#ifdef HASLSTAT
		if (lstat(filename, &stb) < 0)
#else
		if (stat(filename, &stb) < 0)
#endif
		{
			stb.st_mode = ST_MODE_NOFILE;
			mode = FileMode;
			oflags |= O_CREAT|O_EXCL;
		}
		else if (bitset(0111, stb.st_mode) || stb.st_nlink != 1 ||
			 (SafeFileEnv != NULL && !S_ISREG(stb.st_mode)))
			exit(EX_CANTCREAT);
		if (mode == ST_MODE_NOFILE)
			mode = stb.st_mode;

		/* limit the errors to those actually caused in the child */
		errno = 0;
		ExitStat = EX_OK;

		if (ctladdr != NULL || bitset(SFF_RUNASREALUID, sfflags))
		{
			/* ignore setuid and setgid bits */
			mode &= ~(S_ISGID|S_ISUID);
		}

		/* we have to open the dfile BEFORE setuid */
		if (e->e_dfp == NULL && bitset(EF_HAS_DF, e->e_flags))
		{
			char *df = queuename(e, 'd');

			e->e_dfp = fopen(df, "r");
			if (e->e_dfp == NULL)
			{
				syserr("mailfile: Cannot open %s for %s from %s",
					df, e->e_to, e->e_from.q_paddr);
			}
		}

		/* select a new user to run as */
		if (!bitset(SFF_RUNASREALUID, sfflags))
		{
			if (bitset(S_ISUID, mode))
			{
				RealUserName = NULL;
				RealUid = stb.st_uid;
			}
			else if (ctladdr != NULL && ctladdr->q_uid != 0)
			{
				if (ctladdr->q_ruser != NULL)
					RealUserName = ctladdr->q_ruser;
				else
					RealUserName = ctladdr->q_user;
				RealUid = ctladdr->q_uid;
			}
			else if (FileMailer != NULL && FileMailer->m_uid != 0)
			{
				RealUserName = DefUser;
				RealUid = FileMailer->m_uid;
			}
			else
			{
				RealUserName = DefUser;
				RealUid = DefUid;
			}

			/* select a new group to run as */
			if (bitset(S_ISGID, mode))
				RealGid = stb.st_gid;
			else if (ctladdr != NULL && ctladdr->q_uid != 0)
				RealGid = ctladdr->q_gid;
			else if (FileMailer != NULL && FileMailer->m_gid != 0)
				RealGid = FileMailer->m_gid;
			else
				RealGid = DefGid;
		}

		/* last ditch */
		if (!bitset(SFF_ROOTOK, sfflags))
		{
			if (RealUid == 0)
				RealUid = DefUid;
			if (RealGid == 0)
				RealGid = DefGid;
		}

		/* set group id list (needs /etc/group access) */
		if (RealUserName != NULL && !DontInitGroups)
			(void) initgroups(RealUserName, RealGid);

		/* if you have a safe environment, go into it */
		if (SafeFileEnv != NULL && SafeFileEnv[0] != '\0')
		{
			int i;

			if (chroot(SafeFileEnv) < 0)
			{
				syserr("mailfile: Cannot chroot(%s)",
					SafeFileEnv);
				exit(EX_CANTCREAT);
			}
			i = strlen(SafeFileEnv);
			if (strncmp(SafeFileEnv, filename, i) == 0)
				filename += i;
		}
		if (chdir("/") < 0)
			syserr("mailfile: cannot chdir(/)");

		/* now reset the group and user ids */
		endpwent();
		if (setgid(RealGid) < 0 && suidwarn)
			syserr("mailfile: setgid(%ld) failed", (long) RealGid);
		vendor_set_uid(RealUid);
		if (setuid(RealUid) < 0 && suidwarn)
			syserr("mailfile: setuid(%ld) failed", (long) RealUid);

		sfflags |= SFF_NOPATHCHECK|SFF_NOLINK;
		sfflags &= ~SFF_OPENASROOT;
		f = safefopen(filename, oflags, FileMode, sfflags);
		if (f == NULL)
		{
			message("554 cannot open: %s", errstring(errno));
			exit(EX_CANTCREAT);
		}
		if (filechanged(filename, fileno(f), &stb, sfflags))
		{
			message("554 file changed after open");
			exit(EX_CANTCREAT);
		}
		if (fstat(fileno(f), &stb) < 0)
		{
			message("554 cannot fstat %s", errstring(errno));
			exit(EX_CANTCREAT);
		}

		if (ev != NULL)
			clrevent(ev);

		bzero(&mcibuf, sizeof mcibuf);
		mcibuf.mci_mailer = FileMailer;
		mcibuf.mci_out = f;
		if (bitnset(M_7BITS, FileMailer->m_flags))
			mcibuf.mci_flags |= MCIF_7BIT;

		putfromline(&mcibuf, e);
		(*e->e_puthdr)(&mcibuf, e->e_header, e);
		(*e->e_putbody)(&mcibuf, e, NULL);
		putline("\n", &mcibuf);
		if (fflush(f) < 0 || ferror(f))
		{
			message("451 I/O error: %s", errstring(errno));
			setstat(EX_IOERR);
		}

		/* reset ISUID & ISGID bits for paranoid systems */
#if HASFCHMOD
		(void) fchmod(fileno(f), (MODE_T) stb.st_mode);
#else
		(void) chmod(filename, (MODE_T) stb.st_mode);
#endif
		(void) xfclose(f, "mailfile", filename);
		(void) fflush(stdout);
		setuid(RealUid);
		exit(ExitStat);
		/*NOTREACHED*/
	}
	else
	{
		/* parent -- wait for exit status */
		int st;

		st = waitfor(pid);
		if (WIFEXITED(st))
			return (WEXITSTATUS(st));
		else
		{
			syserr("child died on signal %d", st);
			return (EX_UNAVAILABLE);
		}
		/*NOTREACHED*/
	}
	return EX_UNAVAILABLE;	/* avoid compiler warning on IRIX */
}

static void
mailfiletimeout()
{
	longjmp(CtxMailfileTimeout, 1);
}
/*
**  HOSTSIGNATURE -- return the "signature" for a host.
**
**	The signature describes how we are going to send this -- it
**	can be just the hostname (for non-Internet hosts) or can be
**	an ordered list of MX hosts.
**
**	Parameters:
**		m -- the mailer describing this host.
**		host -- the host name.
**		e -- the current envelope.
**
**	Returns:
**		The signature for this host.
**
**	Side Effects:
**		Can tweak the symbol table.
*/

char *
hostsignature(m, host, e)
	register MAILER *m;
	char *host;
	ENVELOPE *e;
{
	register char *p;
	register STAB *s;
	int i;
	int len;
#if NAMED_BIND
	int nmx;
	char *hp;
	char *endp;
	int oldoptions = _res.options;
	char *mxhosts[MAXMXHOSTS + 1];
#endif

	/*
	**  Check to see if this uses IPC -- if not, it can't have MX records.
	*/

	p = m->m_mailer;
	if (strcmp(p, "[IPC]") != 0 && strcmp(p, "[TCP]") != 0)
	{
		/* just an ordinary mailer */
		return host;
	}

	/*
	**  Look it up in the symbol table.
	*/

	s = stab(host, ST_HOSTSIG, ST_ENTER);
	if (s->s_hostsig != NULL)
		return s->s_hostsig;

	/*
	**  Not already there -- create a signature.
	*/

#if NAMED_BIND
	if (ConfigLevel < 2)
		_res.options &= ~(RES_DEFNAMES | RES_DNSRCH);	/* XXX */

	for (hp = host; hp != NULL; hp = endp)
	{
		endp = strchr(hp, ':');
		if (endp != NULL)
			*endp = '\0';

		if (bitnset(M_NOMX, m->m_flags))
		{
			/* skip MX lookups */
			nmx = 1;
			mxhosts[0] = hp;
		}
		else
		{
			auto int rcode;

			nmx = getmxrr(hp, mxhosts, TRUE, &rcode);
			if (nmx <= 0)
			{
				register MCI *mci;

				/* update the connection info for this host */
				mci = mci_get(hp, m);
				mci->mci_errno = errno;
				mci->mci_herrno = h_errno;
				mci->mci_lastuse = curtime();
				mci_setstat(mci, rcode, NULL, NULL);

				/* use the original host name as signature */
				nmx = 1;
				mxhosts[0] = hp;
			}
		}

		len = 0;
		for (i = 0; i < nmx; i++)
		{
			len += strlen(mxhosts[i]) + 1;
		}
		if (s->s_hostsig != NULL)
			len += strlen(s->s_hostsig) + 1;
		p = xalloc(len);
		if (s->s_hostsig != NULL)
		{
			(void) strcpy(p, s->s_hostsig);
			free(s->s_hostsig);
			s->s_hostsig = p;
			p += strlen(p);
			*p++ = ':';
		}
		else
			s->s_hostsig = p;
		for (i = 0; i < nmx; i++)
		{
			if (i != 0)
				*p++ = ':';
			strcpy(p, mxhosts[i]);
			p += strlen(p);
		}
		if (endp != NULL)
			*endp++ = ':';
	}
	makelower(s->s_hostsig);
	if (ConfigLevel < 2)
		_res.options = oldoptions;
#else
	/* not using BIND -- the signature is just the host name */
	s->s_hostsig = host;
#endif
	if (tTd(17, 1))
		printf("hostsignature(%s) = %s\n", host, s->s_hostsig);
	return s->s_hostsig;
}