File: pfixtls.diff

package info (click to toggle)
postfix-tls 1.1.11%2Btls0.7.15-0.woody1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,812 kB
  • ctags: 1,136
  • sloc: ansic: 10,550; makefile: 1,085; sh: 407; perl: 15; csh: 7
file content (7366 lines) | stat: -rw-r--r-- 249,647 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
diff -r -u --new-file postfix-1.1.0-vanilla/Makefile.in postfix-1.1.0/Makefile.in
--- postfix-1.1.0-vanilla/Makefile.in	Mon Jan 14 02:17:09 2002
+++ postfix-1.1.0/Makefile.in	Thu Jan 17 21:30:50 2002
@@ -6,7 +6,8 @@
 	src/lmtp src/trivial-rewrite src/qmgr src/smtp src/bounce src/pipe \
 	src/showq src/postalias src/postcat src/postconf src/postdrop \
 	src/postkick src/postlock src/postlog src/postmap src/postqueue \
-	src/postsuper src/nqmgr src/qmqpd src/spawn src/flush src/virtual
+	src/postsuper src/nqmgr src/qmqpd src/spawn src/flush src/virtual \
+	src/tlsmgr
 MANDIRS	= proto man html
 
 default: update
diff -r -u --new-file postfix-1.1.0-vanilla/conf/master.cf postfix-1.1.0/conf/master.cf
--- postfix-1.1.0-vanilla/conf/master.cf	Thu Jan 10 21:24:59 2002
+++ postfix-1.1.0/conf/master.cf	Thu Jan 17 21:30:50 2002
@@ -69,11 +69,16 @@
 # 		(yes)	(yes)	(yes)	(never)	(50)
 # ==========================================================================
 smtp	  inet	n	-	n	-	-	smtpd
+#smtps	  inet	n	-	n	-	-	smtpd
+#  -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes
+#submission	inet	n	-	n	-	-	smtpd
+#  -o smtpd_enforce_tls=yes -o smtpd_sasl_auth_enable=yes
 #628	  inet	n	-	n	-	-	qmqpd
 pickup	  fifo	n	-	n	60	1	pickup
 cleanup	  unix	n	-	n	-	0	cleanup
 qmgr	  fifo	n	-	n	300	1	qmgr
 #qmgr	  fifo	n	-	n	300	1	nqmgr
+#tlsmgr	  fifo	-	-	n	300	1	tlsmgr
 rewrite	  unix	-	-	n	-	-	trivial-rewrite
 bounce	  unix	-	-	n	-	0	bounce
 defer	  unix	-	-	n	-	0	bounce
diff -r -u --new-file postfix-1.1.0-vanilla/conf/postfix-files postfix-1.1.0/conf/postfix-files
--- postfix-1.1.0-vanilla/conf/postfix-files	Thu Jan 17 18:50:55 2002
+++ postfix-1.1.0/conf/postfix-files	Thu Jan 17 21:30:50 2002
@@ -68,6 +68,7 @@
 $daemon_directory/smtp:f:root:-:755
 $daemon_directory/smtpd:f:root:-:755
 $daemon_directory/spawn:f:root:-:755
+$daemon_directory/tlsmgr:f:root:-:755
 $daemon_directory/trivial-rewrite:f:root:-:755
 $daemon_directory/virtual:f:root:-:755
 $command_directory/postalias:f:root:-:755
@@ -138,6 +139,7 @@
 $manpage_directory/man8/smtp.8:f:root:-:644
 $manpage_directory/man8/smtpd.8:f:root:-:644
 $manpage_directory/man8/spawn.8:f:root:-:644
+$manpage_directory/man8/tlsmgr.8:f:root:-:644
 $manpage_directory/man8/trivial-rewrite.8:f:root:-:644
 $manpage_directory/man8/virtual.8:f:root:-:644
 $sample_directory/sample-aliases.cf:f:root:-:644
@@ -164,6 +166,7 @@
 $sample_directory/sample-rewrite.cf:f:root:-:644
 $sample_directory/sample-smtp.cf:f:root:-:644
 $sample_directory/sample-smtpd.cf:f:root:-:644
+$sample_directory/sample-tls.cf:f:root:-:644
 $sample_directory/sample-transport.cf:f:root:-:644
 $sample_directory/sample-virtual.cf:f:root:-:644
 $readme_directory/DB_README:f:root:-:644
diff -r -u --new-file postfix-1.1.0-vanilla/conf/sample-auth.cf postfix-1.1.0/conf/sample-auth.cf
--- postfix-1.1.0-vanilla/conf/sample-auth.cf	Tue Nov  6 16:19:40 2001
+++ postfix-1.1.0/conf/sample-auth.cf	Thu Jan 17 21:30:50 2002
@@ -108,3 +108,15 @@
 #
 #smtp_sasl_security_options = 
 smtp_sasl_security_options = noplaintext
+
+# Sending AUTH data over an unencrypted channel poses a security risk. When
+# smtpd_tls_enforce_tls is set, AUTH will only be announced and accepted,
+# once the TLS layer has been activated via the STARTTLS protocol. If
+# TLS layer encryption is optional, it may however still be useful to only
+# offer AUTH, when TLS is active. To not break compatiblity with unpatched
+# postfix versions, the default is to accept AUTH without encryption. In
+# order to change this behaviour, set smtpd_tls_auth_only = yes.
+# THIS OPTION ONLY WORKS WITH SSL/TLS SUPPORT COMPILED IN.
+#
+# smtpd_tls_auth_only = no
+
diff -r -u --new-file postfix-1.1.0-vanilla/conf/sample-smtp.cf postfix-1.1.0/conf/sample-smtp.cf
--- postfix-1.1.0-vanilla/conf/sample-smtp.cf	Tue Dec 11 02:04:51 2001
+++ postfix-1.1.0/conf/sample-smtp.cf	Thu Jan 17 21:30:50 2002
@@ -176,6 +176,14 @@
 #
 smtp_helo_timeout = 300s
 
+# The smtp_starttls_timeout parameter limits the time in seconds to write and
+# read operations during TLS start and stop handhake procedures.
+#
+# In case of problems the client does NOT try the next address on
+# the mail exchanger list.
+#
+# smtp_starttls_timeout = 300s
+
 # The smtp_mail_timeout parameter specifies the SMTP client timeout
 # for sending the SMTP MAIL FROM command, and for receiving the server
 # response.
diff -r -u --new-file postfix-1.1.0-vanilla/conf/sample-smtpd.cf postfix-1.1.0/conf/sample-smtpd.cf
--- postfix-1.1.0-vanilla/conf/sample-smtpd.cf	Wed Dec 26 23:11:37 2001
+++ postfix-1.1.0/conf/sample-smtpd.cf	Thu Jan 17 21:30:50 2002
@@ -116,6 +116,11 @@
 # 
 strict_rfc821_envelopes = no
 
+# The smtpd_starttls_timeout parameter limits the time in seconds to write and
+# read operations during TLS start and stop handhake procedures.
+#
+# smtpd_starttls_timeout = 300s
+
 #
 # TARPIT CONTROLS
 #
diff -r -u --new-file postfix-1.1.0-vanilla/conf/sample-tls.cf postfix-1.1.0/conf/sample-tls.cf
--- postfix-1.1.0-vanilla/conf/sample-tls.cf	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/conf/sample-tls.cf	Thu Jan 17 21:30:50 2002
@@ -0,0 +1,493 @@
+# DO NOT EDIT THIS FILE. EDIT THE MAIN.CF FILE INSTEAD. THE STUFF
+# HERE JUST SERVES AS AN EXAMPLE.
+#
+# This file contains example settings of Postfix configuration
+# parameters that control the behaviour of the TLS extensions.
+#
+# We strictly seperate between server side TLS (smtpd_) and client side
+# TLS (smtp_), as for practical reasons we might choose differently.
+
+# Section with SMTPD specific settings
+
+# To use TLS we do need a certificate and a private key. Both must be in
+# "pem" format, the private key must not be encrypted, that does mean:
+# it must be accessable without password. Both parts (certificate and
+# private key) may be in the same file.
+#
+# Both RSA and DSA are certificates are supported. Typically you will only
+# have RSA certificates issued by a commercial CA, also the tools supplied
+# with OpenSSL will by default issue RSA certificates.
+# You can have both at the same time, in this case the cipher used decides,
+# which certificate is presented. For Netscape and OpenSSL clients without
+# special cipher choices, the RSA certificate is preferred.
+#
+# In order to check the certificates, the CA-certificate (in case of a
+# certificate chain, all CA-certificates) must be available.
+# You should add these certificates to the server certificate, the server
+# certificate first, then the issuing CA(s).
+#
+# Example: the certificate for "server.dom.ain" was issued by "intermediate CA"
+# which itself has a certificate of "root CA". Create the server.pem file by
+# 'cat server_cert.pem intemediate_CA.pem root_CA.pem > server.pem'
+#
+# If you want to accept certificates issued by these CAs yourself, you can
+# also add the CA-certificates to the smtpd_tls_CAfile, in which case it is
+# not necessary to have them in the smtpd_tls_[d]cert_file.
+#
+# A certificate supplied here must be useable as SSL server certificate and
+# hence pass the "openssl verify -purpose sslserver ..." test.
+#
+smtpd_tls_cert_file = /etc/postfix/server.pem
+smtpd_tls_key_file = $smtpd_tls_cert_file
+#
+# Its DSA counterparts:
+smtpd_tls_dcert_file = /etc/postfix/server-dsa.pem
+smtpd_tls_dkey_file = $smtpd_tls_dcert_file
+
+# The certificate was issued by a certification authority (CA), the CA-cert
+# of which must be available, if not in the certificate file.
+# This file may also contain the the CA certificates of other trusted CAs.
+# You must use this file for the list of trusted CAs if you want to use
+# chroot-mode. No default is supplied for this value as of now.
+#
+# smtpd_tls_CAfile = /etc/postfix/CAcert.pem
+
+# To verify the peer certificate, we need to know the certificates of
+# certification authorities. These certificates in "pem" format are
+# collected in a directory. The same CAs are offered to clients for
+# client verification. Don't forget to create the necessary "hash"
+# links with $OPENSSL_HOME/bin/c_rehash /etc/postfix/certs. A typical
+# place for the CA-certs may also be $OPENSSL_HOME/certs, so there is
+# no default and you explicitly have to set the value here!
+#
+# To use this option in chroot mode, this directory itself or a copy of it
+# must be inside the chroot jail. Please note also, that the CAs in this
+# directory are not listed to the client, so that e.g. Netscape might not
+# offer certificates issued by them.
+#
+# I therefore discourage the use of this option.
+#
+smtpd_tls_CApath = /etc/postfix/certs
+
+# To get additional information during the TLS setup and negotiations
+# you can increase the loglevel from 0..4:
+# 0: No output about the TLS subsystem
+# 1: Printout startup and certificate information
+# 2: 1 + Printout of levels during negotiation
+# 3: 2 + Hex and ASCII dump of negotiation process
+# 4: 3 + Hex and ASCII dump of complete transmission after STARTTLS
+# Use loglevel 3 only in case of problems. Use of loglevel 4 is strongly
+# discouraged.
+#
+# smtpd_tls_loglevel = 0
+
+# To include information about the protocol and cipher used as well as the
+# client and issuer CommonName into the "Received:" header, set the
+# smtpd_tls_received_header variable to true. The default is no, as the
+# information is not necessarily authentic. Only the final destination
+# is reliable, since the headers might have been changed in between.
+#
+#smtpd_tls_received_header = yes
+
+# By default TLS is disabled, so no difference to plain postfix is visible.
+# Explicitely switch it on here:
+#
+smtpd_use_tls = yes
+
+# You can ENFORCE the use of TLS, so that no commands (except QUIT of course)
+# are allowed without TLS. According to RFC2487 this MUST NOT be applied
+# in case of a publicly-referenced SMTP server. So this option is off
+# by default and should only seldom be used. Using this option implies
+# smtpd_use_tls = yes
+#
+# smtpd_enforce_tls = no
+
+# Besides RFC2487 some clients, namely Outlook [Express] prefer to run the
+# non-standard "wrapper" mode, not the STARTTLS enhancement to SMTP.
+# This is true for OE (Win32 < 5.0 and Win32 >=5.0 when run on a port!=25
+# and OE (5.01 Mac on all ports).
+# It is strictly discouraged to use this mode from main.cf. If you want to
+# support this service, enable a special port in master.cf. Port 465 (smtps)
+# was once chosen for this feature.
+#
+# smtpd_tls_wrappermode = no
+
+# To receive a client certificate, the server must explicitly ask for one.
+# Hence netscape will either complain if no certificate is available (for
+# the list of CAs in /etc/postfix/certs) or will offer you client certificates
+# to choose from. This might be annoying, so this option is "off" by default.
+# You will however need the certificate if you want to to e.g. certificate
+# based relaying.
+#
+# smtpd_tls_ask_ccert = no
+
+# You may also decide to REQUIRE a client certificate to allow TLS connections.
+# I don't think it will be necessary often, it is however included here for
+# completeness. This option implies smtpd_tls_ask_ccert = yes
+#
+# Please be aware, that this will inhibit TLS connections without a proper
+# certificate and only makes sense, when normal submission is disabled and
+# TLS is enforced (smtpd_enforce_tls). Otherwise clients may bypass by simply
+# not using STARTTLS at all. When TLS is not enforced, the connection will be
+# handled, as if only smtpd_tls_ask_ccert = yes would be set and an information
+# is logged.
+#
+# smtpd_tls_req_ccert = no
+
+# The verification depth for client certificates. A depth of 1 is sufficient,
+# if the certificate ist directly issued by a CA listed in the CA locations.
+# The default value (5) should also suffice for longer chains (root CA issues
+# special CA which then issues the actual certificate...)
+#
+# smtpd_tls_ccert_verifydepth = 5
+
+# Sending AUTH data over an unencrypted channel poses a security risk. When
+# smtpd_tls_enforce_tls is set, AUTH will only be announced and accepted,
+# once the TLS layer has been activated via the STARTTLS protocol. If
+# TLS layer encryption is optional, it may however still be useful to only
+# offer AUTH, when TLS is active. To not break compatiblity with unpatched
+# postfix versions, the default is to accept AUTH without encryption. In
+# order to change this behaviour, set smtpd_tls_auth_only = yes.
+#
+# smtpd_tls_auth_only = no
+
+# The server and client negotiate a session, which takes some computer time
+# and network bandwidth. The session is cached only in the smtpd process
+# actually using this session and is lost when the process dies.
+# To share the session information between the smtpd processes, a disc based
+# session cache can be used based on the SDBM databases (routines included
+# in Postfix/TLS). Since concurrent writing must be supported, only SDBM
+# can be used.
+#
+smtpd_tls_session_cache_database = sdbm:/etc/postfix/smtpd_scache
+
+# The cached sessions time out after a certain amount of time. For Postfix/TLS
+# I do not use the OpenSSL default of 300sec, but a longer time of 3600sec
+# (=1 hour). RFC2246 recommends a maximum of 24 hours.
+#
+# smtpd_tls_session_cache_timeout = 3600s
+
+# Two additional options has been added for relay control to the UCE rules:
+#   permit_tls_clientcerts	(a)
+# and
+#   permit_tls_all_clientcerts. (b)
+#
+# If one of these options is added to
+#   smtpd_recipient_restrictions,
+# postfix will relay if 
+# (a) a valid (it passed the verification) client certificate is presented
+#     and its fingerprint is listed in the list of client certs
+#     (relay_clientcerts),
+# (b) any valid (it passed the verification) client certificate is presented.
+#
+# Option (b) must only be used, if a special CA issues the certificates and
+# only this CA is listed as trusted CA. If other CAs are trusted, any owner
+# of a valid (SSL client)-certificate can relay. Option (b) can be practical
+# for a specically created email relay. It is however recommended to stay with
+# option (a) and list all certificates, as (b) does not permit any control
+# when a certificate must no longer be used (e.g. an employee leaving).
+#
+# smtpd_recipient_restrictions = ... permit_tls_clientcerts ...
+
+# The list of client certificates for which relaying will be allowed.
+# Unfortunately the routines for lists in postfix use whitespaces as
+# seperators and choke on special chars. So using the certificate
+# X509ONELINES is quite impractical. We will use the fingerprints at
+# this point, as they are difficult to fake but easy to use for lookup.
+# As postmap (when using e.g. db) insists of having a pair of key and value,
+# but we only need the key, the value can be chosen freely, e.g. the name
+# of the user or host:
+# D7:04:2F:A7:0B:8C:A5:21:FA:31:77:E1:41:8A:EE:80 lutzpc.at.home
+#
+# relay_clientcerts = hash:/etc/postfix/relay_clientcerts
+
+# To influence the cipher selection scheme, you can give cipherlist-string.
+# A detailed description would go to far here, please refer to the openssl
+# documentation.
+# If you don't know what to do with it, simply don't touch it and leave the
+# (openssl-)compiled in default!
+#
+# DO NOT USE " to enclose the string, just the string!!!
+#
+# smtpd_tls_cipherlist = DEFAULT
+
+# If you want to take advantage of ciphers with EDH, DH parameters are needed.
+# There are built in DH parameters for both 1025bit and 512bit available. It
+# is however better to have "own" parameters, since otherwise it would "pay"
+# for a possible attacker to start a brute force attack against these
+# parameters commonly used by everybody. For this reason, the parameters
+# chosen are already different from those distributed with other TLS packages.
+#
+# To generate your own set of parameters, use
+# openssl gendh -out /etc/postfix/dh_1024.pem -2 -rand /var/run/egd-pool 1024
+# openssl gendh -out /etc/postfix/dh_512.pem -2 -rand /var/run/egd-pool 512
+# (your source for "entropy" might vary; on Linux there is /dev/random, on
+# other system, you might consider the "Entropy Gathering Daemon EGD", 
+# available at http://www.lothar.com/tech/crypto/.
+#
+smtpd_tls_dh1024_param_file = /etc/postfix/dh_1024.pem
+smtpd_tls_dh512_param_file = /etc/postfix/dh_512.pem
+
+# The smtpd_starttls_timeout parameter limits the time in seconds to write and
+# read operations during TLS start and stop handhake procedures.
+#
+# smtpd_starttls_timeout = 300s
+
+# Section with SMTP specific settings
+
+# During the startup negotiation we might present a certificate to the server.
+# Netscape is rather clever here and lets the user select between only those
+# certs that will match the CAs accepted from the server. As I simply use
+# the integrated "SSL_connect()" from the OpenSSL package, this is not
+# possible by now and we have to chose just one cert.
+# So for now the default is to use _no_ cert and key unless explictly
+# set here. It is possible to use the same key/cert pair as for the server.
+# If a cert is to be presented, it must be in "pem" format, the private key
+# must not be encrypted, that does mean: it must be accessable without
+# password. Both parts (certificate and private key) may be in the
+# same file.
+#
+# In order to check the certificates, the CA-certificate (in case of a
+# certificate chain, all CA-certificates) must be available.
+# You should add these certificates to the server certificate, the server
+# certificate first, then the issuing CA(s).
+#
+# Example: the certificate for "client.dom.ain" was issued by "intermediate CA"
+# which itself has a certificate of "root CA". Create the client.pem file by
+# 'cat client_cert.pem intemediate_CA.pem root_CA.pem > client.pem'
+#
+# If you want to accept certificates issued by these CAs yourself, you can
+# also add the CA-certificates to the smtp_tls_CAfile, in which case it is
+# not necessary to have them in the smtp_tls_[d]cert_file.
+#
+# A certificate supplied here must be useable as SSL client certificate and
+# hence pass the "openssl verify -purpose sslclient ..." test.
+#
+smtp_tls_cert_file = /etc/postfix/client.pem
+smtp_tls_key_file = $smtp_tls_cert_file
+
+# The certificate was issued by a certification authority (CA), the CA-cert
+# of which must be available, if not in the certificate file.
+# This file may also contain the the CA certificates of other trusted CAs.
+# You must use this file for the list of trusted CAs if you want to use
+# chroot-mode. No default is supplied for this value as of now.
+#
+smtp_tls_CAfile = /etc/postfix/CAcert.pem
+
+# To verify the peer certificate, we need to know the certificates of
+# certification authorities. These certificates in "pem" format are
+# collected in a directory. Don't forget to create the necessary "hash"
+# links with $OPENSSL_HOME/bin/c_rehash /etc/postfix/certs. A typical
+# place for the CA-certs may also be $OPENSSL_HOME/certs, so there is
+# no default and you explicitly have to set the value here!
+#
+# To use this option in chroot mode, this directory itself or a copy of it
+# must be inside the chroot jail.
+#
+smtp_tls_CApath = /etc/postfix/certs
+
+# To get additional information during the TLS setup and negotiations
+# you can increase the loglevel from 0..4:
+# 0: No output about the TLS subsystem
+# 1: Printout startup and certificate information
+# 2: 1 + Printout of levels during negotiation
+# 3: 2 + Hex and ASCII dump of negotiation process
+# 4: 3 + Hex and ASCII dump of complete transmission after STARTTLS
+# Use loglevel 3 only in case of problems. Use of loglevel 4 is strongly
+# discouraged.
+#
+smtp_tls_loglevel = 0
+
+# The server and client negotiate a session, which takes some computer time
+# and network bandwidth. The session is cached only in the smtpd process
+# actually using this session and is lost when the process dies.
+# To share the session information between the smtp processes, a disc based
+# session cache can be used based on the SDBM databases (routines included
+# in Postfix/TLS). Since concurrent writing must be supported, only SDBM
+# can be used.
+#
+smtp_tls_session_cache_database = sdbm:/etc/postfix/smtp_scache
+
+# The cached sessions time out after a certain amount of time. For Postfix/TLS
+# I do not use the OpenSSL default of 300sec, but a longer time of 3600sec
+# (=1 hour). RFC2246 recommends a maximum of 24 hours.
+#
+# smtp_tls_session_cache_timeout = 3600s
+
+# By default TLS is disabled, so no difference to plain postfix is visible.
+# If you enable TLS it will be used when offered by the server.
+# WARNING: I didn't have access to other software (except those explicitely
+# listed) to test the interaction. On corresponding mailing list
+# there was a discussion going on about MS exchange servers offering
+# STARTTLS even if it is not configured, so it might be wise to not
+# use this option on your central mail hub, as you don't know in advance
+# whether you are going to hit such host. Use the recipient/site specific
+# options instead.
+# HINT: I have it switched on on my mailservers and did experience one
+# single failure since client side TLS is implemented. (There was one
+# misconfired MS Exchange server; I contacted ths admin.) Hence, I am happy
+# with it running all the time, but I am interested in testing anyway.
+# You have been warned, however :-)
+#
+# In case of failure, a "4xx" code is issued and the mail stays in the queue.
+#
+# Explicitely switch it on here, if you want it.
+#
+smtp_use_tls = yes
+
+# You can ENFORCE the use of TLS, so that only connections with TLS will
+# be accepted. Additionally, the hostname of the receiving host is matched
+# against the CommonName in the certificate. Also, the certificate must
+# be verified "Ok", so that a CA trusted by the client must have issued
+# the certificate. If the certificate doesn't verify or the hostname doesn't
+# match, a "4xx" will be issued and the mail stays in the queue.
+# The hostname used in the check is beyond question, as it must be the
+# principle hostname (no CNAME allowed here).
+# The behaviour may be changed with the smtp_tls_enforce_peername option
+#
+# This option is useful only if you are definitely sure that you will only
+# connect to servers supporting RFC2487 _and_ with valid certificates.
+# I use it for my clients which will only send email to one mailhub, which
+# does offer the necessary STARTTLS support.
+#
+# smtp_enforce_tls = no
+
+# As of RFC2487 the requirements for hostname checking for MTA clients are
+# not set. When in smtp_enforce_tls mode, the option smtp_tls_enforce_peername
+# can be set to "no" to disable strict peername checking. In this case, the
+# mail delivery will be continued, if a TLS connection was established
+# _and_ the peer certificate passed verification _but_ regardless of the
+# CommonName listed in the certificate. This option only applies to the
+# default setting smtp_enforce_tls_mode, special settings in the
+# smtp_tls_per_site table override smtp_tls_enforce_peername.
+#
+# This can make sense in closed environment where special CAs are created.
+# If not used carefully, this option opens the danger of a "man-in-the-middle"
+# attack (the CommonName of this attacker is logged).
+#
+# smtp_tls_enforce_peername = yes
+
+# As generally trying TLS can be a bad idea (some hosts offer STARTTLS but
+# the negotiation will fail leading to unexplainable failures, it may be
+# a good idea to decide based on the recipient or the mailhub to which you are
+# connecting.
+#
+# Deciding per recipient may be difficult, since a singe email can have
+# several recipients. We use the "nexthop" mechanism inside postfix.
+# When an email is to be delivered, the "nexthop" is obtained. If it matches
+# an entry in the smtp_tls_per_site list, appropriate action is taken.
+# Since entries in the transport table or the use of a relay_host override
+# the nexthop setting, in these cases the relay_host etc must be listed
+# in the table. In any case, the hostname of the peer to be contacted is
+# looked up (that is: the MX or the name of the host, if no MX is given).
+#
+# Special hint for enforcement mode:
+# Since there is no secure mechanism for DNS lookups available, the
+# recommended setup is: put the sensible domains with their mailhost
+# into the transport table (since you can asure security of this table
+# unlike DNS), then set MUST mode for this mailhost.
+#
+# Format of the table:
+# The keys entries are on the left hand side, no wildcards allowed. On the
+# right hand side the keywords NONE (don't use TLS at all), MAY (try to use
+# STARTTLS if offered, no problem if not), MUST (enforce usage of STARTTLS,
+# check server certificate CommonName against server FQDN), MUST_NOPEERMATCH
+# (enforce usage of STARTTLS and verify certificate, but ignore differences
+# between CommonName and server FQDN).
+# dom.ain		NONE
+# host.dom.ain		MAY
+# important.host	MUST
+# some.host.dom.ain	MUST_NOPEERMATCH
+#
+# If an entry is not matched, the default policy is applied; if the default
+# policy is "enforce", NONE explicitely switches it off, otherwise the
+# "enforce" mode is used even for MAY entries.
+#
+smtp_tls_per_site = hash:/etc/postfix/tls_per_site
+
+# The verification depth for server certificates. A depth of 1 is sufficient,
+# if the certificate ist directly issued by a CA listed in the CA locations.
+# The default value (5) should also suffice for longer chains (root CA issues
+# special CA which then issues the actual certificate...)
+#
+# smtp_tls_scert_verifydepth = 5
+
+# As we decide on a "per site" basis, wether to use TLS or not, it would be
+# good to have a list of sites, that offered "STARTTLS'. We can collect it
+# ourselves with this option.
+#
+# If activated and TLS is not already enabled for this host, a line is added
+# to the logfile:
+# postfix/smtp[pid]: Host offered STARTTLS: [name.of.host]
+#
+smtp_tls_note_starttls_offer = yes
+
+# To influence the cipher selection scheme, you can give cipherlist-string.
+# A detailed description would go to far here, please refer to the openssl
+# documentation.
+# If you don't know what to do with it, simply don't touch it and leave the
+# (openssl-)compiled in default!
+#
+# DO NOT USE " to enclose the string, just the string!!!
+#
+# smtp_tls_cipherlist = DEFAULT
+
+# The smtp_starttls_timeout parameter limits the time in seconds to write and
+# read operations during TLS start and stop handhake procedures.
+#
+# In case of problems the client does NOT try the next address on
+# the mail exchanger list.
+#
+# smtp_starttls_timeout = 300s
+
+# In order to seed the PRNG Pseude Random Number Generator, random data is
+# needed. The PRNG pool is maintained by the "tlsmgr" daemon and is used
+# (read) by the smtp[d] processes after adding some more entropy by stirring
+# in time and process id.
+# The file, which is from time to time rewritten by the tlsmgr, is created
+# if not existant. A default value is given; the default should probably
+# be on the /var partition but _not_ inside chroot jail.
+#
+# tls_random_exchange_name = /etc/postfix/prng_exch
+
+# To feed the PRNG pool, entropy is being read from an external source,
+# both at startup and during run.
+# Specify a good entropy source here, like EGD or /dev/urandom; make sure
+# to only use non-blocking sources.
+# In both cases, 32 bytes are read at each re-seeding event (which is an
+# amount of 256bits and hence good enough for 128bit symmetric keys).
+# You must specify the type of source: "dev:" for a device special file
+# or "egd:" for a source with EGD compatible socket interface. A maximum
+# 255 bytes is read from these sources in each step.
+# If you specify a normal file, a larger amount of data can be read.
+#
+# The entropy source is queried again after a certain amount of time. The
+# time is calculated using the PRNG, it is between 0 and the time specified,
+# default is a maximum of 1 hour.
+#
+# tls_random_source = dev:/dev/urandom
+tls_random_source = egd:/var/run/egd-pool
+# tls_random_bytes = 32
+# tls_random_reseed_period = 3600s
+
+# The PRNG pool inside tlsmgr is used to re-generate the 1024 byte file
+# being read by smtp[d]. The time, after which the exchange file is
+# rewritten is calculated using the PRNG, it is between 0 and the time
+# specified, default is a maximum of 60 seconds.
+#
+# tls_random_upd_period = 60s
+
+# If you have a entropy source available, that is not easily drained (like
+# /dev/urandom), the daemons can also load additional entropy on startup from
+# the source specified. By default an amount of 32 bytes is read, the
+# equivalent to 256 bits. This is more than enough to generate a 128bit
+# (or 168bit) session key, but we may have to generate more than one.
+# Usage of this option may drain EGD (consider the case of 50 smtp starting
+# up with a full queue and "postfix start", which will request 1600bytes
+# of entropy). This is however not fatal, as long as "entropy" data could
+# be read from the exchange file.
+#
+# tls_daemon_random_source = dev:/dev/urandom
+tls_daemon_random_source = egd:/var/run/egd-pool
+# tls_daemon_random_bytes = 32
+
diff -r -u --new-file postfix-1.1.0-vanilla/man/man8/tlsmgr.8 postfix-1.1.0/man/man8/tlsmgr.8
--- postfix-1.1.0-vanilla/man/man8/tlsmgr.8	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/man/man8/tlsmgr.8	Thu Jan 17 21:30:50 2002
@@ -0,0 +1,130 @@
+.TH TLSMGR 8 
+.ad
+.fi
+.SH NAME
+tlsmgr
+\-
+Postfix TLS session cache and PRNG handling manager
+.SH SYNOPSIS
+.na
+.nf
+\fBtlsmgr\fR [generic Postfix daemon options]
+.SH DESCRIPTION
+.ad
+.fi
+The tlsmgr process does housekeeping on the session cache database
+files. It runs through the databases and removes expired entries
+and entries written by older (incompatible) versions.
+
+The tlsmgr is responsible for the PRNG handling. The used internal
+OpenSSL PRNG has a pool size of 8192 bits (= 1024 bytes). The pool
+is initially seeded at startup from an external source (EGD or
+/dev/urandom) and additional seed is obtained later during program
+run at a configurable period. The exact time of seed query is
+using random information and is equally distributed in the range of
+[0-\fBtls_random_reseed_period\fR] with a \fBtls_random_reseed_period\fR
+having a default of 1 hour.
+
+Tlsmgr can be run chrooted and with dropped privileges, as it will
+connect to the entropy source at startup.
+
+The PRNG is additionally seeded internally by the data found in the
+session cache and timevalues.
+
+Tlsmgr reads the old value of the exchange file at startup to keep
+entropy already collected during previous runs.
+
+From the PRNG random pool a cryptographically strong 1024 byte random
+sequence is written into the PRNG exchange file. The file is updated
+periodically with the time changing randomly from
+[0-\fBtls_random_prng_update_period\fR].
+.SH STANDARDS
+.na
+.nf
+.SH SECURITY
+.na
+.nf
+.ad
+.fi
+Tlsmgr is not security-sensitive. It only deals with external data
+to be fed into the PRNG, the contents is never trusted. The session
+cache housekeeping will only remove entries if expired and will never
+touch the contents of the cached data.
+.SH DIAGNOSTICS
+.ad
+.fi
+Problems and transactions are logged to the syslog daemon.
+.SH BUGS
+.ad
+.fi
+There is no automatic means to limit the number of entries in the
+session caches and/or the size of the session cache files.
+.SH CONFIGURATION PARAMETERS
+.na
+.nf
+.ad
+.fi
+The following \fBmain.cf\fR parameters are especially relevant to
+this program. See the Postfix \fBmain.cf\fR file for syntax details
+and for default values. Use the \fBpostfix reload\fR command after
+a configuration change.
+.SH Session Cache
+.ad
+.fi
+.IP \fBsmtpd_tls_session_cache_database\fR
+Name of the SDBM file (type sdbm:) containing the SMTP server session
+cache. If the file does not exist, it is created.
+.IP \fBsmtpd_tls_session_cache_timeout\fR
+Expiry time of SMTP server session cache entries in seconds. Entries
+older than this are removed from the session cache. A cleanup-run is
+performed periodically every \fBsmtpd_tls_session_cache_timeout\fR
+seconds. Default is 3600 (= 1 hour).
+.IP \fBsmtp_tls_session_cache_database\fR
+Name of the SDBM file (type sdbm:) containing the SMTP client session
+cache. If the file does not exist, it is created.
+.IP \fBsmtp_tls_session_cache_timeout\fR
+Expiry time of SMTP client session cache entries in seconds. Entries
+older than this are removed from the session cache. A cleanup-run is
+performed periodically every \fBsmtp_tls_session_cache_timeout\fR
+seconds. Default is 3600 (= 1 hour).
+.SH Pseudo Random Number Generator
+.ad
+.fi
+.IP \fBtls_random_source\fR
+Name of the EGD socket or device or regular file to obtain entropy
+from. The type of entropy source must be specified by preceding the
+name with the appropriate type: egd:/path/to/egd_socket,
+dev:/path/to/devicefile, or /path/to/regular/file.
+tlsmgr opens \fBtls_random_source\fR and tries to read
+\fBtls_random_bytes\fR from it.
+.IP \fBtls_random_bytes\fR
+Number of bytes to be read from \fBtls_random_source\fR.
+Default value is 32 bytes. If using EGD, a maximum of 255 bytes is read.
+.IP \fBtls_random_exchange_name\fR
+Name of the file written by tlsmgr and read by smtp and smtpd at
+startup. The length is 1024 bytes. Default value is
+/etc/postfix/prng_exch.
+.IP \fBtls_random_reseed_period\fR
+Time in seconds until the next reseed from external sources is due.
+This is the maximum value. The actual point in time is calculated
+with a random factor equally distributed between 0 and this maximum
+value. Default is 3600 (= 60 minutes).
+.IP \fBtls_random_prng_update_period\fR
+Time in seconds until the PRNG exchange file is updated with new
+pseude random values. This is the maximum value. The actual point
+in time is calculated with a random factor equally distributed
+between 0 and this maximum value. Default is 60 (= 1 minute).
+.SH SEE ALSO
+.na
+.nf
+smtp(8) SMTP client
+smtpd(8) SMTP server
+.SH LICENSE
+.na
+.nf
+.ad
+.fi
+The Secure Mailer license must be distributed with this software.
+.SH AUTHOR(S)
+.na
+.nf
diff -r -u --new-file postfix-1.1.0-vanilla/src/global/Makefile.in postfix-1.1.0/src/global/Makefile.in
--- postfix-1.1.0-vanilla/src/global/Makefile.in	Tue Jan 15 16:25:09 2002
+++ postfix-1.1.0/src/global/Makefile.in	Thu Jan 17 21:30:50 2002
@@ -19,7 +19,7 @@
 	timed_ipc.c tok822_find.c tok822_node.c tok822_parse.c \
 	tok822_resolve.c tok822_rewrite.c tok822_tree.c xtext.c bounce_log.c \
 	flush_clnt.c mail_conf_time.c mbox_conf.c mbox_open.c abounce.c \
-	verp_sender.c match_parent_style.c
+	verp_sender.c match_parent_style.c pfixtls.c
 OBJS	= been_here.o bounce.o canon_addr.o cleanup_strerror.o clnt_stream.o \
 	debug_peer.o debug_process.o defer.o deliver_completed.o \
 	deliver_flock.o deliver_pass.o deliver_request.o domain_list.o \
@@ -40,7 +40,7 @@
 	timed_ipc.o tok822_find.o tok822_node.o tok822_parse.o \
 	tok822_resolve.o tok822_rewrite.o tok822_tree.o xtext.o bounce_log.o \
 	flush_clnt.o mail_conf_time.o mbox_conf.o mbox_open.o abounce.o \
-	verp_sender.o match_parent_style.o
+	verp_sender.o match_parent_style.o pfixtls.o
 HDRS	= been_here.h bounce.h canon_addr.h cleanup_user.h clnt_stream.h \
 	config.h debug_peer.h debug_process.h defer.h deliver_completed.h \
 	deliver_flock.h deliver_pass.h deliver_request.h domain_list.h \
@@ -57,7 +57,7 @@
 	rewrite_clnt.h sent.h smtp_stream.h split_addr.h string_list.h \
 	sys_exits.h timed_ipc.h tok822.h xtext.h bounce_log.h flush_clnt.h \
 	mbox_conf.h mbox_open.h abounce.h qmqp_proto.h verp_sender.h \
-	match_parent_style.h
+	match_parent_style.h pfixtls.h
 TESTSRC	= rec2stream.c stream2rec.c recdump.c
 WARN	= -W -Wformat -Wimplicit -Wmissing-prototypes \
 	-Wparentheses -Wstrict-prototypes -Wswitch -Wuninitialized \
