File: ldap-nss.c

package info (click to toggle)
libnss-ldap 186-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,028 kB
  • ctags: 990
  • sloc: ansic: 9,646; sh: 2,270; perl: 129; makefile: 106
file content (2829 lines) | stat: -rw-r--r-- 66,518 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
/* Copyright (C) 1997-2002 Luke Howard.
   This file is part of the nss_ldap library.
   Contributed by Luke Howard, <lukeh@padl.com>, 1997.

   The nss_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 nss_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 nss_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.
 */

static char rcsId[] =
  "$Id: ldap-nss.c,v 2.153 2002/04/04 03:57:09 lukeh Exp $";

#include "config.h"

#ifdef HAVE_PORT_BEFORE_H
#include <port_before.h>
#endif

#ifdef HAVE_THREAD_H
#include <thread.h>
#elif defined(HAVE_PTHREAD_H)
#include <pthread.h>
#endif

#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include <stdio.h>
#include <syslog.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>

#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

#include "ldap-lutil.h"

#ifdef AT_OC_MAP
#ifdef HAVE_DB3_DB_185_H
#include <db3/db_185.h>
#else
#ifdef HAVE_DB_185_H
#include <db_185.h>
#elif defined(HAVE_DB1_DB_H)
#include <db1/db.h>
#elif defined(HAVE_DB_H)
#include <db.h>
#endif /* HAVE_DB1_DB_H */
#endif /* HAVE_DB3_DB_H */
#endif /* AT_OC_MAP */

#ifndef HAVE_SNPRINTF
#include "snprintf.h"
#endif

#include "ldap-nss.h"
#include "ltf.h"
#include "globals.h"
#include "util.h"
#include "dnsconfig.h"

#ifdef HAVE_THREAD_H
#ifdef HAVE_PTHREAD_ATFORK
#undef HAVE_PTHREAD_ATFORK
#endif
#endif

/* how many messages to retrieve results for */
#ifndef LDAP_MSG_ONE
#define LDAP_MSG_ONE            0x00
#endif
#ifndef LDAP_MSG_ALL
#define LDAP_MSG_ALL            0x01
#endif
#ifndef LDAP_MSG_RECEIVED
#define LDAP_MSG_RECEIVED       0x02
#endif

#ifdef HAVE_LDAP_LD_FREE
#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
extern int ldap_ld_free (LDAP * ld, int close, LDAPControl **,
			 LDAPControl **);
#else
extern int ldap_ld_free (LDAP * ld, int close);
#endif /* OPENLDAP 2.x */
#endif /* HAVE_LDAP_LD_FREE */

NSS_LDAP_DEFINE_LOCK (__lock);

/*
 * the configuration is read by the first call to do_open().
 * Pointers to elements of the list are passed around but should not
 * be freed.
 */
static char __configbuf[NSS_LDAP_CONFIG_BUFSIZ];
static ldap_config_t *__config = NULL;

static void (*__sigpipe_handler) (int) = SIG_DFL;

/*
 * Global LDAP session.
 */
static ldap_session_t __session = { NULL, NULL, 0 };

#if defined(HAVE_PTHREAD_ATFORK) || defined(HAVE_LIBC_LOCK_H) || defined(HAVE_BITS_LIBC_LOCK_H)
static pthread_once_t __once = PTHREAD_ONCE_INIT;
#endif

#ifndef HAVE_PTHREAD_ATFORK
/* 
 * Process ID that opened the session.
 */
static pid_t __pid = -1;
#endif
static uid_t __euid = -1;

#ifdef HAVE_LDAPSSL_CLIENT_INIT
static int __ssl_initialized = 0;
#endif /* HAVE_LDAPSSL_CLIENT_INIT */

#if defined(HAVE_PTHREAD_ATFORK) || defined(HAVE_LIBC_LOCK_H) || defined(HAVE_BITS_LIBC_LOCK_H)
/*
 * Prepare for fork(); lock mutex.
 */
static void do_atfork_prepare (void);

/*
 * Forked in parent, unlock mutex.
 */
static void do_atfork_parent (void);

/*
 * Forked in child; close LDAP socket, unlock mutex.
 */
static void do_atfork_child (void);

/*
 * Install handlers for atfork, called once.
 */
static void do_atfork_setup (void);
#endif

/*
 * Close the global session, sending an unbind.
 */
static void do_close (void);

/*
 * Close the global session without sending an unbind.
 */
static void do_close_no_unbind (void);

/*
 * Disable keepalive on a LDAP connection's socket.
 */
static void do_set_sockopts (void);

/*
 * TLS routines: set global SSL session options.
 */
#if defined HAVE_LDAP_START_TLS_S || (defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS))
static int do_ssl_options (ldap_config_t * cfg);
#endif

/*
 * Open the global session
 */
static NSS_STATUS do_open (void);

/*
 * Perform an asynchronous search.
 */
static int do_search (const char *base, int scope,
		      const char *filter, const char **attrs,
		      int sizelimit, int *);

/*
 * Perform a synchronous search.
 */
static int do_search_s (const char *base, int scope,
			const char *filter, const char **attrs,
			int sizelimit, LDAPMessage **);

/*
 * Fetch an LDAP result.
 */
static NSS_STATUS do_result (ent_context_t * ctx, int all);

/*
 * Format a filter given a prototype.
 */
static NSS_STATUS do_filter (const ldap_args_t * args, const char *filterprot,
			     ldap_service_search_descriptor_t * sd,
			     char *filter, size_t filterlen,
			     const char **retFilter);

/*
 * Parse a result, fetching new results until a successful parse
 * or exceptional condition.
 */
static NSS_STATUS do_parse (ent_context_t * ctx, void *result, char *buffer,
			    size_t buflen, int *errnop, parser_t parser);

/*
 * Parse a result, fetching results from the result chain 
 * rather than the server.
 */
static NSS_STATUS do_parse_s (ent_context_t * ctx, void *result, char *buffer,
			      size_t buflen, int *errnop, parser_t parser);

/*
 * Function to be braced by reconnect harness. Used so we
 * can apply the reconnect code to both asynchronous and
 * synchronous searches.
 */
typedef int (*search_func_t) (const char *, int, const char *,
			      const char **, int, void *);

/*
 * Do a search with a reconnect harness.
 */
static NSS_STATUS
do_with_reconnect (const char *base, int scope,
		   const char *filter, const char **attrs, int sizelimit,
		   void *private, search_func_t func);

/*
 * Do a bind with a defined timeout
 */
static int do_bind (LDAP * ld, int timelimit, const char *dn, const char *pw,
		    int with_sasl);

/*
 * Rebind functions.
 */

#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
#if LDAP_SET_REBIND_PROC_ARGS == 3
static int
do_rebind (LDAP * ld, LDAP_CONST char *url, ber_tag_t request,
	   ber_int_t msgid, void *arg)
#else
static int
do_rebind (LDAP * ld, LDAP_CONST char *url, int request, ber_int_t msgid)
#endif
{
  char *who, *cred;
  int timelimit;
  int with_sasl = 0;

  if (geteuid () == 0 && __session.ls_config->ldc_rootbinddn)
    {
      who = __session.ls_config->ldc_rootbinddn;
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
      with_sasl = __session.ls_config->ldc_rootusesasl;
      if (with_sasl)
	{
	  cred = __session.ls_config->ldc_rootsaslid;
	}
      else
	{
#endif
	  cred = __session.ls_config->ldc_rootbindpw;
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
	}
#endif
    }
  else
    {
      who = __session.ls_config->ldc_binddn;
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
      with_sasl = __session.ls_config->ldc_usesasl;
      if (with_sasl)
	{
	  cred = __session.ls_config->ldc_saslid;
	}
      else
	{
#endif
	  cred = __session.ls_config->ldc_bindpw;
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
	}
#endif
    }

  timelimit = __session.ls_config->ldc_bind_timelimit;

  return do_bind (ld, timelimit, who, cred, with_sasl);
}
#else
#if LDAP_SET_REBIND_PROC_ARGS == 3
static int
do_rebind (LDAP * ld, char **whop, char **credp, int *methodp,
	   int freeit, void *arg)
#elif LDAP_SET_REBIND_PROC_ARGS == 2
static int
do_rebind (LDAP * ld, char **whop, char **credp, int *methodp, int freeit)
#endif
{
  if (freeit)
    {
      if (*whop != NULL)
	free (*whop);
      if (*credp != NULL)
	free (*credp);
    }

  *whop = *credp = NULL;
  if (geteuid () == 0 && __session.ls_config->ldc_rootbinddn)
    {
      *whop = strdup (__session.ls_config->ldc_rootbinddn);
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
      with_sasl = __session.ls_config->ldc_rootusesasl;
      if (with_sasl && __session.ls_config->ldc_rootsaslid)
	{
	  *credp = __session.ls_config->ldc_rootsaslid;
	}
      else
#endif
      if (__session.ls_config->ldc_rootbindpw)
	*credp = strdup (__session.ls_config->ldc_rootbindpw);
    }
  else
    {
      if (__session.ls_config->ldc_binddn != NULL)
	*whop = strdup (__session.ls_config->ldc_binddn);
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
      with_sasl = __session.ls_config->ldc_usesasl;
      if (with_sasl && __session.ls_config->ldc_saslid)
	{
	  *credp = __session.ls_config->ldc_saslid;
	}
      else
#endif
      if (__session.ls_config->ldc_bindpw != NULL)
	*credp = strdup (__session.ls_config->ldc_bindpw);
    }

  *methodp = LDAP_AUTH_SIMPLE;

  return LDAP_SUCCESS;
}
#endif

#ifdef HAVE_NSSWITCH_H
/*
 * Default destructor.
 * The entry point for this function is the destructor in the dispatch
 * table for the switch. Thus, it's safe to grab the mutex from this
 * function.
 */
NSS_STATUS
_nss_ldap_default_destr (nss_backend_t * be, void *args)
{
  debug ("==> _nss_ldap_default_destr");

  if ((((nss_ldap_backend_t *) be)->state) != NULL)
    {
      _nss_ldap_enter ();
      _nss_ldap_ent_context_release ((((nss_ldap_backend_t *) be)->state));
      free ((((nss_ldap_backend_t *) be)->state));
      ((nss_ldap_backend_t *) be)->state = NULL;
      _nss_ldap_leave ();
    }

  /* Ditch the backend. */
  free (be);

  debug ("<== _nss_ldap_default_destr");

  return NSS_SUCCESS;
}

