File: pam_ldap.c

package info (click to toggle)
libpam-ldap 140-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 644 kB
  • ctags: 271
  • sloc: ansic: 3,168; sh: 2,267; perl: 156; makefile: 67
file content (3357 lines) | stat: -rw-r--r-- 83,101 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
/*
 * Copyright (C) 1998, 1999, 2000 Luke Howard.
 * This file is part of the pam_ldap library.
 * Contributed by Luke Howard, <lukeh@padl.com>, 1998.
 *
 * The pam_ldap library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * The pam_ldap library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with the pam_ldap library; see the file COPYING.LIB.  If not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*
 * Portions Copyright Andrew Morgan, 1996.  All rights reserved.
 * Modified by Alexander O. Yuriev
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, and the entire permission notice in its entirety,
 *    including the disclaimer of warranties.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior
 *    written permission.
 *
 * ALTERNATIVELY, this product may be distributed under the terms of
 * the GNU Public License, in which case the provisions of the GPL are
 * required INSTEAD OF the above restrictions.  (This clause is
 * necessary due to a potential bad interaction between the GPL and
 * the restrictions contained in a BSD-style copyright.)
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Portions by Elliot Lee <sopwith@redhat.com>, Red Hat Software.
 * Copyright (C) 1996.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, and the entire permission notice in its entirety,
 *    including the disclaimer of warranties.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior
 *    written permission.
 *
 * ALTERNATIVELY, this product may be distributed under the terms of
 * the GNU Public License, in which case the provisions of the GPL are
 * required INSTEAD OF the above restrictions.  (This clause is
 * necessary due to a potential bad interaction between the GPL and
 * the restrictions contained in a BSD-style copyright.)
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/param.h>
#include <unistd.h>
#include <syslog.h>
#include <netdb.h>
#include <errno.h>

#if defined(HAVE_CRYPT_H)
#include <crypt.h>
#elif defined(HAVE_DES_H)
#include <des.h>
#endif

#ifdef HAVE_LBER_H
#include <lber.h>
#endif
#ifdef HAVE_LDAP_H
#include <ldap.h>
#endif
#ifdef HAVE_LDAP_SSL_H
#include <ldap_ssl.h>
#endif

// I see no way out of this, unless there are major
// rewrites to source. sorry SSL users.
#undef LDAP_OPT_X_TLS

#ifdef YPLDAPD
#include <rpcsvc/yp_prot.h>
#include <rpcsvc/ypclnt.h>
#endif /* YPLDAPD */

#include "pam_ldap.h"
#include "md5.h"

#ifdef HAVE_SECURITY_PAM_MISC_H
 /* FIXME: is there something better to check? */
#define CONST_ARG const
#else
#define CONST_ARG
#endif

#ifndef HAVE_LDAP_MEMFREE
#define ldap_memfree(x)	free(x)
#endif

#ifdef __GNUC__
#define __UNUSED__ __attribute__ ((unused))
#else
#define __UNUSED__
#endif

static char rcsid[] __UNUSED__ =
  "$Id: pam_ldap.c,v 1.143 2002/03/06 08:46:49 lukeh Exp $";
#if LDAP_SET_REBIND_PROC_ARGS < 3
static pam_ldap_session_t *global_session = 0;
#endif
static int pam_debug_level __UNUSED__ = 0;

#ifdef HAVE_LDAPSSL_INIT
static int ssl_initialized = 0;
#endif

#ifdef __GNUC__
#define DEBUG_MSG(level, fmt, args...)		\
	do {					\
		if (level >= pam_debug_level)	\
			syslog(LOG_DEBUG, "%s:%i " fmt , __FUNCTION__ , __LINE__ , ## args); \
	} while (0)
#else
#define DEBUG_MSG(level, fmt, ...)            \
      do {                                    \
              if (level >= pam_debug_level)   \
                      syslog(LOG_DEBUG, "%s:%i " fmt , __FUNCTION__ , __LINE__ , __VA_ARGS__); \
      } while (0)
#endif /* __GNUC__ */

static int i64c (int i);

#ifndef HAVE_LDAP_GET_LDERRNO
static int ldap_get_lderrno (LDAP * ld, char **m, char **s);
#endif

static void _release_config (pam_ldap_config_t ** pconfig);
static void _release_user_info (pam_ldap_user_info_t ** info);
static void _pam_ldap_cleanup_session (pam_handle_t * pamh, void *data,
				       int error_status);
static void _cleanup_data (pam_handle_t * pamh, void *data, int error_status);
static void _cleanup_authtok_data (pam_handle_t * pamh, void *data,
				   int error_status);
static int _alloc_config (pam_ldap_config_t ** presult);
#ifdef YPLDAPD
static int _ypldapd_read_config (pam_ldap_config_t ** presult);
#endif
static int _read_config (const char *configFile, const char *extraFilter,
			 pam_ldap_config_t ** presult);
static int _open_session (pam_ldap_session_t * session);

/* TLS routines */
#if defined HAVE_LDAP_START_TLS_S || (defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS))
static int _set_ssl_default_options (pam_ldap_session_t *);
static int _set_ssl_options (pam_ldap_session_t *);
#endif

static int _connect_anonymously (pam_ldap_session_t * session);
#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
#if LDAP_SET_REBIND_PROC_ARGS == 3
static int _rebind_proc (LDAP * ld, LDAP_CONST char *url, ber_tag_t request,
			 ber_int_t msgid, void *arg);
#else
static int _rebind_proc (LDAP * ld, LDAP_CONST char *url, int request,
			 ber_int_t msgid);
#endif
#else
#if LDAP_SET_REBIND_PROC_ARGS == 3
static int _rebind_proc (LDAP * ld,
			 char **whop, char **credp, int *methodp, int freeit,
			 void *arg);
#else
static int _rebind_proc (LDAP * ld, char **whop, char **credp, int *methodp,
			 int freeit);
#endif
#endif


static int _connect_as_user (pam_ldap_session_t * session,
			     const char *password);
static int _get_integer_value (LDAP * ld, LDAPMessage * e, const char *attr,
			       int *ptr);
static int _get_long_integer_value (LDAP * ld, LDAPMessage * e,
				    const char *attr, long int *ptr);
static int _get_string_value (LDAP * ld, LDAPMessage * e, const char *attr,
			      char **ptr);
static int _get_string_values (LDAP * ld, LDAPMessage * e, const char *attr,
			       char ***ptr);
static int _has_value (char **src, const char *tgt);
static int _host_ok (pam_ldap_session_t * session);


static char *_get_md5_salt (char saltbuf[16]);
static char *_get_salt (char salt[16]);
static int _escape_string (const char *str, char *buf, size_t buflen);
static int _get_user_info (pam_ldap_session_t * session, const char *user);
static int _pam_ldap_get_session (pam_handle_t * pamh, const char *username,
				  const char *configFile,
				  const char *extraFilter, 
				  pam_ldap_session_t ** psession);
static int _reopen (pam_ldap_session_t * session);
static int _get_password_policy (pam_ldap_session_t * session,
				 pam_ldap_password_policy_t * policy);
static int _do_authentication (pam_ldap_session_t * session,
			       const char *user, const char *password);
static int _update_authtok (pam_ldap_session_t * session,
			    const char *user,
			    const char *old_password,
			    const char *new_password);
static int _get_authtok (pam_handle_t * pamh, int flags, int first);
static int _conv_sendmsg (struct pam_conv *aconv,
			  const char *message, int style, int no_warn);


#ifdef HAVE_LIBPTHREAD
#include <dlfcn.h>

/*
 * on Linux at least, the pthread library registers an atexit
 * handler in it's constructor.  Since we are in a library and linking with
 * libpthread, if the client program is not linked with libpthread, it
 * segfaults on exit. So we open an extra reference to the library.
 * 
 * If there is a better way of doing this, let us know.
 */
#ifdef __GNUC__
void nasty_pthread_hack (void) __attribute__ ((constructor));
#else
# ifdef __SUNPRO_C
#  pragma init(nasty_pthread_hack)
# endif				/* __SUNPRO_C */
#endif /* __GNUC__ */

void
nasty_pthread_hack (void)
{
  (void) dlopen ("libpthread.so", RTLD_LAZY);
}
#endif /* HAVE_LIBPTHREAD */

#ifdef HAVE_LDAPSSL_INIT
/*
 * We need to keep ourselves loaded so that ssl_initialized
 * is set across PAM sessions.
 */
#ifdef __GNUC__
void nasty_ssl_hack (void) __attribute__ ((constructor));
#else
# ifdef __SUNPRO_C
#  pragma init(nasty_ssl_hack)
# endif				/* __SUNPRO_C */
#endif /* __GNUC__ */

void
nasty_ssl_hack (void)
{
  (void) dlopen ("/lib/security/pam_ldap.so", RTLD_LAZY);
}
#endif /* HAVE_LDAPSSL_INIT */

/* i64c - convert an integer to a radix 64 character */
static int
i64c (int i)
{
  const char *base64 =
    "./01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  if (i < 0)
    i = 0;
  else if (i > 63)
    i = 63;

  return base64[i];
}

#ifndef HAVE_LDAP_GET_LDERRNO
static int
ldap_get_lderrno (LDAP * ld, char **m, char **s)
{
#ifdef HAVE_LDAP_GET_OPTION
  int rc;
#endif
  int lderrno;

#if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
  /* is this needed? */
  rc = ldap_get_option (ld, LDAP_OPT_ERROR_NUMBER, &lderrno);
  if (rc != LDAP_SUCCESS)
    return rc;
#else
  lderrno = ld->ld_errno;
#endif

  if (s != NULL)
    {
#if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_STRING)
      rc = ldap_get_option (ld, LDAP_OPT_ERROR_STRING, &s);
      if (rc != LDAP_SUCCESS)
	return rc;
#else
      *s = ld->ld_error;
#endif
    }

  if (m != NULL)
    {
      *m = NULL;
    }

  return lderrno;
}
#endif

static void
_release_config (pam_ldap_config_t ** pconfig)
{
  pam_ldap_config_t *c;

  c = *pconfig;
  if (c == NULL)
    return;

  if (c->configFile != NULL)
    free (c->configFile);

  if (c->host != NULL)
    free (c->host);

  if (c->base != NULL)
    free (c->base);

  if (c->binddn != NULL)
    free (c->binddn);

  if (c->bindpw != NULL)
    {
      _pam_overwrite (c->bindpw);
      _pam_drop (c->bindpw);
    }

  if (c->rootbinddn != NULL)
    free (c->rootbinddn);

  if (c->rootbindpw != NULL)
    {
      _pam_overwrite (c->rootbindpw);
      _pam_drop (c->rootbindpw);
    }

  if (c->sslpath != NULL)
    {
      free (c->sslpath);
    }

  if (c->userattr != NULL)
    {
      free (c->userattr);
    }

  if (c->tmplattr != NULL)
    {
      free (c->tmplattr);
    }

  if (c->tmpluser != NULL)
    {
      free (c->tmpluser);
    }

  if (c->groupattr != NULL)
    {
      free (c->groupattr);
    }

  if (c->groupdn != NULL)
    {
      free (c->groupdn);
    }

  if (c->filter != NULL)
    {
      free (c->filter);
    }

  memset (c, 0, sizeof (*c));
  free (c);
  *pconfig = NULL;

  return;
}

static void
_release_user_info (pam_ldap_user_info_t ** info)
{
  if (*info == NULL)
    return;

  if ((*info)->userdn != NULL)
    {
      ldap_memfree ((void *) (*info)->userdn);
    }

  /*
   * Clobber the password.
   */
  _pam_overwrite ((*info)->userpw);
  _pam_drop ((*info)->userpw);

  if ((*info)->hosts_allow != NULL)
    {
      ldap_value_free ((*info)->hosts_allow);
    }

  if ((*info)->tmpluser != NULL)
    {
      free ((void *) (*info)->tmpluser);
    }

  free ((void *) (*info)->username);
  free (*info);

  *info = NULL;
  return;
}

static void
_pam_ldap_cleanup_session (pam_handle_t * pamh, void *data, int error_status)
{
  pam_ldap_session_t *session = (pam_ldap_session_t *) data;

  if (session == NULL)
    return;

  if (session->ld != NULL)
    {
      ldap_unbind (session->ld);
      session->ld = NULL;
    }

  _release_config (&session->conf);
  _release_user_info (&session->info);

  free (data);
#if LDAP_SET_REBIND_PROC_ARGS < 3
  global_session = 0;
#endif

  return;
}

static void
_cleanup_data (pam_handle_t * pamh, void *data, int error_status)
{
  if (data != NULL)
    free (data);

  return;
}

static void
_cleanup_authtok_data (pam_handle_t * pamh, void *data, int error_status)
{
  _pam_overwrite ((char *) data);
  _pam_drop (data);

  return;
}

static int
_alloc_config (pam_ldap_config_t ** presult)
{
  pam_ldap_config_t *result;

  if (*presult == NULL)
    {
      *presult = (pam_ldap_config_t *) calloc (1, sizeof (*result));
      if (*presult == NULL)
	return PAM_BUF_ERR;
    }

  result = *presult;

  result->scope = LDAP_SCOPE_SUBTREE;
  result->deref = LDAP_DEREF_NEVER;
  result->configFile = NULL;
  result->host = NULL;
  result->base = NULL;
  result->port = 0;
  result->binddn = NULL;
  result->bindpw = NULL;
  result->rootbinddn = NULL;
  result->rootbindpw = NULL;
  result->ssl_on = SSL_OFF;
  result->sslpath = NULL;
  result->filter = NULL;
  result->userattr = NULL;
  result->groupattr = NULL;
  result->groupdn = NULL;
  result->getpolicy = 0;
  result->checkhostattr = 0;
#ifdef LDAP_VERSION3
  result->version = LDAP_VERSION3;
#else
  result->version = LDAP_VERSION2;
#endif /* LDAP_VERSION2 */
  result->timelimit = LDAP_NO_LIMIT;
  result->bind_timelimit = 10;
  result->referrals = 1;
  result->restart = 1;
  result->password_type = PASSWORD_CLEAR;
  result->min_uid = 0;
  result->max_uid = 0;
  result->tmplattr = NULL;
  result->tmpluser = NULL;
  result->tls_checkpeer = 0;
  result->tls_cacertfile = NULL;
  result->tls_cacertdir = NULL;
  result->tls_ciphers = NULL;
  result->tls_cert = NULL;
  result->tls_key = NULL;
  return PAM_SUCCESS;
}


#ifdef YPLDAPD
/*
 * Use the "internal" ypldapd.conf map to figure some things
 * out.
 */
static int
_ypldapd_read_config (pam_ldap_config_t ** presult)
{
  pam_ldap_config_t *result;
  char *domain;
  int len;
  char *tmp;

  if (_alloc_config (presult) != PAM_SUCCESS)
    {
      return PAM_BUF_ERR;
    }

  result = *presult;

  yp_get_default_domain (&domain);
  yp_bind (domain);
  if (yp_match (domain,
		"ypldapd.conf",
		"ldaphost", sizeof ("ldaphost") - 1, &tmp, &len))
    {
      return PAM_SERVICE_ERR;
    }

  result->host = (char *) malloc (len + 1);
  if (result->host == NULL)
    return PAM_BUF_ERR;

  memcpy (result->host, tmp, len);
  result->host[len] = '\0';
  free (tmp);

  if (yp_match (domain,
		"ypldapd.conf", "basedn", sizeof ("basedn") - 1, &tmp, &len))
    {
      result->base = NULL;
    }
  else
    {
      result->base = (char *) malloc (len + 1);
      if (result->base == NULL)
	return PAM_BUF_ERR;
      memcpy (result->base, tmp, len);
      result->base[len] = '\0';
      free (tmp);
    }

  if (yp_match (domain,
		"ypldapd.conf",
		"ldapport", sizeof ("ldapport") - 1, &tmp, &len))
    {
      result->port = LDAP_PORT;
    }
  else
    {
      char *p = (char *) malloc (len + 1);
      if (p == NULL)
	return PAM_BUF_ERR;
      memcpy (p, tmp, len);
      result->port = atoi (p);
      free (tmp);
      free (p);
    }

  yp_unbind (domain);

  result->userattr = strdup ("uid");
  if (result->userattr == NULL)
    {
      return PAM_BUF_ERR;
    }

  /* turn on getting policies */
  result->getpolicy = 1;
#ifdef LDAP_VERSION3
  result->version = LDAP_VERSION3;
#endif

  return PAM_SUCCESS;
}
#endif /* YPLDAPD */

#define CHECKPOINTER(ptr) do { if ((ptr) == NULL) { \
    fclose(fp); \
    return PAM_BUF_ERR; \
} \
} while (0)

