File: lookup_ldap.c

package info (click to toggle)
autofs 5.1.8-2%2Bdeb12u2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,864 kB
  • sloc: ansic: 35,535; yacc: 1,819; lex: 1,124; sh: 627; makefile: 541
file content (3839 lines) | stat: -rw-r--r-- 92,261 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
/*
 * lookup_ldap.c - Module for Linux automountd to access automount
 *		   maps in LDAP directories.
 *
 *   Copyright 2001-2003 Ian Kent <raven@themaw.net>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, Inc., 675 Mass Ave, Cambridge MA 02139,
 *   USA; either version 2 of the License, or (at your option) any later
 *   version.
 *
 *   This program 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 General Public License for more details.
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include <lber.h>
#include <libxml/tree.h>
#include <stdlib.h>

#define MODULE_LOOKUP
#include "automount.h"
#include "nsswitch.h"
#include "lookup_ldap.h"
#include "base64.h"

#define MAPFMT_DEFAULT "sun"

#define MODPREFIX "lookup(ldap): "

int lookup_version = AUTOFS_LOOKUP_VERSION;	/* Required by protocol */

#define ENV_LDAPTLS_CERT	"LDAPTLS_CERT"
#define ENV_LDAPTLS_KEY		"LDAPTLS_KEY"

static struct ldap_schema common_schema[] = {
	{"nisMap", "nisMapName", "nisObject", "cn", "nisMapEntry"},
	{"automountMap", "ou", "automount", "cn", "automountInformation"},
	{"automountMap", "automountMapName", "automount", "automountKey", "automountInformation"},
};
static unsigned int common_schema_count = sizeof(common_schema)/sizeof(struct ldap_schema);

static struct ldap_schema amd_timestamp = {
	"madmap", "amdmapName", "amdmapTimestamp", NULL, "amdmapTimestamp"
};

static struct ldap_schema amd_schema = {
	"amdmap", "amdmapName", "amdmap", "amdmapKey", "amdmapValue"
};

/*
 * Initialization and de-initialization of LDAP and OpenSSL must be
 * always serialized to avoid corruption of context structures inside
 * these libraries.
 */
pthread_mutex_t ldapinit_mutex = PTHREAD_MUTEX_INITIALIZER;

struct ldap_search_params {
	struct autofs_point *ap;
	LDAP *ldap;
	char *base;
	char *query, **attrs;
	struct berval *cookie;
	ber_int_t pageSize;
	int morePages;
	ber_int_t totalCount;
	LDAPMessage *result;
	time_t age;
};

static int decode_percent_hack(const char *, char **);

#ifdef WITH_SASL
static int set_env(unsigned logopt, const char *name, const char *val)
{
	int ret = setenv(name, val, 1);
	if (ret == -1) {
		error(logopt, "failed to set config value for %s", name);
		return 0;
	}
	return 1;
}
#endif

#ifndef HAVE_LDAP_CREATE_PAGE_CONTROL
int ldap_create_page_control(LDAP *ldap, ber_int_t pagesize,
			     struct berval *cookie, char isCritical,
			     LDAPControl **output)
{
	BerElement *ber;
	int rc;

	if (!ldap || !output)
		return LDAP_PARAM_ERROR;

	ber = ber_alloc_t(LBER_USE_DER);
	if (!ber)
		return LDAP_NO_MEMORY;

	if (ber_printf(ber, "{io}", pagesize,
			(cookie && cookie->bv_val) ? cookie->bv_val : "",
			(cookie && cookie->bv_val) ? cookie->bv_len : 0)
				== LBER_ERROR) {
		ber_free(ber, 1);
		return LDAP_ENCODING_ERROR;
	}

	rc = ldap_create_control(LDAP_CONTROL_PAGEDRESULTS, ber, isCritical, output);

	return rc;
}
#endif /* HAVE_LDAP_CREATE_PAGE_CONTROL */

#ifndef HAVE_LDAP_PARSE_PAGE_CONTROL
int ldap_parse_page_control(LDAP *ldap, LDAPControl **controls,
			    ber_int_t *totalcount, struct berval **cookie)
{
	int i, rc;
	BerElement *theBer;
	LDAPControl *listCtrlp;

	for (i = 0; controls[i] != NULL; i++) {
		if (strcmp(controls[i]->ldctl_oid, LDAP_CONTROL_PAGEDRESULTS) == 0) {
			listCtrlp = controls[i];

			theBer = ber_init(&listCtrlp->ldctl_value);
			if (!theBer)
				return LDAP_NO_MEMORY;

			rc = ber_scanf(theBer, "{iO}", totalcount, cookie);
			if (rc == LBER_ERROR) {
				ber_free(theBer, 1);
				return LDAP_DECODING_ERROR;
			}

			ber_free(theBer, 1);
			return LDAP_SUCCESS;
		}
	}

	return LDAP_CONTROL_NOT_FOUND;
}
#endif /* HAVE_LDAP_PARSE_PAGE_CONTROL */

static void ldapinit_mutex_lock(void)
{
	int status = pthread_mutex_lock(&ldapinit_mutex);
	if (status)
		fatal(status);
	return;
}

static void ldapinit_mutex_unlock(void)
{
	int status = pthread_mutex_unlock(&ldapinit_mutex);
	if (status)
		fatal(status);
	return;
}

static void uris_mutex_lock(struct lookup_context *ctxt)
{
	int status = pthread_mutex_lock(&ctxt->uris_mutex);
	if (status)
		fatal(status);
	return;
}

static void uris_mutex_unlock(struct lookup_context *ctxt)
{
	int status = pthread_mutex_unlock(&ctxt->uris_mutex);
	if (status)
		fatal(status);
	return;
}

int bind_ldap_simple(unsigned logopt, LDAP *ldap, const char *uri, struct lookup_context *ctxt)
{
	int rv;

	if (ctxt->auth_required == LDAP_AUTH_USESIMPLE)
		rv = ldap_simple_bind_s(ldap, ctxt->user, ctxt->secret);
	else if (ctxt->version == 2)
		rv = ldap_simple_bind_s(ldap, ctxt->base, NULL);
	else
		rv = ldap_simple_bind_s(ldap, NULL, NULL);

	if (rv != LDAP_SUCCESS) {
		if (!ctxt->uris) {
			crit(logopt, MODPREFIX
			     "Unable to bind to the LDAP server: "
			     "%s, error %s", ctxt->server ? "" : "(default)",
			     ldap_err2string(rv));
		} else {
			info(logopt, MODPREFIX "Unable to bind to the LDAP server: "
			     "%s, error %s", uri, ldap_err2string(rv));
		}
		return -1;
	}

	return 0;
}

int __unbind_ldap_connection(unsigned logopt,
			     struct ldap_conn *conn,
			     struct lookup_context *ctxt)
{
	int rv = LDAP_SUCCESS;

	if (ctxt->use_tls == LDAP_TLS_RELEASE)
		ctxt->use_tls = LDAP_TLS_INIT;
#ifdef WITH_SASL
	if (ctxt->auth_required & LDAP_NEED_AUTH)
		autofs_sasl_unbind(conn, ctxt);
	/* No, sasl_dispose does not release the ldap connection
	 * unless it's using sasl EXTERNAL
	 */
#endif
	if (conn->ldap) {
		rv = ldap_unbind_ext(conn->ldap, NULL, NULL);
		conn->ldap = NULL;
	}
	if (rv != LDAP_SUCCESS)
		error(logopt, "unbind failed: %s", ldap_err2string(rv));

	return rv;
}

int unbind_ldap_connection(unsigned logopt,
			   struct ldap_conn *conn,
			   struct lookup_context *ctxt)
{
	int rv;

	ldapinit_mutex_lock();
	rv = __unbind_ldap_connection(logopt, conn, ctxt);
	ldapinit_mutex_unlock();

	return rv;
}

LDAP *init_ldap_connection(unsigned logopt, const char *uri, struct lookup_context *ctxt)
{
	LDAP *ldap = NULL;
	struct timeval timeout     = { ctxt->timeout, 0 };
	struct timeval net_timeout = { ctxt->network_timeout, 0 };
	int rv;

	ctxt->version = 3;

	/* Initialize the LDAP context. */
	rv = ldap_initialize(&ldap, uri);
	if (rv != LDAP_OPT_SUCCESS) {
		info(logopt, MODPREFIX
		     "couldn't initialize LDAP connection to %s",
		     uri ? uri : "default");
		return NULL;
	}

	/* Use LDAPv3 */
	rv = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ctxt->version);
	if (rv != LDAP_OPT_SUCCESS) {
		/* fall back to LDAPv2 */
		ldap_unbind_ext(ldap, NULL, NULL);
		rv = ldap_initialize(&ldap, uri);
		if (rv != LDAP_OPT_SUCCESS) {
			crit(logopt, MODPREFIX "couldn't initialize LDAP");
			return NULL;
		}
		ctxt->version = 2;
	}


	if (ctxt->timeout != -1) {
		/* Set synchronous call timeout */
		rv = ldap_set_option(ldap, LDAP_OPT_TIMEOUT, &timeout);
		if (rv != LDAP_OPT_SUCCESS)
			info(logopt, MODPREFIX
			     "failed to set synchronous call timeout to %d",
			     timeout.tv_sec);
	}

	/* Sane network timeout */
	rv = ldap_set_option(ldap, LDAP_OPT_NETWORK_TIMEOUT, &net_timeout);
	if (rv != LDAP_OPT_SUCCESS)
		info(logopt, MODPREFIX "failed to set connection timeout to %d",
		     net_timeout.tv_sec);

	if (ctxt->use_tls) {
		if (ctxt->version == 2) {
			if (ctxt->tls_required) {
				error(logopt, MODPREFIX
				    "TLS required but connection is version 2");
				ldap_unbind_ext(ldap, NULL, NULL);
				return NULL;
			}
			return ldap;
		}

		rv = ldap_start_tls_s(ldap, NULL, NULL);
		if (rv != LDAP_SUCCESS) {
			ldap_unbind_ext(ldap, NULL, NULL);
			if (ctxt->tls_required) {
				error(logopt, MODPREFIX
				      "TLS required but START_TLS failed: %s",
				      ldap_err2string(rv));
				return NULL;
			}
			ctxt->use_tls = LDAP_TLS_DONT_USE;
			ldap = init_ldap_connection(logopt, uri, ctxt);
			if (ldap)
				ctxt->use_tls = LDAP_TLS_INIT;
			return ldap;
		}
		ctxt->use_tls = LDAP_TLS_RELEASE;
	}

	return ldap;
}

static int get_query_dn(unsigned logopt, LDAP *ldap, struct lookup_context *ctxt, const char *class, const char *key)
{
	char buf[MAX_ERR_BUF];
	char *query, *dn, *qdn = NULL;
	LDAPMessage *result = NULL, *e;
	char *attrs[2];
	struct berval **value;
	int scope;
	int rv, l;

	attrs[0] = (char *) key;
	attrs[1] = NULL;

	if (!ctxt->mapname && !ctxt->base) {
		error(logopt, MODPREFIX "no master map to lookup");
		return 0;
	}

	/* Build a query string. */
	l = strlen("(objectclass=)") + strlen(class) + 1;
	if (ctxt->mapname)
		l += strlen(key) + strlen(ctxt->mapname) + strlen("(&(=))");

	query = malloc(l);
	if (query == NULL) {
		char *estr = strerror_r(errno, buf, sizeof(buf));
		crit(logopt, MODPREFIX "malloc: %s", estr);
		return NSS_STATUS_UNAVAIL;
	}

	/*
	 * If we have a master mapname construct a query using it
	 * otherwise assume the base dn will catch it.
	 */
	if (ctxt->mapname) {
		if (sprintf(query, "(&(objectclass=%s)(%s=%.*s))", class,
		     key, (int) strlen(ctxt->mapname), ctxt->mapname) >= l) {
			debug(logopt,
			      MODPREFIX "error forming query string");
			free(query);
			return 0;
		}
		scope = LDAP_SCOPE_SUBTREE;
	} else {
		if (sprintf(query, "(objectclass=%s)", class) >= l) {
			debug(logopt,
			      MODPREFIX "error forming query string");
			free(query);
			return 0;
		}
		scope = LDAP_SCOPE_SUBTREE;
	}

	dn = NULL;
	if (!ctxt->sdns) {
		rv = ldap_search_s(ldap, ctxt->base,
				   scope, query, attrs, 0, &result);
		if ((rv != LDAP_SUCCESS) || !result) {
			error(logopt,
			      MODPREFIX "query failed for %s: %s",
			      query, ldap_err2string(rv));
			if (result)
				ldap_msgfree(result);
			free(query);
			return 0;
		}

		e = ldap_first_entry(ldap, result);
		if (e && (value = ldap_get_values_len(ldap, e, key))) {
			ldap_value_free_len(value);
			dn = ldap_get_dn(ldap, e);
			debug(logopt, MODPREFIX "found query dn %s", dn);
		} else {
			debug(logopt,
			      MODPREFIX "query succeeded, no matches for %s",
			      query);
			ldap_msgfree(result);
			free(query);
			return 0;
		}
	} else {
		struct ldap_searchdn *this = ctxt->sdns;

		debug(logopt, MODPREFIX "check search base list");

		result = NULL;
		while (this) {
			rv = ldap_search_s(ldap, this->basedn,
					   scope, query, attrs, 0, &result);
			if ((rv == LDAP_SUCCESS) && result) {
				debug(logopt, MODPREFIX
				      "found search base under %s",
				      this->basedn);

				e = ldap_first_entry(ldap, result);
				if (e && (value = ldap_get_values_len(ldap, e, key))) {
					ldap_value_free_len(value);
					dn = ldap_get_dn(ldap, e);
					debug(logopt, MODPREFIX "found query dn %s", dn);
					break;
				} else {
					debug(logopt,
					      MODPREFIX "query succeeded, no matches for %s",
					      query);
					ldap_msgfree(result);
					result = NULL;
				}
			} else {
				error(logopt,
				      MODPREFIX "query failed for search dn %s: %s",
				      this->basedn, ldap_err2string(rv));
				if (result) {
					ldap_msgfree(result);
					result = NULL;
				}
			}

			this = this->next;
		}

		if (!result) {
			error(logopt,
			      MODPREFIX "failed to find query dn under search base dns");
			free(query);
			return 0;
		}
	}

	free(query);
	if (dn) {
		qdn = strdup(dn);
		ldap_memfree(dn);
	}
	ldap_msgfree(result);
	if (!qdn)
		return 0;

	uris_mutex_lock(ctxt);
	if (ctxt->qdn)
		free(ctxt->qdn);
	ctxt->qdn = qdn;
	uris_mutex_unlock(ctxt);

	return 1;
}