/*
 * This is the default "constructor" which gets called from each 
 * constructor, in the NSS dispatch table.
 */
NSS_STATUS
_nss_ldap_default_constr (nss_ldap_backend_t * be)
{
  debug ("==> _nss_ldap_default_constr");

  be->state = NULL;

  debug ("<== _nss_ldap_default_constr");

  return NSS_SUCCESS;
}
#endif /* HAVE_NSSWITCH_H */

#if defined(HAVE_PTHREAD_ATFORK) || defined(HAVE_LIBC_LOCK_H) || defined(HAVE_BITS_LIBC_LOCK_H)
static void
do_atfork_prepare (void)
{
  debug ("==> do_atfork_prepare");
  NSS_LDAP_LOCK (__lock);
  debug ("<== do_atfork_prepare");
}

static void
do_atfork_parent (void)
{
  debug ("==> do_atfork_parent");
  NSS_LDAP_UNLOCK (__lock);
  debug ("<== do_atfork_parent");
}

static void
do_atfork_child (void)
{
  debug ("==> do_atfork_child");
  do_close_no_unbind ();
  NSS_LDAP_UNLOCK (__lock);
  debug ("<== do_atfork_child");
}

static void
do_atfork_setup (void)
{
  debug ("==> do_atfork_setup");

#ifdef HAVE_PTHREAD_ATFORK
  (void) pthread_atfork (do_atfork_prepare, do_atfork_parent,
			 do_atfork_child);
#elif defined(HAVE_LIBC_LOCK_H) || defined(HAVE_BITS_LIBC_LOCK_H)
  (void) __libc_atfork (do_atfork_prepare, do_atfork_parent, do_atfork_child);
#endif

  debug ("<== do_atfork_setup");
}
#endif

/*
 * Acquires global lock, blocks SIGPIPE.
 */
void
_nss_ldap_enter (void)
{
  debug ("==> _nss_ldap_enter");

  NSS_LDAP_LOCK (__lock);

  /*
   * Patch for Debian Bug 130006:
   * ignore SIGPIPE for all LDAP operations.
   */
#ifdef HAVE_SIGSET
  __sigpipe_handler = sigset (SIGPIPE, SIG_IGN);
#else
  __sigpipe_handler = signal (SIGPIPE, SIG_IGN);
#endif /* HAVE_SIGSET */

  debug ("<== _nss_ldap_leave");
}

/*
 * Releases global mutex, releases SIGPIPE.
 */
void
_nss_ldap_leave (void)
{
  debug ("==> _nss_ldap_leave");

  /*
   * Restore signal handler for SIGPIPE.
   */
  if (__sigpipe_handler != SIG_ERR && __sigpipe_handler != SIG_IGN)
    {
#ifdef HAVE_SIGSET
      (void) sigset (SIGPIPE, __sigpipe_handler);
#else
      (void) signal (SIGPIPE, __sigpipe_handler);
#endif /* HAVE_SIGSET */
    }

  NSS_LDAP_UNLOCK (__lock);

  debug ("<== _nss_ldap_leave");
}

static void
do_set_sockopts (void)
{
/*
 * Netscape SSL-enabled LDAP library does not
 * return the real socket.
 */
#ifndef HAVE_LDAPSSL_CLIENT_INIT
  int sd = -1;

  debug ("==> do_set_sockopts");
#if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_DESC)
  if (ldap_get_option (__session.ls_conn, LDAP_OPT_DESC, &sd) == 0)
#else
  if ((sd = __session.ls_conn->ld_sb.sb_sd) > 0)
#endif /* LDAP_OPT_DESC */
    {
      int off = 0;
      int namelen = sizeof (struct sockaddr);

      (void) setsockopt (sd, SOL_SOCKET, SO_KEEPALIVE, &off, sizeof (off));
      (void) fcntl (sd, F_SETFD, FD_CLOEXEC);
      /*
       * NSS modules shouldn't open file descriptors that the program/utility
       * linked against NSS doesn't know about.  The LDAP library opens a
       * connection to the LDAP server transparently.  There's an edge case
       * where a daemon might fork a child and, being written well, closes
       * all its file descriptors.  This will close the socket descriptor
       * being used by the LDAP library!  Worse, the daemon might open many
       * files and sockets, eventually opening a descriptor with the same number
       * as that originally used by the LDAP library.  The only way to know that
       * this isn't "our" socket descriptor is to save the local and remote
       * sockaddr_in structures for later comparison in do_close_no_unbind ().
       */
      (void) getsockname (sd, &__session.ls_sockname, &namelen);
      (void) getpeername (sd, &__session.ls_peername, &namelen);
    }
  debug ("<== do_set_sockopts");
#endif /* HAVE_LDAPSSL_CLIENT_INIT */

  return;
}

/*
 * Closes connection to the LDAP server.
 * This assumes that we have exclusive access to __session.ls_conn,
 * either by some other function having acquired a lock, or by
 * using a thread safe libldap.
 */
static void
do_close (void)
{
  debug ("==> do_close");

  if (__session.ls_conn != NULL)
    {
#ifdef DEBUG
      syslog (LOG_DEBUG, "nss_ldap: closing connection %p",
		 __session.ls_conn);
#endif /* DEBUG */
      ldap_unbind (__session.ls_conn);
      __session.ls_conn = NULL;
    }

  debug ("<== do_close");
}

/*
 * If we've forked, then we need to open a new session.
 * Careful: we have the socket shared with our parent,
 * so we don't want to send an unbind to the server.
 * However, we want to close the descriptor to avoid
 * leaking it, and we also want to release the memory
 * used by __session.ls_conn. The only entry point
 * we have is ldap_unbind() which does both of these
 * things, so we use an internal API, at the expense
 * of compatibility.
 */
static void
do_close_no_unbind (void)
{
  int sd;
  int bogusSd = -1;

  debug ("==> do_close_no_unbind");

  if (__session.ls_conn == NULL)
    {
      debug ("<== do_close_no_unbind (connection was not open)");
      return;
    }

#ifdef DEBUG
  syslog (LOG_DEBUG, "nss_ldap: closing connection (no unbind) %p",
	     __session.ls_conn);
#endif /* DEBUG */

  /*
   * Before freeing the LDAP context or closing the socket descriptor, we
   * must ensure that it is *our* socket descriptor.  See the much lengthier
   * description of this at the end of do_open () where the values
   * __session.ls_sockname and __session.ls_peername are saved.
   */
#ifndef HAVE_LDAPSSL_CLIENT_INIT
#if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_DESC)
  if (ldap_get_option (__session.ls_conn, LDAP_OPT_DESC, &sd) == 0)
#else
  if ((sd = ld->ld_sb.sb_sd) > 0)
#endif /* LDAP_OPT_DESC */
    {
      struct sockaddr sockname;
      struct sockaddr peername;
      int socknamelen = sizeof (struct sockaddr);
      int peernamelen = sizeof (struct sockaddr);

      if ((getsockname (sd, &sockname, &socknamelen) != 0)
	  || (memcmp (&sockname, &__session.ls_sockname, socknamelen) != 0)
	  || (getpeername (sd, &peername, &peernamelen) != 0)
	  || (memcmp (&peername, &__session.ls_peername, peernamelen) != 0))
	{
	  __session.ls_conn = NULL; /* leaky */
	  debug ("<== do_close_no_unbind (invalid socket descriptor)");
	  return;
	}
    }
#endif /* HAVE_LDAPSSL_CLIENT_INIT */

#ifdef HAVE_LDAP_LD_FREE

#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
  (void) ldap_ld_free (__session.ls_conn, 0, NULL, NULL);
#else
  (void) ldap_ld_free (__session.ls_conn, 0);
#endif /* OPENLDAP 2.x */

#else
  close (sd);
#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_DESC)
  (void) ldap_set_option (__session.ls_conn, LDAP_OPT_DESC, &bogusSd);
#else
  __session.ls_conn->ld_sb.sb_sd = bogusSd;
#endif /* LDAP_OPT_DESC */

  /* hope we closed it OK! */
  ldap_unbind (__session.ls_conn);

#endif /* HAVE_LDAP_LD_FREE */

  __session.ls_conn = NULL;

  debug ("<== do_close_no_unbind");

  return;
}

/*
 * A simple alias around do_open().
 */
NSS_STATUS
_nss_ldap_init (void)
{
  return do_open ();
}

/*
 * Opens connection to an LDAP server.
 * As with do_close(), this assumes ownership of sess.
 * It also wants to own __config: is there a potential deadlock here? XXX
 */