static int
_read_config (const char *configFile, const char *extraFilter, 
		pam_ldap_config_t ** presult)
{
  /* this is the same configuration file as nss_ldap */
  FILE *fp;
  char b[BUFSIZ];
  char *defaultBase, *passwdBase, *defaultFilter, *passwdFilter;
  int defaultScope, passwdScope;
  pam_ldap_config_t *result;
  char errmsg[MAXPATHLEN + 25];

  if (_alloc_config (presult) != PAM_SUCCESS)
    {
      return PAM_BUF_ERR;
    }

  result = *presult;

  /* configuration file location is configurable; default /etc/ldap.conf */
  if (configFile == NULL)
    {
      configFile = PAM_LDAP_PATH_CONF;
      result->configFile = NULL;
    }
  else
    {
      result->configFile = strdup (configFile);
      if (result->configFile == NULL)
	return PAM_BUF_ERR;
    }

  fp = fopen (configFile, "r");

  if (fp == NULL)
    {
      /* 
       * According to PAM Documentation, such an error in a config file
       * SHOULD be logged at LOG_ALERT level
       */
      snprintf (errmsg, sizeof (errmsg), "pam_ldap: missing file \"%s\"",
		configFile);
      syslog (LOG_ALERT, errmsg);
      return PAM_SERVICE_ERR;
    }

  defaultBase = NULL;
  defaultFilter = NULL;
  defaultScope = LDAP_SCOPE_SUBTREE;

  passwdBase = NULL;
  passwdFilter = NULL;
  passwdScope = -1;

  while (fgets (b, sizeof (b), fp) != NULL)
    {
      char *k, *v;
      int len;

      if (*b == '\n' || *b == '#')
	continue;

      k = b;
      v = k;
      while (*v != '\0' && *v != ' ' && *v != '\t')
	v++;

      if (*v == '\0')
	continue;

      *(v++) = '\0';

      /* skip all whitespaces between keyword and value */
      /* Lars Oergel <lars.oergel@innominate.de>, 05.10.2000 */
      while (*v == ' ' || *v == '\t')
	v++;

      /* kick off all whitespaces and newline at the end of value */
      /* Bob Guo <bob@mail.ied.ac.cn>, 08.10.2001 */
      len = strlen (v) - 1;
      while (v[len] == ' ' || v[len] == '\t' || v[len] == '\n')
	--len;
      v[len + 1] = '\0';

      if (!strcasecmp (k, "host"))
	{
	  CHECKPOINTER (result->host = strdup (v));
	}
      else if (!strcasecmp (k, "uri"))
	{
	  CHECKPOINTER (result->uri = strdup (v));
	}
      else if (!strcasecmp (k, "base"))
	{
	  CHECKPOINTER (defaultBase = strdup (v));
	}
      else if (!strcasecmp (k, "binddn"))
	{
	  CHECKPOINTER (result->binddn = strdup (v));
	}
      else if (!strcasecmp (k, "bindpw"))
	{
	  CHECKPOINTER (result->bindpw = strdup (v));
	}
      else if (!strcasecmp (k, "rootbinddn"))
	{
	  CHECKPOINTER (result->rootbinddn = strdup (v));
	}
      else if (!strcasecmp (k, "scope"))
	{
	  if (!strncasecmp (v, "sub", 3))
	    result->scope = LDAP_SCOPE_SUBTREE;
	  else if (!strncasecmp (v, "one", 3))
	    result->scope = LDAP_SCOPE_ONELEVEL;
	  else if (!strncasecmp (v, "base", 4))
	    result->scope = LDAP_SCOPE_BASE;
	}
      else if (!strcasecmp (k, "deref"))
	{
	  if (!strcasecmp (v, "never"))
	    result->deref = LDAP_DEREF_NEVER;
	  else if (!strcasecmp (v, "searching"))
	    result->deref = LDAP_DEREF_SEARCHING;
	  else if (!strcasecmp (v, "finding"))
	    result->deref = LDAP_DEREF_FINDING;
	  else if (!strcasecmp (v, "always"))
	    result->deref = LDAP_DEREF_ALWAYS;
	}
      else if (!strcasecmp (k, "pam_password"))
	{
	  if (!strcasecmp (v, "clear"))
	    result->password_type = PASSWORD_CLEAR;
	  else if (!strcasecmp (v, "crypt"))
	    result->password_type = PASSWORD_CRYPT;
	  else if (!strcasecmp (v, "md5"))
	    result->password_type = PASSWORD_MD5;
	  else if (!strcasecmp (v, "nds"))
	    result->password_type = PASSWORD_NDS;
	  else if (!strcasecmp (v, "ad"))
	    result->password_type = PASSWORD_AD;
	  else if (!strcasecmp (v, "exop"))
	    result->password_type = PASSWORD_EXOP;
	}
      else if (!strcasecmp (k, "pam_crypt"))
	{
	  /*
	   * we still support this even though it is 
	   * deprecated, as it could be a security
	   * hole to change this behaviour on 
	   * unsuspecting users of pam_ldap.
	   */
	  if (!strcasecmp (v, "local"))
	    result->password_type = PASSWORD_CRYPT;
	  else
	    result->password_type = PASSWORD_CLEAR;
	}
      else if (!strcasecmp (k, "port"))
	{
	  result->port = atoi (v);
	}
      else if (!strcasecmp (k, "timelimit"))
	{
	  result->timelimit = atoi (v);
	}
      else if (!strcasecmp (k, "bind_timelimit"))
	{
	  result->bind_timelimit = atoi (v);
	}
      else if (!strcasecmp (k, "nss_base_passwd"))
	{
	  char *s;

	  /* this doesn't do any escaping. XXX. */
	  CHECKPOINTER (passwdBase = strdup (v));
	  s = strchr (passwdBase, '?');
	  if (s != NULL)
	    {
	      *s = '\0';
	      s++;
	      if (!strcasecmp (s, "sub"))
		passwdScope = LDAP_SCOPE_SUBTREE;
	      else if (!strcasecmp (s, "one"))
		passwdScope = LDAP_SCOPE_ONELEVEL;
	      else if (!strcasecmp (s, "base"))
		passwdScope = LDAP_SCOPE_BASE;
	      s = strchr (s, '?');
	      if (s != NULL)
		{
		  *s = '\0';
		  s++;
		  CHECKPOINTER (passwdFilter = strdup (s));
		}
	    }
	}
      else if (!strcasecmp (k, "ldap_version"))
	{
	  result->version = atoi (v);
	}
      else if (!strcasecmp (k, "sslpath"))
	{
	  CHECKPOINTER (result->sslpath = strdup (v));
	}
      else if (!strcasecmp (k, "ssl"))
	{
	  if (!strcasecmp (v, "on") || !strcasecmp (v, "yes")
	      || !strcasecmp (v, "true"))
	    {
	      result->ssl_on = SSL_LDAPS;
	    }
	  else if (!strcasecmp (v, "start_tls"))
	    {
	      result->ssl_on = SSL_START_TLS;
	    }
	}
      else if (!strcasecmp (k, "referrals"))
	{
	  result->referrals = (!strcasecmp (v, "on") || !strcasecmp (v, "yes")
			       || !strcasecmp (v, "true"));
	}
      else if (!strcasecmp (k, "restart"))
	{
	  result->restart = (!strcasecmp (v, "on") || !strcasecmp (v, "yes")
			     || !strcasecmp (v, "true"));
	}
      else if (!strcasecmp (k, "pam_filter"))
	{
	  CHECKPOINTER (defaultFilter = strdup (v));
	}
      else if (!strcasecmp (k, "pam_login_attribute"))
	{
	  CHECKPOINTER (result->userattr = strdup (v));
	}
      else if (!strcasecmp (k, "pam_template_login_attribute"))
	{
	  CHECKPOINTER (result->tmplattr = strdup (v));
	}
      else if (!strcasecmp (k, "pam_template_login"))
	{
	  CHECKPOINTER (result->tmpluser = strdup (v));
	}
      else if (!strcasecmp (k, "pam_lookup_policy"))
	{
	  result->getpolicy = !strcasecmp (v, "yes");
	}
      else if (!strcasecmp (k, "pam_check_host_attr"))
	{
	  result->checkhostattr = !strcasecmp (v, "yes");
	}
      else if (!strcasecmp (k, "pam_groupdn"))
	{
	  CHECKPOINTER (result->groupdn = strdup (v));
	}
      else if (!strcasecmp (k, "pam_member_attribute"))
	{
	  CHECKPOINTER (result->groupattr = strdup (v));
	}
      else if (!strcasecmp (k, "pam_min_uid"))
	{
	  result->min_uid = (uid_t) atol (v);
	}
      else if (!strcasecmp (k, "pam_max_uid"))
	{
	  result->max_uid = (uid_t) atol (v);
	}
      else if (!strcasecmp (k, "tls_checkpeer"))
	{
	  if (!strcasecmp (v, "on") || !strcasecmp (v, "yes")
	      || !strcasecmp (v, "true"))
	    {
	      result->tls_checkpeer = 1;
	    }
	  else if (!strcasecmp (v, "off") || !strcasecmp (v, "no")
		   || !strcasecmp (v, "false"))
	    {
	      result->tls_checkpeer = 0;
	    }
	}
      else if (!strcasecmp (k, "tls_cacertfile"))
	{
	  CHECKPOINTER (result->tls_cacertfile = strdup (v));
	}
      else if (!strcasecmp (k, "tls_cacertdir"))
	{
	  CHECKPOINTER (result->tls_cacertdir = strdup (v));
	}
      else if (!strcasecmp (k, "tls_ciphers"))
	{
	  CHECKPOINTER (result->tls_ciphers = strdup (v));
	}
      else if (!strcasecmp (k, "tls_cert"))
	{
	  CHECKPOINTER (result->tls_cert = strdup (v));
	}
      else if (!strcasecmp (k, "tls_key"))
	{
	  CHECKPOINTER (result->tls_key = strdup (v));
	}
    }

  if (passwdBase != NULL)
    {
      if (defaultBase != NULL)
	{
	  size_t len = strlen (passwdBase);

	  if (passwdBase[len - 1] == ',')
	    {
	      char *p;

	      p = (char *) malloc (len + strlen (defaultBase) + 1);
	      if (p == NULL)
		{
		  fclose (fp);
		  free (defaultBase);	/* leak the rest... */
		  return PAM_BUF_ERR;
		}

	      strcpy (p, passwdBase);
	      strcpy (&p[len], defaultBase);
	      free (passwdBase);
	      passwdBase = p;
	    }
	  free (defaultBase);
	}
      result->base = passwdBase;
    }
  else
    {
      result->base = defaultBase;
    }

  /* defaultFilter appears to be the filter that always gets applied
   * so it is the best place to add additional filtering */

  if(extraFilter != NULL)
  {
	  char *tmp = NULL;

	  if (defaultFilter != NULL)
	  { 
		  tmp = malloc(strlen(defaultFilter) + 
				  strlen(extraFilter) + 20);

		  /* yes, i'm lazy. i'm assuming defaultFilter doesn't have
		   * parenthesis and extraFilter is something i can't
		   * quarantee, it can basicly have any filter in it. */

		  if(extraFilter[0] != '(')
			  sprintf(tmp, "&(%s)(%s)", defaultFilter, extraFilter);
		  else
			  sprintf(tmp, "&(%s)%s", defaultFilter, extraFilter);

		  defaultFilter = strdup (tmp);
	  } else {
		  tmp = malloc(strlen(extraFilter) + 20);

		  if(extraFilter[0] != '(')
			  sprintf(tmp, "&(%s)", extraFilter);
		  else
			  sprintf(tmp, "&%s", extraFilter);

		  defaultFilter = strdup(tmp);
	  }
	  free(tmp);
  }
	  
  if (passwdFilter != NULL)
    {
      result->filter = passwdFilter;
      if (defaultFilter != NULL)
	free (defaultFilter);
    }
  else
    {
      result->filter = defaultFilter;
    }

  if (passwdScope != -1)
    {
      result->scope = passwdScope;
    }
  else
    {
      result->scope = defaultScope;
    }

#ifdef HAVE_LDAP_INITIALIZE
  if (result->host == NULL && result->uri == NULL)
#else
  if (result->host == NULL)
#endif
    {
      /* 
       * According to PAM Documentation, such an error in a config file
       * SHOULD be logged at LOG_ALERT level
       */
      syslog (LOG_ALERT, "pam_ldap: missing \"host\" in file \"%s\"",
	      PAM_LDAP_PATH_CONF);
      return PAM_SERVICE_ERR;
    }

  if (result->userattr == NULL)
    {
      CHECKPOINTER (result->userattr = strdup ("uid"));
    }

  if (result->groupattr == NULL)
    {
      CHECKPOINTER (result->groupattr = strdup ("uniquemember"));
    }

  if (result->port == 0)
    {
#if defined(HAVE_LDAPSSL_INIT) || defined(HAVE_LDAP_START_TLS_S)
      if (result->ssl_on == SSL_LDAPS)
	{
	  result->port = LDAPS_PORT;
	}
      else
#endif
	result->port = LDAP_PORT;
    }

  fclose (fp);

  if ((result->rootbinddn != NULL) && (geteuid () == 0))
    {
      fp = fopen (PAM_LDAP_PATH_ROOTPASSWD, "r");
      if (fp != NULL)
	{
	  if (fgets (b, sizeof (b), fp) != NULL)
	    {
	      int len;
	      len = strlen (b);
	      if (len > 0 && b[len - 1] == '\n')
		len--;

	      b[len] = '\0';
	      result->rootbindpw = strdup (b);
	    }
	  fclose (fp);
	}
      else
	{
	  _pam_drop (result->rootbinddn);
	  syslog (LOG_WARNING,
		  "pam_ldap: could not open secret file %s (%s)",
		  PAM_LDAP_PATH_ROOTPASSWD, strerror (errno));
	}
    }

  /* can't use _pam_overwrite because it only goes to end of string, 
   * not the buffer
   */
  memset (b, 0, BUFSIZ);
  return PAM_SUCCESS;
}