static struct ldap_schema *alloc_common_schema(struct ldap_schema *s)
{
	struct ldap_schema *schema;
	char *mc, *ma, *ec, *ea, *va;

	mc = strdup(s->map_class);
	if (!mc)
		return NULL;

	ma = strdup(s->map_attr);
	if (!ma) {
		free(mc);
		return NULL;
	}

	ec = strdup(s->entry_class);
	if (!ec) {
		free(mc);
		free(ma);
		return NULL;
	}

	ea = strdup(s->entry_attr);
	if (!ea) {
		free(mc);
		free(ma);
		free(ec);
		return NULL;
	}

	va = strdup(s->value_attr);
	if (!va) {
		free(mc);
		free(ma);
		free(ec);
		free(ea);
		return NULL;
	}

	schema = malloc(sizeof(struct ldap_schema));
	if (!schema) {
		free(mc);
		free(ma);
		free(ec);
		free(ea);
		free(va);
		return NULL;
	}

	schema->map_class = mc;
	schema->map_attr = ma;
	schema->entry_class = ec;
	schema->entry_attr = ea;
	schema->value_attr = va;

	return schema;
}

static int find_query_dn(unsigned logopt, LDAP *ldap, struct lookup_context *ctxt)
{
	struct ldap_schema *schema;
	unsigned int i;

	if (ctxt->schema)
		return 0;

	if (ctxt->format & MAP_FLAG_FORMAT_AMD) {
		schema = alloc_common_schema(&amd_schema);
		if (!schema) {
			error(logopt, MODPREFIX "failed to allocate schema");
			return 0;
		}
		ctxt->schema = schema;
		return 1;
	}

	for (i = 0; i < common_schema_count; i++) {
		const char *class = common_schema[i].map_class;
		const char *key = common_schema[i].map_attr;
		if (get_query_dn(logopt, ldap, ctxt, class, key)) {
			schema = alloc_common_schema(&common_schema[i]);
			if (!schema) {
				error(logopt, MODPREFIX "failed to allocate schema");
				return 0;
			}
			ctxt->schema = schema;
			return 1;
		}
	}

	return 0;
}

static int do_bind(unsigned logopt, struct ldap_conn *conn,
		   const char *uri, struct lookup_context *ctxt)
{
	char *host = NULL, *nhost;
	int rv;

#ifdef WITH_SASL
	debug(logopt, MODPREFIX "auth_required: %d, sasl_mech %s",
	      ctxt->auth_required, ctxt->sasl_mech);

	if (ctxt->auth_required & LDAP_NEED_AUTH) {
		rv = autofs_sasl_bind(logopt, conn, ctxt);
		debug(logopt, MODPREFIX "autofs_sasl_bind returned %d", rv);
	} else {
		rv = bind_ldap_simple(logopt, conn->ldap, uri, ctxt);
		debug(logopt, MODPREFIX "ldap simple bind returned %d", rv);
	}
#else
	rv = bind_ldap_simple(logopt, conn->ldap, uri, ctxt);
	debug(logopt, MODPREFIX "ldap simple bind returned %d", rv);
#endif

	if (rv != 0)
		return 0;

	rv = ldap_get_option(conn->ldap, LDAP_OPT_HOST_NAME, &host);
        if (rv != LDAP_SUCCESS || !host) {
		debug(logopt, "failed to get hostname for connection");
		return 0;
	}

	nhost = strdup(host);
	if (!nhost) {
		debug(logopt, "failed to alloc context for hostname");
		return 0;
	}
	ldap_memfree(host);

	uris_mutex_lock(ctxt);
	if (!ctxt->cur_host) {
		ctxt->cur_host = nhost;
		if (!(ctxt->format & MAP_FLAG_FORMAT_AMD)) {
			/* Check if schema defined in conf first time only */
			ctxt->schema = defaults_get_schema();
		}
	} else {
		/* If connection host has changed update */
		if (!strcmp(ctxt->cur_host, nhost))
			free(nhost);
		else {
			free(ctxt->cur_host);
			ctxt->cur_host = nhost;
		}
	}
	uris_mutex_unlock(ctxt);

	return 1;
}

static int do_connect(unsigned logopt, struct ldap_conn *conn,
		      const char *uri, struct lookup_context *ctxt)
{
	char *cur_host = NULL;
	int ret = NSS_STATUS_SUCCESS;

#ifdef WITH_SASL
	if (ctxt->extern_cert && ctxt->extern_key) {
		set_env(logopt, ENV_LDAPTLS_CERT, ctxt->extern_cert);
		set_env(logopt, ENV_LDAPTLS_KEY, ctxt->extern_key);
	}
#endif

	conn->ldap = init_ldap_connection(logopt, uri, ctxt);
	if (!conn->ldap) {
		ret = NSS_STATUS_UNAVAIL;
		goto out;
	}

	uris_mutex_lock(ctxt);
	if (ctxt->cur_host)
		cur_host = ctxt->cur_host;
	uris_mutex_unlock(ctxt);

	if (!do_bind(logopt, conn, uri, ctxt)) {
		__unbind_ldap_connection(logopt, conn, ctxt);
		ret = NSS_STATUS_UNAVAIL;
		goto out;
	}

	/* If the lookup schema and the query dn are set and the
	 * ldap host hasn't changed return.
	 */
	uris_mutex_lock(ctxt);
	if (ctxt->schema && ctxt->qdn && (cur_host == ctxt->cur_host)) {
		uris_mutex_unlock(ctxt);
		goto out;
	}
	uris_mutex_unlock(ctxt);

	/*
	 * If the schema isn't defined in the configuration then check for
	 * presence of a map dn with a the common schema. Then calculate the
	 * base dn for searches.
	 */
	if (!ctxt->schema) {
		if (!find_query_dn(logopt, conn->ldap, ctxt)) {
			__unbind_ldap_connection(logopt, conn, ctxt);
			ret = NSS_STATUS_NOTFOUND;
			warn(logopt,
			      MODPREFIX "failed to find valid query dn");
			goto out;
		}
	} else if (!(ctxt->format & MAP_FLAG_FORMAT_AMD)) {
		const char *class = ctxt->schema->map_class;
		const char *key = ctxt->schema->map_attr;
		if (!get_query_dn(logopt, conn->ldap, ctxt, class, key)) {
			__unbind_ldap_connection(logopt, conn, ctxt);
			ret = NSS_STATUS_NOTFOUND;
			error(logopt, MODPREFIX "failed to get query dn");
			goto out;
		}
	}

out:
	return ret;
}

static unsigned long get_amd_timestamp(struct lookup_context *ctxt)
{
	struct ldap_conn conn;
	LDAP *ldap;
	LDAPMessage *result = NULL, *e;
	char *query;
	int scope = LDAP_SCOPE_SUBTREE;
	char *map, *class, *value;
	char *attrs[2];
	struct berval **bvValues;
	unsigned long timestamp = 0;
	int rv, l, ql;

	memset(&conn, 0, sizeof(struct ldap_conn));
	rv = do_connect(LOGOPT_ANY, &conn, ctxt->server, ctxt);
	if (rv != NSS_STATUS_SUCCESS)
		return 0;
	ldap = conn.ldap;

	map = amd_timestamp.map_attr;
	class = amd_timestamp.entry_class;
	value = amd_timestamp.value_attr;

	attrs[0] = value;
	attrs[1] = NULL;

	/* Build a query string. */
	l = strlen(class) +
	    strlen(map) + strlen(ctxt->mapname) + 21;

	query = malloc(l);
	if (query == NULL) {
		char buf[MAX_ERR_BUF];
		char *estr = strerror_r(errno, buf, sizeof(buf));
		crit(LOGOPT_ANY, MODPREFIX "malloc: %s", estr);
		return 0;
	}

	/*
	 * Look for an entry in class under ctxt-base
	 * whose entry is equal to qKey.
	 */
	ql = sprintf(query, "(&(objectclass=%s)(%s=%s))",
		     class, map, ctxt->mapname);
	if (ql >= l) {
		error(LOGOPT_ANY,
		      MODPREFIX "error forming query string");
		free(query);
		return 0;
	}

	rv = ldap_search_s(ldap, ctxt->base, scope, query, attrs, 0, &result);
	if ((rv != LDAP_SUCCESS) || !result) {
		crit(LOGOPT_ANY, MODPREFIX "timestamp query failed %s", query);
		unbind_ldap_connection(LOGOPT_ANY, &conn, ctxt);
		if (result)
			ldap_msgfree(result);
		free(query);
		return 0;
	}

	e = ldap_first_entry(ldap, result);
	if (!e) {
		debug(LOGOPT_ANY,
		     MODPREFIX "got answer, but no entry for timestamp");
		ldap_msgfree(result);
		unbind_ldap_connection(LOGOPT_ANY, &conn, ctxt);
		free(query);
		return CHE_MISSING;
	}

	while (e) {
		char *v_val;
		char *endptr;

		bvValues = ldap_get_values_len(ldap, e, value);
		if (!bvValues || !*bvValues) {
			debug(LOGOPT_ANY,
			      MODPREFIX "no value found in timestamp");
			goto next;
		}

		/* There should be one value for a timestamp */
		v_val = bvValues[0]->bv_val;

		timestamp = strtol(v_val, &endptr, 0);
		if ((errno == ERANGE &&
		    (timestamp == LONG_MAX || timestamp == LONG_MIN)) ||
		    (errno != 0 && timestamp == 0)) {
			debug(LOGOPT_ANY,
			      MODPREFIX "invalid value in timestamp");
			free(query);
			return 0;
		}

		if (endptr == v_val) {
			debug(LOGOPT_ANY,
			      MODPREFIX "no digits found in timestamp");
			free(query);
			return 0;
		}

		if (*endptr != '\0') {
			warn(LOGOPT_ANY, MODPREFIX
			     "characters found after number: %s", endptr);
			warn(LOGOPT_ANY,
			     MODPREFIX "timestamp may be invalid");
		}

		ldap_value_free_len(bvValues);
		break;
next:
		ldap_value_free_len(bvValues);
		e = ldap_next_entry(ldap, e);
	}

	ldap_msgfree(result);
	unbind_ldap_connection(LOGOPT_ANY, &conn, ctxt);
	free(query);

	return timestamp;
}

static int connect_to_server(unsigned logopt, struct ldap_conn *conn,
			     const char *uri, struct lookup_context *ctxt)
{
	int ret;

	ret = do_connect(logopt, conn, uri, ctxt);
	if (ret != NSS_STATUS_SUCCESS) {
		warn(logopt,
		     MODPREFIX "couldn't connect to server %s",
		     uri ? uri : "default");
	}

	return ret;
}

static int find_dc_server(unsigned logopt, struct ldap_conn *conn,
			  const char *uri, struct lookup_context *ctxt)
{
	char *str, *tok, *ptr = NULL;
	int ret = NSS_STATUS_UNAVAIL;

	str = strdup(uri);
	if (!str)
		return ret;

	tok = strtok_r(str, " ", &ptr);
	while (tok) {
		const char *this = (const char *) tok;
		int rv;

		debug(logopt, "trying server uri %s", this);
		rv = connect_to_server(logopt, conn, this, ctxt);
		if (rv == NSS_STATUS_SUCCESS) {
			info(logopt, "connected to uri %s", this);
			free(str);
			return rv;
		}
		if (rv == NSS_STATUS_NOTFOUND)
			ret = NSS_STATUS_NOTFOUND;
		tok = strtok_r(NULL, " ", &ptr);
	}

	free(str);

	return ret;
}

static int find_server(unsigned logopt,
		       struct ldap_conn *conn, struct lookup_context *ctxt)
{
	struct ldap_uri *this = NULL;
	struct list_head *p, *first;
	struct dclist *dclist;
	char *uri = NULL;
	int ret = NSS_STATUS_UNAVAIL;

	uris_mutex_lock(ctxt);
	dclist = ctxt->dclist;
	if (!ctxt->uri)
		first = ctxt->uris;
	else
		first = &ctxt->uri->list;
	uris_mutex_unlock(ctxt);


	/* Try each uri, save point in server list upon success */
	p = first->next;
	while(p != first) {
		int rv;

		/* Skip list head */
		if (p == ctxt->uris) {
			p = p->next;
			continue;
		}
		this = list_entry(p, struct ldap_uri, list);
		if (!strstr(this->uri, ":///")) {
			uri = strdup(this->uri);
			debug(logopt, "trying server uri %s", uri);
			rv = connect_to_server(logopt, conn, uri, ctxt);
			if (rv == NSS_STATUS_SUCCESS) {
				ret = NSS_STATUS_SUCCESS;
				info(logopt, "connected to uri %s", uri);
				free(uri);
				break;
			}
			if (rv == NSS_STATUS_NOTFOUND)
				ret = NSS_STATUS_NOTFOUND;
		} else {
			if (dclist)
				uri = strdup(dclist->uri);
			else {
				struct dclist *tmp;
				tmp = get_dc_list(logopt, this->uri);
				if (!tmp) {
					p = p->next;
					continue;
				}
				dclist = tmp;
				uri = strdup(dclist->uri);
			}
			rv = find_dc_server(logopt, conn, uri, ctxt);
			if (rv == NSS_STATUS_SUCCESS) {
				ret = NSS_STATUS_SUCCESS;
				free(uri);
				break;
			}
			if (rv == NSS_STATUS_NOTFOUND)
				ret = NSS_STATUS_NOTFOUND;
		}
		free(uri);
		uri = NULL;
		if (dclist) {
			free_dclist(dclist);
			dclist = NULL;
		}
		p = p->next;
	}

	uris_mutex_lock(ctxt);
	if (conn->ldap)
		ctxt->uri = this;
	if (dclist) {
		if (!ctxt->dclist)
			ctxt->dclist = dclist;
		else {
			if (ctxt->dclist != dclist) {
				free_dclist(ctxt->dclist);
				ctxt->dclist = dclist;
			}
		}
	}
	uris_mutex_unlock(ctxt);

	return ret;
}

static int do_reconnect(unsigned logopt,
			struct ldap_conn *conn, struct lookup_context *ctxt)
{
	int ret = NSS_STATUS_UNAVAIL;
	int dcrv = NSS_STATUS_SUCCESS;
	int rv = NSS_STATUS_SUCCESS;