@@ -1072,3 +1072,16 @@
 xtext.o: ../../include/vbuf.h
 xtext.o: ../../include/vstring.h
 xtext.o: xtext.h
+pfixtls.o: pfixtls.c
+pfixtls.o: ../../include/sys_defs.h
+pfixtls.o: ../../include/iostuff.h
+pfixtls.o: ../../include/mymalloc.h
+pfixtls.o: ../../include/vstring.h
+pfixtls.o: ../../include/vstream.h
+pfixtls.o: ../../include/dict.h
+pfixtls.o: ../../include/myflock.h
+pfixtls.o: ../../include/stringops.h
+pfixtls.o: ../../include/msg.h
+pfixtls.o: ../../include/connect.h
+pfixtls.o: mail_params.h
+pfixtls.o: pfixtls.h
diff -r -u --new-file postfix-1.1.0-vanilla/src/global/mail_params.c postfix-1.1.0/src/global/mail_params.c
--- postfix-1.1.0-vanilla/src/global/mail_params.c	Thu Jan 17 16:50:56 2002
+++ postfix-1.1.0/src/global/mail_params.c	Thu Jan 17 21:30:50 2002
@@ -199,6 +199,31 @@
 int     var_in_flow_delay;
 char   *var_par_dom_match;
 char   *var_config_dirs;
+char   *var_tls_rand_exch_name;
+char   *var_smtpd_tls_cert_file;
+char   *var_smtpd_tls_key_file;
+char   *var_smtpd_tls_dcert_file;
+char   *var_smtpd_tls_dkey_file;
+char   *var_smtpd_tls_CAfile;
+char   *var_smtpd_tls_CApath;
+char   *var_smtpd_tls_cipherlist;
+char   *var_smtpd_tls_dh512_param_file;
+char   *var_smtpd_tls_dh1024_param_file;
+int     var_smtpd_tls_loglevel;
+char   *var_smtpd_tls_scache_db;
+int     var_smtpd_tls_scache_timeout;
+char   *var_smtp_tls_cert_file;
+char   *var_smtp_tls_key_file;
+char   *var_smtp_tls_dcert_file;
+char   *var_smtp_tls_dkey_file;
+char   *var_smtp_tls_CAfile;
+char   *var_smtp_tls_CApath;
+char   *var_smtp_tls_cipherlist;
+int     var_smtp_tls_loglevel;
+char   *var_smtp_tls_scache_db;
+int     var_smtp_tls_scache_timeout;
+char   *var_tls_daemon_rand_source;
+int     var_tls_daemon_rand_bytes;
 
 char   *var_import_environ;
 char   *var_export_environ;
@@ -413,6 +438,26 @@
 	VAR_VERP_FILTER, DEF_VERP_FILTER, &var_verp_filter, 1, 0,
 	VAR_PAR_DOM_MATCH, DEF_PAR_DOM_MATCH, &var_par_dom_match, 0, 0,
 	VAR_CONFIG_DIRS, DEF_CONFIG_DIRS, &var_config_dirs, 0, 0,