static int
_open_session (pam_ldap_session_t * session)
{
#ifdef LDAP_X_OPT_CONNECT_TIMEOUT
  int timeout;
#endif
#ifdef LDAP_OPT_NETWORK_TIMEOUT
  struct timeval tv;
#endif

#ifdef HAVE_LDAPSSL_INIT
  if (session->conf->ssl_on == SSL_LDAPS && ssl_initialized == 0)
    {
      int rc = ldapssl_client_init (session->conf->sslpath, NULL);
      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR, "pam_ldap: ldapssl_client_init %s",
		  ldap_err2string (rc));
	  return PAM_SERVICE_ERR;
	}
      ssl_initialized = 1;
    }

  if (session->conf->ssl_on)
    {
      session->ld = ldapssl_init (session->conf->host,
				  session->conf->port, TRUE);
    }
  else
#endif /* HAVE_LDAPSSL_INIT */
    {
#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS)
      /* set defaults for global TLS-related options */
      if (_set_ssl_default_options (session) != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR, "pam_ldap: _set_ssl_default_options failed");
	}
#endif
#ifdef HAVE_LDAP_INITIALIZE
      if (session->conf->uri != NULL)
	{
	  int rc = ldap_initialize (&session->ld, session->conf->uri);
	  if (rc != LDAP_SUCCESS)
	    {
	      syslog (LOG_ERR, "pam_ldap: ldap_initialize %s",
		      ldap_err2string (rc));
	      return PAM_SERVICE_ERR;
	    }
	}
      else
	{
#endif /* HAVE_LDAP_INTITIALIZE */
#ifdef HAVE_LDAP_INIT
	  session->ld = ldap_init (session->conf->host, session->conf->port);
#else
	  session->ld = ldap_open (session->conf->host, session->conf->port);
#endif /* HAVE_LDAP_INIT */
#ifdef HAVE_LDAP_INITIALIZE
	}
#endif /* HAVE_LDAP_INTIALIZE */
    }

  if (session->ld == NULL)
    {
      return PAM_SERVICE_ERR;
    }

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS)
  if (session->conf->ssl_on == SSL_LDAPS)
    {
      int tls = LDAP_OPT_X_TLS_HARD;
      int rc = ldap_set_option (session->ld, LDAP_OPT_X_TLS, &tls);
      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR, "pam_ldap: ldap_set_option(LDAP_OPT_X_TLS) %s",
		  ldap_err2string (rc));
	  return PAM_SERVICE_ERR;
	}

      /* set up SSL per-context settings */
      if (_set_ssl_options (session) != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR, "pam_ldap: _set_ssl_options failed");
	}
    }
#endif /* LDAP_OPT_X_TLS */

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_PROTOCOL_VERSION)
  (void) ldap_set_option (session->ld, LDAP_OPT_PROTOCOL_VERSION, &session->conf->version);
#else
  session->ld->ld_version = session->conf->version;
#endif

#if LDAP_SET_REBIND_PROC_ARGS == 3
  ldap_set_rebind_proc (session->ld, _rebind_proc, (void *) session);
#elif LDAP_SET_REBIND_PROC_ARGS == 2
  ldap_set_rebind_proc (session->ld, _rebind_proc);
#endif

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_DEREF)
  (void) ldap_set_option (session->ld, LDAP_OPT_DEREF, &session->conf->deref);
#else
  session->ld->ld_deref = session->conf->deref;
#endif

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_TIMELIMIT)
  (void) ldap_set_option (session->ld, LDAP_OPT_TIMELIMIT, &session->conf->timelimit);
#else
  session->ld->ld_timelimit = session->conf->timelimit;
#endif


#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_X_OPT_CONNECT_TIMEOUT)
  /*
   * This is a new option in the Netscape SDK which sets 
   * the TCP connect timeout. For want of a better value,
   * we use the bind_timelimit to control this.
   */
  timeout = session->conf->bind_timelimit * 1000;
  (void) ldap_set_option (session->ld, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout);
#endif

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_NETWORK_TIMEOUT)
  tv.tv_sec = session->conf->bind_timelimit;
  tv.tv_usec = 0;
  (void) ldap_set_option (session->ld, LDAP_OPT_NETWORK_TIMEOUT, &tv);
#endif

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_REFERRALS)
  (void) ldap_set_option (session->ld, LDAP_OPT_REFERRALS,
			  session->
			  conf->referrals ? LDAP_OPT_ON : LDAP_OPT_OFF);
#endif

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_RESTART)
  (void) ldap_set_option (session->ld, LDAP_OPT_RESTART,
			  session->
			  conf->restart ? LDAP_OPT_ON : LDAP_OPT_OFF);
#endif

#ifdef HAVE_LDAP_START_TLS_S
  if (session->conf->ssl_on == SSL_START_TLS)
    {
      int version, rc;

      if (ldap_get_option (session->ld, LDAP_OPT_PROTOCOL_VERSION, &version)
	  == LDAP_SUCCESS)
	{
	  if (version < LDAP_VERSION3)
	    {
	      version = LDAP_VERSION3;
	      (void) ldap_set_option (session->ld, LDAP_OPT_PROTOCOL_VERSION, &version);
	    }

	  /* set up SSL context */
	  if (_set_ssl_options (session) != LDAP_SUCCESS)
	    {
	      syslog (LOG_ERR, "pam_ldap: _set_ssl_options failed");
	    }

	  rc = ldap_start_tls_s (session->ld, NULL, NULL);
	  if (rc != LDAP_SUCCESS)
	    {
	      syslog (LOG_ERR, "pam_ldap: ldap_starttls_s: %s",
		      ldap_err2string (rc));
	      return PAM_SERVICE_ERR;
	    }
	}
    }
#endif /* HAVE_LDAP_START_TLS_S */
  return PAM_SUCCESS;
}