	ldapinit_mutex_lock();
	if (ctxt->server || !ctxt->uris) {
		ret = do_connect(logopt, conn, ctxt->server, ctxt);
#ifdef WITH_SASL
		/* Dispose of the sasl authentication connection and try again. */
		if (ctxt->auth_required & LDAP_NEED_AUTH &&
		    ret != NSS_STATUS_SUCCESS && ret != NSS_STATUS_NOTFOUND) {
			autofs_sasl_dispose(conn, ctxt);
			ret = connect_to_server(logopt, conn,
						ctxt->server, ctxt);
		}
#endif
		ldapinit_mutex_unlock();
		return ret;
	}

	if (ctxt->dclist) {
		dcrv = find_dc_server(logopt, conn, ctxt->dclist->uri, ctxt);
		if (dcrv == NSS_STATUS_SUCCESS) {
			ldapinit_mutex_unlock();
			return dcrv;
		}
	}

	uris_mutex_lock(ctxt);
	if (ctxt->dclist) {
		if (!conn->ldap || ctxt->dclist->expire < monotonic_time(NULL)) {
			free_dclist(ctxt->dclist);
			ctxt->dclist = NULL;
		}
		/* Make sure we don't skip the domain spec */
		ctxt->uri = NULL;
		uris_mutex_unlock(ctxt);
		goto find_server;
	}
	uris_mutex_unlock(ctxt);

	if (!ctxt->uri)
		goto find_server;

	rv = do_connect(logopt, conn, ctxt->uri->uri, ctxt);
#ifdef WITH_SASL
	/*
	 * Dispose of the sasl authentication connection and try the
	 * current server again before trying other servers in the list.
	 */
	if (ctxt->auth_required & LDAP_NEED_AUTH &&
	    rv != NSS_STATUS_SUCCESS && rv != NSS_STATUS_NOTFOUND) {
		autofs_sasl_dispose(conn, ctxt);
		rv = connect_to_server(logopt, conn, ctxt->uri->uri, ctxt);
	}
#endif
	if (rv == NSS_STATUS_SUCCESS) {
		ldapinit_mutex_unlock();
		return rv;
	}

	/* Failed to connect, try to find a new server */

find_server:
#ifdef WITH_SASL
	autofs_sasl_dispose(conn, ctxt);
#endif

	/* Current server failed, try the rest or dc connection */
	ret = find_server(logopt, conn, ctxt);
	if (ret != NSS_STATUS_SUCCESS) {
		if (ret == NSS_STATUS_NOTFOUND ||
		    dcrv == NSS_STATUS_NOTFOUND ||
		    rv == NSS_STATUS_NOTFOUND)
			ret = NSS_STATUS_NOTFOUND;
		error(logopt, MODPREFIX "failed to find available server");
	}
	ldapinit_mutex_unlock();

	return ret;
}

int get_property(unsigned logopt, xmlNodePtr node, const char *prop, char **value)
{
	xmlChar *ret;
	xmlChar *property = (xmlChar *) prop;

	if (!(ret = xmlGetProp(node, property))) {
		*value = NULL;
		return 0;
	}

	if (!(*value = strdup((char *) ret))) {
		logerr(MODPREFIX "strdup failed with %d", errno);
		xmlFree(ret);
		return -1;
	}

	xmlFree(ret);
	return 0;
}

/*
 *  For plain text, login and digest-md5 authentication types, we need
 *  user and password credentials.
 */
int authtype_requires_creds(const char *authtype)
{
#ifdef WITH_SASL
	if (!strncmp(authtype, "PLAIN", strlen("PLAIN")) ||
	    !strncmp(authtype, "DIGEST-MD5", strlen("DIGEST-MD5")) ||
	    !strncmp(authtype, "LOGIN", strlen("LOGIN")))
		return 1;
#endif
	return 0;
}

/*
 *  Returns:
 *    -1  --  The permission on the file are not correct or
 *            the xml document was mal-formed
 *     0  --  The file was non-existent
 *            the file was empty
 *            the file contained valid data, which was filled into 
 *            ctxt->sasl_mech, ctxt->user, and ctxt->secret
 *
 *  The idea is that a -1 return value should abort the program.  A 0
 *  return value requires more checking.  If ctxt->authtype is filled in,
 *  then no further action is necessary.  If it is not, the caller is free
 *  to then use another method to determine how to connect to the server.
 */
int parse_ldap_config(unsigned logopt, struct lookup_context *ctxt)
{
	int          ret = 0, fallback = 0;
	unsigned int auth_required = LDAP_AUTH_NOTREQUIRED;
	unsigned int tls_required = 0, use_tls = 0;
	struct stat  st;
	xmlDocPtr    doc = NULL;
	xmlNodePtr   root = NULL;
	char         *authrequired, *auth_conf, *authtype;
	char         *user = NULL, *secret = NULL;
	char         *extern_cert = NULL, *extern_key = NULL;
	char         *client_princ = NULL, *client_cc = NULL;
	char	     *usetls, *tlsrequired;

	authtype = user = secret = NULL;

	auth_conf = (char *) defaults_get_auth_conf_file();
	if (!auth_conf) {
		error(logopt,
		      MODPREFIX "failed to get auth config file name.");
		return 0;
	}

	/*
	 *  Here we check that the config file exists, and that we have
	 *  permission to read it.  The XML library does not specify why a
	 *  parse happens to fail, so we have to do all of this checking
	 *  beforehand.
	 */
	memset(&st, 0, sizeof(st));
	if (stat(auth_conf, &st) == -1 || st.st_size == 0) {
		/* Auth config doesn't exist so disable TLS and auth */
		if (errno == ENOENT) {
			ctxt->auth_conf = auth_conf;
			ctxt->use_tls = LDAP_TLS_DONT_USE;
			ctxt->tls_required = LDAP_TLS_DONT_USE;
			ctxt->auth_required = LDAP_AUTH_NOTREQUIRED;
			ctxt->sasl_mech = NULL;
			ctxt->user = NULL;
			ctxt->secret = NULL;
			ctxt->client_princ = NULL;
			return 0;
		}
		error(logopt,
		      MODPREFIX "stat(2) failed with error %s.",
		      strerror(errno));
		free(auth_conf);
		return 0;
	}

	if (!S_ISREG(st.st_mode) ||
	    st.st_uid != 0 || st.st_gid != 0 ||
	    (st.st_mode & 0x01ff) != 0600) {
		error(logopt, MODPREFIX
		      "Configuration file %s exists, but is not usable. "
		      "Please make sure that it is owned by root, group "
		      "is root, and the mode is 0600.",
		      auth_conf);
		free(auth_conf);
		return -1;
	}

	doc = xmlParseFile(auth_conf);
	if (!doc) {
		error(logopt, MODPREFIX
		     "xmlParseFile failed for %s.", auth_conf);
		goto out;
	}

	root = xmlDocGetRootElement(doc);
	if (!root) {
		debug(logopt, MODPREFIX
		      "empty xml document (%s).", auth_conf);
		fallback = 1;
		goto out;
	}

	if (xmlStrcmp(root->name, (const xmlChar *)"autofs_ldap_sasl_conf")) {
		error(logopt, MODPREFIX
		      "The root node of the XML document %s is not "
		      "autofs_ldap_sasl_conf.", auth_conf);
		goto out;
	}

	ret = get_property(logopt, root, "usetls", &usetls);
	if (ret != 0) {
		error(logopt,
		      MODPREFIX
		      "Failed read the usetls property from "
		      "the configuration file %s.", auth_conf);
		goto out;
	}

	if (!usetls || ctxt->port == LDAPS_PORT) {
		use_tls = LDAP_TLS_DONT_USE;
		if (usetls)
			free(usetls);
	} else {
		if (!strcasecmp(usetls, "yes"))
			use_tls = LDAP_TLS_INIT;
		else if (!strcasecmp(usetls, "no"))
			use_tls = LDAP_TLS_DONT_USE;
		else {
			error(logopt,
			      MODPREFIX
			      "The usetls property must have value "
			      "\"yes\" or \"no\".");
			free(usetls);
			ret = -1;
			goto out;
		}
		free(usetls);
	}

	ret = get_property(logopt, root, "tlsrequired", &tlsrequired);
	if (ret != 0) {
		error(logopt,
		      MODPREFIX
		      "Failed read the tlsrequired property from "
		      "the configuration file %s.", auth_conf);
		goto out;
	}

	if (!tlsrequired)
		tls_required = LDAP_TLS_DONT_USE;
	else {
		if (!strcasecmp(tlsrequired, "yes"))
			tls_required = LDAP_TLS_REQUIRED;
		else if (!strcasecmp(tlsrequired, "no"))
			tls_required = LDAP_TLS_DONT_USE;
		else {
			error(logopt,
			      MODPREFIX
			      "The tlsrequired property must have value "
			      "\"yes\" or \"no\".");
			free(tlsrequired);
			ret = -1;
			goto out;
		}
		free(tlsrequired);
	}

	ret = get_property(logopt, root, "authrequired", &authrequired);
	if (ret != 0) {
		error(logopt,
		      MODPREFIX
		      "Failed read the authrequired property from "
		      "the configuration file %s.", auth_conf);
		goto out;
	}

	if (!authrequired)
		auth_required = LDAP_AUTH_NOTREQUIRED;
	else {
		if (!strcasecmp(authrequired, "yes"))
			auth_required = LDAP_AUTH_REQUIRED;
		else if (!strcasecmp(authrequired, "no"))
			auth_required = LDAP_AUTH_NOTREQUIRED;
		else if (!strcasecmp(authrequired, "autodetect"))
			auth_required = LDAP_AUTH_AUTODETECT;
		else if (!strcasecmp(authrequired, "simple"))
			auth_required = LDAP_AUTH_USESIMPLE;
		else {
			error(logopt,
			      MODPREFIX
			      "The authrequired property must have value "
			      "\"yes\", \"no\", \"autodetect\", or \"simple\".");
			free(authrequired);
			ret = -1;
			goto out;
		}
		free(authrequired);
	}

	ret = get_property(logopt, root, "authtype", &authtype);
	if (ret != 0) {
		error(logopt,
		      MODPREFIX
		      "Failed read the authtype property from the "
		      "configuration file %s.", auth_conf);
		goto out;
	}

	if (auth_required == LDAP_AUTH_USESIMPLE ||
	   (authtype && authtype_requires_creds(authtype))) {
		char *s1 = NULL, *s2 = NULL;
		ret = get_property(logopt, root, "user",  &user);
		ret |= get_property(logopt, root, "secret", &s1);
		ret |= get_property(logopt, root, "encoded_secret", &s2);
		if (ret != 0 || (!user || (!s1 && !s2))) {
auth_fail:
			error(logopt,
			      MODPREFIX
			      "%s authentication type requires a username "
			      "and a secret.  Please fix your configuration "
			      "in %s.", authtype, auth_conf);
			free(authtype);
			if (user)
				free(user);
			if (s1)
				free(s1);
			if (s2)
				free(s2);

			ret = -1;
			goto out;
		}
		if (!s2)
			secret = s1;
		else {
			char dec_buf[120];
			int dec_len = base64_decode(s2, dec_buf, 119);
			if (dec_len <= 0)
				goto auth_fail;
			secret = strdup(dec_buf);
			if (!secret)
				goto auth_fail;
			if (s1)
				free(s1);
			if (s2)
				free(s2);
		}
	} else if (auth_required == LDAP_AUTH_REQUIRED &&
		  (authtype && !strncmp(authtype, "EXTERNAL", 8))) {
#ifdef WITH_SASL
		ret = get_property(logopt, root, "external_cert",  &extern_cert);
		ret |= get_property(logopt, root, "external_key",  &extern_key);
		/*
		 * For EXTERNAL auth to function we need a client certificate
		 * and certificate key. The ca certificate used to verify
		 * the server certificate must also be set correctly in the
		 * global configuration as the connection must be encrypted
		 * and the server and client certificates must have been
		 * verified for the EXTERNAL method to be offered by the
		 * server. If the cert and key have not been set in the autofs
		 * configuration they must be set in the ldap rc file.
		 */
		if (ret != 0 || !extern_cert || !extern_key) {
			if (extern_cert)
				free(extern_cert);
			if (extern_key)
				free(extern_key);
		}
#endif
	}

	/*
	 * We allow the admin to specify the principal to use for the
	 * client.  The default is "autofsclient/hostname@REALM".
	 */
	(void)get_property(logopt, root, "clientprinc", &client_princ);
	(void)get_property(logopt, root, "credentialcache", &client_cc);

	ctxt->auth_conf = auth_conf;
	auth_conf = NULL;
	ctxt->use_tls = use_tls;
	ctxt->tls_required = tls_required;
	ctxt->auth_required = auth_required;
	ctxt->sasl_mech = authtype;
	if (!authtype && (auth_required & LDAP_AUTH_REQUIRED))
		ctxt->auth_required |= LDAP_AUTH_AUTODETECT;
	ctxt->user = user;
	ctxt->secret = secret;
	ctxt->client_princ = client_princ;
	ctxt->client_cc = client_cc;
#ifdef WITH_SASL
	ctxt->extern_cert = extern_cert;
	ctxt->extern_key = extern_key;
#endif

	debug(logopt, MODPREFIX
	      "ldap authentication configured with the following options:");
	debug(logopt, MODPREFIX
	      "use_tls: %u, "
	      "tls_required: %u, "
	      "auth_required: %u, "
	      "sasl_mech: %s",
	      use_tls, tls_required, auth_required, authtype);
	if (authtype && !strncmp(authtype, "EXTERNAL", 8)) {
		debug(logopt, MODPREFIX "external cert: %s",
		      extern_cert ? extern_cert : "ldap default");
		debug(logopt, MODPREFIX "external key: %s ",
		      extern_key ? extern_key : "ldap default");
	} else {
		debug(logopt, MODPREFIX
		      "user: %s, "
		      "secret: %s, "
		      "client principal: %s "
		      "credential cache: %s",
		      user, secret ? "specified" : "unspecified",
		      client_princ, client_cc);
	}
out:
	xmlFreeDoc(doc);
	if (auth_conf)
		free(auth_conf);

	if (fallback)
		return 0;

	return ret;
}

/*
 *  Take an input string as specified in the master map, and break it
 *  down into a server name and basedn.
 */