static NSS_STATUS
do_open (void)
{
  ldap_config_t *cfg = NULL;
  uid_t euid;
#ifndef HAVE_PTHREAD_ATFORK
  pid_t pid;
#endif
#ifdef LDAP_X_OPT_CONNECT_TIMEOUT
  int timeout;
#endif
#ifdef LDAP_OPT_NETWORK_TIMEOUT
  struct timeval tv;
#endif
  int usesasl;
  char *bindarg;

  debug ("==> do_open");

#ifndef HAVE_PTHREAD_ATFORK
#if defined(HAVE_LIBC_LOCK_H) || defined(HAVE_BITS_LIBC_LOCK_H)
  /*
   * This bogosity is necessary because Linux uses different
   * PIDs for different threads (like IRIX, which we don't
   * support). We can tell whether we are linked against
   * libpthreads by whether __pthread_atfork is NULL or
   * not. If it is NULL, then we're not linked with the
   * threading library, and we need to compare the current
   * process ID against the saved one to figure out
   * whether we've forked. 
   * 
   * Once we know whether we have forked or not, 
   * courtesy of pthread_atfork() or us checking
   * ourselves, we can close the socket to the LDAP
   * server to avoid leaking a socket, and reopen
   * another connection. Under no circumstances do we
   * wish to use the same connection, or to send an
   * unbind PDU over the parents connection, as that
   * will wreak all sorts of havoc or ineffiencies,
   * respectively.
   */
  if (__pthread_atfork == NULL)
    pid = getpid ();
  else
    pid = -1;			/* linked against libpthreads, don't care */
#else
  pid = getpid ();
#endif /* HAVE_LIBC_LOCK_H || HAVE_BITS_LIBC_LOCK_H */
#endif /* HAVE_PTHREAD_ATFORK */

  euid = geteuid ();

#ifdef DEBUG
#ifdef HAVE_PTHREAD_ATFORK
  syslog (LOG_DEBUG,
	     "nss_ldap: __session.ls_conn=%p, __euid=%i, euid=%i",
	     __session.ls_conn, __euid, euid);
#elif defined(HAVE_LIBC_LOCK_H) || defined(HAVE_BITS_LIBC_LOCK_H)
  syslog (LOG_DEBUG,
	     "nss_ldap: libpthreads=%s, __session.ls_conn=%p, __pid=%i, pid=%i, __euid=%i, euid=%i",
	     (__pthread_atfork == NULL ? "FALSE" : "TRUE"),
	     __session.ls_conn,
	     (__pthread_atfork == NULL ? __pid : -1),
	     (__pthread_atfork == NULL ? pid : -1), __euid, euid);
#else
  syslog (LOG_DEBUG,
	     "nss_ldap: __session.ls_conn=%p, __pid=%i, pid=%i, __euid=%i, euid=%i",
	     __session.ls_conn, __pid, pid, __euid, euid);
#endif
#endif /* DEBUG */

#ifndef HAVE_PTHREAD_ATFORK
#if defined(HAVE_LIBC_LOCK_H) || defined(HAVE_BITS_LIBC_LOCK_H)
  if (__pthread_atfork == NULL && __pid != pid)
#else
  if (__pid != pid)
#endif /* HAVE_LIBC_LOCK_H || HAVE_BITS_LIBC_LOCK_H */
    {
      do_close_no_unbind ();
    }
  else
#endif /* HAVE_PTHREAD_ATFORK */
  if (__euid != euid && (__euid == 0 || euid == 0))
    {
      /*
       * If we've changed user ids, close the session so we can
       * rebind as the correct user.
       */
      do_close ();
    }
  else if (__session.ls_conn != NULL && __session.ls_config != NULL)
    {
      /*
       * Patch from Steven Barrus <sbarrus@eng.utah.edu> to
       * close the session after an idle timeout.
       */
      time_t current_time;
      /*
       * Otherwise we can hand back this process' global
       * LDAP session.
       *
       * Patch from Steven Barrus <sbarrus@eng.utah.edu> to
       * close the session after an idle timeout. 
       */
      if (__session.ls_config->ldc_idle_timelimit)
	{
	  time (&current_time);
	  if ((__session.ls_timestamp +
	       __session.ls_config->ldc_idle_timelimit) < current_time)
	    {
	      debug ("idle_timelimit reached");
	      do_close ();
	    }
	}

      /*
       * If the connection is still there (ie. do_close() wasn't
       * called) then we can return the cached connection.
       */
      if (__session.ls_conn != NULL)
	{
	  debug ("<== do_open");
	  return NSS_SUCCESS;
	}
    }

#ifdef HAVE_PTHREAD_ATFORK
  if (pthread_once (&__once, do_atfork_setup) != 0)
    {
      debug ("<== do_open");
      return NSS_UNAVAIL;
    }
#elif defined(HAVE_LIBC_LOCK_H) || defined(HAVE_BITS_LIBC_LOCK_H)
  /*
   * Only install the pthread_atfork() handlers i
   * we are linked against libpthreads. Otherwise,
   * do close the session when the PID changes.
   */
  if (__pthread_atfork == NULL)
    __pid = pid;
  else
    __libc_once (__once, do_atfork_setup);
#else
  __pid = pid;
#endif

  __euid = euid;
  memset (&__session, 0, sizeof (__session));

  if (__config == NULL)
    {
      NSS_STATUS stat;

      stat =
	_nss_ldap_readconfig (&__config, __configbuf, sizeof (__configbuf));

      if (stat != NSS_SUCCESS)
	{
	  __config = NULL;	/* reset otherwise heap is corrupted */
	  stat =
	    _nss_ldap_readconfigfromdns (&__config, __configbuf,
					 sizeof (__configbuf));
	}

      if (stat != NSS_SUCCESS)
	{
	  __config = NULL;
	  debug ("<== do_open");
	  return stat;
	}
    }

  cfg = __config;

  _nss_ldap_init_attributes (cfg->ldc_attrtab);
  _nss_ldap_init_filters ();

  while (1)
    {
#ifdef HAVE_LDAPSSL_CLIENT_INIT
      /*
       * Initialize the SSL library. 
       */
      if (cfg->ldc_ssl_on == SSL_LDAPS)
	{
	  if (__ssl_initialized == 0
	      && ldapssl_client_init (cfg->ldc_sslpath, NULL) != LDAP_SUCCESS)
	    {
	      break;
	    }
	  __ssl_initialized = 1;
	}
#endif /* SSL */
#ifdef HAVE_LDAP_INITIALIZE
      __session.ls_conn = NULL;
      if (cfg->ldc_uri != NULL)
	{
	  int rc;
	  debug ("==> ldap_initialize");
	  rc = ldap_initialize (&__session.ls_conn, cfg->ldc_uri);
	  debug ("<== ldap_initialize");

	  if (rc != LDAP_SUCCESS)
	    {
	      break;
	    }
	}
      else
	{
#endif /* HAVE_LDAP_INITIALIZE */
#ifdef HAVE_LDAP_INIT
	  debug ("==> ldap_init");
	  __session.ls_conn = ldap_init (cfg->ldc_host, cfg->ldc_port);
	  debug ("<== ldap_init");
#else
	  debug ("==> ldap_open");
	  __session.ls_conn = ldap_open (cfg->ldc_host, cfg->ldc_port);
	  debug ("<== ldap_open");
#endif /* HAVE_LDAP_INIT */
#ifdef HAVE_LDAP_INITIALIZE
	}
#endif
      if (__session.ls_conn != NULL || cfg->ldc_next == cfg)
	{
	  break;
	}
      cfg = cfg->ldc_next;
    }

  if (__session.ls_conn == NULL)
    {
      debug ("<== do_open");
      return NSS_UNAVAIL;
    }

#ifdef LDAP_OPT_THREAD_FN_PTRS
  if (_nss_ldap_ltf_thread_init (__session.ls_conn) != NSS_SUCCESS)
    {
      do_close ();
      debug ("<== do_open");
      return NSS_UNAVAIL;
    }
#endif /* LDAP_OPT_THREAD_FN_PTRS */

#if LDAP_SET_REBIND_PROC_ARGS == 3
  ldap_set_rebind_proc (__session.ls_conn, do_rebind, NULL);
#elif LDAP_SET_REBIND_PROC_ARGS == 2
  ldap_set_rebind_proc (__session.ls_conn, do_rebind);
#endif

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_PROTOCOL_VERSION)
  ldap_set_option (__session.ls_conn, LDAP_OPT_PROTOCOL_VERSION,
		   &cfg->ldc_version);
#else
  __session.ls_conn->ld_version = cfg->ldc_version;
#endif /* LDAP_OPT_PROTOCOL_VERSION */

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_DEREF)
  ldap_set_option (__session.ls_conn, LDAP_OPT_DEREF, &cfg->ldc_deref);
#else
  __session.ls_conn->ld_deref = cfg->ldc_deref;
#endif /* LDAP_OPT_DEREF */

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_TIMELIMIT)
  ldap_set_option (__session.ls_conn, LDAP_OPT_TIMELIMIT,
		   &cfg->ldc_timelimit);
#else
  __session.ls_conn->ld_timelimit = cfg->ldc_timelimit;
#endif /* LDAP_OPT_TIMELIMIT */

#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 = cfg->ldc_bind_timelimit * 1000;
  ldap_set_option (__session.ls_conn, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout);
#endif /* LDAP_X_OPT_CONNECT_TIMEOUT */

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_NETWORK_TIMEOUT)
  tv.tv_sec = cfg->ldc_bind_timelimit;
  tv.tv_usec = 0;
  ldap_set_option (__session.ls_conn, LDAP_OPT_NETWORK_TIMEOUT, &tv);
#endif /* LDAP_OPT_NETWORK_TIMEOUT */

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_REFERRALS)
  ldap_set_option (__session.ls_conn, LDAP_OPT_REFERRALS,
		   cfg->ldc_referrals ? LDAP_OPT_ON : LDAP_OPT_OFF);
#endif

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_RESTART)
  ldap_set_option (__session.ls_conn, LDAP_OPT_RESTART,
		   cfg->ldc_restart ? LDAP_OPT_ON : LDAP_OPT_OFF);
#endif

#ifdef HAVE_LDAP_START_TLS_S
  if (cfg->ldc_ssl_on == SSL_START_TLS)
    {
      int version;

      if (ldap_get_option
	  (__session.ls_conn, LDAP_OPT_PROTOCOL_VERSION,
	   &version) == LDAP_OPT_SUCCESS)
	{
	  if (version < LDAP_VERSION3)
	    {
	      version = LDAP_VERSION3;
	      ldap_set_option (__session.ls_conn, LDAP_OPT_PROTOCOL_VERSION,
			       &version);
	    }
	}

      /* set up SSL context */
      if (do_ssl_options (cfg) != LDAP_SUCCESS)
	{
	  debug ("Setting of SSL options failed");
	}

      debug ("==> start_tls");
      if (ldap_start_tls_s (__session.ls_conn, NULL, NULL) == LDAP_SUCCESS)
	{
	  debug ("TLS startup succeeded");
	}
      else
	{
	  debug ("TLS startup failed");
	  do_close ();
	  debug ("<== do_open");
	  return NSS_UNAVAIL;
	}
      debug ("<== start_tls");
    }
  else