#if defined HAVE_LDAP_START_TLS_S || (defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS))
/* Some global TLS-specific options need to be set before we create our
 * session context, so we set them here. */
static int
_set_ssl_default_options (pam_ldap_session_t * session)
{
  int rc;

  /* ca cert file */
  if (session->conf->tls_cacertfile != NULL)
    {
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE,
			    session->conf->tls_cacertfile);
      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR,
		  "pam_ldap: ldap_set_option(LDAP_OPT_X_TLS_CACERTFILE): %s",
		  ldap_err2string (rc));
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  if (session->conf->tls_cacertdir != NULL)
    {
      /* ca cert directory */
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTDIR,
			    session->conf->tls_cacertdir);
      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR,
		  "pam_ldap: ldap_set_option(LDAP_OPT_X_TLS_CACERTDIR): %s",
		  ldap_err2string (rc));
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  /* require cert? */
  rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,
			&session->conf->tls_checkpeer);
  if (rc != LDAP_SUCCESS)
    {
      syslog (LOG_ERR,
	      "pam_ldap: ldap_set_option(LDAP_OPT_X_TLS_REQUIRE_CERT): %s",
	      ldap_err2string (rc));
      return LDAP_OPERATIONS_ERROR;
    }

  if (session->conf->tls_ciphers != NULL)
    {
      /* set cipher suite, certificate and private key: */
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_CIPHER_SUITE,
			    session->conf->tls_ciphers);
      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR,
		  "pam_ldap: ldap_set_option(LDAP_OPT_X_TLS_CIPHER_SUITE): %s",
		  ldap_err2string (rc));
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  if (session->conf->tls_cert != NULL)
    {
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_CERTFILE,
			    session->conf->tls_cert);
      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR,
		  "pam_ldap: ldap_set_option(LDAP_OPT_X_TLS_CERTFILE): %s",
		  ldap_err2string (rc));
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  if (session->conf->tls_key != NULL)
    {
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_KEYFILE,
			    session->conf->tls_key);
      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR,
		  "pam_ldap: ldap_set_option(LDAP_OPT_X_TLS_KEYFILE): %s",
		  ldap_err2string (rc));
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  return LDAP_SUCCESS;
}

/* Now we can set the per-context TLS-specific options. */
static int
_set_ssl_options (pam_ldap_session_t * session)
{
  return LDAP_SUCCESS;
}
#endif

static int
_connect_anonymously (pam_ldap_session_t * session)
{
  int rc;
  int msgid;
  struct timeval timeout;
  LDAPMessage *result;

  if (session->ld == NULL)
    {
      rc = _open_session (session);
      if (rc != PAM_SUCCESS)
	return rc;
    }

  if (session->conf->rootbinddn && geteuid () == 0)
    {
      msgid = ldap_simple_bind (session->ld,
				session->conf->rootbinddn,
				session->conf->rootbindpw);
    }
  else
    {
      msgid = ldap_simple_bind (session->ld,
				session->conf->binddn, session->conf->bindpw);
    }

  if (msgid == -1)
    {
      syslog (LOG_ERR, "pam_ldap: ldap_simple_bind %s",
	      ldap_err2string (ldap_get_lderrno (session->ld, 0, 0)));
      return PAM_AUTHINFO_UNAVAIL;
    }

  timeout.tv_sec = session->conf->bind_timelimit;	/* default 10 */
  timeout.tv_usec = 0;
  rc = ldap_result (session->ld, msgid, FALSE, &timeout, &result);
  if (rc == -1 || rc == 0)
    {
      syslog (LOG_ERR, "pam_ldap: ldap_result %s",
	      ldap_err2string (ldap_get_lderrno (session->ld, 0, 0)));
      return PAM_AUTHINFO_UNAVAIL;
    }

#ifdef HAVE_LDAP_PARSE_RESULT
  ldap_parse_result (session->ld, result, &rc, 0, 0, 0, 0, TRUE);
#else
  rc = ldap_result2error (session->ld, result, TRUE);
#endif

  if (rc != LDAP_SUCCESS)
    {
      syslog (LOG_ERR, "pam_ldap: error trying to bind (%s)",
	      ldap_err2string (rc));
      return PAM_CRED_INSUFFICIENT;
    }

  if (session->info != NULL)
    {
      session->info->bound_as_user = 0;
    }

  return PAM_SUCCESS;
}

#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
#if LDAP_SET_REBIND_PROC_ARGS == 3
static int
_rebind_proc (LDAP * ld, LDAP_CONST char *url, ber_tag_t request,
	      ber_int_t msgid, void *arg)
#else
static int
_rebind_proc (LDAP * ld, LDAP_CONST char *url, int request, ber_int_t msgid)
#endif
{
#if LDAP_SET_REBIND_PROC_ARGS == 3
  pam_ldap_session_t *session = (pam_ldap_session_t *) arg;
#else
  /* ugly hack */
  pam_ldap_session_t *session = global_session;
#endif
  char *who, *cred;

  if (session->info != NULL && session->info->bound_as_user == 1)
    {
      who = session->info->userdn;
      cred = session->info->userpw;
    }
  else
    {
      if (session->conf->rootbinddn != NULL && geteuid () == 0)
	{
	  who = session->conf->rootbinddn;
	  cred = session->conf->rootbindpw;
	}
      else
	{
	  who = session->conf->binddn;
	  cred = session->conf->bindpw;
	}
    }

  return ldap_simple_bind_s (ld, who, cred);
}
#else
#if LDAP_SET_REBIND_PROC_ARGS == 3
static int
_rebind_proc (LDAP * ld,
	      char **whop, char **credp, int *methodp, int freeit, void *arg)
#else
static int
_rebind_proc (LDAP * ld, char **whop, char **credp, int *methodp, int freeit)
#endif
{
#if LDAP_SET_REBIND_PROC_ARGS == 3
  pam_ldap_session_t *session = (pam_ldap_session_t *) arg;
#else
  /* ugly hack */
  pam_ldap_session_t *session = global_session;
#endif

  if (freeit)
    {
      _pam_drop (*whop);
      _pam_overwrite (*credp);
      _pam_drop (*credp);
      return LDAP_SUCCESS;
    }

  if (session->info != NULL && session->info->bound_as_user == 1)
    {
      /*
       * We're authenticating as a user.
       */
      *whop = strdup (session->info->userdn);
      *credp = strdup (session->info->userpw);
    }
  else
    {
      if (session->conf->rootbinddn != NULL && geteuid () == 0)
	{
	  *whop = strdup (session->conf->rootbinddn);
	  *credp = session->conf->rootbindpw != NULL ?
	    strdup (session->conf->rootbindpw) : NULL;
	}
      else
	{
	  *whop = session->conf->binddn != NULL ?
	    strdup (session->conf->binddn) : NULL;
	  *credp = session->conf->bindpw != NULL ?
	    strdup (session->conf->bindpw) : NULL;
	}
    }

  *methodp = LDAP_AUTH_SIMPLE;

  return LDAP_SUCCESS;
}
#endif


static int
_connect_as_user (pam_ldap_session_t * session, const char *password)
{
  int rc, msgid;
#if defined(HAVE_LDAP_PARSE_RESULT) && defined(HAVE_LDAP_CONTROLS_FREE)
  int parserc;
#endif
  struct timeval timeout;
  LDAPMessage *result;
#ifdef HAVE_LDAP_CONTROLS_FREE
  LDAPControl **controls;
#endif

  /* avoid binding anonymously with a DN but no password */
  if (password == NULL || password[0] == '\0')
    return PAM_AUTH_ERR;

  /* this shouldn't ever happen */
  if (session->info == NULL)
    return PAM_SYSTEM_ERR;

  /* if we already bound as the user don't bother retrying */
  if (session->info->bound_as_user)
    return PAM_SUCCESS;

  if (session->ld == NULL)
    {
      rc = _open_session (session);
      if (rc != PAM_SUCCESS)
	return rc;
    }

  /*
   * We copy the password temporarily so that when referrals are
   * chased, the correct credentials are set by the rebind 
   * procedure.
   */
  if (session->info->userpw != NULL)
    {
      _pam_overwrite (session->info->userpw);
      _pam_drop (session->info->userpw);
    }

  session->info->userpw = strdup (password);
  if (session->info->userpw == NULL)
    return PAM_BUF_ERR;

  msgid =
    ldap_simple_bind (session->ld, session->info->userdn,
		      session->info->userpw);
  if (msgid == -1)
    {
      syslog (LOG_ERR, "pam_ldap: ldap_simple_bind %s",
	      ldap_err2string (ldap_get_lderrno (session->ld, 0, 0)));
      _pam_overwrite (session->info->userpw);
      _pam_drop (session->info->userpw);
      return PAM_AUTHINFO_UNAVAIL;
    }

  timeout.tv_sec = 10;
  timeout.tv_usec = 0;
  rc = ldap_result (session->ld, msgid, FALSE, &timeout, &result);
  if (rc == -1 || rc == 0)
    {
      syslog (LOG_ERR, "pam_ldap: ldap_result %s",
	      ldap_err2string (ldap_get_lderrno (session->ld, 0, 0)));
      _pam_overwrite (session->info->userpw);
      _pam_drop (session->info->userpw);
      return PAM_AUTHINFO_UNAVAIL;
    }

#if defined(HAVE_LDAP_PARSE_RESULT) && defined(HAVE_LDAP_CONTROLS_FREE)
  controls = 0;
  parserc =
    ldap_parse_result (session->ld, result, &rc, 0, 0, 0, &controls, TRUE);
  if (parserc != LDAP_SUCCESS)
    {
      syslog (LOG_ERR, "pam_ldap: ldap_parse_result %s",
	      ldap_err2string (parserc));
      _pam_overwrite (session->info->userpw);
      _pam_drop (session->info->userpw);
      return PAM_SERVICE_ERR;
    }
#else
  rc = ldap_result2error (session->ld, result, TRUE);
#endif

  if (rc != LDAP_SUCCESS)
    {
      syslog (LOG_ERR, "pam_ldap: error trying to bind as user \"%s\" (%s)",
	      session->info->userdn, ldap_err2string (rc));
      _pam_overwrite (session->info->userpw);
      _pam_drop (session->info->userpw);
      return PAM_AUTH_ERR;
    }

#if defined(HAVE_LDAP_CONTROLS_FREE)
  if (controls != NULL)
    {
      LDAPControl **ctlp;
      for (ctlp = controls; *ctlp != NULL; ctlp++)
	{
	  if (!strcmp ((*ctlp)->ldctl_oid, LDAP_CONTROL_PWEXPIRING))
	    {
	      char seconds[32];
	      snprintf (seconds, sizeof seconds, "%.*s",
			(int) (*ctlp)->ldctl_value.bv_len,
			(*ctlp)->ldctl_value.bv_val);
	      session->info->password_expiration_time = atol (seconds);
	    }
	  else if (!strcmp ((*ctlp)->ldctl_oid, LDAP_CONTROL_PWEXPIRED))
	    {
	      session->info->password_expired = 1;
	    }
	}
      ldap_controls_free (controls);
    }
#endif

  session->info->bound_as_user = 1;
  /* userpw is now set. Be sure to clobber it later. */

  return PAM_SUCCESS;
}

static int
_get_integer_value (LDAP * ld, LDAPMessage * e, const char *attr, int *ptr)
{
  char **vals;

  vals = ldap_get_values (ld, e, (char *) attr);
  if (vals == NULL)
    {
      return PAM_AUTHINFO_UNAVAIL;
    }
  *ptr = atoi (vals[0]);
  ldap_value_free (vals);

  return PAM_SUCCESS;
}

static int
_get_long_integer_value (LDAP * ld, LDAPMessage * e, const char *attr,
			 long int *ptr)
{
  char **vals;

  vals = ldap_get_values (ld, e, (char *) attr);
  if (vals == NULL)
    {
      return PAM_AUTHINFO_UNAVAIL;
    }
  *ptr = atol (vals[0]);
  ldap_value_free (vals);

  return PAM_SUCCESS;
}