static int parse_server_string(unsigned logopt, const char *url, struct lookup_context *ctxt)
{
	char buf[MAX_ERR_BUF], *tmp = NULL, proto[9];
	const char *ptr, *name;
	int l, al_len;

	memset(proto, 0, 9);
	ptr = url;

	debug(logopt, MODPREFIX
	      "Attempting to parse LDAP information from string \"%s\".", ptr);

	ctxt->port = LDAP_PORT;
	if (!strncmp(ptr, "ldap:", 5) || !strncmp(ptr, "ldaps:", 6)) {
		if (*(ptr + 4) == 's') {
			ctxt->port = LDAPS_PORT;
			memcpy(proto, ptr, 6);
			strcat(proto, "//");
			ptr += 6;
		} else {
			memcpy(proto, ptr, 5);
			strcat(proto, "//");
			ptr += 5;
		}
	}

	if (!strncmp(ptr, "//", 2)) {
		const char *s = ptr + 2;
		const char *q = NULL;

		/* Isolate the server(s). */
		if ((q = strchr(s, '/')) || (q = strchr(s, '\0'))) {
			l = q - s;
			if (*proto) {
				al_len = l + strlen(proto) + 2;
				tmp = malloc(al_len);
			} else {
				al_len = l + 1;
				tmp = malloc(al_len);
			}
			if (!tmp) {
				char *estr;
				estr = strerror_r(errno, buf, sizeof(buf));
				logerr(MODPREFIX "malloc: %s", estr);
				return 0;
			}
			ctxt->server = tmp;
			memset(ctxt->server, 0, al_len);
			if (*proto) {
				strcpy(ctxt->server, proto);
				memcpy(ctxt->server + strlen(proto), s, l);
				strcat(ctxt->server, "/");
			} else
				memcpy(ctxt->server, s, l);
			ptr = q + 1;
		} else {
			crit(logopt,
			     MODPREFIX "invalid LDAP map syntax %s", ptr);
			return 0;
/* TODO: why did I put this here, the parser shouldn't let this by
			l = strlen(ptr);
			tmp = malloc(l + 1);
			if (!tmp) {
				char *estr;
				estr = strerror_r(errno, buf, sizeof(buf));
				crit(logopt, MODPREFIX "malloc: %s", estr);
				return 0;
			}
			ctxt->server = tmp;
			memset(ctxt->server, 0, l + 1);
			memcpy(ctxt->server, s, l);
*/
		}
	} else if (strchr(ptr, ':') != NULL || *ptr == '[') {
		const char *q = NULL;

		/* Isolate the server. Include the port spec */
		if (*ptr != '[') {
			q = strchr(ptr, ':');
			if (!q) {
				crit(logopt, MODPREFIX
				     "LDAP server name not found in %s", ptr);
				return 0;
			}
		} else {
			q = ++ptr;
			while (*q == ':' || isxdigit(*q))
				q++;
			if (*q != ']') {
				crit(logopt, MODPREFIX
				     "invalid LDAP map syntax %s", ptr);
				return 0;
			}
			q++;
			if (*q == ':')
				q++;
		}

		if (isdigit(*q))
			while (isdigit(*q))
				q++;

		if (*q != ':') {
			crit(logopt,
			     MODPREFIX "invalid LDAP map syntax %s", ptr);
			return 0;
		}

		l = q - ptr;
		if (*proto) {
			al_len = l + strlen(proto) + 2;
			tmp = malloc(al_len);
		} else {
			al_len = l + 1;
			tmp = malloc(al_len);
		}
		/* Isolate the server's name. */
		if (!tmp) {
			char *estr;
			estr = strerror_r(errno, buf, sizeof(buf));
			logerr(MODPREFIX "malloc: %s", estr);
			return 0;
		}
		ctxt->server = tmp;
		memset(ctxt->server, 0, al_len);
		if (*proto) {
			strcpy(ctxt->server, proto);
			memcpy(ctxt->server + strlen(proto), ptr, l);
			strcat(ctxt->server, "/");
		} else
			memcpy(ctxt->server, ptr, l);
		ptr += l + 1;
	}

	if (!ptr || ctxt->format & MAP_FLAG_FORMAT_AMD)
		goto done;

	/*
	 * For nss support we can have a map name with no
	 * type or dn info. If present a base dn must have
	 * at least an "=" and a "," to be at all functional.
	 * If a dn is given it must be fully specified or
	 * the later LDAP calls will fail.
	 */
	l = strlen(ptr);
	if ((name = strchr(ptr, '='))) {
		char *base;

		/*
		 * An '=' with no ',' means a mapname has been given so just
		 * grab it alone to keep it independent of schema otherwize
		 * we expect a full dn.
		 */
		if (!strchr(ptr, ',')) {
			char *map = strdup(name + 1);
			if (map)
				ctxt->mapname = map;
			else {
				char *estr;
				estr = strerror_r(errno, buf, sizeof(buf));
				logerr(MODPREFIX "strdup: %s", estr);
				if (ctxt->server)
					free(ctxt->server);
				return 0;
			}
			
		} else {
			base = malloc(l + 1);
			if (!base) {
				char *estr;
				estr = strerror_r(errno, buf, sizeof(buf));
				logerr(MODPREFIX "malloc: %s", estr);
				if (ctxt->server)
					free(ctxt->server);
				return 0;
			}
			ctxt->base = base;
			memset(ctxt->base, 0, l + 1);
			memcpy(ctxt->base, ptr, l);
		}
	} else {
		char *map = malloc(l + 1);
		if (!map) {
			char *estr;
			estr = strerror_r(errno, buf, sizeof(buf));
			logerr(MODPREFIX "malloc: %s", estr);
			if (ctxt->server)
				free(ctxt->server);
			return 0;
		}
		ctxt->mapname = map;
		memset(ctxt->mapname, 0, l + 1);
		memcpy(map, ptr, l);
	}

	if (!ctxt->server && *proto) {
		if (!strncmp(proto, "ldaps", 5)) {
			info(logopt, MODPREFIX
			     "server must be given to force ldaps, connection "
			     "will use LDAP client configured protocol");
		}
	}
done:
	if (ctxt->mapname)
		debug(logopt, MODPREFIX "mapname %s", ctxt->mapname);
	else
		debug(logopt, MODPREFIX "server \"%s\", base dn \"%s\"",
			ctxt->server ? ctxt->server : "(default)",
			ctxt->base);

	return 1;
}

static void free_context(struct lookup_context *ctxt)
{
	int ret;

	if (ctxt->schema) {
		free(ctxt->schema->map_class);
		free(ctxt->schema->map_attr);
		free(ctxt->schema->entry_class);
		free(ctxt->schema->entry_attr);
		free(ctxt->schema->value_attr);
		free(ctxt->schema);
	}
	if (ctxt->auth_conf)
		free(ctxt->auth_conf);
	if (ctxt->sasl_mech)
		free(ctxt->sasl_mech);
	if (ctxt->user)
		free(ctxt->user);
	if (ctxt->secret)
		free(ctxt->secret);
	if (ctxt->client_princ)
		free(ctxt->client_princ);
	if (ctxt->client_cc)
		free(ctxt->client_cc);
	if (ctxt->mapname)
		free(ctxt->mapname);
	if (ctxt->qdn)
		free(ctxt->qdn);
	if (ctxt->server)
		free(ctxt->server);
	if (ctxt->cur_host)
		free(ctxt->cur_host);
	if (ctxt->base)
		free(ctxt->base);
	if (ctxt->uris)
		defaults_free_uris(ctxt->uris);
	ret = pthread_mutex_destroy(&ctxt->uris_mutex);
	if (ret)
		fatal(ret);
	if (ctxt->sdns)
		defaults_free_searchdns(ctxt->sdns);
	if (ctxt->dclist)
		free_dclist(ctxt->dclist);
#ifdef WITH_SASL
	if (ctxt->extern_cert)
		free(ctxt->extern_cert);
	if (ctxt->extern_key)
		free(ctxt->extern_key);
#endif
	free(ctxt);

	return;
}

static void validate_uris(struct list_head *list)
{
	struct list_head *next;

	next = list->next;
	while (next != list) {
		struct ldap_uri *this;

		this = list_entry(next, struct ldap_uri, list);
		next = next->next;

		/* At least we get some basic validation */
		if (!ldap_is_ldap_url(this->uri)) {
			list_del(&this->list);
			free(this->uri);
			free(this);
		}
	}

	return;			
}

static int do_init(const char *mapfmt,
		   int argc, const char *const *argv,
		   struct lookup_context *ctxt, unsigned int reinit)
{
	unsigned int is_amd_format;
	int ret;

	ret = pthread_mutex_init(&ctxt->uris_mutex, NULL);
	if (ret) {
		error(LOGOPT_ANY, MODPREFIX "failed to init uris mutex");
		return 1;
	}

	/* If a map type isn't explicitly given, parse it like sun entries. */
	if (mapfmt == NULL)
		mapfmt = MAPFMT_DEFAULT;

	is_amd_format = 0;
	if (!strcmp(mapfmt, "amd")) {
		is_amd_format = 1;
		ctxt->format = MAP_FLAG_FORMAT_AMD;
		ctxt->check_defaults = 1;
	}

	if (!defaults_read_config(0)) {
		free_context(ctxt);
		return 1;
	}

	ctxt->timeout = defaults_get_ldap_timeout();
	ctxt->network_timeout = defaults_get_ldap_network_timeout();

	if (!is_amd_format) {
		/*
		 * Parse out the server name and base dn, and fill them
		 * into the proper places in the lookup context structure.
		 */
		if (!parse_server_string(LOGOPT_NONE, argv[0], ctxt)) {
			error(LOGOPT_ANY, MODPREFIX "cannot parse server string");
			return 1;
		}

		if (!ctxt->base)
			ctxt->sdns = defaults_get_searchdns();

		if (!ctxt->server) {
			struct list_head *uris = defaults_get_uris();
			if (uris) {
				validate_uris(uris);
				if (!list_empty(uris))
					ctxt->uris = uris;
				else {
					error(LOGOPT_ANY, MODPREFIX
					    "no valid uris found in config list"
					    ", using default system config");
					free(uris);
				}
			}
		}
	} else {
		char *tmp = conf_amd_get_ldap_base();
		if (!tmp) {
			error(LOGOPT_ANY, MODPREFIX "failed to get base dn");
			return 1;
		}
		ctxt->base = tmp;

		tmp = conf_amd_get_ldap_hostports();
		if (!tmp) {
			error(LOGOPT_ANY,
			      MODPREFIX "failed to get ldap_hostports");
			return 1;
		}

		/*
		 * Parse out the server name and port, and save them in
		 * the proper places in the lookup context structure.
		 */
		if (!parse_server_string(LOGOPT_NONE, tmp, ctxt)) {
			error(LOGOPT_ANY, MODPREFIX "cannot parse server string");
			free(tmp);
			return 1;
		}
		free(tmp);

		if (!ctxt->server) {
			error(LOGOPT_ANY, MODPREFIX "ldap_hostports not valid");
			return 1;
		}

		tmp = strdup(argv[0]);
		if (!tmp) {
			error(LOGOPT_ANY, MODPREFIX "failed to set mapname");
			return 1;
		}
		ctxt->mapname = tmp;
	}

	/*
	 *  First, check to see if a preferred authentication method was
	 *  specified by the user.  parse_ldap_config will return error
	 *  if the permissions on the file were incorrect, or if the
	 *  specified authentication type is not valid.
	 */
	ret = parse_ldap_config(LOGOPT_NONE, ctxt);
	if (ret) {
		error(LOGOPT_ANY, MODPREFIX "failed to parse ldap config");
		return 1;
	}

#ifdef WITH_SASL
	/* Init the sasl callbacks */
	ldapinit_mutex_lock();
	if (!autofs_sasl_client_init(LOGOPT_NONE)) {
		error(LOGOPT_ANY, "failed to init sasl client");
		ldapinit_mutex_unlock();
		return 1;
	}
	ldapinit_mutex_unlock();
#endif

	if (is_amd_format)
		ctxt->timestamp = get_amd_timestamp(ctxt);

	if (reinit) {
		ret = reinit_parse(ctxt->parse,
				   mapfmt, MODPREFIX, argc - 1, argv + 1);
		if (ret)
			logmsg(MODPREFIX "failed to reinit parse context");
	} else {
		/* Open the parser, if we can. */
		ctxt->parse = open_parse(mapfmt, MODPREFIX, argc - 1, argv + 1);
		if (!ctxt->parse) {
			logerr(MODPREFIX "failed to open parse context");
			ret = 1;
		}
	}

	return ret;
}

/*
 * This initializes a context (persistent non-global data) for queries to
 * this module.  Return zero if we succeed.
 */
int lookup_init(const char *mapfmt,
		int argc, const char *const *argv, void **context)
{
	struct lookup_context *ctxt;
	char buf[MAX_ERR_BUF];
	int ret;

	*context = NULL;

	/* If we can't build a context, bail. */
	ctxt = malloc(sizeof(struct lookup_context));
	if (!ctxt) {
		char *estr = strerror_r(errno, buf, sizeof(buf));
		logerr(MODPREFIX "malloc: %s", estr);
		return 1;
	}
	memset(ctxt, 0, sizeof(struct lookup_context));

	ret = do_init(mapfmt, argc, argv, ctxt, 0);
	if (ret) {
		free_context(ctxt);
		return 1;
	}

	*context = ctxt;

	return 0;
}

int lookup_reinit(const char *mapfmt,
		  int argc, const char *const *argv, void **context)
{
	struct lookup_context *ctxt = (struct lookup_context *) *context;
	struct lookup_context *new;
	char buf[MAX_ERR_BUF];
	int ret;

	/* If we can't build a context, bail. */
	new = malloc(sizeof(struct lookup_context));
	if (!new) {
		char *estr = strerror_r(errno, buf, sizeof(buf));
		logerr(MODPREFIX "malloc: %s", estr);
		return 1;
	}
	memset(new, 0, sizeof(struct lookup_context));

	new->parse = ctxt->parse;
	ret = do_init(mapfmt, argc, argv, new, 1);
	if (ret) {
		free_context(new);
		return 1;
	}

	*context = new;

	free_context(ctxt);

	return 0;
}