+	VAR_TLS_RAND_EXCH_NAME, DEF_TLS_RAND_EXCH_NAME, &var_tls_rand_exch_name, 0, 0,
+	VAR_SMTPD_TLS_CERT_FILE, DEF_SMTPD_TLS_CERT_FILE, &var_smtpd_tls_cert_file, 0, 0,
+	VAR_SMTPD_TLS_KEY_FILE, DEF_SMTPD_TLS_KEY_FILE, &var_smtpd_tls_key_file, 0, 0,
+	VAR_SMTPD_TLS_DCERT_FILE, DEF_SMTPD_TLS_DCERT_FILE, &var_smtpd_tls_dcert_file, 0, 0,
+	VAR_SMTPD_TLS_DKEY_FILE, DEF_SMTPD_TLS_DKEY_FILE, &var_smtpd_tls_dkey_file, 0, 0,
+	VAR_SMTPD_TLS_CA_FILE, DEF_SMTPD_TLS_CA_FILE, &var_smtpd_tls_CAfile, 0, 0,
+	VAR_SMTPD_TLS_CA_PATH, DEF_SMTPD_TLS_CA_PATH, &var_smtpd_tls_CApath, 0, 0,
+	VAR_SMTPD_TLS_CLIST, DEF_SMTPD_TLS_CLIST, &var_smtpd_tls_cipherlist, 0, 0,
+	VAR_SMTPD_TLS_512_FILE, DEF_SMTPD_TLS_512_FILE, &var_smtpd_tls_dh512_param_file, 0, 0,
+	VAR_SMTPD_TLS_1024_FILE, DEF_SMTPD_TLS_1024_FILE, &var_smtpd_tls_dh1024_param_file, 0, 0,
+	VAR_SMTPD_TLS_SCACHE_DB, DEF_SMTPD_TLS_SCACHE_DB, &var_smtpd_tls_scache_db, 0, 0,
+	VAR_SMTP_TLS_CERT_FILE, DEF_SMTP_TLS_CERT_FILE, &var_smtp_tls_cert_file, 0, 0,
+	VAR_SMTP_TLS_KEY_FILE, DEF_SMTP_TLS_KEY_FILE, &var_smtp_tls_key_file, 0, 0,
+	VAR_SMTP_TLS_DCERT_FILE, DEF_SMTP_TLS_DCERT_FILE, &var_smtp_tls_dcert_file, 0, 0,
+	VAR_SMTP_TLS_DKEY_FILE, DEF_SMTP_TLS_DKEY_FILE, &var_smtp_tls_dkey_file, 0, 0,
+	VAR_SMTP_TLS_CA_FILE, DEF_SMTP_TLS_CA_FILE, &var_smtp_tls_CAfile, 0, 0,
+	VAR_SMTP_TLS_CA_PATH, DEF_SMTP_TLS_CA_PATH, &var_smtp_tls_CApath, 0, 0,
+	VAR_SMTP_TLS_CLIST, DEF_SMTP_TLS_CLIST, &var_smtp_tls_cipherlist, 0, 0,
+	VAR_SMTP_TLS_SCACHE_DB, DEF_SMTP_TLS_SCACHE_DB, &var_smtp_tls_scache_db, 0, 0,
+	VAR_TLS_DAEMON_RAND_SOURCE, DEF_TLS_DAEMON_RAND_SOURCE, &var_tls_daemon_rand_source, 0, 0,
 	0,
     };
     static CONFIG_STR_FN_TABLE function_str_defaults_2[] = {
@@ -429,6 +474,9 @@
 	VAR_FLOCK_TRIES, DEF_FLOCK_TRIES, &var_flock_tries, 1, 0,
 	VAR_DEBUG_PEER_LEVEL, DEF_DEBUG_PEER_LEVEL, &var_debug_peer_level, 1, 0,
 	VAR_FAULT_INJ_CODE, DEF_FAULT_INJ_CODE, &var_fault_inj_code, 0, 0,
+	VAR_SMTPD_TLS_LOGLEVEL, DEF_SMTPD_TLS_LOGLEVEL, &var_smtpd_tls_loglevel, 0, 0,
+	VAR_SMTP_TLS_LOGLEVEL, DEF_SMTP_TLS_LOGLEVEL, &var_smtp_tls_loglevel, 0, 0,
+	VAR_TLS_DAEMON_RAND_BYTES, DEF_TLS_DAEMON_RAND_BYTES, &var_tls_daemon_rand_bytes, 0, 0,
 	0,
     };
     static CONFIG_TIME_TABLE time_defaults[] = {
@@ -439,6 +487,8 @@
 	VAR_FORK_DELAY, DEF_FORK_DELAY, &var_fork_delay, 1, 0,
 	VAR_FLOCK_DELAY, DEF_FLOCK_DELAY, &var_flock_delay, 1, 0,
 	VAR_FLOCK_STALE, DEF_FLOCK_STALE, &var_flock_stale, 1, 0,
+	VAR_SMTPD_TLS_SCACHTIME, DEF_SMTPD_TLS_SCACHTIME, &var_smtpd_tls_scache_timeout, 0, 0,
+	VAR_SMTP_TLS_SCACHTIME, DEF_SMTP_TLS_SCACHTIME, &var_smtp_tls_scache_timeout, 0, 0,
 	VAR_DAEMON_TIMEOUT, DEF_DAEMON_TIMEOUT, &var_daemon_timeout, 1, 0,
 	VAR_IN_FLOW_DELAY, DEF_IN_FLOW_DELAY, &var_in_flow_delay, 0, 10,
 	0,
diff -r -u --new-file postfix-1.1.0-vanilla/src/global/mail_params.h postfix-1.1.0/src/global/mail_params.h
--- postfix-1.1.0-vanilla/src/global/mail_params.h	Tue Jan 15 16:24:34 2002
+++ postfix-1.1.0/src/global/mail_params.h	Thu Jan 17 21:30:50 2002
@@ -458,6 +458,34 @@
 #define DEF_DUP_FILTER_LIMIT	1000
 extern int var_dup_filter_limit;
 
+#define VAR_TLS_RAND_EXCH_NAME	"tls_random_exchange_name"
+#define DEF_TLS_RAND_EXCH_NAME	"${config_directory}/prng_exch"
+extern char *var_tls_rand_exch_name;
+
+#define VAR_TLS_RAND_SOURCE	"tls_random_source"
+#define DEF_TLS_RAND_SOURCE	""
+extern char *var_tls_rand_source;
+
+#define VAR_TLS_RAND_BYTES	"tls_random_bytes"
+#define DEF_TLS_RAND_BYTES	32
+extern int var_tls_rand_bytes;
+
+#define VAR_TLS_DAEMON_RAND_SOURCE	"tls_daemon_random_source"
+#define DEF_TLS_DAEMON_RAND_SOURCE	""
+extern char *var_tls_daemon_rand_source;
+
+#define VAR_TLS_DAEMON_RAND_BYTES	"tls_daemon_random_bytes"
+#define DEF_TLS_DAEMON_RAND_BYTES	32
+extern int var_tls_daemon_rand_bytes;
+
+#define VAR_TLS_RESEED_PERIOD	"tls_random_reseed_period"
+#define DEF_TLS_RESEED_PERIOD	"3600s"
+extern int var_tls_reseed_period;
+
+#define VAR_TLS_PRNG_UPD_PERIOD	"tls_random_prng_update_period"
+#define DEF_TLS_PRNG_UPD_PERIOD "60s"
+extern int var_tls_prng_upd_period;
+
  /*
   * Queue manager: relocated databases.
   */
@@ -678,6 +706,10 @@
 #define DEF_SMTP_HELO_TMOUT	"300s"
 extern int var_smtp_helo_tmout;
 
+#define VAR_SMTP_STARTTLS_TMOUT	"smtp_starttls_timeout"
+#define DEF_SMTP_STARTTLS_TMOUT	"300s"
+extern int var_smtp_starttls_tmout;
+
 #define VAR_SMTP_MAIL_TMOUT	"smtp_mail_timeout"
 #define DEF_SMTP_MAIL_TMOUT	"300s"
 extern int var_smtp_mail_tmout;
@@ -763,6 +795,10 @@
 #define DEF_SMTPD_TMOUT		"300s"
 extern int var_smtpd_tmout;
 
+#define VAR_SMTPD_STARTTLS_TMOUT "smtpd_starttls_timeout"
+#define DEF_SMTPD_STARTTLS_TMOUT "300s"
+extern int var_smtpd_starttls_tmout;
+
 #define VAR_SMTPD_RCPT_LIMIT	"smtpd_recipient_limit"
 #define DEF_SMTPD_RCPT_LIMIT	1000
 extern int var_smtpd_rcpt_limit;
@@ -791,6 +827,150 @@
 #define DEF_SMTPD_NOOP_CMDS	""
 extern char *var_smtpd_noop_cmds;
 
+#define VAR_SMTPD_TLS_WRAPPER	"smtpd_tls_wrappermode"
+#define DEF_SMTPD_TLS_WRAPPER	0
+extern bool var_smtpd_tls_wrappermode;
+
+#define VAR_SMTPD_USE_TLS	"smtpd_use_tls"
+#define DEF_SMTPD_USE_TLS	0
+extern bool var_smtpd_use_tls;
+
+#define VAR_SMTPD_ENFORCE_TLS	"smtpd_enforce_tls"
+#define DEF_SMTPD_ENFORCE_TLS	0
+extern bool var_smtpd_enforce_tls;
+
+#define VAR_SMTPD_TLS_AUTH_ONLY	"smtpd_tls_auth_only"
+#define DEF_SMTPD_TLS_AUTH_ONLY 0
+extern bool var_smtpd_tls_auth_only;
+
+#define VAR_SMTPD_TLS_ACERT	"smtpd_tls_ask_ccert"
+#define DEF_SMTPD_TLS_ACERT	0
+extern bool var_smtpd_tls_ask_ccert;
+
+#define VAR_SMTPD_TLS_RCERT	"smtpd_tls_req_ccert"
+#define DEF_SMTPD_TLS_RCERT	0
+extern bool var_smtpd_tls_req_ccert;
+
+#define VAR_SMTPD_TLS_CCERT_VD	"smtpd_tls_ccert_verifydepth"
+#define DEF_SMTPD_TLS_CCERT_VD	5
+extern int var_smtpd_tls_ccert_vd;
+
+#define VAR_SMTPD_TLS_CERT_FILE	"smtpd_tls_cert_file"
+#define DEF_SMTPD_TLS_CERT_FILE	""
+extern char *var_smtpd_tls_cert_file;
+
+#define VAR_SMTPD_TLS_KEY_FILE	"smtpd_tls_key_file"
+#define DEF_SMTPD_TLS_KEY_FILE	"$smtpd_tls_cert_file"
+extern char *var_smtpd_tls_key_file;
+
+#define VAR_SMTPD_TLS_DCERT_FILE "smtpd_tls_dcert_file"
+#define DEF_SMTPD_TLS_DCERT_FILE ""
+extern char *var_smtpd_tls_dcert_file;
+
+#define VAR_SMTPD_TLS_DKEY_FILE	"smtpd_tls_dkey_file"
+#define DEF_SMTPD_TLS_DKEY_FILE	"$smtpd_tls_dcert_file"
+extern char *var_smtpd_tls_dkey_file;
+
+#define VAR_SMTPD_TLS_CA_FILE	"smtpd_tls_CAfile"
+#define DEF_SMTPD_TLS_CA_FILE	""
+extern char *var_smtpd_tls_CAfile;
+
+#define VAR_SMTPD_TLS_CA_PATH	"smtpd_tls_CApath"
+#define DEF_SMTPD_TLS_CA_PATH	""
+extern char *var_smtpd_tls_CApath;
+
+#define VAR_SMTPD_TLS_CLIST	"smtpd_tls_cipherlist"
+#define DEF_SMTPD_TLS_CLIST	""
+extern char *var_smtpd_tls_cipherlist;
+
+#define VAR_SMTPD_TLS_512_FILE	"smtpd_tls_dh512_param_file"
+#define DEF_SMTPD_TLS_512_FILE	""
+extern char *var_smtpd_tls_dh512_param_file;
+
+#define VAR_SMTPD_TLS_1024_FILE	"smtpd_tls_dh1024_param_file"
+#define DEF_SMTPD_TLS_1024_FILE	""
+extern char *var_smtpd_tls_dh1024_param_file;
+
+#define VAR_SMTPD_TLS_LOGLEVEL	"smtpd_tls_loglevel"
+#define DEF_SMTPD_TLS_LOGLEVEL	0
+extern int var_smtpd_tls_loglevel;
+
+#define VAR_SMTPD_TLS_RECHEAD	"smtpd_tls_received_header"
+#define DEF_SMTPD_TLS_RECHEAD	0
+extern bool var_smtpd_tls_received_header;
+
+#define VAR_SMTPD_TLS_SCACHE_DB	"smtpd_tls_session_cache_database"
+#define DEF_SMTPD_TLS_SCACHE_DB	""
+extern char *var_smtpd_tls_scache_db;
+
+#define VAR_SMTPD_TLS_SCACHTIME	"smtpd_tls_session_cache_timeout"
+#define DEF_SMTPD_TLS_SCACHTIME	"3600s"
+extern int var_smtpd_tls_scache_timeout;
+
+#define VAR_SMTP_TLS_PER_SITE	"smtp_tls_per_site"
+#define DEF_SMTP_TLS_PER_SITE	""
+extern char *var_smtp_tls_per_site;
+
+#define VAR_SMTP_USE_TLS	"smtp_use_tls"
+#define DEF_SMTP_USE_TLS	0
+extern bool var_smtp_use_tls;
+
+#define VAR_SMTP_ENFORCE_TLS	"smtp_enforce_tls"
+#define DEF_SMTP_ENFORCE_TLS	0
+extern bool var_smtp_enforce_tls;
+
+#define VAR_SMTP_TLS_ENFORCE_PN	"smtp_tls_enforce_peername"
+#define DEF_SMTP_TLS_ENFORCE_PN	1
+extern bool var_smtp_tls_enforce_peername;
+
+#define VAR_SMTP_TLS_SCERT_VD	"smtp_tls_scert_verifydepth"
+#define DEF_SMTP_TLS_SCERT_VD	5
+extern int var_smtp_tls_scert_vd;
+
+#define VAR_SMTP_TLS_CERT_FILE	"smtp_tls_cert_file"
+#define DEF_SMTP_TLS_CERT_FILE	""
+extern char *var_smtp_tls_cert_file;
+
+#define VAR_SMTP_TLS_KEY_FILE	"smtp_tls_key_file"
+#define DEF_SMTP_TLS_KEY_FILE	"$smtp_tls_cert_file"
+extern char *var_smtp_tls_key_file;
+
+#define VAR_SMTP_TLS_DCERT_FILE "smtp_tls_dcert_file"
+#define DEF_SMTP_TLS_DCERT_FILE ""
+extern char *var_smtp_tls_dcert_file;
+
+#define VAR_SMTP_TLS_DKEY_FILE	"smtp_tls_dkey_file"
+#define DEF_SMTP_TLS_DKEY_FILE	"$smtp_tls_dcert_file"
+extern char *var_smtp_tls_dkey_file;
+
+#define VAR_SMTP_TLS_CA_FILE	"smtp_tls_CAfile"
+#define DEF_SMTP_TLS_CA_FILE	""
+extern char *var_smtp_tls_CAfile;
+
+#define VAR_SMTP_TLS_CA_PATH	"smtp_tls_CApath"
+#define DEF_SMTP_TLS_CA_PATH	""
+extern char *var_smtp_tls_CApath;
+
+#define VAR_SMTP_TLS_CLIST	"smtp_tls_cipherlist"
+#define DEF_SMTP_TLS_CLIST	""
+extern char *var_smtp_tls_cipherlist;
+
+#define VAR_SMTP_TLS_LOGLEVEL	"smtp_tls_loglevel"
+#define DEF_SMTP_TLS_LOGLEVEL	0
+extern int var_smtp_tls_loglevel;
+
+#define VAR_SMTP_TLS_NOTEOFFER	"smtp_tls_note_starttls_offer"
+#define DEF_SMTP_TLS_NOTEOFFER	0
+extern bool var_smtp_tls_note_starttls_offer;
+
+#define VAR_SMTP_TLS_SCACHE_DB	"smtp_tls_session_cache_database"
+#define DEF_SMTP_TLS_SCACHE_DB	""
+extern char *var_smtp_tls_scache_db;
+
+#define VAR_SMTP_TLS_SCACHTIME	"smtp_tls_session_cache_timeout"
+#define DEF_SMTP_TLS_SCACHTIME	"3600s"
+extern int var_smtp_tls_scache_timeout;
+
  /*
   * SASL authentication support, SMTP server side.
   */
@@ -1072,6 +1252,10 @@
 #define DEF_RELAY_DOMAINS	"$mydestination"
 extern char *var_relay_domains;
 
+#define VAR_RELAY_CCERTS	"relay_clientcerts"
+#define DEF_RELAY_CCERTS	""
+extern char *var_relay_ccerts;
+
 #define VAR_CLIENT_CHECKS	"smtpd_client_restrictions"
 #define DEF_CLIENT_CHECKS	""
 extern char *var_client_checks;
@@ -1151,6 +1335,8 @@
 #define PERMIT_AUTH_DEST	"permit_auth_destination"
 #define REJECT_UNAUTH_DEST	"reject_unauth_destination"
 #define CHECK_RELAY_DOMAINS	"check_relay_domains"
+#define PERMIT_TLS_CLIENTCERTS	"permit_tls_clientcerts"
+#define PERMIT_TLS_ALL_CLIENTCERTS	"permit_tls_all_clientcerts"
 #define VAR_RELAY_CODE		"relay_domains_reject_code"
 #define DEF_RELAY_CODE		554
 extern int var_relay_code;
diff -r -u --new-file postfix-1.1.0-vanilla/src/global/mail_proto.h postfix-1.1.0/src/global/mail_proto.h
--- postfix-1.1.0-vanilla/src/global/mail_proto.h	Fri Nov  2 21:51:28 2001
+++ postfix-1.1.0/src/global/mail_proto.h	Thu Jan 17 21:30:50 2002
@@ -34,6 +34,7 @@
 #define MAIL_SERVICE_LOCAL	"local"
 #define MAIL_SERVICE_PICKUP	"pickup"
 #define MAIL_SERVICE_QUEUE	"qmgr"
+#define MAIL_SERVICE_TLSMGR	"tlsmgr"
 #define MAIL_SERVICE_RESOLVE	"resolve"
 #define MAIL_SERVICE_REWRITE	"rewrite"
 #define MAIL_SERVICE_VIRTUAL	"virtual"
diff -r -u --new-file postfix-1.1.0-vanilla/src/global/pfixtls.c postfix-1.1.0/src/global/pfixtls.c
--- postfix-1.1.0-vanilla/src/global/pfixtls.c	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/src/global/pfixtls.c	Thu Jan 17 21:30:50 2002
@@ -0,0 +1,2740 @@
+/*++
+/* NAME
+/*	pfixtls
+/* SUMMARY
+/*	interface to openssl routines
+/* SYNOPSIS
+/*	#include <pfixtls.h>
+/*
+/*	const long scache_db_version;
+/*	const long openssl_version;
+/*
+/*	int pfixtls_serverengine;
+/*
+/*	int pfixtls_clientengine;
+/*
+/*	int pfixtls_timed_read(fd, buf, len, timeout, unused_context)
+/*	int fd;
+/*	void *buf;
+/*	unsigned len;
+/*	int timeout;
+/*	void *context;
+/*
+/*	int pfixtls_timed_write(fd, buf, len, timeout, unused_context);
+/*	int fd;
+/*	void *buf;
+/*	unsigned len;
+/*	int timeout;
+/*	void *context;
+/*
+/*	int pfixtls_init_serverengine(verifydepth, askcert);
+/*	int verifydepth;
+/*	int askcert;
+/*
+/*	int pfixtls_start_servertls(stream, timeout, peername, peeraddr,
+/*				    tls_info, requirecert);
+/*	VSTREAM *stream;
+/*	int timeout;
+/*	const char *peername;
+/*	const char *peeraddr;
+/*	tls_info_t *tls_info;
+/*	int requirecert;
+/*
+/*	int pfixtls_stop_servertls(stream, failure, tls_info);
+/*	VSTREAM *stream;
+/*	int failure;
+/*	tls_info_t *tls_info;
+/*	
+/*	int pfixtls_init_clientengine(verifydepth);
+/*	int verifydepth;
+/*
+/*	int pfixtls_start_clienttls(stream, timeout, peername, peeraddr,
+/*				    tls_info);
+/*	VSTREAM *stream;
+/*	int timeout;
+/*	const char *peername;
+/*	const char *peeraddr;
+/*	tls_info_t *tls_info;
+/*
+/*	int pfixtls_stop_clienttls(stream, failure, tls_info);
+/*	VSTREAM *stream;
+/*	int failure;
+/*	tls_info_t *tls_info;
+/*
+/* DESCRIPTION
+/*	This module is the interface between Postfix and the OpenSSL library.
+/*
+/*	pfixtls_timed_read() reads the requested number of bytes calling
+/*	SSL_read(). pfixtls_time_read() will only be called indirect
+/*	as a VSTREAM_FN function.
+/*	pfixtls_timed_write() is the corresponding write function.
+/*
+/*	pfixtls_init_serverengine() is called once when smtpd is started
+/*	in order to initialize as much of the TLS stuff as possible.
+/*	The certificate handling is also decided during the setup phase,
+/*	so that a peer specific handling is not possible.
+/*
+/*	pfixtls_init_clientengine() is the corresponding function called
+/*	in smtp. Here we take the peer's (server's) certificate in any
+/*	case.
+/*
+/*	pfixtls_start_servertls() activates the TLS feature for the VSTREAM
+/*	passed as argument. We expect that all buffers are flushed and the
+/*	TLS handshake can begin	immediately. Information about the peer
+/*	is stored into the tls_info structure passed as argument.
+/*
+/*	pfixtls_stop_servertls() sends the "close notify" alert via
+/*	SSL_shutdown() to the peer and resets all connection specific
+/*	TLS data. As RFC2487 does not specify a seperate shutdown, it
+/*	is supposed that the underlying TCP connection is shut down
+/*	immediately afterwards, so we don't care about additional data
+/*	coming through the channel.
+/*	If the failure flag is set, the session is cleared from the cache.
+/*
+/*	pfixtls_start_clienttls() and pfixtls_stop_clienttls() are the
+/*	corresponding functions for smtp.
+/*
+/*	Once the TLS connection is initiated, information about the TLS
+/*	state is available via the tls_info structure:
+/*	protocol holds the protocol name (SSLv2, SSLv3, TLSv1),
+/*	tls_info->cipher_name the cipher name (e.g. RC4/MD5),
+/*	tls_info->cipher_usebits the number of bits actually used (e.g. 40),
+/*	tls_info->cipher_algbits the number of bits the algorithm is based on
+/*	(e.g. 128).
+/*	The last two values may be different when talking to a crippled
+/*	- ahem - export controled peer (e.g. 40/128).
+/*
+/*	The status of the peer certificate verification is available in
+/*	pfixtls_peer_verified. It is set to 1, when the certificate could
+/*	be verified.
+/*	If the peer offered a certifcate, part of the certificate data are
+/*	available as:
+/*	tls_info->peer_subject X509v3-oneline with the DN of the peer
+/*	tls_info->peer_CN extracted CommonName of the peer
+/*	tls_info->peer_issuer  X509v3-oneline with the DN of the issuer
+/*	tls_info->peer_CN extracted CommonName of the issuer
+/*	tls_info->PEER_FINGERPRINT fingerprint of the certificate
+/*
+/* DESCRIPTION (SESSION CACHING)
+/*	In order to achieve high performance when using a lot of connections
+/*	with TLS, session caching is implemented. It reduces both the CPU load
+/*	(less cryptograpic operations) and the network load (the amount of
+/*	certificate data exchanged is reduced).
+/*	Since postfix uses a setup of independent processes for receiving
+/*	and sending email, the processes must exchange the session information.
+/*	Several connections at the same time between the identical peers can
+/*	occur, so uniqueness and race conditions have to be taken into
+/*	account.
+/*	I have checked both Apache-SSL (Ben Laurie), using a seperate "gcache"
+/*	process and Apache mod_ssl (Ralf S. Engelshall), using shared memory
+/*	between several identical processes spawned from one parent.
+/*
+/*	Postfix/TLS uses a database approach based on the internal "dict"
+/*	interface. Since the session cache information is approximately
+/*	1300 bytes binary data, it will not fit into the dbm/ndbm model.
+/*	It also needs write access to the database, ruling out most other
+/*	interface, leaving Berkeley DB, which however cannot handle concurrent
+/*	access by several processes. Hence a modified SDBM (public domain DBM)
+/*	with enhanced buffer size is used and concurrent write capability
+/*	is used. SDBM is part of Postfix/TLS.
+/*
+/*	Realization:
+/*	Both (client and server) session cache are realized by individual
+/*	cache databases. A common database would not make sense, since the
+/*	key criteria are different (session ID for server, peername for
+/*	client).
+/*
+/*	Server side:
+/*	Session created by OpenSSL have a 32 byte session id, yielding a
+/*	64 char file name. I consider these sessions to be unique. If they
+/*	are not, the last session will win, overwriting the older one in
+/*	the database. Remember: everything that is lost is a temporary
+/*	information and not more than a renegotiation will happen.
+/*	Originating from the same client host, several sessions can come
+/*	in (e.g. from several users sending mail with Netscape at the same
+/*	time), so the session id is the correct identifier; the hostname
+/*	is of no importance, here.
+/*
+/*	Client side:
+/*	We cannot recall sessions based on their session id, because we would
+/*	have to check every session on disk for a matching server name, so
+/*	the lookup has to be done based on the FQDN of the peer (receiving
+/*	host).
+/*	With regard to uniqueness, we might experience several open connections
+/*	to the same server at the same time. This is even very likely to
+/*	happen, since we might have several mails for the same destination
+/*	in the queue, when a queue run is started. So several smtps might
+/*	negotiate sessions at the same time. We can however only save one
+/*	session for one host.
+/*	Like on the server side, the "last write" wins. The reason is
+/*	quite simple. If we dont want to overwrite old sessions, an old
+/*	session file will just stay in place until it is expired. In the
+/*	meantime we would lose "fresh" session however. So we will keep the
+/*	fresh one instead to avoid unnecessary renegotiations.
+/*
+/*	Session lifetime:
+/*	RFC2246 recommends a session lifetime of less than 24 hours. The
+/*	default is 300 seconds (5 minutes) for OpenSSL and is also used
+/*	this way in e.g. mod_ssl. The typical usage for emails might be
+/*	humans typing in emails and sending them, which might take just
+/*	a while, so I think 3600 seconds (1 hour) is a good compromise.
+/*	If the environment is save (the cached session contains secret
+/*	key data), one might even consider using a longer timeout. Anyway,
+/*	since everlasting sessions must be avoided, the session timeout
+/*	is done based on the creation date of the session and so each
+/*	session will timeout eventually.
+/*
+/*	Connection failures:
+/*	RFC2246 requires us to remove sessions if something went wrong.
+/*	Since the in-memory session cache of other smtp[d] processes cannot
+/*	be controlled by simple means, we completely rely on the disc
+/*	based session caching and remove all sessions from memory after
+/*	connection closure.
+/*
+/*	Cache cleanup:
+/*	Since old entries have to be removed from the session cache, a
+/*	cleanup process is needed that runs through the collected session
+/*	files on regular basis. The task is performed by tlsmgr based on
+/*	the timestamp created by pfixtls and included in the saved session,
+/*	so that tlsmgr has not to care about the SSL_SESSION internal data.
+/*
+/* BUGS
+/*	The memory allocation policy of the OpenSSL library is not well
+/*	documented, especially when loading sessions from disc. Hence there
+/*	might be memory leaks.
+/*
+/* LICENSE
+/* AUTHOR(S)
+/*	Lutz Jaenicke
+/*	BTU Cottbus
+/*	Allgemeine Elektrotechnik
+/*	Universitaetsplatz 3-4
+/*	D-03044 Cottbus, Germany
+/*--*/
+
+/* System library. */
+
+#include <sys_defs.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/time.h>			/* gettimeofday, not in POSIX */
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <ctype.h>
+
+/* Utility library. */
+
+#include <iostuff.h>
+#include <mymalloc.h>
+#include <vstring.h>
+#include <vstream.h>
+#include <dict.h>
+#include <myflock.h>
+#include <stringops.h>
+#include <msg.h>
+#include <connect.h>
+
+/* Application-specific. */
+
+#include "mail_params.h"
+#include "pfixtls.h"
+
+#define STR	vstring_str
+
+const tls_info_t tls_info_zero = {
+    0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0
+};
+
+#ifdef HAS_SSL
+
+/* OpenSSL library. */
+
+#include <openssl/lhash.h>
+#include <openssl/bn.h>
+#include <openssl/err.h>
+#include <openssl/pem.h>
+#include <openssl/x509.h>
+#include <openssl/rand.h>
+#include <openssl/ssl.h>
+
+/* We must keep some of the info available */
+static const char hexcodes[] = "0123456789ABCDEF";
+
+/*
+ * When saving sessions, we want to make sure, that the lenght of the key
+ * is somehow limited. When saving client sessions, the hostname is used
+ * as key. According to HP-UX 10.20, MAXHOSTNAMELEN=64. Maybe new standards
+ * will increase this value, but as this will break compatiblity with existing
+ * implementations, we won't see this for long. We therefore choose a limit
+ * of 64 bytes.
+ * The length of the (TLS) session id can be up to 32 bytes according to
+ * RFC2246, so it fits well into the 64bytes limit.
+ */
+#define ID_MAXLENGTH	64		/* Max ID length in bytes */
+
+/*
+ * The session_id_context is set, such that the client knows which services
+ * on a host share the same session information (on the postfix host may
+ * as well run a TLS-enabled webserver.
+ */
+static char server_session_id_context[] = "Postfix/TLS"; /* anything will do */
+static int TLScontext_index = -1;
+static int TLSpeername_index = -1;
+static int do_dump = 0;
+static DH *dh_512 = NULL, *dh_1024 = NULL;
+static SSL_CTX *ctx = NULL;
+
+static int rand_exch_fd = -1;
+
+static DICT *scache_db = NULL;
+const long scache_db_version = 0x00000003L;
+const long openssl_version = OPENSSL_VERSION_NUMBER;
+
+
+int     pfixtls_serverengine = 0;
+static int pfixtls_serveractive = 0;	/* available or not */
+
+int     pfixtls_clientengine = 0;
+static int pfixtls_clientactive = 0;	/* available or not */
+
+/*
+ * Define a maxlength for certificate onelines. The length is checked by
+ * all routines when copying.
+ */
+#define CCERT_BUFSIZ 256
+
+typedef struct {
+  SSL *con;
+  BIO *internal_bio;			/* postfix/TLS side of pair */
+  BIO *network_bio;			/* netsork side of pair */
+  char peer_subject[CCERT_BUFSIZ];
+  char peer_issuer[CCERT_BUFSIZ];
+  char peer_CN[CCERT_BUFSIZ];
+  char issuer_CN[CCERT_BUFSIZ];
+  unsigned char md[EVP_MAX_MD_SIZE];
+  char fingerprint[EVP_MAX_MD_SIZE * 3];
+  char peername_save[129];
+  int enforce_verify_errors;
+  int enforce_CN;
+} TLScontext_t;
+
+typedef struct {
+    int pid;
+    struct timeval tv;
+} randseed_t;
+
+static randseed_t randseed;
+
+/*
+ * Finally some "backup" DH-Parameters to be loaded, if no parameters are
+ * explicitely loaded from file.
+ */
+static unsigned char dh512_p[] = {
+    0x88, 0x3F, 0x00, 0xAF, 0xFC, 0x0C, 0x8A, 0xB8, 0x35, 0xCD, 0xE5, 0xC2,
+    0x0F, 0x55, 0xDF, 0x06, 0x3F, 0x16, 0x07, 0xBF, 0xCE, 0x13, 0x35, 0xE4,
+    0x1C, 0x1E, 0x03, 0xF3, 0xAB, 0x17, 0xF6, 0x63, 0x50, 0x63, 0x67, 0x3E,
+    0x10, 0xD7, 0x3E, 0xB4, 0xEB, 0x46, 0x8C, 0x40, 0x50, 0xE6, 0x91, 0xA5,
+    0x6E, 0x01, 0x45, 0xDE, 0xC9, 0xB1, 0x1F, 0x64, 0x54, 0xFA, 0xD9, 0xAB,
+    0x4F, 0x70, 0xBA, 0x5B,
+};
+
+static unsigned char dh512_g[] = {
+    0x02,
+};
+
+static unsigned char dh1024_p[] = {
+    0xB0, 0xFE, 0xB4, 0xCF, 0xD4, 0x55, 0x07, 0xE7, 0xCC, 0x88, 0x59, 0x0D,
+    0x17, 0x26, 0xC5, 0x0C, 0xA5, 0x4A, 0x92, 0x23, 0x81, 0x78, 0xDA, 0x88,
+    0xAA, 0x4C, 0x13, 0x06, 0xBF, 0x5D, 0x2F, 0x9E, 0xBC, 0x96, 0xB8, 0x51,
+    0x00, 0x9D, 0x0C, 0x0D, 0x75, 0xAD, 0xFD, 0x3B, 0xB1, 0x7E, 0x71, 0x4F,
+    0x3F, 0x91, 0x54, 0x14, 0x44, 0xB8, 0x30, 0x25, 0x1C, 0xEB, 0xDF, 0x72,
+    0x9C, 0x4C, 0xF1, 0x89, 0x0D, 0x68, 0x3F, 0x94, 0x8E, 0xA4, 0xFB, 0x76,
+    0x89, 0x18, 0xB2, 0x91, 0x16, 0x90, 0x01, 0x99, 0x66, 0x8C, 0x53, 0x81,
+    0x4E, 0x27, 0x3D, 0x99, 0xE7, 0x5A, 0x7A, 0xAF, 0xD5, 0xEC, 0xE2, 0x7E,
+    0xFA, 0xED, 0x01, 0x18, 0xC2, 0x78, 0x25, 0x59, 0x06, 0x5C, 0x39, 0xF6,
+    0xCD, 0x49, 0x54, 0xAF, 0xC1, 0xB1, 0xEA, 0x4A, 0xF9, 0x53, 0xD0, 0xDF,
+    0x6D, 0xAF, 0xD4, 0x93, 0xE7, 0xBA, 0xAE, 0x9B,
+};
+
+static unsigned char dh1024_g[] = {
+    0x02,
+};
+
+/*
+ * DESCRIPTION: Keeping control of the network interface using BIO-pairs.
+ *
+ * When the TLS layer is active, all input/output must be filtered through
+ * it. On the other hand to handle timeout conditions, full control over
+ * the network socket must be kept. This rules out the "normal way" of
+ * connecting the TLS layer directly to the socket.
+ * The TLS layer is realized with a BIO-pair:
+ *
+ *     postfix  |   TLS-engine
+ *       |      |
+ *       +--------> SSL_operations()
+ *              |     /\    ||
+ *              |     ||    \/
+ *              |   BIO-pair (internal_bio)
+ *       +--------< BIO-pair (network_bio)
+ *       |      |
+ *     socket   |
+ *
+ * The normal postfix operations connect to the SSL operations to send
+ * and retrieve (cleartext) data. Inside the TLS-engine the data are converted
+ * to/from TLS protocol. The TLS functionality itself is only connected to
+ * the internal_bio and hence only has status information about this internal
+ * interface.
+ * Thus, if the SSL_operations() return successfully (SSL_ERROR_NONE) or want
+ * to read (SSL_ERROR_WANT_READ) there may as well be data inside the buffering
+ * BIO-pair. So whenever an SSL_operation() returns without a fatal error,
+ * the BIO-pair internal buffer must be flushed to the network.
+ * NOTE: This is especially true in the SSL_ERROR_WANT_READ case: the TLS-layer
+ * might want to read handshake data, that will never come since its own
+ * written data will only reach the peer after flushing the buffer!
+ *
+ * The BIO-pair buffer size has been set to 8192 bytes, this is an arbitrary
+ * value that can hold more data than the typical PMTU, so that it does
+ * not force the generation of packets smaller than necessary.
+ * It is also larger than the default VSTREAM_BUFSIZE (4096, see vstream.h),
+ * so that large write operations could be handled within one call.
+ * The internal buffer in the network/network_bio handling layer has been
+ * set to the same value, since this seems to be reasonable. The code is
+ * however able to handle arbitrary values smaller or larger than the
+ * buffer size in the BIO-pair.
+ */
+
+const ssize_t BIO_bufsiz = 8192;
+
+/*
+ * The interface layer between network and BIO-pair. The BIO-pair buffers
+ * the data to/from the TLS layer. Hence, at any time, there may be data
+ * in the buffer that must be written to the network. This writing has
+ * highest priority because the handshake might fail otherwise.
+ * Only then a read_request can be satisfied.
+ */
+static int network_biopair_interop(int fd, int timeout, BIO *network_bio)
+{
+    int want_write;
+    int num_write;
+    int write_pos;
+    int from_bio;
+    int want_read;
+    int num_read;
+    int to_bio;
+#define NETLAYER_BUFFERSIZE 8192
+    char buffer[8192];
+
+    while ((want_write = BIO_ctrl_pending(network_bio)) > 0) {
+	if (want_write > NETLAYER_BUFFERSIZE)
+	    want_write = NETLAYER_BUFFERSIZE;
+	from_bio = BIO_read(network_bio, buffer, want_write);
+
+	/*
+	 * Write the complete contents of the buffer. Since TLS performs
+	 * underlying handshaking, we cannot afford to leave the buffer
+	 * unflushed, as we could run into a deadlock trap (the peer
+	 * waiting for a final byte and we already waiting for his reply
+	 * in read position).
+	 */
+        write_pos = 0;
+	do {
+	    if (timeout > 0 && write_wait(fd, timeout) < 0)
+		return (-1);
+	    num_write = write(fd, buffer + write_pos, from_bio - write_pos);
+	    if (num_write <= 0)
+		return (-1);	/* something happened to the socket */
+	    write_pos += num_write;
+	} while (write_pos < from_bio);
+   }
+
+   while ((want_read = BIO_ctrl_get_read_request(network_bio)) > 0) {
+	if (want_read > NETLAYER_BUFFERSIZE)
+	    want_read = NETLAYER_BUFFERSIZE;
+	if (timeout > 0 && read_wait(fd, timeout) < 0)
+	    return (-1);
+	num_read = read(fd, buffer, want_read);
+	if (num_read <= 0)
+	    return (-1);	/* something happened to the socket */
+	to_bio = BIO_write(network_bio, buffer, num_read);
+	if (to_bio != num_read)
+		msg_fatal("to_bio != num_read");
+    }
+
+    return (0);
+}
+
+static void pfixtls_print_errors(void);
+
+ /*
+  * Function to perform the handshake for SSL_accept(), SSL_connect(),
+  * and SSL_shutdown() and perform the SSL_read(), SSL_write() operations.
+  * Call the underlying network_biopair_interop-layer to make sure the
+  * write buffer is flushed after every operation (that did not fail with
+  * a fatal error).
+  */
+static int do_tls_operation(int fd, int timeout, TLScontext_t *TLScontext,
+			int (*hsfunc)(SSL *),
+			int (*rfunc)(SSL *, void *, int),
+			int (*wfunc)(SSL *, const void *, int),
+			char *buf, int num)
+{
+    int status;
+    int err;
+    int retval = 0;
+    int biop_retval;
+    int done = 0;
+
+    while (!done) {
+	if (hsfunc)
+	    status = hsfunc(TLScontext->con);
+	else if (rfunc)
+	    status = rfunc(TLScontext->con, buf, num);
+	else
+	    status = wfunc(TLScontext->con, (const char *)buf, num);
+	err = SSL_get_error(TLScontext->con, status);
+
+#if (OPENSSL_VERSION_NUMBER <= 0x0090581fL)
+	/*
+	 * There is a bug up to and including OpenSSL-0.9.5a: if an error
+	 * occurs while checking the peers certificate due to some certificate
+	 * error (e.g. as happend with a RSA-padding error), the error is put
+	 * onto the error stack. If verification is not enforced, this error
+	 * should be ignored, but the error-queue is not cleared, so we
+	 * can find this error here. The bug has been fixed on May 28, 2000.
+	 *
+	 * This bug so far has only manifested as
+	 * 4800:error:0407006A:rsa routines:RSA_padding_check_PKCS1_type_1:block type is not 01:rsa_pk1.c:100:
+	 * 4800:error:04067072:rsa routines:RSA_EAY_PUBLIC_DECRYPT:padding check failed:rsa_eay.c:396:
+	 * 4800:error:0D079006:asn1 encoding routines:ASN1_verify:bad get asn1 object call:a_verify.c:109:
+	 * so that we specifically test for this error. We print the errors
+	 * to the logfile and automatically clear the error queue. Then we
+	 * retry to get another error code. We cannot do better, since we
+	 * can only retrieve the last entry of the error-queue without
+	 * actually cleaning it on the way.
+	 *
+	 * This workaround is secure, as verify_result is set to "failed"
+	 * anyway.
+	 */
+	if (err == SSL_ERROR_SSL) {
+	    if (ERR_peek_error() == 0x0407006AL) {
+		pfixtls_print_errors();	/* Keep information for the logfile */
+		msg_info("OpenSSL <= 0.9.5a workaround called: certificate errors ignored");
+		err = SSL_get_error(TLScontext->con, status);
+	    }
+	}
+#endif
+
+	switch (err) {
+	case SSL_ERROR_NONE:		/* success */
+	    retval = status;
+	    done = 1;			/* no break, flush buffer before */
+					/* leaving */
+	case SSL_ERROR_WANT_WRITE:
+	case SSL_ERROR_WANT_READ:
+	    biop_retval = network_biopair_interop(fd, timeout,
+		TLScontext->network_bio);
+	    if (biop_retval < 0)
+		return (-1);		/* fatal network error */
+	    break;
+	case SSL_ERROR_ZERO_RETURN:	/* connection was closed cleanly */
+	case SSL_ERROR_SYSCALL:		
+	case SSL_ERROR_SSL:
+	default:
+	    retval = status;
+	    done = 1;
+	    ;
+	}
+    };
+    return retval;
+}
+
+int pfixtls_timed_read(int fd, void *buf, unsigned buf_len, int timeout, 
+		       void *context)
+{
+    int     i;
+    int     ret;
+    char    mybuf[40];
+    char   *mybuf2;
+    TLScontext_t *TLScontext;
+
+    TLScontext = (TLScontext_t *)context;
+    if (!TLScontext)
+      msg_fatal("Called tls_timed_read() without TLS-context");
+ 
+    ret = do_tls_operation(fd, timeout, TLScontext, NULL, SSL_read, NULL,
+			  (char *)buf, buf_len);
+    if ((pfixtls_serveractive && var_smtpd_tls_loglevel >= 4) ||
+        (pfixtls_clientactive && var_smtp_tls_loglevel >= 4)) {
+	mybuf2 = (char *) buf;
+	if (ret > 0) {
+	    i = 0;
+	    while ((i < 39) && (i < ret) && (mybuf2[i] != 0)) {
+		mybuf[i] = mybuf2[i];
+		i++;
+	    }
+	    mybuf[i] = '\0';
+	    msg_info("Read %d chars: %s", ret, mybuf);
+	}
+    }
+    return (ret);
+}
+
+int pfixtls_timed_write(int fd, void *buf, unsigned len, int timeout,
+			void *context)
+{
+    int     i;
+    char    mybuf[40];
+    char   *mybuf2;
+    TLScontext_t *TLScontext;
+
+    TLScontext = (TLScontext_t *)context;
+    if (!TLScontext)
+      msg_fatal("Called tls_timed_write() without TLS-context");
+
+    if ((pfixtls_serveractive && var_smtpd_tls_loglevel >= 4) ||
+	(pfixtls_clientactive && var_smtp_tls_loglevel >= 4)) {
+	mybuf2 = (char *) buf;
+	if (len > 0) {
+	    i = 0;
+	    while ((i < 39) && (i < len) && (mybuf2[i] != 0)) {
+		mybuf[i] = mybuf2[i];
+		i++;
+	    }
+	    mybuf[i] = '\0';
+	    msg_info("Write %d chars: %s", len, mybuf);
+	}
+    }
+    return (do_tls_operation(fd, timeout, TLScontext, NULL, NULL, SSL_write,
+			     buf, len));
+}
+
+/* Add some more entropy to the pool by adding the actual time */
+
+static void pfixtls_stir_seed(void)
+{
+    GETTIMEOFDAY(&randseed.tv);
+    RAND_seed(&randseed, sizeof(randseed_t));
+}
+
+/*
+ * Skeleton taken from OpenSSL crypto/err/err_prn.c.
+ * Query the error stack and print the error string into the logging facility.
+ * Clear the error stack on the way.
+ */
+
+static void pfixtls_print_errors(void)
+{
+    unsigned long l;
+    char    buf[256];
+    const char   *file;
+    const char   *data;
+    int     line;
+    int     flags;
+    unsigned long es;
+
+    es = CRYPTO_thread_id();
+    while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) {
+	if (flags & ERR_TXT_STRING)
+	    msg_info("%lu:%s:%s:%d:%s:", es, ERR_error_string(l, buf),
+		     file, line, data);
+	else
+	    msg_info("%lu:%s:%s:%d:", es, ERR_error_string(l, buf),
+		     file, line);
+    }
+}
+
+ /*
+  * Set up the cert things on the server side. We do need both the
+  * private key (in key_file) and the cert (in cert_file).
+  * Both files may be identical.
+  *
+  * This function is taken from OpenSSL apps/s_cb.c
+  */
+
+static int set_cert_stuff(SSL_CTX * ctx, char *cert_file, char *key_file)
+{
+    if (cert_file != NULL) {
+	if (SSL_CTX_use_certificate_chain_file(ctx, cert_file) <= 0) {
+	    msg_info("unable to get certificate from '%s'", cert_file);
+	    pfixtls_print_errors();
+	    return (0);
+	}
+	if (key_file == NULL)
+	    key_file = cert_file;
+	if (SSL_CTX_use_PrivateKey_file(ctx, key_file,
+					SSL_FILETYPE_PEM) <= 0) {
+	    msg_info("unable to get private key from '%s'", key_file);
+	    pfixtls_print_errors();
+	    return (0);
+	}
+	/* Now we know that a key and cert have been set against
+         * the SSL context */
+	if (!SSL_CTX_check_private_key(ctx)) {
+	    msg_info("Private key does not match the certificate public key");
+	    return (0);
+	}
+    }
+    return (1);
+}
+
+/* taken from OpenSSL apps/s_cb.c */
+
+static RSA *tmp_rsa_cb(SSL * s, int export, int keylength)
+{
+    static RSA *rsa_tmp = NULL;
+
+    if (rsa_tmp == NULL) {
+	rsa_tmp = RSA_generate_key(keylength, RSA_F4, NULL, NULL);
+    }
+    return (rsa_tmp);
+}
+
+
+static DH *get_dh512(void)
+{
+    DH *dh;
+
+    if (dh_512 == NULL) {
+	/* No parameter file loaded, use the compiled in parameters */
+	if ((dh = DH_new()) == NULL) return(NULL);
+	dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
+	dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
+	if ((dh->p == NULL) || (dh->g == NULL))
+	    return(NULL);
+	else
+	    dh_512 = dh;
+    }
+    return (dh_512);
+}
+
+static DH *get_dh1024(void)
+{
+    DH *dh;
+
+    if (dh_1024 == NULL) {
+	/* No parameter file loaded, use the compiled in parameters */
+	if ((dh = DH_new()) == NULL) return(NULL);
+	dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
+	dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
+	if ((dh->p == NULL) || (dh->g == NULL))
+	    return(NULL);
+	else
+	    dh_1024 = dh;
+    }
+    return (dh_1024);
+}
+
+/* partly inspired by mod_ssl */
+
+static DH *tmp_dh_cb(SSL *s, int export, int keylength)
+{
+    DH *dh_tmp = NULL;
+   
+    if (export) {
+	if (keylength == 512)
+	    dh_tmp = get_dh512();	/* export cipher */
+	else if (keylength == 1024)
+	    dh_tmp = get_dh1024();	/* normal */
+	else
+	    dh_tmp = get_dh1024();	/* not on-the-fly (too expensive) */
+					/* so use the 1024bit instead */
+    }
+    else {
+	dh_tmp = get_dh1024();		/* sign-only certificate */
+    }
+    return (dh_tmp);
+}
+
+
+/*
+ * Skeleton taken from OpenSSL apps/s_cb.c
+ *
+ * The verify_callback is called several times (directly or indirectly) from
+ * crypto/x509/x509_vfy.c. It is called as a last check for several issues,
+ * so this verify_callback() has the famous "last word". If it does return "0",
+ * the handshake is immediately shut down and the connection fails.
+ *
+ * Postfix/TLS has two modes, the "use" mode and the "enforce" mode:
+ *
+ * In the "use" mode we never want the connection to fail just because there is
+ * something wrong with the certificate (as we would have sent happily without
+ * TLS).  Therefore the return value is always "1".
+ *
+ * In the "enforce" mode we can shut down the connection as soon as possible.
+ * In server mode TLS itself may be enforced (e.g. to protect passwords),
+ * but certificates are optional. In this case the handshake must not fail
+ * if we are unhappy with the certificate and return "1" in any case.
+ * Only if a certificate is required the certificate must pass the verification
+ * and failure to do so will result in immediate termination (return 0).
+ * In the client mode the decision is made with respect to the peername
+ * enforcement. If we strictly enforce the matching of the expected peername
+ * the verification must fail immediatly on verification errors. We can also
+ * immediatly check the expected peername, as it is the CommonName at level 0.
+ * In all other cases, the problem is logged, so the SSL_get_verify_result()
+ * will inform about the verification failure, but the handshake (and SMTP
+ * connection will continue).
+ *
+ * The only error condition not handled inside the OpenSSL-Library is the
+ * case of a too-long certificate chain, so we check inside verify_callback().
+ * We only take care of this problem, if "ok = 1", because otherwise the
+ * verification already failed because of another problem and we don't want
+ * to overwrite the other error message. And if the verification failed,
+ * there is no such thing as "more failed", "most failed"... :-)
+ */
+
+static int verify_callback(int ok, X509_STORE_CTX * ctx)
+{
+    char    buf[256];
+    char   *CN_lowercase;
+    char   *peername_left;
+    X509   *err_cert;
+    int     err;
+    int     depth;
+    int     verify_depth;
+    int     hostname_matched;
+    SSL    *con;
+    TLScontext_t *TLScontext;
+
+    err_cert = X509_STORE_CTX_get_current_cert(ctx);
+    err = X509_STORE_CTX_get_error(ctx);
+    depth = X509_STORE_CTX_get_error_depth(ctx);
+
+    con = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
+    TLScontext = SSL_get_ex_data(con, TLScontext_index);
+
+    X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
+    if (((pfixtls_serverengine) && (var_smtpd_tls_loglevel >= 2)) ||
+	((pfixtls_clientengine) && (var_smtp_tls_loglevel >= 2)))
+	msg_info("Peer cert verify depth=%d %s", depth, buf);
+
+    verify_depth = SSL_get_verify_depth(con);
+    if (ok && (verify_depth >= 0) && (depth > verify_depth)) {
+	ok = 0;
+	err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
+	X509_STORE_CTX_set_error(ctx, err);
+    }
+    if (!ok) {
+	msg_info("verify error:num=%d:%s", err,
+		 X509_verify_cert_error_string(err));
+    }
+
+    if (ok && (depth == 0) && pfixtls_clientengine) {
+	/*
+	 * Check out the name certified against the hostname expected.
+	 * In case it does not match, print an information about the result.
+	 * If a matching is enforced, bump out with a verification error
+	 * immediately.
+	 */
+	buf[0] = '\0';
+	if (!X509_NAME_get_text_by_NID(X509_get_subject_name(err_cert),
+                          NID_commonName, buf, 256)) {
+	    msg_info("Could not parse server's subject CN");
+	    pfixtls_print_errors();
+	}
+	CN_lowercase = lowercase(buf);
+	hostname_matched = 0;
+	if (!strcmp(TLScontext->peername_save, CN_lowercase))
+	    hostname_matched = 1;
+	else if ((strlen(CN_lowercase) > 2) &&
+		 (CN_lowercase[0] == '*') && (CN_lowercase[1] == '.')) {
+	    /*
+	     * Allow wildcard certificate matching. The proposed rules in
+	     * RFCs (2818: HTTP/TLS, 2830: LDAP/TLS) are different, RFC2874
+	     * does not specify a rule, so here the strict rule is applied.
+	     * An asterisk '*' is allowed as the leftmost component and may
+	     * replace the left most part of the hostname. Matching is done
+	     * by removing '*.' from the wildcard name and the `name.` from
+	     * the peername and compare what is left.
+	     */
+	    peername_left = strchr(TLScontext->peername_save, '.');
+	    if (peername_left) {
+		if (!strcmp(peername_left + 1, CN_lowercase + 2))
+		    hostname_matched = 1;
+	    }
+	}
+
+	if (!hostname_matched) {
+		msg_info("Peer verification: CommonName in certificate does not match: %s != %s", CN_lowercase, TLScontext->peername_save);
+	    if (TLScontext->enforce_verify_errors && TLScontext->enforce_CN) {
+		err = X509_V_ERR_CERT_REJECTED;
+		X509_STORE_CTX_set_error(ctx, err);
+		msg_info("Verify failure: Hostname mismatch");
+		ok = 0;
+	    }
+	}
+    }
+
+    switch (ctx->error) {
+    case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
+	X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
+	msg_info("issuer= %s", buf);
+	break;
+    case X509_V_ERR_CERT_NOT_YET_VALID:
+    case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
+	msg_info("cert not yet valid");
+	break;
+    case X509_V_ERR_CERT_HAS_EXPIRED:
+    case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
+	msg_info("cert has expired");
+	break;
+    }
+    if (((pfixtls_serverengine) && (var_smtpd_tls_loglevel >= 2)) ||
+	((pfixtls_clientengine) && (var_smtp_tls_loglevel >= 2)))
+	msg_info("verify return:%d", ok);
+
+    if (TLScontext->enforce_verify_errors)
+	return (ok); 
+    else
+	return (1);
+}
+
+/* taken from OpenSSL apps/s_cb.c */
+
+static void apps_ssl_info_callback(SSL * s, int where, int ret)
+{
+    char   *str;
+    int     w;
+
+    w = where & ~SSL_ST_MASK;
+
+    if (w & SSL_ST_CONNECT)
+	str = "SSL_connect";
+    else if (w & SSL_ST_ACCEPT)
+	str = "SSL_accept";
+    else
+	str = "undefined";
+
+    if (where & SSL_CB_LOOP) {
+	    msg_info("%s:%s", str, SSL_state_string_long(s));
+    } else if (where & SSL_CB_ALERT) {
+	str = (where & SSL_CB_READ) ? "read" : "write";
+	if ((ret & 0xff) != SSL3_AD_CLOSE_NOTIFY)
+	msg_info("SSL3 alert %s:%s:%s", str,
+		 SSL_alert_type_string_long(ret),
+		 SSL_alert_desc_string_long(ret));
+    } else if (where & SSL_CB_EXIT) {
+	if (ret == 0)
+	    msg_info("%s:failed in %s",
+		     str, SSL_state_string_long(s));
+	else if (ret < 0) {
+	    msg_info("%s:error in %s",
+		     str, SSL_state_string_long(s));
+	}
+    }
+}
+
+/*
+ * taken from OpenSSL crypto/bio/b_dump.c, modified to save a lot of strcpy
+ * and strcat by Matti Aarnio.
+ */
+
+#define TRUNCATE
+#define DUMP_WIDTH	16
+
+static int pfixtls_dump(const char *s, int len)
+{
+    int     ret = 0;
+    char    buf[160 + 1];
+    char    *ss;
+    int     i;
+    int     j;
+    int     rows;
+    int     trunc;
+    unsigned char ch;
+
+    trunc = 0;
+
+#ifdef TRUNCATE
+    for (; (len > 0) && ((s[len - 1] == ' ') || (s[len - 1] == '\0')); len--)
+	trunc++;
+#endif
+
+    rows = (len / DUMP_WIDTH);
+    if ((rows * DUMP_WIDTH) < len)
+	rows++;
+
+    for (i = 0; i < rows; i++) {
+	buf[0] = '\0';				/* start with empty string */
+	ss = buf;
+
+	sprintf(ss, "%04x ", i * DUMP_WIDTH);
+	ss += strlen(ss);
+	for (j = 0; j < DUMP_WIDTH; j++) {
+	    if (((i * DUMP_WIDTH) + j) >= len) {
+		strcpy(ss, "   ");
+	    } else {
+		ch = ((unsigned char) *((char *) (s) + i * DUMP_WIDTH + j))
+		    & 0xff;
+		sprintf(ss, "%02x%c", ch, j == 7 ? '|' : ' ');
+		ss += 3;
+	    }
+	}
+	ss += strlen(ss);
+	*ss++ = ' ';
+	for (j = 0; j < DUMP_WIDTH; j++) {
+	    if (((i * DUMP_WIDTH) + j) >= len)
+		break;
+	    ch = ((unsigned char) *((char *) (s) + i * DUMP_WIDTH + j)) & 0xff;
+	    *ss++ = (((ch >= ' ') && (ch <= '~')) ? ch : '.');
+	    if (j == 7) *ss++ = ' ';
+	}
+	*ss = 0;
+	/* 
+	 * if this is the last call then update the ddt_dump thing so that
+         * we will move the selection point in the debug window
+         */
+	msg_info("%s", buf);
+	ret += strlen(buf);
+    }
+#ifdef TRUNCATE
+    if (trunc > 0) {
+	sprintf(buf, "%04x - <SPACES/NULS>\n", len + trunc);
+	msg_info("%s", buf);
+	ret += strlen(buf);
+    }
+#endif
+    return (ret);
+}
+
+
+
+/* taken from OpenSSL apps/s_cb.c */
+
+static long bio_dump_cb(BIO * bio, int cmd, const char *argp, int argi,
+			long argl, long ret)
+{
+    if (!do_dump)
+	return (ret);
+
+    if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
+	msg_info("read from %08X [%08lX] (%d bytes => %ld (0x%X))", bio, argp,
+		 argi, ret, ret);
+	pfixtls_dump(argp, (int) ret);
+	return (ret);
+    } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
+	msg_info("write to %08X [%08lX] (%d bytes => %ld (0x%X))", bio, argp,
+		 argi, ret, ret);
+	pfixtls_dump(argp, (int) ret);
+    }
+    return (ret);
+}
+
+
+ /*
+  * Callback to retrieve a session from the external session cache.
+  */
+static SSL_SESSION *get_session_cb(SSL *ssl, unsigned char *SessionID,
+				  int length, int *copy)
+{
+    SSL_SESSION *session;
+    char idstring[2 * ID_MAXLENGTH + 1];
+    int n;
+    int uselength;
+    int hex_length;
+    const char *session_hex;
+    pfixtls_scache_info_t scache_info;
+    unsigned char nibble, *data, *sess_data;
+
+    if (length > ID_MAXLENGTH)
+	uselength = ID_MAXLENGTH;	/* Limit length of ID */
+    else
+	uselength = length;
+
+    for(n=0 ; n < uselength ; n++)
+	sprintf(idstring + 2 * n, "%02x", SessionID[n]);
+    if (var_smtpd_tls_loglevel >= 3)
+	msg_info("Trying to reload Session from disc: %s", idstring);
+
+    session = NULL;
+
+    session_hex = dict_get(scache_db, idstring);
+    if (session_hex) {
+	hex_length = strlen(session_hex);
+	data = (unsigned char *)mymalloc(hex_length / 2);
+	if (!data) {
+	    msg_info("could not allocate memory for session reload");
+	    return(NULL);
+	}
+
+	memset(data, 0, hex_length / 2);
+	for (n = 0; n < hex_length; n++) {
+	    if ((session_hex[n] >= '0') && (session_hex[n] <= '9'))
+		nibble = session_hex[n] - '0';
+	    else
+		nibble = session_hex[n] - 'A' + 10;
+	    if (n % 2)
+		data[n / 2] |= nibble;
+	    else
+		data[n / 2] |= (nibble << 4);
+	}
+
+	/*
+	 * First check the version numbers, since wrong session data might
+	 * hit us hard (SEGFAULT). We also have to check for expiry.
+	 */
+	memcpy(&scache_info, data, sizeof(pfixtls_scache_info_t));
+	if ((scache_info.scache_db_version != scache_db_version) ||
+	    (scache_info.openssl_version != openssl_version) ||
+	    (scache_info.timestamp + var_smtpd_tls_scache_timeout < time(NULL)))
+	    dict_del(scache_db, idstring);
+	else {
+	    sess_data = data + sizeof(pfixtls_scache_info_t);
+	    session = d2i_SSL_SESSION(NULL, &sess_data,
+			      hex_length / 2 - sizeof(pfixtls_scache_info_t));
+	    if (!session)
+		pfixtls_print_errors();
+	}
+	myfree((char *)data);
+    }
+
+    if (session && (var_smtpd_tls_loglevel >= 3))
+	msg_info("Successfully reloaded session from disc");
+
+    return (session);
+}
+
+
+static SSL_SESSION *load_clnt_session(const char *hostname,
+				      int enforce_peername)
+{
+    SSL_SESSION *session = NULL;
+    char idstring[ID_MAXLENGTH + 1];
+    int n;
+    int uselength;
+    int length;
+    int hex_length;
+    const char *session_hex;
+    pfixtls_scache_info_t scache_info;
+    unsigned char nibble, *data, *sess_data;
+
+    length = strlen(hostname); 
+    if (length > ID_MAXLENGTH)
+	uselength = ID_MAXLENGTH;	/* Limit length of ID */
+    else
+	uselength = length;
+
+    for(n=0 ; n < uselength ; n++)
+	idstring[n] = tolower(hostname[n]);
+    idstring[uselength] = '\0';
+    if (var_smtp_tls_loglevel >= 3)
+	msg_info("Trying to reload Session from disc: %s", idstring);
+
+    session_hex = dict_get(scache_db, idstring);
+    if (session_hex) {
+	hex_length = strlen(session_hex);
+	data = (unsigned char *)mymalloc(hex_length / 2);
+	if (!data) {
+	    msg_info("could not allocate memory for session reload");
+	    return(NULL);
+	}
+
+	memset(data, 0, hex_length / 2);
+	for (n = 0; n < hex_length; n++) {
+	    if ((session_hex[n] >= '0') && (session_hex[n] <= '9'))
+		nibble = session_hex[n] - '0';
+	    else
+		nibble = session_hex[n] - 'A' + 10;
+	    if (n % 2)
+		data[n / 2] |= nibble;
+	    else
+		data[n / 2] |= (nibble << 4);
+	}
+
+	/*
+	 * First check the version numbers, since wrong session data might
+	 * hit us hard (SEGFAULT). We also have to check for expiry.
+	 * When we enforce_peername, we may find an old session, that was
+	 * saved when enforcement was not set. In this case the session will
+	 * be removed and a fresh session will be negotiated.
+	 */
+	memcpy(&scache_info, data, sizeof(pfixtls_scache_info_t));
+	if ((scache_info.scache_db_version != scache_db_version) ||
+	    (scache_info.openssl_version != openssl_version) ||
+	    (scache_info.timestamp + var_smtpd_tls_scache_timeout < time(NULL)))
+	    dict_del(scache_db, idstring);
+	else if (enforce_peername && (!scache_info.enforce_peername))
+	    dict_del(scache_db, idstring);
+	else {
+	    sess_data = data + sizeof(pfixtls_scache_info_t);
+	    session = d2i_SSL_SESSION(NULL, &sess_data,
+				      hex_length / 2 - sizeof(time_t));
+	    strncpy(SSL_SESSION_get_ex_data(session, TLSpeername_index),
+		    idstring, ID_MAXLENGTH + 1);
+	    if (!session)
+		pfixtls_print_errors();
+	}
+	myfree((char *)data);
+    }
+
+    if (session && (var_smtp_tls_loglevel >= 3))
+        msg_info("Successfully reloaded session from disc");
+
+    return (session);
+}
+
+
+static void create_client_lookup_id(char *idstring, char *hostname)
+{
+    int n, len, uselength;
+
+    len = strlen(hostname);
+    if (len > ID_MAXLENGTH)
+	uselength = ID_MAXLENGTH;	/* Limit length of ID */
+    else
+	uselength = len;
+
+    for (n = 0 ; n < uselength ; n++)
+	idstring[n] = tolower(hostname[n]);
+    idstring[uselength] = '\0';
+}
+
+
+static void create_server_lookup_id(char *idstring, SSL_SESSION *session)
+{
+    int n, uselength;
+
+    if (session->session_id_length > ID_MAXLENGTH)
+	uselength = ID_MAXLENGTH;	/* Limit length of ID */
+    else
+	uselength = session->session_id_length;
+
+    for(n = 0; n < uselength ; n++)
+	sprintf(idstring + 2 * n, "%02x", session->session_id[n]);
+}
+
+
+static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *session)
+{
+    char idstring[2 * ID_MAXLENGTH + 1];
+    char *hostname;
+
+    if (pfixtls_clientengine) {
+        hostname = SSL_SESSION_get_ex_data(session, TLSpeername_index);
+	create_client_lookup_id(idstring, hostname);
+	if (var_smtp_tls_loglevel >= 3)
+	    msg_info("Trying to remove session from disc: %s", idstring);
+    }
+    else {
+	create_server_lookup_id(idstring, session);
+	if (var_smtpd_tls_loglevel >= 3)
+	    msg_info("Trying to remove session from disc: %s", idstring);
+    }
+
+    if (scache_db)
+	dict_del(scache_db, idstring);
+}
+
+
+/*
+ * We need space to save the peername into the SSL_SESSION, as we must
+ * look up the external database for client sessions by peername, not
+ * by session id. We therefore allocate place for the peername string,
+ * when a new SSL_SESSION is generated. It is filled later.
+ */
+static int new_peername_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+			     int idx, long argl, void *argp)
+{
+    char *peername;
+
+    peername = (char *)mymalloc(ID_MAXLENGTH + 1);
+    if (!peername)
+	return 0;
+    peername[0] = '\0'; 	/* initialize */
+    return CRYPTO_set_ex_data(ad, idx, peername);
+}
+
+/*
+ * When the SSL_SESSION is removed again, we must free the memory to avoid
+ * leaks.
+ */
+static void free_peername_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+			       int idx, long argl, void *argp)
+{
+    myfree(CRYPTO_get_ex_data(ad, idx));
+}
+
+/*
+ * Duplicate application data, when a SSL_SESSION is duplicated
+ */
+static int dup_peername_func(CRYPTO_EX_DATA *to, CRYPTO_EX_DATA *from,
+			     void *from_d, int idx, long argl, void *argp)
+{
+    char *peername_old, *peername_new;
+
+    peername_old = CRYPTO_get_ex_data(from, idx);
+    peername_new = CRYPTO_get_ex_data(to, idx);
+    if (!peername_old || !peername_new)
+	return 0;
+    memcpy(peername_new, peername_old, ID_MAXLENGTH + 1);
+    return 1;
+}
+
+
+ /*
+  * Save a new session to the external cache
+  */
+static int new_session_cb(SSL *ssl, SSL_SESSION *session)
+{
+    char idstring[2 * ID_MAXLENGTH + 1];
+    int n;
+    int dsize;
+    int len;
+    unsigned char *data, *sess_data;
+    pfixtls_scache_info_t scache_info;
+    char *hexdata, *hostname;
+    TLScontext_t *TLScontext;
+
+    if (pfixtls_clientengine) {
+        TLScontext = SSL_get_ex_data(ssl, TLScontext_index);
+	hostname = TLScontext->peername_save;
+	create_client_lookup_id(idstring, hostname);
+	strncpy(SSL_SESSION_get_ex_data(session, TLSpeername_index),
+		hostname, ID_MAXLENGTH + 1);
+	/*
+	 * Remember, whether peername matching was enforced when the session
+	 * was created. If later enforce mode is enabled, we do not want to
+	 * reuse a session that was not sufficiently checked.
+	 */
+	scache_info.enforce_peername =
+		(TLScontext->enforce_verify_errors && TLScontext->enforce_CN);
+
+	if (var_smtp_tls_loglevel >= 3)
+	    msg_info("Trying to save session for hostID to disc: %s", idstring);
+
+#if (OPENSSL_VERSION_NUMBER < 0x00906011L) || (OPENSSL_VERSION_NUMBER == 0x00907000L)
+	    /*
+	     * Ugly Hack: OpenSSL before 0.9.6a does not store the verify
+	     * result in sessions for the client side.
+	     * We modify the session directly which is version specific,
+	     * but this bug is version specific, too.
+	     *
+	     * READ: 0-09-06-01-1 = 0-9-6-a-beta1: all versions before
+	     * beta1 have this bug, it has been fixed during development
+	     * of 0.9.6a. The development version of 0.9.7 can have this
+	     * bug, too. It has been fixed on 2000/11/29.
+	     */
+	    session->verify_result = SSL_get_verify_result(TLScontext->con);
+#endif
+
+    }
+    else {
+	create_server_lookup_id(idstring, session);
+	if (var_smtpd_tls_loglevel >= 3)
+	    msg_info("Trying to save Session to disc: %s", idstring);
+    }
+
+
+    /*
+     * Get the session and convert it into some "database" useable form.
+     * First, get the length of the session to allocate the memory.
+     */
+    dsize = i2d_SSL_SESSION(session, NULL);
+    if (dsize < 0) {
+	msg_info("Could not access session");
+	return 0;
+    }
+    data = (unsigned char *)mymalloc(dsize + sizeof(pfixtls_scache_info_t));
+    if (!data) {
+	msg_info("could not allocate memory for SSL session");
+	return 0;
+    }
+
+    /*
+     * OpenSSL is not robust against wrong session data (might SEGFAULT),
+     * so we secure it against version ids (session cache structure as well
+     * as OpenSSL version).
+     */
+    scache_info.scache_db_version = scache_db_version;
+    scache_info.openssl_version = openssl_version;
+
+    /*
+     * Put a timestamp, so that expiration can be checked without
+     * analyzing the session data itself. (We would need OpenSSL funtions,
+     * since the SSL_SESSION is a private structure.)
+     */
+    scache_info.timestamp = time(NULL);
+
+    memcpy(data, &scache_info, sizeof(pfixtls_scache_info_t));
+    sess_data = data + sizeof(pfixtls_scache_info_t);
+
+    /*
+     * Now, obtain the session. Unfortunately, it is binary and dict_update
+     * cannot handle binary data (it could contain '\0' in it) directly.
+     * To save memory we could use base64 encoding. To make handling easier,
+     * we simply use hex format.
+     */
+    len = i2d_SSL_SESSION(session, &sess_data);
+    len += sizeof(pfixtls_scache_info_t);
+
+    hexdata = (char *)mymalloc(2 * len + 1);
+
+    if (!hexdata) {
+	msg_info("could not allocate memory for SSL session (HEX)");
+	myfree((char *)data);
+	return 0;
+    }
+    for (n = 0; n < len; n++) {
+	hexdata[n * 2] = hexcodes[(data[n] & 0xf0) >> 4];
+	hexdata[(n * 2) + 1] = hexcodes[(data[n] & 0x0f)];
+    }
+    hexdata[len * 2] = '\0';
+
+    /*
+     * The session id is a hex string, all uppercase. We are using SDBM as
+     * compiled into Postfix with 8kB maximum entry size, so we set a limit
+     * when caching. If the session is not cached, we have to renegotiate,
+     * not more, not less. For a real session, this limit should never be
+     * met
+     */
+    if (strlen(idstring) + strlen(hexdata) < 8000)
+      dict_put(scache_db, idstring, hexdata);
+
+    myfree(hexdata);
+    myfree((char *)data);
+    return (1);
+}
+
+
+ /*
+  * pfixtls_exchange_seed: read bytes from the seed exchange-file (expect
+  * 1024 bytes)and immediately write back random bytes. Do so with EXCLUSIVE
+  * lock, so * that each process will find a completely different (and
+  * reseeded) file.
+  */
+static void pfixtls_exchange_seed(void)
+{
+    unsigned char buffer[1024];
+
+    if (rand_exch_fd == -1)
+	return;
+
+    if (myflock(rand_exch_fd, INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) != 0)
+        msg_info("Could not lock random exchange file: %s",
+                  strerror(errno));
+
+    lseek(rand_exch_fd, 0, SEEK_SET);
+    if (read(rand_exch_fd, buffer, 1024) < 0)
+        msg_fatal("reading exchange file failed");
+    RAND_seed(buffer, 1024);
+
+    RAND_bytes(buffer, 1024);
+    lseek(rand_exch_fd, 0, SEEK_SET);
+    if (write(rand_exch_fd, buffer, 1024) != 1024)
+        msg_fatal("Writing exchange file failed");
+
+    if (myflock(rand_exch_fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) != 0)
+        msg_fatal("Could not unlock random exchange file: %s",
+                  strerror(errno));
+}
+
+ /*
+  * This is the setup routine for the SSL server. As smtpd might be called
+  * more than once, we only want to do the initialization one time.
+  *
+  * The skeleton of this function is taken from OpenSSL apps/s_server.c.
+  */
+
+int     pfixtls_init_serverengine(int verifydepth, int askcert)
+{
+    int     off = 0;
+    int     verify_flags = SSL_VERIFY_NONE;
+    int     rand_bytes;
+    int     rand_source_dev_fd;
+    int     rand_source_socket_fd;
+    unsigned char buffer[255];
+    char   *CApath;
+    char   *CAfile;
+    char   *s_cert_file;
+    char   *s_key_file;
+    char   *s_dcert_file;
+    char   *s_dkey_file;
+    FILE   *paramfile;
+
+    if (pfixtls_serverengine)
+	return (0);				/* already running */
+
+    if (var_smtpd_tls_loglevel >= 2)
+	msg_info("starting TLS engine");
+
+    /*
+     * Initialize the OpenSSL library by the book!
+     * To start with, we must initialize the algorithms.
+     * We want cleartext error messages instead of just error codes, so we
+     * load the error_strings.
+     */
+    SSL_load_error_strings();
+    OpenSSL_add_ssl_algorithms();
+
+ /*
+  * Side effect, call a non-existing function to disable TLS usage with an
+  * outdated OpenSSL version. There is a security reason (verify_result
+  * is not stored with the session data).
+  */
+#if (OPENSSL_VERSION_NUMBER < 0x00905100L)
+    needs_openssl_095_or_later();
+#endif
+
+    /*
+     * Initialize the PRNG Pseudo Random Number Generator with some seed.
+     */
+    randseed.pid = getpid();
+    GETTIMEOFDAY(&randseed.tv);
+    RAND_seed(&randseed, sizeof(randseed_t));
+
+    /*
+     * Access the external sources for random seed. We will only query them
+     * once, this should be sufficient and we will stir our entropy by using
+     * the prng-exchange file anyway.
+     * For reliability, we don't consider failure to access the additional
+     * source fatal, as we can run happily without it (considering that we
+     * still have the exchange-file). We also don't care how much entropy
+     * we get back, as we must run anyway. We simply stir in the buffer
+     * regardless how many bytes are actually in it.
+     */
+    if (*var_tls_daemon_rand_source) {
+	if (!strncmp(var_tls_daemon_rand_source, "dev:", 4)) {
+	    /*
+	     * Source is a random device
+	     */
+	    rand_source_dev_fd = open(var_tls_daemon_rand_source + 4, 0, 0);
+	    if (rand_source_dev_fd == -1) 
+		msg_info("Could not open entropy device %s",
+			  var_tls_daemon_rand_source);
+	    else {
+		if (var_tls_daemon_rand_bytes > 255)
+		    var_tls_daemon_rand_bytes = 255;
+	        read(rand_source_dev_fd, buffer, var_tls_daemon_rand_bytes);
+		RAND_seed(buffer, var_tls_daemon_rand_bytes);
+		close(rand_source_dev_fd);
+	    }
+	} else if (!strncmp(var_tls_daemon_rand_source, "egd:", 4)) {
+	    /*
+	     * Source is a EGD compatible socket
+	     */
+	    rand_source_socket_fd = unix_connect(var_tls_daemon_rand_source +4,
+						 BLOCKING, 10);
+	    if (rand_source_socket_fd == -1)
+		msg_info("Could not connect to %s", var_tls_daemon_rand_source);
+	    else {
+		if (var_tls_daemon_rand_bytes > 255)
+		    var_tls_daemon_rand_bytes = 255;
+		buffer[0] = 1;
+		buffer[1] = var_tls_daemon_rand_bytes;
+		if (write(rand_source_socket_fd, buffer, 2) != 2)
+		    msg_info("Could not talk to %s",
+			     var_tls_daemon_rand_source);
+		else if (read(rand_source_socket_fd, buffer, 1) != 1)
+		    msg_info("Could not read info from %s",
+			     var_tls_daemon_rand_source);
+		else {
+		    rand_bytes = buffer[0];
+		    read(rand_source_socket_fd, buffer, rand_bytes);
+		    RAND_seed(buffer, rand_bytes);
+		}
+		close(rand_source_socket_fd);
+	    }
+	} else {
+	    RAND_load_file(var_tls_daemon_rand_source,
+			   var_tls_daemon_rand_bytes);
+	}
+    }
+
+    if (*var_tls_rand_exch_name) {
+	rand_exch_fd = open(var_tls_rand_exch_name, O_RDWR | O_CREAT, 0600);
+	if (rand_exch_fd != -1)
+	    pfixtls_exchange_seed();
+    }
+
+    randseed.pid = getpid();
+    GETTIMEOFDAY(&randseed.tv);
+    RAND_seed(&randseed, sizeof(randseed_t));
+
+    /*
+     * The SSL/TLS speficications require the client to send a message in
+     * the oldest specification it understands with the highest level it
+     * understands in the message.
+     * Netscape communicator can still communicate with SSLv2 servers, so it
+     * sends out a SSLv2 client hello. To deal with it, our server must be
+     * SSLv2 aware (even if we dont like SSLv2), so we need to have the
+     * SSLv23 server here. If we want to limit the protocol level, we can
+     * add an option to not use SSLv2/v3/TLSv1 later.
+     */
+    ctx = SSL_CTX_new(SSLv23_server_method());
+    if (ctx == NULL) {
+	pfixtls_print_errors();
+	return (-1);
+    };
+
+    /*
+     * Here we might set SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1.
+     * Of course, the last one would not make sense, since RFC2487 is only
+     * defined for TLS, but we also want to accept Netscape communicator
+     * requests, and it only supports SSLv3.
+     */
+    off |= SSL_OP_ALL;		/* Work around all known bugs */
+    SSL_CTX_set_options(ctx, off);
+
+    /*
+     * Set the info_callback, that will print out messages during
+     * communication on demand.
+     */
+    if (var_smtpd_tls_loglevel >= 2)
+	SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
+
+    /*
+     * Set the list of ciphers, if explicitely given; otherwise the
+     * (reasonable) default list is kept.
+     */
+    if (strlen(var_smtpd_tls_cipherlist) != 0)
+	if (SSL_CTX_set_cipher_list(ctx, var_smtpd_tls_cipherlist) == 0) {
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+
+    /*
+     * Now we must add the necessary certificate stuff: A server key, a
+     * server certificate, and the CA certificates for both the server
+     * cert and the verification of client certificates.
+     * As provided by OpenSSL we support two types of CA certificate handling:
+     * One possibility is to add all CA certificates to one large CAfile,
+     * the other possibility is a directory pointed to by CApath, containing
+     * seperate files for each CA pointed on by softlinks named by the hash
+     * values of the certificate.
+     * The first alternative has the advantage, that the file is opened and
+     * read at startup time, so that you dont have the hassle to maintain
+     * another copy of the CApath directory for chroot-jail. On the other
+     * hand, the file is not really readable.
+     */
+    if (strlen(var_smtpd_tls_CAfile) == 0)
+	CAfile = NULL;
+    else
+	CAfile = var_smtpd_tls_CAfile;
+    if (strlen(var_smtpd_tls_CApath) == 0)
+	CApath = NULL;
+    else
+	CApath = var_smtpd_tls_CApath;
+
+    if (CAfile || CApath) {
+	if (!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) {
+	    msg_info("TLS engine: cannot load CA data");
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+	if (!SSL_CTX_set_default_verify_paths(ctx)) {
+	    msg_info("TLS engine: cannot set verify paths");
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+    }
+
+    /*
+     * Now we load the certificate and key from the files and check,
+     * whether the cert matches the key (internally done by set_cert_stuff().
+     * We cannot run without (we do not support ADH anonymous Diffie-Hellman
+     * ciphers as of now).
+     * We can use RSA certificates ("cert") and DSA certificates ("dcert"),
+     * both can be made available at the same time. The CA certificates for
+     * both are handled in the same setup already finished.
+     * Which one is used depends on the cipher negotiated (that is: the first
+     * cipher listed by the client which does match the server). A client with
+     * RSA only (e.g. Netscape) will use the RSA certificate only.
+     * A client with openssl-library will use RSA first if not especially
+     * changed in the cipher setup.
+     */
+    if (strlen(var_smtpd_tls_cert_file) == 0)
+	s_cert_file = NULL;
+    else
+	s_cert_file = var_smtpd_tls_cert_file;
+    if (strlen(var_smtpd_tls_key_file) == 0)
+	s_key_file = NULL;
+    else
+	s_key_file = var_smtpd_tls_key_file;
+
+    if (strlen(var_smtpd_tls_dcert_file) == 0)
+	s_dcert_file = NULL;
+    else
+	s_dcert_file = var_smtpd_tls_dcert_file;
+    if (strlen(var_smtpd_tls_dkey_file) == 0)
+	s_dkey_file = NULL;
+    else
+	s_dkey_file = var_smtpd_tls_dkey_file;
+
+    if (s_cert_file) {
+	if (!set_cert_stuff(ctx, s_cert_file, s_key_file)) {
+	    msg_info("TLS engine: cannot load RSA cert/key data");
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+    }
+    if (s_dcert_file) {
+	if (!set_cert_stuff(ctx, s_dcert_file, s_dkey_file)) {
+	    msg_info("TLS engine: cannot load DSA cert/key data");
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+    }
+    if (!s_cert_file && !s_dcert_file) {
+	msg_info("TLS engine: do need at least RSA _or_ DSA cert/key data");
+	return (-1);
+    }
+
+    /*
+     * Sometimes a temporary RSA key might be needed by the OpenSSL
+     * library. The OpenSSL doc indicates, that this might happen when
+     * export ciphers are in use. We have to provide one, so well, we
+     * just do it.
+     */
+    SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb);
+
+    /*
+     * We might also need dh parameters, which can either be loaded from
+     * file (preferred) or we simply take the compiled in values.
+     * First, set the callback that will select the values when requested,
+     * then load the (possibly) available DH parameters from files.
+     * We are generous with the error handling, since we do have default
+     * values compiled in, so we will not abort but just log the error message.
+     */
+    SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_cb);
+    if (strlen(var_smtpd_tls_dh1024_param_file) != 0) {
+	if ((paramfile = fopen(var_smtpd_tls_dh1024_param_file, "r")) != NULL) {
+	    dh_1024 = PEM_read_DHparams(paramfile, NULL, NULL, NULL);
+	    if (dh_1024 == NULL) {
+		msg_info("TLS engine: cannot load 1024bit DH parameters");
+		pfixtls_print_errors();
+	    }
+	}
+	else {
+	    msg_info("TLS engine: cannot load 1024bit DH parameters: %s: %s",
+		     var_smtpd_tls_dh1024_param_file, strerror(errno));
+	}
+    }
+    if (strlen(var_smtpd_tls_dh512_param_file) != 0) {
+	if ((paramfile = fopen(var_smtpd_tls_dh512_param_file, "r")) != NULL) {
+	    dh_512 = PEM_read_DHparams(paramfile, NULL, NULL, NULL);
+	    if (dh_512 == NULL) {
+		msg_info("TLS engine: cannot load 512bit DH parameters");
+		pfixtls_print_errors();
+	    }
+	}
+	else {
+	    msg_info("TLS engine: cannot load 512bit DH parameters: %s: %s",
+		     var_smtpd_tls_dh512_param_file, strerror(errno));
+	}
+    }
+
+    /*
+     * If we want to check client certificates, we have to indicate it
+     * in advance. By now we only allow to decide on a global basis.
+     * If we want to allow certificate based relaying, we must ask the
+     * client to provide one with SSL_VERIFY_PEER. The client now can
+     * decide, whether it provides one or not. We can enforce a failure
+     * of the negotiation with SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we
+     * do not allow a connection without one.
+     * In the "server hello" following the initialization by the "client hello"
+     * the server must provide a list of CAs it is willing to accept.
+     * Some clever clients will then select one from the list of available
+     * certificates matching these CAs. Netscape Communicator will present
+     * the list of certificates for selecting the one to be sent, or it will
+     * issue a warning, if there is no certificate matching the available
+     * CAs.
+     *
+     * With regard to the purpose of the certificate for relaying, we might
+     * like a later negotiation, maybe relaying would already be allowed
+     * for other reasons, but this would involve severe changes in the
+     * internal postfix logic, so we have to live with it the way it is.
+     */
+    if (askcert)
+	verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
+    SSL_CTX_set_verify(ctx, verify_flags, verify_callback);
+    SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
+
+    /*
+     * Initialize the session cache. We only want external caching to
+     * synchronize between server sessions, so we set it to a minimum value
+     * of 1. If the external cache is disabled, we wont cache at all.
+     * The recall of old sessions "get" and save to disk of just created
+     * sessions "new" is handled by the appropriate callback functions.
+     *
+     * We must not forget to set a session id context to identify to which
+     * kind of server process the session was related. In our case, the
+     * context is just the name of the patchkit: "Postfix/TLS".
+     */
+    SSL_CTX_sess_set_cache_size(ctx, 1);
+    SSL_CTX_set_timeout(ctx, var_smtpd_tls_scache_timeout);
+    SSL_CTX_set_session_id_context(ctx, (void*)&server_session_id_context,
+                sizeof(server_session_id_context));
+
+    /*
+     * The session cache is realized by an external database file, that
+     * must be opened before going to chroot jail. Since the session cache
+     * data can become quite large, "[n]dbm" cannot be used as it has a
+     * size limit that is by far to small.
+     */
+    if (*var_smtpd_tls_scache_db) {
+	/*
+	 * Insert a test against other dbms here, otherwise while writing
+	 * a session (content to large), we will receive a fatal error!
+	 */
+	if (strncmp(var_smtpd_tls_scache_db, "sdbm:", 5))
+	    msg_warn("Only sdbm: type allowed for %s",
+		     var_smtpd_tls_scache_db);
+	else
+	    scache_db = dict_open(var_smtpd_tls_scache_db, O_RDWR,
+	      DICT_FLAG_DUP_REPLACE | DICT_FLAG_LOCK | DICT_FLAG_SYNC_UPDATE);
+	if (scache_db) {
+	    SSL_CTX_set_session_cache_mode(ctx,
+			SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_AUTO_CLEAR);
+	    SSL_CTX_sess_set_get_cb(ctx, get_session_cb);
+	    SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
+	    SSL_CTX_sess_set_remove_cb(ctx, remove_session_cb);
+	}
+	else
+	    msg_warn("Could not open session cache %s",
+		     var_smtpd_tls_scache_db);
+    }
+
+    /*
+     * Finally create the global index to access TLScontext information
+     * inside verify_callback.
+     */
+    TLScontext_index = SSL_get_ex_new_index(0, "TLScontext ex_data index",
+					    NULL, NULL, NULL);
+
+    pfixtls_serverengine = 1;
+    return (0);
+}
+
+ /*
+  * This is the actual startup routine for the connection. We expect
+  * that the buffers are flushed and the "220 Ready to start TLS" was
+  * send to the client, so that we can immediately can start the TLS
+  * handshake process.
+  */
+int     pfixtls_start_servertls(VSTREAM *stream, int timeout,
+				const char *peername, const char *peeraddr,
+				tls_info_t *tls_info, int requirecert)
+{
+    int     sts;
+    int     j;
+    int verify_flags;
+    unsigned int n;
+    TLScontext_t *TLScontext;
+    SSL_SESSION *session;
+    SSL_CIPHER *cipher;
+    X509   *peer;
+
+    if (!pfixtls_serverengine) {		/* should never happen */
+	msg_info("tls_engine not running");
+	return (-1);
+    }
+    if (var_smtpd_tls_loglevel >= 1)
+	msg_info("setting up TLS connection from %s[%s]", peername, peeraddr);
+
+    /*
+     * Allocate a new TLScontext for the new connection and get an SSL
+     * structure. Add the location of TLScontext to the SSL to later
+     * retrieve the information inside the verify_callback().
+     */
+    TLScontext = (TLScontext_t *)mymalloc(sizeof(TLScontext_t));
+    if (!TLScontext) {
+	msg_fatal("Could not allocate 'TLScontext' with mymalloc");
+    }
+    if ((TLScontext->con = (SSL *) SSL_new(ctx)) == NULL) {
+	msg_info("Could not allocate 'TLScontext->con' with SSL_new()");
+	pfixtls_print_errors();
+	myfree((char *)TLScontext);
+	return (-1);
+    }
+    if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
+	msg_info("Could not set application data for 'TLScontext->con'");
+	pfixtls_print_errors();
+	SSL_free(TLScontext->con);
+	myfree((char *)TLScontext);
+	return (-1);
+    }
+
+    /*
+     * Set the verification parameters to be checked in verify_callback().
+     */
+    if (requirecert) {
+	verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
+	verify_flags |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
+	TLScontext->enforce_verify_errors = 1;
+        SSL_set_verify(TLScontext->con, verify_flags, verify_callback);
+    }
+    else {
+	TLScontext->enforce_verify_errors = 0;
+    }
+    TLScontext->enforce_CN = 0;
+
+    /*
+     * The TLS connection is realized by a BIO_pair, so obtain the pair.
+     */
+    if (!BIO_new_bio_pair(&TLScontext->internal_bio, BIO_bufsiz,
+			  &TLScontext->network_bio, BIO_bufsiz)) {
+	msg_info("Could not obtain BIO_pair");
+	pfixtls_print_errors();
+	SSL_free(TLScontext->con);
+	myfree((char *)TLScontext);
+	return (-1);
+    }
+
+    /*
+     * Before really starting anything, try to seed the PRNG a little bit
+     * more.
+     */
+    pfixtls_stir_seed();
+    pfixtls_exchange_seed();
+
+    /*
+     * Initialize the SSL connection to accept state. This should not be
+     * necessary anymore since 0.9.3, but the call is still in the library
+     * and maintaining compatibility never hurts.
+     */
+    SSL_set_accept_state(TLScontext->con);
+
+    /*
+     * Connect the SSL-connection with the postfix side of the BIO-pair for
+     * reading and writing.
+     */
+     SSL_set_bio(TLScontext->con, TLScontext->internal_bio,
+		 TLScontext->internal_bio);
+
+    /*
+     * If the debug level selected is high enough, all of the data is
+     * dumped: 3 will dump the SSL negotiation, 4 will dump everything.
+     *
+     * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
+     * Well there is a BIO below the SSL routines that is automatically
+     * created for us, so we can use it for debugging purposes.
+     */
+    if (var_smtpd_tls_loglevel >= 3)
+	BIO_set_callback(SSL_get_rbio(TLScontext->con), bio_dump_cb);
+
+
+    /* Dump the negotiation for loglevels 3 and 4 */
+    if (var_smtpd_tls_loglevel >= 3)
+	do_dump = 1;
+
+    /*
+     * Now we expect the negotiation to begin. This whole process is like a
+     * black box for us. We totally have to rely on the routines build into
+     * the OpenSSL library. The only thing we can do we already have done
+     * by choosing our own callbacks for session caching and certificate
+     * verification.
+     *
+     * Error handling:
+     * If the SSL handhake fails, we print out an error message and remove
+     * everything that might be there. A session has to be removed anyway,
+     * because RFC2246 requires it.
+     */
+    sts = do_tls_operation(vstream_fileno(stream), timeout, TLScontext,
+			   SSL_accept, NULL, NULL, NULL, 0);
+    if (sts <= 0) {
+	msg_info("SSL_accept error from %s[%s]: %d", peername, peeraddr, sts);
+	pfixtls_print_errors();
+	SSL_free(TLScontext->con);
+	myfree((char *)TLScontext);
+	return (-1);
+    }
+
+    /* Only loglevel==4 dumps everything */
+    if (var_smtpd_tls_loglevel < 4)
+	do_dump = 0;
+
+    /*
+     * Lets see, whether a peer certificate is available and what is
+     * the actual information. We want to save it for later use.
+     */
+    peer = SSL_get_peer_certificate(TLScontext->con);
+    if (peer != NULL) {
+	if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
+	    tls_info->peer_verified = 1;
+
+	X509_NAME_oneline(X509_get_subject_name(peer),
+			  TLScontext->peer_subject, CCERT_BUFSIZ);
+	if (var_smtpd_tls_loglevel >= 2)
+	    msg_info("subject=%s", TLScontext->peer_subject);
+	tls_info->peer_subject = TLScontext->peer_subject;
+	X509_NAME_oneline(X509_get_issuer_name(peer),
+			  TLScontext->peer_issuer, CCERT_BUFSIZ);
+	if (var_smtpd_tls_loglevel >= 2)
+	    msg_info("issuer=%s", TLScontext->peer_issuer);
+	tls_info->peer_issuer = TLScontext->peer_issuer;
+	if (X509_digest(peer, EVP_md5(), TLScontext->md, &n)) {
+	    for (j = 0; j < (int) n; j++) {
+		TLScontext->fingerprint[j * 3] =
+			hexcodes[(TLScontext->md[j] & 0xf0) >> 4];
+		TLScontext->fingerprint[(j * 3) + 1] =
+			hexcodes[(TLScontext->md[j] & 0x0f)];
+		if (j + 1 != (int) n)
+		    TLScontext->fingerprint[(j * 3) + 2] = ':';
+		else
+		    TLScontext->fingerprint[(j * 3) + 2] = '\0';
+	    }
+	    if (var_smtpd_tls_loglevel >= 1)
+		msg_info("fingerprint=%s", TLScontext->fingerprint);
+	    tls_info->peer_fingerprint = TLScontext->fingerprint;
+	}
+
+	TLScontext->peer_CN[0] = '\0';
+	if (!X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
+			NID_commonName, TLScontext->peer_CN, CCERT_BUFSIZ)) {
+	    msg_info("Could not parse client's subject CN");
+	    pfixtls_print_errors();
+	}
+	tls_info->peer_CN = TLScontext->peer_CN;
+
+	TLScontext->issuer_CN[0] = '\0';
+	if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer),
+			NID_commonName, TLScontext->issuer_CN, CCERT_BUFSIZ)) {
+	    msg_info("Could not parse client's issuer CN");
+	    pfixtls_print_errors();
+	}
+	if (!TLScontext->issuer_CN[0]) {
+	    /* No issuer CN field, use Organization instead */
+	    if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer),
+		NID_organizationName, TLScontext->issuer_CN, CCERT_BUFSIZ)) {
+		msg_info("Could not parse client's issuer Organization");
+		pfixtls_print_errors();
+	    }
+	}
+	tls_info->issuer_CN = TLScontext->issuer_CN;
+
+	if (var_smtpd_tls_loglevel >= 1) {
+	    if (tls_info->peer_verified)
+		msg_info("Verified: subject_CN=%s, issuer=%s",
+			 TLScontext->peer_CN, TLScontext->issuer_CN);
+	    else
+		msg_info("Unverified: subject_CN=%s, issuer=%s",
+			 TLScontext->peer_CN, TLScontext->issuer_CN);
+	}
+
+	X509_free(peer);
+    }
+
+    /*
+     * At this point we should have a certificate when required.
+     * We may however have a cached session, so the callback would never
+     * be called. We therefore double-check to make sure and remove the
+     * session, if applicable.
+     */
+    if (requirecert) {
+	if (!tls_info->peer_verified || !tls_info->peer_CN) {
+	    msg_info("Re-used session without peer certificate removed");
+	    session = SSL_get_session(TLScontext->con);
+	    SSL_CTX_remove_session(ctx, session);
+	    return (-1);
+	}
+    }
+
+    /*
+     * Finally, collect information about protocol and cipher for logging
+     */
+    tls_info->protocol = SSL_get_version(TLScontext->con);
+    cipher = SSL_get_current_cipher(TLScontext->con);
+    tls_info->cipher_name = SSL_CIPHER_get_name(cipher);
+    tls_info->cipher_usebits = SSL_CIPHER_get_bits(cipher,
+						 &(tls_info->cipher_algbits));
+
+    pfixtls_serveractive = 1;
+
+    /*
+     * The TLS engine is active, switch to the pfixtls_timed_read/write()
+     * functions and store the context.
+     */
+    vstream_control(stream,
+		    VSTREAM_CTL_READ_FN, pfixtls_timed_read,
+		    VSTREAM_CTL_WRITE_FN, pfixtls_timed_write,
+		    VSTREAM_CTL_CONTEXT, (void *)TLScontext,
+		    VSTREAM_CTL_END);
+
+    msg_info("TLS connection established from %s[%s]: %s with cipher %s (%d/%d bits)",
+	     peername, peeraddr,
+	     tls_info->protocol, tls_info->cipher_name,
+	     tls_info->cipher_usebits, tls_info->cipher_algbits);
+    pfixtls_stir_seed();
+
+    return (0);
+}
+
+ /*
+  * Shut down the TLS connection, that does mean: remove all the information
+  * and reset the flags! This is needed if the actual running smtpd is to
+  * be restarted. We do not give back any value, as there is nothing to
+  * be reported.
+  * Since our session cache is external, we will remove the session from
+  * memory in any case. The SSL_CTX_flush_sessions might be redundant here,
+  * I however want to make sure nothing is left.
+  * RFC2246 requires us to remove sessions if something went wrong, as
+  * indicated by the "failure" value, so we remove it from the external
+  * cache, too. 
+  */
+int     pfixtls_stop_servertls(VSTREAM *stream, int timeout, int failure,
+			       tls_info_t *tls_info)
+{
+    TLScontext_t *TLScontext;
+    int retval;
+
+    if (pfixtls_serveractive) {
+	TLScontext = (TLScontext_t *)vstream_context(stream);
+	/*
+	 * Perform SSL_shutdown() twice, as the first attempt may return
+	 * to early: it will only send out the shutdown alert but it will
+	 * not wait for the peer's shutdown alert. Therefore, when we are
+	 * the first party to send the alert, we must call SSL_shutdown()
+	 * again.
+	 * On failure we don't want to resume the session, so we will not
+	 * perform SSL_shutdown() and the session will be removed as being
+	 * bad.
+	 */
+	if (!failure) {
+            retval = do_tls_operation(vstream_fileno(stream), timeout,
+				TLScontext, SSL_shutdown, NULL, NULL, NULL, 0);
+	    if (retval == 0)
+		do_tls_operation(vstream_fileno(stream), timeout, TLScontext,
+				SSL_shutdown, NULL, NULL, NULL, 0);
+	}
+	/*
+	 * Free the SSL structure and the BIOs. Warning: the internal_bio is
+	 * connected to the SSL structure and is automatically freed with
+	 * it. Do not free it again (core dump)!!
+	 * Only free the network_bio.
+	 */
+	SSL_free(TLScontext->con);
+	BIO_free(TLScontext->network_bio);
+	myfree((char *)TLScontext);
+        vstream_control(stream,
+		    VSTREAM_CTL_READ_FN, (VSTREAM_FN) NULL,
+		    VSTREAM_CTL_WRITE_FN, (VSTREAM_FN) NULL,
+		    VSTREAM_CTL_CONTEXT, (void *) NULL,
+		    VSTREAM_CTL_END);
+	SSL_CTX_flush_sessions(ctx, time(NULL));
+
+	pfixtls_stir_seed();
+	pfixtls_exchange_seed();
+
+	*tls_info = tls_info_zero;
+	pfixtls_serveractive = 0;
+
+    }
+
+    return (0);
+}
+
+
+ /*
+  * This is the setup routine for the SSL client. As smtpd might be called
+  * more than once, we only want to do the initialization one time.
+  *
+  * The skeleton of this function is taken from OpenSSL apps/s_client.c.
+  */
+
+int     pfixtls_init_clientengine(int verifydepth)
+{
+    int     off = 0;
+    int     verify_flags = SSL_VERIFY_NONE;
+    int     rand_bytes;
+    int     rand_source_dev_fd;
+    int     rand_source_socket_fd;
+    unsigned char buffer[255];
+    char   *CApath;
+    char   *CAfile;
+    char   *c_cert_file;
+    char   *c_key_file;
+
+
+    if (pfixtls_clientengine)
+	return (0);				/* already running */
+
+    if (var_smtp_tls_loglevel >= 2)
+	msg_info("starting TLS engine");
+
+    /*
+     * Initialize the OpenSSL library by the book!
+     * To start with, we must initialize the algorithms.
+     * We want cleartext error messages instead of just error codes, so we
+     * load the error_strings.
+     */ 
+    SSL_load_error_strings();
+    OpenSSL_add_ssl_algorithms();
+
+ /*
+  * Side effect, call a non-existing function to disable TLS usage with an
+  * outdated OpenSSL version. There is a security reason (verify_result
+  * is not stored with the session data).
+  */
+#if (OPENSSL_VERSION_NUMBER < 0x00905100L)
+    needs_openssl_095_or_later();
+#endif
+
+    /*
+     * Initialize the PRNG Pseudo Random Number Generator with some seed.
+     */
+    randseed.pid = getpid();
+    GETTIMEOFDAY(&randseed.tv);
+    RAND_seed(&randseed, sizeof(randseed_t));
+
+    /*
+     * Access the external sources for random seed. We will only query them
+     * once, this should be sufficient and we will stir our entropy by using
+     * the prng-exchange file anyway.
+     * For reliability, we don't consider failure to access the additional
+     * source fatal, as we can run happily without it (considering that we
+     * still have the exchange-file). We also don't care how much entropy
+     * we get back, as we must run anyway. We simply stir in the buffer
+     * regardless how many bytes are actually in it.
+     */
+    if (*var_tls_daemon_rand_source) {
+	if (!strncmp(var_tls_daemon_rand_source, "dev:", 4)) {
+	    /*
+	     * Source is a random device
+	     */
+	    rand_source_dev_fd = open(var_tls_daemon_rand_source + 4, 0, 0);
+	    if (rand_source_dev_fd == -1) 
+		msg_info("Could not open entropy device %s",
+			  var_tls_daemon_rand_source);
+	    else {
+		if (var_tls_daemon_rand_bytes > 255)
+		    var_tls_daemon_rand_bytes = 255;
+	        read(rand_source_dev_fd, buffer, var_tls_daemon_rand_bytes);
+		RAND_seed(buffer, var_tls_daemon_rand_bytes);
+		close(rand_source_dev_fd);
+	    }
+	} else if (!strncmp(var_tls_daemon_rand_source, "egd:", 4)) {
+	    /*
+	     * Source is a EGD compatible socket
+	     */
+	    rand_source_socket_fd = unix_connect(var_tls_daemon_rand_source +4,
+						 BLOCKING, 10);
+	    if (rand_source_socket_fd == -1)
+		msg_info("Could not connect to %s", var_tls_daemon_rand_source);
+	    else {
+		if (var_tls_daemon_rand_bytes > 255)
+		    var_tls_daemon_rand_bytes = 255;
+		buffer[0] = 1;
+		buffer[1] = var_tls_daemon_rand_bytes;
+		if (write(rand_source_socket_fd, buffer, 2) != 2)
+		    msg_info("Could not talk to %s",
+			     var_tls_daemon_rand_source);
+		else if (read(rand_source_socket_fd, buffer, 1) != 1)
+		    msg_info("Could not read info from %s",
+			     var_tls_daemon_rand_source);
+		else {
+		    rand_bytes = buffer[0];
+		    read(rand_source_socket_fd, buffer, rand_bytes);
+		    RAND_seed(buffer, rand_bytes);
+		}
+		close(rand_source_socket_fd);
+	    }
+	} else {
+	    RAND_load_file(var_tls_daemon_rand_source,
+			   var_tls_daemon_rand_bytes);
+	}
+    }
+
+    if (*var_tls_rand_exch_name) {
+	rand_exch_fd = open(var_tls_rand_exch_name, O_RDWR | O_CREAT, 0600);
+	if (rand_exch_fd != -1)
+	    pfixtls_exchange_seed();
+    }
+
+    randseed.pid = getpid();
+    GETTIMEOFDAY(&randseed.tv);
+    RAND_seed(&randseed, sizeof(randseed_t));
+
+    /*
+     * The SSL/TLS speficications require the client to send a message in
+     * the oldest specification it understands with the highest level it
+     * understands in the message.
+     * RFC2487 is only specified for TLSv1, but we want to be as compatible
+     * as possible, so we will start off with a SSLv2 greeting allowing
+     * the best we can offer: TLSv1.
+     * We can restrict this with the options setting later, anyhow.
+     */
+    ctx = SSL_CTX_new(SSLv23_client_method());
+    if (ctx == NULL) {
+	pfixtls_print_errors();
+	return (-1);
+    };
+
+    /*
+     * Here we might set SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1.
+     * Of course, the last one would not make sense, since RFC2487 is only
+     * defined for TLS, but we dont know what is out there. So leave things
+     * completely open, as of today.
+     */
+    off |= SSL_OP_ALL;		/* Work around all known bugs */
+    SSL_CTX_set_options(ctx, off);
+
+    /*
+     * Set the info_callback, that will print out messages during
+     * communication on demand.
+     */
+    if (var_smtp_tls_loglevel >= 2)
+	SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
+
+    /*
+     * Set the list of ciphers, if explicitely given; otherwise the
+     * (reasonable) default list is kept.
+     */
+    if (strlen(var_smtp_tls_cipherlist) != 0)
+	if (SSL_CTX_set_cipher_list(ctx, var_smtp_tls_cipherlist) == 0) {
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+
+    /*
+     * Now we must add the necessary certificate stuff: A client key, a
+     * client certificate, and the CA certificates for both the client
+     * cert and the verification of server certificates.
+     * In fact, we do not need a client certificate,  so the certificates
+     * are only loaded (and checked), if supplied. A clever client would
+     * handle multiple client certificates and decide based on the list
+     * of acceptable CAs, sent by the server, which certificate to submit.
+     * OpenSSL does however not do this and also has no callback hoods to
+     * easily realize it.
+     *
+     * As provided by OpenSSL we support two types of CA certificate handling:
+     * One possibility is to add all CA certificates to one large CAfile,
+     * the other possibility is a directory pointed to by CApath, containing
+     * seperate files for each CA pointed on by softlinks named by the hash
+     * values of the certificate.
+     * The first alternative has the advantage, that the file is opened and
+     * read at startup time, so that you dont have the hassle to maintain
+     * another copy of the CApath directory for chroot-jail. On the other
+     * hand, the file is not really readable.
+     */ 
+    if (strlen(var_smtp_tls_CAfile) == 0)
+	CAfile = NULL;
+    else
+	CAfile = var_smtp_tls_CAfile;
+    if (strlen(var_smtp_tls_CApath) == 0)
+	CApath = NULL;
+    else
+	CApath = var_smtp_tls_CApath;
+    if (CAfile || CApath) {
+	if (!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) {
+	    msg_info("TLS engine: cannot load CA data");
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+	if (!SSL_CTX_set_default_verify_paths(ctx)) {
+	    msg_info("TLS engine: cannot set verify paths");
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+    }
+
+    if (strlen(var_smtp_tls_cert_file) == 0)
+	c_cert_file = NULL;
+    else
+	c_cert_file = var_smtp_tls_cert_file;
+    if (strlen(var_smtp_tls_key_file) == 0)
+	c_key_file = NULL;
+    else
+	c_key_file = var_smtp_tls_key_file;
+    if (c_cert_file || c_key_file)
+	if (!set_cert_stuff(ctx, c_cert_file, c_key_file)) {
+	    msg_info("TLS engine: cannot load cert/key data");
+	    pfixtls_print_errors();
+	    return (-1);
+	}
+
+    /*
+     * Sometimes a temporary RSA key might be needed by the OpenSSL
+     * library. The OpenSSL doc indicates, that this might happen when
+     * export ciphers are in use. We have to provide one, so well, we
+     * just do it.
+     */
+    SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb);
+
+    /*
+     * Finally, the setup for the server certificate checking, done
+     * "by the book".
+     */
+    SSL_CTX_set_verify(ctx, verify_flags, verify_callback);
+
+    /*
+     * Initialize the session cache. We only want external caching to
+     * synchronize between server sessions, so we set it to a minimum value
+     * of 1. If the external cache is disabled, we wont cache at all.
+     *
+     * In case of the client, there is no callback used in OpenSSL, so
+     * we must call the session cache functions manually during the process.
+     */
+    SSL_CTX_sess_set_cache_size(ctx, 1);
+    SSL_CTX_set_timeout(ctx, var_smtp_tls_scache_timeout);
+
+    /*
+     * The session cache is realized by an external database file, that
+     * must be opened before going to chroot jail. Since the session cache
+     * data can become quite large, "[n]dbm" cannot be used as it has a
+     * size limit that is by far to small.
+     */
+    if (*var_smtp_tls_scache_db) {
+	/*
+	 * Insert a test against other dbms here, otherwise while writing
+	 * a session (content to large), we will receive a fatal error!
+	 */
+	if (strncmp(var_smtp_tls_scache_db, "sdbm:", 5))
+	    msg_warn("Only sdbm: type allowed for %s",
+		     var_smtp_tls_scache_db);
+	else
+	    scache_db = dict_open(var_smtp_tls_scache_db, O_RDWR,
+	      DICT_FLAG_DUP_REPLACE | DICT_FLAG_LOCK | DICT_FLAG_SYNC_UPDATE);
+	if (!scache_db)
+	    msg_warn("Could not open session cache %s",
+		     var_smtp_tls_scache_db);
+	/*
+	 * It is practical to have OpenSSL automatically save newly created
+	 * sessions for us by callback. Therefore we have to enable the
+	 * internal session cache for the client side. Disable automatic
+	 * clearing, as smtp has limited lifetime anyway and we can call
+	 * the cleanup routine at will.
+	 */
+	SSL_CTX_set_session_cache_mode(ctx,
+			SSL_SESS_CACHE_CLIENT|SSL_SESS_CACHE_NO_AUTO_CLEAR);
+	SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
+    }
+   
+    /*
+     * Finally create the global index to access TLScontext information
+     * inside verify_callback.
+     */
+    TLScontext_index = SSL_get_ex_new_index(0, "TLScontext ex_data index",
+					    NULL, NULL, NULL);
+    TLSpeername_index = SSL_SESSION_get_ex_new_index(0,
+					    "TLSpeername ex_data index",
+					    new_peername_func,
+					    dup_peername_func,
+					    free_peername_func);
+
+    pfixtls_clientengine = 1;
+    return (0);
+}
+
+ /*
+  * This is the actual startup routine for the connection. We expect
+  * that the buffers are flushed and the "220 Ready to start TLS" was
+  * received by us, so that we can immediately can start the TLS
+  * handshake process.
+  */
+int     pfixtls_start_clienttls(VSTREAM *stream, int timeout,
+			        int enforce_peername,
+				const char *peername,
+				tls_info_t *tls_info)
+{
+    int     sts;
+    SSL_SESSION *session, *old_session;
+    SSL_CIPHER *cipher;
+    X509   *peer;
+    int     verify_flags;
+    TLScontext_t *TLScontext;
+
+    if (!pfixtls_clientengine) {		/* should never happen */
+	msg_info("tls_engine not running");
+	return (-1);
+    }
+    if (var_smtpd_tls_loglevel >= 1)
+	msg_info("setting up TLS connection to %s", peername);
+
+    /*
+     * Allocate a new TLScontext for the new connection and get an SSL
+     * structure. Add the location of TLScontext to the SSL to later
+     * retrieve the information inside the verify_callback().
+     */
+    TLScontext = (TLScontext_t *)mymalloc(sizeof(TLScontext_t));
+    if (!TLScontext) {
+	msg_fatal("Could not allocate 'TLScontext' with mymalloc");
+    }
+    if ((TLScontext->con = (SSL *) SSL_new(ctx)) == NULL) {
+	msg_info("Could not allocate 'TLScontext->con' with SSL_new()");
+	pfixtls_print_errors();
+	myfree((char *)TLScontext);
+	return (-1);
+    }
+    if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
+	msg_info("Could not set application data for 'TLScontext->con'");
+	pfixtls_print_errors();
+	SSL_free(TLScontext->con);
+	myfree((char *)TLScontext);
+	return (-1);
+    }
+
+    /*
+     * Set the verification parameters to be checked in verify_callback().
+     */
+    if (enforce_peername) {
+	verify_flags = SSL_VERIFY_PEER;
+	TLScontext->enforce_verify_errors = 1;
+	TLScontext->enforce_CN = 1;
+        SSL_set_verify(TLScontext->con, verify_flags, verify_callback);
+    }
+    else {
+	TLScontext->enforce_verify_errors = 0;
+	TLScontext->enforce_CN = 0;
+    }
+
+    /*
+     * The TLS connection is realized by a BIO_pair, so obtain the pair.
+     */
+    if (!BIO_new_bio_pair(&TLScontext->internal_bio, BIO_bufsiz,
+			  &TLScontext->network_bio, BIO_bufsiz)) {
+	msg_info("Could not obtain BIO_pair");
+	pfixtls_print_errors();
+	SSL_free(TLScontext->con);
+	myfree((char *)TLScontext);
+	return (-1);
+    }
+
+    old_session = NULL;
+
+    /*
+     * Find out the hashed HostID for the client cache and try to
+     * load the session from the cache.
+     */
+    strncpy(TLScontext->peername_save, peername, ID_MAXLENGTH + 1);
+    TLScontext->peername_save[ID_MAXLENGTH] = '\0';  /* just in case */
+    (void)lowercase(TLScontext->peername_save);
+    if (scache_db) {
+	old_session = load_clnt_session(peername, enforce_peername);
+	if (old_session) {
+	   SSL_set_session(TLScontext->con, old_session);
+#if (OPENSSL_VERSION_NUMBER < 0x00906011L) || (OPENSSL_VERSION_NUMBER == 0x00907000L)
+	    /*
+	     * Ugly Hack: OpenSSL before 0.9.6a does not store the verify
+	     * result in sessions for the client side.
+	     * We modify the session directly which is version specific,
+	     * but this bug is version specific, too.
+	     *
+	     * READ: 0-09-06-01-1 = 0-9-6-a-beta1: all versions before
+	     * beta1 have this bug, it has been fixed during development
+	     * of 0.9.6a. The development version of 0.9.7 can have this
+	     * bug, too. It has been fixed on 2000/11/29.
+	     */
+	    SSL_set_verify_result(TLScontext->con, old_session->verify_result);
+#endif
+	   
+	}
+    }
+
+    /*
+     * Before really starting anything, try to seed the PRNG a little bit
+     * more.
+     */
+    pfixtls_stir_seed();
+    pfixtls_exchange_seed();
+
+    /*
+     * Initialize the SSL connection to connect state. This should not be
+     * necessary anymore since 0.9.3, but the call is still in the library
+     * and maintaining compatibility never hurts.
+     */
+    SSL_set_connect_state(TLScontext->con);
+
+    /*
+     * Connect the SSL-connection with the postfix side of the BIO-pair for
+     * reading and writing.
+     */
+    SSL_set_bio(TLScontext->con, TLScontext->internal_bio,
+		TLScontext->internal_bio);
+
+    /*
+     * If the debug level selected is high enough, all of the data is
+     * dumped: 3 will dump the SSL negotiation, 4 will dump everything.
+     *
+     * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
+     * Well there is a BIO below the SSL routines that is automatically
+     * created for us, so we can use it for debugging purposes.
+     */
+    if (var_smtp_tls_loglevel >= 3)
+	BIO_set_callback(SSL_get_rbio(TLScontext->con), bio_dump_cb);
+
+
+    /* Dump the negotiation for loglevels 3 and 4 */
+    if (var_smtp_tls_loglevel >= 3)
+	do_dump = 1;
+
+    /*
+     * Now we expect the negotiation to begin. This whole process is like a
+     * black box for us. We totally have to rely on the routines build into
+     * the OpenSSL library. The only thing we can do we already have done
+     * by choosing our own callback certificate verification.
+     *
+     * Error handling:
+     * If the SSL handhake fails, we print out an error message and remove
+     * everything that might be there. A session has to be removed anyway,
+     * because RFC2246 requires it. 
+     */
+    sts = do_tls_operation(vstream_fileno(stream), timeout, TLScontext,
+			   SSL_connect, NULL, NULL, NULL, 0);
+    if (sts <= 0) {
+	msg_info("SSL_connect error to %s: %d", peername, sts);
+	pfixtls_print_errors();
+	session = SSL_get_session(TLScontext->con);
+	if (session) {
+	    SSL_CTX_remove_session(ctx, session);
+	    if (var_smtp_tls_loglevel >= 2)
+		msg_info("SSL session removed");
+	}
+	if ((old_session) && (!SSL_session_reused(TLScontext->con)))
+	    SSL_SESSION_free(old_session);	/* Must also be removed */
+	SSL_free(TLScontext->con);
+	myfree((char *)TLScontext);
+	return (-1);
+    }
+
+    if (!SSL_session_reused(TLScontext->con)) {
+	SSL_SESSION_free(old_session);	/* Remove unused session */
+    }
+    else if (var_smtp_tls_loglevel >= 3)
+	msg_info("Reusing old session");
+
+    /* Only loglevel==4 dumps everything */
+    if (var_smtp_tls_loglevel < 4)
+	do_dump = 0;
+
+    /*
+     * Lets see, whether a peer certificate is available and what is
+     * the actual information. We want to save it for later use.
+     */
+    peer = SSL_get_peer_certificate(TLScontext->con);
+    if (peer != NULL) {
+	if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
+	    tls_info->peer_verified = 1;
+
+	TLScontext->peer_CN[0] = '\0';
+	if (!X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
+			NID_commonName, TLScontext->peer_CN, CCERT_BUFSIZ)) {
+	    msg_info("Could not parse server's subject CN");
+	    pfixtls_print_errors();
+	}
+	tls_info->peer_CN = TLScontext->peer_CN;
+
+	TLScontext->issuer_CN[0] = '\0';
+	if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer),
+			NID_commonName, TLScontext->issuer_CN, CCERT_BUFSIZ)) {
+	    msg_info("Could not parse server's issuer CN");
+	    pfixtls_print_errors();
+	}
+	if (!TLScontext->issuer_CN[0]) {
+	    /* No issuer CN field, use Organization instead */
+	    if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer),
+		NID_organizationName, TLScontext->issuer_CN, CCERT_BUFSIZ)) {
+		msg_info("Could not parse server's issuer Organization");
+		pfixtls_print_errors();
+	    }
+	}
+	tls_info->issuer_CN = TLScontext->issuer_CN;
+
+	if (var_smtp_tls_loglevel >= 1) {
+	    if (tls_info->peer_verified)
+		msg_info("Verified: subject_CN=%s, issuer=%s",
+			 TLScontext->peer_CN, TLScontext->issuer_CN);
+	    else
+		msg_info("Unverified: subject_CN=%s, issuer=%s",
+			 TLScontext->peer_CN, TLScontext->issuer_CN);
+	}
+	X509_free(peer);
+    }
+
+    /*
+     * Finally, collect information about protocol and cipher for logging
+     */ 
+    tls_info->protocol = SSL_get_version(TLScontext->con);
+    cipher = SSL_get_current_cipher(TLScontext->con);
+    tls_info->cipher_name = SSL_CIPHER_get_name(cipher);
+    tls_info->cipher_usebits = SSL_CIPHER_get_bits(cipher,
+						 &(tls_info->cipher_algbits));
+
+    pfixtls_clientactive = 1;
+
+    /*
+     * The TLS engine is active, switch to the pfixtls_timed_read/write()
+     * functions.
+     */
+    vstream_control(stream,
+		    VSTREAM_CTL_READ_FN, pfixtls_timed_read,
+		    VSTREAM_CTL_WRITE_FN, pfixtls_timed_write,
+		    VSTREAM_CTL_CONTEXT, (void *)TLScontext,
+		    VSTREAM_CTL_END);
+
+    msg_info("TLS connection established to %s: %s with cipher %s (%d/%d bits)",
+	     peername,
+	     tls_info->protocol, tls_info->cipher_name,
+	     tls_info->cipher_usebits, tls_info->cipher_algbits);
+
+    pfixtls_stir_seed();
+
+    return (0);
+}
+
+ /*
+  * Shut down the TLS connection, that does mean: remove all the information
+  * and reset the flags! This is needed if the actual running smtp is to
+  * be restarted. We do not give back any value, as there is nothing to
+  * be reported.
+  * Since our session cache is external, we will remove the session from
+  * memory in any case. The SSL_CTX_flush_sessions might be redundant here,
+  * I however want to make sure nothing is left.
+  * RFC2246 requires us to remove sessions if something went wrong, as
+  * indicated by the "failure" value,so we remove it from the external
+  * cache, too.
+  */
+int     pfixtls_stop_clienttls(VSTREAM *stream, int timeout, int failure,
+			       tls_info_t *tls_info)
+{
+    TLScontext_t *TLScontext;
+    int retval;
+
+    if (pfixtls_clientactive) {
+	TLScontext = (TLScontext_t *)vstream_context(stream);
+	/*
+	 * Perform SSL_shutdown() twice, as the first attempt may return
+	 * to early: it will only send out the shutdown alert but it will
+	 * not wait for the peer's shutdown alert. Therefore, when we are
+	 * the first party to send the alert, we must call SSL_shutdown()
+	 * again.
+	 * On failure we don't want to resume the session, so we will not
+	 * perform SSL_shutdown() and the session will be removed as being
+	 * bad.
+	 */
+	if (!failure) {
+	    retval = do_tls_operation(vstream_fileno(stream), timeout,
+				TLScontext, SSL_shutdown, NULL, NULL, NULL, 0);
+	    if (retval == 0)
+		do_tls_operation(vstream_fileno(stream), timeout, TLScontext,
+				SSL_shutdown, NULL, NULL, NULL, 0);
+	}
+	/*
+	 * Free the SSL structure and the BIOs. Warning: the internal_bio is
+	 * connected to the SSL structure and is automatically freed with
+	 * it. Do not free it again (core dump)!!
+	 * Only free the network_bio.
+	 */
+	SSL_free(TLScontext->con);
+	BIO_free(TLScontext->network_bio);
+	myfree((char *)TLScontext);
+	vstream_control(stream,
+		    VSTREAM_CTL_READ_FN, (VSTREAM_FN) NULL,
+		    VSTREAM_CTL_WRITE_FN, (VSTREAM_FN) NULL,
+		    VSTREAM_CTL_CONTEXT, (void *) NULL,
+		    VSTREAM_CTL_END);
+	SSL_CTX_flush_sessions(ctx, time(NULL));
+
+	pfixtls_stir_seed();
+	pfixtls_exchange_seed();
+
+	*tls_info = tls_info_zero;
+	pfixtls_clientactive = 0;
+
+    }
+
+    return (0);
+}
+
+
+#endif /* HAS_SSL */
diff -r -u --new-file postfix-1.1.0-vanilla/src/global/pfixtls.h postfix-1.1.0/src/global/pfixtls.h
--- postfix-1.1.0-vanilla/src/global/pfixtls.h	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/src/global/pfixtls.h	Thu Jan 17 21:30:51 2002
@@ -0,0 +1,76 @@
+/*++
+/* NAME
+/*      pfixtls 3h
+/* SUMMARY
+/*      TLS routines
+/* SYNOPSIS
+/*      include "pfixtls.h"
+/* DESCRIPTION
+/* .nf
+/*--*/
+
+#ifndef PFIXTLS_H_INCLUDED
+#define PFIXTLS_H_INCLUDED
+
+typedef struct {
+    int     peer_verified;
+    char   *peer_subject;
+    char   *peer_issuer;
+    char   *peer_fingerprint;
+    char   *peer_CN;
+    char   *issuer_CN;
+    const char *protocol;
+    const char *cipher_name;
+    int     cipher_usebits;
+    int     cipher_algbits;
+} tls_info_t;
+
+extern const tls_info_t tls_info_zero;
+
+#ifdef HAS_SSL
+
+typedef struct {
+    long scache_db_version;
+    long openssl_version;
+    time_t timestamp;		/* We could add other info here... */
+    int enforce_peername;
+} pfixtls_scache_info_t;
+
+extern const long scache_db_version;
+extern const long openssl_version;
+
+int     pfixtls_timed_read(int fd, void *buf, unsigned len, int timout,
+			   void *unused_timeout);
+int     pfixtls_timed_write(int fd, void *buf, unsigned len, int timeout,
+			    void *unused_timeout);
+
+extern int pfixtls_serverengine;
+int     pfixtls_init_serverengine(int verifydepth, int askcert);
+int     pfixtls_start_servertls(VSTREAM *stream, int timeout,
+				const char *peername, const char *peeraddr,
+				tls_info_t *tls_info, int require_cert);
+int     pfixtls_stop_servertls(VSTREAM *stream, int timeout, int failure,
+			       tls_info_t *tls_info);
+
+extern int pfixtls_clientengine;
+int     pfixtls_init_clientengine(int verifydepth);
+int     pfixtls_start_clienttls(VSTREAM *stream, int timeout,
+				int enforce_peername,
+				const char *peername,
+				tls_info_t *tls_info);
+int     pfixtls_stop_clienttls(VSTREAM *stream, int timeout, int failure,
+			       tls_info_t *tls_info);
+
+#endif /* PFIXTLS_H_INCLUDED */
+#endif
+
+/* LICENSE
+/* .ad
+/* .fi
+/* AUTHOR(S)
+/*	Lutz Jaenicke
+/*	BTU Cottbus
+/*	Allgemeine Elektrotechnik
+/*	Universitaetsplatz 3-4
+/*	D-03044 Cottbus, Germany
+/*--*/
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtp/Makefile.in postfix-1.1.0/src/smtp/Makefile.in
--- postfix-1.1.0-vanilla/src/smtp/Makefile.in	Tue Jan 15 16:25:29 2002
+++ postfix-1.1.0/src/smtp/Makefile.in	Thu Jan 17 21:30:51 2002
@@ -82,6 +82,7 @@
 smtp.o: ../../include/iostuff.h
 smtp.o: ../../include/attr.h
 smtp.o: ../../include/mail_server.h