#endif /* HAVE_LDAP_START_TLS_S */

    /*
     * If SSL is desired, then enable it.
     */
  if (cfg->ldc_ssl_on == SSL_LDAPS)
    {
#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS)
      int tls = LDAP_OPT_X_TLS_HARD;
      if (ldap_set_option (__session.ls_conn, LDAP_OPT_X_TLS, &tls) !=
	  LDAP_SUCCESS)
	{
	  do_close ();
	  debug ("<== do_open");
	  return NSS_UNAVAIL;
	}

      /* set up SSL context */
      (void) do_ssl_options (cfg);

#elif defined(HAVE_LDAPSSL_CLIENT_INIT)
      if (ldapssl_install_routines (__session.ls_conn) != LDAP_SUCCESS)
	{
	  do_close ();
	  debug ("<== do_open");
	  return NSS_UNAVAIL;
	}
      if (ldap_set_option (__session.ls_conn, LDAP_OPT_SSL, LDAP_OPT_ON) !=
	  LDAP_SUCCESS)
	{
	  do_close ();
	  debug ("<== do_open");
	  return NSS_UNAVAIL;
	}
#endif
    }

  /*
   * If we're running as root, let us bind as a special
   * user, so we can fake shadow passwords.
   * Thanks to Doug Nazar <nazard@dragoninc.on.ca> for this
   * patch.
   */
  if (euid == 0 && cfg->ldc_rootbinddn != NULL)
    {
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
      usesasl = cfg->ldc_rootusesasl;
      bindarg =
	cfg->ldc_rootusesasl ? cfg->ldc_rootsaslid : cfg->ldc_rootbindpw;
#else
      usesasl = 0;
      bindarg = cfg->ldc_rootbindpw;
#endif

      if (do_bind
	  (__session.ls_conn, cfg->ldc_bind_timelimit, cfg->ldc_rootbinddn,
	   bindarg, usesasl) != LDAP_SUCCESS)
	{
	  do_close ();
	  debug ("<== do_open");
	  return NSS_UNAVAIL;
	}
    }
  else
    {
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
      usesasl = cfg->ldc_usesasl;
      bindarg = cfg->ldc_usesasl ? cfg->ldc_saslid : cfg->ldc_bindpw;
#else
      usesasl = 0;
      bindarg = cfg->ldc_bindpw;
#endif

      if (do_bind
	  (__session.ls_conn, cfg->ldc_bind_timelimit, cfg->ldc_binddn,
	   cfg->ldc_bindpw, usesasl) != LDAP_SUCCESS)
	{
	  do_close ();
	  debug ("<== do_open");
	  return NSS_UNAVAIL;
	}
    }

  do_set_sockopts ();

  __session.ls_config = cfg;

  time (&__session.ls_timestamp);

  debug ("<== do_open");

  return NSS_SUCCESS;
}