int lookup_read_master(struct master *master, time_t age, void *context)
{
	struct lookup_context *ctxt = (struct lookup_context *) context;
	unsigned int timeout = master->default_timeout;
	unsigned int logging = master->default_logging;
	unsigned int logopt = master->logopt;
	struct ldap_conn conn;
	LDAP *ldap;
	int rv, l, count;
	char buf[MAX_ERR_BUF];
	char parse_buf[PARSE_MAX_BUF];
	char *query;
	LDAPMessage *result = NULL, *e;
	char *class, *info, *entry;
	char **keyValue = NULL;
	char **values = NULL;
	char *attrs[3];
	int scope = LDAP_SCOPE_SUBTREE;

	/* Initialize the LDAP context. */
	memset(&conn, 0, sizeof(struct ldap_conn));
	rv = do_reconnect(logopt, &conn, ctxt);
	if (rv)
		return rv;
	ldap = conn.ldap;

	class = ctxt->schema->entry_class;
	entry = ctxt->schema->entry_attr;
	info = ctxt->schema->value_attr;

	attrs[0] = entry;
	attrs[1] = info;
	attrs[2] = NULL;

	l = strlen("(objectclass=)") + strlen(class) + 1;

	query = malloc(l);
	if (query == NULL) {
		char *estr = strerror_r(errno, buf, sizeof(buf));
		logerr(MODPREFIX "malloc: %s", estr);
		return NSS_STATUS_UNAVAIL;
	}

	if (sprintf(query, "(objectclass=%s)", class) >= l) {
		error(logopt, MODPREFIX "error forming query string");
		free(query);
		return NSS_STATUS_UNAVAIL;
	}

	/* Look around. */
	debug(logopt,
	      MODPREFIX "searching for \"%s\" under \"%s\"", query, ctxt->qdn);

	rv = ldap_search_s(ldap, ctxt->qdn, scope, query, attrs, 0, &result);

	if ((rv != LDAP_SUCCESS) || !result) {
		error(logopt, MODPREFIX "query failed for %s: %s",
		      query, ldap_err2string(rv));
		unbind_ldap_connection(logging, &conn, ctxt);
		if (result)
			ldap_msgfree(result);
		free(query);
		return NSS_STATUS_NOTFOUND;
	}

	e = ldap_first_entry(ldap, result);
	if (!e) {
		debug(logopt,
		      MODPREFIX "query succeeded, no matches for %s",
		      query);
		ldap_msgfree(result);
		unbind_ldap_connection(logging, &conn, ctxt);
		free(query);
		return NSS_STATUS_NOTFOUND;
	} else
		debug(logopt, MODPREFIX "examining entries");

	while (e) {
		char *key = NULL;
		int dec_len, i;

		keyValue = ldap_get_values(ldap, e, entry);

		if (!keyValue || !*keyValue) {
			e = ldap_next_entry(ldap, e);
			continue;
		}

		/*
		 * By definition keys must be unique within
		 * each map entry
		 */
		count = ldap_count_values(keyValue);
		if (strcasecmp(class, "nisObject")) {
			if (count > 1) {
				error(logopt, MODPREFIX
				      "key %s has duplicates - ignoring",
				      *keyValue);
				goto next;
			}
			key = strdup(keyValue[0]);
			if (!key) {
				error(logopt, MODPREFIX
				      "failed to dup map key %s - ignoring",
				      *keyValue);
				goto next;
			}
		} else if (count == 1) {
			dec_len = decode_percent_hack(keyValue[0], &key);
			if (dec_len <= 0) {
				error(logopt, MODPREFIX
				      "invalid map key %s - ignoring",
				      *keyValue);
				goto next;
			}
		} else {
			dec_len = decode_percent_hack(keyValue[0], &key);
			if (dec_len <= 0) {
				error(logopt, MODPREFIX
				      "invalid map key %s - ignoring",
				      *keyValue);
				goto next;
			}

			for (i = 1; i < count; i++) {
				char *k;
				dec_len = decode_percent_hack(keyValue[i], &k);
				if (dec_len <= 0) {
					error(logopt, MODPREFIX
					      "invalid map key %s - ignoring",
					      *keyValue);
					goto next;
				}
				if (strcmp(key, k)) {
					error(logopt, MODPREFIX
					      "key entry mismatch %s - ignoring",
					      *keyValue);
					free(k);
					goto next;
				}
				free(k);
			}
		}

		/*
		 * Ignore keys beginning with '+' as plus map
		 * inclusion is only valid in file maps.
		 */
		if (*key == '+') {
			warn(logopt,
			     MODPREFIX
			     "ignoreing '+' map entry - not in file map");
			goto next;
		}

		values = ldap_get_values(ldap, e, info);
		if (!values || !*values) {
			debug(logopt,
			      MODPREFIX "no %s defined for %s", info, query);
			goto next;
		}

		/*
		 * We require that there be only one value per key.
		 */
		count = ldap_count_values(values);
		if (count > 1) {
			error(logopt,
			      MODPREFIX
			      "one value per key allowed in master map");
			ldap_value_free(values);
			goto next;
		}

		if (snprintf(parse_buf, sizeof(parse_buf), "%s %s",
			     key, *values) >= sizeof(parse_buf)) {
			error(logopt, MODPREFIX "map entry too long");
			ldap_value_free(values);
			goto next;
		}
		ldap_value_free(values);

		master_parse_entry(parse_buf, timeout, logging, age);
next:
		ldap_value_free(keyValue);
		if (key)
			free(key);
		e = ldap_next_entry(ldap, e);
	}

	/* Clean up. */
	ldap_msgfree(result);
	unbind_ldap_connection(logopt, &conn, ctxt);
	free(query);

	return NSS_STATUS_SUCCESS;
}

static int get_percent_decoded_len(const char *name)
{
	int escapes = 0;
	int escaped = 0;
	const char *tmp = name;
	int look_for_close = 0;

	while (*tmp) {
		if (*tmp == '%') {
			/* assume escapes aren't interpreted inside brackets */
			if (look_for_close) {
				tmp++;
				continue;
			}
			/* check for escaped % */
			if (escaped) {
				tmp++;
				escaped = 0;
				continue;
			}
			escapes++;
			tmp++;
			if (*tmp == '[') {
				escapes++;
				tmp++;
				look_for_close = 1;
			} else
				escaped = 1;
		} else if (*tmp == ']' && look_for_close) {
			escaped = 0;
			escapes++;
			tmp++;
			look_for_close = 0;
		} else {
			tmp++;
			escaped = 0;
		}
	}

	assert(strlen(name) > escapes);
	return strlen(name) - escapes;
}

/*
 * Try to catch heap corruption if our logic happens to be incorrect.
 */
static void validate_string_len(const char *orig, char *start,
				char *end, unsigned int len)
{
	debug(LOGOPT_NONE, MODPREFIX "string %s encoded as %s", orig, start);
	/* make sure we didn't overflow the allocated space */
	if (end - start > len + 1) {
		crit(LOGOPT_ANY, MODPREFIX "orig %s, len %d", orig, len);
		crit(LOGOPT_ANY, MODPREFIX "en/decoded %s, len %d", start,
		     end - start);
	}
	assert(end-start <= len + 1);
}

/*
 * Deal with encode and decode of % hack.
 * Return
 * 0 => % hack not present.
 * -1 => syntax error or alloc fail.
 * 1 transofrmed value returned.
 */
/*
 * Assumptions: %'s must be escaped by %'s.  %'s are not used to escape
 * anything else except capital letters (so you can't escape a closing
 * bracket, for example).
 */
static int decode_percent_hack(const char *name, char **key)
{
	const char *tmp;
	char *ptr, *new;
	unsigned int len;
	int escaped = 0, look_for_close = 0;

	if (!key)
		return -1;

	*key = NULL;

	len = get_percent_decoded_len(name);
	if (!len)
		return 0;
	new = malloc(len + 1);
	if (!new)
		return -1;

	ptr = new;
	tmp = name;
	while (*tmp) {
		if (*tmp == '%') {
			if (escaped) {
				*ptr++ = *tmp++;
				if (!look_for_close)
					escaped = 0;
				continue;
			}
			tmp++;
			if (*tmp == '[') {
				tmp++;
				look_for_close = 1;
				escaped = 1;
			} else
				escaped = 1;
		} else if (*tmp == ']' && look_for_close) {
			tmp++;
			look_for_close = 0;
		} else {
			escaped = 0;
			*ptr++ = *tmp++;
		}
	}
	*ptr = '\0';
	*key = new;

	validate_string_len(name, new, ptr, len);
	return strlen(new);
}

/*
 * Calculate the length of a string replacing all capital letters with %letter.
 * For example:
 * Sale -> %Sale
 * SALE -> %S%A%L%E
 */
static int get_encoded_len_escaping_every_cap(const char *name)
{
	const char *tmp;
	unsigned int escapes = 0; /* number of % escape characters */

	tmp = name;
	while (*tmp) {
		/* We'll need to escape percents */
		if (*tmp == '%' || isupper(*tmp))
			escapes++;
		tmp++;
	}

	return strlen(name) + escapes;
}

/*
 * Calculate the length of a string replacing sequences (1 or more) of capital
 * letters with %[letters].  For example:
 * FOO ->  %[FOO]
 * Work -> %[W]ork
 * WorksForMe -> %[W]orks%[F]or%[M]e
 * aaBBaa -> aa%[BB]aa
 */
static int get_encoded_len_escaping_sequences(const char *name)
{
	const char *tmp;
	unsigned int escapes = 0;

	tmp = name;
	while (*tmp) {
		/* escape percents */
		if (*tmp == '%')
			escapes++;
		else if (isupper(*tmp)) {
			/* start an escape block %[...] */
			escapes += 3;  /* %[] */
			while (*tmp && isupper(*tmp))
				tmp++;
			continue;
		}
		tmp++;
	}

	return strlen(name) + escapes;
}

static void encode_individual(const char *name, char *new, unsigned int len)
{
	const char *tmp;
	char *ptr;

	ptr = new;
	tmp = name;
	while (*tmp) {
		if (*tmp == '%' || isupper(*tmp))
			*ptr++ = '%';
		*ptr++ = *tmp++;
	}
	*ptr = '\0';
	validate_string_len(name, new, ptr, len);
}

static void encode_sequence(const char *name, char *new, unsigned int len)
{
	const char *tmp;
	char *ptr;

	ptr = new;
	tmp = name;
	while (*tmp) {
		if (*tmp == '%') {
			*ptr++ = '%';
			*ptr++ = *tmp++;
		} else if (isupper(*tmp)) {
			*ptr++ = '%';
			*ptr++ = '[';
			*ptr++ = *tmp++;

			while (*tmp && isupper(*tmp)) {
				*ptr++ = *tmp;
				tmp++;
			}
			*ptr++ = ']';
		} else
			*ptr++ = *tmp++;
	}
	*ptr = '\0';
	validate_string_len(name, new, ptr, len);
}

/*
 * use_class:  1 means encode string as %[CAPITALS], 0 means encode as
 * %C%A%P%I%T%A%L%S
 */
static int encode_percent_hack(const char *name, char **key, unsigned int use_class)
{
	unsigned int len = 0;

	if (!key)
		return -1;

	if (use_class)
		len = get_encoded_len_escaping_sequences(name);
	else
		len = get_encoded_len_escaping_every_cap(name);

	/* If there is no escaping to be done, return 0 */
	if (len == strlen(name))
		return 0;

	*key = malloc(len + 1);
	if (!*key)
		return -1;

	if (use_class)
		encode_sequence(name, *key, len);
	else
		encode_individual(name, *key, len);

	if (strlen(*key) != len)
		crit(LOGOPT_ANY, MODPREFIX "encoded key length mismatch: key "
		     "%s len %d strlen %d", *key, len, strlen(*key));

	return strlen(*key);
}

static int do_paged_query(struct ldap_search_params *sp, struct lookup_context *ctxt)
{
	struct autofs_point *ap = sp->ap;
	LDAPControl *pageControl=NULL, *controls[2] = { NULL, NULL };
	LDAPControl **returnedControls = NULL;
	static char pagingCriticality = 'T';
	int rv, scope = LDAP_SCOPE_SUBTREE;

	if (sp->morePages == TRUE)
		goto do_paged;

	rv = ldap_search_s(sp->ldap, sp->base, scope, sp->query, sp->attrs, 0, &sp->result);
	if ((rv != LDAP_SUCCESS) || !sp->result) {
		/*
 		 * Check for Size Limit exceeded and force run through loop
		 * and requery using page control.
 		 */
		if (rv == LDAP_SIZELIMIT_EXCEEDED ||
		    rv == LDAP_ADMINLIMIT_EXCEEDED)
			sp->morePages = TRUE;
		else {
			debug(ap->logopt,
			      MODPREFIX "query failed for %s: %s",
			      sp->query, ldap_err2string(rv));
			return rv;
		}
	}
	return rv;

do_paged:
	/* we need to use page controls so requery LDAP */
	debug(ap->logopt, MODPREFIX "getting page of results");

	rv = ldap_create_page_control(sp->ldap, sp->pageSize, sp->cookie,
				      pagingCriticality, &pageControl);
	if (rv != LDAP_SUCCESS) {
		warn(ap->logopt, MODPREFIX "failed to create page control");
		return rv;
	}

	/* Insert the control into a list to be passed to the search. */
	controls[0] = pageControl;

	/* Search for entries in the directory using the parmeters. */
	rv = ldap_search_ext_s(sp->ldap,
			       sp->base, scope, sp->query, sp->attrs,
			       0, controls, NULL, NULL, 0, &sp->result);
	if ((rv != LDAP_SUCCESS) && (rv != LDAP_PARTIAL_RESULTS)) {
		ldap_control_free(pageControl);
		if (rv != LDAP_ADMINLIMIT_EXCEEDED)
			debug(ap->logopt,
			      MODPREFIX "query failed for %s: %s",
			      sp->query, ldap_err2string(rv));
		return rv;
	}

	/* Parse the results to retrieve the contols being returned. */
	rv = ldap_parse_result(sp->ldap, sp->result,
			       NULL, NULL, NULL, NULL,
			       &returnedControls, FALSE);
	if (sp->cookie != NULL) {
		ber_bvfree(sp->cookie);
		sp->cookie = NULL;
	}

	if (rv != LDAP_SUCCESS) {
		debug(ap->logopt,
		      MODPREFIX "ldap_parse_result failed with %d", rv);
		goto out_free;
	}

	/*
	 * Parse the page control returned to get the cookie and
	 * determine whether there are more pages.
	 */
	rv = ldap_parse_page_control(sp->ldap,
				     returnedControls, &sp->totalCount,
				     &sp->cookie);
	if (sp->cookie && sp->cookie->bv_val &&
	    (strlen(sp->cookie->bv_val) || sp->cookie->bv_len))
		sp->morePages = TRUE;
	else
		sp->morePages = FALSE;

	/* Cleanup the controls used. */
	if (returnedControls)
		ldap_controls_free(returnedControls);

out_free:
	ldap_control_free(pageControl);
	return rv;
}