#ifdef notdef
static int
_oc_check (LDAP * ld, LDAPMessage * e, const char *oc)
{
  char **vals, **p;
  int rc = 0;

  vals = ldap_get_values (ld, e, "objectClass");
  if (vals == NULL)
    {
      return PAM_AUTHINFO_UNAVAIL;
    }

  for (p = vals; *p != NULL; p++)
    {
      if (!strcasecmp (*p, oc))
	{
	  rc = 1;
	  break;
	}
    }

  ldap_value_free (vals);

  return rc;
}
#endif /* notdef */

static int
_get_string_value (LDAP * ld, LDAPMessage * e, const char *attr, char **ptr)
{
  char **vals;
  int rc;

  vals = ldap_get_values (ld, e, (char *) attr);
  if (vals == NULL)
    {
      return PAM_AUTHINFO_UNAVAIL;
    }
  *ptr = strdup (vals[0]);
  if (*ptr == NULL)
    {
      rc = PAM_BUF_ERR;
    }
  else
    {
      rc = PAM_SUCCESS;
    }

  ldap_value_free (vals);

  return rc;
}

static int
_get_string_values (LDAP * ld, LDAPMessage * e, const char *attr, char ***ptr)
{
  char **vals;

  vals = ldap_get_values (ld, e, (char *) attr);
  if (vals == NULL)
    {
      return PAM_AUTHINFO_UNAVAIL;
    }
  *ptr = vals;

  return PAM_SUCCESS;
}

static int
_has_value (char **src, const char *tgt)
{
  char **p;

  for (p = src; *p != NULL; p++)
    {
      if (!strcasecmp (*p, tgt))
	{
	  return 1;
	}
    }

  return 0;
}

static int
_host_ok (pam_ldap_session_t * session)
{
  char hostname[MAXHOSTNAMELEN];
  struct hostent *h;
#ifdef HAVE_GETHOSTBYNAME_R
  int herr;
  struct hostent hbuf;
  char buf[1024];
#endif
  char **q;

  /* simple host based access authorization */
  if (session->info->hosts_allow == NULL)
    {
      return PAM_PERM_DENIED;
    }

  /* allow wild-card entries */
  if (_has_value (session->info->hosts_allow, "*"))
    {
      return PAM_SUCCESS;
    }

  if (gethostname (hostname, sizeof hostname) < 0)
    {
      return PAM_SYSTEM_ERR;
    }

#if defined(HAVE_GETHOSTBYNAME_R)
#if GETHOSTBYNAME_R_ARGS == 6
  if (gethostbyname_r (hostname, &hbuf, buf, sizeof buf, &h, &herr) != 0)
    {
      return PAM_SYSTEM_ERR;
    }
#else
  h = gethostbyname_r (hostname, &hbuf, buf, sizeof buf, &herr);
  if (h == NULL)
    {
      return PAM_SYSTEM_ERR;
    }
#endif
#else
  h = gethostbyname (hostname);
  if (h == NULL)
    {
      return PAM_SYSTEM_ERR;
    }
#endif

  if (_has_value (session->info->hosts_allow, h->h_name))
    {
      return PAM_SUCCESS;
    }

  if (h->h_aliases != NULL)
    {
      for (q = h->h_aliases; *q != NULL; q++)
	{
	  if (_has_value (session->info->hosts_allow, *q))
	    {
	      return PAM_SUCCESS;
	    }
	}
    }

  return PAM_PERM_DENIED;
}

static char *
_get_md5_salt (char saltbuf[16])
{
  md5_state_t state;
  md5_byte_t digest[16];
  struct timeval tv;
  int i;

  md5_init (&state);
  gettimeofday (&tv, NULL);
  md5_append (&state, (unsigned char *) &tv, sizeof (tv));
  i = getpid ();
  md5_append (&state, (unsigned char *) &i, sizeof (i));
  i = clock ();
  md5_append (&state, (unsigned char *) &i, sizeof (i));
  md5_append (&state, (unsigned char *) saltbuf, sizeof (saltbuf));
  md5_finish (&state, digest);

  strcpy (saltbuf, "$1$");
  for (i = 0; i < 8; i++)
    saltbuf[i + 3] = i64c (digest[i] & 0x3f);

  saltbuf[i + 3] = '\0';

  return saltbuf;
}

static char *
_get_salt (char salt[16])
{
  int i;
  int j;

  srand (time (NULL));

  for (j = 0; j < 2; j++)
    {
      i = rand () % 3;
      switch (i)
	{
	case 0:
	  i = (rand () % (57 - 46)) + 46;
	  break;
	case 1:
	  i = (rand () % (90 - 65)) + 65;
	  break;
	case 2:
	  i = (rand () % (122 - 97)) + 97;
	  break;
	}
      salt[j] = i;
    }
  salt[2] = '\0';
  return salt;
}

static int
_escape_string (const char *str, char *buf, size_t buflen)
{
  int ret = PAM_BUF_ERR;
  char *p = buf;
  char *limit = p + buflen - 3;
  const char *s = str;

  while (p < limit && *s)
    {
      switch (*s)
	{
	case '*':
	  strcpy (p, "\\2a");
	  p += 3;
	  break;
	case '(':
	  strcpy (p, "\\28");
	  p += 3;
	  break;
	case ')':
	  strcpy (p, "\\29");
	  p += 3;
	  break;
	case '\\':
	  strcpy (p, "\\5c");
	  p += 3;
	  break;
	default:
	  *p++ = *s;
	  break;
	}
      s++;
    }

  if (*s == '\0')
    {
      /* got to end */
      *p = '\0';
      ret = PAM_SUCCESS;
    }

  return ret;
}

static int
_get_user_info (pam_ldap_session_t * session, const char *user)
{
  char filter[LDAP_FILT_MAXSIZ], escapedUser[LDAP_FILT_MAXSIZ];
  int rc;
  LDAPMessage *res, *msg;

  rc = _connect_anonymously (session);
  if (rc != PAM_SUCCESS)
    return rc;

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_SIZELIMIT)
  rc = 1;
  (void) ldap_set_option (session->ld, LDAP_OPT_SIZELIMIT, &rc);
#else
  session->ld->ld_sizelimit = 1;
#endif

  rc = _escape_string (user, escapedUser, sizeof (escapedUser));
  if (rc != PAM_SUCCESS)
    {
      return rc;
    }

  if (session->conf->filter != NULL)
    {
      snprintf (filter, sizeof filter, "(&(%s)(%s=%s))",
		session->conf->filter, session->conf->userattr, escapedUser);
    }
  else
    {
      snprintf (filter, sizeof filter, "(%s=%s)",
		session->conf->userattr, escapedUser);
    }



  rc = ldap_search_s (session->ld,
		      session->conf->base,
		      session->conf->scope, filter, NULL, 0, &res);

  if (rc != LDAP_SUCCESS &&
      rc != LDAP_TIMELIMIT_EXCEEDED && rc != LDAP_SIZELIMIT_EXCEEDED)
    {
      syslog (LOG_ERR, "pam_ldap: ldap_search_s %s", ldap_err2string (rc));
      return PAM_USER_UNKNOWN;
    }

  msg = ldap_first_entry (session->ld, res);
  if (msg == NULL)
    {
      ldap_msgfree (res);
      return PAM_USER_UNKNOWN;
    }

  if (session->info != NULL)
    {
      _release_user_info (&session->info);
    }

  session->info =
    (pam_ldap_user_info_t *) calloc (1, sizeof (pam_ldap_user_info_t));
  if (session->info == NULL)
    {
      ldap_msgfree (res);
      return PAM_BUF_ERR;
    }

  session->info->username = strdup (user);
  if (session->info->username == NULL)
    {
      ldap_msgfree (res);
      _release_user_info (&session->info);
      return PAM_BUF_ERR;
    }

  session->info->userdn = ldap_get_dn (session->ld, msg);
  if (session->info->userdn == NULL)
    {
      ldap_msgfree (res);
      _release_user_info (&session->info);
      return PAM_SERVICE_ERR;
    }

  session->info->bound_as_user = 0;

  /*
   * it might be better to do a compare later, that way we can
   * avoid fetching any attributes at all
   */
  _get_string_values (session->ld, msg, "host", &session->info->hosts_allow);

  /* get UID */
#ifdef UID_NOBODY
  session->info->uid = UID_NOBODY;
#else
  session->info->uid = (uid_t) - 2;
#endif /* UID_NOBODY */
  _get_integer_value (session->ld, msg, "uidNumber",
		      (uid_t *) & session->info->uid);

  /*
   * get mapped user; some PAM host applications let PAM_USER be reset
   * by the user (such as some of those provided with FreeBSD).
   */
  session->info->tmpluser = NULL;
  if (session->conf->tmplattr != NULL)
    {
      if (_get_string_value (session->ld,
			     msg,
			     session->conf->tmplattr,
			     &session->info->tmpluser) != PAM_SUCCESS)
	{
	  /* set to default template user */
	  session->info->tmpluser =
	    session->conf->tmpluser ? strdup (session->conf->tmpluser) : NULL;
	}
    }

  /* Assume shadow controls.  Allocate shadow structure and link to session. */
  session->info->shadow.lstchg = 0;
  session->info->shadow.min = 0;
  session->info->shadow.max = 0;
  session->info->shadow.warn = 0;
  session->info->shadow.inact = 0;
  session->info->shadow.expire = 0;
  session->info->shadow.flag = 0;

  _get_long_integer_value (session->ld, msg, "shadowLastChange",
			   &session->info->shadow.lstchg);
  _get_long_integer_value (session->ld, msg, "shadowMin",
			   &session->info->shadow.min);
  _get_long_integer_value (session->ld, msg, "shadowMax",
			   &session->info->shadow.max);
  _get_long_integer_value (session->ld, msg, "shadowWarning",
			   &session->info->shadow.warn);
  _get_long_integer_value (session->ld, msg, "shadowInactive",
			   &session->info->shadow.inact);
  _get_long_integer_value (session->ld, msg, "shadowExpire",
			   &session->info->shadow.expire);
  _get_long_integer_value (session->ld, msg, "shadowFlag",
			   &session->info->shadow.flag);

  ldap_msgfree (res);

  return PAM_SUCCESS;
}

static int
_pam_ldap_get_session (pam_handle_t * pamh, const char *username,
		     const char *configFile, const char *extraFilter, 
		     pam_ldap_session_t ** psession)
{
  pam_ldap_session_t *session;
  int rc;

  if (pam_get_data
      (pamh, PADL_LDAP_SESSION_DATA, (const void **) &session) == PAM_SUCCESS)
    {
      /*
       * we cache the information retrieved from the LDAP server, however
       * we need to flush this if the application has changed the user
       * or configuration file.
       *
       * For template users, note that pam_ldap may _RESET_ the username!
       */
      if (session->info != NULL &&
	  (strcmp (username, session->info->username) != 0))
	{
	  _release_user_info (&session->info);
	}

      if (configFile == NULL)
	{
	  /* Default configuration file requested. */
	  if (session->conf->configFile != NULL)
	    _release_user_info (&session->info);
	}
      else
	{
	  /* Non-default configuration file requested. */
	  if (session->conf->configFile == NULL ||
	      (strcmp (configFile, session->conf->configFile) != 0))
	    {
	      _release_user_info (&session->info);
	    }
	}

      *psession = session;
#if LDAP_SET_REBIND_PROC_ARGS < 3
      global_session = *psession;
#endif
      return PAM_SUCCESS;
    }

  *psession = NULL;

  session = (pam_ldap_session_t *) calloc (1, sizeof (*session));
#if LDAP_SET_REBIND_PROC_ARGS < 3
  global_session = session;
#endif
  if (session == NULL)
    {
      return PAM_BUF_ERR;
    }

  session->ld = NULL;
  session->conf = NULL;
  session->info = NULL;

#ifdef YPLDAPD
  rc = _ypldapd_read_config (&session->conf);
  if (rc != PAM_SUCCESS)
    {
      _release_config (&session->conf);
#endif /* YPLDAPD */
      rc = _read_config (configFile, extraFilter, &session->conf);
      if (rc != PAM_SUCCESS)
	{
	  _release_config (&session->conf);
	  free (session);
	  return rc;
	}
#ifdef YPLDAPD
    }
#endif /* YPLDAPD */

  rc =
    pam_set_data (pamh, PADL_LDAP_SESSION_DATA, (void *) session,
		  _pam_ldap_cleanup_session);
  if (rc != PAM_SUCCESS)
    {
      _release_config (&session->conf);
      free (session);
      return rc;
    }

  *psession = session;

  return PAM_SUCCESS;
}