+smtp.o: ../../include/pfixtls.h
 smtp.o: smtp.h
 smtp.o: smtp_sasl.h
 smtp_addr.o: smtp_addr.c
@@ -101,6 +102,7 @@
 smtp_addr.o: ../../include/argv.h
 smtp_addr.o: ../../include/deliver_request.h
 smtp_addr.o: ../../include/recipient_list.h
+smtp_addr.o: ../../include/pfixtls.h
 smtp_addr.o: smtp_addr.h
 smtp_chat.o: smtp_chat.c
 smtp_chat.o: ../../include/sys_defs.h
@@ -121,6 +123,7 @@
 smtp_chat.o: ../../include/cleanup_user.h
 smtp_chat.o: ../../include/mail_error.h
 smtp_chat.o: ../../include/name_mask.h
+smtp_chat.o: ../../include/pfixtls.h
 smtp_chat.o: smtp.h
 smtp_connect.o: smtp_connect.c
 smtp_connect.o: ../../include/sys_defs.h
@@ -141,6 +144,7 @@
 smtp_connect.o: ../../include/argv.h
 smtp_connect.o: ../../include/deliver_request.h
 smtp_connect.o: ../../include/recipient_list.h
+smtp_connetc.o: ../../include/pfixtls.h
 smtp_connect.o: smtp_addr.h
 smtp_proto.o: smtp_proto.c
 smtp_proto.o: ../../include/sys_defs.h