static int do_get_entries(struct ldap_search_params *sp, struct map_source *source, struct lookup_context *ctxt)
{
	struct autofs_point *ap = sp->ap;
	struct mapent_cache *mc = source->mc;
	char buf[MAX_ERR_BUF];
	struct berval **bvKey;
	struct berval **bvValues;
	LDAPMessage *e;
	char *class, *info, *entry;
	int rv, ret;
	int i, count;

	class = ctxt->schema->entry_class;
	entry = ctxt->schema->entry_attr;
	info = ctxt->schema->value_attr;

	e = ldap_first_entry(sp->ldap, sp->result);
	if (!e) {
		debug(ap->logopt,
		      MODPREFIX "query succeeded, no matches for %s",
		      sp->query);
		ret = ldap_parse_result(sp->ldap, sp->result,
					&rv, NULL, NULL, NULL, NULL, 0);
		if (ret == LDAP_SUCCESS)
			return rv;
		else
			return LDAP_OPERATIONS_ERROR;
	} else
		debug(ap->logopt, MODPREFIX "examining entries");

	while (e) {
		char *mapent = NULL;
		size_t mapent_len = 0;
		char *k_val;
		ber_len_t k_len;
		char *s_key;

		bvKey = ldap_get_values_len(sp->ldap, e, entry);
		if (!bvKey || !*bvKey) {
			e = ldap_next_entry(sp->ldap, e);
			if (!e) {
				debug(ap->logopt, MODPREFIX
				      "failed to get next entry for query %s",
				      sp->query);
				ret = ldap_parse_result(sp->ldap,
							sp->result, &rv,
							NULL, NULL, NULL, NULL, 0);
				if (ret == LDAP_SUCCESS)
					return rv;
				else
					return LDAP_OPERATIONS_ERROR;
			}
			continue;
		}

		/*
		 * By definition keys should be unique within each map entry,
		 * but as always there are exceptions.
		 */
		k_val = NULL;
		k_len = 0;

		/*
		 * Keys should be unique so, in general, there shouldn't be
		 * more than one attribute value. We make an exception for
		 * wildcard entries as people may have values for '*' or
		 * '/' for compaibility reasons. We use the '/' as the
		 * wildcard in LDAP but allow '*' as well to allow for
		 * people using older schemas that allow '*' as a key
		 * value. Another case where there can be multiple key
		 * values is when people have used the "%" hack to specify
		 * case matching ctriteria in a case insensitive attribute.
		 */
		count = ldap_count_values_len(bvKey);
		if (count > 1) {
			unsigned int i;

			/* Check for the "/" and "*" and use as "/" if found */
			for (i = 0; i < count; i++) {
				bvKey[i]->bv_val[bvKey[i]->bv_len] = '\0';

				/*
				 * If multiple entries are present they could
				 * be the result of people using the "%" hack so
				 * ignore them.
				 */
				if (strchr(bvKey[i]->bv_val, '%'))
					continue;

				/* check for wildcard */
				if (bvKey[i]->bv_len == 1 &&
				    (*bvKey[i]->bv_val == '/' ||
				     *bvKey[i]->bv_val == '*')) {
					/* always use '/' internally */
					*bvKey[i]->bv_val = '/';
					k_val = bvKey[i]->bv_val;
					k_len = 1;
					break;
				}

				/*
				 * We have a result from LDAP so this is a
				 * valid entry. Set the result to the LDAP
				 * key that isn't a wildcard and doesn't have
				 * any "%" hack values present. This should be
				 * the case insensitive match string for the
				 * nis schema, the default value.
				 */
				k_val = bvKey[i]->bv_val;
				k_len = bvKey[i]->bv_len;

				break;
			}

			if (!k_val) {
				error(ap->logopt,
				      MODPREFIX "invalid entry %.*s - ignoring",
				      bvKey[0]->bv_len, bvKey[0]->bv_val);
				goto next;
			}
		} else {
			/* Check for the "*" and use as "/" if found */
			if (bvKey[0]->bv_len == 1 && *bvKey[0]->bv_val == '*')
				*bvKey[0]->bv_val = '/';
			k_val = bvKey[0]->bv_val;
			k_len = bvKey[0]->bv_len;
		}

		/*
		 * Ignore keys beginning with '+' as plus map
		 * inclusion is only valid in file maps.
		 */
		if (*k_val == '+') {
			warn(ap->logopt,
			     MODPREFIX
			     "ignoreing '+' map entry - not in file map");
			goto next;
		}

		bvValues = ldap_get_values_len(sp->ldap, e, info);
		if (!bvValues || !*bvValues) {
			debug(ap->logopt,
			      MODPREFIX "no %s defined for %s", info, sp->query);
			goto next;
		}

		/*
		 * We expect that there will be only one value because
		 * questions of order of returned value entries but we
		 * accumulate values to support simple multi-mounts.
		 *
		 * If the ordering of a mount spec with another containing
		 * options or the actual order of entries causes problems
		 * it won't be supported. Perhaps someone can instruct us
		 * how to force an ordering.
		 */
		count = ldap_count_values_len(bvValues);
		for (i = 0; i < count; i++) {
			char *v_val = bvValues[i]->bv_val;
			ber_len_t v_len = bvValues[i]->bv_len;

			if (!mapent) {
				mapent = malloc(v_len + 1);
				if (!mapent) {
					char *estr;
					estr = strerror_r(errno, buf, sizeof(buf));
					logerr(MODPREFIX "malloc: %s", estr);
					ldap_value_free_len(bvValues);
					goto next;
				}
				strncpy(mapent, v_val, v_len);
				mapent[v_len] = '\0';
				mapent_len = v_len;
			} else {
				int new_size = mapent_len + v_len + 2;
				char *new_me;
				new_me = realloc(mapent, new_size);
				if (new_me) {
					mapent = new_me;
					strcat(mapent, " ");
					strncat(mapent, v_val, v_len);
					mapent[new_size - 1] = '\0';
					mapent_len = new_size - 1;
				} else {
					char *estr;
					estr = strerror_r(errno, buf, sizeof(buf));
					logerr(MODPREFIX "realloc: %s", estr);
				}
			}
		}
		ldap_value_free_len(bvValues);

		if (*k_val == '/' && k_len == 1) {
			if (ap->type == LKP_DIRECT)
				goto next;
			*k_val = '*';
		}

		if (strcasecmp(class, "nisObject")) {
			s_key = sanitize_path(k_val, k_len, ap->type, ap->logopt);
			if (!s_key)
				goto next;
		} else {
			char *dec_key;
			int dec_len = decode_percent_hack(k_val, &dec_key);

			if (dec_len < 0) {
				crit(ap->logopt,
				     "could not use percent hack to decode key %s",
				     k_val);
				goto next;
			}

			if (dec_len == 0)
				s_key = sanitize_path(k_val, k_len, ap->type, ap->logopt);
			else {
				s_key = sanitize_path(dec_key, dec_len, ap->type, ap->logopt);
				free(dec_key);
			}
			if (!s_key)
				goto next;
		}

		cache_writelock(mc);
		cache_update(mc, source, s_key, mapent, sp->age);
		cache_unlock(mc);

		free(s_key);
next:
		if (mapent) {
			free(mapent);
			mapent = NULL;
		}

		ldap_value_free_len(bvKey);
		e = ldap_next_entry(sp->ldap, e);
		if (!e) {
			debug(ap->logopt, MODPREFIX
			      "failed to get next entry for query %s",
			      sp->query);
			ret = ldap_parse_result(sp->ldap,
						sp->result, &rv,
						NULL, NULL, NULL, NULL, 0);
			if (ret == LDAP_SUCCESS)
				return rv;
			else
				return LDAP_OPERATIONS_ERROR;
		}
	}

	return LDAP_SUCCESS;
}

static int do_get_amd_entries(struct ldap_search_params *sp,
			      struct map_source *source,
			      struct lookup_context *ctxt)
{
	struct autofs_point *ap = sp->ap;
	struct mapent_cache *mc = source->mc;
	struct berval **bvKey;
	struct berval **bvValues;
	LDAPMessage *e;
	char *entry, *value;
	int rv, ret, count;

	entry = ctxt->schema->entry_attr;
	value = ctxt->schema->value_attr;

	e = ldap_first_entry(sp->ldap, sp->result);
	if (!e) {
		debug(ap->logopt,
		      MODPREFIX "query succeeded, no matches for %s",
		      sp->query);
		ret = ldap_parse_result(sp->ldap, sp->result,
					&rv, NULL, NULL, NULL, NULL, 0);
		if (ret == LDAP_SUCCESS)
			return rv;
		else
			return LDAP_OPERATIONS_ERROR;
	} else
		debug(ap->logopt, MODPREFIX "examining entries");

	while (e) {
		char *k_val, *v_val;
		ber_len_t k_len;
		char *s_key;

		bvKey = ldap_get_values_len(sp->ldap, e, entry);
		if (!bvKey || !*bvKey) {
			e = ldap_next_entry(sp->ldap, e);
			if (!e) {
				debug(ap->logopt, MODPREFIX
				      "failed to get next entry for query %s",
				      sp->query);
				ret = ldap_parse_result(sp->ldap,
							sp->result, &rv,
							NULL, NULL, NULL, NULL, 0);
				if (ret == LDAP_SUCCESS)
					return rv;
				else
					return LDAP_OPERATIONS_ERROR;
			}
			continue;
		}

		/* By definition keys should be unique within each map entry */
		k_val = NULL;
		k_len = 0;

		count = ldap_count_values_len(bvKey);
		if (count > 1)
			warn(ap->logopt, MODPREFIX
			     "more than one %s, using first", entry);

		k_val = bvKey[0]->bv_val;
		k_len = bvKey[0]->bv_len;

		bvValues = ldap_get_values_len(sp->ldap, e, value);
		if (!bvValues || !*bvValues) {
			debug(ap->logopt,
			      MODPREFIX "no %s defined for %s",
			      value, sp->query);
			goto next;
		}

		count = ldap_count_values_len(bvValues);
		if (count > 1)
			warn(ap->logopt, MODPREFIX
			     "more than one %s, using first", value);

		v_val = bvValues[0]->bv_val;

		/* Don't fail on "/" in key => type == 0 */
		s_key = sanitize_path(k_val, k_len, 0, ap->logopt);
		if (!s_key)
			goto next;

		cache_writelock(mc);
		cache_update(mc, source, s_key, v_val, sp->age);
		cache_unlock(mc);

		free(s_key);
next:
		ldap_value_free_len(bvValues);
		ldap_value_free_len(bvKey);
		e = ldap_next_entry(sp->ldap, e);
		if (!e) {
			debug(ap->logopt, MODPREFIX
			      "failed to get next entry for query %s",
			      sp->query);
			ret = ldap_parse_result(sp->ldap,
						sp->result, &rv,
						NULL, NULL, NULL, NULL, 0);
			if (ret == LDAP_SUCCESS)
				return rv;
			else
				return LDAP_OPERATIONS_ERROR;
		}
	}

	return LDAP_SUCCESS;
}

static int read_one_map(struct autofs_point *ap,
			struct map_source *source,
			struct lookup_context *ctxt,
			time_t age, int *result_ldap)
{
	struct ldap_conn conn;
	struct ldap_search_params sp;
	char buf[MAX_ERR_BUF];
	char *class, *info, *entry;
	char *attrs[3];
	int rv, l;

	/*
	 * If we don't need to create directories (or don't need
	 * to read an amd cache:=all map) then there's no use
	 * reading the map. We always need to read the whole map
	 * for direct mounts in order to mount the triggers.
	 */
	if (ap->type != LKP_DIRECT &&
	    !(ap->flags & (MOUNT_FLAG_GHOST|MOUNT_FLAG_AMD_CACHE_ALL))) {
		debug(ap->logopt, "map read not needed, so not done");
		return NSS_STATUS_SUCCESS;
	}

	sp.ap = ap;
	sp.age = age;

	/* Initialize the LDAP context. */
	memset(&conn, 0, sizeof(struct ldap_conn));
	rv = do_reconnect(ap->logopt, &conn, ctxt);
	if (rv)
		return rv;
	sp.ldap = conn.ldap;

	class = ctxt->schema->entry_class;
	entry = ctxt->schema->entry_attr;
	info = ctxt->schema->value_attr;

	attrs[0] = entry;
	attrs[1] = info;
	attrs[2] = NULL;
	sp.attrs = attrs;

	/* Build a query string. */
	l = strlen("(objectclass=)") + strlen(class) + 1;

	sp.query = malloc(l);
	if (sp.query == NULL) {
		char *estr = strerror_r(errno, buf, sizeof(buf));
		logerr(MODPREFIX "malloc: %s", estr);
		return NSS_STATUS_UNAVAIL;
	}

	if (sprintf(sp.query, "(objectclass=%s)", class) >= l) {
		error(ap->logopt, MODPREFIX "error forming query string");
		free(sp.query);
		return NSS_STATUS_UNAVAIL;
	}

	if (ctxt->format & MAP_FLAG_FORMAT_AMD)
		sp.base = ctxt->base;
	else
		sp.base = ctxt->qdn;

	/* Look around. */
	debug(ap->logopt,
	      MODPREFIX "searching for \"%s\" under \"%s\"", sp.query, sp.base);

	sp.cookie = NULL;
	sp.pageSize = 2000;
	sp.morePages = FALSE;
	sp.totalCount = 0;
	sp.result = NULL;

	do {
		rv = do_paged_query(&sp, ctxt);

		if (rv == LDAP_ADMINLIMIT_EXCEEDED ||
		    rv == LDAP_SIZELIMIT_EXCEEDED) {
			if (sp.result) {
				ldap_msgfree(sp.result);
				sp.result = NULL;
			}
			if (sp.cookie) {
				ber_bvfree(sp.cookie);
				sp.cookie = NULL;
			}
			sp.pageSize = sp.pageSize / 2;
			if (sp.pageSize < 5) {
				debug(ap->logopt, MODPREFIX
				      "result size too small");
				unbind_ldap_connection(ap->logopt, &conn, ctxt);
				*result_ldap = rv;
				free(sp.query);
				return NSS_STATUS_UNAVAIL;
			}
			continue;
		}

		if (rv != LDAP_SUCCESS || !sp.result) {
			unbind_ldap_connection(ap->logopt, &conn, ctxt);
			*result_ldap = rv;
			if (sp.result)
				ldap_msgfree(sp.result);
			if (sp.cookie)
				ber_bvfree(sp.cookie);
			free(sp.query);
			return NSS_STATUS_UNAVAIL;
		}

		if (source->flags & MAP_FLAG_FORMAT_AMD)
			rv = do_get_amd_entries(&sp, source, ctxt);
		else
			rv = do_get_entries(&sp, source, ctxt);
		if (rv != LDAP_SUCCESS) {
			ldap_msgfree(sp.result);
			unbind_ldap_connection(ap->logopt, &conn, ctxt);
			*result_ldap = rv;
			if (sp.cookie)
				ber_bvfree(sp.cookie);
			free(sp.query);
			return NSS_STATUS_NOTFOUND;
		}
		ldap_msgfree(sp.result);
		sp.result = NULL;
	} while (sp.morePages == TRUE);

	debug(ap->logopt, MODPREFIX "done updating map");

	unbind_ldap_connection(ap->logopt, &conn, ctxt);

	source->age = age;
	if (sp.cookie)
		ber_bvfree(sp.cookie);
	free(sp.query);

	return NSS_STATUS_SUCCESS;
}