static int
_reopen (pam_ldap_session_t * session)
{
  /* FYI: V3 lets us avoid five unneeded binds in a password change */
  if (session->conf->version == LDAP_VERSION2)
    {
      if (session->ld != NULL)
	{
	  ldap_unbind (session->ld);
	  session->ld = NULL;
	}
      if (session->info != NULL)
	{
	  session->info->bound_as_user = 0;
	}
      return _open_session (session);
    }
  return PAM_SUCCESS;
}

static int
_get_password_policy (pam_ldap_session_t * session,
		      pam_ldap_password_policy_t * policy)
{
  int rc = PAM_SUCCESS;
  LDAPMessage *res, *msg;

  /* set some reasonable defaults */
  memset (policy, 0, sizeof (*policy));
  policy->password_min_length = 6;
  policy->password_max_failure = 3;

  if (session->conf->getpolicy == 0)
    {
      return PAM_SUCCESS;
    }

  rc = _connect_anonymously (session);
  if (rc != PAM_SUCCESS)
    {
      return rc;
    }

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_SIZELIMIT)
  rc = 1;
  (void) ldap_set_option (session->ld, LDAP_OPT_SIZELIMIT, &rc);
#else
  session->ld->ld_sizelimit = 1;
#endif /* LDAP_VERSION3_API */

  rc = ldap_search_s (session->ld,
		      "",
		      LDAP_SCOPE_BASE,
		      "(objectclass=passwordPolicy)", NULL, 0, &res);

  if (rc == LDAP_SUCCESS ||
      rc == LDAP_TIMELIMIT_EXCEEDED || rc == LDAP_SIZELIMIT_EXCEEDED)
    {
      msg = ldap_first_entry (session->ld, res);
      if (msg != NULL)
	{
	  _get_integer_value (session->ld, msg, "passwordMaxFailure",
			      &policy->password_max_failure);
	  _get_integer_value (session->ld, msg, "passwordMinLength",
			      &policy->password_min_length);
	}
      ldap_msgfree (res);
    }

  return PAM_SUCCESS;
}

static int
_do_authentication (pam_ldap_session_t * session,
		    const char *user, const char *password)
{
  int rc = PAM_SUCCESS;

  if (session->info == NULL)
    {
      rc = _get_user_info (session, user);
      if (rc != PAM_SUCCESS)
	return rc;
    }

  rc = _reopen (session);
  if (rc != PAM_SUCCESS)
    return rc;

  rc = _connect_as_user (session, password);
  _reopen (session);
  _connect_anonymously (session);
  return rc;
}

static int
_update_authtok (pam_ldap_session_t * session,
		 const char *user,
		 const char *old_password, const char *new_password)
{
  char *strvalsold[2];
  char *strvalsnew[2];
  LDAPMod mod, mod2;
  LDAPMod *mods[3];
  char buf[64], saltbuf[16];
  int rc = PAM_SUCCESS, i;

  /* for Active Directory */

  struct berval bvalold;
  struct berval bvalnew;
  struct berval *bvalsold[2];
  struct berval *bvalsnew[2];
  char old_password_with_quotes[17], new_password_with_quotes[17];
  char old_unicode_password[34], new_unicode_password[34];

#ifdef LDAP_EXOP_X_MODIFY_PASSWD
  /* for OpenLDAP password change extended operation */
  BerElement *ber;
  struct berval *bv;
  char *retoid;
  struct berval *retdata;
#endif /* LDAP_EXOP_X_MODIFY_PASSWD */

  if (session->info == NULL)
    {
      rc = _get_user_info (session, user);
      if (rc != PAM_SUCCESS)
	{
	  return rc;
	}
    }

  if (!session->conf->rootbinddn || geteuid () != 0)
    {
      /* We're not root or don't have a rootbinddn so
       * let's try binding as the user.
       * 
       * FIXME:
       * Do we really want to do this? It allows the
       * system to be configured in such a way that the
       * user can bypass local password policy
       */
      rc = _reopen (session);
      if (rc != PAM_SUCCESS)
	return rc;

      rc = _connect_as_user (session, old_password);
      if (rc != PAM_SUCCESS)
	return rc;
    }

  switch (session->conf->password_type)
    {
    case PASSWORD_CLEAR:
      strvalsnew[0] = (char *) new_password;
      strvalsnew[1] = NULL;

      mod.mod_op = LDAP_MOD_REPLACE;
      mod.mod_type = (char *) "userPassword";
      mod.mod_values = strvalsnew;

      mods[0] = &mod;
      mods[1] = NULL;

      break;

    case PASSWORD_CRYPT:
      _get_salt (saltbuf);
      snprintf (buf, sizeof buf, "{crypt}%s", crypt (new_password, saltbuf));
      strvalsnew[0] = buf;
      strvalsnew[1] = NULL;

      mod.mod_op = LDAP_MOD_REPLACE;
      mod.mod_type = (char *) "userPassword";
      mod.mod_values = strvalsnew;

      mods[0] = &mod;
      mods[1] = NULL;

      break;

    case PASSWORD_MD5:
      _get_md5_salt (saltbuf);
      snprintf (buf, sizeof buf, "{crypt}%s", crypt (new_password, saltbuf));
      strvalsnew[0] = buf;
      strvalsnew[1] = NULL;

      mod.mod_op = LDAP_MOD_REPLACE;
      mod.mod_type = (char *) "userPassword";
      mod.mod_values = strvalsnew;

      mods[0] = &mod;
      mods[1] = NULL;

      break;

    case PASSWORD_NDS:
      /* NDS requires that the old password is first removed */
      strvalsold[0] = (char *) old_password;
      strvalsold[1] = NULL;
      strvalsnew[0] = (char *) new_password;
      strvalsnew[1] = NULL;

      mod.mod_vals.modv_strvals = strvalsold;
      mod.mod_type = (char *) "userPassword";
      mod.mod_op = LDAP_MOD_DELETE;

      mod2.mod_vals.modv_strvals = strvalsnew;
      mod2.mod_type = (char *) "userPassword";
      mod2.mod_op = LDAP_MOD_REPLACE;

      mods[0] = &mod;
      mods[1] = &mod2;
      mods[2] = NULL;

      break;

    case PASSWORD_AD:
      /*
       * Patch from Norbert Klasen <klasen@zdv.uni-tuebingen.de>:
       *
       * To be able to change a password in AD via LDAP, an SSL connection
       * with a cipher strength of at least 128 bit must be established.
       * http://support.microsoft.com/support/kb/articles/q264/4/80.ASP
       * http://support.microsoft.com/support/kb/articles/Q247/0/78.ASP
       *
       * The password attribute used by AD is unicodePwd. Its syntax is octect
       * string. The actual value is the password surrounded by quotes in 
       * Unicode (LSBFirst).
       *
       * NT passwords can have max. 14 characters. 
       *
       * FIXME:
       * The conversion to Unicode only works if the locale is 
       * ISO-8859-1 (aka Latin-1) [of which ASCII is a subset]. 
       */

      snprintf (new_password_with_quotes, sizeof (new_password_with_quotes),
		"\"%s\"", new_password);
      memset (new_unicode_password, 0, sizeof (new_unicode_password));
      for (i = 0; i < strlen (new_password_with_quotes); i++)
	new_unicode_password[i * 2] = new_password_with_quotes[i];
      bvalnew.bv_val = new_unicode_password;
      bvalnew.bv_len = strlen (new_password_with_quotes) * 2;

      bvalsnew[0] = &bvalnew;
      bvalsnew[1] = NULL;
      mod.mod_vals.modv_bvals = bvalsnew;
      mod.mod_type = (char *) "unicodePwd";
      mod.mod_op = LDAP_MOD_ADD | LDAP_MOD_BVALUES;

      if (!session->conf->rootbinddn || getuid () != 0)
	{
	  /* user must supply old password */
	  snprintf (old_password_with_quotes,
		    sizeof (old_password_with_quotes), "\"%s\"",
		    old_password);
	  memset (old_unicode_password, 0, sizeof (old_unicode_password));
	  for (i = 0; i < strlen (old_password_with_quotes); i++)
	    old_unicode_password[i * 2] = old_password_with_quotes[i];
	  bvalold.bv_val = old_unicode_password;
	  bvalold.bv_len = strlen (old_password_with_quotes) * 2;

	  bvalsold[0] = &bvalold;
	  bvalsold[1] = NULL;
	  mod2.mod_vals.modv_bvals = bvalsold;
	  mod2.mod_type = (char *) "unicodePwd";
	  mod2.mod_op = LDAP_MOD_DELETE | LDAP_MOD_BVALUES;

	  mods[0] = &mod;
	  mods[1] = &mod2;
	  mods[2] = NULL;
	}
      else
	{
	  mods[0] = &mod;
	  mods[1] = NULL;
	}

      break;

    case PASSWORD_EXOP:
#ifdef LDAP_EXOP_X_MODIFY_PASSWD
      ber = ber_alloc_t (LBER_USE_DER);

      if (ber == NULL)
	{
	  return PAM_BUF_ERR;
	}

      ber_printf (ber, "{");
      ber_printf (ber, "ts", LDAP_TAG_EXOP_X_MODIFY_PASSWD_ID,
		  session->info->userdn);
      /* this doesn't appear to be necessary anymore */
/*      ber_printf (ber, "ts", LDAP_TAG_EXOP_X_MODIFY_PASSWD_OLD, old_password); */
      ber_printf (ber, "ts", LDAP_TAG_EXOP_X_MODIFY_PASSWD_NEW, new_password);
      ber_printf (ber, "N}");

      rc = ber_flatten (ber, &bv);
      if (rc < 0)
	{
	  ber_free (ber, 1);
	  return PAM_BUF_ERR;
	}

      ber_free (ber, 1);

      rc =
	ldap_extended_operation_s (session->ld, LDAP_EXOP_X_MODIFY_PASSWD, bv,
				   NULL, NULL, &retoid, &retdata);
      ber_bvfree (bv);

      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR, "pam_ldap: ldap_extended_operation_s %s",
		  ldap_err2string (rc));
	  rc = PAM_PERM_DENIED;
	}
      else
	{
	  ber_bvfree (retdata);
	  ber_memfree (retoid);
	  rc = PAM_SUCCESS;
	}
#else
      rc = PAM_SERVICE_ERR;
#endif /* LDAP_EXOP_X_MODIFY_PASSWD */

      break;
    }				/* end switch */

  if (session->conf->password_type != PASSWORD_EXOP)
    {
      rc = ldap_modify_s (session->ld, session->info->userdn, mods);
      if (rc != LDAP_SUCCESS)
	{
	  syslog (LOG_ERR, "pam_ldap: ldap_modify_s %s",
		  ldap_err2string (rc));
	  rc = PAM_PERM_DENIED;
	}
      else
	{
	  rc = PAM_SUCCESS;
	}
    }

  return rc;
}

static int
_get_authtok (pam_handle_t * pamh, int flags, int first)
{
  int rc;
  char *p;
  struct pam_message msg[1], *pmsg[1];
  struct pam_response *resp;
  struct pam_conv *conv;

  pmsg[0] = &msg[0];
  msg[0].msg_style = PAM_PROMPT_ECHO_OFF;
  msg[0].msg = first ? "Password: " : "LDAP Password: ";
  resp = NULL;

  rc = pam_get_item (pamh, PAM_CONV, (CONST_ARG void **) &conv);
  if (rc == PAM_SUCCESS)
    {
      rc = conv->conv (1,
		       (CONST_ARG struct pam_message **) pmsg,
		       &resp, conv->appdata_ptr);
    }
  else
    {
      return rc;
    }

  if (resp != NULL)
    {
      if ((flags & PAM_DISALLOW_NULL_AUTHTOK) && resp[0].resp == NULL)
	{
	  free (resp);
	  return PAM_AUTH_ERR;
	}

      p = resp[0].resp;
      /* leak if resp[0].resp is malloced. */
      resp[0].resp = NULL;
    }
  else
    {
      return PAM_CONV_ERR;
    }

  free (resp);
  pam_set_item (pamh, PAM_AUTHTOK, p);

  return PAM_SUCCESS;
}