#if defined HAVE_LDAP_START_TLS_S || (defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS))
static int
do_ssl_options (ldap_config_t * cfg)
{
  int rc;

  debug ("==> do_ssl_options");

  if (cfg->ldc_tls_cacertfile != NULL)
    {
      /* ca cert file */
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE,
			    cfg->ldc_tls_cacertfile);
      if (rc != LDAP_SUCCESS)
	{
	  debug
	    ("<== do_ssl_options: Setting of LDAP_OPT_X_TLS_CACERTFILE failed");
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  if (cfg->ldc_tls_cacertdir != NULL)
    {
      /* ca cert directory */
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTDIR,
			    cfg->ldc_tls_cacertdir);
      if (rc != LDAP_SUCCESS)
	{
	  debug
	    ("<== do_ssl_options: Setting of LDAP_OPT_X_TLS_CACERTDIR failed");
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  /* require cert? */
  rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,
			&cfg->ldc_tls_checkpeer);
  if (rc != LDAP_SUCCESS)
    {
      debug
	("<== do_ssl_options: Setting of LDAP_OPT_X_TLS_REQUIRE_CERT failed");
      return LDAP_OPERATIONS_ERROR;
    }

  if (cfg->ldc_tls_ciphers != NULL)
    {
      /* set cipher suite, certificate and private key: */
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_CIPHER_SUITE,
			    cfg->ldc_tls_ciphers);
      if (rc != LDAP_SUCCESS)
	{
	  debug
	    ("<== do_ssl_options: Setting of LDAP_OPT_X_TLS_CIPHER_SUITE failed");
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  if (cfg->ldc_tls_cert != NULL)
    {
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_CERTFILE, cfg->ldc_tls_cert);
      if (rc != LDAP_SUCCESS)
	{
	  debug
	    ("<== do_ssl_options: Setting of LDAP_OPT_X_TLS_CERTFILE failed");
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  if (cfg->ldc_tls_key != NULL)
    {
      rc = ldap_set_option (NULL, LDAP_OPT_X_TLS_KEYFILE, cfg->ldc_tls_key);
      if (rc != LDAP_SUCCESS)
	{
	  debug
	    ("<== do_ssl_options: Setting of LDAP_OPT_X_TLS_KEYFILE failed");
	  return LDAP_OPERATIONS_ERROR;
	}
    }

  debug ("<== do_ssl_options");

  return LDAP_SUCCESS;
}
#endif

static int
do_bind (LDAP * ld, int timelimit, const char *dn, const char *pw,
	 int with_sasl)
{
  int rc;
  int msgid;
  struct timeval tv;
  LDAPMessage *result;

  debug ("==> do_bind");

  /*
   * set timelimit in ld for select() call in ldap_pvt_connect() 
   * function implemented in libldap2's os-ip.c
   */
  tv.tv_sec = timelimit;
  tv.tv_usec = 0;

#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
  if (!with_sasl)
    {
#endif
      msgid = ldap_simple_bind (ld, dn, pw);

      if (msgid < 0)
	{
#if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
	  if (ldap_get_option (ld, LDAP_OPT_ERROR_NUMBER, &rc) !=
	      LDAP_SUCCESS)
	    {
	      rc = LDAP_UNAVAILABLE;
	    }
#else
	  rc = ld->ld_errno;
#endif /* LDAP_OPT_ERROR_NUMBER */
	  debug ("<== do_bind");

	  return rc;
	}

      rc = ldap_result (ld, msgid, 0, &tv, &result);
      if (rc > 0)
	{
	  debug ("<== do_bind");
	  return ldap_result2error (ld, result, 1);
	}

      /* took too long */
      if (rc == 0)
	{
	  ldap_abandon (ld, msgid);
	}
#if defined(HAVE_LDAP_SASL_INTERACTIVE_BIND_S) && defined(HAVE_SASL_H)
    }
  else
    {
      void *defaults;

      /* FIXME: a little configurability here, perhaps? */
      defaults =
	_nss_ldap_sasl_defaults (ld, "GSSAPI", NULL, NULL, NULL, (char *) pw);

      rc = ldap_sasl_interactive_bind_s (ld, dn, "GSSAPI", NULL, NULL,
					 LDAP_SASL_QUIET,
					 _nss_ldap_sasl_interact, defaults);
      ber_memfree (defaults);

      return rc;
    }
#endif

  debug ("<== do_bind");

  return -1;
}

/*
 * This function initializes an enumeration context.
 * It is called from setXXent() directly, and so can safely lock the
 * mutex. 
 *
 * It could be done from the default constructor, under Solaris, but we
 * delay it until the setXXent() function is called.
 */
ent_context_t *
_nss_ldap_ent_context_init (ent_context_t ** pctx)
{
  ent_context_t *ctx;

  debug ("==> _nss_ldap_ent_context_init");

  _nss_ldap_enter ();

  ctx = *pctx;

  if (ctx == NULL)
    {
      ctx = (ent_context_t *) malloc (sizeof (*ctx));
      if (ctx == NULL)
	{
	  _nss_ldap_leave ();
	  debug ("<== _nss_ldap_ent_context_init");
	  return NULL;
	}
      *pctx = ctx;
    }
  else
    {
      if (ctx->ec_res != NULL)
	{
	  ldap_msgfree (ctx->ec_res);
	}
      if (ctx->ec_msgid > -1 && _nss_ldap_result (ctx) == NSS_SUCCESS)
	{
	  ldap_abandon (__session.ls_conn, ctx->ec_msgid);
	}
    }

  ctx->ec_res = NULL;
  ctx->ec_msgid = -1;

  LS_INIT (ctx->ec_state);

  _nss_ldap_leave ();

  debug ("<== _nss_ldap_ent_context_init");
  return ctx;
}

/*
 * Clears a given context; as of nss_ldap-121
 * we require the caller to acquire the lock.
 */
void
_nss_ldap_ent_context_release (ent_context_t * ctx)
{
  debug ("==> _nss_ldap_ent_context_release");

  if (ctx == NULL)
    {
      debug ("<== _nss_ldap_ent_context_release");
      return;
    }

  if (ctx->ec_res != NULL)
    {
      ldap_msgfree (ctx->ec_res);
      ctx->ec_res = NULL;
    }

  /*
   * Abandon the search if there were more results to fetch.
   */
  if (ctx->ec_msgid > -1 && _nss_ldap_result (ctx) == NSS_SUCCESS)
    {
      ldap_abandon (__session.ls_conn, ctx->ec_msgid);
      ctx->ec_msgid = -1;
    }

  LS_INIT (ctx->ec_state);

  debug ("<== _nss_ldap_ent_context_release");

  return;
}

/*
 * Do the necessary formatting to create a string filter.
 */
static NSS_STATUS
do_filter (const ldap_args_t * args, const char *filterprot,
	   ldap_service_search_descriptor_t * sd, char *userbuf,
	   size_t userbufSiz, const char **retFilter)
{
  char buf1[LDAP_FILT_MAXSIZ], buf2[LDAP_FILT_MAXSIZ];
  char *filterBufP, filterBuf[LDAP_FILT_MAXSIZ];
  size_t filterSiz;
  NSS_STATUS stat;

  debug ("==> do_filter");

  if (args != NULL)
    {
      /* choose what to use for temporary storage */

      if (sd != NULL && sd->lsd_filter != NULL)
	{
	  filterBufP = filterBuf;
	  filterSiz = sizeof (filterBuf);
	}
      else
	{
	  filterBufP = userbuf;
	  filterSiz = userbufSiz;
	}

      switch (args->la_type)
	{
	case LA_TYPE_STRING:
	  if ((stat =
	       _nss_ldap_escape_string (args->la_arg1.la_string, buf1,
					sizeof (buf1))) != NSS_SUCCESS)
	    return stat;
	  snprintf (filterBufP, filterSiz, filterprot, buf1);
	  break;
	case LA_TYPE_NUMBER:
	  snprintf (filterBufP, filterSiz, filterprot,
		    args->la_arg1.la_number);
	  break;
	case LA_TYPE_STRING_AND_STRING:
	  if ((stat =
	       _nss_ldap_escape_string (args->la_arg1.la_string, buf1,
					sizeof (buf1))) != NSS_SUCCESS
	      || (stat =
		  _nss_ldap_escape_string (args->la_arg2.la_string, buf2,
					   sizeof (buf2)) != NSS_SUCCESS))
	    return stat;
	  snprintf (filterBufP, filterSiz, filterprot, buf1, buf2);
	  break;
	case LA_TYPE_NUMBER_AND_STRING:
	  if ((stat =
	       _nss_ldap_escape_string (args->la_arg2.la_string, buf1,
					sizeof (buf1))) != NSS_SUCCESS)
	    return stat;
	  snprintf (filterBufP, filterSiz, filterprot,
		    args->la_arg1.la_number, buf1);
	  break;
	}

      /*
       * This code really needs to be cleaned up.
       */
      if (sd != NULL && sd->lsd_filter != NULL)
	{
	  size_t filterBufPLen = strlen (filterBufP);

	  /* remove trailing bracket */
	  /* ( */
	  if (filterBufP[filterBufPLen - 1] == ')')
	    filterBufP[filterBufPLen - 1] = '\0';

	  /* ( */
	  snprintf (userbuf, userbufSiz, "%s(%s))",
		    filterBufP, sd->lsd_filter);
	}

      *retFilter = userbuf;
    }
  else
    {
      /* no arguments, probably an enumeration filter */
      if (sd != NULL && sd->lsd_filter != NULL)
	{
	  snprintf (userbuf, userbufSiz, "(&%s(%s))",
		    filterprot, sd->lsd_filter);
	  *retFilter = userbuf;
	}
      else
	{
	  *retFilter = filterprot;
	}
    }

  debug (":== do_filter: %s", *retFilter);

  debug ("<== do_filter");

  return NSS_SUCCESS;
}

/*
 * Wrapper around ldap_result() to skip over search references
 * and deal transparently with the last entry.
 */
static NSS_STATUS
do_result (ent_context_t * ctx, int all)
{
  int rc = LDAP_UNAVAILABLE;
  NSS_STATUS stat = NSS_TRYAGAIN;
  struct timeval tv, *tvp;

  debug ("==> do_result");

  if (__session.ls_config->ldc_timelimit == LDAP_NO_LIMIT)
    {
      tvp = NULL;
    }
  else
    {
      tv.tv_sec = __session.ls_config->ldc_timelimit;
      tv.tv_usec = 0;
      tvp = &tv;
    }

  do
    {
      rc =
	ldap_result (__session.ls_conn, ctx->ec_msgid, all, tvp,
		     &ctx->ec_res);
      switch (rc)
	{
	case -1:
	case 0:
#if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
	  if (ldap_get_option
	      (__session.ls_conn, LDAP_OPT_ERROR_NUMBER, &rc) != LDAP_SUCCESS)
	    {
	      rc = LDAP_UNAVAILABLE;
	    }
#else
	  rc = __session.ls_conn->ld_errno;
#endif /* LDAP_OPT_ERROR_NUMBER */
	  syslog (LOG_ERR, "nss_ldap: could not get LDAP result - %s",
		     ldap_err2string (rc));
	  stat = NSS_UNAVAIL;
	  break;
	case LDAP_RES_SEARCH_ENTRY:
	  stat = NSS_SUCCESS;
	  break;
	case LDAP_RES_SEARCH_RESULT:
	  if (all == LDAP_MSG_ALL)
	    {
	      /* we asked for the result chain, we got it. */
	      stat = NSS_SUCCESS;
	    }
	  else
	    {
#ifdef LDAP_MORE_RESULTS_TO_RETURN
	      int parserc;
	      /* NB: this frees ctx->ec_res */
	      parserc =
		ldap_parse_result (__session.ls_conn, ctx->ec_res, &rc, NULL,
				   NULL, NULL, NULL, 1);
	      if (parserc != LDAP_SUCCESS
		  && parserc != LDAP_MORE_RESULTS_TO_RETURN)
		{
		  stat = NSS_UNAVAIL;
		  ldap_abandon (__session.ls_conn, ctx->ec_msgid);
		  syslog (LOG_ERR,
			     "nss_ldap: could not get LDAP result - %s",
			     ldap_err2string (rc));
		}
	      else
		{
		  stat = NSS_NOTFOUND;
		}
#else
	      stat = NSS_NOTFOUND;
#endif /* LDAP_MORE_RESULTS_TO_RETURN */
	      ctx->ec_res = NULL;
	      ctx->ec_msgid = -1;
	    }
	  break;
	default:
	  stat = NSS_UNAVAIL;
	  break;
	}
    }
#ifdef LDAP_RES_SEARCH_REFERENCE
  while (rc == LDAP_RES_SEARCH_REFERENCE);
#else
  while (0);
#endif /* LDAP_RES_SEARCH_REFERENCE */

  if (stat == NSS_SUCCESS)
    time (&__session.ls_timestamp);

  debug ("<== do_result");

  return stat;
}

/*
 * Function to call either do_search() or do_search_s() with
 * reconnection logic.
 */
static NSS_STATUS
do_with_reconnect (const char *base, int scope,
		   const char *filter, const char **attrs, int sizelimit,
		   void *private, search_func_t search_func)
{
  int rc = LDAP_UNAVAILABLE, tries = 0, backoff = 0;
  NSS_STATUS stat = NSS_TRYAGAIN;

  debug ("==> do_with_reconnect");

  while (stat == NSS_TRYAGAIN &&
	 tries < LDAP_NSS_MAXCONNTRIES + LDAP_NSS_TRIES)
    {
      if (tries > LDAP_NSS_MAXCONNTRIES)
	{
	  if (backoff == 0)
	    backoff = LDAP_NSS_SLEEPTIME;
	  else if (backoff < LDAP_NSS_MAXSLEEPTIME)
	    backoff *= 2;

	  syslog (LOG_INFO,
		     "nss_ldap: reconnecting to LDAP server (sleeping %d seconds)...",
		     backoff);
	  (void) sleep (backoff);
	}
      else if (tries > 0)
	{
	  /* Don't sleep, reconnect immediately. */
	  syslog (LOG_INFO, "nss_ldap: reconnecting to LDAP server...");
	}

      if (do_open () != NSS_SUCCESS)
	{
	  __session.ls_conn = NULL;
	  ++tries;
	  continue;
	}

      rc = search_func (base, scope, filter, attrs, sizelimit, private);

      switch (rc)
	{
	case LDAP_SUCCESS:
	case LDAP_SIZELIMIT_EXCEEDED:
	case LDAP_TIMELIMIT_EXCEEDED:
	  stat = NSS_SUCCESS;
	  break;
	case LDAP_NO_SUCH_ATTRIBUTE:
	case LDAP_UNDEFINED_TYPE:
	case LDAP_INAPPROPRIATE_MATCHING:
	case LDAP_CONSTRAINT_VIOLATION:
	case LDAP_TYPE_OR_VALUE_EXISTS:
	case LDAP_INVALID_SYNTAX:
	case LDAP_NO_SUCH_OBJECT:
	case LDAP_ALIAS_PROBLEM:
	case LDAP_INVALID_DN_SYNTAX:
	case LDAP_IS_LEAF:
	case LDAP_ALIAS_DEREF_PROBLEM:
	  stat = NSS_NOTFOUND;
	  break;
	case LDAP_SERVER_DOWN:
	case LDAP_TIMEOUT:
	case LDAP_UNAVAILABLE:
	case LDAP_BUSY:
	case LDAP_LOCAL_ERROR:
#ifdef LDAP_CONNECT_ERROR
	case LDAP_CONNECT_ERROR:
#endif /* LDAP_CONNECT_ERROR */
	  do_close ();
	  stat = NSS_TRYAGAIN;
	  ++tries;
	  continue;
	  break;
	default:
	  stat = NSS_UNAVAIL;
	  break;
	}
    }

  switch (stat)
    {
    case NSS_UNAVAIL:
      syslog (LOG_ERR, "nss_ldap: could not search LDAP server - %s",
		 ldap_err2string (rc));
      break;
    case NSS_TRYAGAIN:
      syslog (LOG_ERR,
		 "nss_ldap: could not reconnect to LDAP server - %s",
		 ldap_err2string (rc));
      stat = NSS_UNAVAIL;
      break;
    case NSS_SUCCESS:
      if (tries)
	{
	  syslog (LOG_INFO,
		     "nss_ldap: reconnected to LDAP server after %d attempt(s)",
		     tries);
	}
      time (&__session.ls_timestamp);
      break;
    default:
      break;
    }

  debug ("<== do_with_reconnect");
  return stat;
}

/*
 * Synchronous search function. Don't call this directly;
 * always wrap calls to this with do_with_reconnect(), or,
 * better still, use _nss_ldap_search_s().
 */
static int
do_search_s (const char *base, int scope,
	     const char *filter, const char **attrs, int sizelimit,
	     LDAPMessage ** res)
{
  int rc;
  struct timeval tv, *tvp;

  debug ("==> do_search_s");

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_SIZELIMIT)
  ldap_set_option (__session.ls_conn, LDAP_OPT_SIZELIMIT,
		   (void *) &sizelimit);
#else
  __session.ls_conn->ld_sizelimit = sizelimit;
#endif /* LDAP_OPT_SIZELIMIT */

  if (__session.ls_config->ldc_timelimit == LDAP_NO_LIMIT)
    {
      tvp = NULL;
    }
  else
    {
      tv.tv_sec = __session.ls_config->ldc_timelimit;
      tv.tv_usec = 0;
      tvp = &tv;
    }

  rc = ldap_search_st (__session.ls_conn, base, scope, filter,
		       (char **) attrs, 0, tvp, res);

  debug ("<== do_search_s");

  return rc;
}

/*
 * Asynchronous search function. Don't call this directly;
 * always wrap calls to this with do_with_reconnect(), or,
 * better still, use _nss_ldap_search().
 */
static int
do_search (const char *base, int scope,
	   const char *filter, const char **attrs, int sizelimit, int *msgid)
{
  int rc;

  debug ("==> do_search");

#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_SIZELIMIT)
  ldap_set_option (__session.ls_conn, LDAP_OPT_SIZELIMIT,
		   (void *) &sizelimit);
#else
  __session.ls_conn->ld_sizelimit = sizelimit;
#endif /* LDAP_OPT_SIZELIMIT */

  *msgid = ldap_search (__session.ls_conn, base, scope, filter,
			(char **) attrs, 0);

  if (*msgid < 0)
    {
#if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
      if (ldap_get_option
	  (__session.ls_conn, LDAP_OPT_ERROR_NUMBER, &rc) != LDAP_SUCCESS)
	{
	  rc = LDAP_UNAVAILABLE;
	}
#else
      rc = __session.ls_conn->ld_errno;
#endif /* LDAP_OPT_ERROR_NUMBER */
    }
  else
    {
      rc = LDAP_SUCCESS;
    }

  debug ("<== do_search");

  return rc;
}

/*
 * Tries parser function "parser" on entries, calling do_result()
 * to retrieve them from the LDAP server until one parses
 * correctly or there is an exceptional condition.
 */
static NSS_STATUS
do_parse (ent_context_t * ctx, void *result, char *buffer, size_t buflen,
	  int *errnop, parser_t parser)
{
  NSS_STATUS parseStat = NSS_NOTFOUND;

  debug ("==> do_parse");

  /*
   * if ec_state.ls_info.ls_index is non-zero, then we don't collect another
   * entry off the LDAP chain, and instead refeed the existing result to
   * the parser. Once the parser has finished with it, it will return
   * NSS_NOTFOUND and reset the index to -1, at which point we'll retrieve
   * another entry.
   */
  do
    {
      NSS_STATUS resultStat = NSS_SUCCESS;

      if (ctx->ec_state.ls_retry == 0 &&
	  (ctx->ec_state.ls_type == LS_TYPE_KEY
	   || ctx->ec_state.ls_info.ls_index == -1))
	{
	  resultStat = do_result (ctx, LDAP_MSG_ONE);
	}

      if (resultStat != NSS_SUCCESS)
	{
	  /* Could not get a result; bail */
	  parseStat = resultStat;
	  break;
	}

      /* 
       * We have an entry; now, try to parse it.
       *
       * If we do not parse the entry because of a schema
       * violation, the parser should return NSS_NOTFOUND.
       * We'll keep on trying subsequent entries until we 
       * find one which is parseable, or exhaust avialable
       * entries, whichever is first.
       */
      parseStat =
	parser (__session.ls_conn, ctx->ec_res, &ctx->ec_state, result,
		buffer, buflen);

      /* hold onto the state if we're out of memory XXX */
      ctx->ec_state.ls_retry = (parseStat == NSS_TRYAGAIN ? 1 : 0);

      /* free entry is we're moving on */
      if (ctx->ec_state.ls_retry == 0 &&
	  (ctx->ec_state.ls_type == LS_TYPE_KEY
	   || ctx->ec_state.ls_info.ls_index == -1))
	{
	  /* we don't need the result anymore, ditch it. */
	  ldap_msgfree (ctx->ec_res);
	  ctx->ec_res = NULL;
	}
    }
  while (parseStat == NSS_NOTFOUND);

  *errnop = 0;
  if (parseStat == NSS_TRYAGAIN)
    {
#ifdef HAVE_NSSWITCH_H
      errno = ERANGE;
      *errnop = 1;		/* this is really erange */
#else
      *errnop = ERANGE;
#endif /* HAVE_NSSWITCH_H */
    }

  debug ("<== do_parse");

  return parseStat;
}

/*
 * Parse, fetching reuslts from chain instead of server.
 */
static NSS_STATUS
do_parse_s (ent_context_t * ctx, void *result, char *buffer, size_t buflen,
	    int *errnop, parser_t parser)
{
  NSS_STATUS parseStat = NSS_NOTFOUND;
  LDAPMessage *e = NULL;

  debug ("==> do_parse_s");

  /*
   * if ec_state.ls_info.ls_index is non-zero, then we don't collect another
   * entry off the LDAP chain, and instead refeed the existing result to
   * the parser. Once the parser has finished with it, it will return
   * NSS_NOTFOUND and reset the index to -1, at which point we'll retrieve
   * another entry.
   */
  do
    {
      if (ctx->ec_state.ls_retry == 0 &&
	  (ctx->ec_state.ls_type == LS_TYPE_KEY
	   || ctx->ec_state.ls_info.ls_index == -1))
	{
	  if (e == NULL)
	    e = ldap_first_entry (__session.ls_conn, ctx->ec_res);
	  else
	    e = ldap_next_entry (__session.ls_conn, e);
	}

      if (e == NULL)
	{
	  /* Could not get a result; bail */
	  parseStat = NSS_NOTFOUND;
	  break;
	}

      /* 
       * We have an entry; now, try to parse it.
       *
       * If we do not parse the entry because of a schema
       * violation, the parser should return NSS_NOTFOUND.
       * We'll keep on trying subsequent entries until we 
       * find one which is parseable, or exhaust avialable
       * entries, whichever is first.
       */
      parseStat =
	parser (__session.ls_conn, e, &ctx->ec_state, result, buffer, buflen);

      /* hold onto the state if we're out of memory XXX */
      ctx->ec_state.ls_retry = (parseStat == NSS_TRYAGAIN ? 1 : 0);
    }
  while (parseStat == NSS_NOTFOUND);

  *errnop = 0;
  if (parseStat == NSS_TRYAGAIN)
    {
#ifdef HAVE_NSSWITCH_H
      errno = ERANGE;
      *errnop = 1;		/* this is really erange */
#else
      *errnop = ERANGE;
#endif /* HAVE_NSSWITCH_H */
    }

  debug ("<== do_parse_s");

  return parseStat;
}

/*
 * Read an entry from the directory, a la X.500. This is used
 * for functions that need to retrieve attributes from a DN,
 * such as the RFC2307bis group expansion function.
 */
NSS_STATUS
_nss_ldap_read (const char *dn, const char **attributes, LDAPMessage ** res)
{
  return do_with_reconnect (dn, LDAP_SCOPE_BASE, "(objectclass=*)", attributes, 1,	/* sizelimit */
			    res, (search_func_t) do_search_s);
}

/*
 * Simple wrapper around ldap_get_values(). Requires that
 * session is already established.
 */
char **
_nss_ldap_get_values (LDAPMessage * e, const char *attr)
{
  if (__session.ls_conn == NULL)
    {
      return NULL;
    }
  return ldap_get_values (__session.ls_conn, e, (char *) attr);
}

/*
 * Simple wrapper around ldap_get_dn(). Requires that
 * session is already established.
 */
char *
_nss_ldap_get_dn (LDAPMessage * e)
{
  if (__session.ls_conn == NULL)
    {
      return NULL;
    }
  return ldap_get_dn (__session.ls_conn, e);
}

/*
 * Simple wrapper around ldap_first_entry(). Requires that
 * session is already established.
 */
LDAPMessage *
_nss_ldap_first_entry (LDAPMessage * res)
{
  if (__session.ls_conn == NULL)
    {
      return NULL;
    }
  return ldap_first_entry (__session.ls_conn, res);
}

/*
 * Simple wrapper around ldap_next_entry(). Requires that
 * session is already established.
 */
LDAPMessage *
_nss_ldap_next_entry (LDAPMessage * res)
{
  if (__session.ls_conn == NULL)
    {
      return NULL;
    }
  return ldap_next_entry (__session.ls_conn, res);
}

/*
 * Calls ldap_result() with LDAP_MSG_ONE.
 */
NSS_STATUS
_nss_ldap_result (ent_context_t * ctx)
{
  return do_result (ctx, LDAP_MSG_ONE);
}

/*
 * The generic synchronous lookup cover function. 
 * Assumes caller holds lock.
 */
NSS_STATUS
_nss_ldap_search_s (const ldap_args_t * args,
		    const char *filterprot,
		    ldap_map_selector_t sel,
		    int sizelimit, LDAPMessage ** res)
{
  char sdBase[LDAP_FILT_MAXSIZ], *base = NULL;
  char filterBuf[LDAP_FILT_MAXSIZ];
  const char **attrs, *filter;
  int scope;
  NSS_STATUS stat;
  ldap_service_search_descriptor_t *sd = NULL;

  debug ("==> _nss_ldap_search_s");

  stat = do_open ();
  if (stat != NSS_SUCCESS)
    {
      __session.ls_conn = NULL;
      debug ("<== _nss_ldap_search_s");
      return stat;
    }

  /* Set some reasonable defaults. */
  base = __session.ls_config->ldc_base;
  scope = __session.ls_config->ldc_scope;
  attrs = NULL;

  if (sel < LM_NONE)
    {
      sd = __session.ls_config->ldc_sds[sel];
      if (sd != NULL)
	{
	  size_t len = strlen (sd->lsd_base);
	  if (sd->lsd_base[len - 1] == ',')
	    {
	      /* is relative */
	      snprintf (sdBase, sizeof (sdBase), "%s%s", sd->lsd_base,
			__session.ls_config->ldc_base);
	      base = sdBase;
	    }
	  else
	    {
	      base = sd->lsd_base;
	    }

	  if (sd->lsd_scope != -1)
	    {
	      scope = sd->lsd_scope;
	    }
	}
      attrs = __session.ls_config->ldc_attrtab[sel];
    }

  stat =
    do_filter (args, filterprot, sd, filterBuf, sizeof (filterBuf), &filter);
  if (stat != NSS_SUCCESS)
    return stat;

  stat = do_with_reconnect (base, scope, filter,
			    attrs, sizelimit, res,
			    (search_func_t) do_search_s);

  debug ("<== _nss_ldap_search_s");

  return stat;
}

/*
 * The generic lookup cover function (asynchronous).
 * Assumes caller holds lock.
 */
NSS_STATUS
_nss_ldap_search (const ldap_args_t * args,
		  const char *filterprot,
		  ldap_map_selector_t sel, int sizelimit, int *msgid)
{
  char sdBase[LDAP_FILT_MAXSIZ], *base = NULL;
  char filterBuf[LDAP_FILT_MAXSIZ];
  const char **attrs, *filter;
  int scope;
  NSS_STATUS stat;
  ldap_service_search_descriptor_t *sd = NULL;

  debug ("==> _nss_ldap_search");

  stat = do_open ();
  if (stat != NSS_SUCCESS)
    {
      __session.ls_conn = NULL;
      debug ("<== _nss_ldap_search");
      return stat;
    }

  /* Set some reasonable defaults. */
  base = __session.ls_config->ldc_base;
  scope = __session.ls_config->ldc_scope;
  attrs = NULL;

  if (sel < LM_NONE)
    {
      sd = __session.ls_config->ldc_sds[sel];

      if (sd != NULL)
	{
	  size_t len = strlen (sd->lsd_base);
	  if (sd->lsd_base[len - 1] == ',')
	    {
	      /* is relative */
	      snprintf (sdBase, sizeof (sdBase), "%s%s", sd->lsd_base,
			__session.ls_config->ldc_base);
	      base = sdBase;
	    }
	  else
	    {
	      base = sd->lsd_base;
	    }

	  if (sd->lsd_scope != -1)
	    {
	      scope = sd->lsd_scope;
	    }
	}
      attrs = __session.ls_config->ldc_attrtab[sel];
    }

  stat =
    do_filter (args, filterprot, sd, filterBuf, sizeof (filterBuf), &filter);
  if (stat != NSS_SUCCESS)
    return stat;

  stat = do_with_reconnect (base, scope, filter,
			    attrs, sizelimit, msgid,
			    (search_func_t) do_search);

  debug ("<== _nss_ldap_search");

  return stat;
}

/*
 * General entry point for enumeration routines.
 * This should really use the asynchronous LDAP search API to avoid
 * pulling down all the entries at once, particularly if the
 * enumeration is not completed.
 * Locks mutex.
 */
NSS_STATUS
_nss_ldap_getent (ent_context_t ** ctx,
		  void *result,
		  char *buffer,
		  size_t buflen,
		  int *errnop,
		  const char *filterprot,
		  ldap_map_selector_t sel, parser_t parser)
{
  NSS_STATUS stat = NSS_SUCCESS;

  debug ("==> _nss_ldap_getent");

  if (*ctx == NULL || (*ctx)->ec_msgid == -1)
    {
      /*
       * implicitly call setent() if this is the first time
       * or there is no active search
       */
      if (_nss_ldap_ent_context_init (ctx) == NULL)
	{
	  debug ("<== _nss_ldap_getent");
	  return NSS_UNAVAIL;
	}
    }

  /*
   * we need to lock here as the context may not be thread-specific
   * data (under glibc, for example). Maybe we should make the lock part
   * of the context.
   */

  _nss_ldap_enter ();

  /*
   * If ctx->ec_msgid < 0, then we haven't searched yet. Let's do it!
   */
  if ((*ctx)->ec_msgid < 0)
    {
      int msgid;

      stat = _nss_ldap_search (NULL, filterprot, sel, LDAP_NO_LIMIT, &msgid);
      if (stat != NSS_SUCCESS)
	{
	  _nss_ldap_leave ();
	  debug ("<== _nss_ldap_getent");
	  return stat;
	}

      (*ctx)->ec_msgid = msgid;
    }


  _nss_ldap_leave ();

  stat = do_parse (*ctx, result, buffer, buflen, errnop, parser);

  debug ("<== _nss_ldap_getent");

  return stat;
}

/*
 * General match function.
 * Locks mutex.
 */
NSS_STATUS
_nss_ldap_getbyname (ldap_args_t * args,
		     void *result,
		     char *buffer,
		     size_t buflen,
		     int *errnop,
		     const char *filterprot,
		     ldap_map_selector_t sel, parser_t parser)
{
  NSS_STATUS stat = NSS_NOTFOUND;
  ent_context_t ctx;

  _nss_ldap_enter ();

  debug ("==> _nss_ldap_getbyname");

  ctx.ec_msgid = -1;

  stat = _nss_ldap_search_s (args, filterprot, sel, 1, &ctx.ec_res);
  if (stat != NSS_SUCCESS)
    {
      _nss_ldap_leave ();
      debug ("<== _nss_ldap_getbyname");
      return stat;
    }

  /*
   * we pass this along for the benefit of the services parser,
   * which uses it to figure out which protocol we really wanted.
   * we only pass the second argument along, as that's what we need
   * in services.
   */
  LS_INIT (ctx.ec_state);
  ctx.ec_state.ls_type = LS_TYPE_KEY;
  ctx.ec_state.ls_info.ls_key = args->la_arg2.la_string;

  stat = do_parse_s (&ctx, result, buffer, buflen, errnop, parser);

  _nss_ldap_ent_context_release (&ctx);

  /* moved unlock here to avoid race condition bug #49 */
  _nss_ldap_leave ();

  debug ("<== _nss_ldap_getbyname");

  return stat;
}

/*
 * These functions are called from within the parser, where it is assumed
 * to be safe to use the connection and the respective message.
 */

/*
 * Assign all values, bar omitvalue (if not NULL), to *valptr.
 */
NSS_STATUS
_nss_ldap_assign_attrvals (LDAP * ld,
			   LDAPMessage * e,
			   const char *attr,
			   const char *omitvalue,
			   char ***valptr,
			   char **pbuffer,
			   size_t * pbuflen, size_t * pvalcount)
{
  char **vals;
  char **valiter;
  int valcount;
  char **p = NULL;

  register int buflen = *pbuflen;
  register char *buffer = *pbuffer;

  if (pvalcount != NULL)
    {
      *pvalcount = 0;
    }

  vals = ldap_get_values (ld, e, (char *) attr);

  valcount = (vals == NULL) ? 0 : ldap_count_values (vals);
  if (bytesleft (buffer, buflen, char *) < (valcount + 1) * sizeof (char *))
    {
      ldap_value_free (vals);
      return NSS_TRYAGAIN;
    }

  align (buffer, buflen, char *);
  p = *valptr = (char **) buffer;

  buffer += (valcount + 1) * sizeof (char *);
  buflen -= (valcount + 1) * sizeof (char *);

  if (valcount == 0)
    {
      *p = NULL;
      *pbuffer = buffer;
      *pbuflen = buflen;
      return NSS_SUCCESS;
    }

  valiter = vals;

  while (*valiter != NULL)
    {
      int vallen;
      char *elt = NULL;

      if (omitvalue != NULL && strcmp (*valiter, omitvalue) == 0)
	{
	  valcount--;
	}
      else
	{
	  vallen = strlen (*valiter);
	  if (buflen < (size_t) (vallen + 1))
	    {
	      ldap_value_free (vals);
	      return NSS_TRYAGAIN;
	    }

	  /* copy this value into the next block of buffer space */
	  elt = buffer;
	  buffer += vallen + 1;
	  buflen -= vallen + 1;

	  strncpy (elt, *valiter, vallen);
	  elt[vallen] = '\0';
	  *p = elt;
	  p++;
	}
      valiter++;
    }

  *p = NULL;
  *pbuffer = buffer;
  *pbuflen = buflen;

  if (pvalcount != NULL)
    {
      *pvalcount = valcount;
    }

  ldap_value_free (vals);
  return NSS_SUCCESS;
}

/* Assign a single value to *valptr. */
NSS_STATUS
_nss_ldap_assign_attrval (LDAP * ld,
			  LDAPMessage * e,
			  const char *attr,
			  char **valptr, char **buffer, size_t * buflen)
{
  char **vals;
  int vallen;

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

  vallen = strlen (*vals);
  if (*buflen < (size_t) (vallen + 1))
    {
      ldap_value_free (vals);
      return NSS_TRYAGAIN;
    }

  *valptr = *buffer;

  strncpy (*valptr, *vals, vallen);
  (*valptr)[vallen] = '\0';

  *buffer += vallen + 1;
  *buflen -= vallen + 1;

  ldap_value_free (vals);

  return NSS_SUCCESS;
}

/*
 * Assign a single value to *valptr, after examining userPassword for
 * a syntactically suitable value. 
 */
NSS_STATUS
_nss_ldap_assign_userpassword (LDAP * ld,
			       LDAPMessage * e,
			       const char *attr,
			       char **valptr, char **buffer, size_t * buflen)
{
  char **vals;
  char **valiter;
  char *pwd = NULL;
  int vallen;
#ifndef AT_OC_MAP
  static char *__crypt_token = "{CRYPT}";
  static size_t __crypt_token_length = sizeof ("{CRYPT}") - 1;
#endif /* AT_OC_MAP */
  const char *token = NULL;
  size_t token_length = 0;

  debug ("==> _nss_ldap_assign_userpassword");
#ifdef AT_OC_MAP
  if (__config != NULL)
    {
      switch (__config->ldc_password_type)
	{
	case LU_RFC2307_USERPASSWORD:
	  token = "{CRYPT}";
	  token_length = sizeof ("{CRYPT}") - 1;
	  break;
	case LU_RFC3112_AUTHPASSWORD:
	  token = "CRYPT$";
	  token_length = sizeof ("CRYPT$") - 1;
	  break;
	case LU_OTHER_PASSWORD:
	  break;
	}
    }
#else
  token = __crypt_token;
  token_length = __crypt_token_length;
#endif /* AT_OC_MAP */

  vals = ldap_get_values (ld, e, (char *) attr);
  if (vals != NULL)
    {
      for (valiter = vals; *valiter != NULL; valiter++)
	{
#ifdef AT_OC_MAP
	  if (token_length == 0 ||
	      strncasecmp (*valiter, token, token_length) == 0)
#else
	  if (strncasecmp (*valiter, token, token_length) == 0)
#endif /* AT_OC_MAP */
	    {
	      pwd = *valiter;
	      break;
	    }
	}
    }

  if (pwd == NULL)
    {
      pwd = "x";
    }
  else
    {
      pwd += token_length;
    }

  vallen = strlen (pwd);

  if (*buflen < (size_t) (vallen + 1))
    {
      if (vals != NULL)
	{
	  ldap_value_free (vals);
	}
      debug ("<== _nss_ldap_assign_userpassword");
      return NSS_TRYAGAIN;
    }

  *valptr = *buffer;

  strncpy (*valptr, pwd, vallen);
  (*valptr)[vallen] = '\0';

  *buffer += vallen + 1;
  *buflen -= vallen + 1;

  if (vals != NULL)
    {
      ldap_value_free (vals);
    }

  debug ("<== _nss_ldap_assign_userpassword");
  return NSS_SUCCESS;
}

NSS_STATUS
_nss_ldap_oc_check (LDAP * ld, LDAPMessage * e, const char *oc)
{
  char **vals, **valiter;
  NSS_STATUS ret = NSS_NOTFOUND;

  vals = ldap_get_values (ld, e, "objectClass");
  if (vals != NULL)
    {
      for (valiter = vals; *valiter != NULL; valiter++)
	{
	  if (strcasecmp (*valiter, oc) == 0)
	    {
	      ret = NSS_SUCCESS;
	      break;
	    }
	}
    }

  if (vals != NULL)
    {
      ldap_value_free (vals);
    }

  return ret;
}

#ifdef AT_OC_MAP
const char *
_nss_ldap_map_at (const char *attribute)
{
  char *mapped;

  if (_nss_ldap_atmap_get (__config, attribute, (const char **) &mapped) ==
      NSS_NOTFOUND)
    return attribute;

  return mapped;
}

const char *
_nss_ldap_map_oc (const char *objectclass)
{
  char *mapped;

  if (_nss_ldap_ocmap_get (__config, objectclass, (const char **) &mapped) ==
      NSS_NOTFOUND)
    return objectclass;

  return mapped;
}

NSS_STATUS
_nss_ldap_atmap_put (ldap_config_t * config,
		     const char *rfc2307attribute, const char *attribute)
{
  DBT key, val;
  int rc;
  char *attrdup;

  if (config->ldc_at_map == NULL)
    {
      config->ldc_at_map = dbopen (NULL, O_RDWR, 0600, DB_HASH, NULL);
      if (config->ldc_at_map == NULL)
	{
	  return NSS_TRYAGAIN;
	}
    }

  attrdup = strdup (attribute);
  if (attrdup == NULL)
    return NSS_TRYAGAIN;

  if (strcmp (rfc2307attribute, "userPassword") == 0)
    {
      if (strcasecmp (attribute, "userPassword") == 0)
	config->ldc_password_type = LU_RFC2307_USERPASSWORD;
      else if (strcasecmp (attribute, "authPassword") == 0)
	config->ldc_password_type = LU_RFC3112_AUTHPASSWORD;
      else
	config->ldc_password_type = LU_OTHER_PASSWORD;
    }

  key.data = (void *) rfc2307attribute;
  key.size = strlen (rfc2307attribute);

  val.data = (void *) &attrdup;
  val.size = sizeof (attrdup);

  rc =
    (((DB *) (config->ldc_at_map))->put) ((DB *) config->ldc_at_map, &key,
					  &val, 0);

  return (rc != 0) ? NSS_TRYAGAIN : NSS_SUCCESS;
}

NSS_STATUS
_nss_ldap_ocmap_put (ldap_config_t * config,
		     const char *rfc2307objectclass, const char *objectclass)
{
  DBT key, val;
  int rc;
  char *ocdup;

  if (config->ldc_oc_map == NULL)
    {
      config->ldc_oc_map = dbopen (NULL, O_RDWR, 0600, DB_HASH, NULL);
      if (config->ldc_oc_map == NULL)
	{
	  return NSS_TRYAGAIN;
	}
    }

  ocdup = strdup (objectclass);
  if (ocdup == NULL)
    return NSS_TRYAGAIN;

  key.data = (void *) rfc2307objectclass;
  key.size = strlen (rfc2307objectclass);
  val.data = (void *) &ocdup;
  val.size = sizeof (ocdup);
  rc =
    (((DB *) (config->ldc_oc_map))->put) ((DB *) config->ldc_oc_map, &key,
					  &val, 0);

  return (rc != 0) ? NSS_TRYAGAIN : NSS_SUCCESS;
}

NSS_STATUS
_nss_ldap_atmap_get (ldap_config_t * config,
		     const char *rfc2307attribute, const char **attribute)
{
  DBT key, val;

  if (config == NULL || config->ldc_at_map == NULL)
    {
      *attribute = rfc2307attribute;
      return NSS_NOTFOUND;
    }

  key.data = (void *) rfc2307attribute;
  key.size = strlen (rfc2307attribute);

  if ((((DB *) config->ldc_at_map)->get)
      ((DB *) config->ldc_at_map, &key, &val, 0) != 0)
    {
      *attribute = rfc2307attribute;
      return NSS_NOTFOUND;
    }

  *attribute = *((char **) val.data);
  return NSS_SUCCESS;
}

NSS_STATUS
_nss_ldap_ocmap_get (ldap_config_t * config,
		     const char *rfc2307objectclass, const char **objectclass)
{
  DBT key, val;

  if (config == NULL || config->ldc_oc_map == NULL)
    {
      *objectclass = rfc2307objectclass;
      return NSS_NOTFOUND;
    }

  key.data = (void *) rfc2307objectclass;
  key.size = strlen (rfc2307objectclass);

  if ((((DB *) config->ldc_oc_map)->get)
      ((DB *) config->ldc_oc_map, &key, &val, 0) != 0)
    {
      *objectclass = rfc2307objectclass;
      return NSS_NOTFOUND;
    }

  *objectclass = *((char **) val.data);

  return NSS_SUCCESS;
}
#endif /* AT_OC_MAP */

#ifdef PROXY_AUTH
/*
 * Proxy bind support for AIX. Very simple, but should do 
 * the job.
 */

#if LDAP_SET_REBIND_PROC_ARGS < 3
static ldap_proxy_bind_args_t __proxy_args = { NULL, NULL };
#endif

#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
#if LDAP_SET_REBIND_PROC_ARGS == 3
static int
do_proxy_rebind (LDAP * ld, LDAP_CONST char *url, ber_tag_t request,
		 ber_int_t msgid, void *arg)
#else
static int
do_proxy_rebind (LDAP * ld, LDAP_CONST char *url, int request,
		 ber_int_t msgid)
#endif
{
  int timelimit;
#if LDAP_SET_REBIND_PROC_ARGS == 3
  ldap_proxy_bind_args_t *who = (ldap_proxy_bind_args_t *) arg;
#else
  ldap_proxy_bind_args_t *who = &__proxy_args;
#endif

  timelimit = __session.ls_config->ldc_bind_timelimit;

  return do_bind (ld, timelimit, who->binddn, who->bindpw, 0);
}
#else
#if LDAP_SET_REBIND_PROC_ARGS == 3
static int
do_proxy_rebind (LDAP * ld, char **whop, char **credp, int *methodp,
		 int freeit, void *arg)
#elif LDAP_SET_REBIND_PROC_ARGS == 2
static int
do_proxy_rebind (LDAP * ld, char **whop, char **credp, int *methodp,
		 int freeit)
#endif
{
#if LDAP_SET_REBIND_PROC_ARGS == 3
  ldap_proxy_bind_args_t *who = (ldap_proxy_bind_args_t *) arg;
#else
  ldap_proxy_bind_args_t *who = &__proxy_args;
#endif
  if (freeit)
    {
      if (*whop != NULL)
	free (*whop);
      if (*credp != NULL)
	free (*credp);
    }

  *whop = who->binddn ? strdup (who->binddn) : NULL;
  *credp = who->bindpw ? strdup (who->bindpw) : NULL;

  *methodp = LDAP_AUTH_SIMPLE;

  return LDAP_SUCCESS;
}
#endif

NSS_STATUS
_nss_ldap_proxy_bind (const char *user, const char *password)
{
  ldap_args_t args;
  LDAPMessage *res, *e;
  NSS_STATUS stat;
  int rc;
#if LDAP_SET_REBIND_PROC_ARGS == 3
  ldap_proxy_bind_args_t proxy_args_buf;
  ldap_proxy_bind_args_t *proxy_args = &proxy_args_buf;
#else
  ldap_proxy_bind_args_t *proxy_args = &__proxy_args;
#endif

  LA_INIT (args);
  LA_TYPE (args) = LA_TYPE_STRING;
  LA_STRING (args) = user;

  /*
   * Binding with an empty password will always work, so don't let
   * the user in if they try that.
   */
  if (password == NULL || password[0] == '\0')
    {
      /* XXX overload */
      return NSS_TRYAGAIN;
    }

  _nss_ldap_enter ();

  stat = _nss_ldap_search_s (&args, _nss_ldap_filt_getpwnam,
			     LM_PASSWD, 1, &res);
  if (stat == NSS_SUCCESS)
    {
      e = _nss_ldap_first_entry (res);
      if (e != NULL)
	{
	  proxy_args->binddn = _nss_ldap_get_dn (e);
	  proxy_args->bindpw = password;

	  if (proxy_args->binddn != NULL)
	    {
	      /* Use our special rebind procedure. */
#if LDAP_SET_REBIND_PROC_ARGS == 3
	      ldap_set_rebind_proc (__session.ls_conn, do_proxy_rebind, NULL);
#elif LDAP_SET_REBIND_PROC_ARGS == 2
	      ldap_set_rebind_proc (__session.ls_conn, do_proxy_rebind);
#endif
	      rc = do_bind (__session.ls_conn,
			    __session.ls_config->ldc_bind_timelimit,
			    proxy_args->binddn, proxy_args->bindpw, 0);
	      switch (rc)
		{
		case LDAP_INVALID_CREDENTIALS:
		  /* XXX overload */
		  stat = NSS_TRYAGAIN;
		  break;
		case LDAP_NO_SUCH_OBJECT:
		  stat = NSS_NOTFOUND;
		  break;
		case LDAP_SUCCESS:
		  stat = NSS_SUCCESS;
		  break;
		default:
		  stat = NSS_UNAVAIL;
		  break;
		}
	      /*
	       * Close the connection, don't want to continue
	       * being bound as this user or using this rebind proc.
	       */
	      do_close ();
	      ldap_memfree (proxy_args->binddn);
	    }
	  else
	    {
	      stat = NSS_NOTFOUND;
	    }
	  proxy_args->binddn = NULL;
	  proxy_args->bindpw = NULL;
	}
      else
	{
	  stat = NSS_NOTFOUND;
	}
      ldap_msgfree (res);
    }

  _nss_ldap_leave ();

  return stat;
}

#endif /* PROXY_AUTH */