@@ -166,6 +170,7 @@
 smtp_proto.o: ../../include/off_cvt.h
 smtp_proto.o: ../../include/mark_corrupt.h
 smtp_proto.o: ../../include/quote_821_local.h
+smtp_proto.o: ../../include/pfixtls.h
 smtp_proto.o: smtp.h
 smtp_proto.o: ../../include/argv.h
 smtp_proto.o: smtp_sasl.h
@@ -211,9 +216,12 @@
 smtp_session.o: ../../include/stringops.h
 smtp_session.o: ../../include/vstring.h
 smtp_session.o: smtp.h
+smtp_session.o: ../../include/mail_params.h
+smtp_session.o: ../../include/pfixtls.h
 smtp_session.o: ../../include/argv.h
 smtp_session.o: ../../include/deliver_request.h
 smtp_session.o: ../../include/recipient_list.h
+smtp_session.o: ../../include/maps.h
 smtp_state.o: smtp_state.c
 smtp_state.o: ../../include/sys_defs.h
 smtp_state.o: ../../include/mymalloc.h
@@ -225,6 +233,7 @@
 smtp_state.o: ../../include/argv.h
 smtp_state.o: ../../include/deliver_request.h
 smtp_state.o: ../../include/recipient_list.h
+smtp_state.o: ../../include/pfixtls.h
 smtp_state.o: smtp_sasl.h
 smtp_trouble.o: smtp_trouble.c
 smtp_trouble.o: ../../include/sys_defs.h
@@ -244,6 +253,7 @@
 smtp_trouble.o: ../../include/name_mask.h
 smtp_trouble.o: smtp.h
 smtp_trouble.o: ../../include/argv.h
+smtp_trouble.o: ../../include/pfixtls.h
 smtp_unalias.o: smtp_unalias.c
 smtp_unalias.o: ../../include/sys_defs.h
 smtp_unalias.o: ../../include/htable.h
@@ -256,3 +266,4 @@
 smtp_unalias.o: ../../include/argv.h
 smtp_unalias.o: ../../include/deliver_request.h
 smtp_unalias.o: ../../include/recipient_list.h
+smtp_unalias.o: ../../include/pfixtls.h
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtp/smtp.c postfix-1.1.0/src/smtp/smtp.c
--- postfix-1.1.0-vanilla/src/smtp/smtp.c	Tue Dec 11 01:49:22 2001
+++ postfix-1.1.0/src/smtp/smtp.c	Thu Jan 17 21:30:51 2002
@@ -221,6 +221,7 @@
 #include <debug_peer.h>
 #include <mail_error.h>
 #include <deliver_pass.h>
+#include <pfixtls.h>
 
 /* Single server skeleton. */
 
@@ -237,6 +238,7 @@
   */
 int     var_smtp_conn_tmout;
 int     var_smtp_helo_tmout;
+int     var_smtp_starttls_tmout;
 int     var_smtp_mail_tmout;
 int     var_smtp_rcpt_tmout;
 int     var_smtp_data0_tmout;
@@ -262,6 +264,12 @@
 bool    var_smtp_break_lines;
 int     var_smtp_pix_thresh;
 int     var_smtp_pix_delay;
+int     var_smtp_use_tls;
+int     var_smtp_enforce_tls;
+int     var_smtp_tls_enforce_peername;
+char   *var_smtp_tls_per_site;
+int     var_smtp_tls_scert_vd;
+int     var_smtp_tls_note_starttls_offer;
 
  /*
   * Global variables. smtp_errno is set by the address lookup routines and by
@@ -370,6 +378,7 @@
 
 static void pre_init(char *unused_name, char **unused_argv)
 {
+
     debug_peer_init();
 
     if (var_smtp_sasl_enable)
@@ -379,6 +388,14 @@
 	msg_warn("%s is true, but SASL support is not compiled in",
 		 VAR_SMTP_SASL_ENABLE);
 #endif
+    /*
+     * Initialize the TLS data before entering the chroot jail
+     */
+#ifdef HAS_SSL
+    if (var_smtp_use_tls || var_smtp_enforce_tls || var_smtp_tls_per_site[0])
+	pfixtls_init_clientengine(var_smtp_tls_scert_vd);
+    smtp_tls_list_init();
+#endif
 }
 
 /* pre_accept - see if tables have changed */
@@ -413,6 +430,7 @@
 	VAR_SMTP_SASL_PASSWD, DEF_SMTP_SASL_PASSWD, &var_smtp_sasl_passwd, 0, 0,
 	VAR_SMTP_SASL_OPTS, DEF_SMTP_SASL_OPTS, &var_smtp_sasl_opts, 0, 0,
 	VAR_SMTP_BIND_ADDR, DEF_SMTP_BIND_ADDR, &var_smtp_bind_addr, 0, 0,
+	VAR_SMTP_TLS_PER_SITE, DEF_SMTP_TLS_PER_SITE, &var_smtp_tls_per_site, 0, 0,
 	0,
     };
     static CONFIG_TIME_TABLE time_table[] = {
@@ -426,6 +444,7 @@
 	VAR_SMTP_QUIT_TMOUT, DEF_SMTP_QUIT_TMOUT, &var_smtp_quit_tmout, 1, 0,
 	VAR_SMTP_PIX_THRESH, DEF_SMTP_PIX_THRESH, &var_smtp_pix_thresh, 0, 0,
 	VAR_SMTP_PIX_DELAY, DEF_SMTP_PIX_DELAY, &var_smtp_pix_delay, 1, 0,
+	VAR_SMTP_STARTTLS_TMOUT, DEF_SMTP_STARTTLS_TMOUT, &var_smtp_starttls_tmout, 1, 0,
 	0,
     };
     static CONFIG_INT_TABLE int_table[] = {
@@ -441,6 +460,10 @@
 	VAR_SMTP_SASL_ENABLE, DEF_SMTP_SASL_ENABLE, &var_smtp_sasl_enable,
 	VAR_SMTP_RAND_ADDR, DEF_SMTP_RAND_ADDR, &var_smtp_rand_addr,
 	VAR_SMTP_BREAK_LINES, DEF_SMTP_BREAK_LINES, &var_smtp_break_lines,
+	VAR_SMTP_USE_TLS, DEF_SMTP_USE_TLS, &var_smtp_use_tls,
+	VAR_SMTP_ENFORCE_TLS, DEF_SMTP_ENFORCE_TLS, &var_smtp_enforce_tls,
+	VAR_SMTP_TLS_ENFORCE_PN, DEF_SMTP_TLS_ENFORCE_PN, &var_smtp_tls_enforce_peername,
+	VAR_SMTP_TLS_NOTEOFFER, DEF_SMTP_TLS_NOTEOFFER, &var_smtp_tls_note_starttls_offer,
 	0,
     };
 
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtp/smtp.h postfix-1.1.0/src/smtp/smtp.h
--- postfix-1.1.0-vanilla/src/smtp/smtp.h	Sun Dec 23 17:42:28 2001
+++ postfix-1.1.0/src/smtp/smtp.h	Thu Jan 17 21:30:51 2002
@@ -27,6 +27,7 @@
   * Global library.
   */
 #include <deliver_request.h>
+#include <pfixtls.h>
 
  /*
   * State information associated with each SMTP delivery. We're bundling the
@@ -77,9 +78,14 @@
     char   *addr;			/* mail exchanger */
     char   *namaddr;			/* mail exchanger */
     int     best;			/* most preferred host */
+    int     tls_use_tls;		/* can do TLS */
+    int     tls_enforce_tls;		/* must do TLS */
+    int     tls_enforce_peername;	/* cert must match */
+    tls_info_t tls_info;		/* TLS connection state */
 } SMTP_SESSION;
 
-extern SMTP_SESSION *smtp_session_alloc(VSTREAM *, char *, char *);
+extern void smtp_tls_list_init(void);
+extern SMTP_SESSION *smtp_session_alloc(char *, VSTREAM *, char *, char *);
 extern void smtp_session_free(SMTP_SESSION *);
 
  /*
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtp/smtp_connect.c postfix-1.1.0/src/smtp/smtp_connect.c
--- postfix-1.1.0-vanilla/src/smtp/smtp_connect.c	Sun Jul  8 21:40:03 2001
+++ postfix-1.1.0/src/smtp/smtp_connect.c	Thu Jan 17 21:30:51 2002
@@ -116,6 +116,7 @@
 
 #include <mail_params.h>
 #include <own_inet_addr.h>
+#include <pfixtls.h>
 
 /* DNS library. */
 
@@ -128,7 +129,7 @@
 
 /* smtp_connect_addr - connect to explicit address */
 
-static SMTP_SESSION *smtp_connect_addr(DNS_RR *addr, unsigned port,
+static SMTP_SESSION *smtp_connect_addr(char *dest, DNS_RR *addr, unsigned port,
 				               VSTRING *why)
 {
     char   *myname = "smtp_connect_addr";
@@ -262,7 +263,7 @@
 	vstream_fclose(stream);
 	return (0);
     }
-    return (smtp_session_alloc(stream, addr->name, inet_ntoa(sin.sin_addr)));
+    return (smtp_session_alloc(dest, stream, addr->name, inet_ntoa(sin.sin_addr)));
 }
 
 /* smtp_connect_host - direct connection to host */