static int
_conv_sendmsg (struct pam_conv *aconv,
	       const char *message, int style, int no_warn)
{
  struct pam_message msg, *pmsg;
  struct pam_response *resp;

  if (no_warn)
    return PAM_SUCCESS;

  pmsg = &msg;

  msg.msg_style = style;
  msg.msg = (char *) message;
  resp = NULL;

  return aconv->conv (1,
		      (CONST_ARG struct pam_message **) &pmsg,
		      &resp, aconv->appdata_ptr);
}

PAM_EXTERN int
pam_sm_authenticate (pam_handle_t * pamh,
		     int flags, int argc, const char **argv)
{
  int rc;
  const char *username;
  char *p;
  int use_first_pass = 0, try_first_pass = 0, ignore_unknown_user = 0;
  int i;
  pam_ldap_session_t *session = NULL;
  const char *configFile = NULL;
  const char *extraFilter = NULL;

  for (i = 0; i < argc; i++)
    {
      if (!strcmp (argv[i], "use_first_pass"))
	use_first_pass = 1;
      else if (!strcmp (argv[i], "try_first_pass"))
	try_first_pass = 1;
      else if (!strncmp (argv[i], "config=", 7))
	configFile = argv[i] + 7;
      else if (!strcmp (argv[i], "ignore_unknown_user"))
	ignore_unknown_user = 1;
      else if (!strcmp (argv[i], "no_warn"))
	;
      else if (!strcmp (argv[i], "debug"))
	;
      else
	syslog (LOG_ERR, "illegal option %s", argv[i]);
    }

  rc = pam_get_user (pamh, (CONST_ARG char **) &username, NULL);
  if (rc != PAM_SUCCESS)
    return rc;

  rc = _pam_ldap_get_session (pamh, username, configFile, extraFilter, &session);
  if (rc != PAM_SUCCESS)
    return rc;

  rc = pam_get_item (pamh, PAM_AUTHTOK, (CONST_ARG void **) &p);
  if (rc == PAM_SUCCESS && (use_first_pass || try_first_pass))
    {
      rc = _do_authentication (session, username, p);
      if (rc == PAM_SUCCESS || use_first_pass)
	{
	  if (rc == PAM_USER_UNKNOWN && ignore_unknown_user)
	    rc = PAM_IGNORE;
	  if (rc == PAM_SUCCESS && session->info->tmpluser != NULL &&
	      strcmp (session->info->tmpluser, session->conf->tmpluser) == 0)
	    {
	      (void) pam_set_data (pamh, PADL_LDAP_AUTH_DATA,
				   (void *) strdup (session->info->username),
				   _cleanup_data);
	      rc =
		pam_set_item (pamh, PAM_USER,
			      (void *) session->info->tmpluser);
	    }
	  return rc;
	}
    }

  /* can prompt for authentication token */
  rc = _get_authtok (pamh, flags, (p == NULL) ? 1 : 0);
  if (rc != PAM_SUCCESS)
    return rc;

  rc = pam_get_item (pamh, PAM_AUTHTOK, (CONST_ARG void **) &p);
  if (rc == PAM_SUCCESS)
    rc = _do_authentication (session, username, p);
  if (rc == PAM_USER_UNKNOWN && ignore_unknown_user)
    rc = PAM_IGNORE;

  /*
   * reset username to template user if necessary
   * FreeBSD pam_radius does this in pam_sm_authenticate() but
   * I think pam_sm_acct_mgmt() is the right place.
   */
  if (rc == PAM_SUCCESS && session->info->tmpluser != NULL &&
      strcmp (session->info->tmpluser, session->conf->tmpluser) == 0)
    {
      /* keep original username for posterity */

      (void) pam_set_data (pamh, PADL_LDAP_AUTH_DATA,
			   (void *) strdup (session->info->username),
			   _cleanup_data);
      rc = pam_set_item (pamh, PAM_USER, (void *) session->info->tmpluser);
    }

  return rc;
}

PAM_EXTERN int
pam_sm_setcred (pam_handle_t * pamh, int flags, int argc, const char **argv)
{
  return PAM_SUCCESS;
}

PAM_EXTERN int
pam_sm_open_session (pam_handle_t * pamh,
		     int flags, int argc, const char **argv)
{
  return PAM_SUCCESS;
}

PAM_EXTERN int
pam_sm_close_session (pam_handle_t * pamh,
		      int flags, int argc, const char **argv)
{
  return PAM_SUCCESS;
}

PAM_EXTERN int
pam_sm_chauthtok (pam_handle_t * pamh, int flags, int argc, const char **argv)
{
  int rc = PAM_SUCCESS;
  char *username, *curpass = NULL, *newpass = NULL, *expuser = NULL;
  char buf[32], *strvals[2];
  struct pam_conv *appconv;
  struct pam_message msg, *pmsg;
  struct pam_response *resp;
  const char *cmiscptr = NULL;
  int tries = 0, i, canabort = 1;
  pam_ldap_session_t *session = NULL;
  int use_first_pass = 0, try_first_pass = 0, no_warn = 0;
  int use_authtok = 0, ignore_unknown_user = 0;
  char errmsg[1024];
  pam_ldap_password_policy_t policy;
  LDAPMod *mods[2], mod;
  const char *configFile = NULL;
  const char *extraFilter = NULL;

  for (i = 0; i < argc; i++)
    {
      if (!strcmp (argv[i], "use_first_pass"))
	use_first_pass = 1;
      else if (!strcmp (argv[i], "try_first_pass"))
	try_first_pass = 1;
      else if (!strncmp (argv[i], "config=", 7))
	configFile = argv[i] + 7;
      else if (!strncmp (argv[i], "filter=", 7))
	extraFilter = argv[i] + 7;
      else if (!strcmp (argv[i], "no_warn"))
	no_warn = 1;
      else if (!strcmp (argv[i], "ignore_unknown_user"))
	ignore_unknown_user = 1;
      else if (!strcmp (argv[i], "debug"))
	;
      else if (!strcmp (argv[i], "use_authtok"))
	use_authtok = 1;
      else
	syslog (LOG_ERR, "illegal option %s", argv[i]);
    }

  if (flags & PAM_SILENT)
    no_warn = 1;

  rc = pam_get_item (pamh, PAM_CONV, (CONST_ARG void **) &appconv);
  if (rc != PAM_SUCCESS)
    return rc;

  /*
   * Call pam_get_data() to see whether the pre-mapped
   * (non-template) user is available to us. If so,
   * use that instead.
   */
  rc = pam_get_data (pamh, PADL_LDAP_AUTH_DATA, (const void **) &username);
  if (rc != PAM_SUCCESS)
    {
      rc = pam_get_user (pamh, (CONST_ARG char **) &username, NULL);
      if (rc != PAM_SUCCESS)
	return rc;
    }

  if (username == NULL)
    return PAM_USER_UNKNOWN;

  rc = pam_get_data (pamh, PADL_LDAP_AUTHTOK_DATA, (const void **) &expuser);
  if (rc == PAM_SUCCESS && expuser != NULL)
    canabort = (strcmp (username, expuser) == 0) ? 0 : 1;

  rc = _pam_ldap_get_session (pamh, username, configFile, extraFilter, &session);
  if (rc != PAM_SUCCESS)
    return rc;

  if (flags & PAM_PRELIM_CHECK)
    {
      /* see whether the user exists */
      rc = _get_user_info (session, username);
      if (rc == PAM_USER_UNKNOWN && ignore_unknown_user)
	rc = PAM_IGNORE;
      if (rc != PAM_SUCCESS)
	return rc;

      if (!(session->conf->rootbinddn && getuid () == 0))
	{
	  /* we are not root, authenticate old password */
	  if (try_first_pass || use_first_pass)
	    {
	      if (pam_get_item
		  (pamh, PAM_OLDAUTHTOK,
		   (CONST_ARG void **) &curpass) == PAM_SUCCESS &&
		  curpass != NULL)
		{
		  rc = _do_authentication (session, username, curpass);
		  if (rc != PAM_SUCCESS)
		    {
		      if (use_first_pass)
			{
			  _conv_sendmsg (appconv, "LDAP Password incorrect",
					 PAM_ERROR_MSG, no_warn);
			}
		      else
			{
			  _conv_sendmsg (appconv,
					 "LDAP Password incorrect: try again",
					 PAM_ERROR_MSG, no_warn);
			}
		      return rc;
		    }
		}
	      else
		{
		  curpass = NULL;
		}
	    }

	  tries = 0;

	  /* support Netscape Directory Server's password policy */
	  rc = _get_password_policy (session, &policy);
	  if (rc != PAM_SUCCESS)
	    return rc;

	  while ((curpass == NULL) && (tries++ < policy.password_max_failure))
	    {
	      pmsg = &msg;
	      msg.msg_style = PAM_PROMPT_ECHO_OFF;
	      msg.msg = OLD_PASSWORD_PROMPT;
	      resp = NULL;

	      rc = appconv->conv (1, (CONST_ARG struct pam_message **) &pmsg,
				  &resp, appconv->appdata_ptr);

	      if (rc != PAM_SUCCESS)
		return rc;

	      curpass = resp->resp;
	      free (resp);

	      /* authenticate the old password */
	      rc = _do_authentication (session, username, curpass);
	      if (rc != PAM_SUCCESS)
		{
		  int abortme = 0;

		  if (curpass != NULL && curpass[0] == '\0')
		    abortme = 1;

		  _pam_overwrite (curpass);
		  _pam_drop (curpass);

		  if (canabort && abortme)
		    {
		      _conv_sendmsg (appconv, "Password change aborted",
				     PAM_ERROR_MSG, no_warn);
#ifdef PAM_AUTHTOK_RECOVERY_ERR
		      return PAM_AUTHTOK_RECOVERY_ERR;
#else
		      return PAM_AUTHTOK_RECOVER_ERR;
#endif /* PAM_AUTHTOK_RECOVERY_ERR */
		    }
		  else
		    {
		      _conv_sendmsg (appconv,
				     "LDAP Password incorrect: try again",
				     PAM_ERROR_MSG, no_warn);
		    }
		}
	    }			/* while */

	  if (curpass == NULL)
	    return PAM_MAXTRIES;	/* maximum tries exceeded */
	  else
	    pam_set_item (pamh, PAM_OLDAUTHTOK, (void *) curpass);
	}
      else
	{
	  /* we are root */
	  curpass = NULL;
	}

      pam_set_data (pamh, PADL_LDAP_OLDAUTHTOK_DATA,
		    (curpass == NULL) ? NULL : (void *) strdup (curpass),
		    _cleanup_authtok_data);
      return rc;
    }				/* prelim */
  else if (session->info == NULL)	/* this is no LDAP user */
    return (ignore_unknown_user == 1) ? PAM_IGNORE : PAM_USER_UNKNOWN;

  if (use_authtok)
    use_first_pass = 1;

  rc =
    pam_get_data (pamh, PADL_LDAP_OLDAUTHTOK_DATA, (const void **) &curpass);
  if (rc != PAM_SUCCESS)
    {
      syslog (LOG_ERR,
	      "pam_ldap: error getting old authentication token (%s)",
	      pam_strerror (pamh, rc));
#ifdef PAM_AUTHTOK_RECOVERY_ERR
      return PAM_AUTHTOK_RECOVERY_ERR;
#else
      return PAM_AUTHTOK_RECOVER_ERR;
#endif /* PAM_AUTHTOK_RECOVERY_ERR */
    }

  if (try_first_pass || use_first_pass)
    {
      if (pam_get_item (pamh, PAM_AUTHTOK, (CONST_ARG void **) &newpass) !=
	  PAM_SUCCESS)
	newpass = NULL;

      if (use_first_pass && newpass == NULL)
#ifdef PAM_AUTHTOK_RECOVERY_ERR
	return PAM_AUTHTOK_RECOVERY_ERR;
#else
	return PAM_AUTHTOK_RECOVER_ERR;
#endif /* PAM_AUTHTOK_RECOVERY_ERR */
    }

  tries = 0;

  /* support Netscape Directory Server's password policy */
  rc = _get_password_policy (session, &policy);
  if (rc != PAM_SUCCESS)
    return rc;

  while ((newpass == NULL) && (tries++ < policy.password_max_failure))
    {
      pmsg = &msg;
      msg.msg_style = PAM_PROMPT_ECHO_OFF;
      msg.msg = NEW_PASSWORD_PROMPT;
      resp = NULL;

      rc = appconv->conv (1, (CONST_ARG struct pam_message **) &pmsg,
			  &resp, appconv->appdata_ptr);

      if (rc != PAM_SUCCESS)
	return rc;

      newpass = resp->resp;
      free (resp);

      if (newpass[0] == '\0')
	{
	  free (newpass);
	  newpass = NULL;
	}

      if (newpass != NULL)
	{
	  if (getuid () != 0)
	    {
	      if (curpass != NULL && !strcmp (curpass, newpass))
		{
		  cmiscptr = "Passwords must differ";
		  newpass = NULL;
		}
	      else if (strlen (newpass) < policy.password_min_length)
		{
		  cmiscptr = "Password too short";
		  newpass = NULL;
		}
	    }
	}
      else
	{
#ifdef PAM_AUTHTOK_RECOVERY_ERR
	  return PAM_AUTHTOK_RECOVERY_ERR;
#else
	  return PAM_AUTHTOK_RECOVER_ERR;
#endif /* PAM_AUTHTOK_RECOVERY_ERR */
	}

      if (cmiscptr == NULL)
	{
	  /* get password again */
	  char *miscptr;

	  pmsg = &msg;
	  msg.msg_style = PAM_PROMPT_ECHO_OFF;
	  msg.msg = AGAIN_PASSWORD_PROMPT;
	  resp = NULL;

	  rc = appconv->conv (1, (CONST_ARG struct pam_message **) &pmsg,
			      &resp, appconv->appdata_ptr);

	  if (rc != PAM_SUCCESS)
	    return rc;

	  miscptr = resp->resp;
	  free (resp);
	  if (miscptr[0] == '\0')
	    {
	      free (miscptr);
	      miscptr = NULL;
	    }
	  if (miscptr == NULL)
	    {
	      if (canabort)
		{
		  _conv_sendmsg (appconv, "Password change aborted",
				 PAM_ERROR_MSG, no_warn);
#ifdef PAM_AUTHTOK_RECOVERY_ERR
		  return PAM_AUTHTOK_RECOVERY_ERR;
#else
		  return PAM_AUTHTOK_RECOVER_ERR;
#endif /* PAM_AUTHTOK_RECOVERY_ERR */
		}
	    }
	  else if (!strcmp (newpass, miscptr))
	    {
	      miscptr = NULL;
	      break;
	    }

	  _conv_sendmsg (appconv, "You must enter the same password",
			 PAM_ERROR_MSG, no_warn);
	  miscptr = NULL;
	  newpass = NULL;
	}
      else
	{
	  _conv_sendmsg (appconv, cmiscptr, PAM_ERROR_MSG, no_warn);
	  cmiscptr = NULL;
	  newpass = NULL;
	}
    }				/* while */

  if (cmiscptr != NULL || newpass == NULL)
    return PAM_MAXTRIES;

  rc = _update_authtok (session, username, curpass, newpass);
  if (rc != PAM_SUCCESS)
    {
      int lderr;
      char *reason = NULL;

      lderr = ldap_get_lderrno (session->ld, NULL, &reason);
      if (reason != NULL)
	snprintf (errmsg, sizeof errmsg,
		  "LDAP password information update failed: %s\n%s",
		  ldap_err2string (lderr), reason);
      else
	snprintf (errmsg, sizeof errmsg,
		  "LDAP password information update failed: %s",
		  ldap_err2string (lderr));

      _conv_sendmsg (appconv, errmsg, PAM_ERROR_MSG, no_warn);
    }
  else
    {
      /* update shadowLastChange; may fail if not shadowAccount */
      snprintf (buf, sizeof buf, "%ld", time (NULL) / (60 * 60 * 24));
      strvals[0] = buf;
      strvals[1] = NULL;

      mod.mod_values = strvals;
      mod.mod_type = (char *) "shadowLastChange";
      mod.mod_op = LDAP_MOD_REPLACE;

      mods[0] = &mod;
      mods[1] = NULL;

      /* do this silently because it may fail */
      (void) ldap_modify_s (session->ld, session->info->userdn, mods);

      snprintf (errmsg, sizeof errmsg,
		"LDAP password information changed for %s", username);
      _conv_sendmsg (appconv, errmsg, PAM_TEXT_INFO,
		     (flags & PAM_SILENT) ? 1 : 0);
    }

  pam_set_item (pamh, PAM_AUTHTOK, (void *) newpass);

  return rc;
}