int lookup_read_map(struct autofs_point *ap, time_t age, void *context)
{
	struct lookup_context *ctxt = (struct lookup_context *) context;
	struct map_source *source;
	int rv = LDAP_SUCCESS;
	int ret, cur_state;

	source = ap->entry->current;
	ap->entry->current = NULL;
	master_source_current_signal(ap->entry);

	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cur_state);
	ret = read_one_map(ap, source, ctxt, age, &rv);
	if (ret != NSS_STATUS_SUCCESS) {
		switch (rv) {
		case LDAP_SIZELIMIT_EXCEEDED:
			crit(ap->logopt, MODPREFIX
			     "Unable to download entire LDAP map for: %s",
			     ap->path);
		case LDAP_UNWILLING_TO_PERFORM:
			pthread_setcancelstate(cur_state, NULL);
			return NSS_STATUS_UNAVAIL;
		}
	}
	pthread_setcancelstate(cur_state, NULL);

	return ret;
}

static int lookup_one(struct autofs_point *ap, struct map_source *source,
		char *qKey, int qKey_len, struct lookup_context *ctxt)
{
	struct mapent_cache *mc;
	struct ldap_conn conn;
	LDAP *ldap;
	int rv, i, l, ql, count;
	char buf[MAX_ERR_BUF];
	time_t age = monotonic_time(NULL);
	char *query;
	LDAPMessage *result = NULL, *e;
	char *class, *info, *entry;
	char *enc_key1, *enc_key2;
	int enc_len1 = 0, enc_len2 = 0;
	struct berval **bvKey;
	struct berval **bvValues;
	char *attrs[3];
	int scope = LDAP_SCOPE_SUBTREE;
	struct mapent *we;
	unsigned int wild = 0;
	int ret = CHE_MISSING;

	mc = source->mc;

	if (ctxt == NULL) {
		crit(ap->logopt, MODPREFIX "context was NULL");
		return CHE_FAIL;
	}

	/* Initialize the LDAP context. */
	memset(&conn, 0, sizeof(struct ldap_conn));
	rv = do_reconnect(ap->logopt, &conn, ctxt);
	if (rv == NSS_STATUS_UNAVAIL)
		return CHE_UNAVAIL;
	if (rv == NSS_STATUS_NOTFOUND)
		return ret;
	ldap = conn.ldap;

	class = ctxt->schema->entry_class;
	entry = ctxt->schema->entry_attr;
	info = ctxt->schema->value_attr;

	attrs[0] = entry;
	attrs[1] = info;
	attrs[2] = NULL;

	enc_key1 = NULL;
	enc_key2 = NULL;

	if (*qKey == '*' && qKey_len == 1)
		*qKey = '/';
	else if (!strcasecmp(class, "nisObject")) {
		enc_len1 = encode_percent_hack(qKey, &enc_key1, 0);
		if (enc_len1 < 0) {
			crit(ap->logopt,
			     "could not use percent hack encode key %s",
			     qKey);
			return CHE_FAIL;
		}
		if (enc_len1 != 0) {
			enc_len2 = encode_percent_hack(qKey, &enc_key2, 1);
			if (enc_len2 < 0) {
				free(enc_key1);
				crit(ap->logopt,
				     "could not use percent hack encode key %s",
				     qKey);
				return CHE_FAIL;
			}
		}
	}

	/* Build a query string. */
	l = strlen(class) + 3*strlen(entry) + strlen(qKey) + 35;
	if (enc_len1)
		l += 2*strlen(entry) + enc_len1 + enc_len2 + 6;

	query = malloc(l);
	if (query == NULL) {
		char *estr = strerror_r(errno, buf, sizeof(buf));
		crit(ap->logopt, MODPREFIX "malloc: %s", estr);
		if (enc_len1) {
			free(enc_key1);
			free(enc_key2);
		}
		free(query);
		return CHE_FAIL;
	}

	/*
	 * Look for an entry in class under ctxt-base
	 * whose entry is equal to qKey.
	 */
	if (!enc_len1) {
		ql = sprintf(query,
			"(&(objectclass=%s)(|(%s=%s)(%s=/)(%s=\\2A)))",
			class, entry, qKey, entry, entry);
	} else {
		if (enc_len2) {
			ql = sprintf(query,
				"(&(objectclass=%s)"
				"(|(%s=%s)(%s=%s)(%s=%s)(%s=/)(%s=\\2A)))",
				class, entry, qKey,
				entry, enc_key1, entry, enc_key2, entry, entry);
			free(enc_key1);
			free(enc_key2);
		} else {
			ql = sprintf(query,
				"(&(objectclass=%s)"
				"(|(%s=%s)(%s=%s)(%s=/)(%s=\\2A)))",
				class, entry, qKey, entry, enc_key1, entry, entry);
			free(enc_key1);
		}
	}
	if (ql >= l) {
		error(ap->logopt,
		      MODPREFIX "error forming query string");
		free(query);
		return CHE_FAIL;
	}

	debug(ap->logopt,
	      MODPREFIX "searching for \"%s\" under \"%s\"", query, ctxt->qdn);

	rv = ldap_search_s(ldap, ctxt->qdn, scope, query, attrs, 0, &result);

	if ((rv != LDAP_SUCCESS) || !result) {
		crit(ap->logopt, MODPREFIX "query failed for %s", query);
		unbind_ldap_connection(ap->logopt, &conn, ctxt);
		if (result)
			ldap_msgfree(result);
		free(query);
		return CHE_FAIL;
	}

	debug(ap->logopt,
	      MODPREFIX "getting first entry for %s=\"%s\"", entry, qKey);

	e = ldap_first_entry(ldap, result);
	if (!e) {
		debug(ap->logopt,
		     MODPREFIX "got answer, but no entry for %s", query);
		ldap_msgfree(result);
		unbind_ldap_connection(ap->logopt, &conn, ctxt);
		free(query);
		return CHE_MISSING;
	}

	while (e) {
		char *mapent = NULL;
		size_t mapent_len = 0;
		char *k_val;
		ber_len_t k_len;
		char *s_key;

		bvKey = ldap_get_values_len(ldap, e, entry);
		if (!bvKey || !*bvKey) {
			e = ldap_next_entry(ldap, e);
			continue;
		}

		/*
		 * By definition keys should be unique within each map entry,
		 * but as always there are exceptions.
		 */
		k_val = NULL;
		k_len = 0;

		/*
		 * Keys must be unique so, in general, there shouldn't be
		 * more than one attribute value. We make an exception for
		 * wildcard entries as people may have values for '*' or
		 * '/' for compaibility reasons. We use the '/' as the
		 * wildcard in LDAP but allow '*' as well to allow for
		 * people using older schemas that allow '*' as a key
		 * value. Another case where there can be multiple key
		 * values is when people have used the "%" hack to specify
		 * case matching ctriteria in a caase insensitive attribute.
		 */
		count = ldap_count_values_len(bvKey);
		if (count > 1) {
			unsigned int i;

			/* Check for the "/" and "*" and use as "/" if found */
			for (i = 0; i < count; i++) {
				bvKey[i]->bv_val[bvKey[i]->bv_len] = '\0';

				/*
				 * If multiple entries are present they could
				 * be the result of people using the "%" hack so
				 * ignore them.
				 */
				if (strchr(bvKey[i]->bv_val, '%'))
					continue;

				/* check for wildcard */
				if (bvKey[i]->bv_len == 1 &&
				    (*bvKey[i]->bv_val == '/' ||
				     *bvKey[i]->bv_val == '*')) {
					/* always use '/' internally */
					*bvKey[i]->bv_val = '/';
					k_val = bvKey[i]->bv_val;
					k_len = 1;
					break;
				}

				/*
				 * The key was matched by LDAP so this is a
				 * valid entry. Set the result key to the
				 * lookup key to provide the mixed case
				 * matching provided by the "%" hack.
				 */
				k_val = qKey;
				k_len = strlen(qKey);

				break;
			}

			if (!k_val) {
				error(ap->logopt,
					MODPREFIX "no valid key found for %.*s",
					qKey_len, qKey);
				ret = CHE_FAIL;
				goto next;
			}
		} else {
			/* Check for the "*" and use as "/" if found */
			if (bvKey[0]->bv_len == 1 && *bvKey[0]->bv_val == '*')
				*bvKey[0]->bv_val = '/';
			k_val = bvKey[0]->bv_val;
			k_len = bvKey[0]->bv_len;
		}

		debug(ap->logopt, MODPREFIX "examining first entry");

		bvValues = ldap_get_values_len(ldap, e, info);
		if (!bvValues || !*bvValues) {
			debug(ap->logopt,
			      MODPREFIX "no %s defined for %s", info, query);
			goto next;
		}

		count = ldap_count_values_len(bvValues);
		for (i = 0; i < count; i++) {
			char *v_val = bvValues[i]->bv_val;
			ber_len_t v_len = bvValues[i]->bv_len;

			if (!mapent) {
				mapent = malloc(v_len + 1);
				if (!mapent) {
					char *estr;
					estr = strerror_r(errno, buf, sizeof(buf));
					logerr(MODPREFIX "malloc: %s", estr);
					ldap_value_free_len(bvValues);
					goto next;
				}
				strncpy(mapent, v_val, v_len);
				mapent[v_len] = '\0';
				mapent_len = v_len;
			} else {
				int new_size = mapent_len + v_len + 2;
				char *new_me;
				new_me = realloc(mapent, new_size);
				if (new_me) {
					mapent = new_me;
					strcat(mapent, " ");
					strncat(mapent, v_val, v_len);
					mapent[new_size - 1] = '\0';
					mapent_len = new_size - 1;
				} else {
					char *estr;
					estr = strerror_r(errno, buf, sizeof(buf));
					logerr(MODPREFIX "realloc: %s", estr);
				}
			}
		}
		ldap_value_free_len(bvValues);

		if (*k_val == '/' && k_len == 1) {
			if (ap->type == LKP_DIRECT)
				goto next;
			wild = 1;
			cache_writelock(mc);
			cache_update(mc, source, "*", mapent, age);
			cache_unlock(mc);
			goto next;
		}

		if (strcasecmp(class, "nisObject")) {
			s_key = sanitize_path(k_val, k_len, ap->type, ap->logopt);
			if (!s_key)
				goto next;
		} else {
			char *dec_key;
			int dec_len = decode_percent_hack(k_val, &dec_key);

			if (dec_len < 0) {
				crit(ap->logopt,
				     "could not use percent hack to decode key %s",
				     k_val);
				goto next;
			}

			if (dec_len == 0)
				s_key = sanitize_path(k_val, k_len, ap->type, ap->logopt);
			else {
				s_key = sanitize_path(dec_key, dec_len, ap->type, ap->logopt);
				free(dec_key);
			}
			if (!s_key)
				goto next;
		}

		cache_writelock(mc);
		ret = cache_update(mc, source, s_key, mapent, age);
		cache_unlock(mc);

		free(s_key);
next:
		if (mapent) {
			free(mapent);
			mapent = NULL;
		}

		ldap_value_free_len(bvKey);
		e = ldap_next_entry(ldap, e);
	}

	ldap_msgfree(result);
	unbind_ldap_connection(ap->logopt, &conn, ctxt);

	/* Failed to find wild entry, update cache if needed */
	cache_writelock(mc);
	we = cache_lookup_distinct(mc, "*");
	if (we) {
		/* Wildcard entry existed and is now gone */
		if (we->source == source && !wild) {
			cache_delete(mc, "*");
			source->stale = 1;
		}
	} else {
		/* Wildcard not in map but now is */
		if (wild)
			source->stale = 1;
	}
	/* Not found in the map but found in the cache */
	if (ret == CHE_MISSING) {
		struct mapent *exists = cache_lookup_distinct(mc, qKey);
		if (exists && exists->source == source) {
			if (exists->mapent) {
				free(exists->mapent);
				exists->mapent = NULL;
				source->stale = 1;
				exists->status = 0;
			}
		}
	}
	cache_unlock(mc);
	free(query);

	return ret;
}

static int lookup_one_amd(struct autofs_point *ap,
			  struct map_source *source,
			  char *qKey, int qKey_len,
			  struct lookup_context *ctxt)
{
	struct mapent_cache *mc = source->mc;
	struct ldap_conn conn;
	LDAP *ldap;
	LDAPMessage *result = NULL, *e;
	char *query;
	int scope = LDAP_SCOPE_SUBTREE;
	char *map, *class, *entry, *value;
	char *attrs[3];
	struct berval **bvKey;
	struct berval **bvValues;
	char buf[MAX_ERR_BUF];
	time_t age = monotonic_time(NULL);
	int rv, l, ql, count;
	int ret = CHE_MISSING;

	if (ctxt == NULL) {
		crit(ap->logopt, MODPREFIX "context was NULL");
		return CHE_FAIL;
	}

	/* Initialize the LDAP context. */
	memset(&conn, 0, sizeof(struct ldap_conn));
	rv = do_reconnect(ap->logopt, &conn, ctxt);
	if (rv == NSS_STATUS_UNAVAIL)
		return CHE_UNAVAIL;
	if (rv == NSS_STATUS_NOTFOUND)
		return ret;
	ldap = conn.ldap;

	map = ctxt->schema->map_attr;
	class = ctxt->schema->entry_class;
	entry = ctxt->schema->entry_attr;
	value = ctxt->schema->value_attr;

	attrs[0] = entry;
	attrs[1] = value;
	attrs[2] = NULL;

	/* Build a query string. */
	l = strlen(class) +
	    strlen(map) + strlen(ctxt->mapname) +
	    strlen(entry) + strlen(qKey) + 24;