@@ -280,7 +281,7 @@
      */
     addr_list = smtp_host_addr(host, why);
     for (addr = addr_list; addr; addr = addr->next) {
-	if ((session = smtp_connect_addr(addr, port, why)) != 0) {
+	if ((session = smtp_connect_addr(host, addr, port, why)) != 0) {
 	    session->best = 1;
 	    break;
 	}
@@ -309,7 +310,7 @@
      */
     addr_list = smtp_domain_addr(name, why, found_myself);
     for (addr = addr_list; addr; addr = addr->next) {
-	if ((session = smtp_connect_addr(addr, port, why)) != 0) {
+	if ((session = smtp_connect_addr(name, addr, port, why)) != 0) {
 	    session->best = (addr->pref == addr_list->pref);
 	    break;
 	}
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtp/smtp_proto.c postfix-1.1.0/src/smtp/smtp_proto.c
--- postfix-1.1.0-vanilla/src/smtp/smtp_proto.c	Wed Dec 26 22:21:04 2001
+++ postfix-1.1.0/src/smtp/smtp_proto.c	Thu Jan 17 21:30:51 2002
@@ -100,6 +100,7 @@
 #include <off_cvt.h>
 #include <mark_corrupt.h>
 #include <quote_821_local.h>
+#include <pfixtls.h>
 
 /* Application-specific. */
 
@@ -158,6 +159,8 @@
     char   *words;
     char   *word;
     int     n;
+    int     oldfeatures;
+    int     rval;
 
     /*
      * Prepare for disaster.
@@ -219,7 +222,8 @@
 				   session->namaddr,
 				   translit(resp->str, "\n", " ")));
     }
-
+    if (var_smtp_always_ehlo)
+	state->features |= SMTP_FEATURE_ESMTP;
     /*
      * Pick up some useful features offered by the SMTP server. XXX Until we
      * have a portable routine to convert from string to off_t with proper
@@ -231,6 +235,7 @@
      * MicroSoft implemented AUTH based on an old draft.
      */
     lines = resp->str;
+    oldfeatures = state->features;		/* remember */
     while ((words = mystrtok(&lines, "\n")) != 0) {
 	if (mystrtok(&words, "- ") && (word = mystrtok(&words, " \t=")) != 0) {
 	    if (strcasecmp(word, "8BITMIME") == 0)
@@ -247,6 +252,8 @@
 			state->size_limit = off_cvt_string(word);
 		}
 	    }
+	    else if (strcasecmp(word, "STARTTLS") == 0)
+		state->features |= SMTP_FEATURE_STARTTLS;
 #ifdef USE_SASL_AUTH
 	    else if (var_smtp_sasl_enable && strcasecmp(word, "AUTH") == 0)
 		smtp_sasl_helo_auth(state, words);
@@ -264,6 +271,121 @@
 	msg_info("server features: 0x%x size %.0f",
 		 state->features, (double) state->size_limit);
 
+#ifdef HAS_SSL
+    if ((state->features & SMTP_FEATURE_STARTTLS) &&
+	(var_smtp_tls_note_starttls_offer) &&
+	(!(session->tls_enforce_tls || session->tls_use_tls)))
+ 	msg_info("Host offered STARTTLS: [%s]", session->host);
+    if ((session->tls_enforce_tls) &&
+	!(state->features & SMTP_FEATURE_STARTTLS))
+    {
+	/*
+	 * We are enforced to use TLS but it is not offered, so we will give
+	 * up on this host. We won't even try STARTTLS, because we could
+	 * receive a "500 command unrecognized" which would bounce the
+	 * message. We instead want to delay until STARTTLS becomes
+	 * available.
+	 */
+	return (smtp_site_fail(state, 450, "Could not start TLS: not offered"));
+    }
+    if ((session->tls_enforce_tls) && !pfixtls_clientengine) {
+	/*
+	 * We would like to start client TLS, but our own TLS-engine is
+	 * not running.
+	 */
+	return (smtp_site_fail(state, 450,
+		 "Could not start TLS: our TLS-engine not running"));
+    }
+    if ((state->features & SMTP_FEATURE_STARTTLS) &&
+	((session->tls_use_tls && pfixtls_clientengine) ||
+	 (session->tls_enforce_tls))) {
+	/*
+         * Try to use the TLS feature
+         */
+	smtp_chat_cmd(state, "STARTTLS");
+	if ((resp = smtp_chat_resp(state))->code / 100 != 2) {
+	    state->features &= ~SMTP_FEATURE_STARTTLS;
+	    /*
+	     * At this point a political decision is necessary. If we
+	     * enforce usage of tls, we have to close the connection
+	     * now.
+	     */
+	    if (session->tls_enforce_tls)
+		return (smtp_site_fail(state, resp->code,
+					 "host %s refused to start TLS: %s",
+					   session->host,
+					   translit(resp->str, "\n", " ")));
+	} else {
+	    if (rval = pfixtls_start_clienttls(session->stream,
+					       var_smtp_starttls_tmout,
+					       session->tls_enforce_peername,
+					       session->host,
+					       &(session->tls_info)))
+		return (smtp_site_fail(state, 450,
+				 "Could not start TLS: client failure"));
+
+
+	    /*
+	     * Now the connection is established and maybe we do have a
+	     * validated cert with a CommonName in it.
+	     * In enforce_peername state, the handshake would already have
+	     * been terminated so the check here is for logging only!
+	     */
+	    if (session->tls_info.peer_CN != NULL) {
+		if (!session->tls_info.peer_verified) {
+		    msg_info("Peer certficate could not be verified");
+		    if (session->tls_enforce_tls) {
+			pfixtls_stop_clienttls(session->stream,
+					       var_smtp_starttls_tmout, 1,
+					       &(session->tls_info));
+			return(smtp_site_fail(state, 450, "TLS-failure: Could not verify certificate"));
+		    }
+		}
+	    } else if (session->tls_enforce_tls) {
+		pfixtls_stop_clienttls(session->stream,
+				       var_smtp_starttls_tmout, 1,
+				       &(session->tls_info));
+		return (smtp_site_fail(state, 450, "TLS-failure: Cannot verify hostname"));
+	    }
+
+	    /*
+	     * At this point we have to re-negotiate the "EHLO" to reget
+	     * the feature-list
+	     */
+	    state->features = oldfeatures;
+	    if (state->features & SMTP_FEATURE_ESMTP) {
+		smtp_chat_cmd(state, "EHLO %s", var_myhostname);
+		if ((resp = smtp_chat_resp(state))->code / 100 != 2)
+		    state->features &= ~SMTP_FEATURE_ESMTP;
+	    }
+	    lines = resp->str;
+	    (void) mystrtok(&lines, "\n");
+	    while ((words = mystrtok(&lines, "\n")) != 0) {
+		if (mystrtok(&words, "- ") &&
+		    (word = mystrtok(&words, " \t")) != 0) {
+		    if (strcasecmp(word, "8BITMIME") == 0)
+			state->features |= SMTP_FEATURE_8BITMIME;
+		    else if (strcasecmp(word, "PIPELINING") == 0)
+			state->features |= SMTP_FEATURE_PIPELINING;
+		    else if (strcasecmp(word, "SIZE") == 0)
+			state->features |= SMTP_FEATURE_SIZE;
+		    else if (strcasecmp(word, "STARTTLS") == 0)
+			state->features |= SMTP_FEATURE_STARTTLS;
+#ifdef USE_SASL_AUTH
+		    else if (var_smtp_sasl_enable && strcasecmp(word, "AUTH") == 0)
+			smtp_sasl_helo_auth(state, words);
+#endif
+		}
+	    }
+	    /*
+	     * Actually, at this point STARTTLS should not be offered
+	     * anymore, so we could check for a protocol violation, but
+	     * what should we do then?
+	     */
+
+	}
+    }
+#endif
 #ifdef USE_SASL_AUTH
     if (var_smtp_sasl_enable && (state->features & SMTP_FEATURE_AUTH))
 	return (smtp_sasl_helo_login(state));
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtp/smtp_session.c postfix-1.1.0/src/smtp/smtp_session.c
--- postfix-1.1.0-vanilla/src/smtp/smtp_session.c	Mon Nov 20 19:06:05 2000
+++ postfix-1.1.0/src/smtp/smtp_session.c	Thu Jan 17 21:30:51 2002
@@ -42,15 +42,42 @@
 #include <vstream.h>
 #include <stringops.h>
 
+#include <mail_params.h>
+#include <maps.h>
+#include <pfixtls.h>
+
 /* Application-specific. */
 
 #include "smtp.h"
 
+#ifdef HAS_SSL
+/* static lists */
+static MAPS *tls_per_site;
+
+/* smtp_tls_list_init - initialize lists */
+
+void smtp_tls_list_init(void)
+{
+    tls_per_site = maps_create(VAR_SMTP_TLS_PER_SITE, var_smtp_tls_per_site,
+			       DICT_FLAG_LOCK);
+}
+#endif
+
 /* smtp_session_alloc - allocate and initialize SMTP_SESSION structure */
 
-SMTP_SESSION *smtp_session_alloc(VSTREAM *stream, char *host, char *addr)
+SMTP_SESSION *smtp_session_alloc(char *dest, VSTREAM *stream, char *host, char *addr)
 {
     SMTP_SESSION *session;
+    const char *lookup;
+    char *lookup_key;
+    int host_dont_use = 0;
+    int host_use = 0;
+    int host_enforce = 0;
+    int host_enforce_peername = 0;
+    int recipient_dont_use = 0;
+    int recipient_use = 0;
+    int recipient_enforce = 0;
+    int recipient_enforce_peername = 0;
 
     session = (SMTP_SESSION *) mymalloc(sizeof(*session));
     session->stream = stream;
@@ -58,6 +85,61 @@
     session->addr = mystrdup(addr);
     session->namaddr = concatenate(host, "[", addr, "]", (char *) 0);
     session->best = 1;
+    session->tls_use_tls = session->tls_enforce_tls = 0;
+    session->tls_enforce_peername = 0;
+#ifdef HAS_SSL
+    lookup_key = lowercase(mystrdup(host));
+    if (lookup = maps_find(tls_per_site, lookup_key, 0)) {
+	if (!strcasecmp(lookup, "NONE"))
+	    host_dont_use = 1;
+	else if (!strcasecmp(lookup, "MAY"))
+	    host_use = 1;
+	else if (!strcasecmp(lookup, "MUST"))
+	    host_enforce = host_enforce_peername = 1;
+	else if (!strcasecmp(lookup, "MUST_NOPEERMATCH"))
+	    host_enforce = 1;
+	else
+	    msg_warn("Unknown TLS state for receiving host %s: '%s', using default policy", session->host, lookup);
+    }
+    myfree(lookup_key);
+    lookup_key = lowercase(mystrdup(dest));
+    if (lookup = maps_find(tls_per_site, dest, 0)) {
+	if (!strcasecmp(lookup, "NONE"))
+	    recipient_dont_use = 1;
+	else if (!strcasecmp(lookup, "MAY"))
+	    recipient_use = 1;
+	else if (!strcasecmp(lookup, "MUST"))
+	    recipient_enforce = recipient_enforce_peername = 1;
+	else if (!strcasecmp(lookup, "MUST_NOPEERMATCH"))
+	    recipient_enforce = 1;
+	else
+	    msg_warn("Unknown TLS state for recipient domain %s: '%s', using default policy", dest, lookup);
+    }
+    myfree(lookup_key);
+
+    if ((var_smtp_enforce_tls && !host_dont_use) || host_enforce ||
+	 recipient_enforce)
+	session->tls_enforce_tls = session->tls_use_tls = 1;
+
+    /*
+     * Set up peername checking. We want to make sure that a MUST* entry in
+     * the tls_per_site table always has precedence. MUST always must lead to
+     * a peername check, MUST_NOPEERMATCH must always disable it. Only when
+     * no explicit setting has been found, the default will be used.
+     * There is the case left, that both "host" and "recipient" settings
+     * conflict. In this case, the "host" setting wins.
+     */
+    if (host_enforce && host_enforce_peername)
+	session->tls_enforce_peername = 1;
+    else if (recipient_enforce && recipient_enforce_peername)
+	session->tls_enforce_peername = 1;
+    else if (var_smtp_enforce_tls && var_smtp_tls_enforce_peername)
+	session->tls_enforce_peername = 1;
+
+    else if ((var_smtp_use_tls && !host_dont_use) || host_use || recipient_use)
+      session->tls_use_tls = 1;
+#endif
+    session->tls_info = tls_info_zero;
     return (session);
 }
 
@@ -65,6 +147,11 @@
 
 void    smtp_session_free(SMTP_SESSION *session)
 {
+#ifdef HAS_SSL
+    vstream_fflush(session->stream);
+    pfixtls_stop_clienttls(session->stream, var_smtp_starttls_tmout, 0,
+			   &(session->tls_info));
+#endif
     vstream_fclose(session->stream);
     myfree(session->host);
     myfree(session->addr);
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtpd/Makefile.in postfix-1.1.0/src/smtpd/Makefile.in
--- postfix-1.1.0-vanilla/src/smtpd/Makefile.in	Tue Jan 15 16:25:19 2002
+++ postfix-1.1.0/src/smtpd/Makefile.in	Thu Jan 17 21:30:51 2002
@@ -131,6 +131,7 @@
 smtpd.o: ../../include/match_list.h
 smtpd.o: ../../include/match_ops.h
 smtpd.o: ../../include/mail_server.h
+smtpd.o: ../../include/pfixtls.h
 smtpd.o: smtpd_token.h
 smtpd.o: smtpd.h
 smtpd.o: smtpd_check.h
@@ -159,6 +160,7 @@
 smtpd_chat.o: ../../include/cleanup_user.h
 smtpd_chat.o: ../../include/mail_error.h
 smtpd_chat.o: ../../include/name_mask.h
+smtpd_chat.o: ../../include/pfixtls.h
 smtpd_chat.o: smtpd.h
 smtpd_chat.o: ../../include/mail_stream.h
 smtpd_chat.o: smtpd_chat.h
@@ -194,6 +196,7 @@
 smtpd_check.o: ../../include/mail_addr_find.h
 smtpd_check.o: ../../include/match_parent_style.h
 smtpd_check.o: ../../include/split_addr.h
+smtpd_check.o: ../../include/pfixtls.h
 smtpd_check.o: smtpd.h
 smtpd_check.o: ../../include/mail_stream.h
 smtpd_check.o: smtpd_sasl_glue.h
@@ -210,6 +213,7 @@
 smtpd_peer.o: ../../include/vstream.h
 smtpd_peer.o: ../../include/argv.h
 smtpd_peer.o: ../../include/mail_stream.h
+smtpd_peer.o: ../../include/pfixtls.h
 smtpd_sasl_glue.o: smtpd_sasl_glue.c
 smtpd_sasl_glue.o: ../../include/sys_defs.h
 smtpd_sasl_glue.o: ../../include/msg.h
@@ -263,6 +267,7 @@
 smtpd_state.o: ../../include/vstring.h
 smtpd_state.o: ../../include/argv.h
 smtpd_state.o: ../../include/mail_stream.h
+smtpd_state.o: ../../include/pfixtls.h
 smtpd_state.o: smtpd_chat.h
 smtpd_state.o: smtpd_sasl_glue.h
 smtpd_token.o: smtpd_token.c
@@ -272,3 +277,4 @@
 smtpd_token.o: smtpd_token.h
 smtpd_token.o: ../../include/vstring.h
 smtpd_token.o: ../../include/vbuf.h
+smtpd_token.o: ../../include/pfixtls.h
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtpd/smtpd.c postfix-1.1.0/src/smtpd/smtpd.c
--- postfix-1.1.0-vanilla/src/smtpd/smtpd.c	Thu Jan 17 17:20:34 2002
+++ postfix-1.1.0/src/smtpd/smtpd.c	Thu Jan 17 21:30:51 2002
@@ -312,6 +312,7 @@
 #include <tok822.h>
 #include <verp_sender.h>
 #include <string_list.h>
+#include <pfixtls.h>
 
 /* Single-threaded server skeleton. */
 
@@ -336,6 +337,7 @@
   */
 int     var_smtpd_rcpt_limit;
 int     var_smtpd_tmout;
+char   *var_relay_ccerts;
 int     var_smtpd_soft_erlim;
 int     var_smtpd_hard_erlim;
 int     var_queue_minfree;		/* XXX use off_t */
@@ -383,6 +385,15 @@
 char   *var_smtpd_noop_cmds;
 char   *var_smtpd_null_key;
 int     var_smtpd_hist_thrsh;
+int     var_smtpd_starttls_tmout;
+int     var_smtpd_tls_wrappermode;
+int     var_smtpd_use_tls;
+int     var_smtpd_enforce_tls;
+int     var_smtpd_tls_auth_only;
+int     var_smtpd_tls_ask_ccert;
+int     var_smtpd_tls_req_ccert;
+int     var_smtpd_tls_ccert_vd;
+int     var_smtpd_tls_received_header;
 
  /*
   * Silly little macros.
@@ -487,11 +498,21 @@
     if (var_disable_vrfy_cmd == 0)
 	smtpd_chat_reply(state, "250-VRFY");
     smtpd_chat_reply(state, "250-ETRN");
+#ifdef HAS_SSL
+    if ((state->tls_use_tls || state->tls_enforce_tls) && (!state->tls_active))
+	smtpd_chat_reply(state, "250-STARTTLS");
+#endif
 #ifdef USE_SASL_AUTH
     if (var_smtpd_sasl_enable) {
+#ifdef HAS_SSL
+      if (!state->tls_auth_only || state->tls_active) {
+#endif
 	smtpd_chat_reply(state, "250-AUTH %s", state->sasl_mechanism_list);
 	if (var_broken_auth_clients)
 	    smtpd_chat_reply(state, "250-AUTH=%s", state->sasl_mechanism_list);
+#ifdef HAS_SSL
+      }
+#endif
     }
 #endif
     smtpd_chat_reply(state, "250-%s", VERP_CMD);
@@ -891,11 +912,76 @@
     state->rcpt_count = 0;
 }
 
+/* CN_sanitize - make sure, the CN-string is well behaved */
+
+static void CN_sanitize(char *CNstring)
+{
+    int i;
+    int len;
+    int parencount;
+
+    /*
+     * The information included in the CN (CommonName) of the peer and its
+     * issuer can be included into the Received: header line. The characters
+     * allowed as well as comment nesting are limited by RFC822.
+     */
+
+    len = strlen(CNstring);
+    /*
+     * The Received: header can only contain characters. Make sure that only
+     * acceptable characters are printed. Maybe we could allow more, but
+     * not everything makes sense inside a CommonName.
+     */
+    for (i = 0; i < len; i++) 
+	if (!((CNstring[i] >= 'A') && (CNstring[i] <='Z')) &&
+	    !((CNstring[i] >= 'a') && (CNstring[i] <='z')) &&
+	    !((CNstring[i] >= '0') && (CNstring[i] <='9')) &&
+	    (CNstring[i] != '(') && (CNstring[i] != ')') &&
+	    (CNstring[i] != '[') && (CNstring[i] != ']') &&
+	    (CNstring[i] != '{') && (CNstring[i] != '}') &&
+	    (CNstring[i] != '<') && (CNstring[i] != '>') &&
+	    (CNstring[i] != '?') && (CNstring[i] != '!') &&
+	    (CNstring[i] != ';') && (CNstring[i] != ':') &&
+	    (CNstring[i] != '"') && (CNstring[i] != '\'') &&
+	    (CNstring[i] != '/') && (CNstring[i] != '|') &&
+	    (CNstring[i] != '+') && (CNstring[i] != '&') &&
+	    (CNstring[i] != '~') && (CNstring[i] != '@') &&
+	    (CNstring[i] != '#') && (CNstring[i] != '$') &&
+	    (CNstring[i] != '%') && (CNstring[i] != '&') &&
+	    (CNstring[i] != '^') && (CNstring[i] != '*') &&
+	    (CNstring[i] != '_') && (CNstring[i] != '-') &&
+	    (CNstring[i] != '.') && (CNstring[i] != ' '))
+	    CNstring[i] = '?';
+
+    /*
+     * This information will go into the Received: header inside a comment.
+     * Since comments can be nested, parentheses '(' and ')' must match.
+     */
+    parencount = 0;
+    for (i = 0; i < len; i++) {
+	if (CNstring[i] == '(')
+	    parencount++;
+	else if (CNstring[i] == ')')
+	    parencount--;
+    }
+    /*
+     * The necessary condition is violated. Do YOU know, where to correct?
+     * I don't know, so I will practically remove all parentheses.
+     */
+    if (parencount != 0) {
+	for (i = 0; i < len; i++)
+	    if ((CNstring[i] == '(') || (CNstring[i] == ')'))
+		CNstring[i] = '/';
+    }
+}
+
 /* data_cmd - process DATA command */
 
 static int data_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *unused_argv)
 {
     char   *start;
+    char   *peer_CN;
+    char   *issuer_CN;
     int     len;
     int     curr_rec_type;
     int     prev_rec_type;
@@ -934,6 +1020,35 @@
 		"Received: from %s (%s [%s])",
 		state->helo_name ? state->helo_name : state->name,
 		state->name, state->addr);
+    if (var_smtpd_tls_received_header && state->tls_active) {
+	rec_fprintf(state->cleanup, REC_TYPE_NORM,
+		    "\t(using %s with cipher %s (%d/%d bits))",
+		    state->tls_info.protocol, state->tls_info.cipher_name,
+		    state->tls_info.cipher_usebits,
+		    state->tls_info.cipher_algbits);
+	if (state->tls_info.peer_CN) {
+            peer_CN = mystrdup(state->tls_info.peer_CN);
+	    CN_sanitize(peer_CN);
+            issuer_CN = mystrdup(state->tls_info.issuer_CN);
+	    CN_sanitize(issuer_CN);
+	    if (state->tls_info.peer_verified)
+		rec_fprintf(state->cleanup, REC_TYPE_NORM,
+			"\t(Client CN \"%s\", Issuer \"%s\" (verified OK))",
+			peer_CN, issuer_CN);
+	    else
+		rec_fprintf(state->cleanup, REC_TYPE_NORM,
+			"\t(Client CN \"%s\", Issuer \"%s\" (not verified))",
+			peer_CN, issuer_CN);
+	    myfree(issuer_CN);
+	    myfree(peer_CN);
+	}
+	else if (var_smtpd_tls_ask_ccert)
+	    rec_fprintf(state->cleanup, REC_TYPE_NORM,
+			"\t(Client did not present a certificate)");
+	else
+	    rec_fprintf(state->cleanup, REC_TYPE_NORM,
+			"\t(No client certificate requested)");
+    }
     if (state->rcpt_count == 1 && state->recipient) {
 	rec_fprintf(state->cleanup, REC_TYPE_NORM,
 		    "\tby %s (%s) with %s id %s",
@@ -1283,6 +1398,77 @@
     }
 }
 
+static int starttls_cmd(SMTPD_STATE *state, int argc, SMTPD_TOKEN *argv)
+{
+    char   *err;
+
+#ifdef HAS_SSL
+    if (argc != 1) {
+	state->error_mask |= MAIL_ERROR_PROTOCOL;
+	smtpd_chat_reply(state, "501 Syntax: STARTTLS");
+	return (-1);
+    }
+    if (state->tls_active != 0) {
+	state->error_mask |= MAIL_ERROR_PROTOCOL;
+	smtpd_chat_reply(state, "554 Error: TLS already active");
+	return (-1);
+    }
+    if (state->tls_use_tls == 0) {
+	state->error_mask |= MAIL_ERROR_PROTOCOL;
+	smtpd_chat_reply(state, "502 Error: command not implemented");
+	return (-1);
+    }
+    if (!pfixtls_serverengine) {
+	smtpd_chat_reply(state, "454 TLS not available due to temporary reason");
+	return (0);
+    }
+    smtpd_chat_reply(state, "220 Ready to start TLS");
+    vstream_fflush(state->client);
+    /*
+     * When deciding about continuing the handshake, we will stop when a
+     * client certificate was _required_ and none was presented or the
+     * verification failed. This however does only make sense when TLS is
+     * enforced. Otherwise we would happily perform perform the SMTP
+     * transaction without any STARTTLS at all! So only have the handshake
+     * fail when TLS is also enforced.
+     */
+    if (pfixtls_start_servertls(state->client, var_smtpd_starttls_tmout,
+				state->name, state->addr, &(state->tls_info),
+			(var_smtpd_tls_req_ccert && state->tls_enforce_tls))) {
+	/*
+         * Typically the connection is hanging at this point, so
+         * we should try to shut it down by force! Unfortunately this
+         * problem is not addressed in postfix!
+         */
+	return (-1);
+    }
+    state->tls_active = 1;
+    helo_reset(state);
+    mail_reset(state);
+    rcpt_reset(state);
+    return (0);
+#else
+    state->error_mask |= MAIL_ERROR_PROTOCOL;
+    smtpd_chat_reply(state, "502 Error: command not implemented");
+    return (-1);
+#endif
+}
+
+static void tls_reset(SMTPD_STATE *state)
+{
+    int failure = 0;
+
+    if (state->reason && state->where && strcmp(state->where, SMTPD_AFTER_DOT))
+	failure = 1;
+#ifdef HAS_SSL
+    vstream_fflush(state->client);
+    if (state->tls_active)
+	pfixtls_stop_servertls(state->client, var_smtpd_starttls_tmout,
+			       failure, &(state->tls_info));
+#endif
+    state->tls_active = 0;
+}
+
  /*
   * The table of all SMTP commands that we know. Set the junk limit flag on
   * any command that can be repeated an arbitrary number of times without
@@ -1300,6 +1486,10 @@
     "HELO", helo_cmd, SMTPD_CMD_FLAG_LIMIT,
     "EHLO", ehlo_cmd, SMTPD_CMD_FLAG_LIMIT,
 
+#ifdef HAS_SSL
+    "STARTTLS", starttls_cmd, 0,
+#endif
+
 #ifdef USE_SASL_AUTH
     "AUTH", smtpd_sasl_auth_cmd, 0,
 #endif
@@ -1399,9 +1589,28 @@
 		state->error_count++;
 		continue;
 	    }
+	    if (state->tls_enforce_tls &&
+		!state->tls_active &&
+		cmdp->action != starttls_cmd &&
+		cmdp->action != noop_cmd &&
+		cmdp->action != ehlo_cmd &&
+		cmdp->action != quit_cmd) {
+		smtpd_chat_reply(state,
+				 "530 Must issue a STARTTLS command first");
+		state->error_count++;
+		continue;
+	    }
 	    state->where = cmdp->name;
-	    if (cmdp->action(state, argc, argv) != 0)
+	    if (cmdp->action(state, argc, argv) != 0) {
 		state->error_count++;
+		/*
+		 * Die after TLS negotiation failure, as there is no
+		 * stable way to recover from a possible mixture of
+		 * TLS and SMTP protocol from the client.
+		 */
+		if (cmdp->action == starttls_cmd)
+		    break;
+	    }
 	    if ((cmdp->flags & SMTPD_CMD_FLAG_LIMIT)
 		&& state->junk_cmds++ > var_smtpd_junk_cmd_limit)
 		state->error_count++;
@@ -1426,6 +1635,7 @@
      * Cleanup whatever information the client gave us during the SMTP
      * dialog.
      */
+    tls_reset(state);
     helo_reset(state);
 #ifdef USE_SASL_AUTH
     if (var_smtpd_sasl_enable)
@@ -1458,6 +1668,39 @@
      * machines.
      */
     smtpd_state_init(&state, stream);
+#ifdef HAS_SSL
+    state.tls_use_tls = var_smtpd_use_tls | var_smtpd_enforce_tls;
+    state.tls_enforce_tls = var_smtpd_enforce_tls;
+    if (var_smtpd_tls_wrappermode) {
+	/*
+	 * TLS has been set to wrapper mode, meaning that we run on a
+	 * seperate port and we must switch to TLS layer before actually
+	 * performing the SMTP protocol. This implies enforce-mode.
+	 */
+	state.tls_use_tls = state.tls_enforce_tls = 1;
+	if (pfixtls_start_servertls(state.client, var_smtpd_starttls_tmout,
+                                    state.name, state.addr, &state.tls_info,
+				    var_smtpd_tls_req_ccert)) {
+            /*
+             * Typically the connection is hanging at this point, so
+             * we should try to shut it down by force! Unfortunately this
+             * problem is not addressed in postfix!
+             */
+            return;
+	}
+	state.tls_active = 1;
+    }
+    if (var_smtpd_tls_auth_only || state.tls_enforce_tls)
+	state.tls_auth_only = 1;
+#else
+    state.tls_use_tls = 0;
+    state.tls_enforce_tls = 0;
+    state.tls_auth_only = 0;
+#endif
+
+    /*
+     * Provide the SMTP service.
+     */
 
     /*
      * See if we need to turn on verbose logging for this client.
@@ -1475,10 +1718,6 @@
 	smtpd_chat_reply(&state, "220 %s", var_smtpd_banner);
 	msg_info("connect from %s[%s]", state.name, state.addr);
     }
-
-    /*
-     * Provide the SMTP service.
-     */
     smtpd_proto(&state);
 
     /*
@@ -1504,7 +1743,6 @@
 
 static void pre_jail_init(char *unused_name, char **unused_argv)
 {
-
     /*
      * Initialize blacklist/etc. patterns before entering the chroot jail, in
      * case they specify a filename pattern.
@@ -1520,6 +1758,12 @@
 	msg_warn("%s is true, but SASL support is not compiled in",
 		 VAR_SMTPD_SASL_ENABLE);
 #endif
+
+#ifdef HAS_SSL
+    if (var_smtpd_use_tls || var_smtpd_enforce_tls || var_smtpd_tls_wrappermode)
+	pfixtls_init_serverengine(var_smtpd_tls_ccert_vd,
+				  var_smtpd_tls_ask_ccert);
+#endif
 }
 
 /* main - the main program */
@@ -1542,6 +1786,7 @@
 	VAR_NON_FQDN_CODE, DEF_NON_FQDN_CODE, &var_non_fqdn_code, 0, 0,
 	VAR_SMTPD_JUNK_CMD, DEF_SMTPD_JUNK_CMD, &var_smtpd_junk_cmd_limit, 1, 0,
 	VAR_SMTPD_HIST_THRSH, DEF_SMTPD_HIST_THRSH, &var_smtpd_hist_thrsh, 1, 0,
+	VAR_SMTPD_TLS_CCERT_VD, DEF_SMTPD_TLS_CCERT_VD, &var_smtpd_tls_ccert_vd, 0, 0,
 	0,
     };
     static CONFIG_TIME_TABLE time_table[] = {
@@ -1557,6 +1802,13 @@
 	VAR_ALLOW_UNTRUST_ROUTE, DEF_ALLOW_UNTRUST_ROUTE, &var_allow_untrust_route,
 	VAR_SMTPD_SASL_ENABLE, DEF_SMTPD_SASL_ENABLE, &var_smtpd_sasl_enable,
 	VAR_BROKEN_AUTH_CLNTS, DEF_BROKEN_AUTH_CLNTS, &var_broken_auth_clients,
+	VAR_SMTPD_TLS_WRAPPER, DEF_SMTPD_TLS_WRAPPER, &var_smtpd_tls_wrappermode,
+	VAR_SMTPD_USE_TLS, DEF_SMTPD_USE_TLS, &var_smtpd_use_tls,
+	VAR_SMTPD_ENFORCE_TLS, DEF_SMTPD_ENFORCE_TLS, &var_smtpd_enforce_tls,
+	VAR_SMTPD_TLS_AUTH_ONLY, DEF_SMTPD_TLS_AUTH_ONLY, &var_smtpd_tls_auth_only,
+	VAR_SMTPD_TLS_ACERT, DEF_SMTPD_TLS_ACERT, &var_smtpd_tls_ask_ccert,
+	VAR_SMTPD_TLS_RCERT, DEF_SMTPD_TLS_RCERT, &var_smtpd_tls_req_ccert,
+	VAR_SMTPD_TLS_RECHEAD, DEF_SMTPD_TLS_RECHEAD, &var_smtpd_tls_received_header,
 	0,
     };
     static CONFIG_STR_TABLE str_table[] = {
@@ -1585,6 +1837,7 @@
 	VAR_SMTPD_SND_AUTH_MAPS, DEF_SMTPD_SND_AUTH_MAPS, &var_smtpd_snd_auth_maps, 0, 0,
 	VAR_SMTPD_NOOP_CMDS, DEF_SMTPD_NOOP_CMDS, &var_smtpd_noop_cmds, 0, 0,
 	VAR_SMTPD_NULL_KEY, DEF_SMTPD_NULL_KEY, &var_smtpd_null_key, 0, 0,
+	VAR_RELAY_CCERTS, DEF_RELAY_CCERTS, &var_relay_ccerts, 0, 0,
 	0,
     };
 
@@ -1600,3 +1853,4 @@
 		       MAIL_SERVER_PRE_ACCEPT, pre_accept,
 		       0);
 }
+
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtpd/smtpd.h postfix-1.1.0/src/smtpd/smtpd.h
--- postfix-1.1.0-vanilla/src/smtpd/smtpd.h	Tue Nov  6 18:35:29 2001
+++ postfix-1.1.0/src/smtpd/smtpd.h	Thu Jan 17 21:30:51 2002
@@ -32,6 +32,7 @@
   * Global library.
   */
 #include <mail_stream.h>