PAM_EXTERN int
pam_sm_acct_mgmt (pam_handle_t * pamh, int flags, int argc, const char **argv)
{
  /*
   * check whether the user can login.
   * returns one of:
   *   PAM_ACCT_EXPIRED (account expired)
   *   PAM_PERM_DENIED (authorization failed)
   *   PAM_AUTHTOKEN_REQD (authtoken expired)
   *   PAM_USER_UNKNOWN
   */
  int rc;
  const char *username;
  int no_warn = 0, ignore_unknown_user = 0;
  int i, success = PAM_SUCCESS;
  struct pam_conv *appconv;
  pam_ldap_session_t *session = NULL;
  char buf[1024];
  time_t currenttime;
  long int currentday;
  long int expirein = 0;	/* seconds until password expires */
  const char *configFile = NULL;
  const char *extraFilter = NULL;

  for (i = 0; i < argc; i++)
    {
      if (!strcmp (argv[i], "use_first_pass"))
	;
      else if (!strcmp (argv[i], "try_first_pass"))
	;
      else if (!strncmp (argv[i], "config=", 7))
	configFile = argv[i] + 7;
      else if (!strncmp (argv[i], "filter=", 7))
	extraFilter = argv[i] + 7;
      else if (!strcmp (argv[i], "no_warn"))
	no_warn = 1;
      else if (!strcmp (argv[i], "ignore_unknown_user"))
	ignore_unknown_user = 1;
      else if (!strcmp (argv[i], "debug"))
	;
      else
	syslog (LOG_ERR, "illegal option %s", argv[i]);
    }

  if (flags & PAM_SILENT)
    no_warn = 1;

  rc = pam_get_item (pamh, PAM_CONV, (CONST_ARG void **) &appconv);
  if (rc != PAM_SUCCESS)
    return rc;

  /*
   * Call pam_get_data() to see whether the pre-mapped
   * (non-template) user is available to us. If so,
   * use that instead.
   */
  rc = pam_get_data (pamh, PADL_LDAP_AUTH_DATA, (const void **) &username);
  if (rc != PAM_SUCCESS)
    {
      rc = pam_get_user (pamh, (CONST_ARG char **) &username, NULL);
      if (rc != PAM_SUCCESS)
	return rc;
    }

  if (username == NULL)
    return PAM_USER_UNKNOWN;

  rc = _pam_ldap_get_session (pamh, username, configFile, extraFilter, &session);
  if (rc != PAM_SUCCESS)
    {
      return rc;
    }

  if (session->info == NULL)
    {
      rc = _get_user_info (session, username);
      if (rc != PAM_SUCCESS)
	{
	  if (rc == PAM_USER_UNKNOWN && ignore_unknown_user)
	    rc = PAM_IGNORE;
	  return rc;
	}
    }

  /* Grab the current time */
  time (&currenttime);
  currentday = (long int) (currenttime / SECSPERDAY);

  /* Check shadow expire conditions */
  /* Do we have an absolute expiry date? */
  if (session->info->shadow.expire > 0)
    {
      if (currentday >= session->info->shadow.expire)
	{
	  return PAM_ACCT_EXPIRED;
	}
    }

  /*
   * Also check if user hasn't changed password for the inactive
   * amount of time.  This also counts as an expired account.
   */
  if ((session->info->shadow.lstchg > 0) &&
      (session->info->shadow.max > 0) && (session->info->shadow.inact > 0))
    {
      if (currentday >= (session->info->shadow.lstchg +
			 session->info->shadow.max +
			 session->info->shadow.inact))
	{
	  return PAM_ACCT_EXPIRED;
	}
    }

  /* Our shadow information should be populated, so do some calculations */
  if ((session->info->shadow.lstchg > 0) && (session->info->shadow.max > 0))
    {
      if (currentday >= (session->info->shadow.lstchg +
			 session->info->shadow.max))
	{
	  session->info->password_expired = 1;
	}
    }

  /* check whether the password has expired */
  if (session->info->password_expired)
    {
      _conv_sendmsg (appconv,
		     "You are required to change your LDAP password immediately.",
		     PAM_ERROR_MSG, no_warn);
#ifdef LINUX
      success = PAM_AUTHTOKEN_REQD;
#else
      success = PAM_NEW_AUTHTOK_REQD;
#endif /* LINUX */

#ifdef notdef			/* ?????? */
#ifdef PAM_AUTHTOK_EXPIRED
      success = PAM_AUTHTOK_EXPIRED;
#else
      success = PAM_AUTHTOKEN_REQD;
#endif
#endif /* notdef */
    }

  /*
   * Warnings.  First, check if we've got a non-zero warning time
   * in the shadow struct.  If so, we're a shadow account, and set
   * things accordingly.  Otherwise, check the Netscape controls.
   */

  /*
   * If the password's expired, no sense warning
   */

  if (!session->info->password_expired)
    {
      if (session->info->shadow.warn > 0)	/* shadowAccount */
	{
	  /*
	   * Are we within warning period?
	   */

	  expirein = session->info->shadow.lstchg +
	    session->info->shadow.max - currentday;

	  if (session->info->shadow.warn <= expirein)
	    {
	      expirein = 0;	/* Not within warning period yet */
	    }
	}
      else
	{
	  expirein = session->info->password_expiration_time / SECSPERDAY;
	}

      if (expirein > 0)
	{
	  snprintf (buf, sizeof buf,
		    "Your LDAP password will expire in %ld day%s.",
		    expirein, (expirein == 1) ? "" : "s");
	  _conv_sendmsg (appconv, buf, PAM_ERROR_MSG, no_warn);

	  /* we set this to make sure that user can't abort a password change */
	  (void) pam_set_data (pamh, PADL_LDAP_AUTHTOK_DATA,
			       (void *) strdup (username), _cleanup_data);
	}
    }				/* password expired */

  /* group auth, per Chris's pam_ldap_auth module */
  if (session->conf->groupdn != NULL)
    {
      rc = ldap_compare_s (session->ld,
			   session->conf->groupdn,
			   session->conf->groupattr, session->info->userdn);
      if (rc != LDAP_COMPARE_TRUE)
	{
	  snprintf (buf, sizeof buf, "You must be a %s of %s to login.",
		    session->conf->groupattr, session->conf->groupdn);
	  _conv_sendmsg (appconv, buf, PAM_ERROR_MSG, no_warn);
	  return PAM_PERM_DENIED;
	}
      else
	rc = success;
    }

  if (session->conf->checkhostattr)
    {
      rc = _host_ok (session);
      if (rc != PAM_SUCCESS)
	_conv_sendmsg (appconv, "Access denied for this host", PAM_ERROR_MSG,
		       no_warn);
      else
	rc = success;
    }

  if (session->conf->min_uid && session->info->uid < session->conf->min_uid)
    {
      snprintf (buf, sizeof buf, "UID must be greater than %ld",
		(long) session->conf->min_uid);
      _conv_sendmsg (appconv, buf, PAM_ERROR_MSG, no_warn);
      return PAM_PERM_DENIED;
    }

  if (session->conf->max_uid && session->info->uid > session->conf->max_uid)
    {
      snprintf (buf, sizeof buf, "UID must be less than %ld",
		(long) session->conf->max_uid);
      _conv_sendmsg (appconv, buf, PAM_ERROR_MSG, no_warn);
      return PAM_PERM_DENIED;
    }

  return rc;
}

/* static module data */
#ifdef PAM_STATIC
struct pam_module _modstruct = {
  "pam_ldap",
  pam_sm_authenticate,
  pam_sm_setcred,
  pam_sm_acct_mgmt,
  pam_sm_open_session, pam_sm_close_session, pam_sm_chauthtok
};
#endif /* PAM_STATIC */