	query = malloc(l);
	if (query == NULL) {
		char *estr = strerror_r(errno, buf, sizeof(buf));
		crit(ap->logopt, MODPREFIX "malloc: %s", estr);
		return CHE_FAIL;
	}

	/*
	 * Look for an entry in class under ctxt-base
	 * whose entry is equal to qKey.
	 */
	ql = sprintf(query, "(&(objectclass=%s)(%s=%s)(%s=%s))",
		     class, map, ctxt->mapname, entry, qKey);
	if (ql >= l) {
		error(ap->logopt,
		      MODPREFIX "error forming query string");
		free(query);
		return CHE_FAIL;
	}

	debug(ap->logopt,
	      MODPREFIX "searching for \"%s\" under \"%s\"", query, ctxt->base);

	rv = ldap_search_s(ldap, ctxt->base, scope, query, attrs, 0, &result);
	if ((rv != LDAP_SUCCESS) || !result) {
		crit(ap->logopt, MODPREFIX "query failed for %s", query);
		unbind_ldap_connection(ap->logopt, &conn, ctxt);
		if (result)
			ldap_msgfree(result);
		free(query);
		return CHE_FAIL;
	}

	debug(ap->logopt,
	      MODPREFIX "getting first entry for %s=\"%s\"", entry, qKey);

	e = ldap_first_entry(ldap, result);
	if (!e) {
		debug(ap->logopt,
		     MODPREFIX "got answer, but no entry for %s", query);
		ldap_msgfree(result);
		unbind_ldap_connection(ap->logopt, &conn, ctxt);
		free(query);
		return CHE_MISSING;
	}

	while (e) {
		char *k_val, *v_val;
		ber_len_t k_len;
		char *s_key;

		bvKey = ldap_get_values_len(ldap, e, entry);
		if (!bvKey || !*bvKey) {
			e = ldap_next_entry(ldap, e);
			continue;
		}

		/* By definition keys should be unique within each map entry */
		k_val = NULL;
		k_len = 0;

		count = ldap_count_values_len(bvKey);
		if (count > 1)
			warn(ap->logopt, MODPREFIX
			     "more than one %s, using first", entry);

		k_val = bvKey[0]->bv_val;
		k_len = bvKey[0]->bv_len;

		debug(ap->logopt, MODPREFIX "examining first entry");

		bvValues = ldap_get_values_len(ldap, e, value);
		if (!bvValues || !*bvValues) {
			debug(ap->logopt,
			      MODPREFIX "no %s defined for %s", value, query);
			goto next;
		}

		count = ldap_count_values_len(bvValues);
		if (count > 1)
			warn(ap->logopt, MODPREFIX
			     "more than one %s, using first", value);

		/* There should be one value for a key, use first value */
		v_val = bvValues[0]->bv_val;

		/* Don't fail on "/" in key => type == 0 */
		s_key = sanitize_path(k_val, k_len, 0, ap->logopt);
		if (!s_key)
			goto next;

		cache_writelock(mc);
		ret = cache_update(mc, source, s_key, v_val, age);
		cache_unlock(mc);

		free(s_key);
next:
		ldap_value_free_len(bvValues);
		ldap_value_free_len(bvKey);
		e = ldap_next_entry(ldap, e);
	}

	ldap_msgfree(result);
	unbind_ldap_connection(ap->logopt, &conn, ctxt);
	free(query);

	return ret;
}

static int match_key(struct autofs_point *ap,
		     struct map_source *source,
		     char *key, int key_len,
		     struct lookup_context *ctxt)
{
	unsigned int is_amd_format = source->flags & MAP_FLAG_FORMAT_AMD;
	char buf[MAX_ERR_BUF];
	char *lkp_key;
	char *prefix;
	int ret;

	if (is_amd_format)
		ret = lookup_one_amd(ap, source, key, key_len, ctxt);
	else
		ret = lookup_one(ap, source, key, key_len, ctxt);

	if (ret == CHE_OK || ret == CHE_UPDATED || !is_amd_format)
		return ret;

	lkp_key = strdup(key);
	if (!lkp_key) {
		char *estr = strerror_r(errno, buf, MAX_ERR_BUF);
		error(ap->logopt, MODPREFIX "strdup: %s", estr);
		return CHE_FAIL;
	}

	ret = CHE_MISSING;

	/*
	 * Now strip successive directory components and try a
	 * match against map entries ending with a wildcard and
	 * finally try the wildcard entry itself.
	 */
	while ((prefix = strrchr(lkp_key, '/'))) {
		char *match;
		size_t len;
		*prefix = '\0';
		len = strlen(lkp_key + 3);
		match = malloc(len);
		if (!match) {
			char *estr = strerror_r(errno, buf, MAX_ERR_BUF);
			error(ap->logopt, MODPREFIX "malloc: %s", estr);
			ret = CHE_FAIL;
			goto done;
		}
		len--;
		strcpy(match, lkp_key);
		strcat(match, "/*");
		ret = lookup_one_amd(ap, source, match, len, ctxt);
		free(match);
		if (ret == CHE_OK || ret == CHE_UPDATED)
			goto done;
	}
done:
	free(lkp_key);
	return ret;
}

static int check_map_indirect(struct autofs_point *ap,
			      struct map_source *source,
			      char *key, int key_len,
			      struct lookup_context *ctxt)
{
	unsigned int is_amd_format = source->flags & MAP_FLAG_FORMAT_AMD;
	struct mapent_cache *mc;
	struct mapent *me;
	time_t now = monotonic_time(NULL);
	time_t t_last_read;
	int ret, cur_state;
	int status;

	mc = source->mc;

	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cur_state);

	status = pthread_mutex_lock(&ap->entry->current_mutex);
	if (status)
		fatal(status);
	if (is_amd_format) {
		unsigned long timestamp = get_amd_timestamp(ctxt);
		if (timestamp > ctxt->timestamp) {
			ctxt->timestamp = timestamp;
			source->stale = 1;
			ctxt->check_defaults = 1;
		}

		if (ctxt->check_defaults) {
			/* Check for a /defaults entry */
			ret = lookup_one_amd(ap, source, "/defaults", 9, ctxt);
			if (ret == CHE_FAIL) {
				warn(ap->logopt, MODPREFIX
				     "error getting /defaults from map %s",
				     ctxt->mapname);
			} else
				ctxt->check_defaults = 0;
		}
	}
	status = pthread_mutex_unlock(&ap->entry->current_mutex);
	if (status)
		fatal(status);

	ret = match_key(ap, source, key, key_len, ctxt);
	if (ret == CHE_FAIL) {
		pthread_setcancelstate(cur_state, NULL);
		return NSS_STATUS_NOTFOUND;
	} else if (ret == CHE_UNAVAIL) {
		struct mapent *exists;
		/*
		 * If the server is down and the entry exists in the cache
		 * and belongs to this map return success and use the entry.
		 */
		if (source->flags & MAP_FLAG_FORMAT_AMD)
			exists = match_cached_key(ap, MODPREFIX, source, key);
		else
			exists = cache_lookup(mc, key);
		if (exists && exists->source == source) {
			pthread_setcancelstate(cur_state, NULL);
			return NSS_STATUS_SUCCESS;
		}

		warn(ap->logopt,
		     MODPREFIX "lookup for %s failed: connection failed", key);

		return NSS_STATUS_UNAVAIL;
	}
	pthread_setcancelstate(cur_state, NULL);

	if (!is_amd_format) {
		/*
		 * Check for map change and update as needed for
		 * following cache lookup.
		 */
		cache_readlock(mc);
		t_last_read = ap->exp_runfreq + 1;
		me = cache_lookup_first(mc);
		while (me) {
			if (me->source == source) {
				t_last_read = now - me->age;
				break;
			}
			me = cache_lookup_next(mc, me);
		}
		cache_unlock(mc);

		status = pthread_mutex_lock(&ap->entry->current_mutex);
		if (status)
			fatal(status);
		if (t_last_read > ap->exp_runfreq && ret & CHE_UPDATED)
			source->stale = 1;
		status = pthread_mutex_unlock(&ap->entry->current_mutex);
		if (status)
			fatal(status);
	}

	cache_readlock(mc);
	me = cache_lookup_distinct(mc, "*");
	if (ret == CHE_MISSING && (!me || me->source != source)) {
		cache_unlock(mc);
		return NSS_STATUS_NOTFOUND;
	}
	cache_unlock(mc);

	return NSS_STATUS_SUCCESS;
}

int lookup_mount(struct autofs_point *ap, const char *name, int name_len, void *context)
{
	struct lookup_context *ctxt = (struct lookup_context *) context;
	struct map_source *source;
	struct mapent_cache *mc;
	struct mapent *me;
	char key[KEY_MAX_LEN + 1];
	int key_len;
	char *lkp_key;
	char *mapent = NULL;
	char mapent_buf[MAPENT_MAX_LEN + 1];
	char buf[MAX_ERR_BUF];
	int status = 0;
	int ret = 1;

	source = ap->entry->current;
	ap->entry->current = NULL;
	master_source_current_signal(ap->entry);

	mc = source->mc;

	debug(ap->logopt, MODPREFIX "looking up %s", name);

	if (!(source->flags & MAP_FLAG_FORMAT_AMD)) {
		key_len = snprintf(key, KEY_MAX_LEN + 1, "%s", name);
		if (key_len > KEY_MAX_LEN)
			return NSS_STATUS_NOTFOUND;
	} else {
		key_len = expandamdent(name, NULL, NULL);
		if (key_len > KEY_MAX_LEN)
			return NSS_STATUS_NOTFOUND;
		expandamdent(name, key, NULL);
		key[key_len] = '\0';
		debug(ap->logopt, MODPREFIX "expanded key: \"%s\"", key);
	}

	/* Check if we recorded a mount fail for this key anywhere */
	me = lookup_source_mapent(ap, key, LKP_DISTINCT);
	if (me) {
		/* negative timeout has not passed, return fail */
		if (cache_lookup_negative(me, key) == CHE_UNAVAIL)
			return NSS_STATUS_NOTFOUND;
	}

        /*
	 * We can't check the direct mount map as if it's not in
	 * the map cache already we never get a mount lookup, so
	 * we never know about it.
	 */
	if (ap->type == LKP_INDIRECT && *key != '/') {
		cache_readlock(mc);
		me = cache_lookup_distinct(mc, key);
		if (me && IS_MM(me))
			lkp_key = strdup(MM_ROOT(me)->key);
		else if (!ap->pref)
			lkp_key = strdup(key);
		else {
			lkp_key = malloc(strlen(ap->pref) + strlen(key) + 1);
			if (lkp_key) {
				strcpy(lkp_key, ap->pref);
				strcat(lkp_key, key);
			}
		}
		cache_unlock(mc);

		if (!lkp_key) {
			char *estr = strerror_r(errno, buf, MAX_ERR_BUF);
			error(ap->logopt, MODPREFIX "malloc: %s", estr);
			return NSS_STATUS_UNKNOWN;
		}

		status = check_map_indirect(ap, source,
					    lkp_key, strlen(lkp_key), ctxt);
		free(lkp_key);
		if (status)
			return status;
	}

	/*
	 * We can't take the writelock for direct mounts. If we're
	 * starting up or trying to re-connect to an existing direct
	 * mount we could be iterating through the map entries with
	 * the readlock held. But we don't need to update the cache
	 * when we're starting up so just take the readlock in that
	 * case.
	 */
	if (ap->flags & MOUNT_FLAG_REMOUNT)
		cache_readlock(mc);
	else
		cache_writelock(mc);

	if (!ap->pref)
		lkp_key = strdup(key);
	else {
		lkp_key = malloc(strlen(ap->pref) + strlen(key) + 1);
		if (lkp_key) {
			strcpy(lkp_key, ap->pref);
			strcat(lkp_key, key);
		}
	}

	if (!lkp_key) {
		char *estr = strerror_r(errno, buf, MAX_ERR_BUF);
		error(ap->logopt, MODPREFIX "malloc: %s", estr);
		cache_unlock(mc);
		return NSS_STATUS_UNKNOWN;
	}

	me = match_cached_key(ap, MODPREFIX, source, lkp_key);
	/* Stale mapent => check for entry in alternate source or wildcard */
	if (me && !me->mapent) {
		while ((me = cache_lookup_key_next(me)))
			if (me->source == source)
				break;
		if (!me)
			me = cache_lookup_distinct(mc, "*");
	}
	if (me && me->mapent) {
		/*
		 * If this is a lookup add wildcard match for later validation
		 * checks and negative cache lookups.
		 */
		if (!(ap->flags & MOUNT_FLAG_REMOUNT) &&
		    ap->type == LKP_INDIRECT && *me->key == '*') {
			ret = cache_update(mc, source, key, me->mapent, me->age);
			if (!(ret & (CHE_OK | CHE_UPDATED)))
				me = NULL;
		}
		if (me && (me->source == source || *me->key == '/')) {
			strcpy(mapent_buf, me->mapent);
			mapent = mapent_buf;
		}
	}
	cache_unlock(mc);

	if (!me) {
		free(lkp_key);
		return NSS_STATUS_NOTFOUND;
	}

	if (!mapent) {
		free(lkp_key);
		return NSS_STATUS_TRYAGAIN;
	}

	debug(ap->logopt, MODPREFIX "%s -> %s", lkp_key, mapent);

	free(lkp_key);

	master_source_current_wait(ap->entry);
	ap->entry->current = source;

	ret = ctxt->parse->parse_mount(ap, key, key_len,
				       mapent, ctxt->parse->context);
	if (ret) {
		/* Don't update negative cache when re-connecting */
		if (ap->flags & MOUNT_FLAG_REMOUNT)
			return NSS_STATUS_TRYAGAIN;
		cache_writelock(mc);
		cache_update_negative(mc, source, key, ap->negative_timeout);
		cache_unlock(mc);
		return NSS_STATUS_TRYAGAIN;
	}

	return NSS_STATUS_SUCCESS;
}

/*
 * This destroys a context for queries to this module.  It releases the parser
 * structure (unloading the module) and frees the memory used by the context.
 */
int lookup_done(void *context)
{
	struct lookup_context *ctxt = (struct lookup_context *) context;
	int rv = close_parse(ctxt->parse);
#ifdef WITH_SASL
	ldapinit_mutex_lock();
	autofs_sasl_dispose(NULL, ctxt);
	autofs_sasl_done();
	ldapinit_mutex_unlock();
#endif
	free_context(ctxt);
	return rv;
}