+#include <pfixtls.h>
 
  /*
   * Variables that keep track of conversation state. There is only one SMTP
@@ -77,6 +78,11 @@
     VSTRING *sasl_decoded;
 #endif
     int     warn_if_reject;
+    int     tls_active;
+    int     tls_use_tls;
+    int     tls_enforce_tls;
+    int     tls_auth_only;
+    tls_info_t tls_info;
 } SMTPD_STATE;
 
 extern void smtpd_state_init(SMTPD_STATE *, VSTREAM *);
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtpd/smtpd_check.c postfix-1.1.0/src/smtpd/smtpd_check.c
--- postfix-1.1.0-vanilla/src/smtpd/smtpd_check.c	Wed Jan 16 19:23:11 2002
+++ postfix-1.1.0/src/smtpd/smtpd_check.c	Thu Jan 17 21:30:51 2002
@@ -280,6 +280,7 @@
 
 #include <namadr_list.h>
 #include <domain_list.h>
+#include <string_list.h>
 #include <mail_params.h>
 #include <canon_addr.h>
 #include <resolve_clnt.h>
@@ -345,6 +346,9 @@
 static DOMAIN_LIST *relay_domains;
 static NAMADR_LIST *mynetworks;
 static NAMADR_LIST *perm_mx_networks;
+#ifdef HAS_SSL
+static MAPS *relay_ccerts;
+#endif
 
  /*
   * How to do parent domain wildcard matching, if any.
@@ -530,6 +534,10 @@
     perm_mx_networks =
 	namadr_list_init(match_parent_style(VAR_PERM_MX_NETWORKS),
 			 var_perm_mx_networks);
+#ifdef HAS_SSL
+    relay_ccerts = maps_create(VAR_RELAY_CCERTS, var_relay_ccerts,
+			       DICT_FLAG_LOCK);
+#endif
 
     /*
      * Pre-parse and pre-open the recipient maps.
@@ -966,6 +974,36 @@
 
 static int permit_auth_destination(SMTPD_STATE *state, char *recipient);
 
+/* permit_tls_clientcerts - OK/DUNNO for message relaying */
+
+#ifdef HAS_SSL
+static int permit_tls_clientcerts(SMTPD_STATE *state, int permit_all_certs)
+{
+    char   *low_name;
+    const char *found;
+
+    if (state->tls_info.peer_verified && permit_all_certs) {
+	if (msg_verbose)
+	    msg_info("Relaying allowed for all verified client certificates");
+	return(SMTPD_CHECK_OK);
+    }
+
+    if (state->tls_info.peer_verified && state->tls_info.peer_fingerprint) {
+	low_name = lowercase(mystrdup(state->tls_info.peer_fingerprint));
+	found = maps_find(relay_ccerts, low_name, DICT_FLAG_FIXED);
+	myfree(low_name);
+	if (found) {
+	    if (msg_verbose)
+		msg_info("Relaying allowed for certified client: %s", found);
+	    return (SMTPD_CHECK_OK);
+	} else if (msg_verbose)
+	    msg_info("relay_clientcerts: No match for fingerprint '%s'",
+		     state->tls_info.peer_fingerprint);
+    }
+    return (SMTPD_CHECK_DUNNO);
+}
+#endif
+
 /* check_relay_domains - OK/FAIL for message relaying */
 
 static int check_relay_domains(SMTPD_STATE *state, char *recipient,
@@ -2157,6 +2195,12 @@
 		status = permit_sasl_auth(state,
 					  SMTPD_CHECK_OK, SMTPD_CHECK_DUNNO);
 #endif
+#ifdef HAS_SSL
+	} else if (strcasecmp(name, PERMIT_TLS_ALL_CLIENTCERTS) == 0) {
+	  status = permit_tls_clientcerts(state, 1);
+	} else if (strcasecmp(name, PERMIT_TLS_CLIENTCERTS) == 0) {
+	  status = permit_tls_clientcerts(state, 0);
+#endif
 	} else if (strcasecmp(name, REJECT_UNKNOWN_RCPTDOM) == 0) {
 	    if (state->recipient)
 		status = reject_unknown_address(state, state->recipient,
@@ -2591,6 +2635,7 @@
 char   *var_rcpt_checks = "";
 char   *var_etrn_checks = "";
 char   *var_relay_domains = "";
+char   *var_relay_ccerts = "";
 char   *var_mynetworks = "";
 char   *var_notify_classes = "";
 
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtpd/smtpd_sasl_proto.c postfix-1.1.0/src/smtpd/smtpd_sasl_proto.c
--- postfix-1.1.0-vanilla/src/smtpd/smtpd_sasl_proto.c	Tue Sep 12 00:45:40 2000
+++ postfix-1.1.0/src/smtpd/smtpd_sasl_proto.c	Thu Jan 17 21:30:51 2002
@@ -128,6 +128,13 @@
 	smtpd_chat_reply(state, "503 Error: authentication not enabled");
 	return (-1);
     }
+#ifdef HAS_SSL
+    if (state->tls_auth_only && !state->tls_active) {
+	state->error_mask |= MAIL_ERROR_PROTOCOL;
+	smtpd_chat_reply(state, "538 Encryption required for requested authentication mechanism");
+	return (-1);
+    }
+#endif
     if (state->sasl_username) {
 	state->error_mask |= MAIL_ERROR_PROTOCOL;
 	smtpd_chat_reply(state, "503 Error: already authenticated");
diff -r -u --new-file postfix-1.1.0-vanilla/src/smtpd/smtpd_state.c postfix-1.1.0/src/smtpd/smtpd_state.c
--- postfix-1.1.0-vanilla/src/smtpd/smtpd_state.c	Tue Nov  6 18:35:40 2001
+++ postfix-1.1.0/src/smtpd/smtpd_state.c	Thu Jan 17 21:30:51 2002
@@ -92,6 +92,11 @@
     state->msg_size = 0;
     state->junk_cmds = 0;
     state->warn_if_reject = 0;
+    state->tls_active = 0;
+    state->tls_use_tls = 0;
+    state->tls_enforce_tls = 0;
+    state->tls_info = tls_info_zero;
+    state->tls_auth_only = 0;
 
 #ifdef USE_SASL_AUTH
     if (SMTPD_STAND_ALONE(state))
diff -r -u --new-file postfix-1.1.0-vanilla/src/tlsmgr/Makefile.in postfix-1.1.0/src/tlsmgr/Makefile.in
--- postfix-1.1.0-vanilla/src/tlsmgr/Makefile.in	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/src/tlsmgr/Makefile.in	Thu Jan 17 21:30:51 2002
@@ -0,0 +1,75 @@
+SHELL	= /bin/sh
+SRCS	= tlsmgr.c
+OBJS	= tlsmgr.o
+HDRS	=
+TESTSRC	=
+WARN	= -W -Wformat -Wimplicit -Wmissing-prototypes \
+	-Wparentheses -Wstrict-prototypes -Wswitch -Wuninitialized \
+	-Wunused
+DEFS	= -I. -I$(INC_DIR) -D$(SYSTYPE)
+CFLAGS	= $(DEBUG) $(OPT) $(DEFS)
+TESTPROG= 
+PROG	= tlsmgr
+INC_DIR	= ../../include
+LIBS	= ../../lib/libmaster.a ../../lib/libglobal.a ../../lib/libutil.a
+
+.c.o:;	$(CC) $(CFLAGS) -c $*.c
+
+$(PROG):	$(OBJS) $(LIBS)
+	$(CC) $(CFLAGS) -o $@ $(OBJS) $(LIBS) $(SYSLIBS)
+
+Makefile: Makefile.in
+	(set -e; echo "# DO NOT EDIT"; $(OPTS) $(SHELL) ../../makedefs; cat $?) >$@
+
+test:	$(TESTPROG)
+
+update: ../../libexec/$(PROG)
+
+../../libexec/$(PROG): $(PROG)
+	cp $(PROG) ../../libexec
+
+printfck: $(OBJS) $(PROG)
+	rm -rf printfck
+	mkdir printfck
+	cp *.h printfck
+	sed '1,/^# do not edit/!d' Makefile >printfck/Makefile
+	set -e; for i in *.c; do printfck -f .printfck $$i >printfck/$$i; done
+	cd printfck; make "INC_DIR=../../../../include" `cd ../..; ls *.o`
+
+lint:
+	lint $(DEFS) $(SRCS) $(LINTFIX)
+
+clean:
+	rm -f *.o *core $(PROG) $(TESTPROG) junk 
+	rm -rf printfck
+
+tidy:	clean
+
+depend: $(MAKES)
+	(sed '1,/^# do not edit/!d' Makefile.in; \
+	set -e; for i in [a-z][a-z0-9]*.c; do \
+	    $(CC) -E $(DEFS) $(INCL) $$i | sed -n -e '/^# *1 *"\([^"]*\)".*/{' \
+	    -e 's//'`echo $$i|sed 's/c$$/o/'`': \1/' -e 'p' -e '}'; \
+	done) | grep -v '[.][o][:][ ][/]' >$$$$ && mv $$$$ Makefile.in
+	@make -f Makefile.in Makefile
+
+# do not edit below this line - it is generated by 'make depend'
+tlsmgr.o: tlsmgr.c
+tlsmgr.o: ../../include/sys_defs.h
+tlsmgr.o: ../../include/msg.h
+tlsmgr.o: ../../include/events.h
+tlsmgr.o: ../../include/vstream.h
+tlsmgr.o: ../../include/vbuf.h
+tlsmgr.o: ../../include/dict.h
+tlsmgr.o: ../../include/argv.h
+tlsmgr.o: ../../include/vstring.h
+tlsmgr.o: ../../include/stringops.h
+tlsmgr.o: ../../include/mymalloc.h
+tlsmgr.o: ../../include/connect.h
+tlsmgr.o: ../../include/myflock.h
+tlsmgr.o: ../../include/mail_conf.h
+tlsmgr.o: ../../include/mail_params.h
+tlsmgr.o: ../../include/iostuff.h
+tlsmgr.o: ../../include/master_proto.h
+tlsmgr.o: ../../include/mail_server.h
+tlsmgr.o: ../../include/pfixtls.h
diff -r -u --new-file postfix-1.1.0-vanilla/src/tlsmgr/tlsmgr.c postfix-1.1.0/src/tlsmgr/tlsmgr.c
--- postfix-1.1.0-vanilla/src/tlsmgr/tlsmgr.c	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/src/tlsmgr/tlsmgr.c	Thu Jan 17 21:30:51 2002
@@ -0,0 +1,598 @@
+/*++
+/* NAME
+/*	tlsmgr 8
+/* SUMMARY
+/*	Postfix TLS session cache and PRNG handling manager
+/* SYNOPSIS
+/*	\fBtlsmgr\fR [generic Postfix daemon options]
+/* DESCRIPTION
+/*	The tlsmgr process does housekeeping on the session cache database
+/*	files. It runs through the databases and removes expired entries
+/*	and entries written by older (incompatible) versions.
+/*
+/*	The tlsmgr is responsible for the PRNG handling. The used internal
+/*	OpenSSL PRNG has a pool size of 8192 bits (= 1024 bytes). The pool
+/*	is initially seeded at startup from an external source (EGD or
+/*	/dev/urandom) and additional seed is obtained later during program
+/*	run at a configurable period. The exact time of seed query is
+/*	using random information and is equally distributed in the range of
+/*	[0-\fBtls_random_reseed_period\fR] with a \fBtls_random_reseed_period\fR
+/*	having a default of 1 hour.
+/*
+/*	Tlsmgr can be run chrooted and with dropped privileges, as it will
+/*	connect to the entropy source at startup.
+/*
+/*	The PRNG is additionally seeded internally by the data found in the
+/*	session cache and timevalues.
+/*
+/*	Tlsmgr reads the old value of the exchange file at startup to keep
+/*	entropy already collected during previous runs.
+/*
+/*	From the PRNG random pool a cryptographically strong 1024 byte random
+/*	sequence is written into the PRNG exchange file. The file is updated
+/*	periodically with the time changing randomly from
+/*	[0-\fBtls_random_prng_update_period\fR].
+/* STANDARDS
+/* SECURITY
+/* .ad
+/* .fi
+/*	Tlsmgr is not security-sensitive. It only deals with external data
+/*	to be fed into the PRNG, the contents is never trusted. The session
+/*	cache housekeeping will only remove entries if expired and will never
+/*	touch the contents of the cached data.
+/* DIAGNOSTICS
+/*	Problems and transactions are logged to the syslog daemon.
+/* BUGS
+/*	There is no automatic means to limit the number of entries in the
+/*	session caches and/or the size of the session cache files.
+/* CONFIGURATION PARAMETERS
+/* .ad
+/* .fi
+/*	The following \fBmain.cf\fR parameters are especially relevant to
+/*	this program. See the Postfix \fBmain.cf\fR file for syntax details
+/*	and for default values. Use the \fBpostfix reload\fR command after
+/*	a configuration change.
+/* .SH Session Cache
+/* .ad
+/* .fi
+/* .IP \fBsmtpd_tls_session_cache_database\fR
+/*	Name of the SDBM file (type sdbm:) containing the SMTP server session
+/*	cache. If the file does not exist, it is created.
+/* .IP \fBsmtpd_tls_session_cache_timeout\fR
+/*	Expiry time of SMTP server session cache entries in seconds. Entries
+/*	older than this are removed from the session cache. A cleanup-run is
+/*	performed periodically every \fBsmtpd_tls_session_cache_timeout\fR
+/*	seconds. Default is 3600 (= 1 hour).
+/* .IP \fBsmtp_tls_session_cache_database\fR
+/*	Name of the SDBM file (type sdbm:) containing the SMTP client session
+/*	cache. If the file does not exist, it is created.
+/* .IP \fBsmtp_tls_session_cache_timeout\fR
+/*	Expiry time of SMTP client session cache entries in seconds. Entries
+/*	older than this are removed from the session cache. A cleanup-run is
+/*	performed periodically every \fBsmtp_tls_session_cache_timeout\fR
+/*	seconds. Default is 3600 (= 1 hour).
+/* .SH Pseudo Random Number Generator
+/* .ad
+/* .fi
+/* .IP \fBtls_random_source\fR
+/*	Name of the EGD socket or device or regular file to obtain entropy
+/*	from. The type of entropy source must be specified by preceding the
+/*      name with the appropriate type: egd:/path/to/egd_socket,
+/*      dev:/path/to/devicefile, or /path/to/regular/file.
+/*	tlsmgr opens \fBtls_random_source\fR and tries to read
+/*	\fBtls_random_bytes\fR from it.
+/* .IP \fBtls_random_bytes\fR
+/*	Number of bytes to be read from \fBtls_random_source\fR.
+/*	Default value is 32 bytes. If using EGD, a maximum of 255 bytes is read.
+/* .IP \fBtls_random_exchange_name\fR
+/*	Name of the file written by tlsmgr and read by smtp and smtpd at
+/*	startup. The length is 1024 bytes. Default value is
+/*	/etc/postfix/prng_exch.
+/* .IP \fBtls_random_reseed_period\fR
+/*	Time in seconds until the next reseed from external sources is due.
+/*	This is the maximum value. The actual point in time is calculated
+/*	with a random factor equally distributed between 0 and this maximum
+/*	value. Default is 3600 (= 60 minutes).
+/* .IP \fBtls_random_prng_update_period\fR
+/*	Time in seconds until the PRNG exchange file is updated with new
+/*	pseude random values. This is the maximum value. The actual point
+/*	in time is calculated with a random factor equally distributed
+/*	between 0 and this maximum value. Default is 60 (= 1 minute).
+/* SEE ALSO
+/*	smtp(8) SMTP client
+/*	smtpd(8) SMTP server
+/* LICENSE
+/* .ad
+/* .fi
+/*	The Secure Mailer license must be distributed with this software.
+/* AUTHOR(S)
+/*--*/
+
+/* System library. */
+
+#include <sys_defs.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <ctype.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/time.h>			/* gettimeofday, not POSIX */
+
+/* OpenSSL library. */
+#ifdef HAS_SSL
+#include <openssl/rand.h>		/* For the PRNG */
+#endif
+
+/* Utility library. */
+
+#include <msg.h>
+#include <events.h>
+#include <dict.h>
+#include <stringops.h>
+#include <mymalloc.h>
+#include <connect.h>
+#include <myflock.h>
+
+/* Global library. */
+
+#include <mail_conf.h>
+#include <mail_params.h>
+#include <pfixtls.h>
+
+/* Master process interface */
+
+#include <master_proto.h>
+#include <mail_server.h>
+
+/* Application-specific. */
+
+ /*
+  * Tunables.
+  */
+char   *var_tls_rand_source;
+int	var_tls_rand_bytes;
+int	var_tls_reseed_period;
+int	var_tls_prng_upd_period;
+
+static int rand_exch_fd;
+static int rand_source_dev_fd = -1;
+static int rand_source_socket_fd = -1;
+static int srvr_scache_db_active;
+static int clnt_scache_db_active;
+static DICT *srvr_scache_db = NULL;
+static DICT *clnt_scache_db = NULL;
+
+static void tlsmgr_prng_upd_event(int unused_event, char *dummy)
+{
+    struct timeval tv;
+    unsigned char buffer[1024];
+    int next_period;
+
+#ifdef HAS_SSL
+    /*
+     * It is time to update the PRNG exchange file. Since other processes might
+     * have added entropy, we do this in a read_stir-back_write cycle.
+     */
+    GETTIMEOFDAY(&tv);
+    RAND_seed(&tv, sizeof(struct timeval));
+
+    if (myflock(rand_exch_fd, INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) != 0)
+	msg_fatal("Could not lock random exchange file: %s",
+		  strerror(errno));
+
+    lseek(rand_exch_fd, 0, SEEK_SET);
+    if (read(rand_exch_fd, buffer, 1024) < 0)
+	msg_fatal("reading exchange file failed");
+    RAND_seed(buffer, 1024);
+
+    RAND_bytes(buffer, 1024);
+    lseek(rand_exch_fd, 0, SEEK_SET);
+    if (write(rand_exch_fd, buffer, 1024) != 1024)
+	msg_fatal("Writing exchange file failed");
+
+    if (myflock(rand_exch_fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) != 0)
+	msg_fatal("Could not unlock random exchange file: %s",
+		  strerror(errno));
+
+    /*
+     * Make prediction difficult for outsiders and calculate the time for the
+     * next execution randomly.
+     */
+    next_period = (var_tls_prng_upd_period * buffer[0]) / 255;
+    event_request_timer(tlsmgr_prng_upd_event, dummy, next_period);
+#endif
+}
+
+
+static void tlsmgr_reseed_event(int unused_event, char *dummy)
+{
+    int egd_success;
+    int next_period;
+    int rand_bytes;
+    char buffer[255];
+    struct timeval tv;
+    unsigned char randbyte;
+
+#ifdef HAS_SSL
+    /*
+     * It is time to reseed the PRNG.
+     */
+
+    GETTIMEOFDAY(&tv);
+    RAND_seed(&tv, sizeof(struct timeval));
+    if (rand_source_dev_fd != -1) {
+	rand_bytes = read(rand_source_dev_fd, buffer, var_tls_rand_bytes);
+	if (rand_bytes > 0)
+	    RAND_seed(buffer, rand_bytes);
+	else if (rand_bytes < 0) {
+	    msg_fatal("Read from entropy device %s failed",
+		      var_tls_rand_source);
+	}
+    } else if (rand_source_socket_fd != -1) {
+	egd_success = 0;
+	buffer[0] = 1;
+	buffer[1] = var_tls_rand_bytes;
+	if (write(rand_source_socket_fd, buffer, 2) != 2)
+	    msg_info("Could not talk to %s", var_tls_rand_source);
+	else if (read(rand_source_socket_fd, buffer, 1) != 1)
+	    msg_info("Could not read info from %s", var_tls_rand_source);
+	else {
+	    rand_bytes = buffer[0];
+	    if (read(rand_source_socket_fd, buffer, rand_bytes) != rand_bytes)
+		msg_info("Could not read data from %s", var_tls_rand_source);
+	    else {
+		egd_success = 1;
+		RAND_seed(buffer, rand_bytes);
+	    }
+	}
+	if (!egd_success) {
+	    msg_info("Lost connection to EGD-device, exiting to reconnect.");
+	    exit(0);
+	}
+    } else if (*var_tls_rand_source) {
+	rand_bytes = RAND_load_file(var_tls_rand_source, var_tls_rand_bytes);
+    }
+
+    /*
+     * Make prediction difficult for outsiders and calculate the time for the
+     * next execution randomly.
+     */
+    RAND_bytes(&randbyte, 1);
+    next_period = (var_tls_reseed_period * randbyte) / 255;
+    event_request_timer(tlsmgr_reseed_event, dummy, next_period);
+#endif
+}
+
+
+static int tlsmgr_do_scache_check(DICT *scache_db, int scache_timeout,
+				  int start)
+{
+#ifdef HAS_SSL
+    int func;
+    int len;
+    int n;
+    int delete = 0;
+    int result;
+    struct timeval tv;
+    const char *member;
+    const char *value;
+    char *member_copy;
+    unsigned char nibble, *data;
+    pfixtls_scache_info_t scache_info;
+
+    GETTIMEOFDAY(&tv);
+    RAND_seed(&tv, sizeof(struct timeval));
+
+    /*
+     * Run through the given dictionary and check the stored sessions.
+     * If "start" is set to 1, a new run is initiated, otherwise the next
+     * item is accessed. The state is internally kept in the DICT.
+     */
+    if (start)
+	func = DICT_SEQ_FUN_FIRST;
+    else
+	func = DICT_SEQ_FUN_NEXT;
+    result = dict_seq(scache_db, func, &member, &value);
+
+    if (result > 0)
+	return 0;	/* End of list reached */
+    else if (result < 0)
+	msg_fatal("Database fault, should already be caught.");
+    else {
+	member_copy = mystrdup(member);
+	len = strlen(value);
+	RAND_seed(value, len);		/* Use it to increase entropy */
+	if (len < 2 * sizeof(pfixtls_scache_info_t))
+	    delete = 1;		/* Messed up, delete */
+	else if (len > 2 * sizeof(pfixtls_scache_info_t))
+	    len = 2 * sizeof(pfixtls_scache_info_t);
+	if (!delete) {
+	    data = (unsigned char *)(&scache_info);
+	    memset(data, 0, len / 2);
+	    for (n = 0; n < len; n++) {
+            if ((value[n] >= '0') && (value[n] <= '9'))
+                nibble = value[n] - '0';
+            else
+                nibble = value[n] - 'A' + 10;
+            if (n % 2)
+                data[n / 2] |= nibble;
+            else
+                data[n / 2] |= (nibble << 4);
+        }
+
+        if ((scache_info.scache_db_version != scache_db_version) ||
+            (scache_info.openssl_version != openssl_version) ||
+            (scache_info.timestamp + scache_timeout < time(NULL)))
+	    delete = 1;
+	}
+	if (delete)
+	    result = dict_del(scache_db, member_copy);
+	myfree(member_copy);
+    }
+
+    if (delete && result)
+	msg_info("Could not delete %s", member);
+    return 1;
+
+#else
+    return 0;
+#endif
+}
+
+static void tlsmgr_clnt_cache_run_event(int unused_event, char *dummy)
+{
+
+    /*
+     * This routine runs when it is time for another tls session cache scan.
+     * Make sure this routine gets called again in the future.
+     */
+    clnt_scache_db_active = tlsmgr_do_scache_check(clnt_scache_db, 
+				var_smtp_tls_scache_timeout, 1);
+    event_request_timer(tlsmgr_clnt_cache_run_event, dummy,
+		 var_smtp_tls_scache_timeout);
+}
+
+
+static void tlsmgr_srvr_cache_run_event(int unused_event, char *dummy)
+{
+
+    /*
+     * This routine runs when it is time for another tls session cache scan.
+     * Make sure this routine gets called again in the future.
+     */
+    srvr_scache_db_active = tlsmgr_do_scache_check(srvr_scache_db,
+				var_smtpd_tls_scache_timeout, 1);
+    event_request_timer(tlsmgr_srvr_cache_run_event, dummy,
+		 var_smtpd_tls_scache_timeout);
+}
+
+
+static DICT *tlsmgr_cache_open(const char *dbname)
+{
+    DICT *retval;
+    char *dbpagname;
+    char *dbdirname;
+
+    /*
+     * First, try to find out the real name of the database file, so that
+     * it can be removed.
+     */
+    if (!strncmp(dbname, "sdbm:", 5)) {
+	dbpagname = concatenate(dbname + 5, ".pag", NULL);
+	REMOVE(dbpagname);
+	myfree(dbpagname);
+	dbdirname = concatenate(dbname + 5, ".dir", NULL);
+	REMOVE(dbdirname);
+	myfree(dbdirname);
+    }
+    else {
+	msg_warn("Only type sdbm: supported: %s", dbname);
+	return NULL;
+    }
+
+    /*
+     * Now open the dictionary. Do it with O_EXCL, so that we only open a
+     * fresh file. If we cannot open it with a fresh file, then we won't
+     * touch it.
+     */
+    retval = dict_open(dbname, O_RDWR | O_CREAT | O_EXCL,
+	      DICT_FLAG_DUP_REPLACE | DICT_FLAG_LOCK | DICT_FLAG_SYNC_UPDATE);
+    if (!retval)
+	msg_warn("Could not create dictionary %s", dbname);
+    return retval;
+}
+
+/* tlsmgr_trigger_event - respond to external trigger(s) */
+
+static void tlsmgr_trigger_event(char *buf, int len,
+			               char *unused_service, char **argv)
+{
+    /*
+     * Sanity check. This service takes no command-line arguments.
+     */
+    if (argv[0])
+	msg_fatal("unexpected command-line argument: %s", argv[0]);
+
+}
+
+/* tlsmgr_loop - queue manager main loop */
+
+static int tlsmgr_loop(char *unused_name, char **unused_argv)
+{
+    /*
+     * This routine runs as part of the event handling loop, after the event
+     * manager has delivered a timer or I/O event (including the completion
+     * of a connection to a delivery process), or after it has waited for a
+     * specified amount of time. The result value of qmgr_loop() specifies
+     * how long the event manager should wait for the next event.
+     */
+#define DONT_WAIT	0
+#define WAIT_FOR_EVENT	(-1)
+
+    if (clnt_scache_db_active)
+	clnt_scache_db_active = tlsmgr_do_scache_check(clnt_scache_db,
+					var_smtp_tls_scache_timeout, 0);
+    if (srvr_scache_db_active)
+	srvr_scache_db_active = tlsmgr_do_scache_check(srvr_scache_db,
+					var_smtpd_tls_scache_timeout, 0);
+    if (clnt_scache_db_active || srvr_scache_db_active)
+	return (DONT_WAIT);
+    return (WAIT_FOR_EVENT);
+}
+
+/* pre_accept - see if tables have changed */
+
+static void pre_accept(char *unused_name, char **unused_argv)
+{
+    if (dict_changed()) {
+	msg_info("table has changed -- exiting");
+	exit(0);
+    }
+}
+
+/* tlsmgr_pre_init - pre-jail initialization */
+
+static void tlsmgr_pre_init(char *unused_name, char **unused_argv)
+{
+    int rand_bytes;
+    unsigned char buffer[255];
+
+#ifdef HAS_SSL
+    /*
+     * Access the external sources for random seed. We may not be able to
+     * access them again if we are sent to chroot jail, so we must leave
+     * dev: and egd: type sources open.
+     */
+    if (*var_tls_rand_source) {
+        if (!strncmp(var_tls_rand_source, "dev:", 4)) {
+	    /*
+	     * Source is a random device
+	     */
+	    rand_source_dev_fd = open(var_tls_rand_source + 4, 0, 0);
+	    if (rand_source_dev_fd == -1) 
+		msg_fatal("Could not open entropy device %s",
+			  var_tls_rand_source);
+	    if (var_tls_rand_bytes > 255)
+		var_tls_rand_bytes = 255;
+	    rand_bytes = read(rand_source_dev_fd, buffer, var_tls_rand_bytes);
+	    RAND_seed(buffer, rand_bytes);
+	} else if (!strncmp(var_tls_rand_source, "egd:", 4)) {
+	    /*
+	     * Source is a EGD compatible socket
+	     */
+	    rand_source_socket_fd = unix_connect(var_tls_rand_source +4,
+						 BLOCKING, 10);
+	    if (rand_source_socket_fd == -1)
+		msg_fatal("Could not connect to %s", var_tls_rand_source);
+	    if (var_tls_rand_bytes > 255)
+		var_tls_rand_bytes = 255;
+	    buffer[0] = 1;
+	    buffer[1] = var_tls_rand_bytes;
+	    if (write(rand_source_socket_fd, buffer, 2) != 2)
+		msg_fatal("Could not talk to %s", var_tls_rand_source);
+	    if (read(rand_source_socket_fd, buffer, 1) != 1)
+		msg_fatal("Could not read info from %s", var_tls_rand_source);
+	    rand_bytes = buffer[0];
+	    if (read(rand_source_socket_fd, buffer, rand_bytes) != rand_bytes)
+		msg_fatal("Could not read data from %s", var_tls_rand_source);
+	    RAND_seed(buffer, rand_bytes);
+	} else {
+	    rand_bytes = RAND_load_file(var_tls_rand_source,
+					var_tls_rand_bytes);
+	}
+    }
+#endif
+
+    /*
+     * Now open the PRNG exchange file
+     */
+    if (*var_tls_rand_exch_name) {
+	rand_exch_fd = open(var_tls_rand_exch_name, O_RDWR | O_CREAT, 0600);
+    }
+
+    /*
+     * Finally, open the session cache files. Remove old files, if still there.
+     * If we could not remove the old files, something is pretty wrong and we
+     * won't touch it!!
+     */
+    if (*var_smtp_tls_scache_db)
+	clnt_scache_db = tlsmgr_cache_open(var_smtp_tls_scache_db);
+    if (*var_smtpd_tls_scache_db)
+	srvr_scache_db = tlsmgr_cache_open(var_smtpd_tls_scache_db);
+}
+
+/* qmgr_post_init - post-jail initialization */
+
+static void tlsmgr_post_init(char *unused_name, char **unused_argv)
+{
+    unsigned char buffer[1024];
+
+    /*
+     * This routine runs after the skeleton code has entered the chroot jail.
+     * Prevent automatic process suicide after a limited number of client
+     * requests or after a limited amount of idle time.
+     */
+    var_use_limit = 0;
+    var_idle_limit = 0;
+
+#ifdef HAS_SSL
+    /*
+     * Complete thie initialization by reading the additional seed from the
+     * PRNG exchange file. Don't care how many bytes were actually read, just
+     * seed buffer into the PRNG, regardless of its contents.
+     */
+    if (rand_exch_fd >= 0) {
+	if (myflock(rand_exch_fd, INTERNAL_LOCK, MYFLOCK_OP_SHARED) == -1)
+	    msg_fatal("Could not lock random exchange file: %s",
+		      strerror(errno));
+	read(rand_exch_fd, buffer, 1024);
+	if (myflock(rand_exch_fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) == -1)
+	    msg_fatal("Could not unlock random exchange file: %s",
+		      strerror(errno));
+	RAND_seed(buffer, 1024);
+	tlsmgr_prng_upd_event(0, (char *) 0);
+	tlsmgr_reseed_event(0, (char *) 0);
+    }
+#endif
+
+    clnt_scache_db_active = 0;
+    srvr_scache_db_active = 0;
+    if (clnt_scache_db)
+	tlsmgr_clnt_cache_run_event(0, (char *) 0);
+    if (srvr_scache_db)
+	tlsmgr_srvr_cache_run_event(0, (char *) 0);
+}
+
+/* main - the main program */
+
+int     main(int argc, char **argv)
+{
+    static CONFIG_STR_TABLE str_table[] = {
+	VAR_TLS_RAND_SOURCE, DEF_TLS_RAND_SOURCE, &var_tls_rand_source, 0, 0,
+	0,
+    };
+    static CONFIG_TIME_TABLE time_table[] = {
+	VAR_TLS_RESEED_PERIOD, DEF_TLS_RESEED_PERIOD, &var_tls_reseed_period, 0, 0,
+	VAR_TLS_PRNG_UPD_PERIOD, DEF_TLS_PRNG_UPD_PERIOD, &var_tls_prng_upd_period, 0, 0,
+	0,
+    };
+    static CONFIG_INT_TABLE int_table[] = {
+	VAR_TLS_RAND_BYTES, DEF_TLS_RAND_BYTES, &var_tls_rand_bytes, 0, 0,
+	0,
+    };
+
+    /*
+     * Use the trigger service skeleton, because no-one else should be
+     * monitoring our service port while this process runs, and because we do
+     * not talk back to the client.
+     */
+    trigger_server_main(argc, argv, tlsmgr_trigger_event,
+			MAIL_SERVER_TIME_TABLE, time_table,
+			MAIL_SERVER_INT_TABLE, int_table,
+			MAIL_SERVER_STR_TABLE, str_table,
+			MAIL_SERVER_PRE_INIT, tlsmgr_pre_init,
+			MAIL_SERVER_POST_INIT, tlsmgr_post_init,
+			MAIL_SERVER_LOOP, tlsmgr_loop,
+			MAIL_SERVER_PRE_ACCEPT, pre_accept,
+			0);
+}
diff -r -u --new-file postfix-1.1.0-vanilla/src/util/Makefile.in postfix-1.1.0/src/util/Makefile.in
--- postfix-1.1.0-vanilla/src/util/Makefile.in	Tue Jan 15 16:24:58 2002
+++ postfix-1.1.0/src/util/Makefile.in	Thu Jan 17 21:30:51 2002
@@ -26,7 +26,7 @@
 	unix_connect.c unix_listen.c unix_trigger.c unsafe.c username.c \
 	valid_hostname.c vbuf.c vbuf_print.c vstream.c vstream_popen.c \
 	vstring.c vstring_vstream.c watchdog.c writable.c write_buf.c \
-	write_wait.c
+	write_wait.c dict_sdbm.c sdbm.c
 OBJS	= alldig.o argv.o argv_split.o attr_print0.o attr_print64.o \
 	attr_scan0.o attr_scan64.o base64_code.o basename.o binhash.o \
 	chroot_uid.o clean_env.o close_on_exec.o concatenate.o ctable.o \
@@ -54,7 +54,7 @@
 	unix_connect.o unix_listen.o unix_trigger.o unsafe.o username.o \
 	valid_hostname.o vbuf.o vbuf_print.o vstream.o vstream_popen.o \
 	vstring.o vstring_vstream.o watchdog.o writable.o write_buf.o \
-	write_wait.o
+	write_wait.o dict_sdbm.o sdbm.o
 HDRS	= argv.h attr.h base64_code.h binhash.h chroot_uid.h clean_env.h \
 	connect.h ctable.h dict.h dict_db.h dict_dbm.h dict_env.h \
 	dict_ht.h dict_ldap.h dict_mysql.h dict_ni.h dict_nis.h \
@@ -71,7 +71,8 @@
 	scan_dir.h set_eugid.h set_ugid.h sigdelay.h spawn_command.h \
 	split_at.h stat_as.h stringops.h sys_defs.h timed_connect.h \
 	timed_wait.h trigger.h username.h valid_hostname.h vbuf.h \
-	vbuf_print.h vstream.h vstring.h vstring_vstream.h watchdog.h
+	vbuf_print.h vstream.h vstring.h vstring_vstream.h watchdog.h \
+	dict_sdbm.h sdbm.h
 TESTSRC	= fifo_open.c fifo_rdwr_bug.c fifo_rdonly_bug.c select_bug.c \
 	stream_test.c dup2_pass_on_exec.c
 WARN	= -W -Wformat -Wimplicit -Wmissing-prototypes \
@@ -590,6 +591,7 @@
 dict_open.o: dict_unix.h
 dict_open.o: dict_tcp.h
 dict_open.o: dict_dbm.h
+dict_open.o: dict_sdbm.h
 dict_open.o: dict_db.h
 dict_open.o: dict_nis.h
 dict_open.o: dict_nisplus.h
@@ -1217,3 +1219,9 @@
 write_wait.o: sys_defs.h
 write_wait.o: msg.h
 write_wait.o: iostuff.h
+sdbm.o: sdbm.c
+sdbm.o: sdbm.h
+dict_sdbm.o: sdbm.h
+dict_sdbm.o: dict_sdbm.c
+dict_sdbm.o: dict_sdbm.h
+dict_sdbm.o: sys_defs.h
diff -r -u --new-file postfix-1.1.0-vanilla/src/util/dict_open.c postfix-1.1.0/src/util/dict_open.c
--- postfix-1.1.0-vanilla/src/util/dict_open.c	Fri Dec 21 23:18:07 2001
+++ postfix-1.1.0/src/util/dict_open.c	Thu Jan 17 21:30:51 2002
@@ -159,6 +159,7 @@
 #include <dict_env.h>
 #include <dict_unix.h>
 #include <dict_tcp.h>
+#include <dict_sdbm.h>
 #include <dict_dbm.h>
 #include <dict_db.h>
 #include <dict_nis.h>
@@ -187,6 +188,7 @@
 #if 0
     DICT_TYPE_TCP, dict_tcp_open,
 #endif
+    "sdbm", dict_sdbm_open,
 #ifdef HAS_DBM
     DICT_TYPE_DBM, dict_dbm_open,
 #endif
diff -r -u --new-file postfix-1.1.0-vanilla/src/util/dict_sdbm.c postfix-1.1.0/src/util/dict_sdbm.c
--- postfix-1.1.0-vanilla/src/util/dict_sdbm.c	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/src/util/dict_sdbm.c	Thu Jan 17 21:30:51 2002
@@ -0,0 +1,407 @@
+/*++
+/* NAME
+/*	dict_sdbm 3
+/* SUMMARY
+/*	dictionary manager interface to SDBM files
+/* SYNOPSIS
+/*	#include <dict_sdbm.h>
+/*
+/*	DICT	*dict_sdbm_open(path, open_flags, dict_flags)
+/*	const char *name;
+/*	const char *path;
+/*	int	open_flags;
+/*	int	dict_flags;
+/* DESCRIPTION
+/*	dict_sdbm_open() opens the named SDBM database and makes it available
+/*	via the generic interface described in dict_open(3).
+/* DIAGNOSTICS
+/*	Fatal errors: cannot open file, file write error, out of memory.
+/* SEE ALSO
+/*	dict(3) generic dictionary manager
+/*	sdbm(3) data base subroutines
+/* LICENSE
+/* .ad
+/* .fi
+/*	The Secure Mailer license must be distributed with this software.
+/* AUTHOR(S)
+/*	Wietse Venema
+/*	IBM T.J. Watson Research
+/*	P.O. Box 704
+/*	Yorktown Heights, NY 10598, USA
+/*--*/
+
+#include "sys_defs.h"
+
+/* System library. */
+
+#include <sys/stat.h>
+#include <string.h>
+#include <unistd.h>
+
+/* Utility library. */
+
+#include "msg.h"
+#include "mymalloc.h"
+#include "htable.h"
+#include "iostuff.h"
+#include "vstring.h"
+#include "myflock.h"
+#include "stringops.h"
+#include "dict.h"
+#include "dict_sdbm.h"
+#include "sdbm.h"
+
+/* Application-specific. */
+
+typedef struct {
+    DICT    dict;			/* generic members */
+    SDBM   *dbm;			/* open database */
+    char   *path;			/* pathname */
+} DICT_SDBM;
+
+/* dict_sdbm_lookup - find database entry */
+
+static const char *dict_sdbm_lookup(DICT *dict, const char *name)
+{
+    DICT_SDBM *dict_sdbm = (DICT_SDBM *) dict;
+    datum   dbm_key;
+    datum   dbm_value;
+    static VSTRING *buf;
+    const char *result = 0;
+
+    dict_errno = 0;
+
+    /*
+     * Acquire an exclusive lock.
+     */
+    if ((dict->flags & DICT_FLAG_LOCK)
+	&& myflock(dict->fd, INTERNAL_LOCK, MYFLOCK_OP_SHARED) < 0)
+	msg_fatal("%s: lock dictionary: %m", dict_sdbm->path);
+
+    /*
+     * See if this DBM file was written with one null byte appended to key
+     * and value.
+     */
+    if (dict->flags & DICT_FLAG_TRY1NULL) {
+	dbm_key.dptr = (void *) name;
+	dbm_key.dsize = strlen(name) + 1;
+	dbm_value = sdbm_fetch(dict_sdbm->dbm, dbm_key);
+	if (dbm_value.dptr != 0) {
+	    dict->flags &= ~DICT_FLAG_TRY0NULL;
+	    result = dbm_value.dptr;
+	}
+    }
+
+    /*
+     * See if this DBM file was written with no null byte appended to key and
+     * value.
+     */
+    if (result == 0 && (dict->flags & DICT_FLAG_TRY0NULL)) {
+	dbm_key.dptr = (void *) name;
+	dbm_key.dsize = strlen(name);
+	dbm_value = sdbm_fetch(dict_sdbm->dbm, dbm_key);
+	if (dbm_value.dptr != 0) {
+	    if (buf == 0)
+		buf = vstring_alloc(10);
+	    vstring_strncpy(buf, dbm_value.dptr, dbm_value.dsize);
+	    dict->flags &= ~DICT_FLAG_TRY1NULL;
+	    result = vstring_str(buf);
+	}
+    }
+
+    /*
+     * Release the exclusive lock.
+     */
+    if ((dict->flags & DICT_FLAG_LOCK)
+	&& myflock(dict->fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) < 0)
+	msg_fatal("%s: unlock dictionary: %m", dict_sdbm->path);
+
+    return (result);
+}
+
+/* dict_sdbm_update - add or update database entry */
+
+static void dict_sdbm_update(DICT *dict, const char *name, const char *value)
+{
+    DICT_SDBM *dict_sdbm = (DICT_SDBM *) dict;
+    datum   dbm_key;
+    datum   dbm_value;
+    int     status;
+
+    dbm_key.dptr = (void *) name;
+    dbm_value.dptr = (void *) value;
+    dbm_key.dsize = strlen(name);
+    dbm_value.dsize = strlen(value);
+
+    /*
+     * If undecided about appending a null byte to key and value, choose a
+     * default depending on the platform.
+     */
+    if ((dict->flags & DICT_FLAG_TRY1NULL)
+	&& (dict->flags & DICT_FLAG_TRY0NULL)) {
+#ifdef DBM_NO_TRAILING_NULL
+	dict->flags &= ~DICT_FLAG_TRY1NULL;
+#else
+	dict->flags &= ~DICT_FLAG_TRY0NULL;
+#endif
+    }
+
+    /*
+     * Optionally append a null byte to key and value.
+     */
+    if (dict->flags & DICT_FLAG_TRY1NULL) {
+	dbm_key.dsize++;
+	dbm_value.dsize++;
+    }
+
+    /*
+     * Acquire an exclusive lock.
+     */
+    if ((dict->flags & DICT_FLAG_LOCK)
+	&& myflock(dict->fd, INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) < 0)
+	msg_fatal("%s: lock dictionary: %m", dict_sdbm->path);
+
+    /*
+     * Do the update.
+     */
+    if ((status = sdbm_store(dict_sdbm->dbm, dbm_key, dbm_value,
+     (dict->flags & DICT_FLAG_DUP_REPLACE) ? DBM_REPLACE : DBM_INSERT)) < 0)
+	msg_fatal("error writing SDBM database %s: %m", dict_sdbm->path);
+    if (status) {
+	if (dict->flags & DICT_FLAG_DUP_IGNORE)
+	     /* void */ ;
+	else if (dict->flags & DICT_FLAG_DUP_WARN)
+	    msg_warn("%s: duplicate entry: \"%s\"", dict_sdbm->path, name);
+	else
+	    msg_fatal("%s: duplicate entry: \"%s\"", dict_sdbm->path, name);
+    }
+
+    /*
+     * Release the exclusive lock.
+     */
+    if ((dict->flags & DICT_FLAG_LOCK)
+	&& myflock(dict->fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) < 0)
+	msg_fatal("%s: unlock dictionary: %m", dict_sdbm->path);
+}
+
+
+/* dict_sdbm_delete - delete one entry from the dictionary */
+
+static int dict_sdbm_delete(DICT *dict, const char *name)
+{
+    DICT_SDBM *dict_sdbm = (DICT_SDBM *) dict;
+    datum   dbm_key;
+    int     status = 1;
+    int     flags = 0;
+
+    /*
+     * Acquire an exclusive lock.
+     */
+    if ((dict->flags & DICT_FLAG_LOCK)
+	&& myflock(dict->fd, INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) < 0)
+	msg_fatal("%s: lock dictionary: %m", dict_sdbm->path);
+
+    /*
+     * See if this DBM file was written with one null byte appended to key
+     * and value.
+     */
+    if (dict->flags & DICT_FLAG_TRY1NULL) {
+	dbm_key.dptr = (void *) name;
+	dbm_key.dsize = strlen(name) + 1;
+	sdbm_clearerr(dict_sdbm->dbm);
+	if ((status = sdbm_delete(dict_sdbm->dbm, dbm_key)) < 0) {
+	    if (sdbm_error(dict_sdbm->dbm) != 0)	/* fatal error */
+		msg_fatal("error deleting from %s: %m", dict_sdbm->path);
+	    status = 1;				/* not found */
+	} else {
+	    dict->flags &= ~DICT_FLAG_TRY0NULL;	/* found */
+	}
+    }
+
+    /*
+     * See if this DBM file was written with no null byte appended to key and
+     * value.
+     */
+    if (status > 0 && (dict->flags & DICT_FLAG_TRY0NULL)) {
+	dbm_key.dptr = (void *) name;
+	dbm_key.dsize = strlen(name);
+	sdbm_clearerr(dict_sdbm->dbm);
+	if ((status = sdbm_delete(dict_sdbm->dbm, dbm_key)) < 0) {
+	    if (sdbm_error(dict_sdbm->dbm) != 0)	/* fatal error */
+		msg_fatal("error deleting from %s: %m", dict_sdbm->path);
+	    status = 1;				/* not found */
+	} else {
+	    dict->flags &= ~DICT_FLAG_TRY1NULL;	/* found */
+	}
+    }
+
+    /*
+     * Release the exclusive lock.
+     */
+    if ((dict->flags & DICT_FLAG_LOCK)
+	&& myflock(dict->fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) < 0)
+	msg_fatal("%s: unlock dictionary: %m", dict_sdbm->path);
+
+    return (status);
+}
+
+/* traverse the dictionary */
+
+static int dict_sdbm_sequence(DICT *dict, const int function,
+			             const char **key, const char **value)
+{
+    char   *myname = "dict_sdbm_sequence";
+    DICT_SDBM *dict_sdbm = (DICT_SDBM *) dict;
+    datum   dbm_key;
+    datum   dbm_value;
+    int     status = 0;
+    static VSTRING *key_buf;
+    static VSTRING *value_buf;
+
+    /*
+     * Acquire an exclusive lock.
+     */
+    if ((dict->flags & DICT_FLAG_LOCK)
+	&& myflock(dict->fd, INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) < 0)
+	msg_fatal("%s: lock dictionary: %m", dict_sdbm->path);
+
+    /*
+     * Determine and execute the seek function. It returns the key.
+     */
+    switch (function) {
+    case DICT_SEQ_FUN_FIRST:
+	dbm_key = sdbm_firstkey(dict_sdbm->dbm);
+	break;
+    case DICT_SEQ_FUN_NEXT:
+	dbm_key = sdbm_nextkey(dict_sdbm->dbm);
+	break;
+    default:
+	msg_panic("%s: invalid function: %d", myname, function);
+    }
+
+    /*
+     * Release the exclusive lock.
+     */
+    if ((dict->flags & DICT_FLAG_LOCK)
+	&& myflock(dict->fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) < 0)
+	msg_fatal("%s: unlock dictionary: %m", dict_sdbm->path);
+
+    if (dbm_key.dptr != 0 && dbm_key.dsize > 0) {
+
+	/*
+	 * See if this DB file was written with one null byte appended to key
+	 * an d value or not. If necessary, copy the key.
+	 */
+	if (((char *) dbm_key.dptr)[dbm_key.dsize - 1] == 0) {
+	    *key = dbm_key.dptr;
+	} else {
+	    if (key_buf == 0)
+		key_buf = vstring_alloc(10);
+	    vstring_strncpy(key_buf, dbm_key.dptr, dbm_key.dsize);
+	    *key = vstring_str(key_buf);
+	}
+
+	/*
+	 * Fetch the corresponding value.
+	 */
+	dbm_value = sdbm_fetch(dict_sdbm->dbm, dbm_key);
+
+	if (dbm_value.dptr != 0 && dbm_value.dsize > 0) {
+
+	    /*
+	     * See if this DB file was written with one null byte appended to
+	     * key and value or not. If necessary, copy the key.
+	     */
+	    if (((char *) dbm_value.dptr)[dbm_value.dsize - 1] == 0) {
+		*value = dbm_value.dptr;
+	    } else {
+		if (value_buf == 0)
+		    value_buf = vstring_alloc(10);
+		vstring_strncpy(value_buf, dbm_value.dptr, dbm_value.dsize);
+		*value = vstring_str(value_buf);
+	    }
+	} else {
+
+	    /*
+	     * Determine if we have hit the last record or an error
+	     * condition.
+	     */
+	    if (sdbm_error(dict_sdbm->dbm))
+		msg_fatal("error seeking %s: %m", dict_sdbm->path);
+	    return (1);				/* no error: eof/not found
+						 * (should not happen!) */
+	}
+    } else {
+
+	/*
+	 * Determine if we have hit the last record or an error condition.
+	 */
+	if (sdbm_error(dict_sdbm->dbm))
+	    msg_fatal("error seeking %s: %m", dict_sdbm->path);
+	return (1);				/* no error: eof/not found */
+    }
+    return (0);
+}
+
+/* dict_sdbm_close - disassociate from data base */
+
+static void dict_sdbm_close(DICT *dict)
+{
+    DICT_SDBM *dict_sdbm = (DICT_SDBM *) dict;
+
+    sdbm_close(dict_sdbm->dbm);
+    myfree(dict_sdbm->path);
+    myfree((char *) dict_sdbm);
+}
+
+/* dict_sdbm_open - open SDBM data base */
+
+DICT   *dict_sdbm_open(const char *path, int open_flags, int dict_flags)
+{
+    DICT_SDBM *dict_sdbm;
+    struct stat st;
+    SDBM   *dbm;
+    char   *dbm_path;
+    int     lock_fd;
+
+    if (dict_flags & DICT_FLAG_LOCK) {
+	dbm_path = concatenate(path, ".pag", (char *) 0);
+	if ((lock_fd = open(dbm_path, open_flags, 0644)) < 0)
+	    msg_fatal("open database %s: %m", dbm_path);
+	if (myflock(lock_fd, INTERNAL_LOCK, MYFLOCK_OP_SHARED) < 0)
+	    msg_fatal("shared-lock database %s for open: %m", dbm_path);
+    }
+
+    /*
+     * XXX SunOS 5.x has no const in dbm_open() prototype.
+     */
+    if ((dbm = sdbm_open((char *) path, open_flags, 0644)) == 0)
+	msg_fatal("open database %s.{dir,pag}: %m", path);
+
+    if (dict_flags & DICT_FLAG_LOCK) {
+	if (myflock(lock_fd, INTERNAL_LOCK, MYFLOCK_OP_NONE) < 0)
+	    msg_fatal("unlock database %s for open: %m", dbm_path);
+	if (close(lock_fd) < 0)
+	    msg_fatal("close database %s: %m", dbm_path);
+	myfree(dbm_path);
+    }
+    dict_sdbm = (DICT_SDBM *) mymalloc(sizeof(*dict_sdbm));
+    dict_sdbm->dict.lookup = dict_sdbm_lookup;
+    dict_sdbm->dict.update = dict_sdbm_update;
+    dict_sdbm->dict.delete = dict_sdbm_delete;
+    dict_sdbm->dict.sequence = dict_sdbm_sequence;
+    dict_sdbm->dict.close = dict_sdbm_close;
+    dict_sdbm->dict.fd = sdbm_pagfno(dbm);
+    if (fstat(dict_sdbm->dict.fd, &st) < 0)
+	msg_fatal("dict_sdbm_open: fstat: %m");
+    dict_sdbm->dict.mtime = st.st_mtime;
+    close_on_exec(sdbm_pagfno(dbm), CLOSE_ON_EXEC);
+    close_on_exec(sdbm_dirfno(dbm), CLOSE_ON_EXEC);
+    dict_sdbm->dict.flags = dict_flags | DICT_FLAG_FIXED;
+    if ((dict_flags & (DICT_FLAG_TRY0NULL | DICT_FLAG_TRY1NULL)) == 0)
+	dict_sdbm->dict.flags |= (DICT_FLAG_TRY0NULL | DICT_FLAG_TRY1NULL);
+    dict_sdbm->dbm = dbm;
+    dict_sdbm->path = mystrdup(path);
+
+    return (&dict_sdbm->dict);
+}
diff -r -u --new-file postfix-1.1.0-vanilla/src/util/dict_sdbm.h postfix-1.1.0/src/util/dict_sdbm.h
--- postfix-1.1.0-vanilla/src/util/dict_sdbm.h	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/src/util/dict_sdbm.h	Thu Jan 17 21:30:51 2002
@@ -0,0 +1,35 @@
+#ifndef _DICT_SDBM_H_INCLUDED_
+#define _DICT_SDBM_H_INCLUDED_
+
+/*++
+/* NAME
+/*	dict_dbm 3h
+/* SUMMARY
+/*	dictionary manager interface to DBM files
+/* SYNOPSIS
+/*	#include <dict_dbm.h>
+/* DESCRIPTION
+/* .nf
+
+ /*
+  * Utility library.
+  */
+#include <dict.h>
+
+ /*
+  * External interface.
+  */
+extern DICT *dict_sdbm_open(const char *, int, int);
+
+/* LICENSE
+/* .ad
+/* .fi
+/*	The Secure Mailer license must be distributed with this software.
+/* AUTHOR(S)
+/*	Wietse Venema
+/*	IBM T.J. Watson Research
+/*	P.O. Box 704
+/*	Yorktown Heights, NY 10598, USA
+/*--*/
+
+#endif
diff -r -u --new-file postfix-1.1.0-vanilla/src/util/sdbm.c postfix-1.1.0/src/util/sdbm.c
--- postfix-1.1.0-vanilla/src/util/sdbm.c	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/src/util/sdbm.c	Thu Jan 17 21:30:51 2002
@@ -0,0 +1,971 @@
+/*++
+/* NAME
+/*      sdbm 3h
+/* SUMMARY
+/*      SDBM Simple DBM: ndbm work-alike hashed database library
+/* SYNOPSIS
+/*      include "sdbm.h"
+/* DESCRIPTION
+/*	This file includes the public domain SDBM (ndbm work-alike hashed
+/*	database library), based on Per-Aake Larson's Dynamic Hashing
+/*	algorithms. BIT 18 (1978).
+/*	author: oz@nexus.yorku.ca
+/*	status: public domain
+/*	The file has been patched following the advice of Uwe Ohse
+/*	<uwe@ohse.de>:
+/*	--------------------------------------------------------------
+/*	this patch fixes a problem with sdbms .dir file, which arrises when
+/*	a second .dir block is needed for the first time. read() returns 0
+/*	in that case, and the library forgot to initialize that new block.
+/*
+/*	A related problem is that the calculation of db->maxbno is wrong.
+/*	It just appends 4096*BYTESIZ bits, which is not enough except for
+/*	small databases (.dir basically doubles everytime it's too small).
+/*	--------------------------------------------------------------
+/*	According to Uwe Ohse, the patch has also been submitted to the
+/*	author of SDBM. (The 4096*BYTESIZ bits comment may apply with a
+/*	different size for Postfix/TLS, as the patch was sent against the
+/*	original SDBM distributiona and for Postfix/TLS I have changed the
+/*	default sizes.
+/* .nf
+/*--*/
+
+/*
+ * sdbm - ndbm work-alike hashed database library
+ * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978).
+ * author: oz@nexus.yorku.ca
+ * status: public domain.
+ *
+ * core routines
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef WIN32
+#include <io.h>
+#include <errno.h>
+#else
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#ifdef __STDC__
+#include <stddef.h>
+#endif
+
+#include <sdbm.h>
+
+/*
+ * useful macros
+ */
+#define bad(x)          ((x).dptr == NULL || (x).dsize <= 0)
+#define exhash(item)    sdbm_hash((item).dptr, (item).dsize)
+#define ioerr(db)       ((db)->flags |= DBM_IOERR)
+
+#define OFF_PAG(off)    (long) (off) * PBLKSIZ
+#define OFF_DIR(off)    (long) (off) * DBLKSIZ
+
+static long masks[] =
+{
+    000000000000, 000000000001, 000000000003, 000000000007,
+    000000000017, 000000000037, 000000000077, 000000000177,
+    000000000377, 000000000777, 000000001777, 000000003777,
+    000000007777, 000000017777, 000000037777, 000000077777,
+    000000177777, 000000377777, 000000777777, 000001777777,
+    000003777777, 000007777777, 000017777777, 000037777777,
+    000077777777, 000177777777, 000377777777, 000777777777,
+    001777777777, 003777777777, 007777777777, 017777777777
+};
+
+datum   nullitem =
+{NULL, 0};
+
+typedef struct
+{
+    int     dirf;			/* directory file descriptor */
+    int     pagf;			/* page file descriptor */
+    int     flags;			/* status/error flags, see below */
+    long    maxbno;			/* size of dirfile in bits */
+    long    curbit;			/* current bit number */
+    long    hmask;			/* current hash mask */
+    long    blkptr;			/* current block for nextkey */
+    int     keyptr;			/* current key for nextkey */
+    long    blkno;			/* current page to read/write */
+    long    pagbno;			/* current page in pagbuf */
+    char   *pagbuf;			/* page file block buffer */
+    long    dirbno;			/* current block in dirbuf */
+    char   *dirbuf;			/* directory file block buffer */
+}       DBM;
+
+
+/* ************************* */
+
+/*
+ * sdbm - ndbm work-alike hashed database library
+ * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978).
+ * author: oz@nexus.yorku.ca
+ * status: public domain. keep it that way.
+ *
+ * hashing routine
+ */
+
+/*
+ * polynomial conversion ignoring overflows
+ * [this seems to work remarkably well, in fact better
+ * then the ndbm hash function. Replace at your own risk]
+ * use: 65599   nice.
+ *      65587   even better.
+ */
+static long sdbm_hash (char *str, int len)
+{
+    unsigned long n = 0;
+
+#ifdef DUFF
+#define HASHC   n = *str++ + 65599 * n
+    if (len > 0)
+      {
+	  int     loop = (len + 8 - 1) >> 3;
+
+	  switch (len & (8 - 1))
+	    {
+	    case 0:
+		do
+		  {
+		      HASHC;
+	    case 7:
+		      HASHC;
+	    case 6:
+		      HASHC;
+	    case 5:
+		      HASHC;
+	    case 4:
+		      HASHC;
+	    case 3:
+		      HASHC;
+	    case 2:
+		      HASHC;
+	    case 1:
+		      HASHC;
+		  }
+		while (--loop);
+	    }
+
+      }
+#else
+    while (len--)
+	n = *str++ + 65599 * n;
+#endif
+    return n;
+}
+
+/*
+ * check page sanity:
+ * number of entries should be something
+ * reasonable, and all offsets in the index should be in order.
+ * this could be made more rigorous.
+ */
+static int chkpage (char *pag)
+{
+    int     n;
+    int     off;
+    short  *ino = (short *) pag;
+
+    if ((n = ino[0]) < 0 || n > PBLKSIZ / sizeof (short))
+	        return 0;
+
+    if (n > 0)
+      {
+	  off = PBLKSIZ;
+	  for (ino++; n > 0; ino += 2)
+	    {
+		if (ino[0] > off || ino[1] > off ||
+		    ino[1] > ino[0])
+		    return 0;
+		off = ino[1];
+		n -= 2;
+	    }
+      }
+    return 1;
+}
+
+/*
+ * search for the key in the page.
+ * return offset index in the range 0 < i < n.
+ * return 0 if not found.
+ */
+static int seepair (char *pag, int n, char *key, int siz)
+{
+    int     i;
+    int     off = PBLKSIZ;
+    short  *ino = (short *) pag;
+
+    for (i = 1; i < n; i += 2)
+      {
+	  if (siz == off - ino[i] &&
+	      memcmp (key, pag + ino[i], siz) == 0)
+	      return i;
+	  off = ino[i + 1];
+      }
+    return 0;
+}
+
+#ifdef SEEDUPS
+static int duppair (char *pag, datum key)
+{
+    short  *ino = (short *) pag;
+
+    return ino[0] > 0 && seepair (pag, ino[0], key.dptr, key.dsize) > 0;
+}
+
+#endif
+
+/* ************************* */
+
+/*
+ * sdbm - ndbm work-alike hashed database library
+ * based on Per-Aake Larson's Dynamic Hashing algorithms. BIT 18 (1978).
+ * author: oz@nexus.yorku.ca
+ * status: public domain.
+ *
+ * page-level routines
+ */
+
+/*
+ * page format:
+ *      +------------------------------+
+ * ino  | n | keyoff | datoff | keyoff |
+ *      +------------+--------+--------+
+ *      | datoff | - - - ---->         |
+ *      +--------+---------------------+
+ *      |        F R E E A R E A       |
+ *      +--------------+---------------+
+ *      |  <---- - - - | data          |
+ *      +--------+-----+----+----------+
+ *      |  key   | data     | key      |
+ *      +--------+----------+----------+
+ *
+ * calculating the offsets for free area:  if the number
+ * of entries (ino[0]) is zero, the offset to the END of
+ * the free area is the block size. Otherwise, it is the
+ * nth (ino[ino[0]]) entry's offset.
+ */
+
+static int fitpair (char *pag, int need)
+{
+    int     n;
+    int     off;
+    int     avail;
+    short  *ino = (short *) pag;
+
+    off = ((n = ino[0]) > 0) ? ino[n] : PBLKSIZ;
+    avail = off - (n + 1) * sizeof (short);
+    need += 2 * sizeof (short);
+
+    return need <= avail;
+}
+
+static void putpair (char *pag, datum key, datum val)
+{
+    int     n;
+    int     off;
+    short  *ino = (short *) pag;
+
+    off = ((n = ino[0]) > 0) ? ino[n] : PBLKSIZ;
+/*
+ * enter the key first
+ */
+    off -= key.dsize;
+    (void) memcpy (pag + off, key.dptr, key.dsize);
+    ino[n + 1] = off;
+/*
+ * now the data
+ */
+    off -= val.dsize;
+    (void) memcpy (pag + off, val.dptr, val.dsize);
+    ino[n + 2] = off;
+/*
+ * adjust item count
+ */
+    ino[0] += 2;
+}
+
+static datum getpair (char *pag, datum key)
+{
+    int     i;
+    int     n;
+    datum   val;
+    short  *ino = (short *) pag;
+
+    if ((n = ino[0]) == 0)
+	return nullitem;
+
+    if ((i = seepair (pag, n, key.dptr, key.dsize)) == 0)
+	return nullitem;
+
+    val.dptr = pag + ino[i + 1];
+    val.dsize = ino[i] - ino[i + 1];
+    return val;
+}
+
+static datum getnkey (char *pag, int num)
+{
+    datum   key;
+    int     off;
+    short  *ino = (short *) pag;
+
+    num = num * 2 - 1;
+    if (ino[0] == 0 || num > ino[0])
+	return nullitem;
+
+    off = (num > 1) ? ino[num - 1] : PBLKSIZ;
+
+    key.dptr = pag + ino[num];
+    key.dsize = off - ino[num];
+
+    return key;
+}
+
+static int delpair (char *pag, datum key)
+{
+    int     n;
+    int     i;
+    short  *ino = (short *) pag;
+
+    if ((n = ino[0]) == 0)
+	return 0;
+
+    if ((i = seepair (pag, n, key.dptr, key.dsize)) == 0)
+	return 0;
+/*
+ * found the key. if it is the last entry
+ * [i.e. i == n - 1] we just adjust the entry count.
+ * hard case: move all data down onto the deleted pair,
+ * shift offsets onto deleted offsets, and adjust them.
+ * [note: 0 < i < n]
+ */
+    if (i < n - 1)
+      {
+	  int     m;
+	  char   *dst = pag + (i == 1 ? PBLKSIZ : ino[i - 1]);
+	  char   *src = pag + ino[i + 1];
+	  int     zoo = dst - src;
+
+/*
+ * shift data/keys down
+ */
+	  m = ino[i + 1] - ino[n];
+#ifdef DUFF
+#define MOVB    *--dst = *--src
+	  if (m > 0)
+	    {
+		int     loop = (m + 8 - 1) >> 3;
+
+		switch (m & (8 - 1))
+		  {
+		  case 0:
+		      do
+			{
+			    MOVB;
+		  case 7:
+			    MOVB;
+		  case 6:
+			    MOVB;
+		  case 5:
+			    MOVB;
+		  case 4:
+			    MOVB;
+		  case 3:
+			    MOVB;
+		  case 2:
+			    MOVB;
+		  case 1:
+			    MOVB;
+			}
+		      while (--loop);
+		  }
+	    }
+#else
+	  dst -= m;
+	  src -= m;
+	  memmove (dst, src, m);
+#endif
+/*
+ * adjust offset index up
+ */
+	  while (i < n - 1)
+	    {
+		ino[i] = ino[i + 2] + zoo;
+		i++;
+	    }
+      }
+    ino[0] -= 2;
+    return 1;
+}
+
+static void splpage (char *pag, char *new, long sbit)
+{
+    datum   key;
+    datum   val;
+
+    int     n;
+    int     off = PBLKSIZ;
+    char    cur[PBLKSIZ];
+    short  *ino = (short *) cur;
+
+    (void) memcpy (cur, pag, PBLKSIZ);
+    (void) memset (pag, 0, PBLKSIZ);
+    (void) memset (new, 0, PBLKSIZ);
+
+    n = ino[0];
+    for (ino++; n > 0; ino += 2)
+      {
+	  key.dptr = cur + ino[0];
+	  key.dsize = off - ino[0];
+	  val.dptr = cur + ino[1];
+	  val.dsize = ino[0] - ino[1];
+/*
+ * select the page pointer (by looking at sbit) and insert
+ */
+	  (void) putpair ((exhash (key) & sbit) ? new : pag, key, val);
+
+	  off = ino[1];
+	  n -= 2;
+      }
+}
+
+static int getdbit (DBM * db, long dbit)
+{
+    long    c;
+    long    dirb;
+
+    c = dbit / BYTESIZ;
+    dirb = c / DBLKSIZ;
+
+    if (dirb != db->dirbno)
+      {
+	  int got;
+	  if (lseek (db->dirf, OFF_DIR (dirb), SEEK_SET) < 0
+	      || (got = read(db->dirf, db->dirbuf, DBLKSIZ)) < 0)
+	      return 0;
+	  if (got==0)
+              memset(db->dirbuf,0,DBLKSIZ);
+	  db->dirbno = dirb;
+      }
+
+    return db->dirbuf[c % DBLKSIZ] & (1 << dbit % BYTESIZ);
+}
+
+static int setdbit (DBM * db, long dbit)
+{
+    long    c;
+    long    dirb;
+
+    c = dbit / BYTESIZ;
+    dirb = c / DBLKSIZ;
+
+    if (dirb != db->dirbno)
+      {
+	  int got;
+	  if (lseek (db->dirf, OFF_DIR (dirb), SEEK_SET) < 0
+	      || (got = read(db->dirf, db->dirbuf, DBLKSIZ)) < 0)
+	      return 0;
+	  if (got==0)
+              memset(db->dirbuf,0,DBLKSIZ);
+	  db->dirbno = dirb;
+      }
+
+    db->dirbuf[c % DBLKSIZ] |= (1 << dbit % BYTESIZ);
+
+#if 0
+    if (dbit >= db->maxbno)
+	db->maxbno += DBLKSIZ * BYTESIZ;
+#else
+    if (OFF_DIR((dirb+1))*BYTESIZ > db->maxbno)
+        db->maxbno=OFF_DIR((dirb+1))*BYTESIZ;
+#endif
+
+    if (lseek (db->dirf, OFF_DIR (dirb), SEEK_SET) < 0
+	|| write (db->dirf, db->dirbuf, DBLKSIZ) < 0)
+	return 0;
+
+    return 1;
+}
+
+/*
+ * getnext - get the next key in the page, and if done with
+ * the page, try the next page in sequence
+ */
+static datum getnext (DBM * db)
+{
+    datum   key;
+
+    for (;;)
+      {
+	  db->keyptr++;
+	  key = getnkey (db->pagbuf, db->keyptr);
+	  if (key.dptr != NULL)
+	      return key;
+/*
+ * we either run out, or there is nothing on this page..
+ * try the next one... If we lost our position on the
+ * file, we will have to seek.
+ */
+	  db->keyptr = 0;
+	  if (db->pagbno != db->blkptr++)
+	      if (lseek (db->pagf, OFF_PAG (db->blkptr), SEEK_SET) < 0)
+		  break;
+	  db->pagbno = db->blkptr;
+	  if (read (db->pagf, db->pagbuf, PBLKSIZ) <= 0)
+	      break;
+	  if (!chkpage (db->pagbuf))
+	      break;
+      }
+
+    return ioerr (db), nullitem;
+}
+
+/*
+ * all important binary trie traversal
+ */
+static int getpage (DBM * db, long hash)
+{
+    int     hbit;
+    long    dbit;
+    long    pagb;
+
+    dbit = 0;
+    hbit = 0;
+    while (dbit < db->maxbno && getdbit (db, dbit))
+	dbit = 2 * dbit + ((hash & (1 << hbit++)) ? 2 : 1);
+
+    db->curbit = dbit;
+    db->hmask = masks[hbit];
+
+    pagb = hash & db->hmask;
+/*
+ * see if the block we need is already in memory.
+ * note: this lookaside cache has about 10% hit rate.
+ */
+    if (pagb != db->pagbno)
+      {
+/*
+ * note: here, we assume a "hole" is read as 0s.
+ * if not, must zero pagbuf first.
+ */
+	  if (lseek (db->pagf, OFF_PAG (pagb), SEEK_SET) < 0
+	      || read (db->pagf, db->pagbuf, PBLKSIZ) < 0)
+	      return 0;
+	  if (!chkpage (db->pagbuf))
+	      return 0;
+	  db->pagbno = pagb;
+      }
+    return 1;
+}
+
+/*
+ * makroom - make room by splitting the overfull page
+ * this routine will attempt to make room for SPLTMAX times before
+ * giving up.
+ */
+static int makroom (DBM * db, long hash, int need)
+{
+    long    newp;
+    char    twin[PBLKSIZ];
+    char   *pag = db->pagbuf;
+    char   *new = twin;
+    int     smax = SPLTMAX;
+
+    do
+      {
+/*
+ * split the current page
+ */
+	  (void) splpage (pag, new, db->hmask + 1);
+/*
+ * address of the new page
+ */
+	  newp = (hash & db->hmask) | (db->hmask + 1);
+
+/*
+ * write delay, read avoidence/cache shuffle:
+ * select the page for incoming pair: if key is to go to the new page,
+ * write out the previous one, and copy the new one over, thus making
+ * it the current page. If not, simply write the new page, and we are
+ * still looking at the page of interest. current page is not updated
+ * here, as sdbm_store will do so, after it inserts the incoming pair.
+ */
+	  if (hash & (db->hmask + 1))
+	    {
+		if (lseek (db->pagf, OFF_PAG (db->pagbno), SEEK_SET) < 0
+		    || write (db->pagf, db->pagbuf, PBLKSIZ) < 0)
+		    return 0;
+		db->pagbno = newp;
+		(void) memcpy (pag, new, PBLKSIZ);
+	    }
+	  else if (lseek (db->pagf, OFF_PAG (newp), SEEK_SET) < 0
+		   || write (db->pagf, new, PBLKSIZ) < 0)
+	      return 0;
+
+	  if (!setdbit (db, db->curbit))
+	      return 0;
+/*
+ * see if we have enough room now
+ */
+	  if (fitpair (pag, need))
+	      return 1;
+/*
+ * try again... update curbit and hmask as getpage would have
+ * done. because of our update of the current page, we do not
+ * need to read in anything. BUT we have to write the current
+ * [deferred] page out, as the window of failure is too great.
+ */
+	  db->curbit = 2 * db->curbit +
+	      ((hash & (db->hmask + 1)) ? 2 : 1);
+	  db->hmask |= db->hmask + 1;
+
+	  if (lseek (db->pagf, OFF_PAG (db->pagbno), SEEK_SET) < 0
+	      || write (db->pagf, db->pagbuf, PBLKSIZ) < 0)
+	      return 0;
+
+      }
+    while (--smax);
+/*
+ * if we are here, this is real bad news. After SPLTMAX splits,
+ * we still cannot fit the key. say goodnight.
+ */
+#ifdef BADMESS
+    (void) write (2, "sdbm: cannot insert after SPLTMAX attempts.\n", 44);
+#endif
+    return 0;
+
+}
+
+static SDBM *sdbm_prep (char *dirname, char *pagname, int flags, int mode)
+{
+    SDBM   *db;
+    struct stat dstat;
+
+    if ((db = (SDBM *) mymalloc (sizeof (SDBM))) == NULL)
+	return errno = ENOMEM, (SDBM *) NULL;
+
+    db->flags = 0;
+    db->blkptr = 0;
+    db->keyptr = 0;
+/*
+ * adjust user flags so that WRONLY becomes RDWR,
+ * as required by this package. Also set our internal
+ * flag for RDONLY if needed.
+ */
+    if (flags & O_WRONLY)
+	flags = (flags & ~O_WRONLY) | O_RDWR;
+    else if ((flags & 03) == O_RDONLY)
+	db->flags = DBM_RDONLY;
+#if defined(OS2) || defined(MSDOS) || defined(WIN32)
+    flags |= O_BINARY;
+#endif
+
+/*
+ * Make sure to ignore the O_EXCL option, as the file might exist due
+ * to the locking.
+ */
+    flags &= ~O_EXCL;
+
+/*
+ * open the files in sequence, and stat the dirfile.
+ * If we fail anywhere, undo everything, return NULL.
+ */
+
+    if ((db->pagf = open (pagname, flags, mode)) > -1)
+      {
+	  if ((db->dirf = open (dirname, flags, mode)) > -1)
+	    {
+/*
+ * need the dirfile size to establish max bit number.
+ */
+		if (fstat (db->dirf, &dstat) == 0)
+		  {
+		      /*
+                       * success
+                       */
+		      return db;
+		  }
+		msg_info ("closing dirf");
+		(void) close (db->dirf);
+	    }
+	  msg_info ("closing pagf");
+	  (void) close (db->pagf);
+      }
+    myfree ((char *) db);
+    return (SDBM *) NULL;
+}
+
+static DBM *sdbm_internal_open (SDBM * sdbm)
+{
+    DBM    *db;
+    struct stat dstat;
+
+    if ((db = (DBM *) mymalloc (sizeof (DBM))) == NULL)
+	return errno = ENOMEM, (DBM *) NULL;
+
+    db->flags = sdbm->flags;
+    db->hmask = 0;
+    db->blkptr = sdbm->blkptr;
+    db->keyptr = sdbm->keyptr;
+    db->pagf = sdbm->pagf;
+    db->dirf = sdbm->dirf;
+    db->pagbuf = sdbm->pagbuf;
+    db->dirbuf = sdbm->dirbuf;
+
+/*
+ * need the dirfile size to establish max bit number.
+ */
+    if (fstat (db->dirf, &dstat) == 0)
+      {
+/*
+ * zero size: either a fresh database, or one with a single,
+ * unsplit data page: dirpage is all zeros.
+ */
+	  db->dirbno = (!dstat.st_size) ? 0 : -1;
+	  db->pagbno = -1;
+	  db->maxbno = dstat.st_size * BYTESIZ;
+
+	  (void) memset (db->pagbuf, 0, PBLKSIZ);
+	  (void) memset (db->dirbuf, 0, DBLKSIZ);
+	  return db;
+      }
+    myfree ((char *) db);
+    return (DBM *) NULL;
+}
+
+static void sdbm_internal_close (DBM * db)
+{
+    if (db == NULL)
+	errno = EINVAL;
+    else
+      {
+	  myfree ((char *) db);
+      }
+}
+
+datum   sdbm_fetch (SDBM * sdb, datum key)
+{
+    datum   retval;
+    DBM    *db;
+
+    if (sdb == NULL || bad (key))
+	return errno = EINVAL, nullitem;
+
+    if (!(db = sdbm_internal_open (sdb)))
+	return errno = EINVAL, nullitem;
+
+    if (getpage (db, exhash (key)))
+      {
+	  retval = getpair (db->pagbuf, key);
+	  sdbm_internal_close (db);
+	  return retval;
+      }
+
+    sdbm_internal_close (db);
+
+    return ioerr (sdb), nullitem;
+}
+
+int     sdbm_delete (SDBM * sdb, datum key)
+{
+    int     retval;
+    DBM    *db;
+
+    if (sdb == NULL || bad (key))
+	return errno = EINVAL, -1;
+    if (sdbm_rdonly (sdb))
+	return errno = EPERM, -1;
+
+    if (!(db = sdbm_internal_open (sdb)))
+	return errno = EINVAL, -1;
+
+    if (getpage (db, exhash (key)))
+      {
+	  if (!delpair (db->pagbuf, key))
+	      retval = -1;
+/*
+ * update the page file
+ */
+	  else if (lseek (db->pagf, OFF_PAG (db->pagbno), SEEK_SET) < 0
+		   || write (db->pagf, db->pagbuf, PBLKSIZ) < 0)
+	      retval = ioerr (sdb), -1;
+	  else
+	      retval = 0;
+      }
+    else
+	retval = ioerr (sdb), -1;
+
+    sdbm_internal_close (db);
+
+    return retval;
+}
+
+int     sdbm_store (SDBM * sdb, datum key, datum val, int flags)
+{
+    int     need;
+    int     retval;
+    long    hash;
+    DBM    *db;
+
+    if (sdb == NULL || bad (key))
+	return errno = EINVAL, -1;
+    if (sdbm_rdonly (sdb))
+	return errno = EPERM, -1;
+
+    need = key.dsize + val.dsize;
+/*
+ * is the pair too big (or too small) for this database ??
+ */
+    if (need < 0 || need > PAIRMAX)
+	return errno = EINVAL, -1;
+
+    if (!(db = sdbm_internal_open (sdb)))
+	return errno = EINVAL, -1;
+
+    if (getpage (db, (hash = exhash (key))))
+      {
+/*
+ * if we need to replace, delete the key/data pair
+ * first. If it is not there, ignore.
+ */
+	  if (flags == DBM_REPLACE)
+	      (void) delpair (db->pagbuf, key);
+#ifdef SEEDUPS
+	  else if (duppair (db->pagbuf, key))
+	    {
+		sdbm_internal_close (db);
+		return 1;
+	    }
+#endif
+/*
+ * if we do not have enough room, we have to split.
+ */
+	  if (!fitpair (db->pagbuf, need))
+	      if (!makroom (db, hash, need))
+		{
+		    sdbm_internal_close (db);
+		    return ioerr (db), -1;
+		}
+/*
+ * we have enough room or split is successful. insert the key,
+ * and update the page file.
+ */
+	  (void) putpair (db->pagbuf, key, val);
+
+	  if (lseek (db->pagf, OFF_PAG (db->pagbno), SEEK_SET) < 0
+	      || write (db->pagf, db->pagbuf, PBLKSIZ) < 0)
+	    {
+		sdbm_internal_close (db);
+		return ioerr (db), -1;
+	    }
+	  /*
+           * success
+           */
+	  sdbm_internal_close (db);
+	  return 0;
+      }
+
+    sdbm_internal_close (db);
+    return ioerr (sdb), -1;
+}
+
+/*
+ * the following two routines will break if
+ * deletions aren't taken into account. (ndbm bug)
+ */
+datum   sdbm_firstkey (SDBM * sdb)
+{
+    datum   retval;
+    DBM    *db;
+
+    if (sdb == NULL)
+	return errno = EINVAL, nullitem;
+
+    if (!(db = sdbm_internal_open (sdb)))
+	return errno = EINVAL, nullitem;
+
+/*
+ * start at page 0
+ */
+    if (lseek (db->pagf, OFF_PAG (0), SEEK_SET) < 0
+	|| read (db->pagf, db->pagbuf, PBLKSIZ) < 0)
+      {
+	  sdbm_internal_close (db);
+	  return ioerr (sdb), nullitem;
+      }
+    db->pagbno = 0;
+    db->blkptr = 0;
+    db->keyptr = 0;
+
+    retval = getnext (db);
+    sdb->blkptr = db->blkptr;
+    sdb->keyptr = db->keyptr;
+    sdbm_internal_close (db);
+    return retval;
+}
+
+datum   sdbm_nextkey (SDBM * sdb)
+{
+    datum   retval;
+    DBM    *db;
+
+    if (sdb == NULL)
+	return errno = EINVAL, nullitem;
+
+    if (!(db = sdbm_internal_open (sdb)))
+	return errno = EINVAL, nullitem;
+
+    retval = getnext (db);
+    sdb->blkptr = db->blkptr;
+    sdb->keyptr = db->keyptr;
+    sdbm_internal_close (db);
+    return retval;
+}
+
+void    sdbm_close (SDBM * db)
+{
+    if (db == NULL)
+	errno = EINVAL;
+    else
+      {
+	  (void) close (db->dirf);
+	  (void) close (db->pagf);
+	  myfree ((char *) db);
+      }
+}
+
+SDBM   *sdbm_open (char *file, int flags, int mode)
+{
+    SDBM   *db;
+    char   *dirname;
+    char   *pagname;
+    int     n;
+
+    if (file == NULL || !*file)
+	return errno = EINVAL, (SDBM *) NULL;
+/*
+ * need space for two seperate filenames
+ */
+    n = strlen (file) * 2 + strlen (DIRFEXT) + strlen (PAGFEXT) + 2;
+
+    if ((dirname = (char *) mymalloc ((unsigned) n)) == NULL)
+	return errno = ENOMEM, (SDBM *) NULL;
+/*
+ * build the file names
+ */
+    dirname = strcat (strcpy (dirname, file), DIRFEXT);
+    pagname = strcpy (dirname + strlen (dirname) + 1, file);
+    pagname = strcat (pagname, PAGFEXT);
+
+    db = sdbm_prep (dirname, pagname, flags, mode);
+    myfree ((char *) dirname);
+    return db;
+}
+
diff -r -u --new-file postfix-1.1.0-vanilla/src/util/sdbm.h postfix-1.1.0/src/util/sdbm.h
--- postfix-1.1.0-vanilla/src/util/sdbm.h	Thu Jan  1 01:00:00 1970
+++ postfix-1.1.0/src/util/sdbm.h	Thu Jan 17 21:30:51 2002
@@ -0,0 +1,97 @@
+/*++
+/* NAME
+/*      sdbm 3h
+/* SUMMARY
+/*      SDBM Simple DBM: ndbm work-alike hashed database library
+/* SYNOPSIS
+/*      include "sdbm.h"
+/* DESCRIPTION
+/* .nf
+/*--*/
+
+#ifndef UTIL_SDBM_H
+#define UTIL_SDBM_H
+
+/*
+ * sdbm - ndbm work-alike hashed database library
+ * based on Per-Ake Larson's Dynamic Hashing algorithms. BIT 18 (1978).
+ * author: oz@nexus.yorku.ca
+ * status: public domain.
+ */
+
+#define DUFF    /* go ahead and use the loop-unrolled version */
+
+#include <stdio.h>
+
+#define DBLKSIZ 16384                   /* SSL cert chains require more */
+#define PBLKSIZ 8192                    /* SSL cert chains require more */
+#define PAIRMAX 8008                    /* arbitrary on PBLKSIZ-N */
+#define SPLTMAX 10                      /* maximum allowed splits */
+                                        /* for a single insertion */
+#define DIRFEXT ".dir"
+#define PAGFEXT ".pag"
+
+typedef struct {
+        int dirf;                      /* directory file descriptor */
+        int pagf;                      /* page file descriptor */
+        int flags;                     /* status/error flags, see below */
+        long blkptr;                   /* current block for nextkey */
+        int keyptr;                    /* current key for nextkey */
+        char pagbuf[PBLKSIZ];          /* page file block buffer */
+        char dirbuf[DBLKSIZ];          /* directory file block buffer */
+} SDBM;
+
+#define DBM_RDONLY      0x1            /* data base open read-only */
+#define DBM_IOERR       0x2            /* data base I/O error */
+
+/*
+ * utility macros
+ */
+#define sdbm_rdonly(db)         ((db)->flags & DBM_RDONLY)
+#define sdbm_error(db)          ((db)->flags & DBM_IOERR)
+
+#define sdbm_clearerr(db)       ((db)->flags &= ~DBM_IOERR)  /* ouch */
+
+#define sdbm_dirfno(db) ((db)->dirf)
+#define sdbm_pagfno(db) ((db)->pagf)
+
+typedef struct {
+        char *dptr;
+        int dsize;
+} datum;
+
+extern datum nullitem;
+
+/*
+ * flags to sdbm_store
+ */
+#define DBM_INSERT      0
+#define DBM_REPLACE     1
+
+/*
+ * ndbm interface
+ */
+extern SDBM *sdbm_open(char *, int, int);
+extern void sdbm_close(SDBM *);
+extern datum sdbm_fetch(SDBM *, datum);
+extern int sdbm_delete(SDBM *, datum);
+extern int sdbm_store(SDBM *, datum, datum, int);
+extern datum sdbm_firstkey(SDBM *);
+extern datum sdbm_nextkey(SDBM *);
+
+/*
+ * sdbm - ndbm work-alike hashed database library
+ * tuning and portability constructs [not nearly enough]
+ * author: oz@nexus.yorku.ca
+ */
+
+#define BYTESIZ         8
+
+/*
+ * important tuning parms (hah)
+ */
+
+#define SEEDUPS                 /* always detect duplicates */
+#define BADMESS                 /* generate a message for worst case:
+                                   cannot make room after SPLTMAX splits */
+#endif /* UTIL_SDBM_H */
diff -r -u --new-file postfix-1.1.0-vanilla/src/util/vstream.c postfix-1.1.0/src/util/vstream.c
--- postfix-1.1.0-vanilla/src/util/vstream.c	Mon Sep 10 02:39:23 2001
+++ postfix-1.1.0/src/util/vstream.c	Thu Jan 17 21:30:51 2002
@@ -72,6 +72,9 @@
 /*	int	vstream_fileno(stream)
 /*	VSTREAM	*stream;
 /*
+/*	void	*vstream_context(stream)
+/*	VSTREAM *stream;
+/*
 /*	int	vstream_ferror(stream)
 /*	VSTREAM	*stream;
 /*
@@ -249,6 +252,9 @@
 /*	vstream_fileno() gives access to the file handle associated with
 /*	a buffered stream. With streams that have separate read/write
 /*	file descriptors, the result is the current descriptor.
+/*
+/*	vstream_context() returns the application context that is passed on to
+/*	the application-specified read/write routines.
 /*
 /*	VSTREAM_PATH() is an unsafe macro that returns the name stored
 /*	with vstream_fopen() or with vstream_control(). The macro is
diff -r -u --new-file postfix-1.1.0-vanilla/src/util/vstream.h postfix-1.1.0/src/util/vstream.h
--- postfix-1.1.0-vanilla/src/util/vstream.h	Sat Dec  9 01:06:10 2000
+++ postfix-1.1.0/src/util/vstream.h	Thu Jan 17 21:30:51 2002
@@ -90,6 +90,7 @@
 #define VSTREAM_GETCHAR()	VSTREAM_GETC(VSTREAM_IN)
 
 #define vstream_fileno(vp)	((vp)->fd)
+#define vstream_context(vp)	((vp)->context)
 #define vstream_ferror(vp)	vbuf_error(&(vp)->buf)
 #define vstream_feof(vp)	vbuf_eof(&(vp)->buf)
 #define vstream_ftimeout(vp)	vbuf_timeout(&(vp)->buf)